a
    a                    @  sn  d dl mZ d dlZd dlZd dlmZ d dlZd dlmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZ d dlm Z  d dlm!Z! ddl"m#Z# dd	l"m$Z$ dd
l$m%Z%m&Z&m'Z' ddl(m)Z) ddl"m*Z* ddl+m,Z, ddl-m.Z. g dZ/eddZ0eddZ1eddZ2dddZ3dd Z4dddZ5dddZ6dd Z7dd!d"Z8d#d$ Z9dd(d)Z:dd,d-Z;dd/d0Z<d1d2 Z=d3d4 Z>dd5d6Z?dd8d9Z@dd:d;ZAdd<d=ZBdd>d?ZCd@dA ZDdBdC ZEddEdFZFddGdHZGedIdJZHdKdL ZIeg dMZJeg dNZKeg dOZLeg dPZMedQdRZNddSdTZOdUdV ZPdWdX ZQedYdRZRddZd[ZSed\dJZTG d]d^ d^ZUeU ZVdd`daZWedbdJZXdcdd ZYededJZZdfdgdhdidjZ[ddldmZ\dndo Z]edpdJZ^dfdgdhdqdrZ_ddsdtZ`edudJZaddxdyZbdzd dd{d|d}d~ZcdddZdde d dd{fddZede d dd{fddZfde d dd{fddZgdS )    )annotationsN)
namedtuple)isscalarr_logarounduniqueasarrayzerosarangesortaminamax
atleast_1dsqrtarraycompresspiexpravelcount_nonzerosincosarctan2hypot)optimize)special   )statlib)stats)find_repeats_contains_nan_normtest_finish)chi2_contingency)distributions)
rv_generic)_get_wilcoxon_distr)mvsdist	bayes_mvskstatkstatvarprobplotppcc_max	ppcc_plot
boxcox_llfboxcoxboxcox_normmaxboxcox_normplotshapiroandersonansaribartlettlevene
binom_testflignermoodwilcoxonmedian_testcircmeancircvarcircstdanderson_ksampyeojohnson_llf
yeojohnsonyeojohnson_normmaxyeojohnson_normplotMean)	statisticZminmaxVarianceStd_dev?c                 C  sp   t | \}}}|dks|dkr*td| t| ||}t| ||}t| ||}|||fS )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   z20 < alpha < 1 is required, but alpha=%s was given.)r'   
ValueErrorrD   meanintervalrF   rG   )dataalphamvsZm_resZv_resZs_res rQ   e/Users/vegardjervell/Documents/master/model/venv/lib/python3.9/site-packages/scipy/stats/morestats.pyr(   '   s    Wr(   c                 C  s   t | }t|}|dk r td| }| }|dkrtj|t|| d}tjt|t|d|  d}tj|td| | d}nZ|d }|| d }	|d }
tj	||t|| d}tj
|
dt|	d}tj|
|	d}|||fS )	a  
    '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   )rU   )r   lenrI   rJ   varr$   normmathr   tZgengammaZinvgamma)rL   xnxbarCZmdistsdistZvdistZnm1facvalrQ   rQ   rR   r'      s"    7"r'   rS   c                 C  s  |dks|dk rt dt|}t|d tj}t| } | j}|dkrPt dtt| rftj	S t
d|d D ]}tj| | dd||< qt|dkr|d d | S |dkr||d  |d d	  ||d   S |d
kr*d|d d
  d
| |d  |d   || |d
   ||d  |d	   S |dkrd|d d  d| |d d  |d   d
| |d  |d d   d| |d  |d  |d
   || |d  |d   ||d  |d	  |d   S t ddS )a5  
    Return the nth k-statistic (1<=n<=4 so far).

    The nth k-statistic k_n is the unique symmetric unbiased estimator of the
    nth cumulant kappa_n.

    Parameters
    ----------
    data : array_like
        Input array. Note that n-D input gets flattened.
    n : int, {1, 2, 3, 4}, optional
        Default is equal to 2.

    Returns
    -------
    kstat : float
        The nth 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 n, the first few k-statistics are given by:

    .. math::

        k_{1} = \mu
        k_{2} = \frac{n}{n-1} m_{2}
        k_{3} = \frac{ n^{2} } {(n-1) (n-2)} m_{3}
        k_{4} = \frac{ n^{2} [(n + 1)m_{4} - 3(n - 1) m^2_{2}]} {(n-1) (n-2) (n-3)}

    where :math:`\mu` is the sample mean, :math:`m_2` is the sample
    variance, and :math:`m_i` is the i-th sample central moment.

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

    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 n in [2, 3, 4, 5, 6, 7]:
    ...     x = rng.normal(size=10**n)
    ...     m, k = stats.moment(x, 3), stats.kstat(x, 3)
    ...     print("%.3g %.3g %.3g" % (m, k, m-k))
    -0.631 -0.651 0.0194  # random
    0.0282 0.0283 -8.49e-05
    -0.0454 -0.0454 1.36e-05
    7.53e-05 7.53e-05 -2.26e-09
    0.00166 0.00166 -4.99e-09
    -2.88e-06 -2.88e-06 8.63e-13
       r   z'k-statistics only supported for 1<=n<=4r   zData input must not be emptyaxis      ?rS   rV      i         @zShould not be here.N)rI   intnpr
   float64r   sizeisnansumnanrange)rL   r^   SNkrQ   rQ   rR   r)      s6    A$
