a
    aJ                    @   s
  d Z ddlZddlZddlmZ ddlmZ ddl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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mZ d
dl m!Z!m"Z"m#Z#m$Z$ ddl%m&Z& d
dl'm(Z( g dZ)dJddZ*dd Z+dd Z,dd Z-dd Z.dd Z/dKdd Z0dLd!d"Z1ed#d$Z2dMd%d&Z3d'd( Z4dNd*d+Z5dOd,d-Z6dPd/d0Z7dQd1d2Z8dRd3d4Z9dSd5d6Z:dTd7d8Z;dd9d:d;Z<dUd<d=Z=dVd>d?Z>dWd@dAZ?edBdCZ@dXdDdEZAdFdG ZBedHdIZCdYdKdLZDedMdIZEdZdNdOZFedPdIZGd[dQdRZHedSdIZIdTdU ZJejKdVdWdXdY ZLd\d\d]ZMd^d_ ZNd]dadbZOedcddZPd^dgdhZQedidjZRd_dkdlZSedmdnZTd`dodpZUdqdr ZVdadsdtZWdudv ZXdwdx ZYdbdydzZZdcd{d|Z[ddd}d~Z\deddZ]de^dd e_d dZ`dfddZadd ZbdejcddfddZddZeejKddeeddejcddfddZfeddZgdgddZhdhddZididdZjdjddZkeddIZlG dd demZnG dd demZodd Zpdd ZqddddZrddddZsdd Zte&ddIZuG dd demZvG dd demZwG dd demZxdd ZydkddZzG dd demZ{eddZ|dlddZ}eddZ~dd ZeddZdmddǄZeddZdnddʄZG dd̄ d̃ZdoddЄZdd҄ ZeddԃZedd
dfdfddքZdd؄ Zddڄ Zdd܄ Zddބ ZeddIZdpddZdd Zdd Zdd Zdd ZeddIZdqddZdd ZdrddZdd Zdd Zdd ZdsddZdtddZduddZdd ZeddIZdvd dZd
dddΐdddZdwddZdd	 Zed
dIZdxddZdyddZeddIZdd Zdd ZdzddZeZdd Zdd Zdd Zdd Zd{ddZd d! Zd|d#d$Zd%d& Zed'dIZd}d(d)Zed*dIZddd+d,Zed-dIZd.d/ Zed0dIZd~d2d3Zdd5d6Zdd7d8Zdd9d:Zdd;d<Zd=d> Zed?d@ZdAdB ZddCdDZddEdFZÐddddHdIZdS (  z
A collection of basic statistical functions for Python.

References
----------
.. [CRCProbStat2000] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
   Probability and Statistics Tables and Formulae. Chapman & Hall: New
   York. 2000.

    N)gcd)
namedtuple)arrayasarraymacdist)measurements)check_random_state
MapWrapperrng_integersfloat_factorial)linalg   )distributions)mstats_basic)_find_repeats
linregresstheilslopessiegelslopes)_kendall_dis_toint64_weightedrankedtau_local_correlations)make_dataclass)_all_partitions)Gfind_repeatsgmeanhmeanmodetmeantvartmintmaxtstdtsemmoment	variationskewkurtosisdescribeskewtestkurtosistest
normaltestjarque_beraitemfreqscoreatpercentilepercentileofscorecumfreqrelfreqobrientransformsemzmapzscoreiqrgstdmedian_absolute_deviationmedian_abs_deviation	sigmacliptrimbothtrim1	trim_meanf_onewayF_onewayConstantInputWarningF_onewayBadInputSizesWarningPearsonRConstantInputWarning PearsonRNearConstantInputWarningpearsonrfisher_exactSpearmanRConstantInputWarning	spearmanrpointbiserialr
kendalltauweightedtaumultiscale_graphcorrr   r   r   ttest_1samp	ttest_indttest_ind_from_stats	ttest_relkstestks_1sampks_2samp	chisquarepower_divergence
tiecorrectranksumskruskalfriedmanchisquarerankdatacombine_pvalueswasserstein_distanceenergy_distancebrunnermunzelalexandergovern	propagatec                 C   s   g d}||vr,t dddd |D  z@tjdd  tt| }W d    n1 s`0    Y  W nP ty   ztjt| 	 v }W n& ty   d}d	}t
d
t Y n0 Y n0 |r|dkrt d||fS )Nr`   raiseomitznan_policy must be one of {%s}z, c                 s   s   | ]}d | V  qdS )z'%s'N ).0srd   rd   a/Users/vegardjervell/Documents/master/model/venv/lib/python3.9/site-packages/scipy/stats/stats.py	<genexpr>S       z _contains_nan.<locals>.<genexpr>ignoreinvalidFrc   zYThe input array could not be properly checked for nan values. nan values will be ignored.rb   zThe input contains nan values)
ValueErrorjoinnperrstateisnansum	TypeErrornansetravelwarningswarnRuntimeWarning)a
nan_policyZpoliciescontains_nanrd   rd   rg   _contains_nanO   s(    2r}   c                 C   sB   |d u rt | } d}nt | } |}| jdkr:t | } | |fS Nr   ro   rv   r   ndimZ
atleast_1d)rz   axisoutaxisrd   rd   rg   _chk_asarraym   s    



r   c                 C   sl   |d u r"t | } t |}d}nt | } t |}|}| jdkrNt | } |jdkrbt |}| ||fS r~   r   )rz   br   r   rd   rd   rg   _chk2_asarray{   s    







r   c                 C   s@   t | j}z
||= W n" ty6   t|| jdY n0 t|S )z
    Given an array `a` and an integer `axis`, return the shape
    of `a` with the `axis` dimension removed.

    Examples
    --------
    >>> a = np.zeros((3, 5, 2))
    >>> _shape_with_dropped_axis(a, 1)
    (3, 2)

    N)listshape
IndexErrorro   	AxisErrorr   tuple)rz   r   shprd   rd   rg   _shape_with_dropped_axis   s    

r   c           	      C   s   t | t | }|dkr,d|  |  }|}n| }d| | }g }t||D ]L\}}|dkr`|}n,|dksp||krv|}ntd|  d| d|| qJt|S )z
    Given two shapes (i.e. tuples of integers), return the shape
    that would result from broadcasting two arrays with the given
    shapes.

    Examples
    --------
    >>> _broadcast_shapes((2, 1), (4, 1, 3))
    (4, 2, 3)
    r   r   r   zshapes  and   could not be broadcast together)lenziprm   appendr   )	Zshape1Zshape2dshp1shp2r   n1n2nrd   rd   rg   _broadcast_shapes   s    r   c              	   C   sR   t | |}t ||}zt||}W n* tyL   td| d| ddY n0 |S )a=  
    Given two arrays `a` and `b` and an integer `axis`, find the
    shape of the broadcast result after dropping `axis` from the
    shapes of `a` and `b`.

    Examples
    --------
    >>> a = np.zeros((5, 2, 1))
    >>> b = np.zeros((1, 9, 3))
    >>> _broadcast_shapes_with_dropped_axis(a, b, 1)
    (5, 3)
    znon-axis shapes r   r   N)r   r   rm   )rz   r   r   r   r   r   rd   rd   rg   #_broadcast_shapes_with_dropped_axis   s    

r   c                 C   s   t | tjs"ttj| |d}nJ|rbt | tjjrLttjj| |d}qlttj| |d}n
t| }|durtj||d}t	tj
|||dS )a  Compute the geometric mean along the specified axis.

    Return the geometric average of the array elements.
    That is:  n-th root of (x1 * x2 * ... * xn)

    Parameters
    ----------
    a : array_like
        Input array or object that can be converted to an array.
    axis : int or None, optional
        Axis along which the geometric mean is computed. Default is 0.
        If None, compute over the whole array `a`.
    dtype : dtype, optional
        Type of the returned array and of the accumulator in which the
        elements are summed. If dtype is not specified, it defaults to the
        dtype of a, unless a has an integer dtype with a precision less than
        that of the default platform integer. In that case, the default
        platform integer is used.
    weights : array_like, optional
        The weights array can either be 1-D (in which case its length must be
        the size of `a` along the given `axis`) or of the same shape as `a`.
        Default is None, which gives each value a weight of 1.0.

    Returns
    -------
    gmean : ndarray
        See `dtype` parameter above.

    See Also
    --------
    numpy.mean : Arithmetic average
    numpy.average : Weighted average
    hmean : Harmonic mean

    Notes
    -----
    The geometric average is computed over a single dimension of the input
    array, axis=0 by default, or all values in the array if axis=None.
    float64 intermediate and return values are used for integer inputs.

    Use masked arrays to ignore any non-finite values in the input or that
    arise in the calculations such as Not a Number and infinity because masked
    arrays automatically mask any non-finite values.

    References
    ----------
    .. [1] "Weighted Geometric Mean", *Wikipedia*, https://en.wikipedia.org/wiki/Weighted_geometric_mean.

    Examples
    --------
    >>> from scipy.stats import gmean
    >>> gmean([1, 4])
    2.0
    >>> gmean([1, 2, 3, 4, 5, 6, 7])
    3.3800151591412964

    dtypeN)r   weights)
isinstancero   ndarraylogr   r   MaskedArrayr   
asanyarrayexpaverage)rz   r   r   r   Zlog_ard   rd   rg   r      s    :
r   c                 C   s   t | tjstj| |d} t| dkrt | tjjrB| |}n&|du r^|  } | j	d }n
| j	| }tj
dd( |tjd|  ||d W  d   S 1 s0    Y  ntddS )	a  Calculate the harmonic mean along the specified axis.

    That is:  n / (1/x1 + 1/x2 + ... + 1/xn)

    Parameters
    ----------
    a : array_like
        Input array, masked array or object that can be converted to an array.
    axis : int or None, optional
        Axis along which the harmonic mean is computed. Default is 0.
        If None, compute over the whole array `a`.
    dtype : dtype, optional
        Type of the returned array and of the accumulator in which the
        elements are summed. If `dtype` is not specified, it defaults to the
        dtype of `a`, unless `a` has an integer `dtype` with a precision less
        than that of the default platform integer. In that case, the default
        platform integer is used.

    Returns
    -------
    hmean : ndarray
        See `dtype` parameter above.

    See Also
    --------
    numpy.mean : Arithmetic average
    numpy.average : Weighted average
    gmean : Geometric mean

    Notes
    -----
    The harmonic mean is computed over a single dimension of the input
    array, axis=0 by default, or all values in the array if axis=None.
    float64 intermediate and return values are used for integer inputs.

    Use masked arrays to ignore any non-finite values in the input or that
    arise in the calculations such as Not a Number and infinity.

    Examples
    --------
    >>> from scipy.stats import hmean
    >>> hmean([1, 4])
    1.6000000000000001
    >>> hmean([1, 2, 3, 4, 5, 6, 7])
    2.6997245179063363

    r   r   Nrj   divide      ?)r   r   zHHarmonic mean only defined if all elements greater than or equal to zero)r   ro   r   r   allr   r   countrv   r   rp   rr   rm   )rz   r   r   sizerd   rd   rg   r   #  s    0
8r   
ModeResult)r   r   c                 C   s  t | |\} }| jdkr.ttg tg S t| |\}}|r^|dkr^t| } t	| |S | j
tkr
tjt|  v r
tt| }t| j}d||< tj|| j
d}tj|td}|D ]>}| |k}	tj|	|dd}
t|
|k||}t|
|}|}qt||S dd }tt| j}t| |d	| ||d d	  |g }t|jd	d
 }tj|jd	d
 | j
d}tj|jd	d
 tjd}
|D ]}||| \||< |
|< qt| j}d||< t|||
|S )a_  Return an array of the modal (most common) value in the passed array.

    If there is more than one such value, only the smallest is returned.
    The bin-count for the modal bins is also returned.

    Parameters
    ----------
    a : array_like
        n-dimensional array of which to find mode(s).
    axis : int or None, optional
        Axis along which to operate. Default is 0. If None, compute over
        the whole array `a`.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

          * 'propagate': returns nan
          * 'raise': throws an error
          * 'omit': performs the calculations ignoring nan values

    Returns
    -------
    mode : ndarray
        Array of modal values.
    count : ndarray
        Array of counts for each mode.

    Examples
    --------
    >>> a = np.array([[6, 8, 3, 0],
    ...               [3, 2, 1, 7],
    ...               [8, 1, 8, 4],
    ...               [5, 3, 0, 5],
    ...               [4, 7, 5, 9]])
    >>> from scipy import stats
    >>> stats.mode(a)
    ModeResult(mode=array([[3, 1, 0, 0]]), count=array([[1, 1, 1, 1]]))

    To get mode of whole array, specify ``axis=None``:

    >>> stats.mode(a, axis=None)
    ModeResult(mode=array([3]), count=array([3]))

    r   rc   r   r   Tkeepdimsc                 S   s&   t j| dd\}}||  | fS )NTZreturn_counts)ro   uniqueargmaxmax)rz   valsZcntsrd   rd   rg   _mode1D  s    zmode.<locals>._mode1DN)r   r   r   ro   r   r}   r   masked_invalidr   r   r   objectrt   ru   rv   r   r   zerosintrr   wheremaximumranger   Z	transposeZndindexemptyint_reshape)rz   r   r{   r|   scoresZ	testshapeZoldmostfreqZ	oldcountsscoretemplatecountsZmostfrequentr   Zin_dimsZa_viewZindsmodesindZnewshaperd   rd   rg   r   i  s>    -

 

*
r   c                 C   s~   |\}}|\}}t | }|dur@|r4t ||}nt ||}|durf|rZt ||}nt ||}| dkrztd|S )a  Mask an array for values outside of given limits.

    This is primarily a utility function.

    Parameters
    ----------
    a : array
    limits : (float or None, float or None)
        A tuple consisting of the (lower limit, upper limit).  Values in the
        input array less than the lower limit or greater than the upper limit
        will be masked out. None implies no limit.
    inclusive : (bool, bool)
        A tuple consisting of the (lower flag, upper flag).  These flags
        determine whether values exactly equal to lower or upper are allowed.

    Returns
    -------
    A MaskedArray.

    Raises
    ------
    A ValueError if there are no values within the given limits.

    Nr   z#No array values within given limits)r   r   Zmasked_lessZmasked_less_equalZmasked_greaterZmasked_greater_equalr   rm   )rz   limits	inclusiveZlower_limitZupper_limitZlower_includeZupper_includeamrd   rd   rg   _mask_to_limits  s    
r   TTc                 C   s8   t | } |du rt| dS t|  ||}|j|dS )a  Compute the trimmed mean.

    This function finds the arithmetic mean of given values, ignoring values
    outside the given `limits`.

    Parameters
    ----------
    a : array_like
        Array of values.
    limits : None or (lower limit, upper limit), optional
        Values in the input array less than the lower limit or greater than the
        upper limit will be ignored.  When limits is None (default), then all
        values are used.  Either of the limit values in the tuple can also be
        None representing a half-open interval.
    inclusive : (bool, bool), optional
        A tuple consisting of the (lower flag, upper flag).  These flags
        determine whether values exactly equal to the lower or upper limits
        are included.  The default value is (True, True).
    axis : int or None, optional
        Axis along which to compute test. Default is None.

    Returns
    -------
    tmean : float
        Trimmed mean.

    See Also
    --------
    trim_mean : Returns mean after trimming a proportion from both tails.

    Examples
    --------
    >>> from scipy import stats
    >>> x = np.arange(20)
    >>> stats.tmean(x)
    9.5
    >>> stats.tmean(x, (3,17))
    10.0

    Nr   )r   ro   meanr   rv   )rz   r   r   r   r   rd   rd   rg   r      s
    )r    c                 C   sR   t | } | t} |du r(| j||dS t| ||}|jtjd}tj|||dS )a}  Compute the trimmed variance.

    This function computes the sample variance of an array of values,
    while ignoring values which are outside of given `limits`.

    Parameters
    ----------
    a : array_like
        Array of values.
    limits : None or (lower limit, upper limit), optional
        Values in the input array less than the lower limit or greater than the
        upper limit will be ignored. When limits is None, then all values are
        used. Either of the limit values in the tuple can also be None
        representing a half-open interval.  The default value is None.
    inclusive : (bool, bool), optional
        A tuple consisting of the (lower flag, upper flag).  These flags
        determine whether values exactly equal to the lower or upper limits
        are included.  The default value is (True, True).
    axis : int or None, optional
        Axis along which to operate. Default is 0. If None, compute over the
        whole array `a`.
    ddof : int, optional
        Delta degrees of freedom.  Default is 1.

    Returns
    -------
    tvar : float
        Trimmed variance.

    Notes
    -----
    `tvar` computes the unbiased sample variance, i.e. it uses a correction
    factor ``n / (n - 1)``.

    Examples
    --------
    >>> from scipy import stats
    >>> x = np.arange(20)
    >>> stats.tvar(x)
    35.0
    >>> stats.tvar(x, (3,17))
    20.0

    Nddofr   Z
fill_value)	r   astypefloatvarr   Zfilledro   rt   Znanvar)rz   r   r   r   r   r   Zamnanrd   rd   rg   r!   %  s    -
r!   Tc                 C   sl   t | |\} }t| |df|df}t||\}}|rF|dkrFt|}tj||j}|jdkrh|d S |S )ak  Compute the trimmed minimum.

    This function finds the miminum value of an array `a` along the
    specified axis, but only considering values greater than a specified
    lower limit.

    Parameters
    ----------
    a : array_like
        Array of values.
    lowerlimit : None or float, optional
        Values in the input array less than the given limit will be ignored.
        When lowerlimit is None, then all values are used. The default value
        is None.
    axis : int or None, optional
        Axis along which to operate. Default is 0. If None, compute over the
        whole array `a`.
    inclusive : {True, False}, optional
        This flag determines whether values exactly equal to the lower limit
        are included.  The default value is True.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

          * 'propagate': returns nan
          * 'raise': throws an error
          * 'omit': performs the calculations ignoring nan values

    Returns
    -------
    tmin : float, int or ndarray
        Trimmed minimum.

    Examples
    --------
    >>> from scipy import stats
    >>> x = np.arange(20)
    >>> stats.tmin(x)
    0

    >>> stats.tmin(x, 13)
    13

    >>> stats.tmin(x, 13, inclusive=False)
    14

    NFrc   r   rd   )	r   r   r}   r   r   minimumreducedatar   )rz   
lowerlimitr   r   r{   r   r|   resrd   rd   rg   r"   [  s    0

r"   c                 C   sl   t | |\} }t| d|fd|f}t||\}}|rF|dkrFt|}tj||j}|jdkrh|d S |S )a]  Compute the trimmed maximum.

    This function computes the maximum value of an array along a given axis,
    while ignoring values larger than a specified upper limit.

    Parameters
    ----------
    a : array_like
        Array of values.
    upperlimit : None or float, optional
        Values in the input array greater than the given limit will be ignored.
        When upperlimit is None, then all values are used. The default value
        is None.
    axis : int or None, optional
        Axis along which to operate. Default is 0. If None, compute over the
        whole array `a`.
    inclusive : {True, False}, optional
        This flag determines whether values exactly equal to the upper limit
        are included.  The default value is True.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

          * 'propagate': returns nan
          * 'raise': throws an error
          * 'omit': performs the calculations ignoring nan values

    Returns
    -------
    tmax : float, int or ndarray
        Trimmed maximum.

    Examples
    --------
    >>> from scipy import stats
    >>> x = np.arange(20)
    >>> stats.tmax(x)
    19

    >>> stats.tmax(x, 13)
    13

    >>> stats.tmax(x, 13, inclusive=False)
    12

    NFrc   r   rd   )	r   r   r}   r   r   r   r   r   r   )rz   Z
upperlimitr   r   r{   r   r|   r   rd   rd   rg   r#     s    /

r#   c                 C   s   t t| ||||S )a  Compute the trimmed sample standard deviation.

    This function finds the sample standard deviation of given values,
    ignoring values outside the given `limits`.

    Parameters
    ----------
    a : array_like
        Array of values.
    limits : None or (lower limit, upper limit), optional
        Values in the input array less than the lower limit or greater than the
        upper limit will be ignored. When limits is None, then all values are
        used. Either of the limit values in the tuple can also be None
        representing a half-open interval.  The default value is None.
    inclusive : (bool, bool), optional
        A tuple consisting of the (lower flag, upper flag).  These flags
        determine whether values exactly equal to the lower or upper limits
        are included.  The default value is (True, True).
    axis : int or None, optional
        Axis along which to operate. Default is 0. If None, compute over the
        whole array `a`.
    ddof : int, optional
        Delta degrees of freedom.  Default is 1.

    Returns
    -------
    tstd : float
        Trimmed sample standard deviation.

    Notes
    -----
    `tstd` computes the unbiased sample standard deviation, i.e. it uses a
    correction factor ``n / (n - 1)``.

    Examples
    --------
    >>> from scipy import stats
    >>> x = np.arange(20)
    >>> stats.tstd(x)
    5.9160797830996161
    >>> stats.tstd(x, (3,17))
    4.4721359549995796

    )ro   sqrtr!   )rz   r   r   r   r   rd   rd   rg   r$     s    -r$   c                 C   sd   t |  } |du r.| j|dt | j S t| ||}t t jj|||d}|t |	  S )a  Compute the trimmed standard error of the mean.

    This function finds the standard error of the mean for given
    values, ignoring values outside the given `limits`.

    Parameters
    ----------
    a : array_like
        Array of values.
    limits : None or (lower limit, upper limit), optional
        Values in the input array less than the lower limit or greater than the
        upper limit will be ignored. When limits is None, then all values are
        used. Either of the limit values in the tuple can also be None
        representing a half-open interval.  The default value is None.
    inclusive : (bool, bool), optional
        A tuple consisting of the (lower flag, upper flag).  These flags
        determine whether values exactly equal to the lower or upper limits
        are included.  The default value is (True, True).
    axis : int or None, optional
        Axis along which to operate. Default is 0. If None, compute over the
        whole array `a`.
    ddof : int, optional
        Delta degrees of freedom.  Default is 1.

    Returns
    -------
    tsem : float
        Trimmed standard error of the mean.

    Notes
    -----
    `tsem` uses unbiased sample standard deviation, i.e. it uses a
    correction factor ``n / (n - 1)``.

    Examples
    --------
    >>> from scipy import stats
    >>> x = np.arange(20)
    >>> stats.tsem(x)
    1.3228756555322954
    >>> stats.tsem(x, (3,17))
    1.1547005383792515

    Nr   r   )
ro   r   rv   stdr   r   r   r   r   r   )rz   r   r   r   r   r   sdrd   rd   rg   r%     s    -r%   c           	         s   t  \ t |\}}|r@|dkr@t  t |S  jdkrt j}|=  j	j
dv rn j	jntj}t|r|nt|g| }t|dkr|tjS tj|tj|dS t|s jdd fdd|D }t|S t |S d	S )
a#  Calculate the nth moment about the mean for a sample.

    A moment is a specific quantitative measure of the shape of a set of
    points. It is often used to calculate coefficients of skewness and kurtosis
    due to its close relationship with them.

    Parameters
    ----------
    a : array_like
       Input array.
    moment : int or array_like of ints, optional
       Order of central moment that is returned. Default is 1.
    axis : int or None, optional
       Axis along which the central moment is computed. Default is 0.
       If None, compute over the whole array `a`.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

          * 'propagate': returns nan
          * 'raise': throws an error
          * 'omit': performs the calculations ignoring nan values

    Returns
    -------
    n-th central moment : ndarray or float
       The appropriate moment along the given axis or over all values if axis
       is None. The denominator for the moment calculation is the number of
       observations, no degrees of freedom correction is done.

    See Also
    --------
    kurtosis, skew, describe

    Notes
    -----
    The k-th central moment of a data sample is:

    .. math::

        m_k = \frac{1}{n} \sum_{i = 1}^n (x_i - \bar{x})^k

    Where n is the number of samples and x-bar is the mean. This function uses
    exponentiation by squares [1]_ for efficiency.

    References
    ----------
    .. [1] https://eli.thegreenplace.net/2009/03/21/efficient-integer-exponentiation-algorithms

    Examples
    --------
    >>> from scipy.stats import moment
    >>> moment([1, 2, 3, 4, 5], moment=1)
    0.0
    >>> moment([1, 2, 3, 4, 5], moment=2)
    2.0

    rc   r   fcr   Tr   c                    s   g | ]}t  |d qS )r   )_momentre   irz   r   r   rd   rg   
<listcomp>  ri   zmoment.<locals>.<listcomp>N)r   r}   r   r   r   r&   r   r   r   r   kindtypero   float64isscalarr   rt   fullr   r   r   )	rz   r&   r   r{   r|   Zmoment_shaper   Z	out_shapeZmmntrd   r   rg   r&   A  s(    ;





r&   r   c                C   s^  t |t | dkr td|dks0|dkrt| j}||= | jjdv rT| jjnt j	}t
|dkrz||dkrtdndS |dkrt j||dS t j||dS n|g}|}|dkr|d r|d d }n|d }|| q|d u r| j|d	d
n|}| | }|d dkr| }	n|d }	|dd d D ] }
|	d }	|
d r,|	|9 }	q,t |	|S d S )Nr   z&All moment parameters must be integersr   r   r           r      Tr   r   )ro   absroundrm   r   r   r   r   r   r   r   onesr   r   r   copy)rz   r&   r   r   r   r   Zn_listZ	current_nZa_zero_meanrf   r   rd   rd   rg   r     s8    


r   c                 C   sX   t | |\} }t| |\}}|r@|dkr@t| } t| ||S | j||d| | S )a  Compute the coefficient of variation.

    The coefficient of variation is the standard deviation divided by the
    mean.  This function is equivalent to::

        np.std(x, axis=axis, ddof=ddof) / np.mean(x)

    The default for ``ddof`` is 0, but many definitions of the coefficient
    of variation use the square root of the unbiased sample variance
    for the sample standard deviation, which corresponds to ``ddof=1``.

    Parameters
    ----------
    a : array_like
        Input array.
    axis : int or None, optional
        Axis along which to calculate the coefficient of variation. Default
        is 0. If None, compute over the whole array `a`.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

        * 'propagate': returns nan
        * 'raise': throws an error
        * 'omit': performs the calculations ignoring nan values

    ddof : int, optional
        Delta degrees of freedom.  Default is 0.

    Returns
    -------
    variation : ndarray
        The calculated variation along the requested axis.

    References
    ----------
    .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
       Probability and Statistics Tables and Formulae. Chapman & Hall: New
       York. 2000.

    Examples
    --------
    >>> from scipy.stats import variation
    >>> variation([1, 2, 3, 4, 5])
    0.47140452079103173

    rc   r   )r   r}   r   r   r   r'   r   r   )rz   r   r{   r   r|   rd   rd   rg   r'     s    0
r'   c                 C   s\  t | |\} }| j| }t| |\}}|rJ|dkrJt| } t| ||S | j|dd}t| d||d}t| d||d}t	j
ddF |t	|jj|| d k}	t	|	d	||d
  }
W d   n1 s0    Y  |sD|	 |dk@ }| rDt	||}t	||}t	|d | |d  | |d
  }t	|
|| |
jd	krX|
 S |
S )a  Compute the sample skewness of a data set.

    For normally distributed data, the skewness should be about zero. For
    unimodal continuous distributions, a skewness value greater than zero means
    that there is more weight in the right tail of the distribution. The
    function `skewtest` can be used to determine if the skewness value
    is close enough to zero, statistically speaking.

    Parameters
    ----------
    a : ndarray
        Input array.
    axis : int or None, optional
        Axis along which skewness is calculated. Default is 0.
        If None, compute over the whole array `a`.
    bias : bool, optional
        If False, then the calculations are corrected for statistical bias.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

          * 'propagate': returns nan
          * 'raise': throws an error
          * 'omit': performs the calculations ignoring nan values

    Returns
    -------
    skewness : ndarray
        The skewness of values along an axis, returning 0 where all values are
        equal.

    Notes
    -----
    The sample skewness is computed as the Fisher-Pearson coefficient
    of skewness, i.e.

    .. math::

        g_1=\frac{m_3}{m_2^{3/2}}

    where

    .. math::

        m_i=\frac{1}{N}\sum_{n=1}^N(x[n]-\bar{x})^i

    is the biased sample :math:`i\texttt{th}` central moment, and
    :math:`\bar{x}` is
    the sample mean.  If ``bias`` is False, the calculations are
    corrected for bias and the value computed is the adjusted
    Fisher-Pearson standardized moment coefficient, i.e.

    .. math::

        G_1=\frac{k_3}{k_2^{3/2}}=
            \frac{\sqrt{N(N-1)}}{N-2}\frac{m_3}{m_2^{3/2}}.

    References
    ----------
    .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
       Probability and Statistics Tables and Formulae. Chapman & Hall: New
       York. 2000.
       Section 2.2.24.1

    Examples
    --------
    >>> from scipy.stats import skew
    >>> skew([1, 2, 3, 4, 5])
    0.0
    >>> skew([2, 8, 0, 4, 1, 9, 9, 0])
    0.2650554122698573

    rc   Tr   r   r      rj   r   r         ?Nr          @)r   r   r}   r   r   r   r(   r   r   ro   rp   finfor   
resolutionsqueezer   anyextractr   placer   item)rz   r   biasr{   r   r|   r   m2Zm3zeror   can_correctnvalrd   rd   rg   r(      s,    J

 4
&r(   c                 C   s  t | |\} }t| |\}}|rB|dkrBt| } t| |||S | j| }| j|dd}t| d||d}t| d||d}	t	j
ddF |t	|jj|| d k}
t	|
d	|	|d
  }W d   n1 s0    Y  |s`|
 |dk@ }| r`t	||}t	||	}	d|d  |d  |d d |	 |d
  d|d d
    }t	|||d  |jd	krt| }|r|d S |S )a  Compute the kurtosis (Fisher or Pearson) of a dataset.

    Kurtosis is the fourth central moment divided by the square of the
    variance. If Fisher's definition is used, then 3.0 is subtracted from
    the result to give 0.0 for a normal distribution.

    If bias is False then the kurtosis is calculated using k statistics to
    eliminate bias coming from biased moment estimators

    Use `kurtosistest` to see if result is close enough to normal.

    Parameters
    ----------
    a : array
        Data for which the kurtosis is calculated.
    axis : int or None, optional
        Axis along which the kurtosis is calculated. Default is 0.
        If None, compute over the whole array `a`.
    fisher : bool, optional
        If True, Fisher's definition is used (normal ==> 0.0). If False,
        Pearson's definition is used (normal ==> 3.0).
    bias : bool, optional
        If False, then the calculations are corrected for statistical bias.
    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
    -------
    kurtosis : array
        The kurtosis of values along an axis. If all values are equal,
        return -3 for Fisher's definition and 0 for Pearson's definition.

    References
    ----------
    .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
       Probability and Statistics Tables and Formulae. Chapman & Hall: New
       York. 2000.

    Examples
    --------
    In Fisher's definiton, the kurtosis of the normal distribution is zero.
    In the following example, the kurtosis is close to zero, because it was
    calculated from the dataset, not from the continuous distribution.

    >>> from scipy.stats import norm, kurtosis
    >>> data = norm.rvs(size=1000, random_state=3)
    >>> kurtosis(data)
    -0.06928694200380558

    The distribution with a higher kurtosis has a heavier tail.
    The zero valued kurtosis of the normal distribution in Fisher's definition
    can serve as a reference point.

    >>> import matplotlib.pyplot as plt
    >>> import scipy.stats as stats
    >>> from scipy.stats import kurtosis

    >>> x = np.linspace(-5, 5, 100)
    >>> ax = plt.subplot()
    >>> distnames = ['laplace', 'norm', 'uniform']

    >>> for distname in distnames:
    ...     if distname == 'uniform':
    ...         dist = getattr(stats, distname)(loc=-2, scale=4)
    ...     else:
    ...         dist = getattr(stats, distname)
    ...     data = dist.rvs(size=1000)
    ...     kur = kurtosis(data, fisher=True)
    ...     y = dist.pdf(x)
    ...     ax.plot(x, y, label="{}, {}".format(distname, round(kur, 3)))
    ...     ax.legend()

    The Laplace distribution has a heavier tail than the normal distribution.
    The uniform distribution (which has negative kurtosis) has the thinnest
    tail.

    rc   Tr   r   r      rj   r   r   r   Nr   r   r         @)r   r}   r   r   r   r)   r   r   r   ro   rp   r   r   r   r   r   r   r   r   r   r   )rz   r   fisherr   r{   r|   r   r   r   Zm4r   r   r   r   rd   rd   rg   r)   g  s,    P

 4
<r)   DescribeResult)nobsZminmaxr   Zvarianceskewnessr)   c                 C   s   t | |\} }t| |\}}|rB|dkrBt| } t| |||S | jdkrTtd| j| }t	j
| |dt	j| |df}t	j| |d}t	j| ||d}	t| ||d}
t| ||d}t||||	|
|S )a\	  Compute several descriptive statistics of the passed array.

    Parameters
    ----------
    a : array_like
        Input data.
    axis : int or None, optional
        Axis along which statistics are calculated. Default is 0.
        If None, compute over the whole array `a`.
    ddof : int, optional
        Delta degrees of freedom (only for variance).  Default is 1.
    bias : bool, optional
        If False, then the skewness and kurtosis calculations are corrected
        for statistical bias.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

        * 'propagate': returns nan
        * 'raise': throws an error
        * 'omit': performs the calculations ignoring nan values

    Returns
    -------
    nobs : int or ndarray of ints
        Number of observations (length of data along `axis`).
        When 'omit' is chosen as nan_policy, the length along each axis
        slice is counted separately.
    minmax: tuple of ndarrays or floats
        Minimum and maximum value of `a` along the given axis.
    mean : ndarray or float
        Arithmetic mean of `a` along the given axis.
    variance : ndarray or float
        Unbiased variance of `a` along the given axis; denominator is number
        of observations minus one.
    skewness : ndarray or float
        Skewness of `a` along the given axis, based on moment calculations
        with denominator equal to the number of observations, i.e. no degrees
        of freedom correction.
    kurtosis : ndarray or float
        Kurtosis (Fisher) of `a` along the given axis.  The kurtosis is
        normalized so that it is zero for the normal distribution.  No
        degrees of freedom are used.

    See Also
    --------
    skew, kurtosis

    Examples
    --------
    >>> from scipy import stats
    >>> a = np.arange(10)
    >>> stats.describe(a)
    DescribeResult(nobs=10, minmax=(0, 9), mean=4.5,
                   variance=9.166666666666666, skewness=0.0,
                   kurtosis=-1.2242424242424244)
    >>> b = [[1, 2], [3, 4]]
    >>> stats.describe(b)
    DescribeResult(nobs=2, minmax=(array([1, 2]), array([3, 4])),
                   mean=array([2., 3.]), variance=array([2., 2.]),
                   skewness=array([0., 0.]), kurtosis=array([-2., -2.]))

    rc   r   zThe input must not be empty.r   r   r   )r   )r   r}   r   r   r   r*   r   rm   r   ro   minr   r   r   r(   r)   r  )rz   r   r   r   r{   r|   r   mmmvskZkurtrd   rd   rg   r*     s    @


r*   c                 C   sn   |dkrt j| }n>|dkr,t j| }n(|dkrLdt jt|  }ntd| jdkrf| d } | |fS )z5Common code between all the normality-test functions.lessgreater	two-sidedr   4alternative must be 'less', 'greater' or 'two-sided'r   rd   )r   normcdfsfro   r   rm   r   )zalternativeprobrd   rd   rg   _normtest_finish2  s    
r  SkewtestResult)	statisticpvaluer  c                 C   s  t | |\} }t| |\}}|rN|dkrN|dkr8tdt| } t| |S |du rdt| } d}t	| |}| j
| }|dk rtdt| |t|d |d	  d
|d    }d|d d|  d  |d  |d	  |d |d  |d  |d   }dtd|d   }	dtdt|	  }
td|	d  }t|dkd|}|
t|| t|| d d   }tt|| S )a
  Test whether the skew is different from the normal distribution.

    This function tests the null hypothesis that the skewness of
    the population that the sample was drawn from is the same
    as that of a corresponding normal distribution.

    Parameters
    ----------
    a : array
        The data to be tested.
    axis : int or None, optional
       Axis along which statistics are calculated. Default is 0.
       If None, compute over the whole array `a`.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

        * 'propagate': returns nan
        * 'raise': throws an error
        * 'omit': performs the calculations ignoring nan values

    alternative : {'two-sided', 'less', 'greater'}, optional
        Defines the alternative hypothesis. Default is 'two-sided'.
        The following options are available:

        * 'two-sided': the skewness of the distribution underlying the sample
          is different from that of the normal distribution (i.e. 0)
        * 'less': the skewness of the distribution underlying the sample
          is less than that of the normal distribution
        * 'greater': the skewness of the distribution underlying the sample
          is greater than that of the normal distribution

        .. versionadded:: 1.7.0

    Returns
    -------
    statistic : float
        The computed z-score for this test.
    pvalue : float
        The p-value for the hypothesis test.

    Notes
    -----
    The sample size must be at least 8.

    References
    ----------
    .. [1] R. B. D'Agostino, A. J. Belanger and R. B. D'Agostino Jr.,
            "A suggestion for using powerful and informative tests of
            normality", American Statistician 44, pp. 316-321, 1990.

    Examples
    --------
    >>> from scipy.stats import skewtest
    >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8])
    SkewtestResult(statistic=1.0108048609177787, pvalue=0.3121098361421897)
    >>> skewtest([2, 8, 0, 4, 1, 9, 9, 0])
    SkewtestResult(statistic=0.44626385374196975, pvalue=0.6554066631275459)
    >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8000])
    SkewtestResult(statistic=3.571773510360407, pvalue=0.0003545719905823133)
    >>> skewtest([100, 100, 100, 100, 100, 100, 100, 101])
    SkewtestResult(statistic=3.5717766638478072, pvalue=0.000354567720281634)
    >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8], alternative='less')
    SkewtestResult(statistic=1.0108048609177787, pvalue=0.8439450819289052)
    >>> skewtest([1, 2, 3, 4, 5, 6, 7, 8], alternative='greater')
    SkewtestResult(statistic=1.0108048609177787, pvalue=0.15605491807109484)

    rc   r  jnan-containing/masked inputs with nan_policy='omit' are currently not supported by one-sided alternatives.Nr      zFskewtest is not valid with less than 8 samples; %i samples were given.r   r         @r   r      F   r         	   r         ?)r   r}   rm   r   r   r   r+   ro   rv   r(   r   r   mathr   r   r   r  r  )rz   r   r{   r  r|   b2r   yZbeta2ZW2deltaalphaZrd   rd   rg   r+   G  s8    E



&&(r+   KurtosistestResultc                 C   s   t | |\} }t| |\}}|rN|dkrN|dkr8tdt| } t| |S | j| }|dk rptdt| |dk rt	
dt|  t| |dd	}d
|d  |d  }d| |d  |d  |d |d  |d  |d   }|| t| }	d|| d|  d  |d |d   td|d  |d  ||d  |d    }
dd|
 d|
 tdd|
d      }ddd|   }d|	td|d    }t|t|dktjtdd|  t| d }t|dkrd}t	
|t || tdd|   }tt|| S )a	  Test whether a dataset has normal kurtosis.

    This function tests the null hypothesis that the kurtosis
    of the population from which the sample was drawn is that
    of the normal distribution.

    Parameters
    ----------
    a : array
        Array of the sample data.
    axis : int or None, optional
       Axis along which to compute test. Default is 0. If None,
       compute over the whole array `a`.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

        * 'propagate': returns nan
        * 'raise': throws an error
        * 'omit': performs the calculations ignoring nan values

    alternative : {'two-sided', 'less', 'greater'}, optional
        Defines the alternative hypothesis.
        The following options are available (default is 'two-sided'):

        * 'two-sided': the kurtosis of the distribution underlying the sample
          is different from that of the normal distribution
        * 'less': the kurtosis of the distribution underlying the sample
          is less than that of the normal distribution
        * 'greater': the kurtosis of the distribution underlying the sample
          is greater than that of the normal distribution

        .. versionadded:: 1.7.0

    Returns
    -------
    statistic : float
        The computed z-score for this test.
    pvalue : float
        The p-value for the hypothesis test.

    Notes
    -----
    Valid only for n>20. This function uses the method described in [1]_.

    References
    ----------
    .. [1] see e.g. F. J. Anscombe, W. J. Glynn, "Distribution of the kurtosis
       statistic b2 for normal samples", Biometrika, vol. 70, pp. 227-234, 1983.

    Examples
    --------
    >>> from scipy.stats import kurtosistest
    >>> kurtosistest(list(range(20)))
    KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.08804338332528348)
    >>> kurtosistest(list(range(20)), alternative='less')
    KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.04402169166264174)
    >>> kurtosistest(list(range(20)), alternative='greater')
    KurtosistestResult(statistic=-1.7058104152122062, pvalue=0.9559783083373583)

    >>> rng = np.random.default_rng()
    >>> s = rng.normal(0, 1, 1000)
    >>> kurtosistest(s)
    KurtosistestResult(statistic=-1.475047944490622, pvalue=0.14019965402996987)

    rc   r  r  r  zJkurtosistest requires at least 5 observations; %i observations were given.   z=kurtosistest only valid for n>=20 ... continuing anyway, n=%iF)r   r   r   g      8@r   r   r   r  r  r  g       @r         @g      "@r   gUUUUUU?r   z\Test statistic not defined in some cases due to division by zero. Return nan in that case...)r   r}   rm   r   r   r   r,   r   r   rw   rx   r)   ro   r   signr   rt   powerr   r   ry   r'  r  )rz   r   r{   r  r|   r   r"  EZvarb2xZ	sqrtbeta1AZterm1denomZterm2msgr&  rd   rd   rg   r,     sH    C

8<*r,   NormaltestResultc                 C   s~   t | |\} }t| |\}}|r>|dkr>t| } t| |S t| |\}}t| |\}}|| ||  }t|t	j
|dS )a  Test whether a sample differs from a normal distribution.

    This function tests the null hypothesis that a sample comes
    from a normal distribution.  It is based on D'Agostino and
    Pearson's [1]_, [2]_ test that combines skew and kurtosis to
    produce an omnibus test of normality.

    Parameters
    ----------
    a : array_like
        The array containing the sample to be tested.
    axis : int or None, optional
        Axis along which to compute test. Default is 0. If None,
        compute over the whole array `a`.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

          * 'propagate': returns nan
          * 'raise': throws an error
          * 'omit': performs the calculations ignoring nan values

    Returns
    -------
    statistic : float or array
        ``s^2 + k^2``, where ``s`` is the z-score returned by `skewtest` and
        ``k`` is the z-score returned by `kurtosistest`.
    pvalue : float or array
       A 2-sided chi squared probability for the hypothesis test.

    References
    ----------
    .. [1] D'Agostino, R. B. (1971), "An omnibus test of normality for
           moderate and large sample size", Biometrika, 58, 341-348

    .. [2] D'Agostino, R. and Pearson, E. S. (1973), "Tests for departure from
           normality", Biometrika, 60, 613-622

    Examples
    --------
    >>> from scipy import stats
    >>> rng = np.random.default_rng()
    >>> pts = 1000
    >>> a = rng.normal(0, 1, size=pts)
    >>> b = rng.normal(2, 1, size=pts)
    >>> x = np.concatenate((a, b))
    >>> k2, p = stats.normaltest(x)
    >>> alpha = 1e-3
    >>> print("p = {:g}".format(p))
    p = 8.4713e-19
    >>> if p < alpha:  # null hypothesis: x comes from a normal distribution
    ...     print("The null hypothesis can be rejected")
    ... else:
    ...     print("The null hypothesis cannot be rejected")
    The null hypothesis can be rejected

    rc   r   )r   r}   r   r   r   r-   r+   r,   r1  r   chi2r  )rz   r   r{   r|   rf   _kZk2rd   rd   rg   r-   #  s    :
r-   Jarque_beraResultc                 C   s   t | } | j}|dkr td|  }| | }d| t |d  d| t |d  d  }d| t |d  d| t |d  d  }|d |d |d d d   }dtj|d }t	||S )	a  Perform the Jarque-Bera goodness of fit test on sample data.

    The Jarque-Bera test tests whether the sample data has the skewness and
    kurtosis matching a normal distribution.

    Note that this test only works for a large enough number of data samples
    (>2000) as the test statistic asymptotically has a Chi-squared distribution
    with 2 degrees of freedom.

    Parameters
    ----------
    x : array_like
        Observations of a random variable.

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

    References
    ----------
    .. [1] Jarque, C. and Bera, A. (1980) "Efficient tests for normality,
           homoscedasticity and serial independence of regression residuals",
           6 Econometric Letters 255-259.

    Examples
    --------
    >>> from scipy import stats
    >>> rng = np.random.default_rng()
    >>> x = rng.normal(0, 1, 100000)
    >>> jarque_bera_test = stats.jarque_bera(x)
    >>> jarque_bera_test
    Jarque_beraResult(statistic=3.3415184718131554, pvalue=0.18810419594996775)
    >>> jarque_bera_test.statistic
    3.3415184718131554
    >>> jarque_bera_test.pvalue
    0.18810419594996775

    r   z%At least one observation is required.r   r   r   r   r      )
ro   r   r   rm   r   rr   r   r2  r  r5  )r-  r   muZdiffxr  r)   Zjb_valueprd   rd   rg   r.   o  s    *
00 r.   zr`itemfreq` is deprecated and will be removed in a future version. Use instead `np.unique(..., return_counts=True)`)messagec                 C   s,   t j| dd\}}t |}t ||gjS )a  
Return a 2-D array of item frequencies.

Parameters
----------
a : (N,) array_like
    Input array.

Returns
-------
itemfreq : (K, 2) ndarray
    A 2-D frequency table.  Column 1 contains sorted, unique values from
    `a`, column 2 contains their respective counts.

Examples
--------
>>> from scipy import stats
>>> a = np.array([1, 1, 5, 0, 1, 2, 2, 0, 1, 4])
>>> stats.itemfreq(a)
array([[ 0.,  2.],
       [ 1.,  4.],
       [ 2.,  2.],
       [ 4.,  1.],
       [ 5.,  1.]])
>>> np.bincount(a)
array([2, 4, 2, 0, 1, 1])

>>> stats.itemfreq(a/10.)
array([[ 0. ,  2. ],
       [ 0.1,  4. ],
       [ 0.2,  2. ],
       [ 0.4,  1. ],
       [ 0.5,  1. ]])

T)Zreturn_inverse)ro   r   bincountr   T)rz   itemsinvfreqrd   rd   rg   r/     s    '
r/   rd   fractionc                 C   s   t | } | jdkr@t |r$t jS t jt |jt jt jdS |r`| |d | k| |d k@  } t j| |d}|du rzd}t	||||S )a  Calculate the score at a given percentile of the input sequence.

    For example, the score at `per=50` is the median. If the desired quantile
    lies between two data points, we interpolate between them, according to
    the value of `interpolation`. If the parameter `limit` is provided, it
    should be a tuple (lower, upper) of two values.

    Parameters
    ----------
    a : array_like
        A 1-D array of values from which to extract score.
    per : array_like
        Percentile(s) at which to extract score.  Values should be in range
        [0,100].
    limit : tuple, optional
        Tuple of two scalars, the lower and upper limits within which to
        compute the percentile. Values of `a` outside
        this (closed) interval will be ignored.
    interpolation_method : {'fraction', 'lower', 'higher'}, optional
        Specifies the interpolation method to use,
        when the desired quantile lies between two data points `i` and `j`
        The following options are available (default is 'fraction'):

          * 'fraction': ``i + (j - i) * fraction`` where ``fraction`` is the
            fractional part of the index surrounded by ``i`` and ``j``
          * 'lower': ``i``
          * 'higher': ``j``

    axis : int, optional
        Axis along which the percentiles are computed. Default is None. If
        None, compute over the whole array `a`.

    Returns
    -------
    score : float or ndarray
        Score at percentile(s).

    See Also
    --------
    percentileofscore, numpy.percentile

    Notes
    -----
    This function will become obsolete in the future.
    For NumPy 1.9 and higher, `numpy.percentile` provides all the functionality
    that `scoreatpercentile` provides.  And it's significantly faster.
    Therefore it's recommended to use `numpy.percentile` for users that have
    numpy >= 1.9.

    Examples
    --------
    >>> from scipy import stats
    >>> a = np.arange(100)
    >>> stats.scoreatpercentile(a, 50)
    49.5

    r   r   r   r   N)
