
    (ph                    V   S SK r S SKrS SKrS SKJr  S SKrS SKJrJrJ	r	J
r
JrJrJrJrJrJrJrJrJrJrJrJrJr  S SKJrJrJrJr  S SKJr  S SKJ r J!r!J"r"  S SK#J$r$J%r%J&r&J'r'  SS	K(J)r)J*r*  SS
K+J,r,J-r-  SSK.J/r/  SSK,J0r0J1r1J2r2J3r3J4r4  SSK5J6r6  SSK+J7r7  SSK8J9r9  SSK:J;r;J<r<  / SQr=\" SS5      r>\" SS5      r?\" SS5      r@SS jrAS rB\;" S S SSS9SSS.S jj5       rC\;" S S SSS9SSS.S  jj5       rDS! rESS# jrFS$ rGSS& jrHSS' jrISS( jrJS) rKS* rLS+ rMS, rNSS- jrOS. rP " S/ S05      rQ\Q" 5       rR S\RS1.S2 jjrSSS3 jrTSS4 jrUSS5 jrVS6 rWS7 rXSS8 jrYSS9 jrZ\" S:S;5      r[\;" \[SSSS<9S= 5       r\\" / S>Q5      r]\" / S?Q5      r^\" / S@Q5      r_\" / SAQ5      r`/ SBQ/ SCQ/ SDQ/ SEQ/ SFQ/ SGQ/ SHQ/ SIQ/ SJQ/ SKQ/ SLQ/ra\R&                  " \a5      ra\R                  " S SMSN5      rc\R                  " \c\aR                  SOS%\aSP   SQ9rfSR rg\" SS/ STQSU/5      rhSSV jriSW rjSX rk\" SY/ SZQ/ 5      rlSSS[.S\ jjrm\" S]S;5      rn " S^ S_5      ro\R                  " 5       rq\;" \nSS`9SSa j5       rr\" SbS;5      rs\;" \sSS`9S S.Sc j5       rt\" SdS;5      ru\;" \uSS`9SeSfSg.Sh j5       rvSi rw\" SjS;5      rx\;" \xSS`9SeSfSg.Sk j5       ry\;" Sl SmSSn9So\z4Sp j5       r{SSq jr|\;" \2S\|Sr9SSs j5       r}\" StSuSv/5      r~Sw rSSx jrSy r\ " SzS{5      \;" \S"S| \\S}9  SS S.S~ jj5       5       r\" S/ SQ/ 5      rSS"SSS.S jrSS jr\;" S SSS S9S\-  S SS4S j5       r\;" S SSS S9S\-  S SS4S j5       r\;" S SSS S9S\-  S SS4S%S.S jj5       r " S S5      rS S"S.S jrS SS.S jrg)    N)
namedtuple)isscalarr_logarounduniqueasarrayzerosarangesortaminamaxsqrtarraypiexpravelcount_nonzero)optimizespecialinterpolatestats)_make_tuple_bunch)_rename_parameter_contains_nan_get_nan)array_namespacexp_sizexp_moveaxis_to_endxp_vector_norm   )gscaleswilk)	_stats_py	_wilcoxon)	FitResult)find_repeats_get_pvalueSignificanceResult_SimpleNormal_SimpleChi2)chi2_contingency)distributions)
rv_generic)_axis_nan_policy_factory_broadcast_arrays)mvsdist	bayes_mvskstatkstatvarprobplotppcc_max	ppcc_plot
boxcox_llfboxcoxboxcox_normmaxboxcox_normplotshapiroandersonansaribartlettleveneflignermoodwilcoxonmedian_testcircmeancircvarcircstdanderson_ksampyeojohnson_llf
yeojohnsonyeojohnson_normmaxyeojohnson_normplotdirectional_statsfalse_discovery_controlMean)	statisticminmaxVarianceStd_devc                 T   [        U 5      u  p#nUS:  d  US::  a  [        SU< S35      e[        UR                  5       UR	                  U5      5      n[        UR                  5       UR	                  U5      5      n[        UR                  5       UR	                  U5      5      nXVU4$ )a  
Bayesian confidence intervals for the mean, var, and std.

Parameters
----------
data : array_like
    Input data, if multi-dimensional it is flattened to 1-D by `bayes_mvs`.
    Requires 2 or more data points.
alpha : float, optional
    Probability that the returned confidence interval contains
    the true parameter.

Returns
-------
mean_cntr, var_cntr, std_cntr : tuple
    The three results are for the mean, variance and standard deviation,
    respectively.  Each result is a tuple of the form::

        (center, (lower, upper))

    with ``center`` the mean of the conditional pdf of the value given the
    data, and ``(lower, upper)`` a confidence interval, centered on the
    median, containing the estimate to a probability ``alpha``.

See Also
--------
mvsdist

Notes
-----
Each tuple of mean, variance, and standard deviation estimates represent
the (center, (lower, upper)) with center the mean of the conditional pdf
of the value given the data and (lower, upper) is a confidence interval
centered on the median, containing the estimate to a probability
``alpha``.

Converts data to 1-D and assumes all data has the same mean and variance.
Uses Jeffrey's prior for variance and std.

Equivalent to ``tuple((x.mean(), x.interval(alpha)) for x in mvsdist(dat))``

References
----------
T.E. Oliphant, "A Bayesian perspective on estimating mean, variance, and
standard-deviation from data", https://scholarsarchive.byu.edu/facpub/278,
2006.

Examples
--------
First a basic example to demonstrate the outputs:

>>> from scipy import stats
>>> data = [6, 9, 12, 7, 8, 8, 13]
>>> mean, var, std = stats.bayes_mvs(data)
>>> mean
Mean(statistic=9.0, minmax=(7.103650222612533, 10.896349777387467))
>>> var
Variance(statistic=10.0, minmax=(3.176724206, 24.45910382))
>>> std
Std_dev(statistic=2.9724954732045084,
        minmax=(1.7823367265645143, 4.945614605014631))

Now we generate some normally distributed random data, and get estimates of
mean and standard deviation with 95% confidence intervals for those
estimates:

>>> n_samples = 100000
>>> data = stats.norm.rvs(size=n_samples)
>>> res_mean, res_var, res_std = stats.bayes_mvs(data, alpha=0.95)

>>> import matplotlib.pyplot as plt
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> ax.hist(data, bins=100, density=True, label='Histogram of data')
>>> ax.vlines(res_mean.statistic, 0, 0.5, colors='r', label='Estimated mean')
>>> ax.axvspan(res_mean.minmax[0],res_mean.minmax[1], facecolor='r',
...            alpha=0.2, label=r'Estimated mean (95% limits)')
>>> ax.vlines(res_std.statistic, 0, 0.5, colors='g', label='Estimated scale')
>>> ax.axvspan(res_std.minmax[0],res_std.minmax[1], facecolor='g', alpha=0.2,
...            label=r'Estimated scale (95% limits)')

>>> ax.legend(fontsize=10)
>>> ax.set_xlim([-4, 4])
>>> ax.set_ylim([0, 0.5])
>>> plt.show()

r!   r   z%0 < alpha < 1 is required, but alpha=z was given.)r1   
ValueErrorrO   meanintervalrR   rS   )dataalphamvsm_resv_ress_ress           I/var/www/html/venv/lib/python3.13/site-packages/scipy/stats/_morestats.pyr2   r2   2   s    p dmGA!zUaZA5(+NOO1::e,-EQVVXqzz%01EAFFHajj/0E    c                    [        U 5      n[        U5      nUS:  a  [        S5      eUR                  5       nUR	                  5       nUS:  a  [
        R                  " U[        R                  " XB-  5      S9n[
        R                  " [        R                  " U5      [        R                  " USU-  -  5      S9n[
        R                  " U[        R                  " SU-  5      U-  S9nOzUS-
  nX$-  S-  n	US-  n
[
        R                  " X[        R                  " XH-  5      S9n[
        R                  " U
S[        R                  " U	5      S9n[
        R                  " XS9nXWU4$ )	ar  
'Frozen' distributions for mean, variance, and standard deviation of data.

Parameters
----------
data : array_like
    Input array. Converted to 1-D using ravel.
    Requires 2 or more data-points.

Returns
-------
mdist : "frozen" distribution object
    Distribution object representing the mean of the data.
vdist : "frozen" distribution object
    Distribution object representing the variance of the data.
sdist : "frozen" distribution object
    Distribution object representing the standard deviation of the data.

See Also
--------
bayes_mvs

Notes
-----
The return values from ``bayes_mvs(data)`` is equivalent to
``tuple((x.mean(), x.interval(0.90)) for x in mvsdist(data))``.

In other words, calling ``<dist>.mean()`` and ``<dist>.interval(0.90)``
on the three distribution objects returned from this function will give
the same results that are returned from `bayes_mvs`.

References
----------
T.E. Oliphant, "A Bayesian perspective on estimating mean, variance, and
standard-deviation from data", https://scholarsarchive.byu.edu/facpub/278,
2006.

Examples
--------
>>> from scipy import stats
>>> data = [6, 9, 12, 7, 8, 8, 13]
>>> mean, var, std = stats.mvsdist(data)

We now have frozen distribution objects "mean", "var" and "std" that we can
examine:

>>> mean.mean()
9.0
>>> mean.interval(0.95)
(6.6120585482655692, 11.387941451734431)
>>> mean.std()
1.1952286093343936

   zNeed at least 2 data-points.i  )locscale       @r!   )re   )r   lenrU   rV   varr-   normmathr   tgengammainvgamma)rX   xnxbarCmdistsdistvdistnm1facvals              r`   r1   r1      s"   n 	dAAA1u788668D	A4x""t499QU3CD""tyy|499Q"q&\;RS""q		#'0BQ0FG!eebjBhTYYqw5GH&&sBdiinE&&s6ra   c                     U $ N ro   s    r`   <lambda>r}          ara   c                     U 4$ rz   r{   r|   s    r`   r}   r}          A4ra   )result_to_tuple	n_outputsdefault_axisrc   axisc          	         [        U 5      nUR                  U 5      n US:  d  US:  a  [        S5      e[        U5      nUc  UR	                  U S5      n SnU R
                  U   nS/[        SUS-   5       Vs/ s H  oSR                  X-  US9PM     sn-   nUS:X  a  US   S-  U-  $ US	:X  a  XFS	   -  US   S
-  -
  XDS-
  -  -  $ US:X  a6  S	US   S-  -  SU-  US   -  US	   -  -
  XD-  US   -  -   XDS-
  -  US
-
  -  -  $ US:X  ar  SUS   S-  -  SU-  US   S	-  -  US	   -  -   SU-  US-
  -  US	   S	-  -  -
  SU-  US-   -  US   -  US   -  -
  XD-  US-   -  US   -  -   XDS-
  -  US
-
  -  US-
  -  -  $ [        S5      es  snf )aO  
Return the `n` th k-statistic ( ``1<=n<=4`` so far).

The `n` th k-statistic ``k_n`` is the unique symmetric unbiased estimator of the
`n` th cumulant :math:`\kappa_n` [1]_ [2]_.

Parameters
----------
data : array_like
    Input array.
n : int, {1, 2, 3, 4}, optional
    Default is equal to 2.
axis : int or None, default: None
    If an int, the axis of the input along which to compute the statistic.
    The statistic of each axis-slice (e.g. row) of the input will appear
    in a corresponding element of the output. If ``None``, the input will
    be raveled before computing the statistic.

Returns
-------
kstat : float
    The `n` th k-statistic.

See Also
--------
kstatvar : Returns an unbiased estimator of the variance of the k-statistic
moment : Returns the n-th central moment about the mean for a sample.

Notes
-----
For a sample size :math:`n`, the first few k-statistics are given by

.. math::

    k_1 &= \frac{S_1}{n}, \\
    k_2 &= \frac{nS_2 - S_1^2}{n(n-1)}, \\
    k_3 &= \frac{2S_1^3 - 3nS_1S_2 + n^2S_3}{n(n-1)(n-2)}, \\
    k_4 &= \frac{-6S_1^4 + 12nS_1^2S_2 - 3n(n-1)S_2^2 - 4n(n+1)S_1S_3
    + n^2(n+1)S_4}{n (n-1)(n-2)(n-3)},

where

.. math::

    S_r \equiv \sum_{i=1}^n X_i^r,

and :math:`X_i` is the :math:`i` th data point.

References
----------
.. [1] http://mathworld.wolfram.com/k-Statistic.html

.. [2] http://mathworld.wolfram.com/Cumulant.html

Examples
--------
>>> from scipy import stats
>>> from numpy.random import default_rng
>>> rng = default_rng()

As sample size increases, `n`-th moment and `n`-th k-statistic converge to the
same number (although they aren't identical). In the case of the normal
distribution, they converge to zero.

>>> for i in range(2,8):
...     x = rng.normal(size=10**i)
...     m, k = stats.moment(x, 3), stats.kstat(x, 3)
...     print(f"{i=}: {m=:.3g}, {k=:.3g}, {(m-k)=:.3g}")
i=2: m=-0.631, k=-0.651, (m-k)=0.0194  # random
i=3: m=0.0282, k=0.0283, (m-k)=-8.49e-05
i=4: m=-0.0454, k=-0.0454, (m-k)=1.36e-05
i=6: m=7.53e-05, k=7.53e-05, (m-k)=-2.26e-09
i=7: m=0.00166, k=0.00166, (m-k)=-4.99e-09
i=8: m=-2.88e-06 k=-2.88e-06, (m-k)=8.63e-13
   r!   z'k-statistics only supported for 1<=n<=4Nr   r         ?rc   rf      i         @zShould not be here.)r   r	   rU   intreshapeshaperangesum)rX   rp   r   xpNkSs          r`   r3   r3      s   ^ 
	B::dD1uABCCAA|zz$&

4A	eAq1uoFo&&t&,oFFAAvtcz!|	
aA$1s"qc'{33	
a!A$'	AaC!HQqTM)AC!H4Ga#g9NOO	
aAaD!Gbd1Q47lQqT11AaC3K!a4GG1ac1Q4!$%'(sAaCy1~6cEAcE"AcE*, 	- .// Gs   8Fc                     U $ rz   r{   r|   s    r`   r}   r}   J  r~   ra   c                     U 4$ rz   r{   r|   s    r`   r}   r}   J  r   ra   c                @   [        U 5      nUR                  U 5      n Uc  UR                  U S5      n SnU R                  U   nUS:X  a  [	        U SUSS9S-  U-  $ US:X  a4  [	        U SUSS9n[	        U SUSS9nSU-  US-  -  US-
  U-  -   XDS-   -  -  $ [        S	5      e)
a  Return an unbiased estimator of the variance of the k-statistic.

See `kstat` and [1]_ for more details about the k-statistic.

Parameters
----------
data : array_like
    Input array.
n : int, {1, 2}, optional
    Default is equal to 2.
axis : int or None, default: None
    If an int, the axis of the input along which to compute the statistic.
    The statistic of each axis-slice (e.g. row) of the input will appear
    in a corresponding element of the output. If ``None``, the input will
    be raveled before computing the statistic.

Returns
-------
kstatvar : float
    The `n` th k-statistic variance.

See Also
--------
kstat : Returns the n-th k-statistic.
moment : Returns the n-th central moment about the mean for a sample.

Notes
-----
Unbiased estimators of the variances of the first two k-statistics are given by

.. math::

    \mathrm{var}(k_1) &= \frac{k_2}{n}, \\
    \mathrm{var}(k_2) &= \frac{2k_2^2n + (n-1)k_4}{n(n - 1)}.

References
----------
.. [1] http://mathworld.wolfram.com/k-Statistic.html

r   r   r!   rc   T)rp   r   _no_decor   r   zOnly n=1 or n=2 supported.)r   r	   r   r   r3   rU   )rX   rp   r   r   r   k2k4s          r`   r4   r4   I  s    X 
	B::dD|zz$&

4AAvTQTD9C?AA	
a414$7414$7!BE	QqS"H$aC11566ra   c                     [         R                  " U [         R                  S9nSSU -  -  US'   SUS   -
  US'   [         R                  " SU 5      nUS-
  U S	-   -  USS& U$ )
a  Approximations of uniform order statistic medians.

Parameters
----------
n : int
    Sample size.

Returns
-------
v : 1d float array
    Approximations of the order statistic medians.

References
----------
.. [1] James J. Filliben, "The Probability Plot Correlation Coefficient
       Test for Normality", Technometrics, Vol. 17, pp. 111-117, 1975.

Examples
--------
Order statistics of the uniform distribution on the unit interval
are marginally distributed according to beta distributions.
The expectations of these order statistic are evenly spaced across
the interval, but the distributions are skewed in a way that
pushes the medians slightly towards the endpoints of the unit interval:

>>> import numpy as np
>>> n = 4
>>> k = np.arange(1, n+1)
>>> from scipy.stats import beta
>>> a = k
>>> b = n-k+1
>>> beta.mean(a, b)
array([0.2, 0.4, 0.6, 0.8])
>>> beta.median(a, b)
array([0.15910358, 0.38572757, 0.61427243, 0.84089642])

The Filliben approximation uses the exact medians of the smallest
and greatest order statistics, and the remaining medians are approximated
by points spread evenly across a sub-interval of the unit interval:

>>> from scipy.stats._morestats import _calc_uniform_order_statistic_medians
>>> _calc_uniform_order_statistic_medians(n)
array([0.15910358, 0.38545246, 0.61454754, 0.84089642])

This plot shows the skewed distributions of the order statistics
of a sample of size four from a uniform distribution on the unit interval:

>>> import matplotlib.pyplot as plt
>>> x = np.linspace(0.0, 1.0, num=50, endpoint=True)
>>> pdfs = [beta.pdf(x, a[i], b[i]) for i in range(n)]
>>> plt.figure()
>>> plt.plot(x, pdfs[0], x, pdfs[1], x, pdfs[2], x, pdfs[3])

dtype      ?r   r   r!   r   rc   gRQ?g\(\?)npemptyfloat64r   )rp   r[   is      r`   %_calc_uniform_order_statistic_mediansr     sg    n 	"**%A#'NAbEqu9AaD
		!QA6za%i(AaGHra   Tc                     [        U [        5      (       a   U $ [        U [        5      (       a   [        [        U 5      n U $ U(       a  Sn[        U5      eU $ ! [
         a  n[        U  S35      UeSnAff = f)a  Parse `dist` keyword.

Parameters
----------
dist : str or stats.distributions instance.
    Several functions take `dist` as a keyword, hence this utility
    function.
enforce_subclass : bool, optional
    If True (default), `dist` needs to be a
    `_distn_infrastructure.rv_generic` instance.
    It can sometimes be useful to set this keyword to False, if a function
    wants to accept objects that just look somewhat like such an instance
    (for example, they have a ``ppf`` method).

z! is not a valid distribution nameNza`dist` should be a stats.distributions instance or a string with the name of such a distribution.)
isinstancer.   strgetattrr-   AttributeErrorrU   )distenforce_subclassemsgs       r`   _parse_dist_kwr     s      $
## K 
D#			P=$/D K 
7oK  	Pv%FGHaO	Ps   A 
A5!A00A5c                     [        U S5      (       a4  U R                  U5        U R                  U5        U R                  U5        gU R	                  U5        U R                  U5        U R                  U5        g! [         a     gf = f)z>Helper function to add axes labels and a title to stats plots.	set_titleN)hasattrr   
set_xlabel
set_ylabeltitlexlabelylabel	Exception)plotr   r   r   s       r`   _add_axis_labels_titler     sr    4%%NN5!OOF#OOF# JJuKKKK  	s   AA; 3A; ;
BBFc                 N   [         R                  " U 5      n U R                  S:X  a.  U(       a$  X 4[         R                  [         R                  S44$ X 4$ [	        [        U 5      5      n[        USS9nUc  Sn[        U5      (       a  U4n[        U[        5      (       d  [        U5      nUR                  " U/UQ76 n[        U 5      nU(       a  [        R                  " Xx5      u  ppnUb  UR                  XxS5        U(       a  UR                  UW	U-  W
-   S5        [        USS	S
S9  U(       ac  U(       a\  [!        U5      n[#        U5      n[!        U 5      n[#        U 5      nUSX-
  -  -   nUSUU-
  -  -   nUR%                  UUSWS-  S S35        U(       a  Xx4W	W
W44$ Xx4$ )a(  
Calculate quantiles for a probability plot, and optionally show the plot.

Generates a probability plot of sample data against the quantiles of a
specified theoretical distribution (the normal distribution by default).
`probplot` optionally calculates a best-fit line for the data and plots the
results using Matplotlib or a given plot function.

Parameters
----------
x : array_like
    Sample/response data from which `probplot` creates the plot.
sparams : tuple, optional
    Distribution-specific shape parameters (shape parameters plus location
    and scale).
dist : str or stats.distributions instance, optional
    Distribution or distribution function name. The default is 'norm' for a
    normal probability plot.  Objects that look enough like a
    stats.distributions instance (i.e. they have a ``ppf`` method) are also
    accepted.
fit : bool, optional
    Fit a least-squares regression (best-fit) line to the sample data if
    True (default).
plot : object, optional
    If given, plots the quantiles.
    If given and `fit` is True, also plots the least squares fit.
    `plot` is an object that has to have methods "plot" and "text".
    The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
    or a custom object with the same methods.
    Default is None, which means that no plot is created.
rvalue : bool, optional
    If `plot` is provided and `fit` is True, setting `rvalue` to True
    includes the coefficient of determination on the plot.
    Default is False.

Returns
-------
(osm, osr) : tuple of ndarrays
    Tuple of theoretical quantiles (osm, or order statistic medians) and
    ordered responses (osr).  `osr` is simply sorted input `x`.
    For details on how `osm` is calculated see the Notes section.
(slope, intercept, r) : tuple of floats, optional
    Tuple  containing the result of the least-squares fit, if that is
    performed by `probplot`. `r` is the square root of the coefficient of
    determination.  If ``fit=False`` and ``plot=None``, this tuple is not
    returned.

Notes
-----
Even if `plot` is given, the figure is not shown or saved by `probplot`;
``plt.show()`` or ``plt.savefig('figname.png')`` should be used after
calling `probplot`.

`probplot` generates a probability plot, which should not be confused with
a Q-Q or a P-P plot.  Statsmodels has more extensive functionality of this
type, see ``statsmodels.api.ProbPlot``.

The formula used for the theoretical quantiles (horizontal axis of the
probability plot) is Filliben's estimate::

    quantiles = dist.ppf(val), for

            0.5**(1/n),                  for i = n
      val = (i - 0.3175) / (n + 0.365),  for i = 2, ..., n-1
            1 - 0.5**(1/n),              for i = 1

where ``i`` indicates the i-th ordered value and ``n`` is the total number
of values.

Examples
--------
>>> import numpy as np
>>> from scipy import stats
>>> import matplotlib.pyplot as plt
>>> nsample = 100
>>> rng = np.random.default_rng()

A t distribution with small degrees of freedom:

>>> ax1 = plt.subplot(221)
>>> x = stats.t.rvs(3, size=nsample, random_state=rng)
>>> res = stats.probplot(x, plot=plt)

A t distribution with larger degrees of freedom:

>>> ax2 = plt.subplot(222)
>>> x = stats.t.rvs(25, size=nsample, random_state=rng)
>>> res = stats.probplot(x, plot=plt)

A mixture of two normal distributions with broadcasting:

>>> ax3 = plt.subplot(223)
>>> x = stats.norm.rvs(loc=[0,5], scale=[1,1.5],
...                    size=(nsample//2,2), random_state=rng).ravel()
>>> res = stats.probplot(x, plot=plt)

A standard normal distribution:

>>> ax4 = plt.subplot(224)
>>> x = stats.norm.rvs(loc=0, scale=1, size=nsample, random_state=rng)
>>> res = stats.probplot(x, plot=plt)

Produce a new figure with a loggamma distribution, using the ``dist`` and
``sparams`` keywords:

>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> x = stats.loggamma.rvs(c=2.5, size=500, random_state=rng)
>>> res = stats.probplot(x, dist=stats.loggamma, sparams=(2.5,), plot=ax)
>>> ax.set_title("Probplot for loggamma dist with shape parameter 2.5")

Show the results with Matplotlib:

>>> plt.show()

r           F)r   r{   bozr-zTheoretical quantileszOrdered ValueszProbability Plotr   r   r   gffffff?{Gz?z$R^2=rc   z1.4f$)r   r	   sizenanr   rh   r   r   r   tupleppfr   r$   
linregressr   r   r   r   text)ro   sparamsr   fitr   rvalueosm_uniformosmosrslope	interceptrprob_xminxmaxyminymaxposxposys                       r`   r5   r5     s   j 	

1Avv{6BFFBFFC0004K7A?K$7D*gu%%.
((;
)
)C
q'C
'0';';C'E$!1		#D!IIc59y0$7t,C&6%7	9
 69D9D7D7D$$+..D$$+..DIIdDE!q&a"89
zE9a000xra   c                     [        U5      n[        [        U 5      5      n[        U 5      nS n[        R
                  " XQX4UR                  4S9$ )a?	  Calculate the shape parameter that maximizes the PPCC.

The probability plot correlation coefficient (PPCC) plot can be used
to determine the optimal shape parameter for a one-parameter family
of distributions. ``ppcc_max`` returns the shape parameter that would
maximize the probability plot correlation coefficient for the given
data to a one-parameter family of distributions.

Parameters
----------
x : array_like
    Input array.
brack : tuple, optional
    Triple (a,b,c) where (a<b<c). If bracket consists of two numbers (a, c)
    then they are assumed to be a starting interval for a downhill bracket
    search (see `scipy.optimize.brent`).
dist : str or stats.distributions instance, optional
    Distribution or distribution function name.  Objects that look enough
    like a stats.distributions instance (i.e. they have a ``ppf`` method)
    are also accepted.  The default is ``'tukeylambda'``.

Returns
-------
shape_value : float
    The shape parameter at which the probability plot correlation
    coefficient reaches its max value.

See Also
--------
ppcc_plot, probplot, boxcox

Notes
-----
The brack keyword serves as a starting point which is useful in corner
cases. One can use a plot to obtain a rough visual estimate of the location
for the maximum to start the search near it.

References
----------
.. [1] J.J. Filliben, "The Probability Plot Correlation Coefficient Test
       for Normality", Technometrics, Vol. 17, pp. 111-117, 1975.
.. [2] Engineering Statistics Handbook, NIST/SEMATEC,
       https://www.itl.nist.gov/div898/handbook/eda/section3/ppccplot.htm

Examples
--------
First we generate some random data from a Weibull distribution
with shape parameter 2.5:

>>> import numpy as np
>>> from scipy import stats
>>> import matplotlib.pyplot as plt
>>> rng = np.random.default_rng()
>>> c = 2.5
>>> x = stats.weibull_min.rvs(c, scale=4, size=2000, random_state=rng)

Generate the PPCC plot for this data with the Weibull distribution.

>>> fig, ax = plt.subplots(figsize=(8, 6))
>>> res = stats.ppcc_plot(x, c/2, 2*c, dist='weibull_min', plot=ax)

We calculate the value where the shape should reach its maximum and a
red line is drawn there. The line should coincide with the highest
point in the PPCC graph.

>>> cmax = stats.ppcc_max(x, brack=(c/2, 2*c), dist='weibull_min')
>>> ax.axvline(cmax, color='r')
>>> plt.show()

c                 L    U" X5      n[         R                  " XB5      u  pVSU-
  $ Nr!   )r$   pearsonr)r   miyvalsfuncxvalsr   r   s          r`   tempfuncppcc_max.<locals>.tempfunc  s&    R$$U21ura   brackargs)r   r   rh   r   r   brentr   )ro   r   r   r   r   r   s         r`   r6   r6     sL    N $D7A?K
q'C
 >>( +$((;= =ra   c                    X!::  a  [        S5      e[        R                  " XUS9n[        R                  " U5      n[	        U5       H  u  p[        X	USS9u  pUS   Xx'   M     Ub"  UR                  XgS5        [        USSS	U S
3S9  Xg4$ )a<  Calculate and optionally plot probability plot correlation coefficient.

The probability plot correlation coefficient (PPCC) plot can be used to
determine the optimal shape parameter for a one-parameter family of
distributions.  It cannot be used for distributions without shape
parameters
(like the normal distribution) or with multiple shape parameters.

By default a Tukey-Lambda distribution (`stats.tukeylambda`) is used. A
Tukey-Lambda PPCC plot interpolates from long-tailed to short-tailed
distributions via an approximately normal one, and is therefore
particularly useful in practice.

Parameters
----------
x : array_like
    Input array.
a, b : scalar
    Lower and upper bounds of the shape parameter to use.
dist : str or stats.distributions instance, optional
    Distribution or distribution function name.  Objects that look enough
    like a stats.distributions instance (i.e. they have a ``ppf`` method)
    are also accepted.  The default is ``'tukeylambda'``.
plot : object, optional
    If given, plots PPCC against the shape parameter.
    `plot` is an object that has to have methods "plot" and "text".
    The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
    or a custom object with the same methods.
    Default is None, which means that no plot is created.
N : int, optional
    Number of points on the horizontal axis (equally distributed from
    `a` to `b`).

Returns
-------
svals : ndarray
    The shape values for which `ppcc` was calculated.
ppcc : ndarray
    The calculated probability plot correlation coefficient values.

See Also
--------
ppcc_max, probplot, boxcox_normplot, tukeylambda

References
----------
J.J. Filliben, "The Probability Plot Correlation Coefficient Test for
Normality", Technometrics, Vol. 17, pp. 111-117, 1975.

Examples
--------
First we generate some random data from a Weibull distribution
with shape parameter 2.5, and plot the histogram of the data:

>>> import numpy as np
>>> from scipy import stats
>>> import matplotlib.pyplot as plt
>>> rng = np.random.default_rng()
>>> c = 2.5
>>> x = stats.weibull_min.rvs(c, scale=4, size=2000, random_state=rng)

Take a look at the histogram of the data.

>>> fig1, ax = plt.subplots(figsize=(9, 4))
>>> ax.hist(x, bins=50)
>>> ax.set_title('Histogram of x')
>>> plt.show()

Now we explore this data with a PPCC plot as well as the related
probability plot and Box-Cox normplot.  A red line is drawn where we
expect the PPCC value to be maximal (at the shape parameter ``c``
used above):

>>> fig2 = plt.figure(figsize=(12, 4))
>>> ax1 = fig2.add_subplot(1, 3, 1)
>>> ax2 = fig2.add_subplot(1, 3, 2)
>>> ax3 = fig2.add_subplot(1, 3, 3)
>>> res = stats.probplot(x, plot=ax1)
>>> res = stats.boxcox_normplot(x, -4, 4, plot=ax2)
>>> res = stats.ppcc_plot(x, c/2, 2*c, dist='weibull_min', plot=ax3)
>>> ax3.axvline(c, color='r')
>>> plt.show()

z`b` has to be larger than `a`.numTr   r   r   ro   zShape ValuesProb Plot Corr. Coef.(z) PPCC Plotr   )rU   r   linspace
empty_like	enumerater5   r   r   )ro   abr   r   r   svalsppccr   svalr   r2s               r`   r7   r7     s    j 	v9::KK!$E==DU#t6R& $ 		%s#tN&='(k%:	< ;ra   c                 x    [         R                  " U SS9[        R                  " U R                  S   5      -
  nU$ Nr   r   )r   	logsumexprk   r   r   )logxress     r`   	_log_meanr   Y  s/    


Dq
)DHHTZZ],C
CCJra   c           	         [        U 5      nUR                  U R                  UR                  5      nUR	                  U R
                  [        S-  US9n[        R                  " UR                  XU-   45      SS9nUR                  UR                  [        R                  " SU-  SS95      5      [        R                  " U R
                  S   5      -
  nU$ )Ny              ?r   r   r   rc   )r   result_typer   	complex64fullr   r   r   r   stackrealr	   rk   r   )r   r   logmeanr   pijlogxmur   s          r`   _log_varr  _  s    oG NN4::r||4E
''$**b2gU'
3Crxx}(=>QGF772::g//F
CDEXXdjjm$%CJra   c                 t   [        U5      nUR                  U5      nUR                  S   nUS:X  a  UR                  $ UR                  nUR                  US5      (       a%  UR                  XR                  S9nUR                  nUR                  U5      nU S:X  a   UR                  UR                  USS95      nO2X-  n[        Xr5      S[        R                  " [        U 5      5      -  -
  nU S-
  UR                  USS9-  US-  U-  -
  nUR                  X5      nUR                  S:X  a  US   nU$ UnU$ )av	  The boxcox log-likelihood function.

Parameters
----------
lmb : scalar
    Parameter for Box-Cox transformation.  See `boxcox` for details.
data : array_like
    Data to calculate Box-Cox log-likelihood for.  If `data` is
    multi-dimensional, the log-likelihood is calculated along the first
    axis.

Returns
-------
llf : float or ndarray
    Box-Cox log-likelihood of `data` given `lmb`.  A float for 1-D `data`,
    an array otherwise.

See Also
--------
boxcox, probplot, boxcox_normplot, boxcox_normmax

Notes
-----
The Box-Cox log-likelihood function is defined here as

.. math::

    llf = (\lambda - 1) \sum_i(\log(x_i)) -
          N/2 \log(\sum_i (y_i - \bar{y})^2 / N),

where ``y`` is the Box-Cox transformed input data ``x``.

Examples
--------
>>> import numpy as np
>>> from scipy import stats
>>> import matplotlib.pyplot as plt
>>> from mpl_toolkits.axes_grid1.inset_locator import inset_axes

Generate some random variates and calculate Box-Cox log-likelihood values
for them for a range of ``lmbda`` values:

>>> rng = np.random.default_rng()
>>> x = stats.loggamma.rvs(5, loc=10, size=1000, random_state=rng)
>>> lmbdas = np.linspace(-2, 10)
>>> llf = np.zeros(lmbdas.shape, dtype=float)
>>> for ii, lmbda in enumerate(lmbdas):
...     llf[ii] = stats.boxcox_llf(lmbda, x)

Also find the optimal lmbda value with `boxcox`:

>>> x_most_normal, lmbda_optimal = stats.boxcox(x)

Plot the log-likelihood as function of lmbda.  Add the optimal lmbda as a
horizontal line to check that that's really the optimum:

>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> ax.plot(lmbdas, llf, 'b.-')
>>> ax.axhline(stats.boxcox_llf(lmbda_optimal, x), color='r')
>>> ax.set_xlabel('lmbda parameter')
>>> ax.set_ylabel('Box-Cox log-likelihood')

Now add some probability plots to show that where the log-likelihood is
maximized the data transformed with `boxcox` looks closest to normal:

>>> locs = [3, 10, 4]  # 'lower left', 'center', 'lower right'
>>> for lmbda, loc in zip([-1, lmbda_optimal, 9], locs):
...     xt = stats.boxcox(x, lmbda=lmbda)
...     (osm, osr), (slope, intercept, r_sq) = stats.probplot(xt)
...     ax_inset = inset_axes(ax, width="20%", height="20%", loc=loc)
...     ax_inset.plot(osm, osr, 'c.', osm, slope*osm + intercept, 'k-')
...     ax_inset.set_xticklabels([])
...     ax_inset.set_yticklabels([])
...     ax_inset.set_title(r'$\lambda=%1.2f$' % lmbda)

>>> plt.show()

r   integralr   r   rc   r!   r{   )r   r	   r   r   r   isdtyper   r   ri   r  rk   absr   astypendim)	lmbrX   r   r   dtlogdatalogvarr   r   s	            r`   r8   r8   l  s&   ` 
	B::dD

1AAvvv	B	zz"j!!zz$jjz1ZZffTlG axwQ/0 }$#a$((3s8*<&<<7bffW1f-
-!f
<C
))C
CXX]#b'CJ ),CJra   c                    S[         R                  R                  SU-
  S5      -  n[        X5      U-
  nS nUS-   nSnU" X`U5      S:  a%  US:  a  US-  nUS-  nU" X`U5      S:  a  US:  a  M  US:X  a  [	        S5      e[
        R                  " XQX`U4S	9nUS-
  nSnU" X`U5      S:  a%  US:  a  US-  nUS-  nU" X`U5      S:  a  US:  a  M  US:X  a  [	        S5      e[
        R                  " XVXU4S	9n	X4$ )
Nr   r!   c                     [        X5      U-
  $ rz   r8   )lmbdarX   targets      r`   rootfunc'_boxcox_conf_interval.<locals>.rootfunc  s    %&//ra   r   r   i  皙?zCould not find endpoint.r   )r-   chi2r   r8   RuntimeErrorr   brentq)
ro   lmaxrY   rw   r  r  newlmr   lmpluslmminuss
             r`   _boxcox_conf_intervalr    s/    ""&&q5y!4
4C 3&F0 3JE	AEf%+!c'	Q Ef%+!c' 	Cx566__XUVEF 3JE	AEf%+!c'	Q Ef%+!c' 	Cx566oohtf+FG?ra   c                    [         R                  " U 5      n Ub  [        R                  " X5      $ U R                  S:w  a  [        S5      eU R                  S:X  a  U $ [         R                  " X S   :H  5      (       a  [        S5      e[         R                  " U S:*  5      (       a  [        S5      e[        U SUS9n[        X5      nUc  XT4$ [        XU5      nXTU4$ )a$  Return a dataset transformed by a Box-Cox power transformation.

Parameters
----------
x : ndarray
    Input array to be transformed.

    If `lmbda` is not None, this is an alias of
    `scipy.special.boxcox`.
    Returns nan if ``x < 0``; returns -inf if ``x == 0 and lmbda < 0``.

    If `lmbda` is None, array must be positive, 1-dimensional, and
    non-constant.

lmbda : scalar, optional
    If `lmbda` is None (default), find the value of `lmbda` that maximizes
    the log-likelihood function and return it as the second output
    argument.

    If `lmbda` is not None, do the transformation for that value.

alpha : float, optional
    If `lmbda` is None and `alpha` is not None (default), return the
    ``100 * (1-alpha)%`` confidence  interval for `lmbda` as the third
    output argument. Must be between 0.0 and 1.0.

    If `lmbda` is not None, `alpha` is ignored.
optimizer : callable, optional
    If `lmbda` is None, `optimizer` is the scalar optimizer used to find
    the value of `lmbda` that minimizes the negative log-likelihood
    function. `optimizer` is a callable that accepts one argument:

    fun : callable
        The objective function, which evaluates the negative
        log-likelihood function at a provided value of `lmbda`

    and returns an object, such as an instance of
    `scipy.optimize.OptimizeResult`, which holds the optimal value of
    `lmbda` in an attribute `x`.

    See the example in `boxcox_normmax` or the documentation of
    `scipy.optimize.minimize_scalar` for more information.

    If `lmbda` is not None, `optimizer` is ignored.

Returns
-------
boxcox : ndarray
    Box-Cox power transformed array.
maxlog : float, optional
    If the `lmbda` parameter is None, the second returned argument is
    the `lmbda` that maximizes the log-likelihood function.
(min_ci, max_ci) : tuple of float, optional
    If `lmbda` parameter is None and `alpha` is not None, this returned
    tuple of floats represents the minimum and maximum confidence limits
    given `alpha`.

See Also
--------
probplot, boxcox_normplot, boxcox_normmax, boxcox_llf

Notes
-----
The Box-Cox transform is given by::

    y = (x**lmbda - 1) / lmbda,  for lmbda != 0
        log(x),                  for lmbda = 0

`boxcox` requires the input data to be positive.  Sometimes a Box-Cox
transformation provides a shift parameter to achieve this; `boxcox` does
not.  Such a shift parameter is equivalent to adding a positive constant to
`x` before calling `boxcox`.

The confidence limits returned when `alpha` is provided give the interval
where:

.. math::

    llf(\hat{\lambda}) - llf(\lambda) < \frac{1}{2}\chi^2(1 - \alpha, 1),

with ``llf`` the log-likelihood function and :math:`\chi^2` the chi-squared
function.

References
----------
G.E.P. Box and D.R. Cox, "An Analysis of Transformations", Journal of the
Royal Statistical Society B, 26, 211-252 (1964).

Examples
--------
>>> from scipy import stats
>>> import matplotlib.pyplot as plt

We generate some random variates from a non-normal distribution and make a
probability plot for it, to show it is non-normal in the tails:

>>> fig = plt.figure()
>>> ax1 = fig.add_subplot(211)
>>> x = stats.loggamma.rvs(5, size=500) + 5
>>> prob = stats.probplot(x, dist=stats.norm, plot=ax1)
>>> ax1.set_xlabel('')
>>> ax1.set_title('Probplot against normal distribution')

We now use `boxcox` to transform the data so it's closest to normal:

>>> ax2 = fig.add_subplot(212)
>>> xt, _ = stats.boxcox(x)
>>> prob = stats.probplot(xt, dist=stats.norm, plot=ax2)
>>> ax2.set_title('Probplot after Box-Cox transformation')

>>> plt.show()

r!   zData must be 1-dimensional.r   zData must not be constant.Data must be positive.mle)method	optimizer)r   r	   r   r9   r
  rU   r   allanyr:   r  )ro   r  rY   r$  r  yrW   s          r`   r9   r9     s    d 	

1A~~a''vv{677vv{	vvaQ4i566	vva1f~~122 !EY?DqA}w )%8  ra   c                     [         R                  " U SU-  -  * [        R                  " U 5      -  U-  SS9n[        R                  " U* [        R                  " U 5      -  SU-  -
  5      $ )Nr   )r   r!   )r   lambertwr   r   r   )ro   r'  r   s      r`   _boxcox_inv_lmbdar*    sX    


Q26]+bffQi7!;r
BC77C4"&&)#a!e+,,ra   c                       \ rS rSrS rSrg)	_BigFloati  c                     g)N	BIG_FLOATr{   selfs    r`   __repr___BigFloat.__repr__  s    ra   r{   N)__name__
__module____qualname____firstlineno__r1  __static_attributes__r{   ra   r`   r,  r,    s    ra   r,  )r   c                  ^^^^^ [         R                  " U 5      n [         R                  " [         R                  " U 5      U S:  -  5      (       d  Sn[	        U5      eSnU[
        L az  [         R                  " U R                  [         R                  5      (       a  U R                  O[         R                  n[         R                  " U5      R                  S-  nSU S3nOUS::  a  [	        S5      eTc  Tc  SmU4S	 jmO/[        T5      (       d  [	        S
5      eTb  [	        S5      eU4S jmU4S jmU4S jmUU4S jnTTUS.n	X)R                  5       ;  a  [	        SU S35      eX   n
U
" U 5      nUc  Sn[	        U5      e[         R                  " U5      (       GdJ  [         R                  " U 5      [         R                  " U 5      pUS:  a  UnOnUS::  a  UnOe[         R"                  " X5      [%        [         R"                  " X5      5      :  n['        U[         R(                  5      (       a  US   nU(       a  UOUn[%        [         R"                  " X5      5      U:  n[         R*                  " U5      (       ak  SU S3U-   n[,        R.                  " USS9  [1        X[         R2                  " US-
  5      -  5      n['        U[         R(                  5      (       a  UUU'   U$ UnU$ )aT  Compute optimal Box-Cox transform parameter for input data.

Parameters
----------
x : array_like
    Input array. All entries must be positive, finite, real numbers.
brack : 2-tuple, optional, default (-2.0, 2.0)
     The starting interval for a downhill bracket search for the default
     `optimize.brent` solver. Note that this is in most cases not
     critical; the final result is allowed to be outside this bracket.
     If `optimizer` is passed, `brack` must be None.
method : str, optional
    The method to determine the optimal transform parameter (`boxcox`
    ``lmbda`` parameter). Options are:

    'pearsonr'  (default)
        Maximizes the Pearson correlation coefficient between
        ``y = boxcox(x)`` and the expected values for ``y`` if `x` would be
        normally-distributed.

    'mle'
        Maximizes the log-likelihood `boxcox_llf`.  This is the method used
        in `boxcox`.

    'all'
        Use all optimization methods available, and return all results.
        Useful to compare different methods.
optimizer : callable, optional
    `optimizer` is a callable that accepts one argument:

    fun : callable
        The objective function to be minimized. `fun` accepts one argument,
        the Box-Cox transform parameter `lmbda`, and returns the value of
        the function (e.g., the negative log-likelihood) at the provided
        argument. The job of `optimizer` is to find the value of `lmbda`
        that *minimizes* `fun`.

    and returns an object, such as an instance of
    `scipy.optimize.OptimizeResult`, which holds the optimal value of
    `lmbda` in an attribute `x`.

    See the example below or the documentation of
    `scipy.optimize.minimize_scalar` for more information.
ymax : float, optional
    The unconstrained optimal transform parameter may cause Box-Cox
    transformed data to have extreme magnitude or even overflow.
    This parameter constrains MLE optimization such that the magnitude
    of the transformed `x` does not exceed `ymax`. The default is
    the maximum value of the input dtype. If set to infinity,
    `boxcox_normmax` returns the unconstrained optimal lambda.
    Ignored when ``method='pearsonr'``.

Returns
-------
maxlog : float or ndarray
    The optimal transform parameter found.  An array instead of a scalar
    for ``method='all'``.

See Also
--------
boxcox, boxcox_llf, boxcox_normplot, scipy.optimize.minimize_scalar

Examples
--------
>>> import numpy as np
>>> from scipy import stats
>>> import matplotlib.pyplot as plt

We can generate some data and determine the optimal ``lmbda`` in various
ways:

>>> rng = np.random.default_rng()
>>> x = stats.loggamma.rvs(5, size=30, random_state=rng) + 5
>>> y, lmax_mle = stats.boxcox(x)
>>> lmax_pearsonr = stats.boxcox_normmax(x)

>>> lmax_mle
2.217563431465757
>>> lmax_pearsonr
2.238318660200961
>>> stats.boxcox_normmax(x, method='all')
array([2.23831866, 2.21756343])

>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> prob = stats.boxcox_normplot(x, -10, 10, plot=ax)
>>> ax.axvline(lmax_mle, color='r')
>>> ax.axvline(lmax_pearsonr, color='g', ls='--')

>>> plt.show()

Alternatively, we can define our own `optimizer` function. Suppose we
are only interested in values of `lmbda` on the interval [6, 7], we
want to use `scipy.optimize.minimize_scalar` with ``method='bounded'``,
and we want to use tighter tolerances when optimizing the log-likelihood
function. To do this, we define a function that accepts positional argument
`fun` and uses `scipy.optimize.minimize_scalar` to minimize `fun` subject
to the provided bounds and tolerances:

>>> from scipy import optimize
>>> options = {'xatol': 1e-12}  # absolute tolerance on `x`
>>> def optimizer(fun):
...     return optimize.minimize_scalar(fun, bounds=(6, 7),
...                                     method="bounded", options=options)
>>> stats.boxcox_normmax(x, optimizer=optimizer)
6.000000000
r   zVThe `x` argument of `boxcox_normmax` must contain only positive, finite, real numbers.zexceed specified `ymax`.i'  zoverflow in .z `ymax` must be strictly positive)g       rf   c                 .   > [         R                  " XTS9$ )N)r   r   )r   r   )r   r   r   s     r`   
_optimizer"boxcox_normmax.<locals>._optimizer  s    >>$??ra   z`optimizer` must be a callablez,`brack` must be None if `optimizer` is givenc                 <   >^ ^ UU 4S jn[        T" U5      SS 5      $ )Nc                    > T" U /TQ76 $ rz   r{   )ro   r   r   s    r`   func_wrapped8boxcox_normmax.<locals>._optimizer.<locals>.func_wrapped-  s    A~~%ra   ro   )r   )r   r   r?  r$  s   `` r`   r;  r<  ,  s    &9\2C>>ra   c                    > [        [        U 5      5      n[        R                  R	                  U5      nS nT" X2U 4S9$ )Nc                 ~    [        X 5      n[        R                  " U5      n[        R                  " X5      u  pVSU-
  $ r   )r9   r   r   r$   r   )r  r   sampsr'  r   r   r   s          r`   _eval_pearsonr9boxcox_normmax.<locals>._pearsonr.<locals>._eval_pearsonr5  s6    
 u$AGGAJE((6GAq5Lra   r  )r   rh   r-   rj   r   )ro   r   r   rD  r;  s       r`   	_pearsonr!boxcox_normmax.<locals>._pearsonr1  s=    ;CFC""&&{3	 .qz::ra   c                    > S nT" X4S9$ )Nc                     [        X5      * $ rz   r  )r  rX   s     r`   	_eval_mle/boxcox_normmax.<locals>._mle.<locals>._eval_mleB  s    s)))ra   r  r{   )ro   rJ  r;  s     r`   _mleboxcox_normmax.<locals>._mleA  s    	* )$//ra   c                 f   > [         R                  " S[        S9nT" U 5      US'   T" U 5      US'   U$ )Nrc   r   r   r!   )r   r   float)ro   maxlogrL  rF  s     r`   _allboxcox_normmax.<locals>._allH  s2    !5)aLq	Gq	ra   )r   r"  r%  zMethod z not recognized.zsThe `optimizer` argument of `boxcox_normmax` must return an object containing the optimal `lmbda` in attribute `x`.r!   zThe optimal lambda is z, but the returned lambda is the constrained optimum to ensure that the maximum or the minimum of the transformed data does not rc   
stacklevel)r   r	   r%  isfiniterU   _BigFloat_singleton
issubdtyper   floatingr   finfomaxcallablekeysisinfminr   r9   r  r   ndarrayr&  warningswarnr*  sign)ro   r   r#  r$  r   messageend_msgr   rQ  methods	optimfuncr   r   r   x_treme	indicatormaskconstrained_resrL  r;  rF  s    ` `              @@@r`   r:   r:     s   \ 	

1A66"++a.AF+,,:!!(G""=="++>>BJJxx""U* q)	;<<  =E	@
 	""=>>KLL	?
; 0 %G \\^#76(*:;<<I
A,C
{P!!XXd^^VVAYq	d19GQYGt1Ct8Q4RRI#rzz**%aL	'dTG7>>'/04766$<<( .4 57>? 
 MM'a0 0RS@T9TUO#rzz**+D	 J &Jra   c                    U S:X  a	  Sn[         nOSn[        n[        R                  " U5      nUR                  S:X  a  U$ X2::  a  [        S5      eU S:X  a)  [        R                  " US:*  5      (       a  [        S5      e[        R                  " X#US9nUS-  n	[        U5       H   u  pU" XS	9n[        US
SS9u  nu    pXU
'   M"     Ub  UR                  XS5        [        USSUS9  X4$ )zCompute parameters for a Box-Cox or Yeo-Johnson normality plot,
optionally show it.

See `boxcox_normplot` or `yeojohnson_normplot` for details.
r9   zBox-Cox Normality PlotzYeo-Johnson Normality Plotr   z `lb` has to be larger than `la`.r!  r   r   )r  rj   Tr   ro   z	$\lambda$r   r   )r9   rJ   r   r	   r   rU   r&  r   r   r5   r   r   )r#  ro   lalbr   r   r   transform_funclmbdasr   r   rx   zr   r   s                  r`   	_normplotrq  }  s     (,#


1Avv{	x;<<bffQ!Vnn122[[Q'FC<DF# 1(D99AqQ $ 		&$tL&=%*	, <ra   c                     [        SXX#U5      $ )a  Compute parameters for a Box-Cox normality plot, optionally show it.

A Box-Cox normality plot shows graphically what the best transformation
parameter is to use in `boxcox` to obtain a distribution that is close
to normal.

Parameters
----------
x : array_like
    Input array.
la, lb : scalar
    The lower and upper bounds for the ``lmbda`` values to pass to `boxcox`
    for Box-Cox transformations.  These are also the limits of the
    horizontal axis of the plot if that is generated.
plot : object, optional
    If given, plots the quantiles and least squares fit.
    `plot` is an object that has to have methods "plot" and "text".
    The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
    or a custom object with the same methods.
    Default is None, which means that no plot is created.
N : int, optional
    Number of points on the horizontal axis (equally distributed from
    `la` to `lb`).

Returns
-------
lmbdas : ndarray
    The ``lmbda`` values for which a Box-Cox transform was done.
ppcc : ndarray
    Probability Plot Correlation Coefficient, as obtained from `probplot`
    when fitting the Box-Cox transformed input `x` against a normal
    distribution.

See Also
--------
probplot, boxcox, boxcox_normmax, boxcox_llf, ppcc_max

Notes
-----
Even if `plot` is given, the figure is not shown or saved by
`boxcox_normplot`; ``plt.show()`` or ``plt.savefig('figname.png')``
should be used after calling `probplot`.

Examples
--------
>>> from scipy import stats
>>> import matplotlib.pyplot as plt

Generate some non-normally distributed data, and create a Box-Cox plot:

>>> x = stats.loggamma.rvs(5, size=500) + 5
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> prob = stats.boxcox_normplot(x, -20, 20, plot=ax)

Determine and plot the optimal ``lmbda`` to transform ``x`` and plot it in
the same plot:

>>> _, maxlog = stats.boxcox(x)
>>> ax.axvline(maxlog, color='r')

>>> plt.show()

r9   rq  ro   rl  rm  r   r   s        r`   r;   r;     s    B Xqb22ra   c                    [         R                  " U 5      n U R                  S:X  a  U $ [         R                  " U R                  [         R
                  5      (       a  [        S5      e[         R                  " U R                  [         R                  5      (       a  U R                  [         R                  SS9n Ub  [        X5      $ [        U 5      n[        X5      nX24$ )a  Return a dataset transformed by a Yeo-Johnson power transformation.

Parameters
----------
x : ndarray
    Input array.  Should be 1-dimensional.
lmbda : float, optional
    If ``lmbda`` is ``None``, find the lambda that maximizes the
    log-likelihood function and return it as the second output argument.
    Otherwise the transformation is done for the given value.

Returns
-------
yeojohnson: ndarray
    Yeo-Johnson power transformed array.
maxlog : float, optional
    If the `lmbda` parameter is None, the second returned argument is
    the lambda that maximizes the log-likelihood function.

See Also
--------
probplot, yeojohnson_normplot, yeojohnson_normmax, yeojohnson_llf, boxcox

Notes
-----
The Yeo-Johnson transform is given by::

    y = ((x + 1)**lmbda - 1) / lmbda,                for x >= 0, lmbda != 0
        log(x + 1),                                  for x >= 0, lmbda = 0
        -((-x + 1)**(2 - lmbda) - 1) / (2 - lmbda),  for x < 0, lmbda != 2
        -log(-x + 1),                                for x < 0, lmbda = 2

Unlike `boxcox`, `yeojohnson` does not require the input data to be
positive.

.. versionadded:: 1.2.0


References
----------
I. Yeo and R.A. Johnson, "A New Family of Power Transformations to
Improve Normality or Symmetry", Biometrika 87.4 (2000):


Examples
--------
>>> from scipy import stats
>>> import matplotlib.pyplot as plt

We generate some random variates from a non-normal distribution and make a
probability plot for it, to show it is non-normal in the tails:

>>> fig = plt.figure()
>>> ax1 = fig.add_subplot(211)
>>> x = stats.loggamma.rvs(5, size=500) + 5
>>> prob = stats.probplot(x, dist=stats.norm, plot=ax1)
>>> ax1.set_xlabel('')
>>> ax1.set_title('Probplot against normal distribution')

We now use `yeojohnson` to transform the data so it's closest to normal:

>>> ax2 = fig.add_subplot(212)
>>> xt, lmbda = stats.yeojohnson(x)
>>> prob = stats.probplot(xt, dist=stats.norm, plot=ax2)
>>> ax2.set_title('Probplot after Yeo-Johnson transformation')

>>> plt.show()

r   z>Yeo-Johnson transformation is not defined for complex numbers.F)copy)r   r	   r   rW  r   complexfloatingrU   integerr	  r   _yeojohnson_transformrK   )ro   r  r  r'  s       r`   rJ   rJ     s    L 	

1Avv{	}}QWWb0011 , - 	- 
}}QWWbjj))HHRZZeH,$Q.. a Da&A7Nra   c                    [         R                  " U R                  [         R                  5      (       a  U R                  O[         R                  n[         R
                  " XS9nU S:  n[        U5      [         R                  " S5      :  a  [         R                  " X   5      X4'   O4[         R                  " U[         R                  " X   5      -  5      U-  X4'   [        US-
  5      [         R                  " S5      :  a@  [         R                  " SU-
  [         R                  " X)    * 5      -  5      * SU-
  -  X4) '   U$ [         R                  " X)    * 5      * X4) '   U$ )zYReturns `x` transformed by the Yeo-Johnson power transform with given
parameter `lmbda`.
r   r   r   rc   )
r   rW  r   rX  r   
zeros_liker  spacinglog1pexpm1)ro   r  r   outposs        r`   ry  ry  F  s
    }}QWWbkk::AGG

E
--
'C
q&C 5zBJJrN"88AF# 88EBHHQV$445= 519~

2&XXq5yBHHagX,>>??1u9MD	 J XXqwh''D	Jra   c           
      ^   [         R                  " U5      nUR                  S   nUS:X  a  [         R                  $ [	        X5      nUR                  SS9n[         R                  " U5      nU[         R                  " UR                  5      R                  :  n[         R                  XV'   U* S-  [         R                  " XF)    5      -  XV) '   XV) ==   U S-
  [         R                  " U5      [         R                  " [         R                  " U5      5      -  R                  SS9-  -  ss'   U$ )a	  The yeojohnson log-likelihood function.

Parameters
----------
lmb : scalar
    Parameter for Yeo-Johnson transformation. See `yeojohnson` for
    details.
data : array_like
    Data to calculate Yeo-Johnson log-likelihood for. If `data` is
    multi-dimensional, the log-likelihood is calculated along the first
    axis.

Returns
-------
llf : float
    Yeo-Johnson log-likelihood of `data` given `lmb`.

See Also
--------
yeojohnson, probplot, yeojohnson_normplot, yeojohnson_normmax

Notes
-----
The Yeo-Johnson log-likelihood function is defined here as

.. math::

    llf = -N/2 \log(\hat{\sigma}^2) + (\lambda - 1)
          \sum_i \text{ sign }(x_i)\log(|x_i| + 1)

where :math:`\hat{\sigma}^2` is estimated variance of the Yeo-Johnson
transformed input data ``x``.

.. versionadded:: 1.2.0

Examples
--------
>>> import numpy as np
>>> from scipy import stats
>>> import matplotlib.pyplot as plt
>>> from mpl_toolkits.axes_grid1.inset_locator import inset_axes

Generate some random variates and calculate Yeo-Johnson log-likelihood
values for them for a range of ``lmbda`` values:

>>> x = stats.loggamma.rvs(5, loc=10, size=1000)
>>> lmbdas = np.linspace(-2, 10)
>>> llf = np.zeros(lmbdas.shape, dtype=float)
>>> for ii, lmbda in enumerate(lmbdas):
...     llf[ii] = stats.yeojohnson_llf(lmbda, x)

Also find the optimal lmbda value with `yeojohnson`:

>>> x_most_normal, lmbda_optimal = stats.yeojohnson(x)

Plot the log-likelihood as function of lmbda.  Add the optimal lmbda as a
horizontal line to check that that's really the optimum:

>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> ax.plot(lmbdas, llf, 'b.-')
>>> ax.axhline(stats.yeojohnson_llf(lmbda_optimal, x), color='r')
>>> ax.set_xlabel('lmbda parameter')
>>> ax.set_ylabel('Yeo-Johnson log-likelihood')

Now add some probability plots to show that where the log-likelihood is
maximized the data transformed with `yeojohnson` looks closest to normal:

>>> locs = [3, 10, 4]  # 'lower left', 'center', 'lower right'
>>> for lmbda, loc in zip([-1, lmbda_optimal, 9], locs):
...     xt = stats.yeojohnson(x, lmbda=lmbda)
...     (osm, osr), (slope, intercept, r_sq) = stats.probplot(xt)
...     ax_inset = inset_axes(ax, width="20%", height="20%", loc=loc)
...     ax_inset.plot(osm, osr, 'c.', osm, slope*osm + intercept, 'k-')
...     ax_inset.set_xticklabels([])
...     ax_inset.set_yticklabels([])
...     ax_inset.set_title(r'$\lambda=%1.2f$' % lmbda)

>>> plt.show()

r   r   rc   r!   )r   r	   r   r   ry  ri   r   rY  r   tinyinfr   rb  r}  r  r   )r  rX   	n_samplestrans	trans_varlogliketiny_variances          r`   rI   rI   ^  s    d ::dD

1IA~vv!$,E		q	!ImmI&G  9 > >>MVVG 

Q	. 9:: NN	qRWWT]RXXbffTl%;;@@a@HHJNra   c           	         S n[         R                  " SS9   [         R                  " [         R                  " U 5      5      (       d  [	        S5      e[         R                  " U S:H  5      (       a
   SSS5        gUb  [
        R                  " X!U 4S9sSSS5        $ [         R                  " U 5      n [         R                  " U R                  [         R                  5      (       a  U R                  O[         R                  n[         R                  " S	[         R                  " [         R                  " U 5      5      -  5      n[         R                  " [         R                   " U5      R"                  5      n[         R                  " [         R                   " U5      R$                  5      U-
  S
-  n[         R                  " [         R                   " U5      R                  5      U-   S
-  nXd-  nXt-  n	[         R                  " U S:  5      (       a
  S
U	-
  S
U-
  pO;[         R&                  " U S:  5      (       a  [        S
U	-
  U5      [)        S
U-
  U	5      pSn
[
        R*                  " X(X4U
S9sSSS5        $ ! , (       d  f       g= f)ai  Compute optimal Yeo-Johnson transform parameter.

Compute optimal Yeo-Johnson transform parameter for input data, using
maximum likelihood estimation.

Parameters
----------
x : array_like
    Input array.
brack : 2-tuple, optional
    The starting interval for a downhill bracket search with
    `optimize.brent`. Note that this is in most cases not critical; the
    final result is allowed to be outside this bracket. If None,
    `optimize.fminbound` is used with bounds that avoid overflow.

Returns
-------
maxlog : float
    The optimal transform parameter found.

See Also
--------
yeojohnson, yeojohnson_llf, yeojohnson_normplot

Notes
-----
.. versionadded:: 1.2.0

Examples
--------
>>> import numpy as np
>>> from scipy import stats
>>> import matplotlib.pyplot as plt

Generate some data and determine optimal ``lmbda``

>>> rng = np.random.default_rng()
>>> x = stats.loggamma.rvs(5, size=30, random_state=rng) + 5
>>> lmax = stats.yeojohnson_normmax(x)

>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> prob = stats.yeojohnson_normplot(x, -10, 10, plot=ax)
>>> ax.axvline(lmax, color='r')

>>> plt.show()

c                 n    [        X5      n[        R                  * U[        R                  " U5      '   U* $ rz   )rI   r   r  r]  )r  rX   llfs      r`   _neg_llf$yeojohnson_normmax.<locals>._neg_llf  s-    U) !ffWBHHSMtra   ignore)invalidz!Yeo-Johnson input must be finite.r   Nr   r      rc   g`sbO>r   xtol)r   errstater%  rU  rU   r   r   r	   rW  r   rX  r   r}  rZ  r  r   rY  epsr  r&  r^  	fminbound)ro   r   r  r   log1p_max_xlog_epslog_tiny_floatlog_max_floatrm  ub	tol_brents              r`   rK   rK     s   b 
X	&vvbkk!n%%@AA66!q&>>	 
'	&
 >>(qdC 
'	& JJqM=="++>>BJJ hhrBFF266!9$556 &&%,,-&&%!5!56@AE 3 34w>!C
 )(66!a%==VQVVVAE]]R_c!b&"o	!!(IN= 
'	&	&s   AI9;I9GI99
Jc                     [        SXX#U5      $ )a  Compute parameters for a Yeo-Johnson normality plot, optionally show it.

A Yeo-Johnson normality plot shows graphically what the best
transformation parameter is to use in `yeojohnson` to obtain a
distribution that is close to normal.

Parameters
----------
x : array_like
    Input array.
la, lb : scalar
    The lower and upper bounds for the ``lmbda`` values to pass to
    `yeojohnson` for Yeo-Johnson transformations. These are also the
    limits of the horizontal axis of the plot if that is generated.
plot : object, optional
    If given, plots the quantiles and least squares fit.
    `plot` is an object that has to have methods "plot" and "text".
    The `matplotlib.pyplot` module or a Matplotlib Axes object can be used,
    or a custom object with the same methods.
    Default is None, which means that no plot is created.
N : int, optional
    Number of points on the horizontal axis (equally distributed from
    `la` to `lb`).

Returns
-------
lmbdas : ndarray
    The ``lmbda`` values for which a Yeo-Johnson transform was done.
ppcc : ndarray
    Probability Plot Correlation Coefficient, as obtained from `probplot`
    when fitting the Box-Cox transformed input `x` against a normal
    distribution.

See Also
--------
probplot, yeojohnson, yeojohnson_normmax, yeojohnson_llf, ppcc_max

Notes
-----
Even if `plot` is given, the figure is not shown or saved by
`boxcox_normplot`; ``plt.show()`` or ``plt.savefig('figname.png')``
should be used after calling `probplot`.

.. versionadded:: 1.2.0

Examples
--------
>>> from scipy import stats
>>> import matplotlib.pyplot as plt

Generate some non-normally distributed data, and create a Yeo-Johnson plot:

>>> x = stats.loggamma.rvs(5, size=500) + 5
>>> fig = plt.figure()
>>> ax = fig.add_subplot(111)
>>> prob = stats.yeojohnson_normplot(x, -20, 20, plot=ax)

Determine and plot the optimal ``lmbda`` to transform ``x`` and plot it in
the same plot:

>>> _, maxlog = stats.yeojohnson(x)
>>> ax.axvline(maxlog, color='r')

>>> plt.show()

rJ   rs  rt  s        r`   rL   rL     s    F \1"A66ra   ShapiroResult)rP   pvalue)r  	too_smallr   c                    [         R                  " U 5      R                  [         R                  5      n [	        U 5      nUS:  a  [        S5      e[        US-  [         R                  S9nSn[        U 5      nX@US-     -  n[        XBU5      u  pVnUS;  a  [        R                  " SSS9  US	:  a  [        R                  " S
U S3SS9  [        [         R                  " U5      [         R                  " U5      5      $ )aC  Perform the Shapiro-Wilk test for normality.

The Shapiro-Wilk test tests the null hypothesis that the
data was drawn from a normal distribution.

Parameters
----------
x : array_like
    Array of sample data. Must contain at least three observations.

Returns
-------
statistic : float
    The test statistic.
p-value : float
    The p-value for the hypothesis test.

See Also
--------
anderson : The Anderson-Darling test for normality
kstest : The Kolmogorov-Smirnov test for goodness of fit.
:ref:`hypothesis_shapiro` : Extended example

Notes
-----
The algorithm used is described in [4]_ but censoring parameters as
described are not implemented. For N > 5000 the W test statistic is
accurate, but the p-value may not be.

References
----------
.. [1] https://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm
       :doi:`10.18434/M32189`
.. [2] Shapiro, S. S. & Wilk, M.B, "An analysis of variance test for
       normality (complete samples)", Biometrika, 1965, Vol. 52,
       pp. 591-611, :doi:`10.2307/2333709`
.. [3] Razali, N. M. & Wah, Y. B., "Power comparisons of Shapiro-Wilk,
       Kolmogorov-Smirnov, Lilliefors and Anderson-Darling tests", Journal
       of Statistical Modeling and Analytics, 2011, Vol. 2, pp. 21-33.
.. [4] Royston P., "Remark AS R94: A Remark on Algorithm AS 181: The
       W-test for Normality", 1995, Applied Statistics, Vol. 44,
       :doi:`10.2307/2986146`

Examples
--------

>>> import numpy as np
>>> from scipy import stats
>>> rng = np.random.default_rng()
>>> x = stats.norm.rvs(loc=5, scale=3, size=100, random_state=rng)
>>> shapiro_test = stats.shapiro(x)
>>> shapiro_test
ShapiroResult(statistic=0.9813305735588074, pvalue=0.16855233907699585)
>>> shapiro_test.statistic
0.9813305735588074
>>> shapiro_test.pvalue
0.16855233907699585

For a more detailed example, see :ref:`hypothesis_shapiro`.
r   zData must be at least length 3.rc   r   r   )r   rc   zPscipy.stats.shapiro: Input data has range zero. The results may not be accurate.rS  i  zVscipy.stats.shapiro: For N > 5000, computed p-value may not be accurate. Current N is r9  )r   r   r	  r   rh   rU   r
   r   r#   r`  ra  r  )ro   r   r   initr'  wpwifaults           r`   r<   r<   g  s    | 	2::&AAA1u:;;ad"**%ADQA1a4LA!%MA6V 6BC	E4x ;;<#Q@!"	$ A

277ra   )g;On?gˡE?gv/?gK7A`?gFx?)g/$?gsh|??g~jt?gV-?gZd;O?)gtV?gMb?MbX9?gMb?gS㥛?)g$C?jt?gQ?gS㥛?gˡE?g)\(?)g㥛 ?gHzG?gS?gNbX9?gX9v?獗n?gn?gn?)gzG?gK7?g/$?gw/?gV-?g5^I?g
ףp=
?g&1?)gOn?gn?gX9v?gJ+?gx&1?gK?g1Zd?gI+?)g$C?g&1?gx?gZd;O?g{Gz?gV-?g+?g5^I?)gQ?g"~?g\(\?g rh?g?gx&1?gRQ?gZd;O?)g-?gl?gZd;?gS?gv/?g{Gz?gw/?g&1?)gjt?g~jt?gK7A?g=
ףp=?goʡ?g/$?gK7?g{Gz?)g{Gz?gx&1?gS㥛?g-?g/$?gDl?gM?gx?)g!rh?gy&1?g/$?gA`"?r  g|?5^?g^I+?gCl?)gK7A`?gjt?g/$?gGz?gCl?333333?gjt?g      ?)gS?gh|?5?r  g'1Z?r  gT㥛 ?g㥛 ?gy&1?r      linearr   )kindbounds_error
fill_valuec                 j  ^^^^ [        T5      mU u  p#nUU4S jmUU4S jmUU4S jnUU4S jnSn[        R                  " U[        R                  " T5      5      (       d  US:  a  SU-   n[	        U5      e [        R
                  " SSS	9   [        R                  " X`S S
 5      n	S S S 5        SW	R                   S3U-   nU	R                  (       d  [	        U5      e U	R                  u  p#U" X#5      nX#U4$ ! , (       d  f       NX= f! [        [        4 a  n
SU-   n[	        U5      U
eS n
A
ff = f)Nc                    > TU-
  nSU -  X -  [         R                  " U5      -  R                  5       X -  R                  5       -  -
  [         R                  " U5      R                  5       T-  -   $ r   )r   r   r   rZ   uxurp   ro   s      r`   dnllf_dm$_weibull_fit_check.<locals>.dnllf_dm  s^    qS!ruRVVBZ',,.{{}<<&&*.."1$% 	&ra   c                    > TU-
  nU S-
  U -  US-  R                  5       -  TX S-
  -  R                  5       -  X -  R                  5       -  -
  $ )Nr!   r   r   r  s      r`   dnllf_du$_weibull_fit_check.<locals>.dnllf_du  sM    qS!QwB||~%2!9//*;(;RUKKM(IIIra   c                 B   > TU-
  U -  T-  R                  5       SU -  -  $ r   r  )rZ   r  rp   ro   s     r`   	get_scale%_weibull_fit_check.<locals>.get_scale  s)     1q
!AaC((ra   c                    > T" U 6 T" U 6 /$ rz   r{   )paramsr  r  s    r`   dnllf!_weibull_fit_check.<locals>.dnllf  s     &!8V#455ra   zMaximum likelihood estimation is known to be challenging for the three-parameter Weibull distribution. Consider performing a custom goodness-of-fit test using `scipy.stats.monte_carlo_test`.r!   zMaximum likelihood estimation has converged to a solution in which the location is equal to the minimum of the data, the shape parameter is less than 2, or both. The table of critical values in [7] does not include this case. raise)overr  r   z/Solution of MLE first-order conditions failed: z. `anderson` cannot continue. zeAn error occurred while fitting the Weibull distribution to the data, so `anderson` cannot continue. )rh   r   allcloser^  rU   r  r   rootrc  successFloatingPointErrorro   )r  ro   rZ   r  r\   r  r  
suggestionrc  r   r   r  r  rp   s    `         @@@r`   _weibull_fit_checkr    s6   
 	AAGA!&J
)
6
4J
 
{{1bffQi  AE) ,6	6
 !!) [[gw7--cr{3C 8 Ekk]"@BDNO{{W%%  55DA!A7N 87 
+ )BDNO!q()s0   :D C;)7D ;
D	D D2D--D2AndersonResult)rP   critical_valuessignificance_level
fit_resultc           	      	   UR                  5       nUS;   a  Sn1 SknX;  a  [        SU S35      e[        U 5      n[        R                  " U SS9n[        U5      nUS:X  a  [        R                  " U S	SS
9nX4-
  U-  nXF4n[        R                  R                  U5      n	[        R                  R                  U5      n
[        / SQ5      n[        [        SSU-  -   SU-  U-  -
  -  S5      nGO@US:X  an  X4-  nSU4n[        R                  R                  U5      n	[        R                  R                  U5      n
[        / SQ5      n[        [        SSU-  -   -  S5      nGOUS:X  a  S n[        U[        R                  " U S	SS
9/5      n[         R"                  " XX4SS9nX?S   -
  US	   -  nUn[        R$                  R                  U5      n	[        R$                  R                  U5      n
[        / SQ5      n[        [&        SSU-  -   -  S5      nGOUS:X  a  [        R(                  R+                  U 5      u  pFX4-
  U-  nXF4n[        R(                  R                  U5      n	[        R(                  R                  U5      n
[        / SQ5      n[        [,        SS[/        U5      -  -   -  S5      nGOvUS:X  a  [        R0                  R+                  U 5      u  pFX4-
  U-  nXF4n[        R0                  R                  U5      n	[        R0                  R                  U5      n
[        / SQ5      n[        [,        SS[/        U5      -  -   -  S5      nOUS:X  a  SnUS:  a  [2        R4                  " USS9  [        R6                  R+                  U5      u  nnn[9        UUU4U5      u  nnnUUU4n[:        R6                  " U6 R                  U5      n	[:        R6                  " U6 R                  U5      n
S	U-  n[        / S Q5      n[=        U5      n[        R>                  " US!-   SS"9n[A        S	US	-   5      nU* [        RB                  " SU-  S-
  U-  W	W
S#S#S$2   -   -  SS9-
  nS%n[         RD                  " S&US'9n[        R                  " W5      Ul#        [I        [K        [        U5      US(US)9n[M        UWWUS*9$ )+ar  Anderson-Darling test for data coming from a particular distribution.

The Anderson-Darling test tests the null hypothesis that a sample is
drawn from a population that follows a particular distribution.
For the Anderson-Darling test, the critical values depend on
which distribution is being tested against.  This function works
for normal, exponential, logistic, weibull_min, or Gumbel (Extreme Value
Type I) distributions.

Parameters
----------
x : array_like
    Array of sample data.
dist : {'norm', 'expon', 'logistic', 'gumbel', 'gumbel_l', 'gumbel_r', 'extreme1', 'weibull_min'}, optional
    The type of distribution to test against.  The default is 'norm'.
    The names 'extreme1', 'gumbel_l' and 'gumbel' are synonyms for the
    same distribution.

Returns
-------
result : AndersonResult
    An object with the following attributes:

    statistic : float
        The Anderson-Darling test statistic.
    critical_values : list
        The critical values for this distribution.
    significance_level : list
        The significance levels for the corresponding critical values
        in percents.  The function returns critical values for a
        differing set of significance levels depending on the
        distribution that is being tested against.
    fit_result : `~scipy.stats._result_classes.FitResult`
        An object containing the results of fitting the distribution to
        the data.

See Also
--------
kstest : The Kolmogorov-Smirnov test for goodness-of-fit.

Notes
-----
Critical values provided are for the following significance levels:

normal/exponential
    15%, 10%, 5%, 2.5%, 1%
logistic
    25%, 10%, 5%, 2.5%, 1%, 0.5%
gumbel_l / gumbel_r
    25%, 10%, 5%, 2.5%, 1%
weibull_min
    50%, 25%, 15%, 10%, 5%, 2.5%, 1%, 0.5%

If the returned statistic is larger than these critical values then
for the corresponding significance level, the null hypothesis that
the data come from the chosen distribution can be rejected.
The returned statistic is referred to as 'A2' in the references.

For `weibull_min`, maximum likelihood estimation is known to be
challenging. If the test returns successfully, then the first order
conditions for a maximum likelihood estimate have been verified and
the critical values correspond relatively well to the significance levels,
provided that the sample is sufficiently large (>10 observations [7]).
However, for some data - especially data with no left tail - `anderson`
is likely to result in an error message. In this case, consider
performing a custom goodness of fit test using
`scipy.stats.monte_carlo_test`.

References
----------
.. [1] https://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm
.. [2] Stephens, M. A. (1974). EDF Statistics for Goodness of Fit and
       Some Comparisons, Journal of the American Statistical Association,
       Vol. 69, pp. 730-737.
.. [3] Stephens, M. A. (1976). Asymptotic Results for Goodness-of-Fit
       Statistics with Unknown Parameters, Annals of Statistics, Vol. 4,
       pp. 357-369.
.. [4] Stephens, M. A. (1977). Goodness of Fit for the Extreme Value
       Distribution, Biometrika, Vol. 64, pp. 583-588.
.. [5] Stephens, M. A. (1977). Goodness of Fit with Special Reference
       to Tests for Exponentiality , Technical Report No. 262,
       Department of Statistics, Stanford University, Stanford, CA.
.. [6] Stephens, M. A. (1979). Tests of Fit for the Logistic Distribution
       Based on the Empirical Distribution Function, Biometrika, Vol. 66,
       pp. 591-595.
.. [7] Richard A. Lockhart and Michael A. Stephens "Estimation and Tests of
       Fit for the Three-Parameter Weibull Distribution"
       Journal of the Royal Statistical Society.Series B(Methodological)
       Vol. 56, No. 3 (1994), pp. 491-500, Table 0.

Examples
--------
Test the null hypothesis that a random sample was drawn from a normal
distribution (with unspecified mean and standard deviation).

>>> import numpy as np
>>> from scipy.stats import anderson
>>> rng = np.random.default_rng()
>>> data = rng.random(size=35)
>>> res = anderson(data)
>>> res.statistic
0.8398018749744764
>>> res.critical_values
array([0.527, 0.6  , 0.719, 0.839, 0.998])
>>> res.significance_level
array([15. , 10. ,  5. ,  2.5,  1. ])

The value of the statistic (barely) exceeds the critical value associated
with a significance level of 2.5%, so the null hypothesis may be rejected
at a significance level of 2.5%, but not at a significance level of 1%.

>   gumbelextreme1gumbel_l>   rj   exponr  gumbel_rlogisticweibull_minz&Invalid distribution; dist must be in r9  r   r   rj   r!   )ddofr   )   
            @r!   r         @g      9@r   r  g333333?r  c                     U u  p4X-
  U-  n[        U5      n[        R                  " SSU-   -  SS9SU-  -
  [        R                  " USU-
  -  SU-   -  SS9U-   /n[        U5      $ )Nr   r!   r   r   r   )r   r   r   r   )abxjr   r   r   tmptmp2rx   s           r`   r  anderson.<locals>.rootfunc  sr    DA6Q,Cs8D66#qv,Q/#a%766#s4x.!D&1:Q>@C:ra   gh㈵>r  )   r  r  r  r!   r         ?r  )r  r  r  r  r!   g?r  zCritical values of the test statistic are given for the asymptotic distribution. These may not be accurate for samples with fewer than 10 observations. Consider using `scipy.stats.monte_carlo_test`.r  rc   rS  )r   g      ?r  ?gffffff?g333333?gGz?gףp=
?gMb@?)decimalsNr   z9`anderson` successfully fit the distribution to the data.T)r  rc  F)discreter   )r  )'lowerrU   r   r   rV   rh   stdr-   rj   logcdflogsfr   r   _Avals_normr  _Avals_exponr   fsolver  _Avals_logisticr  r   _Avals_gumbelr   r  r`  ra  r  r  r   _get_As_weibullroundr   r   OptimizeResultro   r&   r   r  )ro   r   distsr'  rq   r   r\   r  
fit_paramsr  r  sigcriticalr  sol0solrc  rZ   rd   re   cr   A2r   r  s                            r`   r=   r=   )  su   b ::<D%%4E A%JKKQA7711DAAv~FF111%XNW
##**1-""((+'(+s1utAvax)?@!D	HW
$$++A.##))!,'(,#A+6:			 dBFF111567oohA6EQZ3q6!
''..q1&&,,Q/,-/S46\:A>		((,,Q/XNW
''..q1&&,,Q/'(-3T!W+<=qA		((,,Q/XNW
''..q1&&,,Q/'(-3T!W+<=qA		5 r6MM'a0%1155a83*AsE?A>3U]
""J/66q9!!:.44Q7EDE"1% 88Hv-:q!a%A
bffacCi1_tt(<=AF	FB JG

!
!$
@CHHZ CE7=$7$)s4J "h
CCra   c                    SnUR                  US5      nXRR                  :X  a  SnOUR                  US5      U-
  nXxS-  -   n	[        SU5       H  n
[        R                  " X
   5      nUR                  USS9nUR                  [        5      nXR                  US5      -
  nXS-  -  nU[        U5      -  X]-  XU
   -  -
  S-  -  XU	-
  -  XX-  S	-  -
  -  nXoR                  5       XJ   -  -  nM     XeS-
  U-  -  nU$ )
a  Compute A2akN equation 7 of Scholz and Stephens.

Parameters
----------
samples : sequence of 1-D array_like
    Array of sample arrays.
Z : array_like
    Sorted array of all observations.
Zstar : array_like
    Sorted array of unique observations.
k : int
    Number of samples.
n : array_like
    Number of observations in each sample.
N : int
    Total number of observations.

Returns
-------
A2aKN : float
    The A2aKN statistics of Scholz and Stephens 1987.

r   leftr   rightrf   r   siderc   r  )searchsortedr   r   r   r   r	  rO  r   )samplesZZstarr   rp   r   A2akNZ_ssorted_leftljBjr   r\   s_ssorted_rightMijfijinners                   r`   _anderson_ksamp_midrankr
    s   0 E^^E62NJJ^^E7+n<	r'	!BAq\GGGJ..W.=$$U+uf ==RxU1XaD1 44Fad2g8MNqt##  
"f\ELra   c                 v   SnUR                  USS S5      UR                  USS S5      -
  nUR                  5       n[        SU5       Hk  n	[        R                  " X	   5      n
U
R                  USS SS9nU[        U5      -  X[-  XU	   -  -
  S-  -  XU-
  -  -  nXlR                  5       XI   -  -  nMm     U$ )	a  Compute A2akN equation 6 of Scholz & Stephens.

Parameters
----------
samples : sequence of 1-D array_like
    Array of sample arrays.
Z : array_like
    Sorted array of all observations.
Zstar : array_like
    Sorted array of unique observations.
k : int
    Number of samples.
n : array_like
    Number of observations in each sample.
N : int
    Total number of observations.

Returns
-------
A2KN : float
    The A2KN statistics of Scholz and Stephens 1987.

r   Nr   r  r  r   r  rc   )r  cumsumr   r   r   rO  r   )r  r   r  r   rp   r   A2kNr  r  r   r\   r  r	  s                r`   _anderson_ksamp_rightr  !	  s    0 D	
cr
G	,q~~eCRj>D0F 
FB	BAq\GGGJnnU3BZgn6U1X2!9!4q 88Bb&MJ		ad""	 
 Kra   Anderson_ksampResult)rP   r  r  )r#  c                R  ^^^^^^ [        U 5      mTS:  a  [        S5      e[        [        [        R
                  U 5      5      n [        R                  " [        R                  " U 5      5      mTR                  m[        R                  " T5      mTR                  S:  a  [        S5      e[        R                  " U  Vs/ s H  o3R                  PM     sn5      m[        R                  " TS:H  5      (       a  [        S5      eU(       a  [        mO[        mT" U TTTTT5      nUUUUUU4S jnUb)  [        R                  " X40 UR!                  5       DSS0D6nS	T-  R#                  5       nS	[%        TS
-
  S
S5      -  R'                  5       nUS   S
-   n	U[%        ST5      -  R#                  5       n
SU
-  S-
  TS
-
  -  SSU
-  -
  U-  -   nSU
-  S-
  TS-  -  SU	-  T-  -   SU
-  SU	-  -
  S-
  U-  -   SU	-  -
  SU
-  -   S-
  nSU	-  SU
-  -   S-
  TS-  -  SU	-  SU
-  -
  S-   T-  -   SU	-  S-
  U-  -   SU	-  -   nSU	-  S-   TS-  -  SU	-  T-  -
  nUTS-  -  UTS-  -  -   UT-  -   U-   TS	-
  TS-
  -  TS-
  -  -  nTS
-
  nUU-
  [(        R*                  " U5      -  n[        R                  " / SQ5      n[        R                  " / SQ5      n[        R                  " / SQ5      nUU[(        R*                  " U5      -  -   UU-  -   n[        R                  " / SQ5      nUUR-                  5       :  a/  Uc,  UR/                  5       nSU S3n[0        R2                  " USS9  OUUR/                  5       :  a/  Uc,  UR-                  5       nSU S3n[0        R2                  " USS9  OaUcM  [        R4                  " U[7        U5      S5      n[(        R8                  " [        R:                  " UU5      5      nOUb  WR<                  OWn[?        UUU5      nUUl         U$ s  snf )a  The Anderson-Darling test for k-samples.

The k-sample Anderson-Darling test is a modification of the
one-sample Anderson-Darling test. It tests the null hypothesis
that k-samples are drawn from the same population without having
to specify the distribution function of that population. The
critical values depend on the number of samples.

Parameters
----------
samples : sequence of 1-D array_like
    Array of sample data in arrays.
midrank : bool, optional
    Type of Anderson-Darling test which is computed. Default
    (True) is the midrank test applicable to continuous and
    discrete populations. If False, the right side empirical
    distribution is used.
method : PermutationMethod, optional
    Defines the method used to compute the p-value. If `method` is an
    instance of `PermutationMethod`, the p-value is computed using
    `scipy.stats.permutation_test` with the provided configuration options
    and other appropriate settings. Otherwise, the p-value is interpolated
    from tabulated values.

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

    statistic : float
        Normalized k-sample Anderson-Darling test statistic.
    critical_values : array
        The critical values for significance levels 25%, 10%, 5%, 2.5%, 1%,
        0.5%, 0.1%.
    pvalue : float
        The approximate p-value of the test. If `method` is not
        provided, the value is floored / capped at 0.1% / 25%.

Raises
------
ValueError
    If fewer than 2 samples are provided, a sample is empty, or no
    distinct observations are in the samples.

See Also
--------
ks_2samp : 2 sample Kolmogorov-Smirnov test
anderson : 1 sample Anderson-Darling test

Notes
-----
[1]_ defines three versions of the k-sample Anderson-Darling test:
one for continuous distributions and two for discrete
distributions, in which ties between samples may occur. The
default of this routine is to compute the version based on the
midrank empirical distribution function. This test is applicable
to continuous and discrete data. If midrank is set to False, the
right side empirical distribution is used for a test for discrete
data. According to [1]_, the two discrete test statistics differ
only slightly if a few collisions due to round-off errors occur in
the test not adjusted for ties between samples.

The critical values corresponding to the significance levels from 0.01
to 0.25 are taken from [1]_. p-values are floored / capped
at 0.1% / 25%. Since the range of critical values might be extended in
future releases, it is recommended not to test ``p == 0.25``, but rather
``p >= 0.25`` (analogously for the lower bound).

.. versionadded:: 0.14.0

References
----------
.. [1] Scholz, F. W and Stephens, M. A. (1987), K-Sample
       Anderson-Darling Tests, Journal of the American Statistical
       Association, Vol. 82, pp. 918-924.

Examples
--------
>>> import numpy as np
>>> from scipy import stats
>>> rng = np.random.default_rng()
>>> res = stats.anderson_ksamp([rng.normal(size=50),
... rng.normal(loc=0.5, size=30)])
>>> res.statistic, res.pvalue
(1.974403288713695, 0.04991293614572478)
>>> res.critical_values
array([0.325, 1.226, 1.961, 2.718, 3.752, 4.592, 6.546])

The null hypothesis that the two random samples come from the same
distribution can be rejected at the 5% level because the returned
test value is greater than the critical value for 5% (1.961) but
not at the 2.5% level. The interpolation gives an approximate
p-value of 4.99%.

>>> samples = [rng.normal(size=50), rng.normal(size=30),
...            rng.normal(size=20)]
>>> res = stats.anderson_ksamp(samples)
>>> res.statistic, res.pvalue
(-0.29103725200789504, 0.25)
>>> res.critical_values
array([ 0.44925884,  1.3052767 ,  1.9434184 ,  2.57696569,  3.41634856,
  4.07210043, 5.56419101])

The null hypothesis cannot be rejected for three samples from an
identical distribution. The reported p-value (25%) has been capped and
may not be very accurate (since it corresponds to the value 0.449
whereas the statistic is -0.291).

In such cases where the p-value is capped or when sample sizes are
small, a permutation test may be more accurate.

>>> method = stats.PermutationMethod(n_resamples=9999, random_state=rng)
>>> res = stats.anderson_ksamp(samples, method=method)
>>> res.pvalue
0.5254

rc   z)anderson_ksamp needs at least two samplesz7anderson_ksamp needs more than one distinct observationr   z6anderson_ksamp encountered sample without observationsc                     > T" U TTTTT5      $ rz   r{   )r  A2kN_funr   r   r  r   rp   s    r`   rP   !anderson_ksamp.<locals>.statistic	  s    E1a33ra   alternativegreaterr   r!   r   r      r        r   rf   r   )g?g"~?gRQ?g\(\?gS㥛@g/$@gGz@)g\(\Ͽr  gV-?gMb?gx&?gx@gQ@)gzGếgQӿg^I+׿g/$ٿgMbXٿgGzֿgʡEÿ)r  r  皙?g?r   g{Gzt?gMbP?z'p-value capped: true value larger than zI. Consider specifying `method` (e.g. `method=stats.PermutationMethod()`.)rS  z)p-value floored: true value smaller than )!rh   rU   listmapr   r	   r   hstackr   r   r   r&  r
  r  r   permutation_test_asdictr   r   r  rk   r   r^  rZ  r`  ra  polyfitr   r   polyvalr  r  r  ) r  midrankr#  sampler  rP   r   Hhs_cshgr   r   r  dsigmasqrZ   r  b0b1b2r  r  pr   pfr  r   r   r  r   rp   s                              @@@@@@r`   rH   rH   K	  s   l 	GA	ADEE3rzz7+,G
		'"#A	AIIaLEzzA~ ' ( 	( 	G4G&++G45A	vva1f~~ ( ) 	) *(GQq!Q/D4 4 $$W <6>>;K <1:< 
aA&Q2&&..0Eb	AA	1	""$A	
1qQUrAaCxl*A	
1q!Q$1Q!A#1*q.!!33ac9AaC?!CA	
1qsQ1!ac	Aq00AaC!GQ;>1DA	
1q!Q$1QAAv!Q$1$q(a"fR-@AF-KLG	AA
(dii(	(B 
B	CB	C	DB	J	KBB1%%Q.H
((?
@C	HLLNv~GGI8 << < 	ca(	hlln	GGI:1# >< < 	ca(	ZZ#c(A.HHRZZB'( ,CJJ! r8Q
/CCJ} 5s   P$AnsariResultc                   6    \ rS rSrSrS rS rS rS rS r	Sr
g	)
_ABWi
  zEDistribution of Ansari-Bradley W-statistic under the null hypothesis.c                 J    SU l         SU l        SU l        SU l        SU l        g)zMinimal initializer.N)rZ   rp   astarttotalfreqsr/  s    r`   __init___ABW.__init__
  s%    

ra   c                    XR                   :w  d  X R                  :w  af  XsU l         U l        [        X5      u  p4nX0l        UR	                  [
        R                  5      U l        U R                  R                  5       U l	        gg)z/When necessary, recalculate exact distribution.N)
rp   rZ   r"   r2  r	  r   r   r4  r   r3  )r0  rp   rZ   r2  a1r   s         r`   _recalc_ABW._recalc
  sa    ;!vv+NDFDF #1LMF K 2::.DJ)DJ &ra   c                     U R                  X#5        [        R                  " XR                  -
  5      R	                  [
        5      nU R                  U   U R                  -  $ )zProbability mass function.)r9  r   floorr2  r	  r   r4  r3  r0  r   rp   rZ   inds        r`   pmf_ABW.pmf.
  sF    Q hhq;;'..s3zz#++ra   c                     U R                  X#5        [        R                  " XR                  -
  5      R	                  [
        5      nU R                  SUS-    R                  5       U R                  -  $ )z!Cumulative distribution function.Nr!   )	r9  r   ceilr2  r	  r   r4  r   r3  r=  s        r`   cdf_ABW.cdf6
  sV    Q gga++o&--c2zz&3q5!%%'$**44ra   c                     U R                  X#5        [        R                  " XR                  -
  5      R	                  [
        5      nU R                  US R                  5       U R                  -  $ )zSurvival function.N)	r9  r   r<  r2  r	  r   r4  r   r3  r=  s        r`   sf_ABW.sf>
  sR    Q hhq;;'..s3zz#$##%

22ra   )r2  r4  rZ   rp   r3  N)r3  r4  r5  r6  __doc__r5  r9  r?  rC  rF  r7  r{   ra   r`   r0  r0  
  s    O
*,53ra   r0  )r  c           	         US;  a  [        S5      e[        [        S5      (       d  [        5       [        l        [        U 5      [        U5      p[        U 5      n[        U5      nUS:  a  [        S5      eUS:  a  [        S5      eXC-   n[        X4   n[        R                  " U5      n[        [        XuU-
  S-   45      S5      n[        R                  " USU SS	9n	[        U5      n
[        U
5      [        U5      :g  nUS
:  =(       a    US
:  =(       a    U(       + nU(       a!  US
:  d  US
:  a  [        R                   " SSS9  U(       a  US:X  aW  S[        R"                  " [        R                  R%                  XU5      [        R                  R'                  XU5      5      -  nOGUS:X  a!  [        R                  R%                  XU5      nO [        R                  R'                  XU5      n[)        U	[+        SU5      5      $ US-  (       a-  X5S-   S-  -  S-  U-  nX4-  US-   -  SUS-  -   -  SUS-  -  -  nO#X5S-   -  S-  nXC-  US-   -  US-
  -  S-  US-
  -  nU(       ai  [        R                  " US-  SS	9nUS-  (       a&  XC-  SU-  U-  US-   S-  -
  -  SUS-  -  US-
  -  -  nO!XC-  SU-  XUS-   S-  -  -
  -  SU-  US-
  -  -  nX-
  [-        U5      -  n[/        U[1        5       U[        S9n[)        U	S   US   5      $ )aQ  Perform the Ansari-Bradley test for equal scale parameters.

The Ansari-Bradley test ([1]_, [2]_) is a non-parametric test
for the equality of the scale parameter of the distributions
from which two samples were drawn. The null hypothesis states that
the ratio of the scale of the distribution underlying `x` to the scale
of the distribution underlying `y` is 1.

Parameters
----------
x, y : array_like
    Arrays of sample data.
alternative : {'two-sided', 'less', 'greater'}, optional
    Defines the alternative hypothesis. Default is 'two-sided'.
    The following options are available:

    * 'two-sided': the ratio of scales is not equal to 1.
    * 'less': the ratio of scales is less than 1.
    * 'greater': the ratio of scales is greater than 1.

    .. versionadded:: 1.7.0

Returns
-------
statistic : float
    The Ansari-Bradley test statistic.
pvalue : float
    The p-value of the hypothesis test.

See Also
--------
fligner : A non-parametric test for the equality of k variances
mood : A non-parametric test for the equality of two scale parameters

Notes
-----
The p-value given is exact when the sample sizes are both less than
55 and there are no ties, otherwise a normal approximation for the
p-value is used.

References
----------
.. [1] Ansari, A. R. and Bradley, R. A. (1960) Rank-sum tests for
       dispersions, Annals of Mathematical Statistics, 31, 1174-1189.
.. [2] Sprent, Peter and N.C. Smeeton.  Applied nonparametric
       statistical methods.  3rd ed. Chapman and Hall/CRC. 2001.
       Section 5.8.2.
.. [3] Nathaniel E. Helwig "Nonparametric Dispersion and Equality
       Tests" at http://users.stat.umn.edu/~helwig/notes/npde-Notes.pdf

Examples
--------
>>> import numpy as np
>>> from scipy.stats import ansari
>>> rng = np.random.default_rng()

For these examples, we'll create three random data sets.  The first
two, with sizes 35 and 25, are drawn from a normal distribution with
mean 0 and standard deviation 2.  The third data set has size 25 and
is drawn from a normal distribution with standard deviation 1.25.

>>> x1 = rng.normal(loc=0, scale=2, size=35)
>>> x2 = rng.normal(loc=0, scale=2, size=25)
>>> x3 = rng.normal(loc=0, scale=1.25, size=25)

First we apply `ansari` to `x1` and `x2`.  These samples are drawn
from the same distribution, so we expect the Ansari-Bradley test
should not lead us to conclude that the scales of the distributions
are different.

>>> ansari(x1, x2)
AnsariResult(statistic=541.0, pvalue=0.9762532927399098)

With a p-value close to 1, we cannot conclude that there is a
significant difference in the scales (as expected).

Now apply the test to `x1` and `x3`:

>>> ansari(x1, x3)
AnsariResult(statistic=425.0, pvalue=0.0003087020407974518)

The probability of observing such an extreme value of the statistic
under the null hypothesis of equal scales is only 0.03087%. We take this
as evidence against the null hypothesis in favor of the alternative:
the scales of the distributions from which the samples were drawn
are not equal.

We can use the `alternative` parameter to perform a one-tailed test.
In the above example, the scale of `x1` is greater than `x3` and so
the ratio of scales of `x1` and `x3` is greater than 1. This means
that the p-value when ``alternative='greater'`` should be near 0 and
hence we should be able to reject the null hypothesis:

>>> ansari(x1, x3, alternative='greater')
AnsariResult(statistic=425.0, pvalue=0.0001543510203987259)

As we can see, the p-value is indeed quite low. Use of
``alternative='less'`` should thus yield a large p-value:

>>> ansari(x1, x3, alternative='less')
AnsariResult(statistic=425.0, pvalue=0.9998643258449039)

>   lessr  	two-sidedz8'alternative' must be 'two-sided', 'greater', or 'less'.r   r!   zNot enough other observations.zNot enough test observations.r   Nr   7   z%Ties preclude use of exact statistic.rc   rS  rK  rf   r  r   r  r   g      H@0      r   g      0@r   r{   )rU   r   
_abw_stater0  r   r	   rh   r   r$   rankdatar   r   r   r   r   r`  ra  minimumrC  rF  r.  r^  r   r(   r*   )ro   r'  r  rp   rZ   r   xyranksymrankABuxyrepeatsexactpvalmnABvarABrw   rp  r  s                      r`   r>   r>   M
  s   R :: 2 3 	3 :s##v
1:wqzqAAAA1u9::1u899	A	ADBb!D5$D1-.2G	!	$B
*C3x3r7"G"f21r627{EAFa"f=!L+%JLL$4$4RA$>$.LLOOB1$=? ?DI% <<##B1-D<<??2!,DBC// 	1ucEA:~#a'31QT6*dQTk:cE{S 13'",#6ffWaZa(q5ERT#X1q01TAqD[AaC5HIEERVa1qj01TAX15EFE
 
d5k!AMO[R@F2r
++ra   BartlettResultc           	         [        U6 n[        U5      nUS:  a  [        S5      e[        XUS9nU Vs/ s H  n[	        X@US9PM     nnU Vs/ s H)  oBR                  UR                  S   UR                  S9PM+     nnU Vs/ s H#  obR                  XaS   R                  SS 5      PM%     nnU Vs/ s H  oBR                  US	SS
9PM     nnU Vs/ s H  oUR                  S4   PM     nnU Vs/ s H  oUR                  S4   PM     nnUR                  USS9nUR                  USS9nUR                  n	UR                  USU	S9n
UR                  US	-
  U-  SU	S9X-
  -  nX-
  UR                  U5      -  UR                  US	-
  UR                  U5      -  SU	S9-
  nS	S	SUS	-
  -  -  UR                  S	US	-
  -  SU	S9S	X-
  -  -
  -  -   nX-  n[        UR                  US	-
  5      5      n[        XSSUS9nUR!                  USUR"                  S9nUR$                  S:X  a  US   OUnUR$                  S:X  a  US   OUn['        UU5      $ s  snf s  snf s  snf s  snf s  snf s  snf )a	  Perform Bartlett's test for equal variances.

Bartlett's test tests the null hypothesis that all input samples
are from populations with equal variances.  For samples
from significantly non-normal populations, Levene's test
`levene` is more robust.

Parameters
----------
sample1, sample2, ... : array_like
    arrays of sample data.  Only 1d arrays are accepted, they may have
    different lengths.

Returns
-------
statistic : float
    The test statistic.
pvalue : float
    The p-value of the test.

See Also
--------
fligner : A non-parametric test for the equality of k variances
levene : A robust parametric test for equality of k variances
:ref:`hypothesis_bartlett` : Extended example

Notes
-----
Conover et al. (1981) examine many of the existing parametric and
nonparametric tests by extensive simulations and they conclude that the
tests proposed by Fligner and Killeen (1976) and Levene (1960) appear to be
superior in terms of robustness of departures from normality and power
([3]_).

References
----------
.. [1]  https://www.itl.nist.gov/div898/handbook/eda/section3/eda357.htm
.. [2]  Snedecor, George W. and Cochran, William G. (1989), Statistical
          Methods, Eighth Edition, Iowa State University Press.
.. [3] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and
       Hypothesis Testing based on Quadratic Inference Function. Technical
       Report #99-03, Center for Likelihood Studies, Pennsylvania State
       University.
.. [4] Bartlett, M. S. (1937). Properties of Sufficiency and Statistical
       Tests. Proceedings of the Royal Society of London. Series A,
       Mathematical and Physical Sciences, Vol. 160, No.901, pp. 268-282.

Examples
--------

Test whether the lists `a`, `b` and `c` come from populations
with equal variances.

>>> import numpy as np
>>> from scipy import stats
>>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99]
>>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05]
>>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98]
>>> stat, p = stats.bartlett(a, b, c)
>>> p
1.1254782518834628e-05

The very small p-value suggests that the populations do not have equal
variances.

This is not surprising, given that the sample variance of `b` is much
larger than that of `a` and `c`:

>>> [np.var(x, ddof=1) for x in [a, b, c]]
[0.007054444444444413, 0.13073888888888888, 0.008890000000000002]

For a more detailed example, see :ref:`hypothesis_bartlett`.
rc   -Must enter at least two input sample vectors.)r   r   rO  r   r   r   Nr!   )
correctionr   .r   )r   r   r   r  Fr  	symmetricr   r   )r^  rZ  r{   )r   rh   rU   r0   r   r	   r   r   broadcast_tori   newaxisconcatr   r   r+   r(   clipr  r
  r]  )r   r  r   r   r"  Nir   ssqarrr   NtotspsqnumerdenomTr  r  s                    r`   r?   r?   
  s   V 
'	"BGA1uHIIr:GELMW6!&26WGMIP	Qv**V\\"%V\\*
:B	Q=?	@R//!QZ--cr2
3RB	@?F
GwV66&QR60wC
G*,	-"3bjj#o
"B	-+.
/3Crzz33C
/	2A	B
))Ca)
 CHHE66"1E6*D66263,Qe64ADh"&&,&vvrAvrvvc{*%v@AEAq1uI26
%8AtxLHJ JEArzz!A#'Di5RPF
rrvv&A1"!A!;;!+VBZF!V$$5 N	Q	@
G	-
/s#   I0I*I3I$I)3I.LeveneResultmedianr  )centerproportiontocutc                   ^ U S;  a  [        S5      e[        U5      nUS:  a  [        S5      e[        R                  " U5      n[        R                  " US5      nU S:X  a  S nO"U S:X  a  S	 nO[	        U4S
 jU 5       5      nS n[        U5       H  n[        X'   5      XG'   U" X'   5      XW'   M      [        R                  " USS9nS/U-  n	[        U5       H   n
[        [        X*   5      XZ   -
  5      X'   M"     [        R                  " US5      nSn[        U5       H(  n
[        R                  " X   SS9X'   XU
   XJ   -  -  nM*     X-  nX-
  [        R                  " XKU-
  S-  -  SS9-  nSn[        U5       H%  n
U[        R                  " X   X   -
  S-  SS9-  nM'     US-
  U-  nX-  n[        R                  R                  UUS-
  X-
  5      n[        UU5      $ )a
  Perform Levene test for equal variances.

The Levene test tests the null hypothesis that all input samples
are from populations with equal variances.  Levene's test is an
alternative to Bartlett's test `bartlett` in the case where
there are significant deviations from normality.

Parameters
----------
sample1, sample2, ... : array_like
    The sample data, possibly with different lengths. Only one-dimensional
    samples are accepted.
center : {'mean', 'median', 'trimmed'}, optional
    Which function of the data to use in the test.  The default
    is 'median'.
proportiontocut : float, optional
    When `center` is 'trimmed', this gives the proportion of data points
    to cut from each end. (See `scipy.stats.trim_mean`.)
    Default is 0.05.

Returns
-------
statistic : float
    The test statistic.
pvalue : float
    The p-value for the test.

See Also
--------
fligner : A non-parametric test for the equality of k variances
bartlett : A parametric test for equality of k variances in normal samples
:ref:`hypothesis_levene` : Extended example

Notes
-----
Three variations of Levene's test are possible.  The possibilities
and their recommended usages are:

* 'median' : Recommended for skewed (non-normal) distributions>
* 'mean' : Recommended for symmetric, moderate-tailed distributions.
* 'trimmed' : Recommended for heavy-tailed distributions.

The test version using the mean was proposed in the original article
of Levene ([2]_) while the median and trimmed mean have been studied by
Brown and Forsythe ([3]_), sometimes also referred to as Brown-Forsythe
test.

References
----------
.. [1] https://www.itl.nist.gov/div898/handbook/eda/section3/eda35a.htm
.. [2] Levene, H. (1960). In Contributions to Probability and Statistics:
       Essays in Honor of Harold Hotelling, I. Olkin et al. eds.,
       Stanford University Press, pp. 278-292.
.. [3] Brown, M. B. and Forsythe, A. B. (1974), Journal of the American
       Statistical Association, 69, 364-367

Examples
--------

Test whether the lists `a`, `b` and `c` come from populations
with equal variances.

>>> import numpy as np
>>> from scipy import stats
>>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99]
>>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05]
>>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98]
>>> stat, p = stats.levene(a, b, c)
>>> p
0.002431505967249681

The small p-value suggests that the populations do not have equal
variances.

This is not surprising, given that the sample variance of `b` is much
larger than that of `a` and `c`:

>>> [np.var(x, ddof=1) for x in [a, b, c]]
[0.007054444444444413, 0.13073888888888888, 0.008890000000000002]

For a more detailed example, see :ref:`hypothesis_levene`.
rV   rp  trimmed-center must be 'mean', 'median' or 'trimmed'.rc   r_  r'  rp  c                 ,    [         R                  " U SS9$ r   r   rp  r|   s    r`   r   levene.<locals>.func      99QQ''ra   rV   c                 ,    [         R                  " U SS9$ r   r   rV   r|   s    r`   r   ry        7711%%ra   c              3   z   >#    U  H0  n[         R                  " [        R                  " U5      T5      v   M2     g 7frz   )r$   trimbothr   r   .0r"  rr  s     r`   	<genexpr>levene.<locals>.<genexpr>  s0      /&-F "**2776?OLL&-s   8;c                 ,    [         R                  " U SS9$ r   r|  r|   s    r`   r   ry    r}  ra   r   r   Nr   r   r!   )rU   rh   r   r   r   r   r   r  r	   rV   r-   frF  ro  )rq  rr  r  r   rg  Ycir   jrj  Zijr   ZbariZbarrl  dvarrm  WrZ  s    `                r`   r@   r@   g  s   h 22HIIGA1uHII	!B
((1c
C	( 
6		&  /&-/ /	& 1XGJgj!  66"1D &1*C1XWWZ(3612  HHQED1X7736*a25    	LDXdlQ%6 6Q??E D1X)A-A66  WEA??a1df-D4  ra   c           
          [        [        SU[        U 5      4   5      n[        [        U5      S-
  5       Vs/ s H  o2" XU   XS-       5      PM     nn[	        U5      $ s  snf )Nr   r!   )r   r   rh   r   r	   )ro   r&  r   r   outputs        r`   _apply_funcr    sb     	r!QA, A,1#a&1*,=>,=qd1qT!aC&>",=F>6? ?s   A FlignerResultc           	        ^ U S;  a  [        S5      e[        U5      nUS:  a  [        S5      eU H(  nUR                  S:X  d  M  [        U6 n[	        XU5      s  $    U S:X  a  S nO"U S:X  a  S	 nO[        U4S
 jU 5       5      nS n[        [        U5       Vs/ s H  n[        X'   5      PM     sn5      n[        [        U5       Vs/ s H  ov" X'   5      PM     sn5      n	[        R                  " USS9n
[        U5       Vs/ s H  n[        [        X+   5      X   -
  5      PM      nn/ nS/n[        U5       H9  nUR                  [        X   5      5        UR                  [        U5      5        M;     [        R                  " U5      n[         R"                  R%                  USU
S-   -  -  S-   5      n['        XN[        R                  5      U-  n[        R(                  " USS9n[        R*                  " USSS9n[        R                  " U[        U5      U-
  S-  -  SS9U-  n[-        US-
  5      n[/        UUSS[        S9n[	        UU5      $ s  snf s  snf s  snf )a  Perform Fligner-Killeen test for equality of variance.

Fligner's test tests the null hypothesis that all input samples
are from populations with equal variances.  Fligner-Killeen's test is
distribution free when populations are identical [2]_.

Parameters
----------
sample1, sample2, ... : array_like
    Arrays of sample data.  Need not be the same length.
center : {'mean', 'median', 'trimmed'}, optional
    Keyword argument controlling which function of the data is used in
    computing the test statistic.  The default is 'median'.
proportiontocut : float, optional
    When `center` is 'trimmed', this gives the proportion of data points
    to cut from each end. (See `scipy.stats.trim_mean`.)
    Default is 0.05.

Returns
-------
statistic : float
    The test statistic.
pvalue : float
    The p-value for the hypothesis test.

See Also
--------
bartlett : A parametric test for equality of k variances in normal samples
levene : A robust parametric test for equality of k variances
:ref:`hypothesis_fligner` : Extended example

Notes
-----
As with Levene's test there are three variants of Fligner's test that
differ by the measure of central tendency used in the test.  See `levene`
for more information.

Conover et al. (1981) examine many of the existing parametric and
nonparametric tests by extensive simulations and they conclude that the
tests proposed by Fligner and Killeen (1976) and Levene (1960) appear to be
superior in terms of robustness of departures from normality and power
[3]_.

References
----------
.. [1] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and
       Hypothesis Testing based on Quadratic Inference Function. Technical
       Report #99-03, Center for Likelihood Studies, Pennsylvania State
       University.
       https://cecas.clemson.edu/~cspark/cv/paper/qif/draftqif2.pdf
.. [2] Fligner, M.A. and Killeen, T.J. (1976). Distribution-free two-sample
       tests for scale. Journal of the American Statistical Association.
       71(353), 210-213.
.. [3] Park, C. and Lindsay, B. G. (1999). Robust Scale Estimation and
       Hypothesis Testing based on Quadratic Inference Function. Technical
       Report #99-03, Center for Likelihood Studies, Pennsylvania State
       University.
.. [4] Conover, W. J., Johnson, M. E. and Johnson M. M. (1981). A
       comparative study of tests for homogeneity of variances, with
       applications to the outer continental shelf bidding data.
       Technometrics, 23(4), 351-361.

Examples
--------

>>> import numpy as np
>>> from scipy import stats

Test whether the lists `a`, `b` and `c` come from populations
with equal variances.

>>> a = [8.88, 9.12, 9.04, 8.98, 9.00, 9.08, 9.01, 8.85, 9.06, 8.99]
>>> b = [8.88, 8.95, 9.29, 9.44, 9.15, 9.58, 8.36, 9.18, 8.67, 9.05]
>>> c = [8.95, 9.12, 8.95, 8.85, 9.03, 8.84, 9.07, 8.98, 8.86, 8.98]
>>> stat, p = stats.fligner(a, b, c)
>>> p
0.00450826080004775

The small p-value suggests that the populations do not have equal
variances.

This is not surprising, given that the sample variance of `b` is much
larger than that of `a` and `c`:

>>> [np.var(x, ddof=1) for x in [a, b, c]]
[0.007054444444444413, 0.13073888888888888, 0.008890000000000002]

For a more detailed example, see :ref:`hypothesis_fligner`.
rt  rv  rc   r_  r   rp  c                 ,    [         R                  " U SS9$ r   rx  r|   s    r`   r   fligner.<locals>.funcm  rz  ra   rV   c                 ,    [         R                  " U SS9$ r   r|  r|   s    r`   r   r  r  r}  ra   c              3   R   >#    U  H  n[         R                  " UT5      v   M     g 7frz   )r$   r  r  s     r`   r  fligner.<locals>.<genexpr>v  s(      /&-F "**6?CC&-s   $'c                 ,    [         R                  " U SS9$ r   r|  r|   s    r`   r   r  y  r}  ra   r   r   r   r!   )r   r  rf   r  Fra  )rU   rh   r   r   r  r   r	   r   r   r   r  extendr  appendr$   rQ  r-   rj   r   r  rV   ri   r+   r(   )rq  rr  r  r   r"  NaNr   r  rg  r  rj  r   r  allZijr&  ranksAibaranbarvarsqrP   r  rZ  s    `                    r`   rA   rA     s7   v 22HIIGA1uHII ;;!G$C ** 
 	( 
6		&  /&-/ /	& 
5848a#gj/84	5B
U1X6X4
#X6
7C66"1D6;Ah
?h3wwz"SV+,hC
?F	
A1Xd36l#	V  v&E##EQs
^$<s$BCF 266*R/EGGF#EFF6*ErWU^e3c99BUJIqsDy$ISUVDD))+ 56 @s   II%I#c                     U 4$ rz   r{   )x1s    r`   r}   r}     s    bUra   r   )r  r   returnc           	        ^ [         R                  " S/U45      nX7S:g     n[         R                  " [         R                  " [         R                  " US:g  [
        S95      5      SS  n	[        U5      n
[         R                  " SU
S-   [
        S9n[         R                  " [         R                  " X45      5      n[         R                  " U5      n[         R                  " S/U45      n[         R                  " US:g  [
        S9n[         R                  " [         R                  " U5      5      SS  nX-
  n[         R                  " S/U	45      n	[         R                  " S/U45      n[         R                  " U	5      n[         R                  " S/US S 45      nU4S jnUUS-
     S-   nUU   S-   n[        U
5       Vs/ s H   n[         R                  " UU   UU   5      PM"     nnU Vs/ s H  n[         R                  " U" U5      5      PM!     snX   -  n[        UX   -  5      nUTT-  S-
  -  S-  nXT-  TS-   -  TS-  S	-
  -  S
-  XT-  S
T-  TS-
  -  -  [         R                  " XS-  S-
  -  U	S-  S	-
  STU-
  U-
  S-  -  -   -  5      -  -
  nUU-
  [         R                  " U5      -  4$ s  snf s  snf )Nr!   r   r   r   c                     > U TS-   S-  -
  S-  $ )Nr!   rc   r{   )rh  r   s    r`   psi_mood_inner_lc.<locals>.psi  s    QUAI%))ra   r   r   rc   r      r  )r   concatenatebincountr  r	   r   rh   r   r   diffr   r   r   )rS  ro   diffs	sorted_xyrp   rZ   r   
diffs_prepuniquesrl   r   js
sorted_xyxdiff_is_zero
xyx_countsr   r   S_i_m1r  s_lowers_upperidxphi_JI_jphisrn  E_0_TvarMs         `                     r`   _mood_inner_lcr    s    !e-J a(G 	BIIbjjqDEFqrJAGA	1a!e3	'B
 01JGGJE!e-J::jAoS9LRYY|45ab9JA 	Qx A
Qx A
		!A ^^aS!CR&M*F
*
 Qi!mGeaiG>CAhGhsRYYws|WS\2hEG
 )..BFF3s8.6D
 	D15LA QOb EEQWa!,s2ES1WA&'"&&TAX!Q$(bAEFNq3H.H"IJ+ D
 Y"''$-'))) H
 /s   'J6/&J;c                 X    U u  p4UR                   U   nUR                   U   nXe-   nUS:  $ )Nr   )r   )r  kwargsr   ro   r'  rp   rZ   r   s           r`   _mood_too_smallr    s3    DA	A	A	Aq5Lra   )r  r  c                    [         R                  " U [        S9n [         R                  " U[        S9nUS:  a  U R                  U-   n[	        [        [        U R                  5      5       Vs/ s H  oDU:w  d  M
  U R                  U   PM     sn5      nU[	        [        [        UR                  5      5       Vs/ s H  nXB:w  d  M
  UR                  U   PM     sn5      :X  d  [        S5      eU R                  U   nUR                  U   nXv-   nUS:  a  [        S5      e[         R                  " X4US9n	[         R                  " XS9n
[         R                  " XS9nSU;   a"  [         R                  " [        XXXgUUS95      nOUS:w  a  [         R                  " XS5      n	U	R                  U	R                  S   S5      n	[         R                  " U	5      n[        U	R                  S   5       H'  n[         R"                  " U	S	S	2U4   5      US	S	2U4'   M)     US	U n[         R$                  " XS
-   S-  -
  S-  SS9nXhU-  S
-
  -  S-  nXv-  US
-   -  US-   -  US-
  -  S-  nUU-
  ['        U5      -  n[)        U[+        5       U[         S9nUS:X  a  US   nUS   nOX\l        UUl        [-        US   US   5      $ s  snf s  snf )a  Perform Mood's test for equal scale parameters.

Mood's two-sample test for scale parameters is a non-parametric
test for the null hypothesis that two samples are drawn from the
same distribution with the same scale parameter.

Parameters
----------
x, y : array_like
    Arrays of sample data. There must be at least three observations
    total.
axis : int, optional
    The axis along which the samples are tested.  `x` and `y` can be of
    different length along `axis`.
    If `axis` is None, `x` and `y` are flattened and the test is done on
    all values in the flattened arrays.
alternative : {'two-sided', 'less', 'greater'}, optional
    Defines the alternative hypothesis. Default is 'two-sided'.
    The following options are available:

    * 'two-sided': the scales of the distributions underlying `x` and `y`
      are different.
    * 'less': the scale of the distribution underlying `x` is less than
      the scale of the distribution underlying `y`.
    * 'greater': the scale of the distribution underlying `x` is greater
      than the scale of the distribution underlying `y`.

    .. versionadded:: 1.7.0

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

    statistic : scalar or ndarray
        The z-score for the hypothesis test.  For 1-D inputs a scalar is
        returned.
    pvalue : scalar ndarray
        The p-value for the hypothesis test.

See Also
--------
fligner : A non-parametric test for the equality of k variances
ansari : A non-parametric test for the equality of 2 variances
bartlett : A parametric test for equality of k variances in normal samples
levene : A parametric test for equality of k variances

Notes
-----
The data are assumed to be drawn from probability distributions ``f(x)``
and ``f(x/s) / s`` respectively, for some probability density function f.
The null hypothesis is that ``s == 1``.

For multi-dimensional arrays, if the inputs are of shapes
``(n0, n1, n2, n3)``  and ``(n0, m1, n2, n3)``, then if ``axis=1``, the
resulting z and p values will have shape ``(n0, n2, n3)``.  Note that
``n1`` and ``m1`` don't have to be equal, but the other dimensions do.

References
----------
[1] Mielke, Paul W. "Note on Some Squared Rank Tests with Existing Ties."
    Technometrics, vol. 9, no. 2, 1967, pp. 312-14. JSTOR,
    https://doi.org/10.2307/1266427. Accessed 18 May 2022.

Examples
--------
>>> import numpy as np
>>> from scipy import stats
>>> rng = np.random.default_rng()
>>> x2 = rng.standard_normal((2, 45, 6, 7))
>>> x1 = rng.standard_normal((2, 30, 6, 7))
>>> res = stats.mood(x1, x2, axis=1)
>>> res.pvalue.shape
(2, 6, 7)

Find the number of points where the difference in scale is not significant:

>>> (res.pvalue > 0.1).sum()
78

Perform the test with different scales:

>>> x1 = rng.standard_normal((2, 30))
>>> x2 = rng.standard_normal((2, 35)) * 10.0
>>> stats.mood(x1, x2, axis=1)
SignificanceResult(statistic=array([-5.76174136, -6.12650783]),
                   pvalue=array([8.32505043e-09, 8.98287869e-10]))

r   r   z<Dimensions of x and y on all axes except `axis` should matchr   zNot enough observations.r   r   r!   Nr   rc   r   r  rO  r{   )r   r	   rO  r
  r   r   rh   r   rU   r  r   r  r  moveaxisr   r   r$   rQ  r   r   r(   r*   r)   )ro   r'  r   r  ax	res_shaperp   rZ   r   rS  r  r  rp  	all_ranksr  RiMmnMr  rZ  s                       r`   rB   rB     s   v 	

1E"A


1E"Aaxvv} U3qww<-@O-@r$J{qwwr{-@OPIeCL6I  ,6I "
 !,6I  , - - ( ) 	) 	
A	A	A1u344	T	*B&IGGI)EEzJJ~bUqQ+/1 2 19Rq)BZZR( MM"%	rxx{#A'00AqD:IadO $ r]FFBc'Q&1,15q53;"$uC AE*a!e4s:WT
"q-/;2>DBaDAw
aeT"X..] P ,s   -	K:K:	K
K
WilcoxonResultrP   r  c                     [        U S5      (       a#  U R                  U R                  U R                  4$ U R                  U R                  4$ )N
zstatistic)r   rP   r  r  )r   s    r`   wilcoxon_result_unpackerr  |  s;    sL!!}}cjj#..88}}cjj((ra   c                 .    [        X5      nUb  X#l        U$ rz   )r  r  )rP   r  r  r   s       r`   wilcoxon_result_objectr    s    

+C#Jra   c                 6    U R                  SS5      nUS:X  a  gg)Nr#  auto
asymptoticr   rc   get)kwdsr#  s     r`   wilcoxon_outputsr    s     XXh'Fra   moder#  c                 0    U R                  SS 5      b  S$ S$ )Nr'  rc   r!   r  )r  s    r`   r}   r}     s    d 3 ?1FQFra   )pairedr  r   r   c          	      D    US:X  a  Sn[         R                  " XX#UXV5      $ )a&  Calculate the Wilcoxon signed-rank test.

The Wilcoxon signed-rank test tests the null hypothesis that two
related paired samples come from the same distribution. In particular,
it tests whether the distribution of the differences ``x - y`` is symmetric
about zero. It is a non-parametric version of the paired T-test.

Parameters
----------
x : array_like
    Either the first set of measurements (in which case ``y`` is the second
    set of measurements), or the differences between two sets of
    measurements (in which case ``y`` is not to be specified.)  Must be
    one-dimensional.
y : array_like, optional
    Either the second set of measurements (if ``x`` is the first set of
    measurements), or not specified (if ``x`` is the differences between
    two sets of measurements.)  Must be one-dimensional.

    .. warning::
        When `y` is provided, `wilcoxon` calculates the test statistic
        based on the ranks of the absolute values of ``d = x - y``.
        Roundoff error in the subtraction can result in elements of ``d``
        being assigned different ranks even when they would be tied with
        exact arithmetic. Rather than passing `x` and `y` separately,
        consider computing the difference ``x - y``, rounding as needed to
        ensure that only truly unique elements are numerically distinct,
        and passing the result as `x`, leaving `y` at the default (None).

zero_method : {"wilcox", "pratt", "zsplit"}, optional
    There are different conventions for handling pairs of observations
    with equal values ("zero-differences", or "zeros").

    * "wilcox": Discards all zero-differences (default); see [4]_.
    * "pratt": Includes zero-differences in the ranking process,
      but drops the ranks of the zeros (more conservative); see [3]_.
      In this case, the normal approximation is adjusted as in [5]_.
    * "zsplit": Includes zero-differences in the ranking process and
      splits the zero rank between positive and negative ones.

correction : bool, optional
    If True, apply continuity correction by adjusting the Wilcoxon rank
    statistic by 0.5 towards the mean value when computing the
    z-statistic if a normal approximation is used.  Default is False.
alternative : {"two-sided", "greater", "less"}, optional
    Defines the alternative hypothesis. Default is 'two-sided'.
    In the following, let ``d`` represent the difference between the paired
    samples: ``d = x - y`` if both ``x`` and ``y`` are provided, or
    ``d = x`` otherwise.

    * 'two-sided': the distribution underlying ``d`` is not symmetric
      about zero.
    * 'less': the distribution underlying ``d`` is stochastically less
      than a distribution symmetric about zero.
    * 'greater': the distribution underlying ``d`` is stochastically
      greater than a distribution symmetric about zero.

method : {"auto", "exact", "asymptotic"} or `PermutationMethod` instance, optional
    Method to calculate the p-value, see Notes. Default is "auto".

axis : int or None, default: 0
    If an int, the axis of the input along which to compute the statistic.
    The statistic of each axis-slice (e.g. row) of the input will appear
    in a corresponding element of the output. If ``None``, the input will
    be raveled before computing the statistic.

Returns
-------
An object with the following attributes.

statistic : array_like
    If `alternative` is "two-sided", the sum of the ranks of the
    differences above or below zero, whichever is smaller.
    Otherwise the sum of the ranks of the differences above zero.
pvalue : array_like
    The p-value for the test depending on `alternative` and `method`.
zstatistic : array_like
    When ``method = 'asymptotic'``, this is the normalized z-statistic::

        z = (T - mn - d) / se

    where ``T`` is `statistic` as defined above, ``mn`` is the mean of the
    distribution under the null hypothesis, ``d`` is a continuity
    correction, and ``se`` is the standard error.
    When ``method != 'asymptotic'``, this attribute is not available.

See Also
--------
kruskal, mannwhitneyu

Notes
-----
In the following, let ``d`` represent the difference between the paired
samples: ``d = x - y`` if both ``x`` and ``y`` are provided, or ``d = x``
otherwise. Assume that all elements of ``d`` are independent and
identically distributed observations, and all are distinct and nonzero.

- When ``len(d)`` is sufficiently large, the null distribution of the
  normalized test statistic (`zstatistic` above) is approximately normal,
  and ``method = 'asymptotic'`` can be used to compute the p-value.

- When ``len(d)`` is small, the normal approximation may not be accurate,
  and ``method='exact'`` is preferred (at the cost of additional
  execution time).

- The default, ``method='auto'``, selects between the two:
  ``method='exact'`` is used when ``len(d) <= 50``, and
  ``method='asymptotic'`` is used otherwise.

The presence of "ties" (i.e. not all elements of ``d`` are unique) or
"zeros" (i.e. elements of ``d`` are zero) changes the null distribution
of the test statistic, and ``method='exact'`` no longer calculates
the exact p-value. If ``method='asymptotic'``, the z-statistic is adjusted
for more accurate comparison against the standard normal, but still,
for finite sample sizes, the standard normal is only an approximation of
the true null distribution of the z-statistic. For such situations, the
`method` parameter also accepts instances of `PermutationMethod`. In this
case, the p-value is computed using `permutation_test` with the provided
configuration options and other appropriate settings.

The presence of ties and zeros affects the resolution of ``method='auto'``
accordingly: exhasutive permutations are performed when ``len(d) <= 13``,
and the asymptotic method is used otherwise. Note that they asymptotic
method may not be very accurate even for ``len(d) > 14``; the threshold
was chosen as a compromise between execution time and accuracy under the
constraint that the results must be deterministic. Consider providing an
instance of `PermutationMethod` method manually, choosing the
``n_resamples`` parameter to balance time constraints and accuracy
requirements.

Please also note that in the edge case that all elements of ``d`` are zero,
the p-value relying on the normal approximaton cannot be computed (NaN)
if ``zero_method='wilcox'`` or ``zero_method='pratt'``.

References
----------
.. [1] https://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test
.. [2] Conover, W.J., Practical Nonparametric Statistics, 1971.
.. [3] Pratt, J.W., Remarks on Zeros and Ties in the Wilcoxon Signed
   Rank Procedures, Journal of the American Statistical Association,
   Vol. 54, 1959, pp. 655-667. :doi:`10.1080/01621459.1959.10501526`
.. [4] Wilcoxon, F., Individual Comparisons by Ranking Methods,
   Biometrics Bulletin, Vol. 1, 1945, pp. 80-83. :doi:`10.2307/3001968`
.. [5] Cureton, E.E., The Normal Approximation to the Signed-Rank
   Sampling Distribution When Zero Differences are Present,
   Journal of the American Statistical Association, Vol. 62, 1967,
   pp. 1068-1069. :doi:`10.1080/01621459.1967.10500917`

Examples
--------
In [4]_, the differences in height between cross- and self-fertilized
corn plants is given as follows:

>>> d = [6, 8, 14, 16, 23, 24, 28, 29, 41, -48, 49, 56, 60, -67, 75]

Cross-fertilized plants appear to be higher. To test the null
hypothesis that there is no height difference, we can apply the
two-sided test:

>>> from scipy.stats import wilcoxon
>>> res = wilcoxon(d)
>>> res.statistic, res.pvalue
(24.0, 0.041259765625)

Hence, we would reject the null hypothesis at a confidence level of 5%,
concluding that there is a difference in height between the groups.
To confirm that the median of the differences can be assumed to be
positive, we use:

>>> res = wilcoxon(d, alternative='greater')
>>> res.statistic, res.pvalue
(96.0, 0.0206298828125)

This shows that the null hypothesis that the median is negative can be
rejected at a confidence level of 5% in favor of the alternative that
the median is greater than zero. The p-values above are exact. Using the
normal approximation gives very similar values:

>>> res = wilcoxon(d, method='asymptotic')
>>> res.statistic, res.pvalue
(24.0, 0.04088813291185591)

Note that the statistic changed to 96 in the one-sided case (the sum
of ranks of positive differences) whereas it is 24 in the two-sided
case (the minimum of sum of ranks above and below zero).

In the example above, the differences in height between paired plants are
provided to `wilcoxon` directly. Alternatively, `wilcoxon` accepts two
samples of equal length, calculates the differences between paired
elements, then performs the test. Consider the samples ``x`` and ``y``:

>>> import numpy as np
>>> x = np.array([0.5, 0.825, 0.375, 0.5])
>>> y = np.array([0.525, 0.775, 0.325, 0.55])
>>> res = wilcoxon(x, y, alternative='greater')
>>> res
WilcoxonResult(statistic=5.0, pvalue=0.5625)

Note that had we calculated the differences by hand, the test would have
produced different results:

>>> d = [-0.025, 0.05, 0.05, -0.05]
>>> ref = wilcoxon(d, alternative='greater')
>>> ref
WilcoxonResult(statistic=6.0, pvalue=0.5)

The substantial difference is due to roundoff error in the results of
``x-y``:

>>> d - (x-y)
array([2.08166817e-17, 6.93889390e-17, 1.38777878e-17, 4.16333634e-17])

Even though we expected all the elements of ``(x-y)[1:]`` to have the same
magnitude ``0.05``, they have slightly different magnitudes in practice,
and therefore are assigned different ranks in the test. Before performing
the test, consider calculating ``d`` and adjusting it as necessary to
ensure that theoretically identically values are not numerically distinct.
For example:

>>> d2 = np.around(x - y, decimals=3)
>>> wilcoxon(d2, alternative='greater')
WilcoxonResult(statistic=6.0, pvalue=0.5)

approxr  )r%   _wilcoxon_nd)ro   r'  zero_methodr`  r  r#  r   s          r`   rC   rC     s.    R !!!"(0 0ra   MedianTestResult)rP   r  rp  tablebelow	propagate)tiesr`  lambda_
nan_policyc                    [        U5      S:  a  [        S5      e/ SQnX;  a  [        SU  S[        U5      SS  35      eU Vs/ s H  n[        R                  " U5      PM     nn[        U5       HS  u  pU	R                  S:X  a  [        S	US-   -  5      eU	R                  S:w  d  M8  [        S
US-   U	R                  4-  5      e   [        R                  " U5      n
[        X5      u  pU(       a>  US:X  a8  [        [        R                  [        R                  [        R                  S5      $ U(       a/  [        R                  " U
[        R                  " U
5      )    5      nO[        R                  " U
5      n[        R                  " S[        U5      4[        R                  S9n[        U5       H  u  pU[        R                  " U5      )    n[!        Xl:  5      n[!        Xl:  5      nUR                  X-   -
  nUSU4==   U-  ss'   USU4==   U-  ss'   U S:X  a  USU4==   U-  ss'   M  U S:X  d  M  USU4==   U-  ss'   M     UR#                  SS9nUS   S:X  a  [        SU S35      eUS   S:X  a  [        SU S35      eU S:X  aP  [        R$                  " US:H  R'                  SS95      S   n[        U5      S:  a  SUS   S-   U4-  n[        U5      e[)        XUS9u  nnnn[        UUX5      $ s  snf )aJ  Perform a Mood's median test.

Test that two or more samples come from populations with the same median.

Let ``n = len(samples)`` be the number of samples.  The "grand median" of
all the data is computed, and a contingency table is formed by
classifying the values in each sample as being above or below the grand
median.  The contingency table, along with `correction` and `lambda_`,
are passed to `scipy.stats.chi2_contingency` to compute the test statistic
and p-value.

Parameters
----------
sample1, sample2, ... : array_like
    The set of samples.  There must be at least two samples.
    Each sample must be a one-dimensional sequence containing at least
    one value.  The samples are not required to have the same length.
ties : str, optional
    Determines how values equal to the grand median are classified in
    the contingency table.  The string must be one of::

        "below":
            Values equal to the grand median are counted as "below".
        "above":
            Values equal to the grand median are counted as "above".
        "ignore":
            Values equal to the grand median are not counted.

    The default is "below".
correction : bool, optional
    If True, *and* there are just two samples, apply Yates' correction
    for continuity when computing the test statistic associated with
    the contingency table.  Default is True.
lambda_ : float or str, optional
    By default, the statistic computed in this test is Pearson's
    chi-squared statistic.  `lambda_` allows a statistic from the
    Cressie-Read power divergence family to be used instead.  See
    `power_divergence` for details.
    Default is 1 (Pearson's chi-squared statistic).
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'.

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

    statistic : float
        The test statistic.  The statistic that is returned is determined
        by `lambda_`.  The default is Pearson's chi-squared statistic.
    pvalue : float
        The p-value of the test.
    median : float
        The grand median.
    table : ndarray
        The contingency table.  The shape of the table is (2, n), where
        n is the number of samples.  The first row holds the counts of the
        values above the grand median, and the second row holds the counts
        of the values below the grand median.  The table allows further
        analysis with, for example, `scipy.stats.chi2_contingency`, or with
        `scipy.stats.fisher_exact` if there are two samples, without having
        to recompute the table.  If ``nan_policy`` is "propagate" and there
        are nans in the input, the return value for ``table`` is ``None``.

See Also
--------
kruskal : Compute the Kruskal-Wallis H-test for independent samples.
mannwhitneyu : Computes the Mann-Whitney rank test on samples x and y.

Notes
-----
.. versionadded:: 0.15.0

References
----------
.. [1] Mood, A. M., Introduction to the Theory of Statistics. McGraw-Hill
    (1950), pp. 394-399.
.. [2] Zar, J. H., Biostatistical Analysis, 5th ed. Prentice Hall (2010).
    See Sections 8.12 and 10.15.

Examples
--------
A biologist runs an experiment in which there are three groups of plants.
Group 1 has 16 plants, group 2 has 15 plants, and group 3 has 17 plants.
Each plant produces a number of seeds.  The seed counts for each group
are::

    Group 1: 10 14 14 18 20 22 24 25 31 31 32 39 43 43 48 49
    Group 2: 28 30 31 33 34 35 36 40 44 55 57 61 91 92 99
    Group 3:  0  3  9 22 23 25 25 33 34 34 40 45 46 48 62 67 84

The following code applies Mood's median test to these samples.

>>> g1 = [10, 14, 14, 18, 20, 22, 24, 25, 31, 31, 32, 39, 43, 43, 48, 49]
>>> g2 = [28, 30, 31, 33, 34, 35, 36, 40, 44, 55, 57, 61, 91, 92, 99]
>>> g3 = [0, 3, 9, 22, 23, 25, 25, 33, 34, 34, 40, 45, 46, 48, 62, 67, 84]
>>> from scipy.stats import median_test
>>> res = median_test(g1, g2, g3)

The median is

>>> res.median
34.0

and the contingency table is

>>> res.table
array([[ 5, 10,  7],
       [11,  5, 10]])

`p` is too large to conclude that the medians are not the same:

>>> res.pvalue
0.12609082774093244

The "G-test" can be performed by passing ``lambda_="log-likelihood"`` to
`median_test`.

>>> res = median_test(g1, g2, g3, lambda_="log-likelihood")
>>> res.pvalue
0.12224779737117837

The median occurs several times in the data, so we'll get a different
result if, for example, ``ties="above"`` is used:

>>> res = median_test(g1, g2, g3, ties="above")
>>> res.pvalue
0.063873276069553273

>>> res.table
array([[ 5, 11,  9],
       [11,  4,  8]])

This example demonstrates that if the data set is not large and there
are values equal to the median, the p-value can be sensitive to the
choice of `ties`.

rc   z)median_test requires two or more samples.)r  abover  zinvalid 'ties' option 'z'; 'ties' must be one of: r!   r   r   z@Sample %d is empty. All samples must contain at least one value.zLSample %d has %d dimensions.  All samples must be one-dimensional sequences.r  Nr   r  r  r   z'All values are below the grand median (z).z'All values are above the grand median (r  znAll values in sample %d are equal to the grand median (%r), so they are ignored, resulting in an empty sample.)r  r`  )rh   rU   r   r   r	   r   r   r
  r  r   r  r   rp  isnanr
   int64r   r   nonzeror%  r,   )r  r`  r  r  r  ties_optionsr"  rX   r   r'  cdatacontains_nangrand_medianr  nabovenbelownequalrowsums	zero_colsr   statr,  dofexpecteds                           r`   rD   rD     s   \ 7|aDEE/L24& 9  #L 1!B 78: ; 	; .55W6BJJvWD5 $66Q; ;>?!eE F F66Q; J!eQVV_- . .   NN4 E,U?L
k1==yy'7!89yy' HHaT^2884Et_	&))*v45v450advadv7?!Q$K6!KW_!Q$K6!K %  iiQiGqzQB<.PRSTTqzQB<.PRSTTx
 JJ
//Q/78;	y>A#&/lQ&6%EFC S/!-e9CED!S(D!\99} 6s    Lc                 "   Uc  [        U 5      OUnUR                  U R                  S5      (       a*  UR                  S5      R                  nUR                  XS9n U S[        -  U-  -  nUR                  U5      nUR                  U5      nXU4$ )Nr  r   r   rf   )r   r  r   r	   r   sincos)r  periodr   r   scaled_samplessin_sampcos_samps          r`   _circfuncs_commonr  ]  s    %'Z	!RB	zz'--,,

2$$**W*2 rV 34Nvvn%Hvvn%Hh&&ra   c                     U $ rz   r{   r|   s    r`   r}   r}   n  r~   ra   c                     U 4$ rz   r{   r|   s    r`   r}   r}   o      qdra   )r   r   r   c                 0   [        U 5      n[        U 5      S:X  a  UR                  XS9$ X-
  n[        XUS9u  pnUR	                  XsS9n	UR	                  XS9n
UR                  X5      nUR                  S:X  a  US   OUnXS[        -  -  -  U-
  U-  U-   $ )a  Compute the circular mean of a sample of angle observations.

Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in
radians, their *circular mean* is defined by ([1]_, Eq. 2.2.4)

.. math::

   \mathrm{Arg} \left( \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right)

where :math:`i` is the imaginary unit and :math:`\mathop{\mathrm{Arg}} z`
gives the principal value of the argument of complex number :math:`z`,
restricted to the range :math:`[0,2\pi]` by default.  :math:`z` in the
above expression is known as the `mean resultant vector`.

Parameters
----------
samples : array_like
    Input array of angle observations.  The value of a full angle is
    equal to ``(high - low)``.
high : float, optional
    Upper boundary of the principal value of an angle.  Default is ``2*pi``.
low : float, optional
    Lower boundary of the principal value of an angle.  Default is ``0``.

Returns
-------
circmean : float
    Circular mean, restricted to the range ``[low, high]``.

    If the mean resultant vector is zero, an input-dependent,
    implementation-defined number between ``[low, high]`` is returned.
    If the input array is empty, ``np.nan`` is returned.

See Also
--------
circstd : Circular standard deviation.
circvar : Circular variance.

References
----------
.. [1] Mardia, K. V. and Jupp, P. E. *Directional Statistics*.
       John Wiley & Sons, 1999.

Examples
--------
For readability, all angles are printed out in degrees.

>>> import numpy as np
>>> from scipy.stats import circmean
>>> import matplotlib.pyplot as plt
>>> angles = np.deg2rad(np.array([20, 30, 330]))
>>> circmean = circmean(angles)
>>> np.rad2deg(circmean)
7.294976657784009

>>> mean = angles.mean()
>>> np.rad2deg(mean)
126.66666666666666

Plot and compare the circular mean against the arithmetic mean.

>>> plt.plot(np.cos(np.linspace(0, 2*np.pi, 500)),
...          np.sin(np.linspace(0, 2*np.pi, 500)),
...          c='k')
>>> plt.scatter(np.cos(angles), np.sin(angles), c='k')
>>> plt.scatter(np.cos(circmean), np.sin(circmean), c='b',
...             label='circmean')
>>> plt.scatter(np.cos(mean), np.sin(mean), c='r', label='mean')
>>> plt.legend()
>>> plt.axis('equal')
>>> plt.show()

r   r   rO  r{   rf   )r   r   rV   r  r   atan2r
  r   )r  highlowr   r  r   r  r  r  sin_sumcos_sumr   s               r`   rE   rE   m  s    \ 
	!B w1wwww**ZF"3G"KGxffXf)GffXf)G
((7
$CXX]#b'CS2X&'#-7#==ra   c                     U $ rz   r{   r|   s    r`   r}   r}     r~   ra   c                     U 4$ rz   r{   r|   s    r`   r}   r}     r  ra   c                     [        U 5      nX-
  n[        XUS9u  pnUR                  XsS9n	UR                  XS9n
U	S-  U
S-  -   S-  nUR                  USS9nSU-
  nU$ )a	  Compute the circular variance of a sample of angle observations.

Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in
radians, their *circular variance* is defined by ([2]_, Eq. 2.3.3)

.. math::

   1 - \left| \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right|

where :math:`i` is the imaginary unit and :math:`|z|` gives the length
of the complex number :math:`z`.  :math:`|z|` in the above expression
is known as the `mean resultant length`.

Parameters
----------
samples : array_like
    Input array of angle observations.  The value of a full angle is
    equal to ``(high - low)``.
high : float, optional
    Upper boundary of the principal value of an angle.  Default is ``2*pi``.
low : float, optional
    Lower boundary of the principal value of an angle.  Default is ``0``.

Returns
-------
circvar : float
    Circular variance.  The returned value is in the range ``[0, 1]``,
    where ``0`` indicates no variance and ``1`` indicates large variance.

    If the input array is empty, ``np.nan`` is returned.

See Also
--------
circmean : Circular mean.
circstd : Circular standard deviation.

Notes
-----
In the limit of small angles, the circular variance is close to
half the 'linear' variance if measured in radians.

References
----------
.. [1] Fisher, N.I. *Statistical analysis of circular data*. Cambridge
       University Press, 1993.
.. [2] Mardia, K. V. and Jupp, P. E. *Directional Statistics*.
       John Wiley & Sons, 1999.

Examples
--------
>>> import numpy as np
>>> from scipy.stats import circvar
>>> import matplotlib.pyplot as plt
>>> samples_1 = np.array([0.072, -0.158, 0.077, 0.108, 0.286,
...                       0.133, -0.473, -0.001, -0.348, 0.131])
>>> samples_2 = np.array([0.111, -0.879, 0.078, 0.733, 0.421,
...                       0.104, -0.136, -0.867,  0.012,  0.105])
>>> circvar_1 = circvar(samples_1)
>>> circvar_2 = circvar(samples_2)

Plot the samples.

>>> fig, (left, right) = plt.subplots(ncols=2)
>>> for image in (left, right):
...     image.plot(np.cos(np.linspace(0, 2*np.pi, 500)),
...                np.sin(np.linspace(0, 2*np.pi, 500)),
...                c='k')
...     image.axis('equal')
...     image.axis('off')
>>> left.scatter(np.cos(samples_1), np.sin(samples_1), c='k', s=15)
>>> left.set_title(f"circular variance: {np.round(circvar_1, 2)!r}")
>>> right.scatter(np.cos(samples_2), np.sin(samples_2), c='k', s=15)
>>> right.set_title(f"circular variance: {np.round(circvar_2, 2)!r}")
>>> plt.show()

rO  r   rf   r   r   rZ  )r   r  rV   rf  )r  r  r  r   r  r   r  r  r  sin_meancos_mean
hypotenuseRr   s                 r`   rF   rF     s~    b 
	!BZF"3G"KGxwwxw+Hwwxw+HB,2-3J

#A
q&CJra   c                     U $ rz   r{   r|   s    r`   r}   r}   )  r~   ra   c                     U 4$ rz   r{   r|   s    r`   r}   r}   *  r  ra   )	normalizec                   [        U 5      nX-
  n[        XUS9u  pn	UR                  XS9n
UR                  XS9nU
S-  US-  -   S-  nUR                  USS9nSUR	                  U5      -  S-  S-   nU(       d  XU-
  S[
        -  -  -  nU$ )	aH  
Compute the circular standard deviation of a sample of angle observations.

Given :math:`n` angle observations :math:`x_1, \cdots, x_n` measured in
radians, their `circular standard deviation` is defined by
([2]_, Eq. 2.3.11)

.. math::

   \sqrt{ -2 \log \left| \frac{1}{n} \sum_{k=1}^n e^{i x_k} \right| }

where :math:`i` is the imaginary unit and :math:`|z|` gives the length
of the complex number :math:`z`.  :math:`|z|` in the above expression
is known as the `mean resultant length`.

Parameters
----------
samples : array_like
    Input array of angle observations.  The value of a full angle is
    equal to ``(high - low)``.
high : float, optional
    Upper boundary of the principal value of an angle.  Default is ``2*pi``.
low : float, optional
    Lower boundary of the principal value of an angle.  Default is ``0``.
normalize : boolean, optional
    If ``False`` (the default), the return value is computed from the
    above formula with the input scaled by ``(2*pi)/(high-low)`` and
    the output scaled (back) by ``(high-low)/(2*pi)``.  If ``True``,
    the output is not scaled and is returned directly.

Returns
-------
circstd : float
    Circular standard deviation, optionally normalized.

    If the input array is empty, ``np.nan`` is returned.

See Also
--------
circmean : Circular mean.
circvar : Circular variance.

Notes
-----
In the limit of small angles, the circular standard deviation is close
to the 'linear' standard deviation if ``normalize`` is ``False``.

References
----------
.. [1] Mardia, K. V. (1972). 2. In *Statistics of Directional Data*
   (pp. 18-24). Academic Press. :doi:`10.1016/C2013-0-07425-7`.
.. [2] Mardia, K. V. and Jupp, P. E. *Directional Statistics*.
       John Wiley & Sons, 1999.

Examples
--------
>>> import numpy as np
>>> from scipy.stats import circstd
>>> import matplotlib.pyplot as plt
>>> samples_1 = np.array([0.072, -0.158, 0.077, 0.108, 0.286,
...                       0.133, -0.473, -0.001, -0.348, 0.131])
>>> samples_2 = np.array([0.111, -0.879, 0.078, 0.733, 0.421,
...                       0.104, -0.136, -0.867,  0.012,  0.105])
>>> circstd_1 = circstd(samples_1)
>>> circstd_2 = circstd(samples_2)

Plot the samples.

>>> fig, (left, right) = plt.subplots(ncols=2)
>>> for image in (left, right):
...     image.plot(np.cos(np.linspace(0, 2*np.pi, 500)),
...                np.sin(np.linspace(0, 2*np.pi, 500)),
...                c='k')
...     image.axis('equal')
...     image.axis('off')
>>> left.scatter(np.cos(samples_1), np.sin(samples_1), c='k', s=15)
>>> left.set_title(f"circular std: {np.round(circstd_1, 2)!r}")
>>> right.plot(np.cos(np.linspace(0, 2*np.pi, 500)),
...            np.sin(np.linspace(0, 2*np.pi, 500)),
...            c='k')
>>> right.scatter(np.cos(samples_2), np.sin(samples_2), c='k', s=15)
>>> right.set_title(f"circular std: {np.round(circstd_2, 2)!r}")
>>> plt.show()

rO  r   rf   r   r   r  rg   r   )r   r  rV   rf  r   r   )r  r  r  r   r  r  r   r  r  r  r	  r
  r  r  r   s                  r`   rG   rG   (  s    v 
	!BZF"3G"KGxwwxw+Hwwxw+HB,2-3J

#AbffQi<#
c
!CS2b5!!Jra   c                        \ rS rSrS rS rSrg)DirectionalStatsi  c                     Xl         X l        g rz   mean_directionmean_resultant_length)r0  r  r  s      r`   r5  DirectionalStats.__init__  s    ,%:"ra   c                 <    SU R                    SU R                   S3$ )Nz DirectionalStats(mean_direction=z, mean_resultant_length=)r  r/  s    r`   r1  DirectionalStats.__repr__  s0    243F3F2G H**.*D*D)EQH 	Ira   r  N)r3  r4  r5  r6  r5  r1  r7  r{   ra   r`   r  r    s    ;Ira   r  )r   r  c                   [        U 5      nUR                  U 5      n U R                  S:  a!  [        S[	        U R
                  5       35      eUR                  XS5      n U(       a  [        U SSUS9nX-  n UR                  U SS9n[        USSUS9nXV-  nUR                  USS9nUR                  S:X  a  US   OUn[        Xv5      $ )	a  
Computes sample statistics for directional data.

Computes the directional mean (also called the mean direction vector) and
mean resultant length of a sample of vectors.

The directional mean is a measure of "preferred direction" of vector data.
It is analogous to the sample mean, but it is for use when the length of
the data is irrelevant (e.g. unit vectors).

The mean resultant length is a value between 0 and 1 used to quantify the
dispersion of directional data: the smaller the mean resultant length, the
greater the dispersion. Several definitions of directional variance
involving the mean resultant length are given in [1]_ and [2]_.

Parameters
----------
samples : array_like
    Input array. Must be at least two-dimensional, and the last axis of the
    input must correspond with the dimensionality of the vector space.
    When the input is exactly two dimensional, this means that each row
    of the data is a vector observation.
axis : int, default: 0
    Axis along which the directional mean is computed.
normalize: boolean, default: True
    If True, normalize the input to ensure that each observation is a
    unit vector. It the observations are already unit vectors, consider
    setting this to False to avoid unnecessary computation.

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

    mean_direction : ndarray
        Directional mean.
    mean_resultant_length : ndarray
        The mean resultant length [1]_.

See Also
--------
circmean: circular mean; i.e. directional mean for 2D *angles*
circvar: circular variance; i.e. directional variance for 2D *angles*

Notes
-----
This uses a definition of directional mean from [1]_.
Assuming the observations are unit vectors, the calculation is as follows.

.. code-block:: python

    mean = samples.mean(axis=0)
    mean_resultant_length = np.linalg.norm(mean)
    mean_direction = mean / mean_resultant_length

This definition is appropriate for *directional* data (i.e. vector data
for which the magnitude of each observation is irrelevant) but not
for *axial* data (i.e. vector data for which the magnitude and *sign* of
each observation is irrelevant).

Several definitions of directional variance involving the mean resultant
length ``R`` have been proposed, including ``1 - R`` [1]_, ``1 - R**2``
[2]_, and ``2 * (1 - R)`` [2]_. Rather than choosing one, this function
returns ``R`` as attribute `mean_resultant_length` so the user can compute
their preferred measure of dispersion.

References
----------
.. [1] Mardia, Jupp. (2000). *Directional Statistics*
   (p. 163). Wiley.

.. [2] https://en.wikipedia.org/wiki/Directional_statistics

Examples
--------
>>> import numpy as np
>>> from scipy.stats import directional_stats
>>> data = np.array([[3, 4],    # first observation, 2D vector space
...                  [6, -8]])  # second observation
>>> dirstats = directional_stats(data)
>>> dirstats.mean_direction
array([1., 0.])

In contrast, the regular sample mean of the vectors would be influenced
by the magnitude of each observation. Furthermore, the result would not be
a unit vector.

>>> data.mean(axis=0)
array([4.5, -2.])

An exemplary use case for `directional_stats` is to find a *meaningful*
center for a set of observations on a sphere, e.g. geographical locations.

>>> data = np.array([[0.8660254, 0.5, 0.],
...                  [0.8660254, -0.5, 0.]])
>>> dirstats = directional_stats(data)
>>> dirstats.mean_direction
array([1., 0., 0.])

The regular sample mean on the other hand yields a result which does not
lie on the surface of the sphere.

>>> data.mean(axis=0)
array([0.8660254, 0., 0.])

The function also returns the mean resultant length, which
can be used to calculate a directional variance. For example, using the
definition ``Var(z) = 1 - R`` from [2]_ where ``R`` is the
mean resultant length, we can calculate the directional variance of the
vectors in the above example as:

>>> 1 - dirstats.mean_resultant_length
0.13397459716167093
rc   zEsamples must at least be two-dimensional. Instead samples has shape: r   r   T)r   keepdimsr   r   r{   )r   r	   r
  rU   r   r   r  r    rV   squeezer  )	r  r   r  r   vectornormsrV   r  r  mrls	            r`   rM   rM     s    f 
	!Bjj!G||a 77<W]]7K6LN O 	Okk'+G$W2L%7777#D*4b4BO1N
****
4C'*xx1}CG#NBBra   bh)r   r#  c                   [         R                  " U 5      n [         R                  " U R                  [         R                  5      =(       a/    [         R
                  " U [         R                  " U SS5      :H  5      nU(       d  [        S5      eSS1nUR                  5       U;  a  [        SU SU S35      eUR                  5       nUc  SnU R                  5       n [         R                  " U5      S
   n[         R                  " UR                  [         R                  5      (       a  UR                  S:w  a  [        S5      eU R                  S::  d  U R                  U   S::  a  U S
   $ [         R                  " XS5      n U R                  S   n[         R                  " U SS9n[         R                  " XSS9n [         R                   " SUS-   5      nXU-  -  n US:X  a  U [         R"                  " SU-  5      -  n [         R$                  R'                  U SS	S	S24   U SS	S	S24   SS9  [         R(                  " XU R+                  5       SS9  [         R                  " U SU5      n [         R                  " U SS5      $ )a;  Adjust p-values to control the false discovery rate.

The false discovery rate (FDR) is the expected proportion of rejected null
hypotheses that are actually true.
If the null hypothesis is rejected when the *adjusted* p-value falls below
a specified level, the false discovery rate is controlled at that level.

Parameters
----------
ps : 1D array_like
    The p-values to adjust. Elements must be real numbers between 0 and 1.
axis : int
    The axis along which to perform the adjustment. The adjustment is
    performed independently along each axis-slice. If `axis` is None, `ps`
    is raveled before performing the adjustment.
method : {'bh', 'by'}
    The false discovery rate control procedure to apply: ``'bh'`` is for
    Benjamini-Hochberg [1]_ (Eq. 1), ``'by'`` is for Benjaminini-Yekutieli
    [2]_ (Theorem 1.3). The latter is more conservative, but it is
    guaranteed to control the FDR even when the p-values are not from
    independent tests.

Returns
-------
ps_adusted : array_like
    The adjusted p-values. If the null hypothesis is rejected where these
    fall below a specified level, the false discovery rate is controlled
    at that level.

See Also
--------
combine_pvalues
statsmodels.stats.multitest.multipletests

Notes
-----
In multiple hypothesis testing, false discovery control procedures tend to
offer higher power than familywise error rate control procedures (e.g.
Bonferroni correction [1]_).

If the p-values correspond with independent tests (or tests with
"positive regression dependencies" [2]_), rejecting null hypotheses
corresponding with Benjamini-Hochberg-adjusted p-values below :math:`q`
controls the false discovery rate at a level less than or equal to
:math:`q m_0 / m`, where :math:`m_0` is the number of true null hypotheses
and :math:`m` is the total number of null hypotheses tested. The same is
true even for dependent tests when the p-values are adjusted accorded to
the more conservative Benjaminini-Yekutieli procedure.

The adjusted p-values produced by this function are comparable to those
produced by the R function ``p.adjust`` and the statsmodels function
`statsmodels.stats.multitest.multipletests`. Please consider the latter
for more advanced methods of multiple comparison correction.

References
----------
.. [1] Benjamini, Yoav, and Yosef Hochberg. "Controlling the false
       discovery rate: a practical and powerful approach to multiple
       testing." Journal of the Royal statistical society: series B
       (Methodological) 57.1 (1995): 289-300.

.. [2] Benjamini, Yoav, and Daniel Yekutieli. "The control of the false
       discovery rate in multiple testing under dependency." Annals of
       statistics (2001): 1165-1188.

.. [3] TileStats. FDR - Benjamini-Hochberg explained - Youtube.
       https://www.youtube.com/watch?v=rZKa4tW2NKs.

.. [4] Neuhaus, Karl-Ludwig, et al. "Improved thrombolysis in acute
       myocardial infarction with front-loaded administration of alteplase:
       results of the rt-PA-APSAC patency study (TAPS)." Journal of the
       American College of Cardiology 19.5 (1992): 885-891.

Examples
--------
We follow the example from [1]_.

    Thrombolysis with recombinant tissue-type plasminogen activator (rt-PA)
    and anisoylated plasminogen streptokinase activator (APSAC) in
    myocardial infarction has been proved to reduce mortality. [4]_
    investigated the effects of a new front-loaded administration of rt-PA
    versus those obtained with a standard regimen of APSAC, in a randomized
    multicentre trial in 421 patients with acute myocardial infarction.

There were four families of hypotheses tested in the study, the last of
which was "cardiac and other events after the start of thrombolitic
treatment". FDR control may be desired in this family of hypotheses
because it would not be appropriate to conclude that the front-loaded
treatment is better if it is merely equivalent to the previous treatment.

The p-values corresponding with the 15 hypotheses in this family were

>>> ps = [0.0001, 0.0004, 0.0019, 0.0095, 0.0201, 0.0278, 0.0298, 0.0344,
...       0.0459, 0.3240, 0.4262, 0.5719, 0.6528, 0.7590, 1.000]

If the chosen significance level is 0.05, we may be tempted to reject the
null hypotheses for the tests corresponding with the first nine p-values,
as the first nine p-values fall below the chosen significance level.
However, this would ignore the problem of "multiplicity": if we fail to
correct for the fact that multiple comparisons are being performed, we
are more likely to incorrectly reject true null hypotheses.

One approach to the multiplicity problem is to control the family-wise
error rate (FWER), that is, the rate at which the null hypothesis is
rejected when it is actually true. A common procedure of this kind is the
Bonferroni correction [1]_.  We begin by multiplying the p-values by the
number of hypotheses tested.

>>> import numpy as np
>>> np.array(ps) * len(ps)
array([1.5000e-03, 6.0000e-03, 2.8500e-02, 1.4250e-01, 3.0150e-01,
       4.1700e-01, 4.4700e-01, 5.1600e-01, 6.8850e-01, 4.8600e+00,
       6.3930e+00, 8.5785e+00, 9.7920e+00, 1.1385e+01, 1.5000e+01])

To control the FWER at 5%, we reject only the hypotheses corresponding
with adjusted p-values less than 0.05. In this case, only the hypotheses
corresponding with the first three p-values can be rejected. According to
[1]_, these three hypotheses concerned "allergic reaction" and "two
different aspects of bleeding."

An alternative approach is to control the false discovery rate: the
expected fraction of rejected null hypotheses that are actually true. The
advantage of this approach is that it typically affords greater power: an
increased rate of rejecting the null hypothesis when it is indeed false. To
control the false discovery rate at 5%, we apply the Benjamini-Hochberg
p-value adjustment.

>>> from scipy import stats
>>> stats.false_discovery_control(ps)
array([0.0015    , 0.003     , 0.0095    , 0.035625  , 0.0603    ,
       0.06385714, 0.06385714, 0.0645    , 0.0765    , 0.486     ,
       0.58118182, 0.714875  , 0.75323077, 0.81321429, 1.        ])

Now, the first *four* adjusted p-values fall below 0.05, so we would reject
the null hypotheses corresponding with these *four* p-values. Rejection
of the fourth null hypothesis was particularly important to the original
study as it led to the conclusion that the new treatment had a
"substantially lower in-hospital mortality rate."

r   r!   z/`ps` must include only numbers between 0 and 1.r   byzUnrecognized `method` 'z'.Method must be one of r9  Nr{   z#`axis` must be an integer or `None`r   r   .)r  r   )valuesr   )r   r	   rW  r   numberr%  rf  rU   r  r   rx  r   r   r  argsorttake_along_axisr   r   rR  
accumulateput_along_axisrv  )psr   r#  ps_in_rangere  rZ   orderr   s           r`   rN   rN   !  s   \ 
BB==2995 7vvbBGGB1$556 JKKTlG||~W$26( ;229!= > 	>\\^F|XXZ::dBD==RZZ00DIIN>??	ww!|rxx~*"v	Rr	"B
A JJr#E			BB	/B 			!QqSAa%KB ~
bffQUm JJ"S$B$Y-RTrT	]D b	;	RT	"B772q!ra   )r  )rc   )T)r{   rj   TNF))r   r   tukeylambda)r,  NP   )NNN)Nr   N)Nr-  rz   )rj   )rK  r   )r   rK  )NwilcoxFrK  r  )rk   r`  	threadingcollectionsr   numpyr   r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   scipyr   r   r   r   scipy._lib._bunchr   scipy._lib._utilr   r   r   scipy._lib._array_apir   r   r   r    _ansari_swilk_statisticsr"   r#    r$   r%   _fitr&   r'   r(   r)   r*   r+   contingencyr,   r-   _distn_infrastructurer.   _axis_nan_policyr/   r0   __all__rO   rR   rS   r2   r1   r3   r4   r   r   r   r5   r6   r7   r   r  r8   r  r9   r*  r,  rV  r:   rq  r;   rJ   ry  rI   rK   rL   r  r<   r  r  r  r  _Avals_weibullr   _cvals_weibullinterp1drn  r  r  r  r=   r
  r  r  rH   r.  r0  localrP  r>   r]  r?   ro  r@   r  r  rA   rO  r  r  rB   r  r  r  r  rC   r  rD   r  rE   rF   rG   r  rM   rN   r{   ra   r`   <module>rA     sl      " 2 2 2 2 2 8 7 / G G  4 " 4 4 )  - I	 &12j"9:
Y 7
8`FHV 14c0T c0c0L 1477 7777t<~>&`FU=pdN
k\ FL!^- 
  k  15`>Q`F'TA3HXv0dNVOrC7L ?,CD -1PTUV8 VV8x 7889 9: BC
 KJJJJJJJJJJ
L .)QR(&&~~7G7G,452@2DF
>B ##3$:<H>K
JDZ(V!H ). @D @F .*AB33 33r __
 ,!4a, 5a,H ,.EF .D9 k% :k%\ .*AB ,$7$d K! 8K!\ ?,CD -48%t M* 9M*` *a1EF* F* FF*R ,_UO/ VO/d ##3k85LM) 68$4F,8H
 :?-3f0=>f0 %f0R %.   '4&T:n'  14" R4QTk V>	V>r 14" B$AD[ W	Wt 14" B$AD[ cc	cLI I ()D BCJ )*$ Dra   