L
Fr)   c                 C  s   t | } t| }|dkr,t| ddd | S |dkrtt| dd}t| dd}d| |d  |d |  ||d   S tddS )a#  Return an unbiased estimator of the variance of the k-statistic.

    See `kstat` for more details of the k-statistic.

    Parameters
    ----------
    data : array_like
        Input array. Note that n-D input gets flattened.
    n : int, {1, 2}, optional
        Default is equal to 2.

    Returns
    -------
    kstatvar : float
        The nth 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
    -----
    The variances of the first few k-statistics are given by:

    .. math::

        var(k_{1}) = \frac{\kappa^2}{n}
        var(k_{2}) = \frac{\kappa^4}{n} + \frac{2\kappa^2_{2}}{n - 1}
        var(k_{3}) = \frac{\kappa^6}{n} + \frac{9 \kappa_2 \kappa_4}{n - 1} +
                     \frac{9 \kappa^2_{3}}{n - 1} +
                     \frac{6 n \kappa^3_{2}}{(n-1) (n-2)}
        var(k_{4}) = \frac{\kappa^8}{n} + \frac{16 \kappa_2 \kappa_6}{n - 1} +
                     \frac{48 \kappa_{3} \kappa_5}{n - 1} +
                     \frac{34 \kappa^2_{4}}{n-1} + \frac{72 n \kappa^2_{2} \kappa_4}{(n - 1) (n - 2)} +
                     \frac{144 n \kappa_{2} \kappa^2_{3}}{(n - 1) (n - 2)} +
                     \frac{24 (n + 1) n \kappa^4_{2}}{(n - 1) (n - 2) (n - 3)}
    r   rS   )r^   rg   rd   zOnly n=1 or n=2 supported.N)r   rX   r)   rI   )rL   r^   rt   Zk2Zk4rQ   rQ   rR   r*   5  s    '(r*   c                 C  sX   t j| t jd}dd|   |d< d|d  |d< t d| }|d | d	  |dd< |S )
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:

    >>> 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.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      ?rg   r   r   rS   gRQ?g\(\?)rl   emptyrm   r   )r^   rO   irQ   rQ   rR   %_calc_uniform_order_statistic_mediansh  s    6r|   Tc              
   C  sn   t | trn^t | trZztt| } W qj tyV } ztd|  |W Y d}~qjd}~0 0 n|rjd}t|| S )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#%s 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$   AttributeErrorrI   )distenforce_subclassemsgrQ   rQ   rR   _parse_dist_kw  s    

&r   c                 C  sd   zLt | dr,| | | | | | n| | | | | | W n ty^   Y n0 dS )z>Helper function to add axes labels and a title to stats plots.	set_titleN)hasattrr   Z
set_xlabelZ
set_ylabeltitlexlabelylabel	Exception)plotr   r   r   rQ   rQ   rR   _add_axis_labels_title  s    




r   rQ   rZ   Fc                 C  sp  t | } | jdkr6|r.| | ft jt jdffS | | fS tt| }t|dd}|du rZd}t|rh|f}t|t	szt	|}|j
|g|R  }t| }|rt||\}	}
}}}|durL|||d |r|||	| |
 d t|d	d
dd |rLt|}t|}t| }t| }|d||   }|d||   }|||d|d   |rd||f|	|
|ffS ||fS dS )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.

    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
    --------
    >>> 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   NrQ   Zbozr-zTheoretical quantileszOrdered ValueszProbability Plotr   r   r   gffffff?{Gz?z$R^2=%1.4f$rS   )rl   r	   rn   rq   r|   rX   r   r   r}   tupleppfr   r   Z
linregressr   r   r   r   text)r]   Zsparamsr   fitr   Zrvalueosm_uniformZosmosrZslopeZ	interceptrprob_ZxminZxmaxZyminZymaxZposxZposyrQ   rQ   rR   r+     sH    p



r+   r   rg   tukeylambdac                 C  s<   t |}tt| }t| }dd }tj|||||jfdS )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:

    >>> 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                 S  s"   ||| }t ||\}}d| S Nr   )r   pearsonr)shapemiyvalsfuncxvalsr   r   rQ   rQ   rR   tempfunc  s    
zppcc_max.<locals>.tempfuncbrackargs)r   r|   rX   r   r   brentr   )r]   r   r   r   r   r   rQ   rQ   rR   r,   v  s    F
r,   P   c                 C  s   ||krt dtj|||d}t|}t|D ](\}}	t| |	|dd\}
}|d ||< q2|dur|||d t|dd	d
| d ||fS )a9  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:

    >>> 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   ry   Nr]   zShape ValuesProb Plot Corr. Coef.z(%s) PPCC Plotr   )rI   rl   linspace
empty_like	enumerater+   r   r   )r]   abr   r   rt   Zsvalsppccru   Zsvalr   Zr2rQ   rQ   rR   r-     s    T
r-   c                 C  s   t |}|jd }|dkr"t jS t |}| dkrDt j|dd}nt j||  |  dd}| d t j|dd |d t |  S )aK
  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
    --------
    >>> 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   re   r   rS   )rl   r	   r   rq   r   rY   rp   )lmbrL   rt   ZlogdataZvariancerQ   rQ   rR   r.   3  s    O


r.   c           
      C  s   dt jd| d }t|| | }dd }|d }d}||| |dkrb|dk rb|d7 }|d7 }q8|dkrrtd	tj|||| |fd
}|d }d}||| |dkr|dk r|d8 }|d7 }q|dkrtd	tj|||| |fd
}	|	|fS )Nrx   r   c                 S  s   t | || S Nr.   )lmbdarL   targetrQ   rQ   rR   rootfunc  s    z'_boxcox_conf_interval.<locals>.rootfuncr   r   i  皙?zCould not find endpoint.r   )r$   chi2r   r.   RuntimeErrorr   Zbrentq)
r]   lmaxrM   rb   r   r   Znewlmrt   ZlmplusZlmminusrQ   rQ   rR   _boxcox_conf_interval  s(    

r   c                 C  s   t | } | jdkrtd| jdkr*| S t | | d krDtdt | dkrZtd|durnt| |S t	| d|d}t| |}|du r||fS t
| ||}|||fS dS )	a?  Return a dataset transformed by a Box-Cox power transformation.

    Parameters
    ----------
    x : ndarray
        Input array.  Must be positive 1-dimensional.  Must not be constant.
    lmbda : {None, scalar}, optional
        If `lmbda` is not None, do the transformation for that value.
        If `lmbda` is None, find the lambda that maximizes the log-likelihood
        function and return it as the second output argument.
    alpha : {None, float}, optional
        If ``alpha`` is not None, return the ``100 * (1-alpha)%`` confidence
        interval for `lmbda` as the third output argument.
        Must be between 0.0 and 1.0.
    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 lambda 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.zData must be positive.Nmle)method	optimizer)rl   r	   ndimrI   rn   allanyr   r/   r0   r   )r]   r   rM   r   r   yrK   rQ   rQ   rR   r/     s"    e