ro   r   r   r   rt   r   r   r   sort_compute_qth_percentile)rz   perlimitinterpolation_methodr   sorted_rd   rd   rg   r0     s    =


r0   c                    s^  t |s* fdd|D }t |S d|  kr>dksHn tdtd gj }|d j  d  }t||krdkrtt |}n*d	krtt 	|}nd
krntdt|}||krt||d | < td}d}	nRt||d | < |d }
t|
| || gt
}dgj }d| < ||_| }	t jjt| |  d|	 S )Nc                    s   g | ]}t | qS rd   )rA  r   r   rD  rE  rd   rg   r   +  s   z+_compute_qth_percentile.<locals>.<listcomp>r   d   z(percentile must be in the range [0, 100]      Y@r   lowerZhigherr?  z@interpolation_method can only be 'fraction', 'lower' or 'higher'r   r   r   )ro   r   r   rm   slicer   r   r   floorceilr   rr   addr   r   )rE  rB  rD  r   r   Zindexeridxr   r   ZsumvaljZwshaperd   rF  rg   rA  )  s<    

rA  rankc                 C   s   t |rt jS t | } t| }|dkr.dS |dkrvt | |k }t | |k}|| ||krddnd d | }|S |dkrt | |k | d S |dkrt | |k| d S |d	krt | |k t | |k | d
 }|S tddS )a  Compute the percentile rank of a score relative to a list of scores.

    A `percentileofscore` of, for example, 80% means that 80% of the
    scores in `a` are below the given score. In the case of gaps or
    ties, the exact definition depends on the optional keyword, `kind`.

    Parameters
    ----------
    a : array_like
        Array of scores to which `score` is compared.
    score : int or float
        Score that is compared to the elements in `a`.
    kind : {'rank', 'weak', 'strict', 'mean'}, optional
        Specifies the interpretation of the resulting score.
        The following options are available (default is 'rank'):

          * 'rank': Average percentage ranking of score.  In case of multiple
            matches, average the percentage rankings of all matching scores.
          * 'weak': This kind corresponds to the definition of a cumulative
            distribution function.  A percentileofscore of 80% means that 80%
            of values are less than or equal to the provided score.
          * 'strict': Similar to "weak", except that only values that are
            strictly less than the given score are counted.
          * 'mean': The average of the "weak" and "strict" scores, often used
            in testing.  See https://en.wikipedia.org/wiki/Percentile_rank

    Returns
    -------
    pcos : float
        Percentile-position of score (0-100) relative to `a`.

    See Also
    --------
    numpy.percentile

    Examples
    --------
    Three-quarters of the given values lie below a given score:

    >>> from scipy import stats
    >>> stats.percentileofscore([1, 2, 3, 4], 3)
    75.0

    With multiple matches, note how the scores of the two matches, 0.6
    and 0.8 respectively, are averaged:

    >>> stats.percentileofscore([1, 2, 3, 3, 4], 3)
    70.0

    Only 2/5 values are strictly less than 3:

    >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='strict')
    40.0

    But 4/5 values are less than or equal to 3:

    >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='weak')
    80.0

    The average between the weak and the strict scores is:

    >>> stats.percentileofscore([1, 2, 3, 3, 4], 3, kind='mean')
    60.0

    r   rH  rP  r   g      I@strictrG  Zweakr   2   z3kind can only be 'rank', 'strict', 'weak' or 'mean'N)ro   rq   rt   r   r   Zcount_nonzerorm   )rz   r   r   r   leftrightpctrd   rd   rg   r1   T  s2    B

 r1   HistogramResult)r   r   binsizeextrapoints
   Fc                    s   t | }  du rV| jdkr"d n4|  }|  }|| d|d   }|| || f t j| | |d\}}	t j|td}|	d |	d  }
t fd	d
| D }|dkr|rt	
d|  t| d |
|S )a  Create a histogram.

    Separate the range into several bins and return the number of instances
    in each bin.

    Parameters
    ----------
    a : array_like
        Array of scores which will be put into bins.
    numbins : int, optional
        The number of bins to use for the histogram. Default is 10.
    defaultlimits : tuple (lower, upper), optional
        The lower and upper values for the range of the histogram.
        If no value is given, a range slightly larger than the range of the
        values in a is used. Specifically ``(a.min() - s, a.max() + s)``,
        where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
    weights : array_like, optional
        The weights for each value in `a`. Default is None, which gives each
        value a weight of 1.0
    printextras : bool, optional
        If True, if there are extra points (i.e. the points that fall outside
        the bin limits) a warning is raised saying how many of those points
        there are.  Default is False.

    Returns
    -------
    count : ndarray
        Number of points (or sum of weights) in each bin.
    lowerlimit : float
        Lowest value of histogram, the lower limit of the first bin.
    binsize : float
        The size of the bins (all bins have the same size).
    extrapoints : int
        The number of points outside the range of the histogram.

    See Also
    --------
    numpy.histogram

    Notes
    -----
    This histogram is based on numpy's histogram but has a larger range by
    default if default limits is not set.

    Nr   r   r   r   r   )Zbinsr   r   r   r   c                    s(   g | ] } d  |ks | d kr|qS rZ  rd   )re   r  defaultlimitsrd   rg   r     s   z_histogram.<locals>.<listcomp>z)Points outside given histogram range = %s)ro   rv   r   r  r   Z	histogramr   r   r   rw   rx   rV  )rz   numbinsr\  r   ZprintextrasZdata_minZdata_maxrf   histZ	bin_edgesrW  rX  rd   r[  rg   
_histogram  s&    /



r_  CumfreqResult)Zcumcountr   rW  rX  c           	      C   s8   t | |||d\}}}}tj|d dd}t||||S )a  Return a cumulative frequency histogram, using the histogram function.

    A cumulative histogram is a mapping that counts the cumulative number of
    observations in all of the bins up to the specified bin.

    Parameters
    ----------
    a : array_like
        Input array.
    numbins : int, optional
        The number of bins to use for the histogram. Default is 10.
    defaultreallimits : tuple (lower, upper), optional
        The lower and upper values for the range of the histogram.
        If no value is given, a range slightly larger than the range of the
        values in `a` is used. Specifically ``(a.min() - s, a.max() + s)``,
        where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
    weights : array_like, optional
        The weights for each value in `a`. Default is None, which gives each
        value a weight of 1.0

    Returns
    -------
    cumcount : ndarray
        Binned values of cumulative frequency.
    lowerlimit : float
        Lower real limit
    binsize : float
        Width of each bin.
    extrapoints : int
        Extra points.

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> from numpy.random import default_rng
    >>> from scipy import stats
    >>> rng = default_rng()
    >>> x = [1, 4, 2, 1, 3, 1]
    >>> res = stats.cumfreq(x, numbins=4, defaultreallimits=(1.5, 5))
    >>> res.cumcount
    array([ 1.,  2.,  3.,  3.])
    >>> res.extrapoints
    3

    Create a normal distribution with 1000 random values

    >>> samples = stats.norm.rvs(size=1000, random_state=rng)

    Calculate cumulative frequencies

    >>> res = stats.cumfreq(samples, numbins=25)

    Calculate space of values for x

    >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.cumcount.size,
    ...                                  res.cumcount.size)

    Plot histogram and cumulative histogram

    >>> fig = plt.figure(figsize=(10, 4))
    >>> ax1 = fig.add_subplot(1, 2, 1)
    >>> ax2 = fig.add_subplot(1, 2, 2)
    >>> ax1.hist(samples, bins=25)
    >>> ax1.set_title('Histogram')
    >>> ax2.bar(x, res.cumcount, width=res.binsize)
    >>> ax2.set_title('Cumulative histogram')
    >>> ax2.set_xlim([x.min(), x.max()])

    >>> plt.show()

    r   r   r   r   )r_  ro   cumsumr`  )	rz   r]  defaultreallimitsr   hlr   eZcumhistrd   rd   rg   r2     s    Hr2   RelfreqResult)Z	frequencyr   rW  rX  c                 C   s>   t | } t| |||d\}}}}|| jd  }t||||S )a  Return a relative frequency histogram, using the histogram function.

    A relative frequency  histogram is a mapping of the number of
    observations in each of the bins relative to the total of observations.

    Parameters
    ----------
    a : array_like
        Input array.
    numbins : int, optional
        The number of bins to use for the histogram. Default is 10.
    defaultreallimits : tuple (lower, upper), optional
        The lower and upper values for the range of the histogram.
        If no value is given, a range slightly larger than the range of the
        values in a is used. Specifically ``(a.min() - s, a.max() + s)``,
        where ``s = (1/2)(a.max() - a.min()) / (numbins - 1)``.
    weights : array_like, optional
        The weights for each value in `a`. Default is None, which gives each
        value a weight of 1.0

    Returns
    -------
    frequency : ndarray
        Binned values of relative frequency.
    lowerlimit : float
        Lower real limit.
    binsize : float
        Width of each bin.
    extrapoints : int
        Extra points.

    Examples
    --------
    >>> import matplotlib.pyplot as plt
    >>> from numpy.random import default_rng
    >>> from scipy import stats
    >>> rng = default_rng()
    >>> a = np.array([2, 4, 1, 2, 3, 2])
    >>> res = stats.relfreq(a, numbins=4)
    >>> res.frequency
    array([ 0.16666667, 0.5       , 0.16666667,  0.16666667])
    >>> np.sum(res.frequency)  # relative frequencies should add up to 1
    1.0

    Create a normal distribution with 1000 random values

    >>> samples = stats.norm.rvs(size=1000, random_state=rng)

    Calculate relative frequencies

    >>> res = stats.relfreq(samples, numbins=25)

    Calculate space of values for x

    >>> x = res.lowerlimit + np.linspace(0, res.binsize*res.frequency.size,
    ...                                  res.frequency.size)

    Plot relative frequency histogram

    >>> fig = plt.figure(figsize=(5, 4))
    >>> ax = fig.add_subplot(1, 1, 1)
    >>> ax.bar(x, res.frequency, width=res.binsize)
    >>> ax.set_title('Relative frequency histogram')
    >>> ax.set_xlim([x.min(), x.max()])

    >>> plt.show()

    ra  r   )ro   r   r_  r   rg  )rz   r]  rc  r   rd  re  r   rf  rd   rd   rg   r3   W  s    E
r3   c                  G   s   t t tj}g }d}| D ]}t |}t|}t |}|| d }| }	|d | | d|	  |d |d   }
|	|d  }t	|t |
 |krt
d||
 |j}q|r|dd D ] }||jkrt j|td  S qt |S )	am  Compute the O'Brien transform on input data (any number of arrays).

    Used to test for homogeneity of variance prior to running one-way stats.
    Each array in ``*args`` is one level of a factor.
    If `f_oneway` is run on the transformed data and found significant,
    the variances are unequal.  From Maxwell and Delaney [1]_, p.112.

    Parameters
    ----------
    args : tuple of array_like
        Any number of arrays.

    Returns
    -------
    obrientransform : ndarray
        Transformed data for use in an ANOVA.  The first dimension
        of the result corresponds to the sequence of transformed
        arrays.  If the arrays given are all 1-D of the same length,
        the return value is a 2-D array; otherwise it is a 1-D array
        of type object, with each element being an ndarray.

    References
    ----------
    .. [1] S. E. Maxwell and H. D. Delaney, "Designing Experiments and
           Analyzing Data: A Model Comparison Perspective", Wadsworth, 1990.

    Examples
    --------
    We'll test the following data sets for differences in their variance.

    >>> x = [10, 11, 13, 9, 7, 12, 12, 9, 10]
    >>> y = [13, 21, 5, 10, 8, 14, 10, 12, 7, 15]

    Apply the O'Brien transform to the data.

    >>> from scipy.stats import obrientransform
    >>> tx, ty = obrientransform(x, y)

    Use `scipy.stats.f_oneway` to apply a one-way ANOVA test to the
    transformed data.

    >>> from scipy.stats import f_oneway
    >>> F, p = f_oneway(tx, ty)
    >>> p
    0.1314139477040335

    If we require that ``p < 0.05`` for significance, we cannot conclude
    that the variances are different.

    Nr   r   r   r   z'Lack of convergence in obrientransform.r   r   )ro   r   r   r   Zepsr   r   r   rr   r   rm   r   r   r   r   )argsZTINYZarraysZsLastargrz   r   r7  sqZsumsqtr   arrrd   rd   rg   r4     s(    3

(

r4   c                 C   sh   t | |\} }t| |\}}|r@|dkr@t| } t| ||S | j| }tj| ||dt	| }|S )aG  Compute standard error of the mean.

    Calculate the standard error of the mean (or standard error of
    measurement) of the values in the input array.

    Parameters
    ----------
    a : array_like
        An array containing the values for which the standard error is
        returned.
    axis : int or None, optional
        Axis along which to operate. Default is 0. If None, compute over
        the whole array `a`.
    ddof : int, optional
        Delta degrees-of-freedom. How many degrees of freedom to adjust
        for bias in limited samples relative to the population estimate
        of variance. Defaults to 1.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

          * 'propagate': returns nan
          * 'raise': throws an error
          * 'omit': performs the calculations ignoring nan values

    Returns
    -------
    s : ndarray or float
        The standard error of the mean in the sample(s), along the input axis.

    Notes
    -----
    The default value for `ddof` is different to the default (0) used by other
    ddof containing routines, such as np.std and np.nanstd.

    Examples
    --------
    Find standard error along the first axis:

    >>> from scipy import stats
    >>> a = np.arange(20).reshape(5,4)
    >>> stats.sem(a)
    array([ 2.8284,  2.8284,  2.8284,  2.8284])

    Find standard error across the whole array, using n degrees of freedom:

    >>> stats.sem(a, axis=None, ddof=0)
    1.2893796958227628

    rc   r  )
r   r}   r   r   r   r5   r   ro   r   r   )rz   r   r   r{   r|   r   rf   rd   rd   rg   r5     s    3

r5   c                 C   s>   | t |   }|jdkr&t dgS |d |kjddS dS )z
    Check if all values in x are the same.  nans are ignored.

    x must be a 1d array.

    The return value is a 1d array with length 1, so it can be used
    in np.apply_along_axis.
    r   Tr   N)ro   rq   r   r   r   r-  r#  rd   rd   rg   _isconst:	  s    	
rn  c                 C   s:   | t |   }|jdkr(t t jgS t j|ddS dS )z
    Compute nanmean for the 1d array x, but quietly return nan if x is all nan.

    The return value is a 1d array with length 1, so it can be used
    in np.apply_along_axis.
    r   Tr   N)ro   rq   r   r   rt   r   rm  rd   rd   rg   _quiet_nanmeanJ	  s    
ro  c                 C   s<   | t |   }|jdkr(t t jgS t j|d|dS dS )z
    Compute nanstd for the 1d array x, but quietly return nan if x is all nan.

    The return value is a 1d array with length 1, so it can be used
    in np.apply_along_axis.
    r   T)r   r   N)ro   rq   r   r   rt   r   )r-  r   r#  rd   rd   rg   _quiet_nanstdX	  s    
rp  c                 C   s   t | | |||dS )a
  
    Compute the z score.

    Compute the z score of each value in the sample, relative to the
    sample mean and standard deviation.

    Parameters
    ----------
    a : array_like
        An array like object containing the sample data.
    axis : int or None, optional
        Axis along which to operate. Default is 0. If None, compute over
        the whole array `a`.
    ddof : int, optional
        Degrees of freedom correction in the calculation of the
        standard deviation. Default is 0.
    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'.  Note that when the value is 'omit',
        nans in the input also propagate to the output, but they do not affect
        the z-scores computed for the non-nan values.

    Returns
    -------
    zscore : array_like
        The z-scores, standardized by mean and standard deviation of
        input array `a`.

    Notes
    -----
    This function preserves ndarray subclasses, and works also with
    matrices and masked arrays (it uses `asanyarray` instead of
    `asarray` for parameters).

    Examples
    --------
    >>> a = np.array([ 0.7972,  0.0767,  0.4383,  0.7866,  0.8091,
    ...                0.1954,  0.6307,  0.6599,  0.1065,  0.0508])
    >>> from scipy import stats
    >>> stats.zscore(a)
    array([ 1.1273, -1.247 , -0.0552,  1.0923,  1.1664, -0.8559,  0.5786,
            0.6748, -1.1488, -1.3324])

    Computing along a specified axis, using n-1 degrees of freedom
    (``ddof=1``) to calculate the standard deviation:

    >>> b = np.array([[ 0.3148,  0.0478,  0.6243,  0.4608],
    ...               [ 0.7149,  0.0775,  0.6072,  0.9656],
    ...               [ 0.6341,  0.1403,  0.9759,  0.4064],
    ...               [ 0.5918,  0.6948,  0.904 ,  0.3721],
    ...               [ 0.0921,  0.2481,  0.1188,  0.1366]])
    >>> stats.zscore(b, axis=1, ddof=1)
    array([[-0.19264823, -1.28415119,  1.07259584,  0.40420358],
           [ 0.33048416, -1.37380874,  0.04251374,  1.00081084],
           [ 0.26796377, -1.12598418,  1.23283094, -0.37481053],
           [-0.22095197,  0.24468594,  1.19042819, -1.21416216],
           [-0.82780366,  1.4457416 , -0.43867764, -0.1792603 ]])

    An example with `nan_policy='omit'`:

    >>> x = np.array([[25.11, 30.10, np.nan, 32.02, 43.15],
    ...               [14.95, 16.06, 121.25, 94.35, 29.81]])
    >>> stats.zscore(x, axis=1, nan_policy='omit')
    array([[-1.13490897, -0.37830299,         nan, -0.08718406,  1.60039602],
           [-0.91611681, -0.89090508,  1.4983032 ,  0.88731639, -0.5785977 ]])
    )r   r   r{   )r6   )rz   r   r   r{   rd   rd   rg   r7   f	  s    Dr7   c                 C   s  t |}|jdkr t |jS t||\}}|r|dkr|du rlt| }t| |d}t	| }	qt 
t||}t j
t|||d}t 
t	||}	nR|j|dd}|j||dd}|du r|d|k }	nt|||kj|dd}	d||	< | | | }
t j|
t |	|
j< |
S )	a  
    Calculate the relative z-scores.

    Return an array of z-scores, i.e., scores that are standardized to
    zero mean and unit variance, where mean and variance are calculated
    from the comparison array.

    Parameters
    ----------
    scores : array_like
        The input for which z-scores are calculated.
    compare : array_like
        The input from which the mean and standard deviation of the
        normalization are taken; assumed to have the same dimension as
        `scores`.
    axis : int or None, optional
        Axis over which mean and variance of `compare` are calculated.
        Default is 0. If None, compute over the whole array `scores`.
    ddof : int, optional
        Degrees of freedom correction in the calculation of the
        standard deviation. Default is 0.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle the occurrence of nans in `compare`.
        'propagate' returns nan, 'raise' raises an exception, 'omit'
        performs the calculations ignoring nan values. Default is
        'propagate'. Note that when the value is 'omit', nans in `scores`
        also propagate to the output, but they do not affect the z-scores
        computed for the non-nan values.

    Returns
    -------
    zscore : array_like
        Z-scores, in the same shape as `scores`.

    Notes
    -----
    This function preserves ndarray subclasses, and works also with
    matrices and masked arrays (it uses `asanyarray` instead of
    `asarray` for parameters).

    Examples
    --------
    >>> from scipy.stats import zmap
    >>> a = [0.5, 2.0, 2.5, 3]
    >>> b = [0, 1, 2, 3, 4]
    >>> zmap(a, b)
    array([-1.06066017,  0.        ,  0.35355339,  0.70710678])

    r   rc   Nr   Tr   r   )r   r   r   r   )ro   r   r   r   r   r}   ro  rv   rp  rn  apply_along_axisr   r   r   r   _firstrt   broadcast_to)r   comparer   r   r{   rz   r|   mnr   Zisconstr  rd   rd   rg   r6   	  s*    2

r6   c              
   C   sv  t | } t| tjrtjnt j}zTt 8 tdt	 t 
t j|| ||dW  d   W S 1 sj0    Y  W n t	yB } zt |  rtd|t | }| }|rt t | ds|st | d rtd|nFdt|krt||n,t 
t j|| | d||dW  Y d}~S W Y d}~n8d}~0  typ } ztd	|W Y d}~n
d}~0 0 dS )
a  
    Calculate the geometric standard deviation of an array.

    The geometric standard deviation describes the spread of a set of numbers
    where the geometric mean is preferred. It is a multiplicative factor, and
    so a dimensionless quantity.

    It is defined as the exponent of the standard deviation of ``log(a)``.
    Mathematically the population geometric standard deviation can be
    evaluated as::

        gstd = exp(std(log(a)))

    .. versionadded:: 1.3.0

    Parameters
    ----------
    a : array_like
        An array like object containing the sample data.
    axis : int, tuple or None, optional
        Axis along which to operate. Default is 0. If None, compute over
        the whole array `a`.
    ddof : int, optional
        Degree of freedom correction in the calculation of the
        geometric standard deviation. Default is 1.

    Returns
    -------
    ndarray or float
        An array of the geometric standard deviation. If `axis` is None or `a`
        is a 1d array a float is returned.

    Notes
    -----
    As the calculation requires the use of logarithms the geometric standard
    deviation only supports strictly positive values. Any non-positive or
    infinite values will raise a `ValueError`.
    The geometric standard deviation is sometimes confused with the exponent of
    the standard deviation, ``exp(std(a))``. Instead the geometric standard
    deviation is ``exp(std(log(a)))``.
    The default value for `ddof` is different to the default value (0) used
    by other ddof containing functions, such as ``np.std`` and ``np.nanstd``.

    Examples
    --------
    Find the geometric standard deviation of a log-normally distributed sample.
    Note that the standard deviation of the distribution is one, on a
    log scale this evaluates to approximately ``exp(1)``.

    >>> from scipy.stats import gstd
    >>> rng = np.random.default_rng()
    >>> sample = rng.lognormal(mean=0, sigma=1, size=1000)
    >>> gstd(sample)
    2.810010162475324

    Compute the geometric standard deviation of a multidimensional array and
    of a given axis.

    >>> a = np.arange(1, 25).reshape(2, 3, 4)
    >>> gstd(a, axis=None)
    2.2944076136018947
    >>> gstd(a, axis=2)
    array([[1.82424757, 1.22436866, 1.13183117],
           [1.09348306, 1.07244798, 1.05914985]])
    >>> gstd(a, axis=(1,2))
    array([2.12939215, 1.22120169])

    The geometric standard deviation further handles masked arrays.

    >>> a = np.arange(1, 25).reshape(2, 3, 4)
    >>> ma = np.ma.masked_where(a > 16, a)
    >>> ma
    masked_array(
      data=[[[1, 2, 3, 4],
             [5, 6, 7, 8],
             [9, 10, 11, 12]],
            [[13, 14, 15, 16],
             [--, --, --, --],
             [--, --, --, --]]],
      mask=[[[False, False, False, False],
             [False, False, False, False],
             [False, False, False, False]],
            [[False, False, False, False],
             [ True,  True,  True,  True],
             [ True,  True,  True,  True]]],
      fill_value=999999)
    >>> gstd(ma, axis=2)
    masked_array(
      data=[[1.8242475707663655, 1.2243686572447428, 1.1318311657788478],
            [1.0934830582350938, --, --]],
      mask=[[False, False, False],
            [False,  True,  True]],
      fill_value=999999)

    errorr  NzjInfinite value encountered. The geometric standard deviation is defined for strictly positive values only.r   znNon positive value encountered. The geometric standard deviation is defined for strictly positive values only.z!Degrees of freedom <= 0 for slice)r   zRInvalid array input. The inputs could not be safely coerced to any supported types)ro   r   r   r   r   r   rw   catch_warningssimplefilterry   r   r   isinfr   rm   rq   
less_equalZnanminstrrs   )rz   r   r   r   wZa_nanZ	a_nan_anyrf  rd   rd   rg   r9   	  sD    `