r/   r   c           	        s   du r"du rdfddn,t s2tddurBtdfddfdd	fd
d  fdd} |d}|| vrtd| || }|| }|du rd}t||S )aT  Compute optimal Box-Cox transform parameter for input data.

    Parameters
    ----------
    x : array_like
        Input array.
    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'
            Minimizes 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 optimized. `fun` accepts one argument,
            the Box-Cox transform parameter `lmbda`, and returns the negative
            log-likelihood function at the provided value. 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.

    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
    --------
    >>> 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
    1.4613865614008015
    >>> lmax_pearsonr
    1.6685004886804342
    >>> stats.boxcox_normmax(x, method='all')
    array([1.66850049, 1.46138656])

    >>> 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.000...
    N)g       rV   c                   s   t j| | dS )N)r   r   r   r   )r   r   )r   rQ   rR   
_optimizer  s    z"boxcox_normmax.<locals>._optimizerz`optimizer` must be a callablez,`brack` must be None if `optimizer` is givenc                   s    fdd}t |dd S )Nc                   s   | g R  S r   rQ   r]   r   r   rQ   rR   func_wrapped  s    z8boxcox_normmax.<locals>._optimizer.<locals>.func_wrappedr]   )r   )r   r   r   )r   r   rR   r     s    c                   s0   t t| }tj|}dd } ||| fdS )Nc                 S  s,   t || }t|}t||\}}d| S r   )r/   rl   r   r   r   )r   r   Zsampsr   r   r   r   rQ   rQ   rR   _eval_pearsonr  s    

z9boxcox_normmax.<locals>._pearsonr.<locals>._eval_pearsonrr   )r|   rX   r$   rZ   r   )r]   r   r   r   r   rQ   rR   	_pearsonr  s    
z!boxcox_normmax.<locals>._pearsonrc                   s   dd } || fdS )Nc                 S  s   t | | S r   r   )r   rL   rQ   rQ   rR   	_eval_mle  s    z/boxcox_normmax.<locals>._mle.<locals>._eval_mler   rQ   )r]   r   r   rQ   rR   _mle  s    zboxcox_normmax.<locals>._mlec                   s*   t jdtd}| |d<  | |d< |S )NrS   rv   r   r   )rl   rz   float)r]   Zmaxlog)r   r   rQ   rR   _all  s    zboxcox_normmax.<locals>._all)r   r   r   zMethod %s not recognized.zQ`optimizer` must return an object containing the optimal `lmbda` in attribute `x`)callablerI   keys)	r]   r   r   r   r   methodsZ	optimfuncresmessagerQ   )r   r   r   r   r   rR   r0   9  s0    cr0   c                 C  s   | dkrd}t }nd}t}t|}|jdkr2|S ||krBtdtj|||d}|d }	t|D ]4\}
}|||d}t|d	d
d\}\}}}||	|
< qb|dur|	||	d t
|dd|d ||	fS )zCompute parameters for a Box-Cox or Yeo-Johnson normality plot,
    optionally show it.

    See `boxcox_normplot` or `yeojohnson_normplot` for details.
    r/   zBox-Cox Normality PlotzYeo-Johnson Normality Plotr   z `lb` has to be larger than `la`.r   r   )r   rZ   Tr   Nr]   z	$\lambda$r   r   )r/   rA   rl   r	   rn   rI   r   r   r+   r   r   )r   r]   lalbr   rt   r   Ztransform_funcZlmbdasr   r{   rc   zr   r   rQ   rQ   rR   	_normplot  s.    


r   c                 C  s   t d| ||||S )ad  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 Correlelation 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()

    r/   r   r]   r   r   r   rt   rQ   rQ   rR   r1     s    Ar1   c                 C  s|   t | } | jdkr| S t | jt jr0tdt | jt jrP| jt j	dd} |durbt
| |S t| }t
| |}||fS )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)copyN)rl   r	   rn   Z
issubdtyperw   ZcomplexfloatingrI   integerastyperm   _yeojohnson_transformrB   )r]   r   r   r   rQ   rQ   rR   rA   K  s    F



rA   c                 C  s   t | }| dk}t|t dk r8t | | ||< n t | | d |d | ||< t|d t dkrt | |   d d| d  d|  || < nt | |    || < |S )zaReturns `x` transformed by the Yeo-Johnson power transform with given
    parameter `lmbda`.
    r   rg   r   rS   )rl   Z
zeros_likeabsspacinglog1ppower)r]   r   outposrQ   rQ   rR   r     s    
 2r   c                 C  s~   t |}|jd }|dkr"t jS t|| }| d t |jdd }|| d t |t t |d  j	dd 7 }|S )av
  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 the Yeo-Johnson
    transformed input data ``x``.

    .. versionadded:: 1.2.0

    Examples
    --------
    >>> 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   rS   re   r   )
rl   r	   r   rq   r   r   rY   signr   rp   )r   rL   Z	n_samplesZtransZloglikerQ   rQ   rR   r@     s    Q


2r@   rW   rS   c                 C  s   dd }t j||| fdS )a  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.

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

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

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

    Examples
    --------
    >>> 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                 S  s   t | | S r   )r@   )r   rL   rQ   rQ   rR   _neg_llfJ  s    z$yeojohnson_normmax.<locals>._neg_llfr   r   )r]   r   r   rQ   rQ   rR   rB     s    /rB   c                 C  s   t d| ||||S )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 Correlelation 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()

    rA   r   r   rQ   rQ   rR   rC   P  s    CrC   ShapiroResult)rE   Zpvaluec                 C  s   t | } t| }|dk r"tdt|d}d}t| }t||d|d  |\}}}}|dvrlt	d |d	kr~t	d
 t