>
@r9   r   r   r   )rawnormal   K   linearc                 C   s   t | } | jstjS t|trZ| }|tvr<td	||dkrRt
dtj t| }t| |\}}|r||dkr|tj}	ntj}	t|dkrtdt| rtdt|}|	| ||||d}
t|
d	 |
d
 }|dkr|| }|S )a  
    Compute the interquartile range of the data along the specified axis.

    The interquartile range (IQR) is the difference between the 75th and
    25th percentile of the data. It is a measure of the dispersion
    similar to standard deviation or variance, but is much more robust
    against outliers [2]_.

    The ``rng`` parameter allows this function to compute other
    percentile ranges than the actual IQR. For example, setting
    ``rng=(0, 100)`` is equivalent to `numpy.ptp`.

    The IQR of an empty array is `np.nan`.

    .. versionadded:: 0.18.0

    Parameters
    ----------
    x : array_like
        Input array or object that can be converted to an array.
    axis : int or sequence of int, optional
        Axis along which the range is computed. The default is to
        compute the IQR for the entire array.
    rng : Two-element sequence containing floats in range of [0,100] optional
        Percentiles over which to compute the range. Each must be
        between 0 and 100, inclusive. The default is the true IQR:
        `(25, 75)`. The order of the elements is not important.
    scale : scalar or str, optional
        The numerical value of scale will be divided out of the final
        result. The following string values are recognized:

          * 'raw' : No scaling, just return the raw IQR.
            **Deprecated!**  Use `scale=1` instead.
          * 'normal' : Scale by
            :math:`2 \sqrt{2} erf^{-1}(\frac{1}{2}) \approx 1.349`.

        The default is 1.0. The use of scale='raw' is deprecated.
        Array-like scale is also allowed, as long
        as it broadcasts correctly to the output such that
        ``out / scale`` is a valid operation. The output dimensions
        depend on the input array, `x`, the `axis` argument, and the
        `keepdims` flag.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

          * 'propagate': returns nan
          * 'raise': throws an error
          * 'omit': performs the calculations ignoring nan values
    interpolation : {'linear', 'lower', 'higher', 'midpoint',
                     'nearest'}, optional

        Specifies the interpolation method to use when the percentile
        boundaries lie between two data points `i` and `j`.
        The following options are available (default is 'linear'):

          * 'linear': `i + (j - i) * fraction`, where `fraction` is the
            fractional part of the index surrounded by `i` and `j`.
          * 'lower': `i`.
          * 'higher': `j`.
          * 'nearest': `i` or `j` whichever is nearest.
          * 'midpoint': `(i + j) / 2`.

    keepdims : bool, optional
        If this is set to `True`, the reduced axes are left in the
        result as dimensions with size one. With this option, the result
        will broadcast correctly against the original array `x`.

    Returns
    -------
    iqr : scalar or ndarray
        If ``axis=None``, a scalar is returned. If the input contains
        integers or floats of smaller precision than ``np.float64``, then the
        output data-type is ``np.float64``. Otherwise, the output data-type is
        the same as that of the input.

    See Also
    --------
    numpy.std, numpy.var

    Notes
    -----
    This function is heavily dependent on the version of `numpy` that is
    installed. Versions greater than 1.11.0b3 are highly recommended, as they
    include a number of enhancements and fixes to `numpy.percentile` and
    `numpy.nanpercentile` that affect the operation of this function. The
    following modifications apply:

    Below 1.10.0 : `nan_policy` is poorly defined.
        The default behavior of `numpy.percentile` is used for 'propagate'. This
        is a hybrid of 'omit' and 'propagate' that mostly yields a skewed
        version of 'omit' since NaNs are sorted to the end of the data. A
        warning is raised if there are NaNs in the data.
    Below 1.9.0: `numpy.nanpercentile` does not exist.
        This means that `numpy.percentile` is used regardless of `nan_policy`
        and a warning is issued. See previous item for a description of the
        behavior.
    Below 1.9.0: `keepdims` and `interpolation` are not supported.
        The keywords get ignored with a warning if supplied with non-default
        values. However, multiple axes are still supported.

    References
    ----------
    .. [1] "Interquartile range" https://en.wikipedia.org/wiki/Interquartile_range
    .. [2] "Robust measures of scale" https://en.wikipedia.org/wiki/Robust_measures_of_scale
    .. [3] "Quantile" https://en.wikipedia.org/wiki/Quantile

    Examples
    --------
    >>> from scipy.stats import iqr
    >>> x = np.array([[10, 7, 4], [3, 2, 1]])
    >>> x
    array([[10,  7,  4],
           [ 3,  2,  1]])
    >>> iqr(x)
    4.0
    >>> iqr(x, axis=0)
    array([ 3.5,  2.5,  1.5])
    >>> iqr(x, axis=1)
    array([ 3.,  1.])
    >>> iqr(x, axis=1, keepdims=True)
    array([[ 3.],
           [ 1.]])

    z{0} not a valid scale for `iqr`r~  7use of scale='raw' is deprecated, use scale=1.0 insteadrc   r   z+quantile range must be two element sequencezrange must not contain NaNs)r   interpolationr   r   r   r   )r   r   ro   rt   r   r|  rI  _scale_conversionsrm   formatrw   rx   VisibleDeprecationWarningr}   ZnanpercentileZ
percentiler   rs   rq   r   sortedsubtract)r-  r   rngscaler{   r  r   Z	scale_keyr|   Zpercentile_funcrU  outrd   rd   rg   r8   
  s:    

r8   c                 C   sZ   t | }| r*|dkr t jS | |  } | jdkr:t jS || }t t | | }|S )Nr`   r   )ro   rq   r   rt   r   medianr   )r-  centerr{   rq   medmadrd   rd   rg   _mad_1d3  s    


r  c           	         s:  t |stdt| dt|trF| dkr8d}nt| dt| } | js du rbt	j
S t fddt| jD }|d	krt	j
S t	|t	j
S t| |\}}|rڈ du rt|  ||}nt	t | ||}nX du r|| dd
}t	t	| | }n,t	||  d
 }t	jt	| |  d
}|| S )a=  
    Compute the median absolute deviation of the data along the given axis.

    The median absolute deviation (MAD, [1]_) computes the median over the
    absolute deviations from the median. It is a measure of dispersion
    similar to the standard deviation but more robust to outliers [2]_.

    The MAD of an empty array is ``np.nan``.

    .. versionadded:: 1.5.0

    Parameters
    ----------
    x : array_like
        Input array or object that can be converted to an array.
    axis : int or None, optional
        Axis along which the range is computed. Default is 0. If None, compute
        the MAD over the entire array.
    center : callable, optional
        A function that will return the central value. The default is to use
        np.median. Any user defined function used will need to have the
        function signature ``func(arr, axis)``.
    scale : scalar or str, optional
        The numerical value of scale will be divided out of the final
        result. The default is 1.0. The string "normal" is also accepted,
        and results in `scale` being the inverse of the standard normal
        quantile function at 0.75, which is approximately 0.67449.
        Array-like scale is also allowed, as long as it broadcasts correctly
        to the output such that ``out / scale`` is a valid operation. The
        output dimensions depend on the input array, `x`, and the `axis`
        argument.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

        * 'propagate': returns nan
        * 'raise': throws an error
        * 'omit': performs the calculations ignoring nan values

    Returns
    -------
    mad : scalar or ndarray
        If ``axis=None``, a scalar is returned. If the input contains
        integers or floats of smaller precision than ``np.float64``, then the
        output data-type is ``np.float64``. Otherwise, the output data-type is
        the same as that of the input.

    See Also
    --------
    numpy.std, numpy.var, numpy.median, scipy.stats.iqr, scipy.stats.tmean,
    scipy.stats.tstd, scipy.stats.tvar

    Notes
    -----
    The `center` argument only affects the calculation of the central value
    around which the MAD is calculated. That is, passing in ``center=np.mean``
    will calculate the MAD around the mean - it will not calculate the *mean*
    absolute deviation.

    The input array may contain `inf`, but if `center` returns `inf`, the
    corresponding MAD for that data will be `nan`.

    References
    ----------
    .. [1] "Median absolute deviation",
           https://en.wikipedia.org/wiki/Median_absolute_deviation
    .. [2] "Robust measures of scale",
           https://en.wikipedia.org/wiki/Robust_measures_of_scale

    Examples
    --------
    When comparing the behavior of `median_abs_deviation` with ``np.std``,
    the latter is affected when we change a single value of an array to have an
    outlier value while the MAD hardly changes:

    >>> from scipy import stats
    >>> x = stats.norm.rvs(size=100, scale=1, random_state=123456)
    >>> x.std()
    0.9973906394005013
    >>> stats.median_abs_deviation(x)
    0.82832610097857
    >>> x[0] = 345.6
    >>> x.std()
    34.42304872314415
    >>> stats.median_abs_deviation(x)
    0.8323442311590675

    Axis handling example:

    >>> x = np.array([[10, 7, 4], [3, 2, 1]])
    >>> x
    array([[10,  7,  4],
           [ 3,  2,  1]])
    >>> stats.median_abs_deviation(x)
    array([3.5, 2.5, 1.5])
    >>> stats.median_abs_deviation(x, axis=None)
    2.0

    Scale normal example:

    >>> x = stats.norm.rvs(size=1000000, scale=2, random_state=123456)
    >>> stats.median_abs_deviation(x)
    1.3487398527041636
    >>> stats.median_abs_deviation(x, scale='normal')
    1.9996446978061115

    z8The argument 'center' must be callable. The given value z is not callable.r  gIRk?z is not a valid scale value.Nc                 3   s   | ]\}}| kr|V  qd S Nrd   )re   r   r   r   rd   rg   rh     ri   z'median_abs_deviation.<locals>.<genexpr>rd   r   )callablers   reprr   r|  rI  rm   r   r   ro   rt   r   	enumerater   r   r}   r  rv   rr  r  r   Zexpand_dims)	r-  r   r  r  r{   Z	nan_shaper|   r  r  rd   r   rg   r;   I  s6    m


r;   a  
To preserve the existing default behavior, use
`scipy.stats.median_abs_deviation(..., scale=1/1.4826)`.
The value 1.4826 is not numerically precise for scaling
with a normal distribution. For a numerically precise value, use
`scipy.stats.median_abs_deviation(..., scale='normal')`.
r:   )Zold_namenew_namer9  g)Ǻ?c                 C   sL   t |tr(| dkr(tdtj d}t |ts:d| }t| ||||dS )a[  
Compute the median absolute deviation of the data along the given axis.

The median absolute deviation (MAD, [1]_) computes the median over the
absolute deviations from the median. It is a measure of dispersion
similar to the standard deviation but more robust to outliers [2]_.

The MAD of an empty array is ``np.nan``.

.. versionadded:: 1.3.0

Parameters
----------
x : array_like
    Input array or object that can be converted to an array.
axis : int or None, optional
    Axis along which the range is computed. Default is 0. If None, compute
    the MAD over the entire array.
center : callable, optional
    A function that will return the central value. The default is to use
    np.median. Any user defined function used will need to have the function
    signature ``func(arr, axis)``.
scale : int, optional
    The scaling factor applied to the MAD. The default scale (1.4826)
    ensures consistency with the standard deviation for normally distributed
    data.
nan_policy : {'propagate', 'raise', 'omit'}, optional
    Defines how to handle when input contains nan.
    The following options are available (default is 'propagate'):

    * 'propagate': returns nan
    * 'raise': throws an error
    * 'omit': performs the calculations ignoring nan values

Returns
-------
mad : scalar or ndarray
    If ``axis=None``, a scalar is returned. If the input contains
    integers or floats of smaller precision than ``np.float64``, then the
    output data-type is ``np.float64``. Otherwise, the output data-type is
    the same as that of the input.

See Also
--------
numpy.std, numpy.var, numpy.median, scipy.stats.iqr, scipy.stats.tmean,
scipy.stats.tstd, scipy.stats.tvar

Notes
-----
The `center` argument only affects the calculation of the central value
around which the MAD is calculated. That is, passing in ``center=np.mean``
will calculate the MAD around the mean - it will not calculate the *mean*
absolute deviation.

References
----------
.. [1] "Median absolute deviation",
       https://en.wikipedia.org/wiki/Median_absolute_deviation
.. [2] "Robust measures of scale",
       https://en.wikipedia.org/wiki/Robust_measures_of_scale

Examples
--------
When comparing the behavior of `median_absolute_deviation` with ``np.std``,
the latter is affected when we change a single value of an array to have an
outlier value while the MAD hardly changes:

>>> from scipy import stats
>>> x = stats.norm.rvs(size=100, scale=1, random_state=123456)
>>> x.std()
0.9973906394005013
>>> stats.median_absolute_deviation(x)
1.2280762773108278
>>> x[0] = 345.6
>>> x.std()
34.42304872314415
>>> stats.median_absolute_deviation(x)
1.2340335571164334

Axis handling example:

>>> x = np.array([[10, 7, 4], [3, 2, 1]])
>>> x
array([[10,  7,  4],
       [ 3,  2,  1]])
>>> stats.median_absolute_deviation(x)
array([5.1891, 3.7065, 2.2239])
>>> stats.median_absolute_deviation(x, axis=None)
2.9652

r~  r  r   r   )r   r  r  r{   )r   r|  rI  rw   rx   ro   r  r;   )r-  r   r  r  r{   rd   rd   rg   r:     s    `


SigmaclipResult)ZclippedrI  upperr)  c           
      C   sp   t |  }d}|rd| }| }|j}|||  }|||  }	|||k||	k@  }||j }qt|||	S )a  Perform iterative sigma-clipping of array elements.

    Starting from the full sample, all elements outside the critical range are
    removed, i.e. all elements of the input array `c` that satisfy either of
    the following conditions::

        c < mean(c) - std(c)*low
        c > mean(c) + std(c)*high

    The iteration continues with the updated sample until no
    elements are outside the (updated) range.

    Parameters
    ----------
    a : array_like
        Data array, will be raveled if not 1-D.
    low : float, optional
        Lower bound factor of sigma clipping. Default is 4.
    high : float, optional
        Upper bound factor of sigma clipping. Default is 4.

    Returns
    -------
    clipped : ndarray
        Input array with clipped elements removed.
    lower : float
        Lower threshold value use for clipping.
    upper : float
        Upper threshold value use for clipping.

    Examples
    --------
    >>> from scipy.stats import sigmaclip
    >>> a = np.concatenate((np.linspace(9.5, 10.5, 31),
    ...                     np.linspace(0, 20, 5)))
    >>> fact = 1.5
    >>> c, low, upp = sigmaclip(a, fact, fact)
    >>> c
    array([  9.96666667,  10.        ,  10.03333333,  10.        ])
    >>> c.var(), c.std()
    (0.00055555555555555165, 0.023570226039551501)
    >>> low, c.mean() - fact*c.std(), c.min()
    (9.9646446609406727, 9.9646446609406727, 9.9666666666666668)
    >>> upp, c.mean() + fact*c.std(), c.max()
    (10.035355339059327, 10.035355339059327, 10.033333333333333)

    >>> a = np.concatenate((np.linspace(9.5, 10.5, 11),
    ...                     np.linspace(-100, -50, 3)))
    >>> c, low, upp = sigmaclip(a, 1.8, 1.8)
    >>> (c == np.linspace(9.5, 10.5, 11)).all()
    True

    r   )ro   r   rv   r   r   r   r  )
rz   lowhighcr$  Zc_stdZc_meanr   Z	critlowerZ	critupperrd   rd   rg   r<   c  s    6r<   c                 C   s   t | } | jdkr| S |du r,|  } d}| j| }t|| }|| }||krZtdt | ||d f|}tdg|j	 }t||||< |t
| S )a$  Slice off a proportion of items from both ends of an array.

    Slice off the passed proportion of items from both ends of the passed
    array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and**
    rightmost 10% of scores). The trimmed values are the lowest and
    highest ones.
    Slice off less if proportion results in a non-integer slice index (i.e.
    conservatively slices off `proportiontocut`).

    Parameters
    ----------
    a : array_like
        Data to trim.
    proportiontocut : float
        Proportion (in range 0-1) of total data set to trim of each end.
    axis : int or None, optional
        Axis along which to trim data. Default is 0. If None, compute over
        the whole array `a`.

    Returns
    -------
    out : ndarray
        Trimmed version of array `a`. The order of the trimmed content
        is undefined.

    See Also
    --------
    trim_mean

    Examples
    --------
    >>> from scipy import stats
    >>> a = np.arange(20)
    >>> b = stats.trimboth(a, 0.1)
    >>> b.shape
    (16,)

    r   NProportion too big.r   )ro   r   r   rv   r   r   rm   	partitionrJ  r   r   rz   proportiontocutr   r  lowercutuppercutatmpslrd   rd   rg   r=     s    '


r=   rT  c                 C   s   t | } |du r|  } d}| j| }|dkr4g S | dkrVd}|t||  }n| dkrrt|| }|}t | ||d f|}||| S )a   Slice off a proportion from ONE end of the passed array distribution.

    If `proportiontocut` = 0.1, slices off 'leftmost' or 'rightmost'
    10% of scores. The lowest or highest values are trimmed (depending on
    the tail).
    Slice off less if proportion results in a non-integer slice index
    (i.e. conservatively slices off `proportiontocut` ).

    Parameters
    ----------
    a : array_like
        Input array.
    proportiontocut : float
        Fraction to cut off of 'left' or 'right' of distribution.
    tail : {'left', 'right'}, optional
        Defaults to 'right'.
    axis : int or None, optional
        Axis along which to trim data. Default is 0. If None, compute over
        the whole array `a`.

    Returns
    -------
    trim1 : ndarray
        Trimmed version of array `a`. The order of the trimmed content is
        undefined.

    Examples
    --------
    >>> from scipy import stats
    >>> a = np.arange(20)
    >>> b = stats.trim1(a, 0.5, 'left')
    >>> b
    array([10, 11, 12, 13, 14, 16, 15, 17, 18, 19])

    Nr   r   rT  rS  )ro   r   rv   r   rI  r   r  )rz   r  tailr   r  r  r  r  rd   rd   rg   r>     s    $

r>   c                 C   s   t | } | jdkrt jS |du r.|  } d}| j| }t|| }|| }||kr\tdt | ||d f|}t	dg|j
 }t	||||< t j|t| |dS )a  Return mean of array after trimming distribution from both tails.

    If `proportiontocut` = 0.1, slices off 'leftmost' and 'rightmost' 10% of
    scores. The input is sorted before slicing. Slices off less if proportion
    results in a non-integer slice index (i.e., conservatively slices off
    `proportiontocut` ).

    Parameters
    ----------
    a : array_like
        Input array.
    proportiontocut : float
        Fraction to cut off of both tails of the distribution.
    axis : int or None, optional
        Axis along which the trimmed means are computed. Default is 0.
        If None, compute over the whole array `a`.

    Returns
    -------
    trim_mean : ndarray
        Mean of trimmed array.

    See Also
    --------
    trimboth
    tmean : Compute the trimmed mean ignoring values outside given `limits`.

    Examples
    --------
    >>> from scipy import stats
    >>> x = np.arange(20)
    >>> stats.trim_mean(x, 0.1)
    9.5
    >>> x2 = x.reshape(5, 4)
    >>> x2
    array([[ 0,  1,  2,  3],
           [ 4,  5,  6,  7],
           [ 8,  9, 10, 11],
           [12, 13, 14, 15],
           [16, 17, 18, 19]])
    >>> stats.trim_mean(x2, 0.25)
    array([  8.,   9.,  10.,  11.])
    >>> stats.trim_mean(x2, 0.25, axis=1)
    array([  1.5,   5.5,   9.5,  13.5,  17.5])

    r   Nr  r   r   )ro   r   r   rt   rv   r   r   rm   r  rJ  r   r   r   r  rd   rd   rg   r?      s    /


r?   F_onewayResultc                   @   s   e Zd ZdZdddZdS )rA   z
    Warning generated by `f_oneway` when an input is constant, e.g.
    each of the samples provided is a constant array.
    Nc                 C   s   |d u rd}|f| _ d S )NzOEach of the input arrays is constant;the F statistic is not defined or infiniterh  selfr0  rd   rd   rg   __init__n  s    z%F_onewayConstantInputWarning.__init__)N__name__
__module____qualname____doc__r  rd   rd   rd   rg   rA   h  s   rA   c                   @   s   e Zd ZdZdS )rB   zm
    Warning generated by `f_oneway` when an input has length 0,
    or if all the inputs have length 1.
    N)r  r  r  r  rd   rd   rd   rg   rB   u  s   rB   c                 C   sh   t jj|t| }| d| | |d d  }|dkrFt j}t j}nt j|t jd}| }t||S )z
    This is a helper function for f_oneway for creating the return values
    in certain degenerate conditions.  It creates return values that are
    all nan with the appropriate shape for the given `shape` and `axis`.
    Nr   rd   r   )	ro   core
multiarraynormalize_axis_indexr   rt   r   r   r  )r   r   r   fr  rd   rd   rg   _create_f_oneway_nan_result}  s    r  c                 C   s   t | t jd| jd|S )z>Return arr[..., 0:1, ...] where 0:1 is in the `axis` position.r   )Zndmin)ro   Ztake_along_axisr   r   )rl  r   rd   rd   rg   rs    s    rs  r   c                    s@  t |dk r tdt | ddd |D }t |}tj| d}|j  }t fdd|D r~ttd	 t	|j S t
 fd
d|D rd}tt| t	|j S tj fdd|D  d}|j
 d}| rtt  t| |kj
 d}|j dd}	||	8 }t| d| }
t| d|
 }d}|D ]$}|t||	  d|j   7 }qB||