||S )a  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.

    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.

    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.

    The chance of rejecting the null hypothesis when it is true is close to 5%
    regardless of sample size.

    References
    ----------
    .. [1] https://www.itl.nist.gov/div898/handbook/prc/section2/prc213.htm
    .. [2] Shapiro, S. S. & Wilk, M.B (1965). An analysis of variance test for
           normality (complete samples), Biometrika, Vol. 52, pp. 591-611.
    .. [3] Razali, N. M. & Wah, Y. B. (2011) Power comparisons of Shapiro-Wilk,
           Kolmogorov-Smirnov, Lilliefors and Anderson-Darling tests, Journal of
           Statistical Modeling and Analytics, Vol. 2, pp. 21-33.
    .. [4] ALGORITHM AS R94 APPL. STATIST. (1995) VOL. 44, NO. 4.

    Examples
    --------
    >>> 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

    rh   zData must be at least length 3.fr   NrS   )r   rS   zGInput data for shapiro has range zero. The results may not be accurate.i  z)p-value may not be accurate for N > 5000.)rl   r   rX   rI   r
   r   r   Zswilkwarningswarnr   )r]   rt   r   initr   wpwZifaultrQ   rQ   rR   r2     s    8

"

r2   )g;On?gˡE?gv/?gK7A`?gFx?)g/$?gsh|??g~jt?gV-?gZd;O?)gtV?gMb?gMbX9?gMb?gS㥛?)g$C?gjt?gQ?gS㥛?gˡE?g)\(?AndersonResult)rE   Zcritical_valuesZsignificance_levelc                 C  s  |dvrt dt| }tj| dd}t|}|dkrtj| ddd}|| | }tj|}tj	|}t
g d}	ttd	d
|  d| |   d}
n|dkr|| }tj|}tj	|}t
g d}	ttd	d|   d}
nP|dkrzdd }t
|tj| dddg}tj||| |fdd}||d  |d  }tj|}tj	|}t
g d}	ttd	d|   d}
n|dkrtj| \}}|| | }tj|}tj	|}t
g d}	ttd	dt|   d}
nZtj| \}}|| | }tj|}tj	|}t
g d}	ttd	dt|   d}
td|d }| tjd| d	 | ||ddd   dd }t||
|	S )a  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, 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'}, 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
    -------
    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.

    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
        25%, 10%, 5%, 2.5%, 1%

    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.

    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.

    )rZ   exponZgumbelgumbel_lgumbel_rZextreme1logisticzWInvalid distribution; dist must be 'norm', 'expon', 'gumbel', 'extreme1' or 'logistic'.r   re   rZ   r   )ddofrf   )   
            @r   rg         @g      9@rh   r   g333333?r   c                 S  sd   | \}}|| | }t |}tjdd|  ddd|  tj|d|  d|  dd| g}t|S )Nrg   r   r   re   rx   )r   rl   rp   r   )abZxjrt   r   r   tmpZtmp2rc   rQ   rQ   rR   r   S  s     zanderson.<locals>.rootfuncgh㈵>)r   Zxtol)   r   r   r   r   rx         ?r   )r   r   r   r   r   g?rS   Nry   )rI   r   rl   rJ   rX   Zstdr$   rZ   logcdflogsfr   r   _Avals_normr   _Avals_exponr   Zfsolver   _Avals_logisticr   r   _Avals_gumbelr   r   r   rp   r   )r]   r   r   r_   rt   rP   r   r   r  sigcriticalr   Zsol0Zsolr{   A2rQ   rQ   rR   r3     sV    F&

2r3   c                 C  s   d}| |d}||jkr d}n| |d| }||d  }	td|D ]}
t| |
 }|j |dd}|t}|| |d }||d 8 }|t| || |	||
   d  |	||	  || d	   }|| ||
  7 }qF||d | 9 }|S )
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   leftrg   rightrV   r   ZsiderS   r   )searchsortedrn   r   rl   r   r   r   rp   )samplesZZstarru   r^   rt   ZA2akNZZ_ssorted_leftljBjr{   rP   Zs_ssorted_rightMijZfijinnerrQ   rQ   rR   _anderson_ksamp_midrankw  s     

<r  c                 C  s   d}| |dd d| |dd d }| }td|D ]l}	t| |	 }
|
j |dd dd}|t| || |||	   d  |||   }|| ||	  7 }q>|S )	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   Nry   r
  r	  r   r  rS   )r  cumsumr   rl   r   r   rp   )r  r  r  ru   r^   rt   A2kNr  r  r{   rP   r  r  rQ   rQ   rR   _anderson_ksamp_right  s     0r  Anderson_ksampResultc                 C  s  t | }|dk rtdtttj| } tt| }|j}t	|}|jdk rZtdt
dd | D }t|dkrtd|rt| |||||}nt| |||||}d|  }dt|d	 d	d
  }	|	d
 d	 }
|	td|  }d| d |d	  dd|  |  }d| d |d  d|
 |  d| d|
  d |  d|
  d|  d }d|
 d|  d |d  d|
 d|  d |  d|
 d |  d|
  }d|
 d |d  d|
 |  }||d  ||d   ||  | |d |d  |d   }|d	 }|| t| }t
g d}t
g d}t
g d}||t|  ||  }t
g d}|| k r| }tjd|dd nP|| kr| }tjd|dd n$t|t|d}tt||}t|||S )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.

    Returns
    -------
    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%.
    significance_level : float
        An approximate significance level at which the null hypothesis for the
        provided samples can be rejected. The value is floored / capped at
        0.1% / 25%.

    Raises
    ------
    ValueError
        If less 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
    --------
    >>> from scipy import stats
    >>> rng = np.random.default_rng()

    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
    significance level of 3.2%:

    >>> stats.anderson_ksamp([rng.normal(size=50),
    ... rng.normal(loc=0.5, size=30)])
    (1.974403288713695,
      array([0.325, 1.226, 1.961, 2.718, 3.752, 4.592, 6.546]),
      0.04991293614572478)


    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.731):

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

    rS   z)anderson_ksamp needs at least two samplesz7anderson_ksamp needs more than one distinct observationc                 S  s   g | ]
}|j qS rQ   )rn   ).0samplerQ   rQ   rR   
<listcomp>;      z"anderson_ksamp.<locals>.<listcomp>r   z6anderson_ksamp encountered sample without observationsrg   r   ry   rd      r         rh   rV   rj   )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 {})
stacklevelz+p-value floored: true value smaller than {})rX   rI   listmaprl   r	   r   Zhstackrn   r   r   r   r  r  rp   r   r  r[   r   minmaxr   r   formatZpolyfitr   r   Zpolyvalr  )r  Zmidrankru   r  rt   r  r^   r  HZhs_cshgr   r   cdZsigmasqrN   r  Zb0b1b2r  r  ppfrQ   rQ   rR   r?     sX    d

$LL <r?   AnsariResultc                   @  s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )_ABWzEDistribution of Ansari-Bradley W-statistic under the null hypothesis.c                 C  s"   d| _ d| _d| _d| _d| _dS )zMinimal initializer.N)rN   r^   astarttotalfreqs)selfrQ   rQ   rR   __init__s  s
    z_ABW.__init__c                 C  sX   || j ks|| jkrT|| | _ | _t||\}}}|| _|tj| _| j	 | _
dS )z/When necessary, recalculate exact distribution.N)r^   rN   r   Zgscaler2  r   rl   rm   r4  rp   r3  )r5  r^   rN   r2  Za1r   rQ   rQ   rR   _recalc{  s    z_ABW._recalcc                 C  s2   |  || t|| j t}| j| | j S )zProbability mass function.)r7  rl   floorr2  r   rk   r4  r3  r5  ru   r^   rN   indrQ   rQ   rR   pmf  s    z_ABW.pmfc                 C  s>   |  || t|| j t}| jd|d   | j S )z!Cumulative distribution function.Nr   )	r7  rl   ceilr2  r   rk   r4  rp   r3  r9  rQ   rQ   rR   cdf  s    z_ABW.cdfc                 C  s:   |  || t|| j t}| j|d  | j S )zSurvival function.N)	r7  rl   r8  r2  r   rk   r4  rp   r3  r9  rQ   rQ   rR   sf  s    z_ABW.sfN)	__name__
__module____qualname____doc__r6  r7  r;  r=  r>  rQ   rQ   rQ   rR   r1  m  s   r1  	two-sidedc              	   C  s  |dvrt dt| t| } }t| }t|}|dk rBt d|dk rRt d|| }t| |f }t|}tt||| d fd}tj	|d| dd}	t
|}
t|
t|k}|d	k o|d	k o| }|r|d	k s|d	k rtd
 |rZ|dkr"dtt|	||t|	|| }n(|dkr<t|	||}nt|	||}t|	td|S |d r||d d  d | }|| |d  d|d   d|d   }n4||d  d }|| |d  |d  d |d  }|rbtj	|d dd}|d r2|| d| | |d d   d|d  |d   }n0|| d| ||d d    d| |d   }||	 t| }t||\}}t|	|S )av  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
    --------
    >>> 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)

    >   rC  lessgreaterz8'alternative' must be 'two-sided', 'greater', or 'less'.r   zNot enough other observations.zNot enough test observations.r   Nre   7   z%Ties preclude use of exact statistic.rC  rV   rE  rg   rS   r   rh   g      H@0      rd   g      0@)rI   r	   rX   r   r   rankdatar   r   rl   rp   r   r   r   minimum
_abw_stater=  r>  r0  r$  r   r"   )r]   r   alternativer^   rN   rt   xyZrankZsymrankZABZuxyZrepeatsexactpvalZmnABZvarABrb   r   rQ   rQ   rR   r4     sR    g




*$
60r4   BartlettResultc                  G  s^  | D ]>}t |jdkr*tt jt j  S t |jdkrtdqt| }|dk r\tdt |}t |d}t	|D ]*}t| | ||< t j
| | dd||< qzt j|dd}t j|d | ddd	||   }|d	 | t| t j|d	 t| dd }d	d	d
|d   t jd	|d	  ddd	||     }	||	 }
tj|
|d }t|
|S )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

    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 or not the lists `a`, `b` and `c` come from populations
    with equal variances.

    >>> from scipy.stats import bartlett
    >>> 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 = 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]

    r   r    Samples must be one-dimensional.rS   -Must enter at least two input sample vectors.r+  )r   re   rg   rh   )rl   
asanyarrayrn   rP  rq   r   rI   rX   rz   rr   rY   rp   r   r$   r   r>  )r   r   ru   NiZssqjNtotZspsqnumerdenomTrO  rQ   rQ   rR   r5   I	  s,    J

".$
r5   LeveneResultmedianr   )centerproportiontocutc                   s  | dvrt dt|}|dk r(t dt|D ] }t|| jdkr0t dq0t|}t|d}| dkrzd	d
 }n0| dkrdd
 }nt fdd|D }dd
 }t|D ]$}t|| ||< ||| ||< qtj|dd}dg| }	t|D ] }
t	t
||
 ||
  |	|
< qt|d}d}t|D ]0}
tj|	|
 dd||
< |||
 ||
  7 }q2|| }|| tj||| d  dd }d}t|D ](}
|tj|	|
 ||
  d dd7 }q|d | }|| }tj||d || }t||S )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.

    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 or not the lists `a`, `b` and `c` come from populations
    with equal variances.

    >>> from scipy.stats import levene
    >>> 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 = 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]

    rJ   r[  Ztrimmed-center must be 'mean', 'median' or 'trimmed'.rS   rR  r   rQ  r+  r[  c                 S  s   t j| ddS Nr   re   rl   r[  r   rQ   rQ   rR   <lambda>
  r  zlevene.<locals>.<lambda>rJ   c                 S  s   t j| ddS r`  rl   rJ   r   rQ   rQ   rR   rb  

  r  c                 3  s    | ]}t t| V  qd S r   )r   trimbothrl   r   r  argr]  rQ   rR   	<genexpr>
  s   zlevene.<locals>.<genexpr>c                 S  s   t j| ddS r`  rc  r   rQ   rQ   rR   rb  
  r  r   re   Nr   rg   )rI   rX   rr   rl   rS  r   rz   r   rp   r   r	   rJ   r$   r   r>  rZ  )r\  r]  r   ru   rU  rT  Ycir   rV  Zijr{   ZZbariZZbarrW  ZdvarrX  WrO  rQ   rg  rR   r6   	  sN    J




"&r6   rx   c           	      C  s  t | tj} t| dkr6| d | d  }| d } n@t| dkrn| d } |du sZ|| k rbtdt|}ntd|dks|dk rtd	|d
vrtd|dkrtj| ||}|S |dkrtj	| d ||}|S tj
| ||}d}| || krd}n| || k rrtt|| |d }tjtj
||||| kdd}tj| ||tj	|| || }nbtt|| d }tjtj
||||| kdd}tj|d ||tj	| d || }td|S )a  Perform a test that the probability of success is p.

    Note: `binom_test` is deprecated; it is recommended that `binomtest`
    be used instead.

    This is an exact, two-sided test of the null hypothesis
    that the probability of success in a Bernoulli experiment
    is `p`.

    Parameters
    ----------
    x : int or array_like
        The number of successes, or if x has length 2, it is the
        number of successes and the number of failures.
    n : int
        The number of trials.  This is ignored if x gives both the
        number of successes and failures.
    p : float, optional
        The hypothesized probability of success.  ``0 <= p <= 1``. The
        default value is ``p = 0.5``.
    alternative : {'two-sided', 'greater', 'less'}, optional
        Indicates the alternative hypothesis. The default value is
        'two-sided'.

    Returns
    -------
    p-value : float
        The p-value of the hypothesis test.

    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/Binomial_test

    Examples
    --------
    >>> from scipy import stats

    A car manufacturer claims that no more than 10% of their cars are unsafe.
    15 cars are inspected for safety, 3 were found to be unsafe. Test the
    manufacturer's claim:

    >>> stats.binom_test(3, n=15, p=0.1, alternative='greater')
    0.18406106910639114

    The null hypothesis cannot be rejected at the 5% level of significance
    because the returned p-value is greater than the critical value of 5%.

    rS   r   r   Nzn must be >= xzIncorrect length for x.rg   r   zp must be in range [0,1]rC  rD  rE  zEalternative not recognized
should be 'two-sided', 'less' or 'greater'rD  rE  g  ?re   )r   r   rl   int_rX   rI   r$   Zbinomr=  r>  r;  r   r<  rp   r8  r$  )	r]   r^   r.  rL  rO  r+  Zrerrr{   r   rQ   rQ   rR   r7   0
  sH    1
""r7   c                   s@   t tdtf  fddttd D }t|S )Nr   c                   s(   g | ] } | |d    qS )r   rQ   )r  ru   r   r)  r]   rQ   rR   r  
  r  z_apply_func.<locals>.<listcomp>r   )r   r   rX   rr   r	   )r]   r)  r   outputrQ   rn  rR   _apply_func
  s    "rp  FlignerResultc                   s  | dvrt dD ]&}t|jdkrttjtj  S qt}|dk rTt d| dkrfdd n0| d	krxd
d ntfddD dd tfddt	|D }tfddt	|D  tj
|dd} fddt	|D }g }dg}	t	|D ]&}
|t||
  |	t| qt|}tj|d|d   d }t||	tj
| }tj|dd}tj|ddd}tj
|t|| d  dd| }tj||d }t||S )ad  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

    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 biding data.
           Technometrics, 23(4), 351-361.

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

    >>> from scipy.stats import fligner
    >>> 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 = 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]

    r^  r_  r   rS   rR  r[  c                 S  s   t j| ddS r`  ra  r   rQ   rQ   rR   rb    r  zfligner.<locals>.<lambda>rJ   c                 S  s   t j| ddS r`  rc  r   rQ   rQ   rR   rb    r  c                 3  s   | ]}t | V  qd S r   )r   rd  re  rg  rQ   rR   rh    r  zfligner.<locals>.<genexpr>c                 S  s   t j| ddS r`  rc  r   rQ   rQ   rR   rb    r  c                   s   g | ]}t  | qS rQ   )rX   r  rU  r   rQ   rR   r    r  zfligner.<locals>.<listcomp>c                   s   g | ]} | qS rQ   rQ   rr  r   rQ   rR   r  	  r  re   c                   s$   g | ]}t t|  |  qS rQ   )r   r	   )r  r{   )ri  r   rQ   rR   r    r  rg   rx   r   )rf   r   rV   )rI   rl   rS  rn   rq  rq   rX   r   r	   rr   rp   extendr"  appendr   rI  r$   rZ   r   rp  rJ   rY   r   r>  )r\  r]  r   r   ru   rT  rV  rj  ZallZijr)  r{   ZranksZAibarZanbarZvarsqZXsqrO  rQ   )ri  r   r   r]  rR   r8   
  s>    W