8 }|| }|d }|| }|| }|| }tjddd || }W d   n1 s0    Y  t|||}t|r|rtj}tj}n|r6tj}d}n&tj||< d||< tj||< tj||< t||S )a6  Perform one-way ANOVA.

    The one-way ANOVA tests the null hypothesis that two or more groups have
    the same population mean.  The test is applied to samples from two or
    more groups, possibly with differing sizes.

    Parameters
    ----------
    sample1, sample2, ... : array_like
        The sample measurements for each group.  There must be at least
        two arguments.  If the arrays are multidimensional, then all the
        dimensions of the array must be the same except for `axis`.
    axis : int, optional
        Axis of the input arrays along which the test is applied.
        Default is 0.

    Returns
    -------
    statistic : float
        The computed F statistic of the test.
    pvalue : float
        The associated p-value from the F distribution.

    Warns
    -----
    F_onewayConstantInputWarning
        Raised if each of the input arrays is constant array.
        In this case the F statistic is either infinite or isn't defined,
        so ``np.inf`` or ``np.nan`` is returned.

    F_onewayBadInputSizesWarning
        Raised if the length of any input array is 0, or if all the input
        arrays have length 1.  ``np.nan`` is returned for the F statistic
        and the p-value in these cases.

    Notes
    -----
    The ANOVA test has important assumptions that must be satisfied in order
    for the associated p-value to be valid.

    1. The samples are independent.
    2. Each sample is from a normally distributed population.
    3. The population standard deviations of the groups are all equal.  This
       property is known as homoscedasticity.

    If these assumptions are not true for a given set of data, it may still
    be possible to use the Kruskal-Wallis H-test (`scipy.stats.kruskal`) or
    the Alexander-Govern test (`scipy.stats.alexandergovern`) although with
    some loss of power.

    The length of each group must be at least one, and there must be at
    least one group with length greater than one.  If these conditions
    are not satisfied, a warning is generated and (``np.nan``, ``np.nan``)
    is returned.

    If each group contains constant values, and there exist at least two
    groups with different values, the function generates a warning and
    returns (``np.inf``, 0).

    If all values in all groups are the same, function generates a warning
    and returns (``np.nan``, ``np.nan``).

    The algorithm is from Heiman [2]_, pp.394-7.

    References
    ----------
    .. [1] R. Lowry, "Concepts and Applications of Inferential Statistics",
           Chapter 14, 2014, http://vassarstats.net/textbook/

    .. [2] G.W. Heiman, "Understanding research methods and statistics: An
           integrated introduction for psychology", Houghton, Mifflin and
           Company, 2001.

    .. [3] G.H. McDonald, "Handbook of Biological Statistics", One-way ANOVA.
           http://www.biostathandbook.com/onewayanova.html

    Examples
    --------
    >>> from scipy.stats import f_oneway

    Here are some data [3]_ on a shell measurement (the length of the anterior
    adductor muscle scar, standardized by dividing by length) in the mussel
    Mytilus trossulus from five locations: Tillamook, Oregon; Newport, Oregon;
    Petersburg, Alaska; Magadan, Russia; and Tvarminne, Finland, taken from a
    much larger data set used in McDonald et al. (1991).

    >>> tillamook = [0.0571, 0.0813, 0.0831, 0.0976, 0.0817, 0.0859, 0.0735,
    ...              0.0659, 0.0923, 0.0836]
    >>> newport = [0.0873, 0.0662, 0.0672, 0.0819, 0.0749, 0.0649, 0.0835,
    ...            0.0725]
    >>> petersburg = [0.0974, 0.1352, 0.0817, 0.1016, 0.0968, 0.1064, 0.105]
    >>> magadan = [0.1033, 0.0915, 0.0781, 0.0685, 0.0677, 0.0697, 0.0764,
    ...            0.0689]
    >>> tvarminne = [0.0703, 0.1026, 0.0956, 0.0973, 0.1039, 0.1045]
    >>> f_oneway(tillamook, newport, petersburg, magadan, tvarminne)
    F_onewayResult(statistic=7.121019471642447, pvalue=0.0002812242314534544)

    `f_oneway` accepts multidimensional input arrays.  When the inputs
    are multidimensional and `axis` is not given, the test is performed
    along the first axis of the input arrays.  For the following data, the
    test is performed three times, once for each column.

    >>> a = np.array([[9.87, 9.03, 6.81],
    ...               [7.18, 8.35, 7.00],
    ...               [8.39, 7.58, 7.68],
    ...               [7.45, 6.33, 9.35],
    ...               [6.41, 7.10, 9.33],
    ...               [8.00, 8.24, 8.44]])
    >>> b = np.array([[6.35, 7.30, 7.16],
    ...               [6.65, 6.68, 7.63],
    ...               [5.72, 7.73, 6.72],
    ...               [7.01, 9.19, 7.41],
    ...               [7.75, 7.87, 8.30],
    ...               [6.90, 7.97, 6.97]])
    >>> c = np.array([[3.31, 8.77, 1.01],
    ...               [8.25, 3.24, 3.62],
    ...               [6.32, 8.81, 5.19],
    ...               [7.48, 8.83, 8.91],
    ...               [8.59, 6.01, 6.07],
    ...               [3.07, 9.72, 7.48]])
    >>> F, p = f_oneway(a, b, c)
    >>> F
    array([1.75676344, 0.03701228, 3.76439349])
    >>> p
    array([0.20630784, 0.96375203, 0.04733157])

    r   z&at least two inputs are required; got .c                 S   s   g | ]}t j|td qS r   ro   r   r   re   ri  rd   rd   rg   r     ri   zf_oneway.<locals>.<listcomp>r   c                 3   s   | ]}|j   d kV  qdS )r   Nr   r  r   rd   rg   rh   $  ri   zf_oneway.<locals>.<genexpr>zat least one input has length 0c                 3   s   | ]}|j   d kV  qdS )r   Nr  r  r   rd   rg   rh   *  ri   zeall input arrays have length 1.  f_oneway requires that at least one input has length greater than 1.c                    s$   g | ]}t | |kj d dqS )Trq  )rs  r   )re   rz   r   rd   rg   r   9  s   Trq  r   r   rj   r   rl   Nr   )r   rs   ro   concatenater   r   rw   rx   rB   r  r   rA   rs  r   _square_of_sums_sum_of_squaresrp   specialZfdtrcr   rt   infr  )r   rh  
num_groupsalldataZbignr0  Zis_constZ	all_constZall_same_constoffsetZnormalized_ssZsstotssbnrz   ZsswnZdfbnZdfwnZmsbZmswr  r  rd   r   rg   r@     sf     
"(


r@   r{   c                    s  t | }tdd |D r8tt  ttjtjS t fdd|D }tdd |D }dd t	||D }dt
| }|t| }t|| }|| | }|d }	|	d }
d|
d	  }|
td|d	 |	   d }||d
 d
|  |  d|d  d|d   d|d
   d|  |d	 d d| |d   d|    }tt
|}tj|t|d }t||S )a  Performs the Alexander Govern test.

    The Alexander-Govern approximation tests the equality of k independent
    means in the face of heterogeneity of variance. The test is applied to
    samples from two or more groups, possibly with differing sizes.

    Parameters
    ----------
    sample1, sample2, ... : array_like
        The sample measurements for each group.  There must be at least
        two samples.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

        * 'propagate': returns nan
        * 'raise': throws an error
        * 'omit': performs the calculations ignoring nan values

    Returns
    -------
    statistic : float
        The computed A statistic of the test.
    pvalue : float
        The associated p-value from the chi-squared distribution.

    Warns
    -----
    AlexanderGovernConstantInputWarning
        Raised if an input is a constant array.  The statistic is not defined
        in this case, so ``np.nan`` is returned.

    See Also
    --------
    f_oneway : one-way ANOVA

    Notes
    -----
    The use of this test relies on several assumptions.

    1. The samples are independent.
    2. Each sample is from a normally distributed population.
    3. Unlike `f_oneway`, this test does not assume on homoscedasticity,
       instead relaxing the assumption of equal variances.

    Input samples must be finite, one dimensional, and with size greater than
    one.

    References
    ----------
    .. [1] Alexander, Ralph A., and Diane M. Govern. "A New and Simpler
           Approximation for ANOVA under Variance Heterogeneity." Journal
           of Educational Statistics, vol. 19, no. 2, 1994, pp. 91-101.
           JSTOR, www.jstor.org/stable/1165140. Accessed 12 Sept. 2020.

    Examples
    --------
    >>> from scipy.stats import alexandergovern

    Here are some data on annual percentage rate of interest charged on
    new car loans at nine of the largest banks in four American cities
    taken from the National Institute of Standards and Technology's
    ANOVA dataset.

    We use `alexandergovern` to test the null hypothesis that all cities
    have the same mean APR against the alternative that the cities do not
    all have the same mean APR. We decide that a sigificance level of 5%
    is required to reject the null hypothesis in favor of the alternative.

    >>> atlanta = [13.75, 13.75, 13.5, 13.5, 13.0, 13.0, 13.0, 12.75, 12.5]
    >>> chicago = [14.25, 13.0, 12.75, 12.5, 12.5, 12.4, 12.3, 11.9, 11.9]
    >>> houston = [14.0, 14.0, 13.51, 13.5, 13.5, 13.25, 13.0, 12.5, 12.5]
    >>> memphis = [15.0, 14.0, 13.75, 13.59, 13.25, 12.97, 12.5, 12.25,
    ...           11.89]
    >>> alexandergovern(atlanta, chicago, houston, memphis)
    AlexanderGovernResult(statistic=4.65087071883494,
                          pvalue=0.19922132490385214)

    The p-value is 0.1992, indicating a nearly 20% chance of observing
    such an extreme value of the test statistic under the null hypothesis.
    This exceeds 5%, so we do not reject the null hypothesis in favor of
    the alternative.

    c                 S   s   g | ]}||d  k  qS )r   r   r  rd   rd   rg   r     ri   z#alexandergovern.<locals>.<listcomp>c                    s&   g | ]} d krt |nt|qS )rc   )r   r   r   r  r  rd   rg   r     s   c                 S   s   g | ]}t |qS rd   )ro   r   r  rd   rd   rg   r     ri   c                 S   s(   g | ] \}}t j|d dt | qS )r   r   )ro   r   r   )re   ri  lengthrd   rd   rg   r     s   r   r   0   r   r   r   r  !   r     iW  rY  r    )!_alexandergovern_input_validationro   r   rw   rx   #AlexanderGovernConstantInputWarningAlexanderGovernResultrt   r   r   squarerr   r   r   r2  r  r   )r{   rh  lengthsZmeansZstandard_errorsZ	inv_sq_ser   Zvar_wZt_statsr  rz   r   r  r  r.  r8  rd   r  rg   r_   v  s6    U
*"r_   c                 C   s   t | dk rtdt |  dd | D } t| D ]p\}}t|dkrRtd|jdkrdtdt| rztdt	||d	\}}|r4|d
kr4t
|| |< q4| S )Nr   z2 or more inputs required, got c                 S   s   g | ]}t j|td qS r  r  r  rd   rd   rg   r     ri   z5_alexandergovern_input_validation.<locals>.<listcomp>r   z+Input sample size must be greater than one.z%Input samples must be one-dimensionalzInput samples must be finite.r  rc   )r   rs   r  ro   r   rm   r   rz  r   r}   r   r   )rh  r{   r   ri  r|   rd   rd   rg   r    s    
r  r  c                   @   s   e Zd ZdZdddZdS )r  zAWarning generated by `alexandergovern` when an input is constant.Nc                 C   s   |d u rd}|f| _ d S )Nz9An input array is constant; the statistic is not defined.r  r  rd   rd   rg   r    s    z,AlexanderGovernConstantInputWarning.__init__)Nr  rd   rd   rd   rg   r    s   r  c                   @   s   e Zd ZdZdddZdS )rC   z:Warning generated by `pearsonr` when an input is constant.Nc                 C   s   |d u rd}|f| _ d S NzGAn input array is constant; the correlation coefficient is not defined.r  r  rd   rd   rg   r  "  s    z%PearsonRConstantInputWarning.__init__)Nr  rd   rd   rd   rg   rC     s   rC   c                   @   s   e Zd ZdZdddZdS )rD   zAWarning generated by `pearsonr` when an input is nearly constant.Nc                 C   s   |d u rd}|f| _ d S )NzZAn input array is nearly constant; the computed correlation coefficient may be inaccurate.r  r  rd   rd   rg   r  ,  s    z)PearsonRNearConstantInputWarning.__init__)Nr  rd   rd   rd   rg   rD   )  s   rD   c                 C   s  t | }|t |krtd|dk r,tdt| } t|}| | d k s`||d k rxtt  tjtjfS t	d| d  |d  }|dkr|t
| d | d  t
|d |d   dfS | j|d}|j|d}| || }||| }t|}t|}	d}
||
t| k s<|	|
t| k rHtt  t|| ||	 }tt|dd	}|d d }dt||d
dtt|   }||fS )aB  
    Pearson correlation coefficient and p-value for testing non-correlation.

    The Pearson correlation coefficient [1]_ measures the linear relationship
    between two datasets.  The calculation of the p-value relies on the
    assumption that each dataset is normally distributed.  (See Kowalski [3]_
    for a discussion of the effects of non-normality of the input on the
    distribution of the correlation coefficient.)  Like other correlation
    coefficients, this one varies between -1 and +1 with 0 implying no
    correlation. Correlations of -1 or +1 imply an exact linear relationship.
    Positive correlations imply that as x increases, so does y. Negative
    correlations imply that as x increases, y decreases.

    The p-value roughly indicates the probability of an uncorrelated system
    producing datasets that have a Pearson correlation at least as extreme
    as the one computed from these datasets.

    Parameters
    ----------
    x : (N,) array_like
        Input array.
    y : (N,) array_like
        Input array.

    Returns
    -------
    r : float
        Pearson's correlation coefficient.
    p-value : float
        Two-tailed p-value.

    Warns
    -----
    PearsonRConstantInputWarning
        Raised if an input is a constant array.  The correlation coefficient
        is not defined in this case, so ``np.nan`` is returned.

    PearsonRNearConstantInputWarning
        Raised if an input is "nearly" constant.  The array ``x`` is considered
        nearly constant if ``norm(x - mean(x)) < 1e-13 * abs(mean(x))``.
        Numerical errors in the calculation ``x - mean(x)`` in this case might
        result in an inaccurate calculation of r.

    See Also
    --------
    spearmanr : Spearman rank-order correlation coefficient.
    kendalltau : Kendall's tau, a correlation measure for ordinal data.

    Notes
    -----
    The correlation coefficient is calculated as follows:

    .. math::

        r = \frac{\sum (x - m_x) (y - m_y)}
                 {\sqrt{\sum (x - m_x)^2 \sum (y - m_y)^2}}

    where :math:`m_x` is the mean of the vector :math:`x` and :math:`m_y` is
    the mean of the vector :math:`y`.

    Under the assumption that :math:`x` and :math:`m_y` are drawn from
    independent normal distributions (so the population correlation coefficient
    is 0), the probability density function of the sample correlation
    coefficient :math:`r` is ([1]_, [2]_):

    .. math::

        f(r) = \frac{{(1-r^2)}^{n/2-2}}{\mathrm{B}(\frac{1}{2},\frac{n}{2}-1)}

    where n is the number of samples, and B is the beta function.  This
    is sometimes referred to as the exact distribution of r.  This is
    the distribution that is used in `pearsonr` to compute the p-value.
    The distribution is a beta distribution on the interval [-1, 1],
    with equal shape parameters a = b = n/2 - 1.  In terms of SciPy's
    implementation of the beta distribution, the distribution of r is::

        dist = scipy.stats.beta(n/2 - 1, n/2 - 1, loc=-1, scale=2)

    The p-value returned by `pearsonr` is a two-sided p-value.  For a
    given sample with correlation coefficient r, the p-value is
    the probability that abs(r') of a random sample x' and y' drawn from
    the population with zero correlation would be greater than or equal
    to abs(r).  In terms of the object ``dist`` shown above, the p-value
    for a given r and length n can be computed as::

        p = 2*dist.cdf(-abs(r))

    When n is 2, the above continuous distribution is not well-defined.
    One can interpret the limit of the beta distribution as the shape
    parameters a and b approach a = b = 0 as a discrete distribution with
    equal probability masses at r = 1 and r = -1.  More directly, one
    can observe that, given the data x = [x1, x2] and y = [y1, y2], and
    assuming x1 != x2 and y1 != y2, the only possible values for r are 1
    and -1.  Because abs(r') for any sample x' and y' with length 2 will
    be 1, the two-sided p-value for a sample of length 2 is always 1.

    References
    ----------
    .. [1] "Pearson correlation coefficient", Wikipedia,
           https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
    .. [2] Student, "Probable error of a correlation coefficient",
           Biometrika, Volume 6, Issue 2-3, 1 September 1908, pp. 302-310.
    .. [3] C. J. Kowalski, "On the Effects of Non-Normality on the Distribution
           of the Sample Product-Moment Correlation Coefficient"
           Journal of the Royal Statistical Society. Series C (Applied
           Statistics), Vol. 21, No. 1 (1972), pp. 1-12.

    Examples
    --------
    >>> from scipy import stats
    >>> a = np.array([0, 0, 0, 1, 1, 1, 1])
    >>> b = np.arange(7)
    >>> stats.pearsonr(a, b)
    (0.8660254037844386, 0.011724811003954649)

    >>> stats.pearsonr([1, 2, 3, 4, 5], [10, 9, 2.5, 6, 4])
    (-0.7426106572325057, 0.1505558088534455)

    z"x and y must have the same length.r   z$x and y must have length at least 2.r   r   r   r   gvIh%<=      r   )r   rm   ro   r   r   rw   rx   rC   rt   r   r*  r   r   r   r  r   rD   dotr   r  r  Zbtdtrr   )r-  r#  r   r   ZxmeanZymeanZxmZymZnormxmZnormym	thresholdrabr  rd   rd   rg   rE   3  s6    x

 4

$
$rE   c                    s  t jtj| tjd}|jdks(tdt|dk r>tdd|jddv s^d|jddv rhtj	dfS |d	 dkr|d
 dkr|d |d  |d	 |d
   }ntj
}|d |d
  }|d	 |d  }|d |d	  } fdd}|dkr|d || ||}n|dkrB|d
 || ||d
 |d  }nt|dkrt|d |d  || d  |d || |||| ||}	d t|	 t|	 d  kr|dfS |d k r@|d || ||}
||| ||  kr||
fS ||||d}|
|d || || }nh|d d || ||}d|| ||  kr||fS ||||d}|||| || }nd}t|t|d}||fS )ap  Perform a Fisher exact test on a 2x2 contingency table.

    Parameters
    ----------
    table : array_like of ints
        A 2x2 contingency table.  Elements must be non-negative integers.
    alternative : {'two-sided', 'less', 'greater'}, optional
        Defines the alternative hypothesis.
        The following options are available (default is 'two-sided'):

        * 'two-sided'
        * 'less': one-sided
        * 'greater': one-sided

        See the Notes for more details.

    Returns
    -------
    oddsratio : float
        This is prior odds ratio and not a posterior estimate.
    p_value : float
        P-value, the probability of obtaining a distribution at least as
        extreme as the one that was actually observed, assuming that the
        null hypothesis is true.

    See Also
    --------
    chi2_contingency : Chi-square test of independence of variables in a
        contingency table.  This can be used as an alternative to
        `fisher_exact` when the numbers in the table are large.
    barnard_exact : Barnard's exact test, which is a more powerful alternative
        than Fisher's exact test for 2x2 contingency tables.
    boschloo_exact : Boschloo's exact test, which is a more powerful alternative
        than Fisher's exact test for 2x2 contingency tables.

    Notes
    -----
    *Null hypothesis and p-values*

    The null hypothesis is that the input table is from the hypergeometric
    distribution with parameters (as used in `hypergeom`)
    ``M = a + b + c + d``, ``n = a + b`` and ``N = a + c``, where the
    input table is ``[[a, b], [c, d]]``.  This distribution has support
    ``max(0, N + n - M) <= x <= min(N, n)``, or, in terms of the values
    in the input table, ``min(0, a - d) <= x <= a + min(b, c)``.  ``x``
    can be interpreted as the upper-left element of a 2x2 table, so the
    tables in the distribution have form::

        [  x           n - x     ]
        [N - x    M - (n + N) + x]

    For example, if::

        table = [6  2]
                [1  4]

    then the support is ``2 <= x <= 7``, and the tables in the distribution
    are::

        [2 6]   [3 5]   [4 4]   [5 3]   [6 2]  [7 1]
        [5 0]   [4 1]   [3 2]   [2 3]   [1 4]  [0 5]

    The probability of each table is given by the hypergeometric distribution
    ``hypergeom.pmf(x, M, n, N)``.  For this example, these are (rounded to
    three significant digits)::

        x       2      3      4      5       6        7
        p  0.0163  0.163  0.408  0.326  0.0816  0.00466

    These can be computed with::

        >>> from scipy.stats import hypergeom
        >>> table = np.array([[6, 2], [1, 4]])
        >>> M = table.sum()
        >>> n = table[0].sum()
        >>> N = table[:, 0].sum()
        >>> start, end = hypergeom.support(M, n, N)
        >>> hypergeom.pmf(np.arange(start, end+1), M, n, N)
        array([0.01631702, 0.16317016, 0.40792541, 0.32634033, 0.08158508,
               0.004662  ])

    The two-sided p-value is the probability that, under the null hypothesis,
    a random table would have a probability equal to or less than the
    probability of the input table.  For our example, the probability of
    the input table (where ``x = 6``) is 0.0816.  The x values where the
    probability does not exceed this are 2, 6 and 7, so the two-sided p-value
    is ``0.0163 + 0.0816 + 0.00466 ~= 0.10256``::

        >>> from scipy.stats import fisher_exact
        >>> oddsr, p = fisher_exact(table, alternative='two-sided')
        >>> p
        0.10256410256410257

    The one-sided p-value for ``alternative='greater'`` is the probability
    that a random table has ``x >= a``, which in our example is ``x >= 6``,
    or ``0.0816 + 0.00466 ~= 0.08626``::

        >>> oddsr, p = fisher_exact(table, alternative='greater')
        >>> p
        0.08624708624708627

    This is equivalent to computing the survival function of the
    distribution at ``x = 5`` (one less than ``x`` from the input table,
    because we want to include the probability of ``x = 6`` in the sum)::

        >>> hypergeom.sf(5, M, n, N)
        0.08624708624708627

    For ``alternative='less'``, the one-sided p-value is the probability
    that a random table has ``x <= a``, (i.e. ``x <= 6`` in our example),
    or ``0.0163 + 0.163 + 0.408 + 0.326 + 0.0816 ~= 0.9949``::

        >>> oddsr, p = fisher_exact(table, alternative='less')
        >>> p
        0.9953379953379957

    This is equivalent to computing the cumulative distribution function
    of the distribution at ``x = 6``:

        >>> hypergeom.cdf(6, M, n, N)
        0.9953379953379957

    *Odds ratio*

    The calculated odds ratio is different from the one R uses. This SciPy
    implementation returns the (more common) "unconditional Maximum
    Likelihood Estimate", while R uses the "conditional Maximum Likelihood
    Estimate".

    Examples
    --------
    Say we spend a few days counting whales and sharks in the Atlantic and
    Indian oceans. In the Atlantic ocean we find 8 whales and 1 shark, in the
    Indian ocean 2 whales and 5 sharks. Then our contingency table is::

                Atlantic  Indian
        whales     8        2
        sharks     1        5

    We use this table to find the p-value:

    >>> from scipy.stats import fisher_exact
    >>> oddsratio, pvalue = fisher_exact([[8, 2], [1, 5]])
    >>> pvalue
    0.0349...

    The probability that we would observe this or an even more imbalanced ratio
    by chance is about 3.5%.  A commonly used significance level is 5%--if we
    adopt that, we can therefore conclude that our observed imbalance is
    statistically significant; whales prefer the Atlantic while sharks prefer
    the Indian ocean.

    r   r   r   z*The input `table` must be of shape (2, 2).r   z*All values in `table` must be nonnegative.r   r   r   r   r   rZ  )r   r   )r   r   c           	         s  |dkr}| }nd}}d}|| dkr||d krD||krD|}n|| d } ||| || }|dkrv|d }n|d }|  kr ||| || k rq nqq|k r|}q|}q|dkr|}|dkr2|dkr ||| ||   k r|d8 }qԈ ||| ||   kr|d7 }qn^ ||| ||   k r\|d7 }q2|dkr ||| ||   kr|d8 }q\|S )z:Binary search for where to begin halves in two-sided test.r  r   r   r   r   )pmf)	r   r   r   sideminvalmaxvalguessZpguessngepsilon	hypergeomr   Zpexactrd   rg   binary_search  sF    
(



z#fisher_exact.<locals>.binary_searchr
  r  r  r   gH.?r  rI  z?`alternative` should be one of {'two-sided', 'less', 'greater'})r   r  ro   r   int64r   rm   r   rr   rt   r  r  r   r  r   r   r  r  )tabler  r  Z	oddsratior   r   r   r  r  ZpmodeZplowerr  Zpupperr0  rd   r  rg   rF     sT     
 
")

(
 $
rF   c                   @   s   e Zd ZdZdddZdS )rG   z;Warning generated by `spearmanr` when an input is constant.Nc                 C   s   |d u rd}|f| _ d S r  r  r  rd   rd   rg   r    s    z&SpearmanRConstantInputWarning.__init__)Nr  rd   rd   rd   rg   rG     s   rG   SpearmanrResult)Zcorrelationr  c                 C   s  |dur|dkrt d|t| |\} }| jdkr>t d|du rZ| jdk rt dn4t||\}}|dkrt| |f} nt| |f} | jd|  }| j| }|dkrttj	tj	S |dkr6| dddf d | dddf k
 s| dddf d | dddf k
 rtt  ttj	tj	S nn| dddf d | dddf k
 s| dddf d | dddf k
 rtt  ttj	tj	S t| |\}	}tj|td}
|	r"|d	krtj| |||d
S |dkr"| jdks|dkrttj	tj	S t| j|d}
tt|| }tj||d}|d }tjdd4 |t||d d|   d }W d   n1 s0    Y  t|||\}}|jdkrt|d |d S tj	||
ddf< tj	|dd|
f< t||S dS )a  Calculate a Spearman correlation coefficient with associated p-value.

    The Spearman rank-order correlation coefficient is a nonparametric measure
    of the monotonicity of the relationship between two datasets. Unlike the
    Pearson correlation, the Spearman correlation does not assume that both
    datasets are normally distributed. Like other correlation coefficients,
    this one varies between -1 and +1 with 0 implying no correlation.
    Correlations of -1 or +1 imply an exact monotonic relationship. Positive
    correlations imply that as x increases, so does y. Negative correlations
    imply that as x increases, y decreases.

    The p-value roughly indicates the probability of an uncorrelated system
    producing datasets that have a Spearman correlation at least as extreme
    as the one computed from these datasets. The p-values are not entirely
    reliable but are probably reasonable for datasets larger than 500 or so.

    Parameters
    ----------
    a, b : 1D or 2D array_like, b is optional
        One or two 1-D or 2-D arrays containing multiple variables and
        observations. When these are 1-D, each represents a vector of
        observations of a single variable. For the behavior in the 2-D case,
        see under ``axis``, below.
        Both arrays need to have the same length in the ``axis`` dimension.
    axis : int or None, optional
        If axis=0 (default), then each column represents a variable, with
        observations in the rows. If axis=1, the relationship is transposed:
        each row represents a variable, while the columns contain observations.
        If axis=None, then both arrays will be raveled.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

        * 'propagate': returns nan
        * 'raise': throws an error
        * 'omit': performs the calculations ignoring nan values

    alternative : {'two-sided', 'less', 'greater'}, optional
        Defines the alternative hypothesis. Default is 'two-sided'.
        The following options are available:

        * 'two-sided': the correlation is nonzero
        * 'less': the correlation is negative (less than zero)
        * 'greater':  the correlation is positive (greater than zero)

        .. versionadded:: 1.7.0

    Returns
    -------
    correlation : float or ndarray (2-D square)
        Spearman correlation matrix or correlation coefficient (if only 2
        variables are given as parameters. Correlation matrix is square with
        length equal to total number of variables (columns or rows) in ``a``
        and ``b`` combined.
    pvalue : float
        The p-value for a hypothesis test whose null hypotheisis
        is that two sets of data are uncorrelated. See `alternative` above
        for alternative hypotheses. `pvalue` has the same
        shape as `correlation`.

    References
    ----------
    .. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
       Probability and Statistics Tables and Formulae. Chapman & Hall: New
       York. 2000.
       Section  14.7

    Examples
    --------
    >>> from scipy import stats
    >>> stats.spearmanr([1,2,3,4,5], [5,6,7,8,7])
    SpearmanrResult(correlation=0.82078..., pvalue=0.08858...)
    >>> rng = np.random.default_rng()
    >>> x2n = rng.standard_normal((100, 2))
    >>> y2n = rng.standard_normal((100, 2))
    >>> stats.spearmanr(x2n)
    SpearmanrResult(correlation=-0.07960396039603959, pvalue=0.4311168705769747)
    >>> stats.spearmanr(x2n[:,0], x2n[:,1])
    SpearmanrResult(correlation=-0.07960396039603959, pvalue=0.4311168705769747)
    >>> rho, pval = stats.spearmanr(x2n, y2n)
    >>> rho
    array([[ 1.        , -0.07960396, -0.08314431,  0.09662166],
           [-0.07960396,  1.        , -0.14448245,  0.16738074],
           [-0.08314431, -0.14448245,  1.        ,  0.03234323],
           [ 0.09662166,  0.16738074,  0.03234323,  1.        ]])
    >>> pval
    array([[0.        , 0.43111687, 0.41084066, 0.33891628],
           [0.43111687, 0.        , 0.15151618, 0.09600687],
           [0.41084066, 0.15151618, 0.        , 0.74938561],
           [0.33891628, 0.09600687, 0.74938561, 0.        ]])
    >>> rho, pval = stats.spearmanr(x2n.T, y2n.T, axis=1)
    >>> rho
    array([[ 1.        , -0.07960396, -0.08314431,  0.09662166],
           [-0.07960396,  1.        , -0.14448245,  0.16738074],
           [-0.08314431, -0.14448245,  1.        ,  0.03234323],
           [ 0.09662166,  0.16738074,  0.03234323,  1.        ]])
    >>> stats.spearmanr(x2n, y2n, axis=None)
    SpearmanrResult(correlation=0.044981624540613524, pvalue=0.5270803651336189)
    >>> stats.spearmanr(x2n.ravel(), y2n.ravel())
    SpearmanrResult(correlation=0.044981624540613524, pvalue=0.5270803651336189)

    >>> rng = np.random.default_rng()
    >>> xint = rng.integers(10, size=(100, 2))
    >>> stats.spearmanr(xint)
    SpearmanrResult(correlation=0.09800224850707953, pvalue=0.3320271757932076)

    Nr   zqspearmanr only handles 1-D or 2-D arrays, supplied axis argument {}, please use only values 0, 1 or None for axisr   z(spearmanr only handles 1-D or 2-D arraysz1`spearmanr` needs at least 2 variables to comparer   r   rc   )r   r{   r  r`   r   )Zrowvarrj   r   r   r  r  )rm   r  r   r   ro   Zcolumn_stackZ	row_stackr   r  rt   r   rw   rx   rG   r}   r   boolr   rH   rq   r   rr  rZ   Zcorrcoefrp   r   clip_ttest_finish)rz   r   r   r{   r  Zaxisoutr3  Zn_varsZn_obsZa_contains_nanZvariable_has_nanZa_rankedrsZdofrk  r  rd   rd   rg   rH     s^    m




TT


DrH   PointbiserialrResultc                 C   s   t | |\}}t||S )a
  Calculate a point biserial correlation coefficient and its p-value.

    The point biserial correlation is used to measure the relationship
    between a binary variable, x, and a continuous variable, y. Like other
    correlation coefficients, this one varies between -1 and +1 with 0
    implying no correlation. Correlations of -1 or +1 imply a determinative
    relationship.

    This function uses a shortcut formula but produces the same result as
    `pearsonr`.

    Parameters
    ----------
    x : array_like of bools
        Input array.
    y : array_like
        Input array.

    Returns
    -------
    correlation : float
        R value.
    pvalue : float
        Two-sided p-value.

    Notes
    -----
    `pointbiserialr` uses a t-test with ``n-1`` degrees of freedom.
    It is equivalent to `pearsonr`.

    The value of the point-biserial correlation can be calculated from:

    .. math::

        r_{pb} = \frac{\overline{Y_{1}} -
                 \overline{Y_{0}}}{s_{y}}\sqrt{\frac{N_{1} N_{2}}{N (N - 1))}}

    Where :math:`Y_{0}` and :math:`Y_{1}` are means of the metric
    observations coded 0 and 1 respectively; :math:`N_{0}` and :math:`N_{1}`
    are number of observations coded 0 and 1 respectively; :math:`N` is the
    total number of observations and :math:`s_{y}` is the standard
    deviation of all the metric observations.

    A value of :math:`r_{pb}` that is significantly different from zero is
    completely equivalent to a significant difference in means between the two
    groups. Thus, an independent groups t Test with :math:`N-2` degrees of
    freedom may be used to test whether :math:`r_{pb}` is nonzero. The
    relation between the t-statistic for comparing two independent groups and
    :math:`r_{pb}` is given by:

    .. math::

        t = \sqrt{N - 2}\frac{r_{pb}}{\sqrt{1 - r^{2}_{pb}}}

    References
    ----------
    .. [1] J. Lev, "The Point Biserial Coefficient of Correlation", Ann. Math.
           Statist., Vol. 20, no.1, pp. 125-126, 1949.

    .. [2] R.F. Tate, "Correlation Between a Discrete and a Continuous
           Variable. Point-Biserial Correlation.", Ann. Math. Statist., Vol. 25,
           np. 3, pp. 603-607, 1954.

    .. [3] D. Kornbrot "Point Biserial Correlation", In Wiley StatsRef:
           Statistics Reference Online (eds N. Balakrishnan, et al.), 2014.
           :doi:`10.1002/9781118445112.stat06227`

    Examples
    --------
    >>> from scipy import stats
    >>> a = np.array([0, 0, 0, 1, 1, 1, 1])
    >>> b = np.arange(7)
    >>> stats.pointbiserialr(a, b)
    (0.8660254037844386, 0.011724811003954652)
    >>> stats.pearsonr(a, b)
    (0.86602540378443871, 0.011724811003954626)
    >>> np.corrcoef(a, b)
    array([[ 1.       ,  0.8660254],
           [ 0.8660254,  1.       ]])

    )rE   r  )r-  r#  Zrpbr  rd   rd   rg   rI     s    RrI   KendalltauResultautor   c                 C   sN  t |  } t | }| j|jkrBtd| j d|j n| jrN|js\tt jt jS t| |\}}t||\}}	|p~|}
|dks|	dkrd}|
r|dkrtt jt jS |
r|dkrt	| } t	|}|dkrt
j| ||ddS td|d	urtd
 dd }| j}t |}| | ||  } }t jd|dd	 |d	d kf jt jd}t j| dd}| | ||  } }t jd| dd	 | d	d kf jt jd} t| |}t jd| dd	 | d	d k|dd	 |d	d kB df }t t |d jddd}||d  d  }|| \}}}||\}}}||d  d }||ks^||krltt jt jS || | | d|  }|dkr|t ||  t ||  }nR|dkrttt| tt|}d| |d |d  |  }ntd| dtdtd|}|dkr8|dks0|dkr8td|dkr~|dkrz|dkrz|dkstt||| dkrzd}nd }|dkr|dkr|dkrt
|t||| }n|d kr4||d  }|d| d!  | | d" d| | |  || d#| |d    }tt |t | t d }ntd$| d%t||S )&a  Calculate Kendall's tau, a correlation measure for ordinal data.

    Kendall's tau is a measure of the correspondence between two rankings.
    Values close to 1 indicate strong agreement, and values close to -1
    indicate strong disagreement. This implements two variants of Kendall's
    tau: tau-b (the default) and tau-c (also known as Stuart's tau-c). These
    differ only in how they are normalized to lie within the range -1 to 1;
    the hypothesis tests (their p-values) are identical. Kendall's original
    tau-a is not implemented separately because both tau-b and tau-c reduce
    to tau-a in the absence of ties.

    Parameters
    ----------
    x, y : array_like
        Arrays of rankings, of the same shape. If arrays are not 1-D, they
        will be flattened to 1-D.
    initial_lexsort : bool, optional
        Unused (deprecated).
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

          * 'propagate': returns nan
          * 'raise': throws an error
          * 'omit': performs the calculations ignoring nan values

    method : {'auto', 'asymptotic', 'exact'}, optional
        Defines which method is used to calculate the p-value [5]_.
        The following options are available (default is 'auto'):

          * 'auto': selects the appropriate method based on a trade-off
            between speed and accuracy
          * 'asymptotic': uses a normal approximation valid for large samples
          * 'exact': computes the exact p-value, but can only be used if no ties
            are present. As the sample size increases, the 'exact' computation
            time may grow and the result may lose some precision.

    variant: {'b', 'c'}, optional
        Defines which variant of Kendall's tau is returned. Default is 'b'.

    Returns
    -------
    correlation : float
       The tau statistic.
    pvalue : float
       The two-sided p-value for a hypothesis test whose null hypothesis is
       an absence of association, tau = 0.

    See Also
    --------
    spearmanr : Calculates a Spearman rank-order correlation coefficient.
    theilslopes : Computes the Theil-Sen estimator for a set of points (x, y).
    weightedtau : Computes a weighted version of Kendall's tau.

    Notes
    -----
    The definition of Kendall's tau that is used is [2]_::

      tau_b = (P - Q) / sqrt((P + Q + T) * (P + Q + U))

      tau_c = 2 (P - Q) / (n**2 * (m - 1) / m)

    where P is the number of concordant pairs, Q the number of discordant
    pairs, T the number of ties only in `x`, and U the number of ties only in
    `y`.  If a tie occurs for the same pair in both `x` and `y`, it is not
    added to either T or U. n is the total number of samples, and m is the
    number of unique values in either `x` or `y`, whichever is smaller.

    References
    ----------
    .. [1] Maurice G. Kendall, "A New Measure of Rank Correlation", Biometrika
           Vol. 30, No. 1/2, pp. 81-93, 1938.
    .. [2] Maurice G. Kendall, "The treatment of ties in ranking problems",
           Biometrika Vol. 33, No. 3, pp. 239-251. 1945.
    .. [3] Gottfried E. Noether, "Elements of Nonparametric Statistics", John
           Wiley & Sons, 1967.
    .. [4] Peter M. Fenwick, "A new data structure for cumulative frequency
           tables", Software: Practice and Experience, Vol. 24, No. 3,
           pp. 327-336, 1994.
    .. [5] Maurice G. Kendall, "Rank Correlation Methods" (4th Edition),
           Charles Griffin & Co., 1970.

    Examples
    --------
    >>> from scipy import stats
    >>> x1 = [12, 2, 1, 12, 2]
    >>> x2 = [1, 4, 7, 1, 0]
    >>> tau, p_value = stats.kendalltau(x1, x2)
    >>> tau
    -0.47140452079103173
    >>> p_value
    0.2827454599327748

    zBAll inputs to `kendalltau` must be of the same size, found x-size z and y-size rc   r`   r   T)methodZuse_tiesz/Only variant 'b' is supported for masked arraysNz"initial_lexsort" is gone!c                 S   sf   t | jddd}||dk }||d  d  ||d  |d   ||d  d| d   fS )Nr  Fr   r   r   r   r  )ro   r:  r   rr   )Zrankscntrd   rd   rg   count_rank_tie  s    z"kendalltau.<locals>.count_rank_tier   r   r   	mergesortr   r   r  Fr  r   r  z&Unknown variant of the method chosen: z. variant must be 'b' or 'c'.r   r  exactz(Ties found, exact method cannot be used.r  r  Z
asymptoticr     r  zUnknown method z1 specified.  Use 'auto', 'exact' or 'asymptotic'.) ro   r   rv   r   rm   r  rt   r}   r   r   r   rJ   rw   rx   argsortr_rb  intpr   diffnonzeror   rr   r   r  r   ru   r   Z_kendall_p_exactr  erfcr   )r-  r#  Zinitial_lexsortr{   r  variantcnxnpxcnynpyr|   r  r   permdisobsr  ZntieZxtieZx0x1ZytieZy0y1ZtotZcon_minus_distauZ
minclassesr  r  r   rd   rd   rg   rJ     s    `





,,
<
"


rJ   WeightedTauResultc                 C   s  t |  } t | }| j|jkr<td| j|jf | jsPtt jt jS t t | rht	| } t t |rt	|}| j
|j
kr| j
t jkrt	| } |j
t jkrt	|}n*| j
t jt jt jt jfvrt	| } t	|}|du rtt| |d||t|| d|| d t jS |du r4t j| jt jd}n:|durnt | }|j| jkrntd| j|jf tt| ||||t jS )a:  Compute a weighted version of Kendall's :math:`\tau`.

    The weighted :math:`\tau` is a weighted version of Kendall's
    :math:`\tau` in which exchanges of high weight are more influential than
    exchanges of low weight. The default parameters compute the additive
    hyperbolic version of the index, :math:`\tau_\mathrm h`, which has
    been shown to provide the best balance between important and
    unimportant elements [1]_.

    The weighting is defined by means of a rank array, which assigns a
    nonnegative rank to each element (higher importance ranks being
    associated with smaller values, e.g., 0 is the highest possible rank),
    and a weigher function, which assigns a weight based on the rank to
    each element. The weight of an exchange is then the sum or the product
    of the weights of the ranks of the exchanged elements. The default
    parameters compute :math:`\tau_\mathrm h`: an exchange between
    elements with rank :math:`r` and :math:`s` (starting from zero) has
    weight :math:`1/(r+1) + 1/(s+1)`.

    Specifying a rank array is meaningful only if you have in mind an
    external criterion of importance. If, as it usually happens, you do
    not have in mind a specific rank, the weighted :math:`\tau` is
    defined by averaging the values obtained using the decreasing
    lexicographical rank by (`x`, `y`) and by (`y`, `x`). This is the
    behavior with default parameters. Note that the convention used
    here for ranking (lower values imply higher importance) is opposite
    to that used by other SciPy statistical functions.

    Parameters
    ----------
    x, y : array_like
        Arrays of scores, of the same shape. If arrays are not 1-D, they will
        be flattened to 1-D.
    rank : array_like of ints or bool, optional
        A nonnegative rank assigned to each element. If it is None, the
        decreasing lexicographical rank by (`x`, `y`) will be used: elements of
        higher rank will be those with larger `x`-values, using `y`-values to
        break ties (in particular, swapping `x` and `y` will give a different
        result). If it is False, the element indices will be used
        directly as ranks. The default is True, in which case this
        function returns the average of the values obtained using the
        decreasing lexicographical rank by (`x`, `y`) and by (`y`, `x`).
    weigher : callable, optional
        The weigher function. Must map nonnegative integers (zero
        representing the most important element) to a nonnegative weight.
        The default, None, provides hyperbolic weighing, that is,
        rank :math:`r` is mapped to weight :math:`1/(r+1)`.
    additive : bool, optional
        If True, the weight of an exchange is computed by adding the
        weights of the ranks of the exchanged elements; otherwise, the weights
        are multiplied. The default is True.

    Returns
    -------
    correlation : float
       The weighted :math:`\tau` correlation index.
    pvalue : float
       Presently ``np.nan``, as the null statistics is unknown (even in the
       additive hyperbolic case).

    See Also
    --------
    kendalltau : Calculates Kendall's tau.
    spearmanr : Calculates a Spearman rank-order correlation coefficient.
    theilslopes : Computes the Theil-Sen estimator for a set of points (x, y).

    Notes
    -----
    This function uses an :math:`O(n \log n)`, mergesort-based algorithm
    [1]_ that is a weighted extension of Knight's algorithm for Kendall's
    :math:`\tau` [2]_. It can compute Shieh's weighted :math:`\tau` [3]_
    between rankings without ties (i.e., permutations) by setting
    `additive` and `rank` to False, as the definition given in [1]_ is a
    generalization of Shieh's.

    NaNs are considered the smallest possible score.

    .. versionadded:: 0.19.0

    References
    ----------
    .. [1] Sebastiano Vigna, "A weighted correlation index for rankings with
           ties", Proceedings of the 24th international conference on World
           Wide Web, pp. 1166-1176, ACM, 2015.
    .. [2] W.R. Knight, "A Computer Method for Calculating Kendall's Tau with
           Ungrouped Data", Journal of the American Statistical Association,
           Vol. 61, No. 314, Part 1, pp. 436-439, 1966.
    .. [3] Grace S. Shieh. "A weighted Kendall's tau statistic", Statistics &
           Probability Letters, Vol. 39, No. 1, pp. 17-24, 1998.

    Examples
    --------
    >>> from scipy import stats
    >>> x = [12, 2, 1, 12, 2]
    >>> y = [1, 4, 7, 1, 0]
    >>> tau, p_value = stats.weightedtau(x, y)
    >>> tau
    -0.56694968153682723
    >>> p_value
    nan
    >>> tau, p_value = stats.weightedtau(x, y, additive=False)
    >>> tau
    -0.62205716951801038

    NaNs are considered the smallest possible score:

    >>> x = [12, 2, 1, 12, 2]
    >>> y = [1, 4, 7, 1, np.nan]
    >>> tau, _ = stats.weightedtau(x, y)
    >>> tau
    -0.56694968153682723

    This is exactly Kendall's tau:

    >>> x = [12, 2, 1, 12, 2]
    >>> y = [1, 4, 7, 1, 0]
    >>> tau, _ = stats.weightedtau(x, y, weigher=lambda x: 1)
    >>> tau
    -0.47140452079103173

    >>> x = [12, 2, 1, 12, 2]
    >>> y = [1, 4, 7, 1, 0]
    >>> stats.weightedtau(x, y, rank=None)
    WeightedTauResult(correlation=-0.4157652301037516, pvalue=nan)
    >>> stats.weightedtau(y, x, rank=None)
    WeightedTauResult(correlation=-0.7181341329699028, pvalue=nan)

    zSAll inputs to `weightedtau` must be of the same size, found x-size %s and y-size %sTNr   Fr   zVAll inputs to `weightedtau` must be of the same size, found x-size %s and rank-size %s)ro   r   rv   r   rm   r  rt   rq   rr   r   r   r  int32Zfloat32r   r   aranger  )r-  r#  rP  ZweigherZadditiverd   rd   rg   rK     sV     





rK   c                   @   s    e Zd ZdZdd Zdd ZdS )
_ParallelPz.Helper function to calculate parallel p-value.c                 C   s   || _ || _|| _d S r  r-  r#  random_states)r  r-  r#  r	  rd   rd   rg   r    s    z_ParallelP.__init__c                 C   sB   | j | | jjd }| j| d d |f }t| j|d }|S r~   )r	  permutationr#  r   	_mgc_statr-  )r  indexorderZpermyZ	perm_statrd   rd   rg   __call__  s    z_ParallelP.__call__N)r  r  r  r  r  r  rd   rd   rd   rg   r    s   r  r  r   c                    s   t    fddt|D }t| ||d}t|(}tt||t|}	W d   n1 sb0    Y  |	|k | }
|
dkrd| }
|
|	fS )a  Helper function that calculates the p-value. See below for uses.

    Parameters
    ----------
    x, y : ndarray
        `x` and `y` have shapes `(n, p)` and `(n, q)`.
    stat : float
        The sample test statistic.
    reps : int, optional
        The number of replications used to estimate the null when using the
        permutation test. The default is 1000 replications.
    workers : int or map-like callable, optional
        If `workers` is an int the population is subdivided into `workers`
        sections and evaluated in parallel (uses
        `multiprocessing.Pool <multiprocessing>`). Supply `-1` to use all cores
        available to the Process. Alternatively supply a map-like callable,
        such as `multiprocessing.Pool.map` for evaluating the population in
        parallel. This evaluation is carried out as `workers(func, iterable)`.
        Requires that `func` be pickleable.
    random_state : {None, int, `numpy.random.Generator`,
                    `numpy.random.RandomState`}, optional

        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
        singleton is used.
        If `seed` is an int, a new ``RandomState`` instance is used,
        seeded with `seed`.
        If `seed` is already a ``Generator`` or ``RandomState`` instance then
        that instance is used.

    Returns
    -------
    pvalue : float
        The sample test p-value.
    null_dist : list
        The approximated null distribution.

    c              
      s&   g | ]}t jt d dt jdqS )l        r   )r   r   )ro   randomZRandomStater   Zuint32)re   r3  random_staterd   rg   r     s   z_perm_test.<locals>.<listcomp>r  Nr   r   )r
   r   r  r   ro   r   r   rr   )r-  r#  statrepsworkersr  r	  Z	parallelpZ
mapwrapper	null_distr  rd   r  rg   
_perm_test  s    (

6r  c                 C   s
   t | | S r  r   )r-  rd   rd   rg   _euclidean_dist  s    r  	MGCResult)r  r  mgc_dictc                 C   s&  t | tjrt |tjs td| jdkr>| ddtjf } n| jdkrXtd| j|jdkrv|ddtjf }n|jdkrtd|j| j\}}|j\}	}
t| dd t|dd t	t
| d	kst	t
|d	krtd
||	kr||
krd}ntd|dk s"|	dk r*td| tj} |tj}t|s^|dur^tdt |trt|d	k r~tdn|dk rd}t|t |r|du rtdt| |\} }|dur|| } ||}t| |\}}|d }|d }t| |||||d\}}|||d}t|||S )a"$  Computes the Multiscale Graph Correlation (MGC) test statistic.

    Specifically, for each point, MGC finds the :math:`k`-nearest neighbors for
    one property (e.g. cloud density), and the :math:`l`-nearest neighbors for
    the other property (e.g. grass wetness) [1]_. This pair :math:`(k, l)` is
    called the "scale". A priori, however, it is not know which scales will be
    most informative. So, MGC computes all distance pairs, and then efficiently
    computes the distance correlations for all scales. The local correlations
    illustrate which scales are relatively informative about the relationship.
    The key, therefore, to successfully discover and decipher relationships
    between disparate data modalities is to adaptively determine which scales
    are the most informative, and the geometric implication for the most
    informative scales. Doing so not only provides an estimate of whether the
    modalities are related, but also provides insight into how the
    determination was made. This is especially important in high-dimensional
    data, where simple visualizations do not reveal relationships to the
    unaided human eye. Characterizations of this implementation in particular
    have been derived from and benchmarked within in [2]_.

    Parameters
    ----------
    x, y : ndarray
        If ``x`` and ``y`` have shapes ``(n, p)`` and ``(n, q)`` where `n` is
        the number of samples and `p` and `q` are the number of dimensions,
        then the MGC independence test will be run.  Alternatively, ``x`` and
        ``y`` can have shapes ``(n, n)`` if they are distance or similarity
        matrices, and ``compute_distance`` must be sent to ``None``. If ``x``
        and ``y`` have shapes ``(n, p)`` and ``(m, p)``, an unpaired
        two-sample MGC test will be run.
    compute_distance : callable, optional
        A function that computes the distance or similarity among the samples
        within each data matrix. Set to ``None`` if ``x`` and ``y`` are
        already distance matrices. The default uses the euclidean norm metric.
        If you are calling a custom function, either create the distance
        matrix before-hand or create a function of the form
        ``compute_distance(x)`` where `x` is the data matrix for which
        pairwise distances are calculated.
    reps : int, optional
        The number of replications used to estimate the null when using the
        permutation test. The default is ``1000``.
    workers : int or map-like callable, optional
        If ``workers`` is an int the population is subdivided into ``workers``
        sections and evaluated in parallel (uses ``multiprocessing.Pool
        <multiprocessing>``). Supply ``-1`` to use all cores available to the
        Process. Alternatively supply a map-like callable, such as
        ``multiprocessing.Pool.map`` for evaluating the p-value in parallel.
        This evaluation is carried out as ``workers(func, iterable)``.
        Requires that `func` be pickleable. The default is ``1``.
    is_twosamp : bool, optional
        If `True`, a two sample test will be run. If ``x`` and ``y`` have
        shapes ``(n, p)`` and ``(m, p)``, this optional will be overriden and
        set to ``True``. Set to ``True`` if ``x`` and ``y`` both have shapes
        ``(n, p)`` and a two sample test is desired. The default is ``False``.
        Note that this will not run if inputs are distance matrices.
    random_state : {None, int, `numpy.random.Generator`,
                    `numpy.random.RandomState`}, optional

        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
        singleton is used.
        If `seed` is an int, a new ``RandomState`` instance is used,
        seeded with `seed`.
        If `seed` is already a ``Generator`` or ``RandomState`` instance then
        that instance is used.

    Returns
    -------
    stat : float
        The sample MGC test statistic within `[-1, 1]`.
    pvalue : float
        The p-value obtained via permutation.
    mgc_dict : dict
        Contains additional useful additional returns containing the following
        keys:

            - mgc_map : ndarray
                A 2D representation of the latent geometry of the relationship.
                of the relationship.
            - opt_scale : (int, int)
                The estimated optimal scale as a `(x, y)` pair.
            - null_dist : list
                The null distribution derived from the permuted matrices

    See Also
    --------
    pearsonr : Pearson correlation coefficient and p-value for testing
               non-correlation.
    kendalltau : Calculates Kendall's tau.
    spearmanr : Calculates a Spearman rank-order correlation coefficient.

    Notes
    -----
    A description of the process of MGC and applications on neuroscience data
    can be found in [1]_. It is performed using the following steps:

    #. Two distance matrices :math:`D^X` and :math:`D^Y` are computed and
       modified to be mean zero columnwise. This results in two
       :math:`n \times n` distance matrices :math:`A` and :math:`B` (the
       centering and unbiased modification) [3]_.

    #. For all values :math:`k` and :math:`l` from :math:`1, ..., n`,

       * The :math:`k`-nearest neighbor and :math:`l`-nearest neighbor graphs
         are calculated for each property. Here, :math:`G_k (i, j)` indicates
         the :math:`k`-smallest values of the :math:`i`-th row of :math:`A`
         and :math:`H_l (i, j)` indicates the :math:`l` smallested values of
         the :math:`i`-th row of :math:`B`

       * Let :math:`\circ` denotes the entry-wise matrix product, then local
         correlations are summed and normalized using the following statistic:

    .. math::

        c^{kl} = \frac{\sum_{ij} A G_k B H_l}
                      {\sqrt{\sum_{ij} A^2 G_k \times \sum_{ij} B^2 H_l}}

    #. The MGC test statistic is the smoothed optimal local correlation of
       :math:`\{ c^{kl} \}`. Denote the smoothing operation as :math:`R(\cdot)`
       (which essentially set all isolated large correlations) as 0 and
       connected large correlations the same as before, see [3]_.) MGC is,

    .. math::

        MGC_n (x, y) = \max_{(k, l)} R \left(c^{kl} \left( x_n, y_n \right)
                                                    \right)

    The test statistic returns a value between :math:`(-1, 1)` since it is
    normalized.

    The p-value returned is calculated using a permutation test. This process
    is completed by first randomly permuting :math:`y` to estimate the null
    distribution and then calculating the probability of observing a test
    statistic, under the null, at least as extreme as the observed test
    statistic.

    MGC requires at least 5 samples to run with reliable results. It can also
    handle high-dimensional data sets.
    In addition, by manipulating the input data matrices, the two-sample
    testing problem can be reduced to the independence testing problem [4]_.
    Given sample data :math:`U` and :math:`V` of sizes :math:`p \times n`
    :math:`p \times m`, data matrix :math:`X` and :math:`Y` can be created as
    follows:

    .. math::

        X = [U | V] \in \mathcal{R}^{p \times (n + m)}
        Y = [0_{1 \times n} | 1_{1 \times m}] \in \mathcal{R}^{(n + m)}

    Then, the MGC statistic can be calculated as normal. This methodology can
    be extended to similar tests such as distance correlation [4]_.

    .. versionadded:: 1.4.0

    References
    ----------
    .. [1] Vogelstein, J. T., Bridgeford, E. W., Wang, Q., Priebe, C. E.,
           Maggioni, M., & Shen, C. (2019). Discovering and deciphering
           relationships across disparate data modalities. ELife.
    .. [2] Panda, S., Palaniappan, S., Xiong, J., Swaminathan, A.,
           Ramachandran, S., Bridgeford, E. W., ... Vogelstein, J. T. (2019).
           mgcpy: A Comprehensive High Dimensional Independence Testing Python
           Package. :arXiv:`1907.02088`
    .. [3] Shen, C., Priebe, C.E., & Vogelstein, J. T. (2019). From distance
           correlation to multiscale graph correlation. Journal of the American
           Statistical Association.
    .. [4] Shen, C. & Vogelstein, J. T. (2018). The Exact Equivalence of
           Distance and Kernel Methods for Hypothesis Testing.
           :arXiv:`1806.05514`

    Examples
    --------
    >>> from scipy.stats import multiscale_graphcorr
    >>> x = np.arange(100)
    >>> y = x
    >>> stat, pvalue, _ = multiscale_graphcorr(x, y, workers=-1)
    >>> '%.1f, %.3f' % (stat, pvalue)
    '1.0, 0.001'

    Alternatively,

    >>> x = np.arange(100)
    >>> y = x
    >>> mgc = multiscale_graphcorr(x, y)
    >>> '%.1f, %.3f' % (mgc.stat, mgc.pvalue)
    '1.0, 0.001'

    To run an unpaired two-sample test,

    >>> x = np.arange(100)
    >>> y = np.arange(79)
    >>> mgc = multiscale_graphcorr(x, y)
    >>> '%.3f, %.2f' % (mgc.stat, mgc.pvalue)  # doctest: +SKIP
    '0.033, 0.02'

    or, if shape of the inputs are the same,

    >>> x = np.arange(100)
    >>> y = x
    >>> mgc = multiscale_graphcorr(x, y, is_twosamp=True)
    >>> '%.3f, %.1f' % (mgc.stat, mgc.pvalue)  # doctest: +SKIP
    '-0.008, 1.0'

    zx and y must be ndarraysr   Nr   z(Expected a 2-D array `x`, found shape {}z(Expected a 2-D array `y`, found shape {}rb   r  r   zInputs contain infinitiesTzZShape mismatch, x and y must have shape [n, p] and [n, q] or have shape [n, p] and [m, p].r  z;MGC requires at least 5 samples to give reasonable results.z$Compute_distance must be a function.z1Number of reps must be an integer greater than 0.r  zThe number of replications is low (under 1000), and p-value calculations may be unreliable. Use the p-value result, with caution!z*Cannot run if inputs are distance matricesstat_mgc_map	opt_scale)r  r  r  )Zmgc_mapr  r  )r   ro   r   rm   r   Znewaxisr  r   r}   rr   rz  r   r   r  r   rw   rx   ry   _two_sample_transformr  r  r  )r-  r#  Zcompute_distancer  r  Z
is_twosampr  nxZpxnypyr0  r  	stat_dictr  r  r  r  r  rd   rd   rg   rL     sl     M





(






rL   c           
      C   s|   t | |dd}|j\}}|dks(|dkrF||d  |d  }|| }n$t| d }t||}t||\}}||d}	||	fS )as  Helper function that calculates the MGC stat. See above for use.

    Parameters
    ----------
    x, y : ndarray
        `x` and `y` have shapes `(n, p)` and `(n, q)` or `(n, n)` and `(n, n)`
        if distance matrices.

    Returns
    -------
    stat : float
        The sample MGC test statistic within `[-1, 1]`.
    stat_dict : dict
        Contains additional useful additional returns containing the following
        keys:

            - stat_mgc_map : ndarray
                MGC-map of the statistics.
            - opt_scale : (float, float)
                The estimated optimal scale as a `(x, y)` pair.

    Zmgc)Zglobal_corrr   )r  r  )r   r   r   _threshold_mgc_map_smooth_mgc_map)
ZdistxZdistyr  r   r  r  r  	samp_sizesig_connectr   rd   rd   rg   r    s    


r  c           
      C   s   | j \}}dd|  }||d  d d }tj|||d d }t|| |d  |d  }| |k}t|dkrt|\}}tj	|dd	\}}t
|dd
 d }	||	k}ntdgg}|S )ar  
    Finds a connected region of significance in the MGC-map by thresholding.

    Parameters
    ----------
    stat_mgc_map : ndarray
        All local correlations within `[-1,1]`.
    samp_size : int
        The sample size of original data.

    Returns
    -------
    sig_connect : ndarray
        A binary matrix with 1's indicating the significant region.

    r   {Gz?r   r   r   r   r   Tr   NF)r   r   betaZppfr   ro   rr   r	   labelr   r   r   )
r  r#  r  r   Zper_sigr  r$  r3  Zlabel_countsZ	max_labelrd   rd   rg   r!  1  s    

r!  c                 C   s   |j \}}||d  |d  }||g}tj| dkrt| tdt|| t|| krt||  }t||k| @ }||kr|}|\}}	|| |	 }
t|
| }t|
| }	|d |	d g}||fS )aJ  Finds the smoothed maximal within the significant region R.

    If area of R is too small it returns the last local correlation. Otherwise,
    returns the maximum within significant_connected_region.

    Parameters
    ----------
    sig_connect: ndarray
        A binary matrix with 1's indicating the significant region.
    stat_mgc_map: ndarray
        All local correlations within `[-1, 1]`.

    Returns
    -------
    stat : float
        The sample MGC statistic within `[-1, 1]`.
    opt_scale: (float, float)
        The estimated optimal scale as an `(x, y)` pair.

    r   r   r%  )	r   ro   r   r  rr   rL  r   r  r   )r$  r  r  r   r  r  Zmax_corrZmax_corr_indexr4  re  Zone_d_indicesrd   rd   rg   r"  ^  s    
(r"  c                 C   sT   | j d }|j d }tj| |gdd}tjt|t|gdddd}||fS )a  Helper function that concatenates x and y for two sample MGC stat.

    See above for use.

    Parameters
    ----------
    u, v : ndarray
        `u` and `v` have shapes `(n, p)` and `(m, p)`.

    Returns
    -------
    x : ndarray
        Concatenate `u` and `v` along the `axis = 0`. `x` thus has shape
        `(2n, p)`.
    y : ndarray
        Label matrix for `x` where 0 refers to samples that comes from `u` and
        1 refers to samples that come from `v`. `y` thus has shape `(2n, 1)`.

    r   r   r   r   )r   ro   r  r   r   r   )ur  r  r  r-  r#  rd   rd   rg   r    s
    

&r  Ttest_1sampResultc                 C   s   t | |\} }t| |\}}|rP|dkrP|dkr8tdt| } t| ||S | j| }|d }t	| || }tj
| |dd}	t|	| }
tjddd t||
}W d   n1 s0    Y  t|||\}}t||S )	a
  Calculate the T-test for the mean of ONE group of scores.

    This is a two-sided test for the null hypothesis that the expected value
    (mean) of a sample of independent observations `a` is equal to the given
    population mean, `popmean`.

    Parameters
    ----------
    a : array_like
        Sample observation.
    popmean : float or array_like
        Expected value in null hypothesis. If array_like, then it must have the
        same shape as `a` excluding the axis dimension.
    axis : int or None, optional
        Axis along which to compute test; default is 0. If None, compute over
        the whole array `a`.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

          * 'propagate': returns nan
          * 'raise': throws an error
          * 'omit': performs the calculations ignoring nan values
    alternative : {'two-sided', 'less', 'greater'}, optional
        Defines the alternative hypothesis.
        The following options are available (default is 'two-sided'):

          * 'two-sided'
          * 'less': one-sided
          * 'greater': one-sided

        .. versionadded:: 1.6.0

    Returns
    -------
    statistic : float or array
        t-statistic.
    pvalue : float or array
        Two-sided p-value.

    Examples
    --------
    >>> from scipy import stats
    >>> rng = np.random.default_rng()
    >>> rvs = stats.norm.rvs(loc=5, scale=10, size=(50, 2), random_state=rng)

    Test if mean of random sample is equal to true mean, and different mean.
    We reject the null hypothesis in the second case and don't reject it in
    the first case.

    >>> stats.ttest_1samp(rvs, 5.0)
    Ttest_1sampResult(statistic=array([-2.09794637, -1.75977004]), pvalue=array([0.04108952, 0.08468867]))
    >>> stats.ttest_1samp(rvs, 0.0)
    Ttest_1sampResult(statistic=array([1.64495065, 1.62095307]), pvalue=array([0.10638103, 0.11144602]))

    Examples using axis and non-scalar dimension for population mean.

    >>> result = stats.ttest_1samp(rvs, [5.0, 0.0])
    >>> result.statistic
    array([-2.09794637,  1.62095307])
    >>> result.pvalue
    array([0.04108952, 0.11144602])

    >>> result = stats.ttest_1samp(rvs.T, [5.0, 0.0], axis=1)
    >>> result.statistic
    array([-2.09794637,  1.62095307])
    >>> result.pvalue
    array([0.04108952, 0.11144602])

    >>> result = stats.ttest_1samp(rvs, [[5.0], [0.0]])
    >>> result.statistic
    array([[-2.09794637, -1.75977004],
           [ 1.64495065,  1.62095307]])
    >>> result.pvalue
    array([[0.04108952, 0.08468867],
           [0.10638103, 0.11144602]])

    rc   r  r  r   r   rj   r  N)r   r}   rm   r   r   r   rM   r   ro   r   r   r   rp   r   r  r)  )rz   Zpopmeanr   r{   r  r|   r   dfr   r  r/  rk  r  rd   rd   rg   rM     s     P

*rM   c                 C   st   |dkrt j|| }nB|dkr0t j|| }n*|dkrRdt jt||  }ntd|jdkrl|d }||fS )z+Common code between all 3 t-test functions.r
  r  r  r   r  r   rd   )r   rk  r  r  ro   r   rm   r   )r*  rk  r  r  rd   rd   rg   r    s    
r  c                 C   sZ   | | }t jddd t ||}W d    n1 s80    Y  t|||\}}||fS )Nrj   r  )ro   rp   r   r  )mean1mean2r/  r*  r  r   rk  r  rd   rd   rg   _ttest_ind_from_stats/  s
    *r-  c                 C   s   | | }|| }t jddd< || d |d |d  |d |d    }W d    n1 s`0    Y  t t |d|}t || }||fS )Nrj   r  r   r   )ro   rp   r   rq   r   )v1r   v2r   Zvn1Zvn2r*  r/  rd   rd   rg   _unequal_var_ttest_denom9  s    Jr0  c                 C   sJ   || d }|d |  |d |  | }t |d| d|   }||fS )Nr   r   r   )ro   r   )r.  r   r/  r   r*  Zsvarr/  rd   rd   rg   _equal_var_ttest_denomF  s    r1  Ttest_indResultc                 C   sz   t | } t |}t |}t |}|rHt|d ||d |\}}	nt|d ||d |\}}	t| ||	||}