"r8   c                   s  t jtdt jtd du r8  d  dk rJj   t fddttjD }|t fddttjD kst	dj  }j  }|| }|dk rt	d	t j
f d
} dkrt | }||jd d}t |}	t|jd D ](}
t|dd|
f |	dd|
f< q|	d| }t j||d d  d dd
}||| d  d }|| |d  |d  |d  d }|| t| }t||\}}|dkr|d }|d }n||_||_||fS )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.
    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
    -------
    z : scalar or ndarray
        The z-score for the hypothesis test.  For 1-D inputs a scalar is
        returned.
    p-value : 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.

    Examples
    --------
    >>> 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))
    >>> z, p = stats.mood(x1, x2, axis=1)
    >>> p.shape
    (2, 6, 7)

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

    >>> (p > 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)
    (array([-5.76174136, -6.12650783]), array([8.32505043e-09, 8.98287869e-10]))

    rv   Nr   c                   s   g | ]}| krj | qS rQ   r   r  ax)rf   r]   rQ   rR   r  y  r  zmood.<locals>.<listcomp>c                   s   g | ]}| krj | qS rQ   ru  rv  )rf   r   rQ   rR   r  z  s   z<Dimensions of x and y on all axes except `axis` should matchrh   zNot enough observations.re   ry   r   rg   rS   ri      rQ   )rl   r	   r   flattenr   r   rr   rX   r   rI   concatenateZrollaxisZreshaper   r   rI  rp   r   r"   )r]   r   rf   rL  Z	res_shaper^   rN   rt   rM  Z	all_ranksrU  ZRiMZmnMZvarMr   rO  rQ   )rf   r]   r   rR   r9     sF    N