t|
 S )a  
    T-test for means of two independent samples from descriptive statistics.

    This is a two-sided test for the null hypothesis that two independent
    samples have identical average (expected) values.

    Parameters
    ----------
    mean1 : array_like
        The mean(s) of sample 1.
    std1 : array_like
        The standard deviation(s) of sample 1.
    nobs1 : array_like
        The number(s) of observations of sample 1.
    mean2 : array_like
        The mean(s) of sample 2.
    std2 : array_like
        The standard deviations(s) of sample 2.
    nobs2 : array_like
        The number(s) of observations of sample 2.
    equal_var : bool, optional
        If True (default), perform a standard independent 2 sample test
        that assumes equal population variances [1]_.
        If False, perform Welch's t-test, which does not assume equal
        population variance [2]_.
    alternative : {'two-sided', 'less', 'greater'}, optional
        Defines the alternative hypothesis.
        The following options are available (default is 'two-sided'):

          * 'two-sided'
          * 'less': one-sided
          * 'greater': one-sided

        .. versionadded:: 1.6.0

    Returns
    -------
    statistic : float or array
        The calculated t-statistics.
    pvalue : float or array
        The two-tailed p-value.

    See Also
    --------
    scipy.stats.ttest_ind

    Notes
    -----
    .. versionadded:: 0.16.0

    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test

    .. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test

    Examples
    --------
    Suppose we have the summary data for two samples, as follows::

                         Sample   Sample
                   Size   Mean   Variance
        Sample 1    13    15.0     87.5
        Sample 2    11    12.0     39.0

    Apply the t-test to this data (with the assumption that the population
    variances are equal):

    >>> from scipy.stats import ttest_ind_from_stats
    >>> ttest_ind_from_stats(mean1=15.0, std1=np.sqrt(87.5), nobs1=13,
    ...                      mean2=12.0, std2=np.sqrt(39.0), nobs2=11)
    Ttest_indResult(statistic=0.9051358093310269, pvalue=0.3751996797581487)

    For comparison, here is the data from which those summary statistics
    were taken.  With this data, we can compute the same result using
    `scipy.stats.ttest_ind`:

    >>> a = np.array([1, 3, 4, 6, 11, 13, 15, 19, 22, 24, 25, 26, 26])
    >>> b = np.array([2, 4, 6, 9, 11, 13, 14, 15, 18, 19, 21])
    >>> from scipy.stats import ttest_ind
    >>> ttest_ind(a, b)
    Ttest_indResult(statistic=0.905135809331027, pvalue=0.3751996797581486)

    Suppose we instead have binary data and would like to apply a t-test to
    compare the proportion of 1s in two independent groups::

                          Number of    Sample     Sample
                    Size    ones        Mean     Variance
        Sample 1    150      30         0.2        0.16
        Sample 2    200      45         0.225      0.174375

    The sample mean :math:`\hat{p}` is the proportion of ones in the sample
    and the variance for a binary observation is estimated by
    :math:`\hat{p}(1-\hat{p})`.

    >>> ttest_ind_from_stats(mean1=0.2, std1=np.sqrt(0.16), nobs1=150,
    ...                      mean2=0.225, std2=np.sqrt(0.17437), nobs2=200)
    Ttest_indResult(statistic=-0.564327545549774, pvalue=0.5728947691244874)

    For comparison, we could compute the t statistic and p-value using
    arrays of 0s and 1s and `scipy.stat.ttest_ind`, as above.

    >>> group1 = np.array([1]*30 + [0]*(150-30))
    >>> group2 = np.array([1]*45 + [0]*(200-45))
    >>> ttest_ind(group1, group2)
    Ttest_indResult(statistic=-0.5627179589855622, pvalue=0.573989277115258)

    r   )ro   r   r1  r0  r-  r2  )r+  Zstd1Znobs1r,  Zstd2Znobs2	equal_varr  r*  r/  r   rd   rd   rg   rO   P  s    n




rO   c                 C   sH   t | ||}t|dkr&tj}tj}ntj|tjd}| }|||S )a  
    Generate an array of `nan`, with shape determined by `a`, `b` and `axis`.

    This function is used by ttest_ind and ttest_rel to create the return
    value when one of the inputs has size 0.

    The shapes of the arrays are determined by dropping `axis` from the
    shapes of `a` and `b` and broadcasting what is left.

    The return value is a named tuple of the type given in `namedtuple_type`.

    Examples
    --------
    >>> a = np.zeros((9, 2))
    >>> b = np.zeros((5, 1))
    >>> _ttest_nans(a, b, 0, Ttest_indResult)
    Ttest_indResult(statistic=array([nan, nan]), pvalue=array([nan, nan]))

    >>> a = np.zeros((3, 0, 9))
    >>> b = np.zeros((1, 10))
    >>> stat, p = _ttest_nans(a, b, -1, Ttest_indResult)
    >>> stat
    array([], shape=(3, 0), dtype=float64)
    >>> p
    array([], shape=(3, 0), dtype=float64)

    >>> a = np.zeros(10)
    >>> b = np.zeros(7)
    >>> _ttest_nans(a, b, 0, Ttest_indResult)
    Ttest_indResult(statistic=nan, pvalue=nan)

    r   r   )r   r   ro   rt   r   r   )rz   r   r   Znamedtuple_typer   rk  r8  rd   rd   rg   _ttest_nans  s    !r4  c	              
   C   s   d|  krdk sn t dt| ||\} }}t| |\}	}
t||\}}|	pR|}|
dksd|dkrhd}|r|dkr|s|dks|dkrt dt| } t|}t| |||S | jdks|jdkrt| ||t	S |dur@|dkr@|dkrt d|dk st
|r&t||kr&t d	t| |||||||d
}n| j| }|j| }|dkrt
j| |dd}t
j||dd}t
| |}t
||}n$t| ||\}}}t|||\}}}|rt||||\}}nt||||\}}t|||||}t	| S )a#  
    Calculate the T-test for the means of *two independent* samples of scores.

    This is a two-sided test for the null hypothesis that 2 independent samples
    have identical average (expected) values. This test assumes that the
    populations have identical variances by default.

    Parameters
    ----------
    a, b : array_like
        The arrays must have the same shape, except in the dimension
        corresponding to `axis` (the first, by default).
    axis : int or None, optional
        Axis along which to compute test. If None, compute over the whole
        arrays, `a`, and `b`.
    equal_var : bool, optional
        If True (default), perform a standard independent 2 sample test
        that assumes equal population variances [1]_.
        If False, perform Welch's t-test, which does not assume equal
        population variance [2]_.

        .. versionadded:: 0.11.0

    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

          * 'propagate': returns nan
          * 'raise': throws an error
          * 'omit': performs the calculations ignoring nan values

        The 'omit' option is not currently available for permutation tests or
        one-sided asympyotic tests.

    permutations : non-negative int, np.inf, or None (default), optional
        If 0 or None (default), use the t-distribution to calculate p-values.
        Otherwise, `permutations` is  the number of random permutations that
        will be used to estimate p-values using a permutation test. If
        `permutations` equals or exceeds the number of distinct partitions of
        the pooled data, an exact test is performed instead (i.e. each
        distinct partition is used exactly once). See Notes for details.

        .. versionadded:: 1.7.0

    random_state : {None, int, `numpy.random.Generator`,
            `numpy.random.RandomState`}, optional

        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
        singleton is used.
        If `seed` is an int, a new ``RandomState`` instance is used,
        seeded with `seed`.
        If `seed` is already a ``Generator`` or ``RandomState`` instance then
        that instance is used.

        Pseudorandom number generator state used to generate permutations
        (used only when `permutations` is not None).

        .. versionadded:: 1.7.0

    alternative : {'two-sided', 'less', 'greater'}, optional
        Defines the alternative hypothesis.
        The following options are available (default is 'two-sided'):

          * 'two-sided'
          * 'less': one-sided
          * 'greater': one-sided

        .. versionadded:: 1.6.0

    trim : float, optional
        If nonzero, performs a trimmed (Yuen's) t-test.
        Defines the fraction of elements to be trimmed from each end of the
        input samples. If 0 (default), no elements will be trimmed from either
        side. The number of trimmed elements from each tail is the floor of the
        trim times the number of elements. Valid range is [0, .5).

        .. versionadded:: 1.7

    Returns
    -------
    statistic : float or array
        The calculated t-statistic.
    pvalue : float or array
        The two-tailed p-value.

    Notes
    -----
    Suppose we observe two independent samples, e.g. flower petal lengths, and
    we are considering whether the two samples were drawn from the same
    population (e.g. the same species of flower or two species with similar
    petal characteristics) or two different populations.

    The t-test quantifies the difference between the arithmetic means
    of the two samples. The p-value quantifies the probability of observing
    as or more extreme values assuming the null hypothesis, that the
    samples are drawn from populations with the same population means, is true.
    A p-value larger than a chosen threshold (e.g. 5% or 1%) indicates that
    our observation is not so unlikely to have occurred by chance. Therefore,
    we do not reject the null hypothesis of equal population means.
    If the p-value is smaller than our threshold, then we have evidence
    against the null hypothesis of equal population means.

    By default, the p-value is determined by comparing the t-statistic of the
    observed data against a theoretical t-distribution.
    When ``1 < permutations < binom(n, k)``, where

    * ``k`` is the number of observations in `a`,
    * ``n`` is the total number of observations in `a` and `b`, and
    * ``binom(n, k)`` is the binomial coefficient (``n`` choose ``k``),

    the data are pooled (concatenated), randomly assigned to either group `a`
    or `b`, and the t-statistic is calculated. This process is performed
    repeatedly (`permutation` times), generating a distribution of the
    t-statistic under the null hypothesis, and the t-statistic of the observed
    data is compared to this distribution to determine the p-value. When
    ``permutations >= binom(n, k)``, an exact test is performed: the data are
    partitioned between the groups in each distinct way exactly once.

    The permutation test can be computationally expensive and not necessarily
    more accurate than the analytical test, but it does not make strong
    assumptions about the shape of the underlying distribution.

    Use of trimming is commonly referred to as the trimmed t-test. At times
    called Yuen's t-test, this is an extension of Welch's t-test, with the
    difference being the use of winsorized means in calculation of the variance
    and the trimmed sample size in calculation of the statistic. Trimming is
    reccomended if the underlying distribution is long-tailed or contaminated
    with outliers [4]_.

    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/T-test#Independent_two-sample_t-test

    .. [2] https://en.wikipedia.org/wiki/Welch%27s_t-test

    .. [3] http://en.wikipedia.org/wiki/Resampling_%28statistics%29

    .. [4] Yuen, Karen K. "The Two-Sample Trimmed t for Unequal Population
           Variances." Biometrika, vol. 61, no. 1, 1974, pp. 165-170. JSTOR,
           www.jstor.org/stable/2334299. Accessed 30 Mar. 2021.

    .. [5] Yuen, Karen K., and W. J. Dixon. "The Approximate Behaviour and
           Performance of the Two-Sample Trimmed t." Biometrika, vol. 60,
           no. 2, 1973, pp. 369-374. JSTOR, www.jstor.org/stable/2334550.
           Accessed 30 Mar. 2021.

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

    Test with sample with identical means:

    >>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
    >>> rvs2 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
    >>> stats.ttest_ind(rvs1, rvs2)
    Ttest_indResult(statistic=-0.4390847099199348, pvalue=0.6606952038870015)
    >>> stats.ttest_ind(rvs1, rvs2, equal_var=False)
    Ttest_indResult(statistic=-0.4390847099199348, pvalue=0.6606952553131064)

    `ttest_ind` underestimates p for unequal variances:

    >>> rvs3 = stats.norm.rvs(loc=5, scale=20, size=500, random_state=rng)
    >>> stats.ttest_ind(rvs1, rvs3)
    Ttest_indResult(statistic=-1.6370984482905417, pvalue=0.1019251574705033)
    >>> stats.ttest_ind(rvs1, rvs3, equal_var=False)
    Ttest_indResult(statistic=-1.637098448290542, pvalue=0.10202110497954867)

    When ``n1 != n2``, the equal variance t-statistic is no longer equal to the
    unequal variance t-statistic:

    >>> rvs4 = stats.norm.rvs(loc=5, scale=20, size=100, random_state=rng)
    >>> stats.ttest_ind(rvs1, rvs4)
    Ttest_indResult(statistic=-1.9481646859513422, pvalue=0.05186270935842703)
    >>> stats.ttest_ind(rvs1, rvs4, equal_var=False)
    Ttest_indResult(statistic=-1.3146566100751664, pvalue=0.1913495266513811)

    T-test with different means, variance, and n:

    >>> rvs5 = stats.norm.rvs(loc=8, scale=20, size=100, random_state=rng)
    >>> stats.ttest_ind(rvs1, rvs5)
    Ttest_indResult(statistic=-2.8415950600298774, pvalue=0.0046418707568707885)
    >>> stats.ttest_ind(rvs1, rvs5, equal_var=False)
    Ttest_indResult(statistic=-1.8686598649188084, pvalue=0.06434714193919686)

    When performing a permutation test, more permutations typically yields
    more accurate results. Use a ``np.random.Generator`` to ensure
    reproducibility:

    >>> stats.ttest_ind(rvs1, rvs5, permutations=10000,
    ...                 random_state=rng)
    Ttest_indResult(statistic=-2.8415950600298774, pvalue=0.0052)

    Take these two samples, one of which has an extreme tail.

    >>> a = (56, 128.6, 12, 123.8, 64.34, 78, 763.3)
    >>> b = (1.1, 2.9, 4.2)

    Use the `trim` keyword to perform a trimmed (Yuen) t-test. For example,
    using 20% trimming, ``trim=.2``, the test will reduce the impact of one
    (``np.floor(trim*len(a))``) element from each tail of sample `a`. It will
    have no effect on sample `b` because ``np.floor(trim*len(b))`` is 0.

    >>> stats.ttest_ind(a, b, trim=.2)
    Ttest_indResult(statistic=3.4463884028073513,
                    pvalue=0.01369338726499547)
    r   r   z/Trimming percentage should be 0 <= `trim` < .5.rc   r  znan-containing/masked inputs with nan_policy='omit' are currently not supported by permutation tests, one-sided asymptotic tests, or trimmed tests.Nz7Permutations are currently not supported with trimming.z,Permutations must be a non-negative integer.)permutationsr   r3  r{   r  r  r   r   )rm   r   r}   r   r   r   rN   r   r4  r2  ro   isfiniter   _permutation_ttestr   r   r   _ttest_trim_var_mean_lenr1  r0  r-  )rz   r   r   r3  r{   r5  r  r  trimcnanpacnbnpbr|   r   r   r   r.  r/  m1r   r*  r/  rd   rd   rg   rN     sX     S





rN   c                 C   sT   t j| |d} | j| }t|| }t| ||}|d| 8 }t| ||d}|||fS )zCVariance, mean, and length of winsorized input along specified axisr   r   )ro   r@  r   r   _calculate_winsorized_variancer?   )rz   r9  r   r   gr  r  rd   rd   rg   r8    s    
r8  c                 C   s   |dkrt j| d|dS t | |d}t jt |dd}|d|gf |dd|f< |d| d gf |d| df< t t j|d| d dd}t j||< |S )	z;Calculates g-times winsorized variance along specified axisr   r   r   r   r   .Nr   )ro   r   moveaxisr   rq   r   rt   )rz   r@  r   Za_winZnans_indicesZvar_winrd   rd   rg   r?    s    	"
r?  c                    sZ    fdd| D } t jdd | D  jfdd| D } t j| dd}t | d}|S )z3Concatenate arrays along an axis with broadcasting.c                    s   g | ]}t | d qS r   )ro   swapaxesre   r-  r   rd   rg   r   C  ri   z*_broadcast_concatenate.<locals>.<listcomp>c                 S   s   g | ]}|d  qS )).r   rd   rD  rd   rd   rg   r   E  ri   c                    s$   g | ]}t | |jd  f qS rB  )ro   rt  r   rD  r  rd   rg   r   G  ri   r   r   )ro   	broadcastr   r  rC  )xsr   r   rd   )r   r   rg   _broadcast_concatenate@  s    rG  c                    s   t   |dk r| j| }| j| t|}||k rZt fddt|D j}n$|}tdd t	|| D j}| 
|d} | d|f } | 
d|} t| dd} | |fS )zAAll partitions of data into sets of given lengths, ignoring orderr   c                    s   g | ]}  qS rd   )r
  r   r  r   rd   rg   r   \  s   z$_data_partitions.<locals>.<listcomp>c                 S   s   g | ]}t |qS rd   )ro   r  )re   r  rd   rd   rg   r   `  s   r   .r   )r
   r   r   r  combro   r   r   r;  r   rC  rA  )r   r5  size_ar   r  Zn_maxindicesrd   rH  rg   _data_partitionsO  s$    



rL  c                 C   s   | j | }|j | }tj| |d}tj||d}tj| |dd}tj||dd}	|sht|||	|d }
nt|||	|d }
|| |
 S )z4Calculate the t statistic along the given dimension.r   r   r  )r   ro   r   r   r0  r1  )rz   r   r3  r   nanbZavg_aZavg_bZvar_aZvar_br/  rd   rd   rg   _calc_t_statj  s    

rO  c                 C   s   t |}t| |||d}| j| }	t| |f|d}
t|
|d}
t|
||	|d\}}|dd|	f } |d|	df }t| ||}tjtjdd d}|| ||}|j	d	d| }|d
krt
| rt|d	krttj}ntj|t
|< ||fS )a  
    Calculates the T-test for the means of TWO INDEPENDENT samples of scores
    using permutation methods.

    This test is similar to `stats.ttest_ind`, except it doesn't rely on an
    approximate normality assumption since it uses a permutation test.
    This function is only called from ttest_ind when permutations is not None.

    Parameters
    ----------
    a, b : array_like
        The arrays must be broadcastable, except along the dimension
        corresponding to `axis` (the zeroth, by default).
    axis : int, optional
        The axis over which to operate on a and b.
    permutations: int, optional
        Number of permutations used to calculate p-value. If greater than or
        equal to the number of distinct permutations, perform an exact test.
    equal_var: bool, optional
        If False, an equal variance (Welch's) t-test is conducted.  Otherwise,
        an ordinary t-test is conducted.
    random_state : {None, int, `numpy.random.Generator`}, optional
        If `seed` is None the `numpy.random.Generator` singleton is used.
        If `seed` is an int, a new ``Generator`` instance is used,
        seeded with `seed`.
        If `seed` is already a ``Generator`` instance then that instance is
        used.
        Pseudorandom number generator state used for generating random
        permutations.

    Returns
    -------
    statistic : float or array
        The calculated t-statistic.
    pvalue : float or array
        The two-tailed p-value.

    r   r   )rJ  r  .Nc                 S   s   | t | k| t |kB S r  )ro   r   rm  rd   rd   rg   <lambda>  ri   z$_permutation_ttest.<locals>.<lambda>r
  r  r  r   r`   )r
   rO  r   rG  ro   rA  rL  r{  Zgreater_equalrr   rq   r   r   r   rt   )rz   r   r5  r   r3  r{   r  r  Zt_stat_observedrM  matZmat_permZt_statru  Zcmpspvaluesrd   rd   rg   r7  {  s,    )

r7  c                 C   s8   z| j | }W n$ ty2   t|| j|d Y n0 |S r  )r   r   ro   r   r   )rz   r   r0  r   rd   rd   rg   _get_len  s
    rT  Ttest_relResultc                 C   s  t | ||\} }}t| |\}}t||\}}|p4|}	|dksF|dkrJd}|	r|dkr|dkrftdt| } t|}tt| t|}
tj| |
dd}tj||
dd}t	|||S t
| |d}t
||d}||krtd|d	krt| ||tS | j| }|d
 }| | tj}tj||d
d}t||}t|| }tjddd t||}W d   n1 s|0    Y  t|||\}}t||S )a
  Calculate the t-test on TWO RELATED samples of scores, a and b.

    This is a two-sided test for the null hypothesis that 2 related or
    repeated samples have identical average (expected) values.

    Parameters
    ----------
    a, b : array_like
        The arrays must have the same shape.
    axis : int or None, optional
        Axis along which to compute test. If None, compute over the whole
        arrays, `a`, and `b`.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

          * 'propagate': returns nan
          * 'raise': throws an error
          * 'omit': performs the calculations ignoring nan values
    alternative : {'two-sided', 'less', 'greater'}, optional
        Defines the alternative hypothesis.
        The following options are available (default is 'two-sided'):

          * 'two-sided'
          * 'less': one-sided
          * 'greater': one-sided

          .. versionadded:: 1.6.0

    Returns
    -------
    statistic : float or array
        t-statistic.
    pvalue : float or array
        Two-sided p-value.

    Notes
    -----
    Examples for use are scores of the same set of student in
    different exams, or repeated sampling from the same units. The
    test measures whether the average score differs significantly
    across samples (e.g. exams). If we observe a large p-value, for
    example greater than 0.05 or 0.1 then we cannot reject the null
    hypothesis of identical average scores. If the p-value is smaller
    than the threshold, e.g. 1%, 5% or 10%, then we reject the null
    hypothesis of equal averages. Small p-values are associated with
    large t-statistics.

    References
    ----------
    https://en.wikipedia.org/wiki/T-test#Dependent_t-test_for_paired_samples

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

    >>> rvs1 = stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
    >>> rvs2 = (stats.norm.rvs(loc=5, scale=10, size=500, random_state=rng)
    ...         + stats.norm.rvs(scale=0.2, size=500, random_state=rng))
    >>> stats.ttest_rel(rvs1, rvs2)
    Ttest_relResult(statistic=-0.4549717054410304, pvalue=0.6493274702088672)
    >>> rvs3 = (stats.norm.rvs(loc=8, scale=10, size=500, random_state=rng)
    ...         + stats.norm.rvs(scale=0.2, size=500, random_state=rng))
    >>> stats.ttest_rel(rvs1, rvs3)
    Ttest_relResult(statistic=-5.879467544540889, pvalue=7.540777129099917e-09)

    rc   r  r  T)maskr   zfirst argumentzsecond argumentzunequal length arraysr   r   r   rj   r  N)r   r}   rm   r   r   Zmask_orZgetmaskr   r   rP   rT  r4  rU  r   r   ro   r   r   r   r   rp   r   r  )rz   r   r   r{   r  r:  r;  r<  r=  r|   r  ZaaZbbrM  rN  r   r*  r   r  dmr/  rk  r  rd   rd   rg   rP     s>    E


,rP   g      r   gUUUUUU?)pearsonzlog-likelihoodzfreeman-tukeyzmod-log-likelihoodZneymanzcressie-readc                 C   sT   t | dr6| j|d}t|tjrP|jdkrPt|}n|du rF| j}n
| j| }|S )zCount the number of non-masked elements of an array.

    This function behaves like `np.ma.count`, but is much faster
    for ndarrays.
    r   r   r   N)	hasattrr   r   ro   r   r   r   r   r   )rz   r   numrd   rd   rg   _countL  s    