"&


&$

r9   WilcoxonResultwilcoxautoc                 C  s  |dvrt d|dvr t d|dvr0t d|du rTt| }|jdkrt d	nNtt| |f\} }| jdksz|jdkrt d
t| t|krt d| | }|dkrt|dkrd}nd}t|dk}|dkr|dkrd}td |dkr2|dv r|t|krt d|dkr2t	t
|d|}t|}|dk rX|dkrXtd tt|}	t|dk|	 }
t|dk |	 }|dkrt|dk|	 }|
|d 7 }
||d 7 }|dkrt|
|}n|
}|dkr"||d  d }||d  d| d  }|dkrP|	|dk }	|||d  d 8 }|||d  d| d  8 }t|	\}}|jdkr|d||| d    8 }t|d }d}|r|dkrdt||  }n|dkrd }nd}|| | | }|dkrdtjt| }n$|d!krtj|}ntj|}n|dkrt|}t|
}
|dkr|
t|d d" krbd}nFt|d|
d  d"|  }t||
d d"|  }d"t|| }nD|d!krt||
d d"|  }nt|d|
d  d"|  }t||S )#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.
    zero_method : {"pratt", "wilcox", "zsplit"}, optional
        The following options are available (default is "wilcox"):

          * "pratt": Includes zero-differences in the ranking process,
            but drops the ranks of the zeros, see [4]_, (more conservative).
          * "wilcox": Discards all zero-differences, the default.
          * "zsplit": Includes zero-differences in the ranking process and
            split 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
        The alternative hypothesis to be tested, see Notes. Default is
        "two-sided".
    mode : {"auto", "exact", "approx"}
        Method to calculate the p-value, see Notes. Default is "auto".

    Returns
    -------
    statistic : float
        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 : float
        The p-value for the test depending on ``alternative`` and ``mode``.

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

    Notes
    -----
    The test has been introduced in [4]_. Given n independent samples
    (xi, yi) from a bivariate distribution (i.e. paired samples),
    it computes the differences di = xi - yi. One assumption of the test
    is that the differences are symmetric, see [2]_.
    The two-sided test has the null hypothesis that the median of the
    differences is zero against the alternative that it is different from
    zero. The one-sided test has the null hypothesis that the median is
    positive against the alternative that it is negative
    (``alternative == 'less'``), or vice versa (``alternative == 'greater.'``).

    To derive the p-value, the exact distribution (``mode == 'exact'``)
    can be used for sample sizes of up to 25. The default ``mode == 'auto'``
    uses the exact distribution if there are at most 25 observations and no
    ties, otherwise a normal approximation is used (``mode == 'approx'``).

    The treatment of ties can be controlled by the parameter `zero_method`.
    If ``zero_method == 'pratt'``, the normal approximation is adjusted as in
    [5]_. A typical rule is to require that n > 20 ([2]_, p. 383).

    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 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
    >>> w, p = wilcoxon(d)
    >>> w, p
    (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:

    >>> w, p = wilcoxon(d, alternative='greater')
    >>> w, p
    (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:

    >>> w, p = wilcoxon(d, mode='approx')
    >>> w, p
    (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).

    )r~  approxrN  z/mode must be either 'auto', 'approx' or 'exact')r}  prattzsplitz:Zero method must be either 'wilcox' or 'pratt' or 'zsplit'rl  z;Alternative must be either 'two-sided', 'greater' or 'less'Nr   z!Sample x must be one-dimensional.z(Samples x and y must be one-dimensional.z.The samples x and y must have the same length.r~  r   rN  r  r   z]Exact p-value calculation does not work if there are ties. Switching to normal approximation.)r}  r  zOzero_method 'wilcox' and 'pratt' do not work if x - y is zero for all elements.r}  r   z/Sample size too small for normal approximation.r  rV   rC  rg   r   r  rx      rD  g      rE  rS   )rI   r	   r   r#  rX   rl   rp   r   r   r   	not_equalr   rI  r   r$  r    rn   r   r   r$   rZ   r>  r=  r&   rk   r|  )r]   r   Zzero_method