r[  c                 C   s>   t j| r.t jjt | |t | j|dS t j| |ddS )N)rV  T)Zsubok)ro   r   ZisMaskedArrayZmasked_arrayrt  rV  )rz   r   rd   rd   rg   _m_broadcast_to`  s
    r\  Power_divergenceResultc                 C   s,  t |trD|tvr:ttt dd }td||t| }n|du rPd}t	| } | 
tj}|dur,t	|}t|j|j}t||}t||}d}tjddN |j|d}	|j|d}
t|	|
 t|	|
 }||k }W d   n1 s0    Y  |rhd	| d
| }t|n<tjdd | j|dd}W d   n1 s^0    Y  |dkr|| d | }nh|dkrdt| | |  }nH|dkrdt|||   }n(| | | | d  }|d| |d   }|j|d}t||d}t|}tj||d | }t||S )a`  Cressie-Read power divergence statistic and goodness of fit test.

    This function tests the null hypothesis that the categorical data
    has the given frequencies, using the Cressie-Read power divergence
    statistic.

    Parameters
    ----------
    f_obs : array_like
        Observed frequencies in each category.
    f_exp : array_like, optional
        Expected frequencies in each category.  By default the categories are
        assumed to be equally likely.
    ddof : int, optional
        "Delta degrees of freedom": adjustment to the degrees of freedom
        for the p-value.  The p-value is computed using a chi-squared
        distribution with ``k - 1 - ddof`` degrees of freedom, where `k`
        is the number of observed frequencies.  The default value of `ddof`
        is 0.
    axis : int or None, optional
        The axis of the broadcast result of `f_obs` and `f_exp` along which to
        apply the test.  If axis is None, all values in `f_obs` are treated
        as a single data set.  Default is 0.
    lambda_ : float or str, optional
        The power in the Cressie-Read power divergence statistic.  The default
        is 1.  For convenience, `lambda_` may be assigned one of the following
        strings, in which case the corresponding numerical value is used::

            String              Value   Description
            "pearson"             1     Pearson's chi-squared statistic.
                                        In this case, the function is
                                        equivalent to `stats.chisquare`.
            "log-likelihood"      0     Log-likelihood ratio. Also known as
                                        the G-test [3]_.
            "freeman-tukey"      -1/2   Freeman-Tukey statistic.
            "mod-log-likelihood" -1     Modified log-likelihood ratio.
            "neyman"             -2     Neyman's statistic.
            "cressie-read"        2/3   The power recommended in [5]_.

    Returns
    -------
    statistic : float or ndarray
        The Cressie-Read power divergence test statistic.  The value is
        a float if `axis` is None or if` `f_obs` and `f_exp` are 1-D.
    pvalue : float or ndarray
        The p-value of the test.  The value is a float if `ddof` and the
        return value `stat` are scalars.

    See Also
    --------
    chisquare

    Notes
    -----
    This test is invalid when the observed or expected frequencies in each
    category are too small.  A typical rule is that all of the observed
    and expected frequencies should be at least 5.

    Also, the sum of the observed and expected frequencies must be the same
    for the test to be valid; `power_divergence` raises an error if the sums
    do not agree within a relative tolerance of ``1e-8``.

    When `lambda_` is less than zero, the formula for the statistic involves
    dividing by `f_obs`, so a warning or error may be generated if any value
    in `f_obs` is 0.

    Similarly, a warning or error may be generated if any value in `f_exp` is
    zero when `lambda_` >= 0.

    The default degrees of freedom, k-1, are for the case when no parameters
    of the distribution are estimated. If p parameters are estimated by
    efficient maximum likelihood then the correct degrees of freedom are
    k-1-p. If the parameters are estimated in a different way, then the
    dof can be between k-1-p and k-1. However, it is also possible that
    the asymptotic distribution is not a chisquare, in which case this
    test is not appropriate.

    This function handles masked arrays.  If an element of `f_obs` or `f_exp`
    is masked, then data at that position is ignored, and does not count
    towards the size of the data set.

    .. versionadded:: 0.13.0

    References
    ----------
    .. [1] Lowry, Richard.  "Concepts and Applications of Inferential
           Statistics". Chapter 8.
           https://web.archive.org/web/20171015035606/http://faculty.vassar.edu/lowry/ch8pt1.html
    .. [2] "Chi-squared test", https://en.wikipedia.org/wiki/Chi-squared_test
    .. [3] "G-test", https://en.wikipedia.org/wiki/G-test
    .. [4] Sokal, R. R. and Rohlf, F. J. "Biometry: the principles and
           practice of statistics in biological research", New York: Freeman
           (1981)
    .. [5] Cressie, N. and Read, T. R. C., "Multinomial Goodness-of-Fit
           Tests", J. Royal Stat. Soc. Series B, Vol. 46, No. 3 (1984),
           pp. 440-464.

    Examples
    --------
    (See `chisquare` for more examples.)

    When just `f_obs` is given, it is assumed that the expected frequencies
    are uniform and given by the mean of the observed frequencies.  Here we
    perform a G-test (i.e. use the log-likelihood ratio statistic):

    >>> from scipy.stats import power_divergence
    >>> power_divergence([16, 18, 16, 14, 12, 12], lambda_='log-likelihood')
    (2.006573162632538, 0.84823476779463769)

    The expected frequencies can be given with the `f_exp` argument:

    >>> power_divergence([16, 18, 16, 14, 12, 12],
    ...                  f_exp=[16, 16, 16, 16, 16, 8],
    ...                  lambda_='log-likelihood')
    (3.3281031458963746, 0.6495419288047497)

    When `f_obs` is 2-D, by default the test is applied to each column.

    >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T
    >>> obs.shape
    (6, 2)
    >>> power_divergence(obs, lambda_="log-likelihood")
    (array([ 2.00657316,  6.77634498]), array([ 0.84823477,  0.23781225]))

    By setting ``axis=None``, the test is applied to all data in the array,
    which is equivalent to applying the test to the flattened array.

    >>> power_divergence(obs, axis=None)
    (23.31034482758621, 0.015975692534127565)
    >>> power_divergence(obs.ravel())
    (23.31034482758621, 0.015975692534127565)

    `ddof` is the change to make to the default degrees of freedom.

    >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=1)
    (2.0, 0.73575888234288467)

    The calculation of the p-values is done by broadcasting the
    test statistic with `ddof`.

    >>> power_divergence([16, 18, 16, 14, 12, 12], ddof=[0,1,2])
    (2.0, array([ 0.84914504,  0.73575888,  0.5724067 ]))

    `f_obs` and `f_exp` are also broadcast.  In the following, `f_obs` has
    shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting
    `f_obs` and `f_exp` has shape (2, 6).  To compute the desired chi-squared
    statistics, we must use ``axis=1``:

    >>> power_divergence([16, 18, 16, 14, 12, 12],
    ...                  f_exp=[[16, 16, 16, 16, 16, 8],
    ...                         [8, 20, 20, 16, 12, 12]],
    ...                  axis=1)
    (array([ 3.5 ,  9.25]), array([ 0.62338763,  0.09949846]))

    r   r   z8invalid string for lambda_: {0!r}. Valid strings are {1}Ng:0yE>rj   rk   r   zFor each axis slice, the sum of the observed frequencies must agree with the sum of the expected frequencies to a relative tolerance of z#, but the percent differences are:
Trq  r   r   r   r   )r   r|  _power_div_lambda_namesr  r   keysrm   r  ro   r   r   r   r   r   r\  rp   rr   r   r   r   r   r  Zxlogyr[  r   r   r2  r  r]  )f_obsf_expr   r   lambda_namesZf_obs_floatZbshapeZrtolZ	f_obs_sumZ	f_exp_sumZrelative_diffZdiff_gt_tolr0  Ztermsr  Znum_obsr8  rd   rd   rg   rU   k  s^     







,
.


rU   c                 C   s   t | |||ddS )a  Calculate a one-way chi-square test.

    The chi-square test tests the null hypothesis that the categorical data
    has the given frequencies.

    Parameters
    ----------
    f_obs : array_like
        Observed frequencies in each category.
    f_exp : array_like, optional
        Expected frequencies in each category.  By default the categories are
        assumed to be equally likely.
    ddof : int, optional
        "Delta degrees of freedom": adjustment to the degrees of freedom
        for the p-value.  The p-value is computed using a chi-squared
        distribution with ``k - 1 - ddof`` degrees of freedom, where `k`
        is the number of observed frequencies.  The default value of `ddof`
        is 0.
    axis : int or None, optional
        The axis of the broadcast result of `f_obs` and `f_exp` along which to
        apply the test.  If axis is None, all values in `f_obs` are treated
        as a single data set.  Default is 0.

    Returns
    -------
    chisq : float or ndarray
        The chi-squared test statistic.  The value is a float if `axis` is
        None or `f_obs` and `f_exp` are 1-D.
    p : float or ndarray
        The p-value of the test.  The value is a float if `ddof` and the
        return value `chisq` are scalars.

    See Also
    --------
    scipy.stats.power_divergence
    scipy.stats.fisher_exact : Fisher exact test on a 2x2 contingency table.
    scipy.stats.barnard_exact : An unconditional exact test. An alternative
        to chi-squared test for small sample sizes.

    Notes
    -----
    This test is invalid when the observed or expected frequencies in each
    category are too small.  A typical rule is that all of the observed
    and expected frequencies should be at least 5. According to [3]_, the
    total number of samples is recommended to be greater than 13,
    otherwise exact tests (such as Barnard's Exact test) should be used
    because they do not overreject.

    Also, the sum of the observed and expected frequencies must be the same
    for the test to be valid; `chisquare` raises an error if the sums do not
    agree within a relative tolerance of ``1e-8``.

    The default degrees of freedom, k-1, are for the case when no parameters
    of the distribution are estimated. If p parameters are estimated by
    efficient maximum likelihood then the correct degrees of freedom are
    k-1-p. If the parameters are estimated in a different way, then the
    dof can be between k-1-p and k-1. However, it is also possible that
    the asymptotic distribution is not chi-square, in which case this test
    is not appropriate.

    References
    ----------
    .. [1] Lowry, Richard.  "Concepts and Applications of Inferential
           Statistics". Chapter 8.
           https://web.archive.org/web/20171022032306/http://vassarstats.net:80/textbook/ch8pt1.html
    .. [2] "Chi-squared test", https://en.wikipedia.org/wiki/Chi-squared_test
    .. [3] Pearson, Karl. "On the criterion that a given system of deviations from the probable
           in the case of a correlated system of variables is such that it can be reasonably
           supposed to have arisen from random sampling", Philosophical Magazine. Series 5. 50
           (1900), pp. 157-175.

    Examples
    --------
    When just `f_obs` is given, it is assumed that the expected frequencies
    are uniform and given by the mean of the observed frequencies.

    >>> from scipy.stats import chisquare
    >>> chisquare([16, 18, 16, 14, 12, 12])
    (2.0, 0.84914503608460956)

    With `f_exp` the expected frequencies can be given.

    >>> chisquare([16, 18, 16, 14, 12, 12], f_exp=[16, 16, 16, 16, 16, 8])
    (3.5, 0.62338762774958223)

    When `f_obs` is 2-D, by default the test is applied to each column.

    >>> obs = np.array([[16, 18, 16, 14, 12, 12], [32, 24, 16, 28, 20, 24]]).T
    >>> obs.shape
    (6, 2)
    >>> chisquare(obs)
    (array([ 2.        ,  6.66666667]), array([ 0.84914504,  0.24663415]))

    By setting ``axis=None``, the test is applied to all data in the array,
    which is equivalent to applying the test to the flattened array.

    >>> chisquare(obs, axis=None)
    (23.31034482758621, 0.015975692534127565)
    >>> chisquare(obs.ravel())
    (23.31034482758621, 0.015975692534127565)

    `ddof` is the change to make to the default degrees of freedom.

    >>> chisquare([16, 18, 16, 14, 12, 12], ddof=1)
    (2.0, 0.73575888234288467)

    The calculation of the p-values is done by broadcasting the
    chi-squared statistic with `ddof`.

    >>> chisquare([16, 18, 16, 14, 12, 12], ddof=[0,1,2])
    (2.0, array([ 0.84914504,  0.73575888,  0.5724067 ]))

    `f_obs` and `f_exp` are also broadcast.  In the following, `f_obs` has
    shape (6,) and `f_exp` has shape (2, 6), so the result of broadcasting
    `f_obs` and `f_exp` has shape (2, 6).  To compute the desired chi-squared
    statistics, we use ``axis=1``:

    >>> chisquare([16, 18, 16, 14, 12, 12],
    ...           f_exp=[[16, 16, 16, 16, 16, 8], [8, 20, 20, 16, 12, 12]],
    ...           axis=1)
    (array([ 3.5 ,  9.25]), array([ 0.62338763,  0.09949846]))

    rX  )ra  r   r   rb  )rU   )r`  ra  r   r   rd   rd   rg   rT   H  s    |
rT   KstestResultc                 C   s$   t | }td|d | |   S )zComputes D+ as used in the Kolmogorov-Smirnov test.

    Parameters
    ----------
    cdfvals: array_like
      Sorted array of CDF values between 0 and 1

    Returns
    -------
      Maximum distance of the CDF values below Uniform(0, 1)
r   r   r   ro   r  r   cdfvalsr   rd   rd   rg   _compute_dplus  s    rh  c                 C   s    t | }| td||   S )zComputes D- as used in the Kolmogorov-Smirnov test.

    Parameters
    ----------
    cdfvals: array_like
      Sorted array of CDF values between 0 and 1

    Returns
    -------
      Maximum distance of the CDF values above Uniform(0, 1)

    r   re  rf  rd   rd   rg   _compute_dminus  s    ri  c                 C   s<  dddd | d |}|dvr0td| tj| rD|  } t| }t| } || g|R  }|dkrt	|}t
|tj||S |dkrt|}t
|tj||S t	|}t|}t||g}	|dkrd	}|d	krtj|	|}
n4|d
krtj|	t| }
ndtj|	| }
t|
dd}
t
|	|
S )a  
    Performs the one-sample Kolmogorov-Smirnov test for goodness of fit.

    This test compares the underlying distribution F(x) of a sample
    against a given continuous distribution G(x). See Notes for a description
    of the available null and alternative hypotheses.

    Parameters
    ----------
    x : array_like
        a 1-D array of observations of iid random variables.
    cdf : callable
        callable used to calculate the cdf.
    args : tuple, sequence, optional
        Distribution parameters, used with `cdf`.
    alternative : {'two-sided', 'less', 'greater'}, optional
        Defines the null and alternative hypotheses. Default is 'two-sided'.
        Please see explanations in the Notes below.
    mode : {'auto', 'exact', 'approx', 'asymp'}, optional
        Defines the distribution used for calculating the p-value.
        The following options are available (default is 'auto'):

          * 'auto' : selects one of the other options.
          * 'exact' : uses the exact distribution of test statistic.
          * 'approx' : approximates the two-sided probability with twice
            the one-sided probability
          * 'asymp': uses asymptotic distribution of test statistic

    Returns
    -------
    statistic : float
        KS test statistic, either D, D+ or D- (depending on the value
        of 'alternative')
    pvalue :  float
        One-tailed or two-tailed p-value.

    See Also
    --------
    ks_2samp, kstest

    Notes
    -----
    There are three options for the null and corresponding alternative
    hypothesis that can be selected using the `alternative` parameter.

    - `two-sided`: The null hypothesis is that the two distributions are
      identical, F(x)=G(x) for all x; the alternative is that they are not
      identical.

    - `less`: The null hypothesis is that F(x) >= G(x) for all x; the
      alternative is that F(x) < G(x) for at least one x.

    - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the
      alternative is that F(x) > G(x) for at least one x.

    Note that the alternative hypotheses describe the *CDFs* of the
    underlying distributions, not the observed values. For example,
    suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in
    x1 tend to be less than those in x2.

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

    >>> x = np.linspace(-15, 15, 9)
    >>> stats.ks_1samp(x, stats.norm.cdf)
    (0.44435602715924361, 0.038850142705171065)

    >>> stats.ks_1samp(stats.norm.rvs(size=100, random_state=rng),
    ...                stats.norm.cdf)
    KstestResult(statistic=0.165471391799..., pvalue=0.007331283245...)

    *Test against one-sided alternative hypothesis*

    Shift distribution to larger values, so that `` CDF(x) < norm.cdf(x)``:

    >>> x = stats.norm.rvs(loc=0.2, size=100, random_state=rng)
    >>> stats.ks_1samp(x, stats.norm.cdf, alternative='less')
    KstestResult(statistic=0.100203351482..., pvalue=0.125544644447...)

    Reject null hypothesis in favor of alternative hypothesis: less

    >>> stats.ks_1samp(x, stats.norm.cdf, alternative='greater')
    KstestResult(statistic=0.018749806388..., pvalue=0.920581859791...)

    Reject null hypothesis in favor of alternative hypothesis: greater

    >>> stats.ks_1samp(x, stats.norm.cdf)
    KstestResult(statistic=0.100203351482..., pvalue=0.250616879765...)

    Don't reject null hypothesis in favor of alternative hypothesis: two-sided

    *Testing t distributed random variables against normal distribution*

    With 100 degrees of freedom the t distribution looks close to the normal
    distribution, and the K-S test does not reject the hypothesis that the
    sample came from the normal distribution:

    >>> stats.ks_1samp(stats.t.rvs(100,size=100, random_state=rng),
    ...                stats.norm.cdf)
    KstestResult(statistic=0.064273776544..., pvalue=0.778737758305...)

    With 3 degrees of freedom the t distribution looks sufficiently different
    from the normal distribution, that we can reject the hypothesis that the
    sample came from the normal distribution at the 10% level:

    >>> stats.ks_1samp(stats.t.rvs(3,size=100, random_state=rng),
    ...                stats.norm.cdf)
    KstestResult(statistic=0.128678487493..., pvalue=0.066569081515...)

    r  r  r
  rk  r@  re  r   r  r  r
  Unexpected alternative %sr  r  asympr   r   )getrI  rm   ro   r   	is_masked
compressedr   r@  rh  rd  r   Zksoner  ri  r   kstwoZ	kstwobignr   r  )r-  r  rh  r  r   Nrg  ZDplusZDminusDr  rd   rd   rg   rR     s8    q

rR   c                 C   s  | |k r||  } }| | }|| }dt tt|| |d  }}|| }t d| d |d }	tj}
tj|	|
d}d|||< d}td| d D ]}|| }}ttt|| | | d d}t ||}t tt|| | | |d }||kr dS t	||| ||  |d|| < || }||krZd||| || ||  < ||| d  }t
|\}}|dkr|d8 }t|| }||7 }q||| d  }td|d D ]D}|| | |  }t
|\}}|dk rt|| }||7 }qt||S )a  
    Count the proportion of paths that stay strictly inside two diagonal lines.

    Parameters
    ----------
    m : integer
        m > 0
    n : integer
        n > 0
    g : integer
        g is greatest common divisor of m and n
    h : integer
        0 <= h <= lcm(m,n)

    Returns
    -------
    p : float
        The proportion of paths that stay inside the two lines.

    Count the integer lattice paths from (0, 0) to (m, n) which satisfy
    |x/m - y/n| < h / lcm(m, n).
    The paths make steps of size +1 in either positive x or positive y
    directions.

    We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk.
    Hodges, J.L. Jr.,
    "The Significance Probability of the Smirnov Two-Sample Test,"
    Arkiv fiur Matematik, 3, No. 43 (1958), 469-86.

    r   r   r   r   i  i   i)r  r   ro   rL  r   r   r   r   rK  rb  r!  frexpldexp)r  r   r@  rd  mgr  ZminjZmaxjZcurlenZlenAr   r.  Zexpntr   ZlastminjZlastlenvalr3  Zvalexptrd   rd   rg   _compute_prob_inside_method  sH     
"

$
$
&


rx  c                 C   sv   d}t t| | }|dkrnd}t|D ],}| ||  | | | ||  | d  }q*|d|  }|d8 }qd| S )a$  
    Compute the proportion of paths that pass outside the two diagonal lines.

    Parameters
    ----------
    n : integer
        n > 0
    h : integer
        0 <= h <= n

    Returns
    -------
    p : float
        The proportion of paths that pass outside the lines x-y = +/-h.

    r   r   r   r   r   )r   ro   rK  r   )r   rd  Pr4  p1rO  rd   rd   rg   _compute_prob_outside_square  s    *
r{  c              	      s  | |k r||  } }| | || |    } fddt |D }|dkrjtt| | |S t|}d|d< t d|D ]}tt|| | |}t|st t |D ]>}	tt|| ||	  | |	 ||	 }
||
||	  8 }q|||< t|st qd}t |D ]R}tt| ||  ||  || }
|| |
 }t|sjt ||7 }q"t|S )a  Count the number of paths that pass outside the specified diagonal.

    Parameters
    ----------
    m : integer
        m > 0
    n : integer
        n > 0
    g : integer
        g is greatest common divisor of m and n
    h : integer
        0 <= h <= lcm(m,n)

    Returns
    -------
    p : float
        The number of paths that go low.
        The calculation may overflow - check for a finite answer.

    Raises
    ------
    FloatingPointError: Raised if the intermediate computation goes outside
    the range of a float.

    Notes
    -----
    Count the integer lattice paths from (0, 0) to (m, n), which at some
    point (x, y) along the path, satisfy:
      m*y <= n*x - h*g
    The paths make steps of size +1 in either positive x or positive y
    directions.

    We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk.
    Hodges, J.L. Jr.,
    "The Significance Probability of the Smirnov Two-Sample Test,"
    Arkiv fiur Matematik, 3, No. 43 (1958), 469-86.

    c                    s$   g | ]} |   d   qS r   rd   )re   rO  rd  rv  r  rd   rg   r   I  ri   z/_count_paths_outside_method.<locals>.<listcomp>r   r   )r   ro   r   r  binomr   r6  FloatingPointError)r  r   r@  rd  ZlxjZxjBrO  ZBjr   bin	num_pathsZtermrd   r|  rg   _count_paths_outside_method  s8    /


*
&r  c                 C   sL  | | | }t t|| }|d | }|dkr<d|dfS dtj }}z|dkrz| |krft| |}qdt| ||| }nv| |krt|}	t| |	 | |	 d  }nHt| |||}
t	
| | | }t|rt|
r|
|krd}n|
| }W n ty
   d}Y n0 |rd|tjfS d|  kr6dksBn d||fS d||fS )zAttempts to compute the exact 2sample probability.

    n1, n2 are the sample sizes
    g is the gcd(n1, n2)
    d is the computed max difference in ECDFs

    Returns (success, d, probability)
    r   r   TFr  r   )r   ro   r   rt   r{  rx  r  prodr  r  r}  r6  r~  )r   r   r@  r   r  lcmrd  Zsaw_fp_errorr  Zjranger  r  rd   rd   rg   _attempt_exact_2kssamph  s8    	



r  c                 C   s  |dvrt d| dddd| d |}|dvrHt d	| d
}tj| r`|  } tj|rt| }t| } t|}| jd }|jd }t	||dkrt dt
| |g}tj| |dd| }tj||dd| }	||	 }
tt	|
 dd}t|
}||t||d}|| }t||}|| }|| }tj }|}|dkrtt|||krndnd}n@|dkr|ttjj| krd}td| d| dt |dkrt|||||\}}}|sd}|dkrtd| dt |dkrtt|t|gdd\}}|| ||  }|dkrRtj|t|}nRt|| }d|d  d| |d|   t|| ||   d  }t|}t|dd}t||S )a  
    Performs the two-sample Kolmogorov-Smirnov test for goodness of fit.

    This test compares the underlying continuous distributions F(x) and G(x)
    of two independent samples.  See Notes for a description
    of the available null and alternative hypotheses.

    Parameters
    ----------
    data1, data2 : array_like, 1-Dimensional
        Two arrays of sample observations assumed to be drawn from a continuous
        distribution, sample sizes can be different.
    alternative : {'two-sided', 'less', 'greater'}, optional
        Defines the null and alternative hypotheses. Default is 'two-sided'.
        Please see explanations in the Notes below.
    mode : {'auto', 'exact', 'asymp'}, optional
        Defines the method used for calculating the p-value.
        The following options are available (default is 'auto'):

          * 'auto' : use 'exact' for small size arrays, 'asymp' for large
          * 'exact' : use exact distribution of test statistic
          * 'asymp' : use asymptotic distribution of test statistic

    Returns
    -------
    statistic : float
        KS statistic.
    pvalue : float
        One-tailed or two-tailed p-value.

    See Also
    --------
    kstest, ks_1samp, epps_singleton_2samp, anderson_ksamp

    Notes
    -----
    There are three options for the null and corresponding alternative
    hypothesis that can be selected using the `alternative` parameter.

    - `two-sided`: The null hypothesis is that the two distributions are
      identical, F(x)=G(x) for all x; the alternative is that they are not
      identical.

    - `less`: The null hypothesis is that F(x) >= G(x) for all x; the
      alternative is that F(x) < G(x) for at least one x.

    - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the
      alternative is that F(x) > G(x) for at least one x.

    Note that the alternative hypotheses describe the *CDFs* of the
    underlying distributions, not the observed values. For example,
    suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in
    x1 tend to be less than those in x2.


    If the KS statistic is small or the p-value is high, then we cannot
    reject the null hypothesis in favor of the alternative.

    If the mode is 'auto', the computation is exact if the sample sizes are
    less than 10000.  For larger sizes, the computation uses the
    Kolmogorov-Smirnov distributions to compute an approximate value.

    The 'two-sided' 'exact' computation computes the complementary probability
    and then subtracts from 1.  As such, the minimum probability it can return
    is about 1e-16.  While the algorithm itself is exact, numerical
    errors may accumulate for large sample sizes.   It is most suited to
    situations in which one of the sample sizes is only a few thousand.

    We generally follow Hodges' treatment of Drion/Gnedenko/Korolyuk [1]_.

    References
    ----------
    .. [1] Hodges, J.L. Jr.,  "The Significance Probability of the Smirnov
           Two-Sample Test," Arkiv fiur Matematik, 3, No. 43 (1958), 469-86.

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

    >>> n1 = 200  # size of first sample
    >>> n2 = 300  # size of second sample

    For a different distribution, we can reject the null hypothesis since the
    pvalue is below 1%:

    >>> rvs1 = stats.norm.rvs(size=n1, loc=0., scale=1, random_state=rng)
    >>> rvs2 = stats.norm.rvs(size=n2, loc=0.5, scale=1.5, random_state=rng)
    >>> stats.ks_2samp(rvs1, rvs2)
     KstestResult(statistic=0.24833333333333332, pvalue=5.846586728086578e-07)

    For a slightly different distribution, we cannot reject the null hypothesis
    at a 10% or lower alpha since the p-value at 0.144 is higher than 10%

    >>> rvs3 = stats.norm.rvs(size=n2, loc=0.01, scale=1.0, random_state=rng)
    >>> stats.ks_2samp(rvs1, rvs3)
    KstestResult(statistic=0.07833333333333334, pvalue=0.4379658456442945)

    For an identical distribution, we cannot reject the null hypothesis since
    the p-value is high, 41%:

    >>> rvs4 = stats.norm.rvs(size=n2, loc=0.0, scale=1.0, random_state=rng)
    >>> stats.ks_2samp(rvs1, rvs4)
    KstestResult(statistic=0.12166666666666667, pvalue=0.05401863039081145)

    )r  r  rm  zInvalid value for mode: r  r  r
  rj  r   )r  r
  r  zInvalid value for alternative: i'  z)Data passed to ks_2samp must not be emptyrT  )r  r   rQ  r  r  rm  z;Exact ks_2samp calculation not possible with samples sizes r   z. Switching to 'asymp'.z<ks_2samp: Exact calculation unsuccessful. Switching to mode=r  T)reverser   r   r   )rm   rn  rI  ro   r   ro  rp  r@  r   r  r  searchsortedr  r   r   r  Ziinfor  rw   rx   ry   r  r  r   r   rq  r  r   r   r   rd  )data1data2r  r   Z
MAX_AUTO_Nr   r   Zdata_allZcdf1Zcdf2ZcddiffsZminSZmaxSZ
alt2Dvaluer   r@  Zn1gZn2gr  Zoriginal_modesuccessr  r   enr  Zexptrd   rd   rg   rS     s    k











:
rS   c                 C   s~   d\}}t | tr tt| j}nt| r,| }t |trHtt|j}d }nt|rX|}d }t|rn||d|in| } | ||fS )N)NNr   )	r   r|  getattrr   rvsr  r  ro   r@  )r  r  rh  rr  Zrvsfuncr  rd   rd   rg   _parse_kstest_argsH  s    

r  r(  c                 C   sZ   |dkrd}|dvr t d| t| |||\}}}|rJt|||||dS t||||dS )aA  
    Performs the (one-sample or two-sample) Kolmogorov-Smirnov test for
    goodness of fit.

    The one-sample test compares the underlying distribution F(x) of a sample
    against a given distribution G(x). The two-sample test compares the
    underlying distributions of two independent samples. Both tests are valid
    only for continuous distributions.

    Parameters
    ----------
    rvs : str, array_like, or callable
        If an array, it should be a 1-D array of observations of random
        variables.
        If a callable, it should be a function to generate random variables;
        it is required to have a keyword argument `size`.
        If a string, it should be the name of a distribution in `scipy.stats`,
        which will be used to generate random variables.
    cdf : str, array_like or callable
        If array_like, it should be a 1-D array of observations of random
        variables, and the two-sample test is performed
        (and rvs must be array_like).
        If a callable, that callable is used to calculate the cdf.
        If a string, it should be the name of a distribution in `scipy.stats`,
        which will be used as the cdf function.
    args : tuple, sequence, optional
        Distribution parameters, used if `rvs` or `cdf` are strings or
        callables.
    N : int, optional
        Sample size if `rvs` is string or callable.  Default is 20.
    alternative : {'two-sided', 'less', 'greater'}, optional
        Defines the null and alternative hypotheses. Default is 'two-sided'.
        Please see explanations in the Notes below.
    mode : {'auto', 'exact', 'approx', 'asymp'}, optional
        Defines the distribution used for calculating the p-value.
        The following options are available (default is 'auto'):

          * 'auto' : selects one of the other options.
          * 'exact' : uses the exact distribution of test statistic.
          * 'approx' : approximates the two-sided probability with twice the
            one-sided probability
          * 'asymp': uses asymptotic distribution of test statistic

    Returns
    -------
    statistic : float
        KS test statistic, either D, D+ or D-.
    pvalue :  float
        One-tailed or two-tailed p-value.

    See Also
    --------
    ks_2samp

    Notes
    -----
    There are three options for the null and corresponding alternative
    hypothesis that can be selected using the `alternative` parameter.

    - `two-sided`: The null hypothesis is that the two distributions are
      identical, F(x)=G(x) for all x; the alternative is that they are not
      identical.

    - `less`: The null hypothesis is that F(x) >= G(x) for all x; the
      alternative is that F(x) < G(x) for at least one x.

    - `greater`: The null hypothesis is that F(x) <= G(x) for all x; the
      alternative is that F(x) > G(x) for at least one x.

    Note that the alternative hypotheses describe the *CDFs* of the
    underlying distributions, not the observed values. For example,
    suppose x1 ~ F and x2 ~ G. If F(x) > G(x) for all x, the values in
    x1 tend to be less than those in x2.


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

    >>> x = np.linspace(-15, 15, 9)
    >>> stats.kstest(x, 'norm')
    KstestResult(statistic=0.444356027159..., pvalue=0.038850140086...)

    >>> stats.kstest(stats.norm.rvs(size=100, random_state=rng), stats.norm.cdf)
    KstestResult(statistic=0.165471391799..., pvalue=0.007331283245...)

    The above lines are equivalent to:

    >>> stats.kstest(stats.norm.rvs, 'norm', N=100)
    KstestResult(statistic=0.113810164200..., pvalue=0.138690052319...)  # may vary

    *Test against one-sided alternative hypothesis*

    Shift distribution to larger values, so that ``CDF(x) < norm.cdf(x)``:

    >>> x = stats.norm.rvs(loc=0.2, size=100, random_state=rng)
    >>> stats.kstest(x, 'norm', alternative='less')
    KstestResult(statistic=0.1002033514..., pvalue=0.1255446444...)

    Reject null hypothesis in favor of alternative hypothesis: less

    >>> stats.kstest(x, 'norm', alternative='greater')
    KstestResult(statistic=0.018749806388..., pvalue=0.920581859791...)

    Don't reject null hypothesis in favor of alternative hypothesis: greater

    >>> stats.kstest(x, 'norm')
    KstestResult(statistic=0.100203351482..., pvalue=0.250616879765...)

    *Testing t distributed random variables against normal distribution*

    With 100 degrees of freedom the t distribution looks close to the normal
    distribution, and the K-S test does not reject the hypothesis that the
    sample came from the normal distribution:

    >>> stats.kstest(stats.t.rvs(100, size=100, random_state=rng), 'norm')
    KstestResult(statistic=0.064273776544..., pvalue=0.778737758305...)

    With 3 degrees of freedom the t distribution looks sufficiently different
    from the normal distribution, that we can reject the hypothesis that the
    sample came from the normal distribution at the 10% level:

    >>> stats.kstest(stats.t.rvs(3, size=100, random_state=rng), 'norm')
    KstestResult(statistic=0.128678487493..., pvalue=0.066569081515...)

    Z	two_sidedr  rk  rl  )rh  r  r   )r  r   )rm   r  rR   rS   )r  r  rh  rr  r  r   ZxvalsZyvalsrd   rd   rg   rQ   e  s     
rQ   c                 C   s   t | }t t jd|dd |dd kdf d }t |t j}t |j}|dk rbdS d|d |  |d |   S )	a  Tie correction factor for Mann-Whitney U and Kruskal-Wallis H tests.

    Parameters
    ----------
    rankvals : array_like
        A 1-D sequence of ranks.  Typically this will be the array
        returned by `~scipy.stats.rankdata`.

    Returns
    -------
    factor : float
        Correction factor for U or H.

    See Also
    --------
    rankdata : Assign ranks to the data
    mannwhitneyu : Mann-Whitney rank test
    kruskal : Kruskal-Wallis H test

    References
    ----------
    .. [1] Siegel, S. (1956) Nonparametric Statistics for the Behavioral
           Sciences.  New York: McGraw-Hill.

    Examples
    --------
    >>> from scipy.stats import tiecorrect, rankdata
    >>> tiecorrect([1, 2.5, 2.5, 4])
    0.9
    >>> ranks = rankdata([1, 3, 2, 4, 5, 7, 2, 8, 4])
    >>> ranks
    array([ 1. ,  4. ,  2.5,  5.5,  7. ,  8. ,  2.5,  9. ,  5.5])
    >>> tiecorrect(ranks)
    0.9833333333333333

    Tr   Nr   r   r   r   r   )	ro   r@  r  r  r  r   r   r   rr   )Zrankvalsrl  rN  r  r   rd   rd   rg   rV     s
    %
.rV   RanksumsResultc                 C   s   t tj| |f\} }t| }t|}t| |f}t|}|d| } tj| dd}||| d  d }|| t|| || d  d  }	t|	|\}	}
t	|	|
S )a	  Compute the Wilcoxon rank-sum statistic for two samples.

    The Wilcoxon rank-sum test tests the null hypothesis that two sets
    of measurements are drawn from the same distribution.  The alternative
    hypothesis is that values in one sample are more likely to be
    larger than the values in the other sample.

    This test should be used to compare two samples from continuous
    distributions.  It does not handle ties between measurements
    in x and y.  For tie-handling and an optional continuity correction
    see `scipy.stats.mannwhitneyu`.

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

        * 'two-sided': one of the distributions (underlying `x` or `y`) is
          stochastically greater than the other.
        * 'less': the distribution underlying `x` is stochastically less
          than the distribution underlying `y`.
        * 'greater': the distribution underlying `x` is stochastically greater
          than the distribution underlying `y`.

        .. versionadded:: 1.7.0

    Returns
    -------
    statistic : float
        The test statistic under the large-sample approximation that the
        rank sum statistic is normally distributed.
    pvalue : float
        The p-value of the test.

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

    Examples
    --------
    We can test the hypothesis that two independent unequal-sized samples are
    drawn from the same distribution with computing the Wilcoxon rank-sum
    statistic.

    >>> from scipy.stats import ranksums
    >>> rng = np.random.default_rng()
    >>> sample1 = rng.uniform(-1, 1, 200)
    >>> sample2 = rng.uniform(-0.5, 1.5, 300) # a shifted distribution
    >>> ranksums(sample1, sample2)
    RanksumsResult(statistic=-7.887059, pvalue=3.09390448e-15)  # may vary
    >>> ranksums(sample1, sample2, alternative='less')
    RanksumsResult(statistic=-7.750585297581713, pvalue=4.573497606342543e-15) # may vary
    >>> ranksums(sample1, sample2, alternative='greater')
    RanksumsResult(statistic=-7.750585297581713, pvalue=0.9999999999999954) # may vary

    The p-value of less than ``0.05`` indicates that this test rejects the
    hypothesis at the 5% significance level.

    Nr   r   r   r         (@)
mapro   r   r   r  rZ   rr   r   r  r  )r-  r#  r  r   r   r  rankedrf   expectedr  r  rd   rd   rg   rW   !  s    ?&rW   KruskalResultc                 G   s  t ttj|}t|}|dk r(td|D ]2}|jdkrLttjtj  S |j	dkr,tdq,tt tt|}| dvrtdd}|D ]}t
|| }|d rd	} qq|r| d
kr|D ]}t|}qtj| S |r| dkrttjtjS t|}t|}	t|	}
|
dkrtdtt|dd}d}t|D ].}|t|	|| ||d   ||  7 }q<tj|td}d||d   | d|d   }|d }||
 }t|tj||S )a{	  Compute the Kruskal-Wallis H-test for independent samples.

    The Kruskal-Wallis H-test tests the null hypothesis that the population
    median of all of the groups are equal.  It is a non-parametric version of
    ANOVA.  The test works on 2 or more independent samples, which may have
    different sizes.  Note that rejecting the null hypothesis does not
    indicate which of the groups differs.  Post hoc comparisons between
    groups are required to determine which groups are different.

    Parameters
    ----------
    sample1, sample2, ... : array_like
       Two or more arrays with the sample measurements can be given as
       arguments. Samples must be one-dimensional.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

          * 'propagate': returns nan
          * 'raise': throws an error
          * 'omit': performs the calculations ignoring nan values

    Returns
    -------
    statistic : float
       The Kruskal-Wallis H statistic, corrected for ties.
    pvalue : float
       The p-value for the test using the assumption that H has a chi
       square distribution. The p-value returned is the survival function of
       the chi square distribution evaluated at H.

    See Also
    --------
    f_oneway : 1-way ANOVA.
    mannwhitneyu : Mann-Whitney rank test on two samples.
    friedmanchisquare : Friedman test for repeated measurements.

    Notes
    -----
    Due to the assumption that H has a chi square distribution, the number
    of samples in each group must not be too small.  A typical rule is
    that each sample must have at least 5 measurements.

    References
    ----------
    .. [1] W. H. Kruskal & W. W. Wallis, "Use of Ranks in
       One-Criterion Variance Analysis", Journal of the American Statistical
       Association, Vol. 47, Issue 260, pp. 583-621, 1952.
    .. [2] https://en.wikipedia.org/wiki/Kruskal-Wallis_one-way_analysis_of_variance

    Examples
    --------
    >>> from scipy import stats
    >>> x = [1, 3, 5, 7, 9]
    >>> y = [2, 4, 6, 8, 10]
    >>> stats.kruskal(x, y)
    KruskalResult(statistic=0.2727272727272734, pvalue=0.6015081344405895)

    >>> x = [1, 1, 1]
    >>> y = [2, 2, 2]
    >>> z = [2, 2]
    >>> stats.kruskal(x, y, z)
    KruskalResult(statistic=7.0, pvalue=0.0301973834223185)

    r   z+Need at least two groups in stats.kruskal()r   r   z Samples must be one-dimensional.ra   z1nan_policy must be 'propagate', 'raise' or 'omit'FTrc   r`   z$All numbers are identical in kruskalr   r  r   )r   r  ro   r   r   rm   r   r  rt   r   r}   r   r   r   rX   r  rZ   rV   insertrb  r   r  rr   r   r   r2  r  )r{   rh  r  ri  r   r|   Zcnrz   r  r  tiesrO  r  r   Ztotalnrd  r*  rd   rd   rg   rX   q  sL    B






, rX   FriedmanchisquareResultc                  G   sH  t | }|dk rtd|t | d }td|D ]}t | | |kr4tdq4t| j}|t}tt |D ]}t	|| ||< qtd}tt |D ]6}t
t|| \}}|D ]}|||| d  7 }qqd|||| d  |   }	t|jddd }
d|| |d   |
 d| |d   |	 }t|tj||d S )	a  Compute the Friedman test for repeated measurements.

    The Friedman test tests the null hypothesis that repeated measurements of
    the same individuals have the same distribution.  It is often used
    to test for consistency among measurements obtained in different ways.
    For example, if two measurement techniques are used on the same set of
    individuals, the Friedman test can be used to determine if the two
    measurement techniques are consistent.

    Parameters
    ----------
    measurements1, measurements2, measurements3... : array_like
        Arrays of measurements.  All of the arrays must have the same number
        of elements.  At least 3 sets of measurements must be given.

    Returns
    -------
    statistic : float
        The test statistic, correcting for ties.
    pvalue : float
        The associated p-value assuming that the test statistic has a chi
        squared distribution.

    Notes
    -----
    Due to the assumption that the test statistic has a chi squared
    distribution, the p-value is only reliable for n > 10 and more than
    6 repeated measurements.

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

    r   zHAt least 3 sets of measurements must be given for Friedman test, got {}.r   r   z*Unequal N in friedmanchisquare.  Aborting.r   r   r  )r   rm   r  r   ro   Zvstackr;  r   r   rZ   r   r   rr   r  r   r2  r  )rh  r4  r   r   r   r  ZreplistZrepnumrk  r  r  Zchisqrd   rd   rg   rY     s,    #