correctionrL  moder+  Zn_zerocountr   Zr_plusZr_minusZr_zerorY  mnseZreplistZrepnumr   r   ZcntZp_lessZ	p_greaterrQ   rQ   rR   r:     s    }







	









r:   below	propagate)tiesr  lambda_
nan_policyc                 G  sn  t |dk rtdg d}| |vr@td| t|dd f dd |D }t|D ]B\}}|jd	krxtd
|d  |jdkrVtd|d |jf qVt|}	t|	|\}
}|
r|dkrtj	tj	tj	dfS |
rt
|	t|	  }n
t
|	}tjdt |ftjd}t|D ]\}}|t|  }t||k}t||k }|j||  }|d	|f  |7  < |d|f  |7  < | dkr|d|f  |7  < n| dkr|d	|f  |7  < q|jdd}|d	 d	krtd| |d d	krtd| | dkrLt|d	kjd	dd	 }t |d	krLd|d	 d |f }t|t|||d\}}}}||||fS )al  Perform a Mood's median test.

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

    Let ``n = len(args)`` 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
    -------
    stat : float
        The test statistic.  The statistic that is returned is determined by
        `lambda_`.  The default is Pearson's chi-squared statistic.
    p : float
        The p-value of the test.
    m : 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
    >>> stat, p, med, tbl = median_test(g1, g2, g3)

    The median is

    >>> med
    34.0

    and the contingency table is

    >>> tbl
    array([[ 5, 10,  7],
           [11,  5, 10]])

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

    >>> p
    0.12609082774093244

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

    >>> g, p, med, tbl = median_test(g1, g2, g3, lambda_="log-likelihood")
    >>> p
    0.12224779737117837

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

    >>> stat, p, med, tbl = median_test(g1, g2, g3, ties="above")
    >>> p
    0.063873276069553273

    >>> tbl
    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`.

    rS   z)median_test requires two or more samples.)r  aboveignorez5invalid 'ties' option '%s'; 'ties' must be one of: %sr   ry   c                 S  s   g | ]}t |qS rQ   )rl   r	   re  rQ   rQ   rR   r  7  r  zmedian_test.<locals>.<listcomp>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  Nrv   r  r  re   z+All values are below the grand median (%r).z+All values are above the grand median (%r).r  znAll values in sample %d are equal to the grand median (%r), so they are ignored, resulting in an empty sample.)r  r  )rX   rI   r~   r   rn   r   rl   rz  r!   rq   r[  ro   r
   Zint64r   rp   Znonzeror   r#   )r  r  r  r  r   Zties_optionsrL   ru   r+  cdatacontains_nanZgrand_mediantabler  ZnaboveZnbelowZnequalZrowsumsZ	zero_colsr   statr.  ZdofexpectedrQ   rQ   rR   r;     sr     






r;   c                 C  s   t | } | jdkr2t jt t jt t jd fS t| | d t ||  }t| | d t ||  }t| |\}}|r|dkrt | }d||< d||< nd }| |||fS )Nr   rV   Zomitr   )	rl   r	   rn   rq   r   r   r   r!   ro   )r  highlowr  sin_sampcos_sampr  maskrQ   rQ   rR   _circfuncs_commonz  s    



r  c                 C  s  t | |||d\} }}}|j|d}|j|d}	t||	}
t|
 }|jdkr^|
| dk }n|
dk }|jdkr|||< |
|  dt 7  < n|r|
dt 7 }
|dur| rtj|
j	tj
d}
n8|du rdn|}|j	| |j|dk}| rtj
|
|< |
||  d t | S )a  Compute the circular mean for samples in a range.

    Parameters
    ----------
    samples : array_like
        Input array.
    high : float or int, optional
        High boundary for circular mean range.  Default is ``2*pi``.
    low : float or int, optional
        Low boundary for circular mean range.  Default is 0.
    axis : int, optional
        Axis along which means are computed.  The default is to compute
        the mean of the flattened array.
    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
    -------
    circmean : float
        Circular mean.

    Examples
    --------
    >>> from scipy.stats import circmean
    >>> circmean([0.1, 2*np.pi+0.2, 6*np.pi+0.3])
    0.2

    >>> from scipy.stats import circmean
    >>> circmean([0.2, 1.4, 2.6], high = 1, low = 0)
    0.4

    r  re   r   rS   N)r   Z
fill_valuerV   )r  rp   r   rl   ro   r   r   r   fullr   rq   r   )r  r  r  rf   r  r  r  ZnmaskZsin_sumZcos_sumr   Zmask_nanr  ZnshapeZsmaskrQ   rQ   rR   r<     s.    #



r<   c                 C  s   t | |||d\} }}}|du r:|j|d}|j|d}	nJttj| |dt}
tj|
|
dk< |j|d|
 }|j|d|
 }	tjdd" t	dt
||	}W d   n1 s0    Y  || d t d	 d
 t| S )aZ  Compute the circular variance for samples assumed to be in a range.

    Parameters
    ----------
    samples : array_like
        Input array.
    high : float or int, optional
        High boundary for circular variance range.  Default is ``2*pi``.
    low : float or int, optional
        Low boundary for circular variance range.  Default is 0.
    axis : int, optional
        Axis along which variances are computed.  The default is to compute
        the variance of the flattened array.
    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
    -------
    circvar : float
        Circular variance.

    Notes
    -----
    This uses a definition of circular variance that in the limit of small
    angles returns a number close to the 'linear' variance.

    Examples
    --------
    >>> from scipy.stats import circvar
    >>> circvar([0, 2*np.pi/3, 5*np.pi/3])
    2.19722457734

    r  Nre   r   r  invalidr   rV   rS   rW   )r  rJ   rl   r	   rp   r   r   rq   errstaterJ  r   r   r   r  r  r  rf   r  r  r  r  Zsin_meanZcos_meanZnsumRrQ   rQ   rR   r=     s    $0r=   c                 C  s   t | |||d\} }}}|du r:|j|d}|j|d}	nJttj| |dt}
tj|
|
dk< |j|d|
 }|j|d|
 }	tjdd" t	dt
||	}W d   n1 s0    Y  || d t td	t|  S )
a  
    Compute the circular standard deviation for samples assumed to be in the
    range [low to high].

    Parameters
    ----------
    samples : array_like
        Input array.
    high : float or int, optional
        High boundary for circular standard deviation range.
        Default is ``2*pi``.
    low : float or int, optional
        Low boundary for circular standard deviation range.  Default is 0.
    axis : int, optional
        Axis along which standard deviations are computed.  The default is
        to compute the standard deviation of the flattened array.
    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
    -------
    circstd : float
        Circular standard deviation.

    Notes
    -----
    This uses a definition of circular standard deviation that in the limit of
    small angles returns a number close to the 'linear' standard deviation.

    Examples
    --------
    >>> from scipy.stats import circstd
    >>> circstd([0, 0.1*np.pi/2, 0.001*np.pi, 0.03*np.pi/2])
    0.063564063306

    r  Nre   r   r  r  r   rV   rW   )r  rJ   rl   r	   rp   r   r   rq   r  rJ  r   r   r   r   r  rQ   rQ   rR   r>     s    '0r>   )rH   )rS   )rS   )T)rQ   rZ   TNF)r   r   )r   Nr   )NNN)Nr   N)Nr   )Nr   )N)r   )Nr   )rZ   )T)rC  )Nrx   rC  )r   rC  )Nr}  FrC  r~  )r  )h
__future__r   r[   r   collectionsr   Znumpyrl   r   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Zscipyr   r    r   r   r    r!   r"   Zcontingencyr#   r$   Z_distn_infrastructurer%   Z
_hypotestsr&   __all__rD   rF   rG   r(   r'   r)   r*   r|   r   r   r+   r,   r-   r.   r   r/   r0   r   r1   rA   r   r@   rB   rC   r   r2   r  r  r  r  r   r3   r  r  r  r?   r0  r1  rK  r4   rP  r5   rZ  r6   r7   rp  rq  r8   r9   r|  r:   r;   r  r<   r=   r>   rQ   rQ   rQ   rR   <module>   s   d



cK
`
3>

 
W
fb#
 
 (
'
D
[_
5
F
O

+$
  
7
  
c
 
`

 
 
  
 } W
D5