,rY   BrunnerMunzelResultrk  c                 C   s  t | } t |}t| |\}}t||\}}|p6|}	|dksH|dkrLd}|	rf|dkrftt jt jS |	r|dkrt| } t|}t| |||S t	| }
t	|}|
dks|dkrtt jt jS t
t | |f}|d|
 }||
|
|  }t |}t |}t
| }t
|}t |}t |}t t || | | d}||
d  }t t || | | d}||d  }|
| ||  }||
| t |
| ||    }|dkrt |
| ||  d}t |
| d|
d  }|t || d|d  7 }|| }tj||}n |dkr6tj|}ntd|d	krJn>|d
kr^d| }n*|dkrdt |d| g }ntdt||S )a
  Compute the Brunner-Munzel test on samples x and y.

    The Brunner-Munzel test is a nonparametric test of the null hypothesis that
    when values are taken one by one from each group, the probabilities of
    getting large values in both groups are equal.
    Unlike the Wilcoxon-Mann-Whitney's U test, this does not require the
    assumption of equivariance of two groups. Note that this does not assume
    the distributions are same. This test works on two independent samples,
    which may have different sizes.

    Parameters
    ----------
    x, y : array_like
        Array of samples, should be one-dimensional.
    alternative : {'two-sided', 'less', 'greater'}, optional
        Defines the alternative hypothesis.
        The following options are available (default is 'two-sided'):

          * 'two-sided'
          * 'less': one-sided
          * 'greater': one-sided
    distribution : {'t', 'normal'}, optional
        Defines how to get the p-value.
        The following options are available (default is 't'):

          * 't': get the p-value by t-distribution
          * 'normal': get the p-value by standard normal distribution.
    nan_policy : {'propagate', 'raise', 'omit'}, optional
        Defines how to handle when input contains nan.
        The following options are available (default is 'propagate'):

          * 'propagate': returns nan
          * 'raise': throws an error
          * 'omit': performs the calculations ignoring nan values

    Returns
    -------
    statistic : float
        The Brunner-Munzer W statistic.
    pvalue : float
        p-value assuming an t distribution. One-sided or
        two-sided, depending on the choice of `alternative` and `distribution`.

    See Also
    --------
    mannwhitneyu : Mann-Whitney rank test on two samples.

    Notes
    -----
    Brunner and Munzel recommended to estimate the p-value by t-distribution
    when the size of data is 50 or less. If the size is lower than 10, it would
    be better to use permuted Brunner Munzel test (see [2]_).

    References
    ----------
    .. [1] Brunner, E. and Munzel, U. "The nonparametric Benhrens-Fisher
           problem: Asymptotic theory and a small-sample approximation".
           Biometrical Journal. Vol. 42(2000): 17-25.
    .. [2] Neubert, K. and Brunner, E. "A studentized permutation test for the
           non-parametric Behrens-Fisher problem". Computational Statistics and
           Data Analysis. Vol. 51(2007): 5192-5204.

    Examples
    --------
    >>> from scipy import stats
    >>> x1 = [1,2,1,1,1,1,1,1,1,1,2,4,1,1]
    >>> x2 = [3,3,4,3,1,2,3,1,1,5,4]
    >>> w, p_value = stats.brunnermunzel(x1, x2)
    >>> w
    3.1374674823029505
    >>> p_value
    0.0057862086661515377

    rc   r`   r   r   r   rk  r  z&distribution should be 't' or 'normal'r  r
  r  r   z6alternative should be 'less', 'greater' or 'two-sided')ro   r   r}   r  rt   r   r   r   r^   r   rZ   r  r   rr   r+  r   r   rk  r  r  rm   r  )r-  r#  r  distributionr{   r  r  r  r  r|   r  r  ZrankcZrankcxZrankcyZrankcx_meanZrankcy_meanZrankxZrankyZ
rankx_meanZ
ranky_meanZSxZSyZwbfnZdf_numerZdf_denomr*  r8  rd   rd   rg   r^   0  sj    L







"





r^   r   c           	      C   s  t | } | jdkrtd|dkrRdt t |  }tj|dt	|  }nv|dkrdt t 
|   }tj|dt	|  }n>|dkr
t dt	|  t j }t t |  t t 
|   }d	t	|  d
 }t ||d  }tj|| | |}n|dkr4t | }tj|dt	| }n|dkr|du rTt | }nt	|t	| krntdt |}|jdkrtdtj| }t ||t j| }tj|}n
td|||fS )a  
    Combine p-values from independent tests bearing upon the same hypothesis.

    Parameters
    ----------
    pvalues : array_like, 1-D
        Array of p-values assumed to come from independent tests.
    method : {'fisher', 'pearson', 'tippett', 'stouffer',
              'mudholkar_george'}, optional

        Name of method to use to combine p-values.
        The following methods are available (default is 'fisher'):

          * 'fisher': Fisher's method (Fisher's combined probability test), the
            sum of the logarithm of the p-values
          * 'pearson': Pearson's method (similar to Fisher's but uses sum of the
            complement of the p-values inside the logarithms)
          * 'tippett': Tippett's method (minimum of p-values)
          * 'stouffer': Stouffer's Z-score method
          * 'mudholkar_george': the difference of Fisher's and Pearson's methods
            divided by 2
    weights : array_like, 1-D, optional
        Optional array of weights used only for Stouffer's Z-score method.

    Returns
    -------
    statistic: float
        The statistic calculated by the specified method.
    pval: float
        The combined p-value.

    Notes
    -----
    Fisher's method (also known as Fisher's combined probability test) [1]_ uses
    a chi-squared statistic to compute a combined p-value. The closely related
    Stouffer's Z-score method [2]_ uses Z-scores rather than p-values. The
    advantage of Stouffer's method is that it is straightforward to introduce
    weights, which can make Stouffer's method more powerful than Fisher's
    method when the p-values are from studies of different size [6]_ [7]_.
    The Pearson's method uses :math:`log(1-p_i)` inside the sum whereas Fisher's
    method uses :math:`log(p_i)` [4]_. For Fisher's and Pearson's method, the
    sum of the logarithms is multiplied by -2 in the implementation. This
    quantity has a chi-square distribution that determines the p-value. The
    `mudholkar_george` method is the difference of the Fisher's and Pearson's
    test statistics, each of which include the -2 factor [4]_. However, the
    `mudholkar_george` method does not include these -2 factors. The test
    statistic of `mudholkar_george` is the sum of logisitic random variables and
    equation 3.6 in [3]_ is used to approximate the p-value based on Student's
    t-distribution.

    Fisher's method may be extended to combine p-values from dependent tests
    [5]_. Extensions such as Brown's method and Kost's method are not currently
    implemented.

    .. versionadded:: 0.15.0

    References
    ----------
    .. [1] https://en.wikipedia.org/wiki/Fisher%27s_method
    .. [2] https://en.wikipedia.org/wiki/Fisher%27s_method#Relation_to_Stouffer.27s_Z-score_method
    .. [3] George, E. O., and G. S. Mudholkar. "On the convolution of logistic
           random variables." Metrika 30.1 (1983): 1-13.
    .. [4] Heard, N. and Rubin-Delanchey, P. "Choosing between methods of
           combining p-values."  Biometrika 105.1 (2018): 239-246.
    .. [5] Whitlock, M. C. "Combining probability from independent tests: the
           weighted Z-method is superior to Fisher's approach." Journal of
           Evolutionary Biology 18, no. 5 (2005): 1368-1373.
    .. [6] Zaykin, Dmitri V. "Optimally weighted Z-test is a powerful method
           for combining probabilities in meta-analysis." Journal of
           Evolutionary Biology 24, no. 8 (2011): 1836-1841.
    .. [7] https://en.wikipedia.org/wiki/Extensions_of_Fisher%27s_method

    r   zpvalues is not 1-Dr   r   r   rX  Zmudholkar_georger   r  r   ZtippettZstoufferNz-pvalues and weights must be of the same size.zweights is not 1-DzoInvalid method '%s'. Options are 'fisher', 'pearson',             'mudholkar_george', 'tippett', 'or 'stouffer')ro   r   r   rm   rr   r   r   r2  r  r   log1pr   pirk  r  r&  Z	ones_liker  Zisfr  r   )	rS  r  r   r  ZpvalZnormalizing_factornuZapprox_factorZZird   rd   rg   r[     sL    J


$




r[   c                 C   s   t d| |||S )a^
  
    Compute the first Wasserstein distance between two 1D distributions.

    This distance is also known as the earth mover's distance, since it can be
    seen as the minimum amount of "work" required to transform :math:`u` into
    :math:`v`, where "work" is measured as the amount of distribution weight
    that must be moved, multiplied by the distance it has to be moved.

    .. versionadded:: 1.0.0

    Parameters
    ----------
    u_values, v_values : array_like
        Values observed in the (empirical) distribution.
    u_weights, v_weights : array_like, optional
        Weight for each value. If unspecified, each value is assigned the same
        weight.
        `u_weights` (resp. `v_weights`) must have the same length as
        `u_values` (resp. `v_values`). If the weight sum differs from 1, it
        must still be positive and finite so that the weights can be normalized
        to sum to 1.

    Returns
    -------
    distance : float
        The computed distance between the distributions.

    Notes
    -----
    The first Wasserstein distance between the distributions :math:`u` and
    :math:`v` is:

    .. math::

        l_1 (u, v) = \inf_{\pi \in \Gamma (u, v)} \int_{\mathbb{R} \times
        \mathbb{R}} |x-y| \mathrm{d} \pi (x, y)

    where :math:`\Gamma (u, v)` is the set of (probability) distributions on
    :math:`\mathbb{R} \times \mathbb{R}` whose marginals are :math:`u` and
    :math:`v` on the first and second factors respectively.

    If :math:`U` and :math:`V` are the respective CDFs of :math:`u` and
    :math:`v`, this distance also equals to:

    .. math::

        l_1(u, v) = \int_{-\infty}^{+\infty} |U-V|

    See [2]_ for a proof of the equivalence of both definitions.

    The input distributions can be empirical, therefore coming from samples
    whose values are effectively inputs of the function, or they can be seen as
    generalized functions, in which case they are weighted sums of Dirac delta
    functions located at the specified values.

    References
    ----------
    .. [1] "Wasserstein metric", https://en.wikipedia.org/wiki/Wasserstein_metric
    .. [2] Ramdas, Garcia, Cuturi "On Wasserstein Two Sample Testing and Related
           Families of Nonparametric Tests" (2015). :arXiv:`1509.02237`.

    Examples
    --------
    >>> from scipy.stats import wasserstein_distance
    >>> wasserstein_distance([0, 1, 3], [5, 6, 8])
    5.0
    >>> wasserstein_distance([0, 1], [0, 1], [3, 1], [2, 2])
    0.25
    >>> wasserstein_distance([3.4, 3.9, 7.5, 7.8], [4.5, 1.4],
    ...                      [1.4, 0.9, 3.1, 7.2], [3.2, 3.5])
    4.0781331438047861

    r   )_cdf_distanceu_valuesv_values	u_weights	v_weightsrd   rd   rg   r\   5   s    Jr\   c                 C   s   t dtd| ||| S )ui  Compute the energy distance between two 1D distributions.

    .. versionadded:: 1.0.0

    Parameters
    ----------
    u_values, v_values : array_like
        Values observed in the (empirical) distribution.
    u_weights, v_weights : array_like, optional
        Weight for each value. If unspecified, each value is assigned the same
        weight.
        `u_weights` (resp. `v_weights`) must have the same length as
        `u_values` (resp. `v_values`). If the weight sum differs from 1, it
        must still be positive and finite so that the weights can be normalized
        to sum to 1.

    Returns
    -------
    distance : float
        The computed distance between the distributions.

    Notes
    -----
    The energy distance between two distributions :math:`u` and :math:`v`, whose
    respective CDFs are :math:`U` and :math:`V`, equals to:

    .. math::

        D(u, v) = \left( 2\mathbb E|X - Y| - \mathbb E|X - X'| -
        \mathbb E|Y - Y'| \right)^{1/2}

    where :math:`X` and :math:`X'` (resp. :math:`Y` and :math:`Y'`) are
    independent random variables whose probability distribution is :math:`u`
    (resp. :math:`v`).

    As shown in [2]_, for one-dimensional real-valued variables, the energy
    distance is linked to the non-distribution-free version of the Cramér-von
    Mises distance:

    .. math::

        D(u, v) = \sqrt{2} l_2(u, v) = \left( 2 \int_{-\infty}^{+\infty} (U-V)^2
        \right)^{1/2}

    Note that the common Cramér-von Mises criterion uses the distribution-free
    version of the distance. See [2]_ (section 2), for more details about both
    versions of the distance.

    The input distributions can be empirical, therefore coming from samples
    whose values are effectively inputs of the function, or they can be seen as
    generalized functions, in which case they are weighted sums of Dirac delta
    functions located at the specified values.

    References
    ----------
    .. [1] "Energy distance", https://en.wikipedia.org/wiki/Energy_distance
    .. [2] Szekely "E-statistics: The energy of statistical samples." Bowling
           Green State University, Department of Mathematics and Statistics,
           Technical Report 02-16 (2002).
    .. [3] Rizzo, Szekely "Energy distance." Wiley Interdisciplinary Reviews:
           Computational Statistics, 8(1):27-38 (2015).
    .. [4] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer,
           Munos "The Cramer Distance as a Solution to Biased Wasserstein
           Gradients" (2017). :arXiv:`1705.10743`.

    Examples
    --------
    >>> from scipy.stats import energy_distance
    >>> energy_distance([0], [2])
    2.0000000000000004
    >>> energy_distance([0, 8], [0, 8], [3, 1], [2, 2])
    1.0000000000000002
    >>> energy_distance([0.7, 7.4, 2.4, 6.8], [1.4, 8. ],
    ...                 [2.1, 4.2, 7.4, 8. ], [7.6, 8.8])
    0.88003340976158217

    r   )ro   r   r  r  rd   rd   rg   r]      s    Nr]   c                 C   s  t ||\}}t ||\}}t|}t|}t||f}|jdd t|}|| |dd d}	|| |dd d}
|du r|	|j }n*tdgt|| f}||	 |d  }|du r|
|j }n*tdgt|| f}||
 |d  }| dkr&t	t
t|| |S | dkrRtt	t
t|| |S tt	t
tt|| | |d|  S )	a  
    Compute, between two one-dimensional distributions :math:`u` and
    :math:`v`, whose respective CDFs are :math:`U` and :math:`V`, the
    statistical distance that is defined as:

    .. math::

        l_p(u, v) = \left( \int_{-\infty}^{+\infty} |U-V|^p \right)^{1/p}

    p is a positive parameter; p = 1 gives the Wasserstein distance, p = 2
    gives the energy distance.

    Parameters
    ----------
    u_values, v_values : array_like
        Values observed in the (empirical) distribution.
    u_weights, v_weights : array_like, optional
        Weight for each value. If unspecified, each value is assigned the same
        weight.
        `u_weights` (resp. `v_weights`) must have the same length as
        `u_values` (resp. `v_values`). If the weight sum differs from 1, it
        must still be positive and finite so that the weights can be normalized
        to sum to 1.

    Returns
    -------
    distance : float
        The computed distance between the distributions.

    Notes
    -----
    The input distributions can be empirical, therefore coming from samples
    whose values are effectively inputs of the function, or they can be seen as
    generalized functions, in which case they are weighted sums of Dirac delta
    functions located at the specified values.

    References
    ----------
    .. [1] Bellemare, Danihelka, Dabney, Mohamed, Lakshminarayanan, Hoyer,
           Munos "The Cramer Distance as a Solution to Biased Wasserstein
           Gradients" (2017). :arXiv:`1705.10743`.

    r  r  Nr   rT  r   r   r   )_validate_distributionro   r  r  r@  r  r  r   rb  rr   multiplyr   r   r  r+  )r8  r  r  r  r  Zu_sorterZv_sorterZ
all_valuesZdeltasZu_cdf_indicesZv_cdf_indicesZu_cdfZu_sorted_cumweightsZv_cdfZv_sorted_cumweightsrd   rd   rg   r     s<    ,




" r  c                 C   s   t j| td} t| dkr"td|durt j|td}t|t| krPtdt |dk rftddt |  k rt jk sn td| |fS | dfS )a  
    Validate the values and weights from a distribution input of `cdf_distance`
    and return them as ndarray objects.

    Parameters
    ----------
    values : array_like
        Values observed in the (empirical) distribution.
    weights : array_like
        Weight for each value.

    Returns
    -------
    values : ndarray
        Values as ndarray.
    weights : ndarray
        Weights as ndarray.

    r   r   zDistribution can't be empty.NzZValue and weight array-likes for the same empirical distribution must be of the same size.z!All weights must be non-negative.zcWeight array-like sum must be positive and finite. Set as None for an equal distribution of weight.)ro   r   r   r   rm   r   rr   r  )valuesr   rd   rd   rg   r  +!  s    r  RepeatedResults)r  r   c                 C   s   t ttj| tjd S )a  Find repeats and repeat counts.

    Parameters
    ----------
    arr : array_like
        Input array. This is cast to float64.

    Returns
    -------
    values : ndarray
        The unique values from the (flattened) input that are repeated.

    counts : ndarray
        Number of times the corresponding 'value' is repeated.

    Notes
    -----
    In numpy >= 1.9 `numpy.unique` provides similar functionality. The main
    difference is that `find_repeats` only returns repeated values.

    Examples
    --------
    >>> from scipy import stats
    >>> stats.find_repeats([2, 1, 2, 3, 2, 2, 5])
    RepeatedResults(values=array([2.]), counts=array([4]))

    >>> stats.find_repeats([[10, 20, 1, 2], [5, 5, 4, 4]])
    RepeatedResults(values=array([4.,  5.]), counts=array([2, 2]))

    r   )r  r   ro   r   r   )rl  rd   rd   rg   r   ]!  s     r   c                 C   s   t | |\} }t| |  |S )a  Square each element of the input array, and return the sum(s) of that.

    Parameters
    ----------
    a : array_like
        Input array.
    axis : int or None, optional
        Axis along which to calculate. Default is 0. If None, compute over
        the whole array `a`.

    Returns
    -------
    sum_of_squares : ndarray
        The sum along the given axis for (a**2).

    See Also
    --------
    _square_of_sums : The square(s) of the sum(s) (the opposite of
        `_sum_of_squares`).

    )r   ro   rr   )rz   r   rd   rd   rg   r  !  s    r  c                 C   sB   t | |\} }t| |}t|s2|t| S t|| S dS )a  Sum elements of the input array, and return the square(s) of that sum.

    Parameters
    ----------
    a : array_like
        Input array.
    axis : int or None, optional
        Axis along which to calculate. Default is 0. If None, compute over
        the whole array `a`.

    Returns
    -------
    square_of_sums : float or ndarray
        The square of the sum over `axis`.

    See Also
    --------
    _sum_of_squares : The sum of squares (the opposite of `square_of_sums`).

    N)r   ro   rr   r   r   r   )rz   r   rf   rd   rd   rg   r  !  s
    
r  r   c                C   s  |dvrt d||durxt| } | jdkrhtjj|| j |dkrRtj	ntj
}tj| j|dS tt|| |S tt| }|dkrdnd	}tj||d
}tj|jtjd}tj|jtjd||< |dkr|d S || }tjd|dd |dd kf }| | }	|dkr"|	S tjt|d t|f }
|dkrP|
|	 S |dkrj|
|	d  d S d|
|	 |
|	d   d  S )a	  Assign ranks to data, dealing with ties appropriately.

    By default (``axis=None``), the data array is first flattened, and a flat
    array of ranks is returned. Separately reshape the rank array to the
    shape of the data array if desired (see Examples).

    Ranks begin at 1.  The `method` argument controls how ranks are assigned
    to equal values.  See [1]_ for further discussion of ranking methods.

    Parameters
    ----------
    a : array_like
        The array of values to be ranked.
    method : {'average', 'min', 'max', 'dense', 'ordinal'}, optional
        The method used to assign ranks to tied elements.
        The following methods are available (default is 'average'):

          * 'average': The average of the ranks that would have been assigned to
            all the tied values is assigned to each value.
          * 'min': The minimum of the ranks that would have been assigned to all
            the tied values is assigned to each value.  (This is also
            referred to as "competition" ranking.)
          * 'max': The maximum of the ranks that would have been assigned to all
            the tied values is assigned to each value.
          * 'dense': Like 'min', but the rank of the next highest element is
            assigned the rank immediately after those assigned to the tied
            elements.
          * 'ordinal': All values are given a distinct rank, corresponding to
            the order that the values occur in `a`.
    axis : {None, int}, optional
        Axis along which to perform the ranking. If ``None``, the data array
        is first flattened.

    Returns
    -------
    ranks : ndarray
         An array of size equal to the size of `a`, containing rank
         scores.

    References
    ----------
    .. [1] "Ranking", https://en.wikipedia.org/wiki/Ranking

    Examples
    --------
    >>> from scipy.stats import rankdata
    >>> rankdata([0, 2, 3, 2])
    array([ 1. ,  2.5,  4. ,  2.5])
    >>> rankdata([0, 2, 3, 2], method='min')
    array([ 1,  2,  4,  2])
    >>> rankdata([0, 2, 3, 2], method='max')
    array([ 1,  3,  4,  3])
    >>> rankdata([0, 2, 3, 2], method='dense')
    array([ 1,  2,  3,  2])
    >>> rankdata([0, 2, 3, 2], method='ordinal')
    array([ 1,  2,  4,  3])
    >>> rankdata([[0, 2], [3, 2]]).reshape(2,2)
    array([[1. , 2.5],
          [4. , 2.5]])
    >>> rankdata([[0, 2, 2], [3, 2, 5]], axis=1)
    array([[1. , 2.5, 2.5],
           [2. , 1. , 3. ]])

    )r   r  r   denseordinalzunknown method "{0}"Nr   r   r   r  r  Z	quicksortr  r   Tr   r  r   r  r   )rm   r  ro   r   r   r  r  r  r   r   r   r   r   rr  rZ   rv   r  r  r  r  rb  r  r   )rz   r  r   dtrl  algoZsorterr=  r   r  r   rd   rd   rg   rZ   !  s6    A

"


rZ   )r`   )r   NN)r   N)r   r`   )Nr   N)Nr   r   r   )Nr   Tr`   )Nr   Tr`   )Nr   r   r   )Nr   r   r   )r   r   r`   )r   r`   r   )r   Tr`   )r   TTr`   )r   r   Tr`   )r   r`   r  )r   r`   r  )r   r`   )rd   r?  N)rP  )rY  NNF)rY  NN)rY  NN)r   r   r`   )r   )r   r   r`   )r   r   r`   )r   r   )Nr  r   r`   r  F)r)  r)  )r   )rT  r   )r   )r  )Nr   r`   r  )Nr`   r  r   )TNT)r  r   N)r   r`   r  )Tr  )r   Tr`   NNr  r   )r   N)r   )r   Tr`   Nr  )r   r`   r  )N)Nr   r   N)Nr   r   )rd   r  r  )r  r  )rd   r(  r  r  )r  )r  rk  r`   )r   N)NN)NN)NN)r   )r   )r   )r  rw   r!  r   collectionsr   Znumpyro   r   r   r   Zscipy.spatial.distancer   Zscipy.ndimager	   Zscipy._lib._utilr
   r   r   r   Zscipy.specialr  Zscipyr    r   r   Z_stats_mstats_commonr   r   r   r   Z_statsr   r   r   r   Zdataclassesr   Z
_hypotestsr   __all__r}   r   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r   r'   r(   r)   r  r*   r  r  r+   r'  r,   r1  r-   r5  r.   Z	deprecater/   r0   rA  r1   rV  r_  r`  r2   rg  r3   r4   r5   rn  ro  rp  r7   r6   r9   Zerfinvr   r  r8   r  r  r;   Z%_median_absolute_deviation_deprec_msgr:   r  r<   r=   r>   r?   r  ry   rA   rB   r  rs  r@   r_   r  r  r  rC   rD   rE   rF   rG   r  rH   r  rI   r  rJ   r  rK   r  r  r  r  rL   r  r!  r"  r  r)  rM   r  r-  r0  r1  r2  rO   r4  rN   r8  r?  rG  rL  rO  r7  rT  rU  rP   r^  r[  r\  r]  rU   rT   rd  rh  ri  rR   ZKs_2sampResultrx  r{  r  r  rS   r  rQ   rV   r  rW   r  rX   r  rY   r  r^   r[   r\   r]   r  r  r  r   r  r  rZ   rd   rd   rd   rg   <module>   s  
LC
].16>=0;Y+;gnX
f
p
I
>
) 
P+Z 
NMPS@GR  
 -
 
p
D=<E
 d 
	

 9  

 
 :V
 
 J
 5<

  !0-3
 
j


|+  
  #  
K
r
 ^  g&W/ 2 -MvA  yMRW/#