
    (ph^                    b   S r SSKrSSKrSSKJr  SSKJr  SSKJr  SSKr	SSKJ
r
JrJr  SSKJr  SSKJr  SS	KJrJr  SS
KJrJrJrJrJrJr  SSKJr  SSKJr  SSKJr  SSK J!r!  SSK J"r#  SSK$J%r%J&r&J'r'  SSK(J)r)J*r*J+r+  SSK,J-r-J.r.  SSK/J0r0  SSK1J2r2  SSK3J4r4J5r5J6r6J7r7J8r8J9r9J:r:  SSK;J<r<J=r=J>r>J?r?J@r@JArAJBrBJCrCJDrD  SSKEJFrG  SSKHJIrI  SSKJJrJ  SSKJKrK  SSKJLrL  SSKMJNrNJOrOJPrPJQrQJRrRJSrSJTrTJUrU  SSKVJWrX  SSKJYrY  / SQrZSS .S! jr[S" r\SS .S# jr]\I" S$S%S&// 5      r^\<" S' SSSS(S) S*/S+9GS>S, j5       r_\<" S- SSSS(S. S*/S+9GS?SS/.S0 jj5       r`\<" S1 SSSS(S2 S*/S+9SSSS3.S4 j5       ra\" S5S65      rbS7 rc\<" \cS(S8S9.S:9GS@S< j5       rd\	R                  S4S= jrf\<" S> SSS? S@9GSASA j5       rg\<" SB SSC SD9GSBSE j5       rh\<" SF SSG SD9GSCSH j5       ri\<" SI SSJ SD9GSCSK j5       rj\<" SL SSM SD9GSBSN j5       rk\<" SO SSP SD9GSBSQ j5       rlGSDSR jrmSS rnST ro\" SUSV5      \<" \nS\o\mSW9GSESSX.SY jj5       5       rpS(SZ.S[ jrqSSS\.S] jrrGSFS^ jrs\<" S_ S` SSa9GSGSb j5       rt\<" Sc Sd SSa9GSHSe j5       ru\" SfSg5      rvGSISh jrwGSJSi jrx\" SjSk5      ry\<" \ySSlSm9GSKSo j5       rz\" SpSk5      r{\<" \{SSqSm9GSKSr j5       r|\" SsSk5      r}\<" \}SSlSm9GSLSt j5       r~\<" \^SSu9SSv.Sw j5       r  GSMSx jrSy rGSNSz jr\" S{S|5      r  GSOS} jr\" S~S5      rGSPS jr\" SS5      rGSPS jrS r\<" S S SSS9GSQS j5       rS rGSRS jrSSS;S.S jrGSRS jrGSSS jrS\GR                   " S5      S-  \GR"                  " S5      -  0r\<" S S SSSS80S9  GSTS j5       rS rS\	GR*                  SS;4S jr\" SS5      rGSUS jrGSVS jrGSWS jrGSVS jr\" SSk5      rS rS rGSXS jr\<" \S\Sm9SSv.S j5       r\- " S S5      5       r\<" \SS SS9S;SS.S j5       rS rS rS r\" SSS/5      r\I" SS%S&// 5      r " S S\5      rSnSSS.S jrGSYSS.S jjrS rS rS rS r  GSZS jrS rS;SSSnS.S jrGS[S jr\I" SS%S&/S/5      r " S S\5      rS rS r\<" \SS\SS9GSKS j5       rGS\S jrGSYS jrGSYS jrGSYS jr\" SSk5      r GS]S jrSr\" SSS1\S9\<" \SS\SS9SS(S;SSSnSSS.S j5       5       rS rS rS r GSYS jrGS^S jr   GS_S jrS r\<" \SS\SS(S9GSKS j5       rSSSSSSS.rS rS rS rS r\" SSk5      rGS`S jrGSaS jrGSbS(S.S jjr\I" SS%S&/SS/5      rS rS rS rS r\<" \SSq\S9\" SS5      GScS j5       5       r\rS rS rS r\<" \SSq\S9\" SS5      GSdS j5       5       rGS  rGS r\<" \\Sq\S9\" SS5      GSeGS j5       5       rGS r\" GSSk5      r\<" \SGS9GSfGS j5       r\" GSSk5      r\<" \SGS9S;GS.GS	 j5       r\" GS
Sk5      r\<" \SS(GS9GS 5       r\" GSSk5      r\<" \SGS9  GSgGS j5       r\<" \^S*/S(GS9GShSSv.GS jj5       r\- " GS GS5      5       rGS rSSSnGS.GS jrGS\GS jrGS\GS jrGS\GS jrGS\GS jrGS r\" GSGS5      r\Y" GS5      GS 5       rGSVGS jrGSVGS  jrGSiSS;GS!.GS" jjrGS# rGSjGS$ jrGSkSS/.GS% jjrGS& rSGS'.GS( jrGS) r\<" \nS\oGS* SW9GSYSS8S(GS+.GS, jj5       r\I" GS-/ GS.QGS//GS09rGSlGS1 jrSSS8S;SSGS2.GS3 jrSSS8S;SSGS4.GS5 jGr  " GS6 GS75      Gr " GS8 GS95      Gr " GS: GS;5      Gr " GS< GS=5      Grg(m  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)Sequence)arrayasarrayma)sparse)distance_matrix)milpLinearConstraint)check_random_state_get_nan_rename_parameter_contains_nan	AxisError
_lazywhere)_deprecate_positional_args)linalg   )distributions)_mstats_basic)_find_repeatstheilslopessiegelslopes)_kendall_dis_toint64_weightedrankedtau)	dataclassfield)_all_partitions)!_compute_outer_prob_inside_method)MonteCarloMethodPermutationMethodBootstrapMethodmonte_carlo_testpermutation_test	bootstrap_batch_generator)	_axis_nan_policy_factory_broadcast_concatenate_broadcast_shapes#_broadcast_array_shapes_remove_axisSmallSampleWarningtoo_small_1d_not_omittoo_small_1d_omittoo_small_nd_not_omittoo_small_nd_omit)_binary_search_for_binom_tst)_make_tuple_bunch)stats)root_scalar)normalize_axis_index)_asarrayarray_namespaceis_numpyxp_sizexp_moveaxis_to_endxp_signxp_vector_normxp_broadcast_promote)array_api_extra)_deprecated)Dfind_repeatsgmeanhmeanpmeanmodetmeantvartmintmaxtstdtsemmomentskewkurtosisdescribeskewtestkurtosistest
normaltestjarque_berascoreatpercentilepercentileofscorecumfreqrelfreqobrientransformsemzmapzscoregzscoreiqrgstdmedian_abs_deviation	sigmacliptrimbothtrim1	trim_meanf_onewaypearsonrfisher_exact	spearmanrpointbiserialr
kendalltauweightedtau
linregressr   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quantile_testwasserstein_distancewasserstein_distance_ndenergy_distancebrunnermunzelalexandergovern	expectilelmomentxpc                    Uc  [        U 5      nUc  UR                  U S5      n SnOUR                  U 5      n UnU R                  S:X  a  UR                  U S5      n X4$ )Nr   )r8   reshaper   ndim)aaxisr   outaxiss       H/var/www/html/venv/lib/python3.13/site-packages/scipy/stats/_stats_py.py_chk_asarrayr   p   s`    	zQ|JJq% JJqMvv{JJq% :    c                 b   Uc/  [         R                  " U 5      n [         R                  " U5      nSnO.[         R                  " U 5      n [         R                  " U5      nUnU R                  S:X  a  [         R                  " U 5      n UR                  S:X  a  [         R                  " U5      nXU4$ )Nr   )npravelr   r   
atleast_1d)r   br   r   s       r   _chk2_asarrayr      s    |HHQKHHQKJJqMJJqMvv{MM!vv{MM!=r   c           	         U c  [        U6 OU n U Vs/ s H  n[        USS9PM     nnU Vs/ s HK  nU R                  UR                  S5      (       a  U R	                  S5      R                  OUR                  PMM     nnU R
                  " U6 nU Vs/ s H  o R                  X$SS9PM     nn[        U5      S:X  a  US   $ [        U5      $ s  snf s  snf s  snf )	NTsubokintegral      ?Fcopyr   r   )	r8   r7   isdtypedtyper   result_typeastypelentuple)r   arraysr   dtypesr   s        r   _convert_common_floatr      s    %'Z&	!RB7=>vehuD)vF>.46.4U (*zz%++z'J'Jrzz"~##KK .4  6NNF#E?EFveii5i1vFFFQ6!99E&M9 ?6 Gs   CACCSignificanceResult	statisticpvaluec                     U $ N xs    r   <lambda>r          !r   Tc                     U 4$ r   r   r   s    r   r   r          1$r   weights)	n_samples	n_outputs	too_smallpairedresult_to_tuplekwd_samplesc                 
   [        X5      nUR                  XS9n Ub  UR                  X2S9n[        R                  " SS9   UR	                  U 5      nSSS5        UR                  [        WXS95      $ ! , (       d  f       N'= f)a  Compute the weighted geometric mean along the specified axis.

The weighted geometric mean of the array :math:`a_i` associated to weights
:math:`w_i` is:

.. math::

    \exp \left( \frac{ \sum_{i=1}^n w_i \ln a_i }{ \sum_{i=1}^n w_i }
               \right) \, ,

and, with equal weights, it gives:

.. math::

    \sqrt[n]{ \prod_{i=1}^n a_i } \, .

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 to which the input arrays are cast before the calculation is
    performed.
weights : array_like, optional
    The `weights` array must be broadcastable to 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 sample geometric mean is the exponential of the mean of the natural
logarithms of the observations.
Negative observations will produce NaNs in the output because the *natural*
logarithm (as opposed to the *complex* logarithm) is defined only for
non-negative reals.

References
----------
.. [1] "Weighted Geometric Mean", *Wikipedia*,
       https://en.wikipedia.org/wiki/Weighted_geometric_mean.
.. [2] Grossman, J., Grossman, M., Katz, R., "Averages: A New Approach",
       Archimedes Foundation, 1983

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

r   Nignoredivider   r   )r8   r   r   errstatelogexp_xp_mean)r   r   r   r   r   log_as         r   rB   rB      st    N 
	$B


1
"A**W*2	H	%q	 
& 66(5t=>> 
&	%s   A44
Bc                     U $ r   r   r   s    r   r   r      r   r   c                     U 4$ r   r   r   s    r   r   r      r   r   r   c                ~   [        X5      nUR                  XS9n Ub  UR                  X2S9nU S:  nUR                  U5      (       a8  UR                  XTR                  U 5      n Sn[
        R                  " U[        SS9  [        R                  " SS9   S	[        S	U -  XS
9-  sSSS5        $ ! , (       d  f       g= f)a  Calculate the weighted harmonic mean along the specified axis.

The weighted harmonic mean of the array :math:`a_i` associated to weights
:math:`w_i` is:

.. math::

    \frac{ \sum_{i=1}^n w_i }{ \sum_{i=1}^n \frac{w_i}{a_i} } \, ,

and, with equal weights, it gives:

.. math::

    \frac{ n }{ \sum_{i=1}^n \frac{1}{a_i} } \, .

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

    .. versionadded:: 1.9

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

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

Notes
-----
The sample harmonic mean is the reciprocal of the mean of the reciprocals
of the observations.

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.

The harmonic mean is only defined if all observations are non-negative;
otherwise, the result is NaN.

References
----------
.. [1] "Weighted Harmonic Mean", *Wikipedia*,
       https://en.wikipedia.org/wiki/Harmonic_mean#Weighted_harmonic_mean
.. [2] Ferger, F., "The nature and use of the harmonic mean", Journal of
       the American Statistical Association, vol. 26, pp. 36-40, 1931

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

r   Nr   zaThe harmonic mean is only defined if all elements are non-negative; otherwise, the result is NaN.   
stacklevelr   r   r   r   )r8   r   anywherenanwarningswarnRuntimeWarningr   r   r   )r   r   r   r   r   negative_maskmessages          r   rC   rC      s    ` 
	$B


1
"A**W*2EM	vvm HH]FFA.Ag~!<	H	%XcAgDBB 
&	%	%s   B..
B<c                     U $ r   r   r   s    r   r   r   Z  r   r   c                     U 4$ r   r   r   s    r   r   r   [  r   r   r   r   r   c                   [        U[        [        45      (       d  [        S5      eUS:X  a
  [	        XX4S9$ [        X5      nUR                  XS9n Ub  UR                  XCS9nU S:  nUR                  U5      (       a=  UR                  U[        R                  U 5      n Sn[        R                  " U[        SS9  [        R                  " S	S	S
9   [        U [        U5      -  X$S9SU-  -  sSSS5        $ ! , (       d  f       g= f)uz  Calculate the weighted power mean along the specified axis.

The weighted power mean of the array :math:`a_i` associated to weights
:math:`w_i` is:

.. math::

    \left( \frac{ \sum_{i=1}^n w_i a_i^p }{ \sum_{i=1}^n w_i }
          \right)^{ 1 / p } \, ,

and, with equal weights, it gives:

.. math::

    \left( \frac{ 1 }{ n } \sum_{i=1}^n a_i^p \right)^{ 1 / p }  \, .

When ``p=0``, it returns the geometric mean.

This mean is also called generalized mean or Hölder mean, and must not be
confused with the Kolmogorov generalized mean, also called
quasi-arithmetic mean or generalized f-mean [3]_.

Parameters
----------
a : array_like
    Input array, masked array or object that can be converted to an array.
p : int or float
    Exponent.
axis : int or None, optional
    Axis along which the power 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
-------
pmean : ndarray, see `dtype` parameter above.
    Output array containing the power mean values.

See Also
--------
numpy.average : Weighted average
gmean : Geometric mean
hmean : Harmonic mean

Notes
-----
The power 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.

The power mean is only defined if all observations are non-negative;
otherwise, the result is NaN.

.. versionadded:: 1.9

References
----------
.. [1] "Generalized Mean", *Wikipedia*,
       https://en.wikipedia.org/wiki/Generalized_mean
.. [2] Norris, N., "Convexity properties of generalized mean value
       functions", The Annals of Mathematical Statistics, vol. 8,
       pp. 118-120, 1937
.. [3] Bullen, P.S., Handbook of Means and Their Inequalities, 2003

Examples
--------
>>> from scipy.stats import pmean, hmean, gmean
>>> pmean([1, 4], 1.3)
2.639372938300652
>>> pmean([1, 2, 3, 4, 5, 6, 7], 1.3)
4.157111214492084
>>> pmean([1, 4, 7], -2, weights=[3, 1, 3])
1.4969684896631954

For p=-1, power mean is equal to harmonic mean:

>>> pmean([1, 4, 7], -1, weights=[3, 1, 3])
1.9029126213592233
>>> hmean([1, 4, 7], weights=[3, 1, 3])
1.9029126213592233

For p=0, power mean is defined as the geometric mean:

>>> pmean([1, 4, 7], 0, weights=[3, 1, 3])
2.80668351922014
>>> gmean([1, 4, 7], weights=[3, 1, 3])
2.80668351922014

z:Power mean only defined for exponent of type int or float.r   r   r   Nz^The power mean is only defined if all elements are non-negative; otherwise, the result is NaN.r   r   r   r   invalidr   r   )
isinstanceintfloat
ValueErrorrB   r8   r   r   r   r   r   r   r   r   r   r   )r   pr   r   r   r   r   r   s           r   rD   rD   Y  s    L a#u&& " # 	#AvQ@@		$B


1
"A**W*2EM	vvm HH]BFFA.Ag~!<	Hh	758$@1Q3G 
8	7	7s   C66
D
ModeResult)rE   countc                     [         R                  " U5      nUR                  S:X  a,  U(       a"  [         R                  " SUR                  S9S   OUnOSX'   [        X5      $ )Nr   r   r   )r   isnanshaper   r   r   )rE   r   is      r   _mode_resultr     sK     	Aww"}89

1EKK04ud""r   F)vectorizationnan_propagation)override	propagatec                    [         R                  " U R                  [         R                  5      (       d  Sn[	        U5      eU R
                  S:X  a2  [        U 5      n[        [         R                  " US/UR                  S96 $ [         R                  " U SS9u  pgXgR                  5          UR                  5       p[        US   U	S   5      $ )a  Return an array of the modal (most common) value in the passed array.

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

Parameters
----------
a : array_like
    Numeric, 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': treats nan as it would treat any other value
      * 'raise': throws an error
      * 'omit': performs the calculations ignoring nan values
keepdims : bool, optional
    If set to ``False``, the `axis` over which the statistic is taken
    is consumed (eliminated from the output array). If set to ``True``,
    the `axis` is retained with size one, and the result will broadcast
    correctly against the input array.

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

Notes
-----
The mode  is calculated using `numpy.unique`.
In NumPy versions 1.21 and after, all NaNs - even those with different
binary representations - are treated as equivalent and counted as separate
instances of the same value.

By convention, the mode of an empty array is NaN, and the associated count
is zero.

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

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

>>> stats.mode(a, axis=None, keepdims=True)
ModeResult(mode=[[3]], count=[[5]])
>>> stats.mode(a, axis=None, keepdims=False)
ModeResult(mode=3, count=5)

zArgument `a` is not recognized as numeric. Support for input that cannot be coerced to a numeric array was deprecated in SciPy 1.9.0 and removed in SciPy 1.11.0. Please consider `np.unique`.r   r   T)return_countsr   )r   
issubdtyper   number	TypeErrorsizer   r   r   uniqueargmaxmax)
r   r   
nan_policykeepdimsr   NaNvalscntsmodescountss
             r   rE   rE     s    D ==")),,:   vv{qk288S!HCII>??1D1JD'6eBi,,r   c                    Uc  [        U 5      OUnUR                  U R                  UR                  S9nUc  X4$ Uu  pgUu  pUb  XX(       a  X:  OX:*  -  nUb  XY(       a  X:  OX:  -  nUR	                  U5      (       a  [        S5      eUR                  U5      (       ag  UR                  U R                  S5      (       a  UR                  S5      R                  OU R                  n
UR                  XTR                  X:S9U 5      n X4$ )as  Replace elements outside limits with a value.

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).  Elements in the
    input array less than the lower limit or greater than the upper limit
    will be replaced with `val`. 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.
val : float, default: NaN
    The value with which extreme elements of the array are replaced.

r   z#No array values within given limitsr   r   )r8   zerosr   boolallr   r   r   r   r   r   )r   limits	inclusivevalr   masklower_limitupper_limitlower_includeupper_includer   s              r   _put_val_to_limitsr  :  s    &  "z	rB88AGG2778+D~w%K#, M]8HH]8HH	vvd||>??	vvd|| )+

177J(G(G

2$$QWWHHT::c:7;7Nr   c                     U $ r   r   r   s    r   r   r   b      ar   c                     U 4$ r   r   r   s    r   r   r   c  s    qdr   )r   default_axisr   c                 H   [        U 5      n[        XUSUS9u  pUR                  XU R                  S9nUR                  UR	                  U) U R                  S9X0R                  S9n[        US:g  Xg4UR                  UR                  5      nUR                  S:X  a  US   $ U$ )aW  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 : ndarray
    Trimmed mean.

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

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

        r   r   r   r   r   r   r   )	r8   r  sumr   r   r   r   r   r   )	r   r   r   r   r   r   r  nmeans	            r   rF   rF   a  s    \ 
	B I2"EGA
&&QWW&
-C
rzz4%qwwz/d''JAa1fsh		266:DyyA~48/4/r   c                     U $ r   r   r   s    r   r   r     r  r   c                     U 4$ r   r   r   s    r   r   r         r   )r   r   c           	          [        U 5      n[        XX%S9u  p[        R                  " 5          [        R                  " S[
        5        [        XUSUS9sSSS5        $ ! , (       d  f       g= f)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
--------
>>> import numpy as np
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tvar(x)
35.0
>>> stats.tvar(x, (3,17))
20.0

r   r   omit
correctionr   r   r   N)r8   r  r   catch_warningssimplefilterr-   _xp_var)r   r   r   r   ddofr   _s          r   rG   rG     sV    b 
	Ba:DA		 	 	"h(:; qBO 
#	"	"s   'A
A,c                     U $ r   r   r   s    r   r   r     r  r   c                     U 4$ r   r   r   s    r   r   r     r  r   c                    [        U 5      nU R                  n[        XS4US4UR                  US9u  pUR	                  XS9nUR                  UR                  U) U R                  S9US9n	UR                  U	S:g  XR                  5      n
UR                  UR                  U
5      5      (       d  UR                  XSS9n
U
R                  S:X  a  U
S   $ U
$ )	a  Compute the trimmed minimum.

This function finds the minimum 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.

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

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

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

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

Nr  r   r   r   Fr   r   )r8   r   r  infminr  r   r   r   r   r   r   r   )r   
lowerlimitr   r   r   r   r   r   r"  r  ress              r   rH   rH     s    Z 
	B GGE $6D8I%'VV4GA &&&
C
rzz4%qwwz/d;A
((163
'C66"((3-  iii/hh!m3r7,,r   c                     U $ r   r   r   s    r   r   r     r  r   c                     U 4$ r   r   r   s    r   r   r     r  r   c                    [        U 5      nU R                  n[        U SU4SU4UR                  * US9u  pUR	                  XS9nUR                  UR                  U) U R                  S9US9n	UR                  U	S:g  XR                  5      n
UR                  UR                  U
5      5      (       d  UR                  XSS9n
U
R                  S:X  a  U
S   $ U
$ )	a  Compute the trimmed maximum.

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

Parameters
----------
a : array_like
    Array of values.
upperlimit : None or float, optional
    Values in the input array greater than the given limit will be ignored.
    When upperlimit is None, then all values are used. The default value
    is None.
axis : int or None, optional
    Axis along which to operate. Default is 0. If None, compute over the
    whole array `a`.
inclusive : {True, False}, optional
    This flag determines whether values exactly equal to the upper limit
    are included.  The default value is True.

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

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

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

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

Nr  r   r   r   Fr   r   )r8   r   r  r!  r   r  r   r   r   r   r   r   r   )r   
upperlimitr   r   r   r   r   r   r   r  r$  s              r   rI   rI     s    X 
	B GGE T:$6y8I&(ffW5GA &&&
C
rzz4%qwwz/d;A
((163
'C66"((3-  iii/hh!m3r7,,r   c                     U $ r   r   r   s    r   r   r   P  r  r   c                     U 4$ r   r   r   s    r   r   r   P  r  r   c           	           [        XX#USS9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
--------
>>> import numpy as np
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tstd(x)
5.9160797830996161
>>> stats.tstd(x, (3,17))
4.4721359549995796

T_no_deco      ?)rG   )r   r   r   r   r  s        r   rJ   rJ   O  s    b 9D4@#EEr   c                     U $ r   r   r   s    r   r   r     r  r   c                     U 4$ r   r   r   s    r   r   r     r  r   c           	      F   [        U 5      n[        XX%S9u  p[        R                  " 5          [        R                  " S[
        5        [        XUSUS9S-  nSSS5        UR                  UR                  U 5      ) UWR                  S9nXxS-  -  $ ! , (       d  f       N@= f)a6  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
--------
>>> import numpy as np
>>> from scipy import stats
>>> x = np.arange(20)
>>> stats.tsem(x)
1.3228756555322954
>>> stats.tsem(x, (3,17))
1.1547005383792515

r   r   r  r  r.  Nr  )
r8   r  r   r  r  r-   r  r  r   r   )	r   r   r   r   r  r   r  sdn_obss	            r   rK   rK     s    b 
	Ba:DA		 	 	"h(:; Qdv"MsR 
# FFBHHQK<d"((F;Es
? 
#	"s   +B
B c                     [         R                  " U R                  SU5      5      nSnUR                  S:X  d  UR                  S:  a  [        U5      e[        U5      $ )Norder1`order` must be a scalar or a non-empty 1D array.r   r   )r   r   getr   r   r   r   )kwdsdefault_orderr5  r   s       r   _moment_outputsr:    sJ    MM$((7M:;EAGzzQ%**q.!!u:r   c                  V    [        U 5      S:X  a  U S   $ [        R                  " U 5      $ )Nr   r   )r   r   r   )argss    r   _moment_result_objectr=    s%    
4yA~Aw::dr   c                 *    US:  a  [        U 5      $ U 4$ Nr   )r   )r   n_outs     r   _moment_tuplerA    s    qy58*qd*r   rL   r5  )r   r   r   )centerc          
         [        U 5      n[        XUS9u  pUR                  U R                  S5      (       a  UR	                  XR
                  S9n OUR	                  U 5      n UR	                  XR                  S9n[        U5      S:X  a  [        S5      eUR                  XR                  U5      :g  5      (       a  [        S5      eUR                  S:X  a  US   OUnUR                  S:  a  USL =(       a    UR                  US	:  5      nU(       a  UR                  XS
S9OSn/ n[        UR                  S   5       Hj  n	X   n
Uc4  U
S	:  a.  UR                  [        X
X'S9[         R"                  S4   5        M>  UR                  [        X
X$S9[         R"                  S4   5        Ml     UR%                  USS9$ [        XX$S9$ )aC  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.
order : int or 1-D 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

center : float or None, optional
   The point about which moments are taken. This can be the sample mean,
   the origin, or any other be point. If `None` (default) compute the
   center as the sample mean.

Returns
-------
n-th moment about the `center` : 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 moment of a data sample is:

.. math::

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

Where `n` is the number of samples, and `c` is the center around which the
moment is calculated. This function uses exponentiation by squares [1]_ for
efficiency.

Note that, if `a` is an empty array (``a.size == 0``), array `moment` with
one element (`moment.size == 1`) is treated the same as scalar `moment`
(``np.isscalar(moment)``). This might produce arrays of unexpected shape.

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], order=1)
0.0
>>> moment([1, 2, 3, 4, 5], order=2)
2.0

r   r   r   r   r6  z)All elements of `order` must be integral.r   Nr   Tr   r   )r  .r   )r8   r   r   r   r   float64r:   r   r   roundr   r  ranger   append_momentr   newaxisconcat)r   r5  r   r   rB  r   calculate_meanr  mmntr   order_is              r   rL   rL     s   T 
	B1r*GA	zz!'':&&JJq

J+JJqMJJuGGJ,Eu~
 LMM	vvexx&''DEEqE"IeE zzA~4=BFF519,=7Erwwqdw34u{{1~&AhG~'A+GA@SQRGAB2::s?ST ' yyAy&&q33r   )precision_warningc                   X-
  n[        U5      S:X  a  U$ UR                  UR                  5      R                  S-  n[        R
                  " SSS9   UR                  UR                  U5      USS9UR                  U5      -  nS S S 5        [        R
                  " SS9   UR                  WU:  5      nS S S 5        Uc  [        U 5      OJ[        R                  " [        R                  " U R                  5      [        R                  " U5         5      n	W(       a)  U	S:  a#  U(       a  S	n
[        R                  " U
[        S
S9  U$ ! , (       d  f       N= f! , (       d  f       N= f)Nr   
   r   r   TrD  r   r   zPrecision loss occurred in moment calculation due to catastrophic cancellation. This occurs when the data are nearly identical. Results may be unreliable.   r   )r:   finfor   epsr   r   r   absr   prodr   r   r   r   r   )r   r  r   r   rO  a_zero_meanrU  rel_diffprecision_lossr  r   s              r   _demeanr[  b  s   
 (K{q 
((4::

"
"R
'C	Hh	766"&&-D#'  )+-66$<8 
8 
X	&3/ 
'|ggbjj)"**T*:;<  !a%$5F 	g~!< 
8	7 
'	&s   3E
"E

E
E)r  r   c                N   Uc  [        U 5      OUnUR                  U R                  S5      (       a  UR                  XR                  S9n U R                  n[        U 5      S:X  a  UR                  XS9$ US:X  d	  US:X  aU  UcR  [        U R                  5      nXb	 US:X  a  UR                  XeS9OUR                  XeS9nUR                  S:X  a  US   $ U$ U/nUn	U	S:  a1  U	S-  (       a	  U	S-
  S-  n	OU	S-  n	UR                  U	5        U	S:  a  M1  Uc  UR                  XS	S
9OUR                  X5S9nUR                  S:X  a  US   OUn[        XX$S9n
US   S:X  a  UR                  U
S	S9nOU
S-  nUSSS2    H  nUS-  nUS-  (       d  M  X-  nM     UR                  XS9$ )zVectorized calculation of raw moment about specified center

When `mean` is None, the mean is computed and used as the center;
otherwise, the provided value is used as the center.

Nr   r   r   r   r   r   r   TrD  r   r   r   )r8   r   r   r   rE  r:   r  listr   onesr   r   rH  r[  )r   r5  r   r  r   r   r   tempn_list	current_nrX  sr  s                r   rI  rI    s     "z	rB	zz!'':&&JJq

J+GGE qzQwwqw$$zeqjT\ QWWK/4z+XXeX1 	99>tBx3t3 WFI
a-q="Q!+INIi  a- 59LBGGA4G0D. 	yyA~484D!4/KbzQJJ{J.N BFF^qDq55A  7717  r   c                     Uc  [        U 5      OUn[        U SXUS9nUS:w  a9  Ub  U R                  U   O
[        U 5      nU[        R
                  " XfU-
  5      -  nU$ )Nr   r\  r   )r8   rI  r   r:   r   r   )r   r   r  r  r   varr  s          r   _varrg    s]    !z	rB
!QB
/Cqy!-AGGDM71:ryydF##Jr   c                     U $ r   r   r   s    r   r   r     r  r   c                     U 4$ r   r   r   s    r   r   r         A4r   )r   r   c                    [        U 5      n[        XUS9u  pU R                  U   nUR                  XSS9nUR	                  XaS9n[        U SXUS9n[        U SXUS9n	[        R                  " SS	9   UR                  UR                  5      R                  n
XU-  S-  :*  nUR                  XR                  UR                  5      XS
-  -  5      nSSS5        U(       dF  W) US:  -  nUR                  U5      (       a'  X   nX   n	US-
  U-  S-  US-
  -  U	-  US
-  -  nUWU'   WR                  S:X  a  US   $ U$ ! , (       d  f       Nr= f)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 NaN 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

r   TrD  r   r   r\     r   r         ?Nr   r.         @r   r   )r8   r   r   r  squeezerI  r   r   rT  r   rU  r   r   r   r   r   )r   r   biasr   r   r  r  mean_reducedm2m3rU  zeror   can_correctnvals                  r   rM   rM     sP   ^ 
	B1r*GA	A771$7/D::d:.L	At2	.B	At2	.B		"hhrxx $$L(1,,xxjj0"3w,? 
# eq1uo66+BBWMC'1s73b82s7BD $DyyA~48/4/ 
#	"s   2A D>>
Ec                     U $ r   r   r   s    r   r   r   )  r  r   c                     U 4$ r   r   r   s    r   r   r   )  rj  r   c                    [        U 5      n[        XUS9u  pU R                  U   nUR                  XSS9nUR	                  XqS9n[        U SXUS9n	[        U SXUS9n
[        R                  " SS	9   XR                  U	R                  5      R                  U-  S-  :*  n[        XS9nUR                  XXS
-  -  5      nSSS5        U(       d[  W) US:  -  nUR                  U5      (       a<  X   n	X   n
SUS-
  -  US-
  -  US-  S-
  U
-  U	S
-  -  SUS-
  S
-  -  -
  -  nUS-   WU'   U(       a  WS-
  OWnUR                  S:X  a  US   $ U$ ! , (       d  f       N= f)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, returning NaN where all values
    are equal.

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 definition, 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.

>>> import numpy as np
>>> 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.

r   TrD  r   r   r\     r   rm  ro  Nrl  r   r         @r   r   )r8   r   r   r  rp  rI  r   r   rT  r   rU  r   r   r   r   )r   r   fisherrq  r   r   r  r  rr  rs  m4ru  r   r   rv  rw  s                   r   rN   rN   (  sp   l 
	B1r*GA	A771$7/D::d:.L	At2	.B	At2	.B		"hhrxx(,,|;a??r!xx2C<0 
#
 eq1uo66+BB!9ac?q!tCxmBG&;a1s
l&JKD $s
D4!84DyyA~48/4/ 
#	"s   2AE
EDescribeResult)nobsminmaxr  varianceskewnessrN   c                    [        U 5      n[        XUS9u  p[        X5      u  pdU(       a3  US:X  a-  [        R                  " U 5      n [
        R                  " XX#5      $ [        U 5      S:X  a  [        S5      eU R                  U   nUR                  XS9UR                  XS94nUR                  XS9n	[        XX%S9n
[        XUS9n[        XUS9n[!        XxXX5      $ )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.

Raises
------
ValueError
    If size of `a` is 0.

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

Examples
--------
>>> import numpy as np
>>> 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.]))

r   r  r   zThe input must not be empty.r   )r   r  r   rq  )r8   r   r   r   masked_invalidmstats_basicrO   r:   r   r   r"  r   r  rg  rM   rN   r  )r   r   r  rq  r   r   contains_nanr  mmmvskkurts                r   rO   rO     s    L 
	B1r*GA,Q;L
f,a $$Qd99qzQ788	A
&&&
q 4	5B
AQ,A	aD	!BA$'D!r00r   c                 d   Uc  [        U 5      OUnUS:X  a  UR                  U 5      nU$ US:X  a  UR                  U 5      nU$ US:X  a\  SU(       a   UR                  UR                  U 5      5      O/UR	                  UR                  U 5      UR                  U 5      5      -  nU$ Sn[        U5      e)zKGet p-value given the statistic, (continuous) distribution, and alternativelessgreater	two-sidedr   z8`alternative` must be 'less', 'greater', or 'two-sided'.)r8   cdfsfrV  minimumr   )r   distributionalternative	symmetricr   r   r   s          r   _get_pvaluer    s    ')z	#rBf!!), M 
		!+ M 
	#IloobffY&78::l&6&6y&A&2ooi&@BC M M!!r   SkewtestResultr   r      )r   r   r  c                 z   [        U 5      n[        XUS9u  p[        XSS9nU R                  U   nUS:  a  SU< S3n[	        U5      eU[
        R                  " US-   US-   -  S	US
-
  -  -  5      -  nSUS
-  SU-  -   S-
  -  US-   -  US-   -  US-
  US-   -  US-   -  US-   -  -  n	S[
        R                  " S
U	S-
  -  5      -   n
S[
        R                  " S[
        R                  " U
5      -  5      -  n[
        R                  " SU
S-
  -  5      nUR                  US:H  UR                  SUR                  S9U5      nXR                  X-  UR                  X-  S
-  S-   5      -   5      -  n[        U[        5       X4S9nUR                  S:X  a  US   OUnUR                  S:X  a  US   OUn[        X5      $ )ae
  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. Must contain at least eight observations.
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.

See Also
--------
:ref:`hypothesis_skewtest` : Extended example

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)

For a more detailed example, see :ref:`hypothesis_skewtest`.
r   Tr,     z4`skewtest` requires at least 8 observations; only n= observations were given.r   rl        @r   r|     F   ro  rS  r  	   r   r.  r   r   r   )r8   r   rM   r   r   mathsqrtr   r   r   r   r  _SimpleNormalr   r  )r   r   r   r  r   b2r  r   ybeta2W2deltaalphaZr   s                  r   rP   rP     s   \ 
	B1r*GA	a	%B	A1u$79!!
TYYQ1q5)cQUm<==AAqD2a4K"$%1-15u1o1%1-/E	diiUQY(	(B		#,--EIIcR!Vn%E
aAQWW5q9Aqy277AI>A+=#>>??AMO[@F1"!A!;;!+VBZF!$$r   KurtosistestResultr{  c           	         [        U 5      n[        XUS9u  pU R                  U   nUS:  a  SU< S3n[        U5      eUS:  a  SU< S3n[        R
                  " USS9  [        XS	S
S9nSUS-
  -  US-   -  nSU-  US-
  -  US-
  -  US-   US-   -  US-   -  US-   -  -  n	Xx-
  U	S-  -  n
SXU-  SU-  -
  S-   -  US-   US-   -  -  SUS-   -  US-   -  XUS-
  -  US-
  -  -  S-  -  nSSU-  SU-  SSUS-  -  -   S-  -   -  -   nSSSU-  -  -
  nSU
SUS-
  -  S-  -  -   n[        XS9n[        U5      UR                  US:H  USSU-  -
  UR                  U5      -  S-  5      -  nUR                  US:H  5      (       a  Sn[        R
                  " U[        SS9  UU-
  SSU-  -  S-  -  n[        U[        5       X4S9nUR                  S:X  a  US   OUnUR                  S:X  a  US   OUn[!        UU5      $ )au	  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. Must contain at least five observations.
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.

See Also
--------
:ref:`hypothesis_kurtosistest` : Extended example

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

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

Examples
--------

>>> import numpy as np
>>> 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)

For a more detailed example, see :ref:`hypothesis_kurtosistest`.
r   rS  z8`kurtosistest` requires at least 5 observations; only n=r     zQ`kurtosistest` p-value may be inaccurate with fewer than 20 observations; only n=r   r   FT)r}  r-  r|  r   g      8@rl  r   r.  r  r  r  g       @ro        @g      "@r  gUUUUUU?r   z\Test statistic not defined in some cases due to division by zero. Return nan in that case...r   )r8   r   r   r   r   r   rN   r   r<   r   rV  r   r   r  r  r   r  )r   r   r   r  r   r  r   r  Evarb2r   	sqrtbeta1Aterm1denomr   term2msgr  r   s                       r   rQ   rQ   ~  s   R 
	B1r*GA	A1u$79!!2v,)*,EGg!,	!%$	7BQqS	QqSAFAaCL!A#1Q32,!"4ac":;E	AQS1WQY!A#!-#qs)QqS/45sGQqSM2CEH1I II 	c)ms9}#y!|2D0Ds/JJKKA3q5	MEQ#Y$$$E
1
CENRXXeslC()#a%'>#&FH HE	vveqj2c>a8	1c!e9s**AMO[@F1"!A!;;!+VBZFa((r   NormaltestResultc                    [        U 5      n[        XSS9u  pE[        XSS9u  peXD-  Xf-  -   n[        UR	                  S5      5      n[        XxSSUS9n	UR                  S:X  a  US   OUnU	R                  S:X  a  U	S   OU	n	[        Xy5      $ )	a3  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. Must contain
    at least eight observations.
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.

See Also
--------
:ref:`hypothesis_normaltest` : Extended example

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

>>> import numpy as np
>>> 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))
>>> res = stats.normaltest(x)
>>> res.statistic
53.619...  # random
>>> res.pvalue
2.273917413209226e-12  # random

For a more detailed example, see :ref:`hypothesis_normaltest`.
Tr,  ro  r  Fr  r  r   r   r   )r8   rP   rQ   _SimpleChi2r   r  r   r  )
r   r   r   r   rd  r  kr   chi2r   s
             r   rR   rR     s    | 
	BAd+DA$/DAac	Irzz"~&Di5UWXF!*1!4	")I!;;!+VBZFI..r   )r	  r   c                   [        U 5      nUR                  U 5      n Uc  UR                  U S5      n SnU R                  U   nUS:X  a  [	        S5      eUR                  XSS9nX-
  n[        XQSS9n[        XQSS9nUS-  US-  US-  S	-  -   -  n[        UR                  S
5      5      n	[        XSSUS9n
UR                  S:X  a  US   OUnU
R                  S:X  a  U
S   OU
n
[        X5      $ )aq  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.
axis : int or None, default: 0
    If an int, the axis of the input along which to compute the statistic.
    The statistic of each axis-slice (e.g. row) of the input will appear in
    a corresponding element of the output.
    If ``None``, the input will be raveled before computing the statistic.

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

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

See Also
--------
:ref:`hypothesis_jarque_bera` : Extended example

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

>>> import numpy as np
>>> 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

For a more detailed example, see :ref:`hypothesis_jarque_bera`.
r   r   z%At least one observation is required.TrD  )r   r-     r   r{  ro  r  Fr  r   )r8   r   r   r   r   r  rM   rN   r  r  r   r   )r   r   r   r  mudiffxrd  r  r   r  r   s              r   rS   rS   A  s    t 
	B


1A|JJq% 	AAv@AA		-BFEU-AD1AAA1q)Irzz"~&Di5UWXF!*1!4	")I!;;!+VBZFi00r   c                    [         R                  " U 5      n U R                  S:X  a{  [         R                  " U5      (       a  [         R                  $ [         R
                  " [         R                  " U5      R                  [         R                  [         R                  S9$ U(       a  XS   U :*  XS   :*  -     n [         R                  " XS9nUc  Sn[        XQX45      $ )a0  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
--------
>>> import numpy as np
>>> from scipy import stats
>>> a = np.arange(100)
>>> stats.scoreatpercentile(a, 50)
49.5

r   r   r   r   )
r   r   r   isscalarr   fullr   rE  sort_compute_qth_percentile)r   perlimitinterpolation_methodr   sorted_s         r   rT   rT     s    | 	

1Avv{;;s66M772::c?00"&&

KKQx1}Ah/0gga#G|"71ELLr   c           	      |   [         R                  " U5      (       d2  U Vs/ s H  n[        XX#5      PM     nn[         R                  " U5      $ SUs=::  a  S::  d  O  [	        S5      e[        S 5      /U R                  -  nUS-  U R                  U   S-
  -  n[        U5      U:w  a^  US:X  a   [        [         R                  " U5      5      nO8US:X  a   [        [         R                  " U5      5      nOUS:X  a  O[	        S	5      e[        U5      nXG:X  a  [        XDS-   5      Xc'   [        S5      nS
n	OU[        XDS-   5      Xc'   US-   n
[        X-
  Xt-
  /[        5      nS/U R                  -  nSX'   Xl        UR                  5       n	[         R                  R                  U [        U5         U-  US9U	-  $ s  snf )Nr   d   z(percentile must be in the range [0, 100]      Y@r   lowerhigherfractionz@interpolation_method can only be 'fraction', 'lower' or 'higher'r   r   r   )r   r  r  r   r   slicer   r   r   floorceilr   r  addreducer   )r  r  r  r   r   scoreindexeridxr   sumvaljwshapes               r   r  r    s   ;;s Q ))=E 	  xxOOCDDT{mgll*G
*d+a/
0C
3x37*bhhsm$C!X-bggcl#C!Z/ 3 4 4 	CAxaQ(aQE!'SW.6w||# 66==w07:=FOOMs   F9c                    [         R                  " U 5      n [        U 5      n[         R                  " U5      n[        X5      u  pV[        X5      u  pxU(       d  U(       a  US:X  a  [	        S5      eU(       a+  [
        R                  " [         R                  " U5      U5      nU(       aI  US:X  a;  [
        R                  " [         R                  " U 5      U 5      n U R                  5       nUS:X  a  SnUS:X  a3  [         R                  " U[         R                  [         R                  S9n	OUS   nS n
US	:X  a&  U
" X:  5      nU
" X:*  5      nX:  nX-   U-   S
U-  -  n	O^US:X  a  U
" X:  5      SU-  -  n	OGUS:X  a  U
" X:*  5      SU-  -  n	O0US:X  a  U
" X:  5      nU
" X:*  5      nX-   S
U-  -  n	O[	        S5      e[
        R                  " U	[         R                  5      n	U	R                  S:X  a  U	S   $ U	$ )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
    A 1-D array to which `score` is compared.
score : array_like
    Scores to compute percentiles for.
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
nan_policy : {'propagate', 'raise', 'omit'}, optional
    Specifies how to treat `nan` values in `a`.
    The following options are available (default is 'propagate'):

      * 'propagate': returns nan (for each value in `score`).
      * 'raise': throws an error
      * 'omit': performs the calculations ignoring nan values

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

See Also
--------
numpy.percentile
scipy.stats.scoreatpercentile, scipy.stats.rankdata

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

>>> import numpy as np
>>> 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

Score arrays (of any dimensionality) are supported:

>>> stats.percentileofscore([1, 2, 3, 3, 4], [2, 3])
array([40., 70.])

The inputs can be infinite:

>>> stats.percentileofscore([-np.inf, 0, 1, np.inf], [1, 2, np.inf])
array([75., 75., 100.])

If `a` is empty, then the resulting percentiles are all `nan`:

>>> stats.percentileofscore([], [1, 2])
array([nan, nan])
raisezThe input contains nan valuesr  r   r   r   ).Nc                 0    [         R                  " U S5      $ Nr   )r   count_nonzeror   s    r   r    percentileofscore.<locals>.count  s    ##Ar**r   rankg      I@strictr  weakr  z3kind can only be 'rank', 'strict', 'weak' or 'mean'r   )r   r   r   r   r   r   masked_wherer   r   	full_liker   rE  filledr   )r   r  kindr   r  cnanpacnsnpsperctr   leftrightplus1s                 r   rU   rU     s   t 	

1AAAJJuE Q+HCU/HCs
g-899
 7
Q/A	A$A 	AvUBFF"**= i 	+ 6>#D!*%ELE\E)dQh7EX!)$	2EV^!*%3EV^#D!*%E\dQh/EEG G IIeRVV$EzzQRyLr   HistogramResult)r   r#  binsizeextrapointsc                    [         R                  " U 5      n UcH  U R                  S:X  a  SnO5U R                  5       nU R	                  5       nXe-
  SUS-
  -  -  nXW-
  Xg-   4n[         R
                  " XUUS9u  p[         R                  " U[        S9nU	S   U	S   -
  n
[        U  Vs/ s H  nUS   U:  d
  XS   :  d  M  UPM     sn5      nUS:  a  U(       a  [        R                  " SU 3S	S
9  [        XS   X5      $ s  snf )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.

r   r   r   ro  r   )binsrG  r   r   r   z'Points outside given histogram range = rl  r   )r   r   r   r"  r   	histogramr   r   r   r   r   r  )r   numbinsdefaultlimitsr   printextrasdata_mindata_maxrd  hist	bin_edgesr  r  r  s                r   
_histogramr     s   ^ 	A66Q;"M uuwHuuwH$w|)<=A%\8<8M ll1-+24OD 88D&D lYq\)G! H!Q'*Q.!A6F2F ! H IKQ;?}M!"	% 4q!17HHHs   'D DCumfreqResult)cumcountr#  r  r  c                 d    [        XX#S9u  pEpg[        R                  " US-  SS9n[        XXg5      $ )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 numpy as np
>>> import matplotlib.pyplot as plt
>>> from scipy import stats
>>> rng = np.random.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   r   cumsumr  )	r   r  defaultreallimitsr   hlr   ecumhists	            r   rV   rV   	  s7    P A(9KJA!iiAA&GQ**r   RelfreqResult)	frequencyr#  r  r  c                     [         R                  " U 5      n [        XX#S9u  pEpgX@R                  S   -  n[	        XEXg5      $ )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 numpy as np
>>> import matplotlib.pyplot as plt
>>> from scipy import stats
>>> rng = np.random.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()

r   r   )r   
asanyarrayr   r   r
  )r   r  r  r   r  r  r   r  s           r   rW   rW   W	  s@    J 	aAA(9KJA!	GGAJAq$$r   c                     [         R                  " [         R                  " [        5      R                  5      n/ nSnU  H  n[         R
                  " U5      n[        U5      n[         R                  " U5      nXW-
  S-  nUR                  5       n	US-
  U-  U-  SU	-  -
  US-
  US-
  -  -  n
XS-
  -  n[        U[         R                  " U
5      -
  5      U:  a  [        S5      eUR                  U
5        UR                  nM     U(       a6  USS  H-  nX<R                  :w  d  M  [         R                  " U[        S9s  $    [         R                  " U5      $ )	a  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 ``*samples`` 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
----------
sample1, sample2, ... : 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.

Raises
------
ValueError
    If the mean of the transformed data is not equal to the original
    variance, indicating a lack of convergence in the O'Brien transform.

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   rn  r.  r   z'Lack of convergence in obrientransform.r   r   )r   r  rT  r   rU  r   r   r  r  rV  r   rH  r   r   object)samplesTINYr   sLastsampler   r  r  sqsumsqtrf  arrs                r   rX   rX   	  s)   r 77288E?&&'D FEJJvFWWQZfq[ #g]R#+-1q5QU2CD 1uosRWWQZ 4'FGGa# & #2;C		!xxf55  88Fr   c                     U $ r   r   r   s    r   r   r   
  r  r   c                     U 4$ r   r   r   s    r   r   r   
  rj  r   )r   r   r   c                     [        U 5      nUc  UR                  U S5      n Sn[        R                  " UR	                  U 5      SUS9n U R
                  U   nUR                  XUS9US-  -  nU$ )a  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. Must contain at least two observations.
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:

>>> import numpy as np
>>> 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

r   r   r   )r   r   )r   r  r.  )r8   r   xpx
atleast_ndr   r   std)r   r   r  r   r   r  rd  s          r   rY   rY    
  sp    n 
	B|JJq% rzz!}14A	A
q-36AHr   c                     U [         R                  " U 5      )    nUR                  S:X  a  [         R                  " S/5      $ US   U:H  R	                  SS9$ )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   T)r   )r   r   r   r   r   r   r  s     r   _isconstr   A
  sL     	
288A;,Avv{xx!	--r   c                     [        X XUS9$ )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`.

See Also
--------
numpy.mean : Arithmetic average
numpy.std : Arithmetic standard deviation
scipy.stats.gzscore : Geometric standard score

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

References
----------
.. [1] "Standard score", *Wikipedia*,
       https://en.wikipedia.org/wiki/Standard_score.
.. [2] Huck, S. W., Cross, T. L., Clark, S. B, "Overcoming misconceptions
       about Z-scores", Teaching Statistics, vol. 8, pp. 38-40, 1986

Examples
--------
>>> import numpy as np
>>> 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   )rZ   )r   r   r  r   s       r   r[   r[   Q
  s    d 4zBBr   r"  c                    [        U 5      n[        XS9n [        U [        R                  5      (       a  [        R
                  OUR
                  n[        U" U 5      XUS9$ )a	  
Compute the geometric standard score.

Compute the geometric z score of each strictly positive value in the
sample, relative to the geometric mean and standard deviation.
Mathematically the geometric z score can be evaluated as::

    gzscore = log(a/gmu) / log(gsigma)

where ``gmu`` (resp. ``gsigma``) is the geometric mean (resp. standard
deviation).

Parameters
----------
a : array_like
    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 geometric z scores computed for the non-nan values.

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

See Also
--------
gmean : Geometric mean
gstd : Geometric standard deviation
zscore : Standard score

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

.. versionadded:: 1.8

References
----------
.. [1] "Geometric standard score", *Wikipedia*,
       https://en.wikipedia.org/wiki/Geometric_standard_deviation#Geometric_standard_score.

Examples
--------
Draw samples from a log-normal distribution:

>>> import numpy as np
>>> from scipy.stats import zscore, gzscore
>>> import matplotlib.pyplot as plt

>>> rng = np.random.default_rng()
>>> mu, sigma = 3., 1.  # mean and standard deviation
>>> x = rng.lognormal(mu, sigma, size=500)

Display the histogram of the samples:

>>> fig, ax = plt.subplots()
>>> ax.hist(x, 50)
>>> plt.show()

Display the histogram of the samples standardized by the classical zscore.
Distribution is rescaled but its shape is unchanged.

>>> fig, ax = plt.subplots()
>>> ax.hist(zscore(x), 50)
>>> plt.show()

Demonstrate that the distribution of geometric zscores is rescaled and
quasinormal:

>>> fig, ax = plt.subplots()
>>> ax.hist(gzscore(x), 50)
>>> plt.show()

r   r"  )r8   r   r   r   MaskedArrayr   r[   )r   r   r  r   r   r   s         r   r\   r\   
  sK    p 
	Ba'Aq"..11"&&rvvC#a&t:FFr   c           	      d   XL n[        X5      n[        XUS9u  p[        R                  " 5          U(       a  [        R                  " S[
        5        [        XSUS9n[        XUSUS9S-  nSSS5        [        R                  " SSS9   [        U WX&S	S
9W-  n	SSS5        U(       ae  UR                  W	R                  5      R                  n
WUR                  U
W-  5      :*  nUR                  XR                   5      nUR"                  X'   W	$ ! , (       d  f       N= f! , (       d  f       N= f)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   r   T)r   r   r   )r   r  r   r   r.  Nr   r   F)r   rO  )r8   r   r   r  r  r-   r   r  r   r   r[  rT  r   rU  rV  broadcast_tor   r   )scorescomparer   r  r   like_zscorer   mnr  zrU  ru  s               r   rZ   rZ     s   l $K		)B+FCOF		 	 	"!!(,>?g4JOgT#
<=@A 
# 
Xh	7FBuEK 
8
 hhqww##bffS2X&&tWW-&&H' 
#	" 
8	7s   =D
D!
D!
D/c           	         [         R                  " U 5      n [        U [        R                  5      (       a-  Sn[
        R                  " U[        SS9  [        R                  nO[         R                  n[         R                  " SSS9   [         R                  " [         R                  " U" U 5      XS95      nSSS5        U S:*  R                  5       (       a  S	n[
        R                  " U[        SS9  W$ ! , (       d  f       ND= f)
aZ  
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 exponential of the standard deviation of the
natural logarithms of the observations.

Parameters
----------
a : array_like
    An array containing finite, strictly positive, real numbers.

    .. deprecated:: 1.14.0
        Support for masked array input was deprecated in
        SciPy 1.14.0 and will be removed in version 1.16.0.

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
-------
gstd : ndarray or float
    An array of the geometric standard deviation. If `axis` is None or `a`
    is a 1d array a float is returned.

See Also
--------
gmean : Geometric mean
numpy.std : Standard deviation
gzscore : Geometric standard score

Notes
-----
Mathematically, the sample geometric standard deviation :math:`s_G` can be
defined in terms of the natural logarithms of the observations
:math:`y_i = \log(x_i)`:

.. math::

    s_G = \exp(s), \quad s = \sqrt{\frac{1}{n - d} \sum_{i=1}^n (y_i - \bar y)^2}

where :math:`n` is the number of observations, :math:`d` is the adjustment `ddof`
to the degrees of freedom, and :math:`\bar y` denotes the mean of the natural
logarithms of the observations. Note that the default ``ddof=1`` is different from
the default value used by similar functions, such as `numpy.std` and `numpy.var`.

When an observation is infinite, the geometric standard deviation is
NaN (undefined). Non-positive observations will also produce NaNs in the
output because the *natural* logarithm (as opposed to the *complex*
logarithm) is defined and finite only for positive reals.
The geometric standard deviation is sometimes confused with the exponential
of the standard deviation, ``exp(std(a))``. Instead, the geometric standard
deviation is ``exp(std(log(a)))``.

References
----------
.. [1] "Geometric standard deviation", *Wikipedia*,
       https://en.wikipedia.org/wiki/Geometric_standard_deviation.
.. [2] Kirkwood, T. B., "Geometric means and measures of dispersion",
       Biometrics, vol. 35, pp. 908-909, 1979

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

>>> import numpy as np
>>> 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])

zk`gstd` support for masked array input was deprecated in SciPy 1.14.0 and will be removed in version 1.16.0.r   r   r   r&  r   r  Nr   zThe geometric standard deviation is only defined if all elements are greater than or equal to zero; otherwise, the result is NaN.)r   r  r   r   r$  r   r   DeprecationWarningr   r   r   r  r   r   )r   r   r  r   r   r$  s         r   r^   r^   T  s    ~ 	aA!R^^$$Ig1a@ffff	Xh	7ffRVVCF9: 
8 	
Q||~~Vg~!<J 
8	7s   0C66
Dnormalr.  ro  c                     U $ r   r   r   s    r   r   r     r  r   c                     U 4$ r   r   r   s    r   r   r     rj  r   r   )r   r   r	  r   r   c                 f   [        U 5      n U R                  (       d  [        U 5      $ [        U[        5      (       a1  UR                  5       nU[        ;  a  [        U S35      e[        U   n[        X5      u  pU(       a  US:X  a  [        R                  n	O[        R                  n	[        U5      S:w  a  [        S5      e[        R                  " U5      R                  5       (       a  [        S5      e[!        U5      nU	" XXUS9n
[        R"                  " U
S   U
S   5      nUS	:w  a  X-  nU$ )
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 or array_like of reals, optional
    The numerical value of scale will be divided out of the final
    result. The following string value is also recognized:

      * 'normal' : Scale by
        :math:`2 \sqrt{2} erf^{-1}(\frac{1}{2}) \approx 1.349`.

    The default is 1.0.
    Array-like `scale` of real dtype 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 : str, 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``.

    For NumPy >= 1.22.0, the additional options provided by the ``method``
    keyword of `numpy.percentile` are also valid.

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

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
--------
>>> import numpy as np
>>> 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 not a valid scale for `iqr`r  r   z+quantile range must be two element sequencezrange must not contain NaNs)r   methodr   r   r   r   )r   r   r   r   strr  _scale_conversionsr   r   r   nanpercentile
percentiler   r   r   r   sortedsubtract)r   r   rngscaler   interpolationr   	scale_keyr  percentile_funcpctouts               r   r]   r]     s   ^ 	
A 66{ %KKM	..w&BCDD"9-  -Q;L
f,**--
3x1}EFF	xx}677
+C
!t#+-C
++c!fc!f
%C|Jr   c                 :   [         R                  " U 5      nUR                  5       (       a  US:X  a  [         R                  $ X)    n U R                  S:X  a  [         R                  $ U" U 5      n[         R
                  " [         R                  " X-
  5      5      nU$ )Nr   r   )r   r   r   r   r   medianrV  )r   rB  r   r   medmads         r   _mad_1drF  b  sp     HHQKEyy{{$66MfIvv{vv
)C
))BFF17O
$CJr   c                   ^ [        U5      (       d  [        S[        U5       S35      e[        U[        5      (       a%  UR                  5       S:X  a  SnO[        U S35      e[        U 5      n U R                  (       dv  Tc  [        R                  $ [        U4S j[        U R                  5       5       5      nUS:X  a  [        R                  $ [        R                  " U[        R                  5      $ [        X5      u  pdU(       aC  Tc  [!        U R#                  5       X$5      nXs-  $ [        R$                  " [         TXU5      n Xs-  $ Tc7  U" U SS	9n[        R&                  " [        R(                  " X-
  5      5      nXs-  $ [        R*                  " U" U TS	9T5      n[        R&                  " [        R(                  " X-
  5      TS	9nXs-  $ )
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:

>>> import numpy as np
>>> 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.r0  gIRk?z is not a valid scale value.Nc              3   <   >#    U  H  u  pUT:w  d  M  Uv   M     g 7fr   r   ).0r   itemr   s      r   	<genexpr>'median_abs_deviation.<locals>.<genexpr>  s     N.@71AI$$.@s   	r   r   )callabler   reprr   r5  r  r   r   r   r   r   r   	enumerater   r  r   rF  r   apply_along_axisrC  rV  expand_dims)	r   r   rB  r<  r   	nan_shaper  rE  rD  s	    `       r   r_   r_   x  s   \ F !!%f.?A B 	B
 %;;=H$&Ew&BCDD
A 66<66MNi.@NN	?66Mwwy"&&)),Q;L<!'')V8C ; %%gtQ
KC ; <&C))BFF17O,C ; ..!5t<C))BFF17O$7C;r   SigmaclipResult)clippedr  upperc                 0   [         R                  " U 5      R                  5       nSnU(       a]  UR                  5       nUR	                  5       nUR
                  nXeU-  -
  nXeU-  -   n	X3U:  X9:*  -     nXsR
                  -
  nU(       a  M]  [        UWW	5      $ )aC  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
--------
>>> import numpy as np
>>> 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   )r   r   r   r  r  r   rS  )
r   lowhighcr  c_stdc_meanr   	critlower	crituppers
             r   r`   r`     s    n 	

1AE
vvS[(	T\)	I~!.12vv % 1i33r   c                 |   [         R                  " U 5      n U R                  S:X  a  U $ Uc  U R                  5       n SnU R                  U   n[        X-  5      nX4-
  nXE:  a  [        S5      e[         R                  " XUS-
  4U5      n[        S5      /UR                  -  n[        XE5      Xr'   U[        U5         $ )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
--------
Create an array of 10 values and trim 10% of those values from each end:

>>> import numpy as np
>>> from scipy import stats
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> stats.trimboth(a, 0.1)
array([1, 3, 2, 4, 5, 6, 7, 8])

Note that the elements of the input array are trimmed by value, but the
output array is not necessarily sorted.

The proportion to trim is rounded down to the nearest integer. For
instance, trimming 25% of the values from each end of an array of 10
values will return an array of 6 values:

>>> b = np.arange(10)
>>> stats.trimboth(b, 1/4).shape
(6,)

Multidimensional arrays can be trimmed along any axis or across the entire
array:

>>> c = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9]
>>> d = np.array([a, b, c])
>>> stats.trimboth(d, 0.4, axis=0).shape
(1, 10)
>>> stats.trimboth(d, 0.4, axis=1).shape
(3, 2)
>>> stats.trimboth(d, 0.4, axis=None).shape
(6,)

r   NProportion too big.r   )r   r   r   r   r   r   r   	partitionr  r   r   r   proportiontocutr   r  lowercutuppercutatmpsls           r   ra   ra   _  s    @ 	

1Avv{|GGI774=D?)*HH.//<<hl3T:D
+	"BX(BHb	?r   c                    [         R                  " U 5      n Uc  U R                  5       n SnU R                  U   nUS:  a  / $ UR	                  5       S:X  a  SnU[        X-  5      -
  nO#UR	                  5       S:X  a  [        X-  5      nUn[         R                  " U WWS-
  4U5      n[        S5      /UR                  -  n[        XV5      X'   U[        U5         $ )al  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
--------
Create an array of 10 values and trim 20% of its lowest values:

>>> import numpy as np
>>> from scipy import stats
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> stats.trim1(a, 0.2, 'left')
array([2, 4, 3, 5, 6, 7, 8, 9])

Note that the elements of the input array are trimmed by value, but the
output array is not necessarily sorted.

The proportion to trim is rounded down to the nearest integer. For
instance, trimming 25% of the values from an array of 10 values will
return an array of 8 values:

>>> b = np.arange(10)
>>> stats.trim1(b, 1/4).shape
(8,)

Multidimensional arrays can be trimmed along any axis or across the entire
array:

>>> c = [2, 4, 6, 8, 0, 1, 3, 5, 7, 9]
>>> d = np.array([a, b, c])
>>> stats.trim1(d, 0.8, axis=0).shape
(1, 10)
>>> stats.trim1(d, 0.8, axis=1).shape
(3, 2)
>>> stats.trim1(d, 0.8, axis=None).shape
(6,)

Nr   r   r  r  )
r   r   r   r   r  r   r`  r  r   r   )	r   rb  tailr   r  rc  rd  re  rf  s	            r   rb   rb     s    z 	

1A|GGI774=D !	zz|w#o455		-.<<Hhl3T:D
+	"BX(BHb	?r   c                    [         R                  " U 5      n U R                  S:X  a  [         R                  $ Uc  U R	                  5       n SnU R
                  U   n[        X-  5      nX4-
  nXE:  a  [        S5      e[         R                  " XUS-
  4U5      n[        S5      /UR                  -  n[        XE5      Xr'   [         R                  " U[        U5         US9$ )aQ  Return mean of array after trimming a specified fraction of extreme values

Removes the specified proportion of elements from *each* end of the
sorted array, then computes the mean of the remaining elements.

Parameters
----------
a : array_like
    Input array.
proportiontocut : float
    Fraction of the most positive and most negative elements to remove.
    When the specified proportion does not result in an integer number of
    elements, the number of elements to trim is rounded down.
axis : int or None, default: 0
    Axis along which the trimmed means are computed.
    If None, compute over the raveled array.

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

See Also
--------
trimboth : Remove a proportion of elements from each end of an array.
tmean : Compute the mean after trimming values outside specified limits.

Notes
-----
For 1-D array `a`, `trim_mean` is approximately equivalent to the following
calculation::

    import numpy as np
    a = np.sort(a)
    m = int(proportiontocut * len(a))
    np.mean(a[m: len(a) - m])

Examples
--------
>>> import numpy as np
>>> from scipy import stats
>>> x = [1, 2, 3, 5]
>>> stats.trim_mean(x, 0.25)
2.5

When the specified proportion does not result in an integer number of
elements, the number of elements to trim is rounded down.

>>> stats.trim_mean(x, 0.24999) == np.mean(x)
True

Use `axis` to specify the axis along which the calculation is performed.

>>> x2 = [[1, 2, 3, 5],
...       [10, 20, 30, 50]]
>>> stats.trim_mean(x2, 0.25)
array([ 5.5, 11. , 16.5, 27.5])
>>> stats.trim_mean(x2, 0.25, axis=1)
array([ 2.5, 25. ])

r   Nr_  r   r   )r   r   r   r   r   r   r   r   r`  r  r   r  r   ra  s           r   rc   rc     s    | 	

1Avv{vv|GGI774=D?)*HH.//<<hl3T:D
+	"BX(BH774b	?..r   F_onewayResultc                     [        U[        U 5      5      nU SU XS-   S -   n[        R                  " U[	        U6 S9nUR                  5       n[        US   US   5      $ )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   )
fill_valuer   )r6   r   r   r  r   r   rj  )r   r   r  shpfprobs         r   _create_f_oneway_nan_resultrp  c  sa      c%j1D
,Avw
'C
' 23A668D!B%b**r   c                 l    [         R                  " U [         R                  " SU R                  S9U5      $ )z>Return arr[..., 0:1, ...] where 0:1 is in the `axis` position.r   )ndmin)r   take_along_axisr   r   )r  r   s     r   _firstrt  p  s&    c288ASXX#>EEr   r   c                   ^ S[        U 5       S3n[        U 5      S:  a  [        U5      e[        U4S jU  5       5      (       a  g[        U4S jU  5       5      (       a!  Sn[        R
                  " [        U5      SS9  gg	)
Nz'At least two samples are required; got .r   c              3   F   >#    U  H  oR                   T   S :H  v   M     g7fr   Nr   rI  r  r   s     r   rK  )_f_oneway_is_too_small.<locals>.<genexpr>|       
9v<<"   !Tc              3   F   >#    U  H  oR                   T   S :H  v   M     g7f)r   Nry  rz  s     r   rK  r{    r|  r}  zeall input arrays have length 1.  f_oneway requires that at least one input has length greater than 1.r   F)r   r   r   r   r   r   r-   )r  kwargsr   r   r  s     `  r   _f_oneway_is_too_smallr  u  sv    7G~QGG
7|a   
9
999 
9
999<(-!<r   c           
          [        U5      S:  a  [        S[        U5       S35      e[        U5      n[        R                  " XS9nUR                  U    n[        U5      (       a  [        UR                  X5      $ [        R                  " U Vs/ s H  n[        XP5      U:H  R                  U SS9PM!     snU S9nUR                  U S9nUR                  5       (       a+  Sn[        R                  " [        R                  " U5      SS9  [        X05      U:H  R                  U S9n	UR                  U SS9n
X:-
  n[        X0S9U-  n[!        X0S9U-
  nS	nU H#  n[        XZ-
  U S9nXUR                  U    -  -   nM%     X-
  nX-
  nUS
-
  nXB-
  nUU-  nUU-  n[        R"                  " SSS9   UU-  nSSS5        [$        R&                  " UUW5      n[        R(                  " U5      (       aB  U	(       a!  [        R*                  n[        R*                  nOXU(       a  [        R,                  nSnO>[        R,                  UU'   SUU'   [        R*                  UU	'   [        R*                  UU	'   [/        UU5      $ s  snf ! , (       d  f       N= f)a  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
-----
`~scipy.stats.ConstantInputWarning`
    Emitted if all values within each of the input arrays are identical.
    In this case the F statistic is either infinite or isn't defined,
    so ``np.inf`` or ``np.nan`` is returned.

RuntimeWarning
    Emitted 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 all values in each group are identical, 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
--------
>>> import numpy as np
>>> 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 = f_oneway(a, b, c)
>>> F.statistic
array([1.75676344, 0.03701228, 3.76439349])
>>> F.pvalue
array([0.20630784, 0.96375203, 0.04733157])

r   z&at least two inputs are required; got rv  r   TrD  zPEach of the input arrays is constant; the F statistic is not defined or infiniter   r   r   r   r   Nr  )r   r   r   concatenater   r  rp  rt  r   r   r   r   r4   ConstantInputWarningr  _square_of_sums_sum_of_squaresr   specialfdtrcr  r   r!  rj  )r   r  
num_groupsalldatabignr  is_const	all_constr  all_same_constoffsetnormalized_sssstotssbnsmo_sssswndfbndfwnmsbmswrn  ro  s                         r   rd   rd     s}   F 7|a   #G~Q0 1 	1 WJ nnW0G==D g&&*7==$HH ~~ 	 V 
&
(	-	-47; 
. 
=	  	H $'I}}<e005!D W+w6;;;FN \\td\3FG#G7$>MG/-?ED t<v||D111  D<D>DD
+C
+C	Hh	7#I 
8 ==tQ'D 
{{1~~A66DADvv)YFF.!vv^!T""	 V 
8	7s   &I:-I??
Jc                   *    \ rS rSr% \\S'   \\S'   Srg)AlexanderGovernResultij  r   r   r   N)__name__
__module____qualname____firstlineno__r   __annotations____static_attributes__r   r   r   r  r  j  s    Mr   r  c                 2    U R                   U R                  4$ r   r  r   s    r   r   r   r  s    q{{AHH5r   )r   r   r   )r   r   c           
      "   [        X U5      nU Vs/ s H  o3R                  S   PM     nn[        R                  " U Vs/ s H  n[	        USS9PM     sn5      n[        X$5       VVs/ s H  u  p6[        USSS9U-  PM     nnn[        R                  " U5      nUS-  n	[        R                  " U	R                  5      R                  n
U	[        R                  " X-  5      :*  n[        R                  " [        R                  U	R                  S9n[        R                  " XU	5      n	SU-  nU[        R                  " USSS	9-  n[        R                  " X-  SSS	9n[        X_S[        S
9U	-  n[        R                  " U5      S-
  n[        R                  " USSUR                   S-
  -  -   5      nUS-
  nSUS-  -  nU[        R"                  " SUS-  U-  -   5      -  S-  nUUS-  SU-  -   U-  -   SUS-  -  SUS-  -  -   SUS-  -  -   SU-  -   US-  S-  SU-  US-  -  -   SU-  -   -  -
  n[        R                  " US-  SS9n[%        U5      S-
  n['        U5      n[)        UUSS[        S9n[+        UU5      $ s  snf s  snf s  snnf )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, and each sample must contain at least two observations.
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
-------
res : AlexanderGovernResult
    An object with attributes:

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

Warns
-----
`~scipy.stats.ConstantInputWarning`
    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 significance 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.

r   r   r   )r  r   r.  r   r   TrD  r   r   r   r   0   r   rl  r{  r  !   rS     iW  rQ  r  i  r  Fr  )!_alexandergovern_input_validationr   r   r   r   zipr  rT  r   rU  rV  r   r   r  r[  r   r   r   r   r  r  r  )r   r   r  r  lengthsmeanslengthse2standard_errors_squaredstandard_errorsrU  ru  r   	inv_sq_ser   var_wt_statsr  r   r   rY  r,  r  dfr  r   s                             r   r   r   p  s   z 0TJG /66gF||BgG6JJHfb1HIE "%W!68!6~v Fqr2V;!6  8 jjo-s2O ((?((
)
-
-CbffS[11D
**RVV?#8#8
9Chht/:O ++I"&&TBBG FF7?T:E er2_DG 	

7aA


1edGLLN334A	BA
QT	A	
RVVAAq(()	)B.A 
q!tacz1n	QT6Bq!tGc!Q$h&Q.a47QqSAXQ&(
)A
 	q!t!A 
W	Br?DAteKA A&&] 7H8s   JJ(Jc                     [        U 5      S:  a  [        S[        U 5       35      eU  H!  nUR                  U   S::  d  M  [        S5      e   U  Vs/ s H  n[        R
                  " X2S5      PM     n nU $ s  snf )Nr   z2 or more inputs required, got r   z+Input sample size must be greater than one.r   )r   r   r   r   r   moveaxis)r  r   r   r  s       r   r  r    sy    
7|a9#g,HII<<"JKK  <CC7r{{6,7GCN Ds   !A7c                 F   [        U 5      n[        R                  " SS9   UR                  U 5      nSSS5        UR	                  U 5      nUR                  XR                  S9nUR                  X R                  S9nUS:  a  UR                  SUS-
  -  5      nUS:X  aM  [        R                  " SUS	-  -   5      nWX-  -
  n	XXU-  -   n
UR                  U	5      nUR                  U
5      nOmUS
:X  a2  [        R                  " U5      nWX-  -   n
UR                  U
5      nU* nO5[        R                  " U5      nWX-  -
  n	UR                  U	5      nUnOU* UpUR                  S:X  a  US   OUnUR                  S:X  a  US   OUn[        XS9$ ! , (       d  f       GNf= f)z
Compute the confidence interval for Pearson's R.

Fisher's transformation is used to compute the confidence interval
(https://en.wikipedia.org/wiki/Fisher_transformation).
r   r   Nr   rl  r   r  r.  r   r  r   r   rW  rX  )r8   r   r   atanh	ones_liker   r   r  r  ndtritanhr   ConfidenceInterval)rr  confidence_levelr  r   zrr`  ser  zlozhirlorhis                r   _pearsonr_fisher_cir    s~    
	B	H	%XXa[ 
& <<?D


1GG
$Azz"2''zB1uWWQ!a%[!+%c$4Q$667Aqt)Ct)C''#,C''#,CF"./Aqt)C''#,C%C ./Aqt)C''#,CC5$SXX]#b'CXX]#b'C#00= 
&	%s   F
F c                     S n[        X#4U4XSUS.UR                  5       D6n[        R                  " UR                  SS5      Ul        [        UR                  6 $ )zF
Compute the confidence interval for Pearson's R using the bootstrap.
c                     [        XUS9u  p4U$ Nr   re   )r   r  r   r   r  s        r   r   )_pearsonr_bootstrap_ci.<locals>.statisticA  s    40	r   T)r  r   r   r  r   r   )r'   _asdictr   clipconfidence_intervalr  )r  r4  r   r  r  r   r   r$  s           r   _pearsonr_bootstrap_cir  =  sf     QFI N8H[N<BNN<LNC !ggc&=&=r1ECs6677r   r  rW  rX  PearsonRResultBasec                   6   ^  \ rS rSrSrU 4S jrSS jrSrU =r$ )PearsonRResultiS  a`  
Result of `scipy.stats.pearsonr`

Attributes
----------
statistic : float
    Pearson product-moment correlation coefficient.
pvalue : float
    The p-value associated with the chosen alternative.

Methods
-------
confidence_interval
    Computes the confidence interval of the correlation
    coefficient `statistic` for the given confidence level.

c                 l   > [         TU ]  X5        X0l        X@l        XPl        X`l        Xpl        Xl        g r   )super__init___alternative_n_x_y_axiscorrelation)	selfr   r   r  r  r   r  r   	__class__s	           r   r  PearsonRResult.__init__e  s2    +'
 %r   c                 ~   [        U[        5      (       ak  [        U R                  5      nSn[	        U5      (       d  [        U5      e[        XU R                  U R                  U R                  U R                  5      nU$ Uc.  [        U R                  U R                  UU R                  5      nU$ Sn[        U5      e)a;  
The confidence interval for the correlation coefficient.

Compute the confidence interval for the correlation coefficient
``statistic`` with the given confidence level.

If `method` is not provided,
The confidence interval is computed using the Fisher transformation
F(r) = arctanh(r) [1]_.  When the sample pairs are drawn from a
bivariate normal distribution, F(r) approximately follows a normal
distribution with standard error ``1/sqrt(n - 3)``, where ``n`` is the
length of the original samples along the calculation axis. When
``n <= 3``, this approximation does not yield a finite, real standard
error, so we define the confidence interval to be -1 to 1.

If `method` is an instance of `BootstrapMethod`, the confidence
interval is computed using `scipy.stats.bootstrap` with the provided
configuration options and other appropriate settings. In some cases,
confidence limits may be NaN due to a degenerate resample, and this is
typical for very small samples (~6 observations).

Parameters
----------
confidence_level : float
    The confidence level for the calculation of the correlation
    coefficient confidence interval. Default is 0.95.

method : BootstrapMethod, optional
    Defines the method used to compute the confidence interval. See
    method description for details.

    .. versionadded:: 1.11.0

Returns
-------
ci : namedtuple
    The confidence interval is returned in a ``namedtuple`` with
    fields `low` and `high`.

References
----------
.. [1] "Pearson correlation coefficient", Wikipedia,
       https://en.wikipedia.org/wiki/Pearson_correlation_coefficient
zF`method` must be `None` if `pearsonr` arguments were not NumPy arrays.z:`method` must be an instance of `BootstrapMethod` or None.)r   r$   r8   r  r9   r   r  r  r  r  r  r   r  )r  r  r4  r   r   cis         r   r  "PearsonRResult.confidence_intervalp  s    Z fo.. )B:GB<< ))'(8$''477(,(9(94::GB 	 ^$T^^TWW>N%)%6%68B 	"GW%%r   )r  r  r  r  r  r  )ffffff?N	r  r  r  r  __doc__r  r  r  __classcell__r  s   @r   r  r  S  s    "	%= =r   r  )r  r4  r   c          
      L  ^ ^ [        T U5      nUR                  T 5      m UR                  U5      n[        U5      (       d  Ub  SnUc&  UR                  T S5      m UR                  US5      nSn[	        U5      nXd:w  a  [        S5      eUnT R                  U   nXqR                  U   :w  a  [        S5      eUS:  a  [        S5      e UR                  T U5      u  m n[        T XES
9m [        XUS
9nSnUR                  T R                  UR                  5      n
UR                  U
S5      (       a  UR                  S5      R                  n
UR                  U
S5      (       a  [        S5      eUR                  T U
SS9m UR                  XSS9nUR                  U
5      R                  S-  nUR!                  T T SSS24   :H  SS9nUR!                  XSSS24   :H  SS9nX-  nUR#                  U5      (       a+  Sn[$        R&                  " [(        R*                  " U5      SS9  [-        U[.        5      (       aI  UU 4S jn[1        U4U4SUTS.UR3                  5       D6n[5        UR6                  UR8                  UTT XS9$ [-        U[:        5      (       a  U4S jnUR3                  5       nUR=                  SS5      =nb:  [>        R@                  RC                  U5      nURD                  URD                  4US'   [G        T U44UUTS.UD6n[5        UR6                  UR8                  UTT XS9$ US:X  a  S n	[        U	5      eUb  S!n	[        U	5      eURI                  T US"S#9nURI                  XS"S#9nT U-
  nUU-
  nURK                  URM                  U5      US"S#9nURK                  URM                  U5      US"S#9n[>        RN                  " S$S$S%9   U[Q        UU-  US"S#9-  nU[Q        UU-  US"S#9-  nSSS5        UR#                  WXRM                  U5      -  :  US9nUR#                  WXRM                  U5      -  :  US9nUU-  nUR#                  UU) -  5      (       a+  S&n[$        R&                  " [(        RR                  " U5      SS9  [>        RN                  " S$S$S%9   URU                  UU-  U-  U-  US9nSSS5        UR                  SU
S'9nUR                  URW                  WU* U5      5      nURX                  UU'   US:X  a`  UR[                  U5      nUR                  SU
S'9nUR]                  UR                  UR_                  U5      5      URX                  U-  U5      n O/UR                  US-  S-
  5      n![a        U!U!SSS(9n"[c        UU"TUS
9n URd                  S:X  a  US)   OUnU Rd                  S:X  a  U S)   OU n [5        UU UTT XS9$ ! [
        [        4 a  nS	n	[        U	5      UeSnAff = f! , (       d  f       GN= f! , (       d  f       GNZ= f)*a(  
Pearson correlation coefficient and p-value for testing non-correlation.

The Pearson correlation coefficient [1]_ measures the linear relationship
between two datasets. 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.

This function also performs a test of the null hypothesis that the
distributions underlying the samples are uncorrelated and normally
distributed. (See Kowalski [3]_
for a discussion of the effects of non-normality of the input on the
distribution of the correlation coefficient.)
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 : array_like
    Input array.
y : array_like
    Input array.
axis : int or None, default
    Axis along which to perform the calculation. Default is 0.
    If None, ravel both arrays before performing the calculation.

    .. versionadded:: 1.13.0
alternative : {'two-sided', 'greater', 'less'}, 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.9.0
method : ResamplingMethod, optional
    Defines the method used to compute the p-value. If `method` is an
    instance of `PermutationMethod`/`MonteCarloMethod`, the p-value is
    computed using
    `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the
    provided configuration options and other appropriate settings.
    Otherwise, the p-value is computed as documented in the notes.

    .. versionadded:: 1.11.0

Returns
-------
result : `~scipy.stats._result_classes.PearsonRResult`
    An object with the following attributes:

    statistic : float
        Pearson product-moment correlation coefficient.
    pvalue : float
        The p-value associated with the chosen alternative.

    The object has the following method:

    confidence_interval(confidence_level, method)
        This computes the confidence interval of the correlation
        coefficient `statistic` for the given confidence level.
        The confidence interval is returned in a ``namedtuple`` with
        fields `low` and `high`. If `method` is not provided, the
        confidence interval is computed using the Fisher transformation
        [1]_. If `method` is an instance of `BootstrapMethod`, the
        confidence interval is computed using `scipy.stats.bootstrap` with
        the provided configuration options and other appropriate settings.
        In some cases, confidence limits may be NaN due to a degenerate
        resample, and this is typical for very small samples (~6
        observations).

Raises
------
ValueError
    If `x` and `y` do not have length at least 2.

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

`~scipy.stats.NearConstantInputWarning`
    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 x and :math:`m_y` is
the mean of the vector y.

Under the assumption that x and y are drawn from
independent normal distributions (so the population correlation coefficient
is 0), the probability density function of the sample correlation
coefficient 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 when
the `method` parameter is left at its default value (None).
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 default 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.

For backwards compatibility, the object that is returned also behaves
like a tuple of length two that holds the statistic and the p-value.

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
--------
>>> import numpy as np
>>> from scipy import stats
>>> x, y = [1, 2, 3, 4, 5, 6, 7], [10, 9, 2.5, 6, 4, 3, 2]
>>> res = stats.pearsonr(x, y)
>>> res
PearsonRResult(statistic=-0.828503883588428, pvalue=0.021280260007523286)

To perform an exact permutation version of the test:

>>> rng = np.random.default_rng(7796654889291491997)
>>> method = stats.PermutationMethod(n_resamples=np.inf, random_state=rng)
>>> stats.pearsonr(x, y, method=method)
PearsonRResult(statistic=-0.828503883588428, pvalue=0.028174603174603175)

To perform the test under the null hypothesis that the data were drawn from
*uniform* distributions:

>>> method = stats.MonteCarloMethod(rvs=(rng.uniform, rng.uniform))
>>> stats.pearsonr(x, y, method=method)
PearsonRResult(statistic=-0.828503883588428, pvalue=0.0188)

To produce an asymptotic 90% confidence interval:

>>> res.confidence_interval(confidence_level=0.9)
ConfidenceInterval(low=-0.9644331982722841, high=-0.3460237473272273)

And for a bootstrap confidence interval:

>>> method = stats.BootstrapMethod(method='BCa', rng=rng)
>>> res.confidence_interval(confidence_level=0.9, method=method)
ConfidenceInterval(low=-0.9983163756488651, high=-0.22771001702132443)  # may vary

If N-dimensional arrays are provided, multiple tests are performed in a
single call according to the same conventions as most `scipy.stats` functions:

>>> rng = np.random.default_rng(2348246935601934321)
>>> x = rng.standard_normal((8, 15))
>>> y = rng.standard_normal((8, 15))
>>> stats.pearsonr(x, y, axis=0).statistic.shape  # between corresponding columns
(15,)
>>> stats.pearsonr(x, y, axis=1).statistic.shape  # between corresponding rows
(8,)

To perform all pairwise comparisons between slices of the arrays,
use standard NumPy broadcasting techniques. For instance, to compute the
correlation between all pairs of rows:

>>> stats.pearsonr(x[:, np.newaxis, :], y, axis=-1).statistic.shape
(8, 8)

There is a linear dependence between x and y if y = a + b*x + e, where
a,b are constants and e is a random error term, assumed to be independent
of x. For simplicity, assume that x is standard normal, a=0, b=1 and let
e follow a normal distribution with mean zero and standard deviation s>0.

>>> rng = np.random.default_rng()
>>> s = 0.5
>>> x = stats.norm.rvs(size=500, random_state=rng)
>>> e = stats.norm.rvs(scale=s, size=500, random_state=rng)
>>> y = x + e
>>> stats.pearsonr(x, y).statistic
0.9001942438244763

This should be close to the exact value given by

>>> 1/np.sqrt(1 + s**2)
0.8944271909999159

For s=0.5, we observe a high level of correlation. In general, a large
variance of the noise reduces the correlation, while the correlation
approaches one as the variance of the error goes to zero.

It is important to keep in mind that no correlation does not imply
independence unless (x, y) is jointly normal. Correlation can even be zero
when there is a very simple dependence structure: if X follows a
standard normal distribution, let y = abs(x). Note that the correlation
between x and y is zero. Indeed, since the expectation of x is zero,
cov(x, y) = E[x*y]. By definition, this equals E[x*abs(x)] which is zero
by symmetry. The following lines of code illustrate this observation:

>>> y = np.abs(x)
>>> stats.pearsonr(x, y)
PearsonRResult(statistic=-0.05444919272687482, pvalue=0.22422294836207743)

A non-zero correlation coefficient can be misleading. For example, if X has
a standard normal distribution, define y = x if x < 0 and y = 0 otherwise.
A simple calculation shows that corr(x, y) = sqrt(2/Pi) = 0.797...,
implying a high level of correlation:

>>> y = np.where(x < 0, x, 0)
>>> stats.pearsonr(x, y)
PearsonRResult(statistic=0.861985781588, pvalue=4.813432002751103e-149)

This is unintuitive since there is no dependence of x and y if x is larger
than zero which happens in about half of the cases if we sample x and y.

Nr   r   r   `axis` must be an integer.z3`x` and `y` must have the same length along `axis`.r   z(`x` and `y` must have length at least 2.z"`x` and `y` must be broadcastable.r   r   r   complex floatingz+This function does not support complex dataFr   g      ?.r   r   r   GAn input array is constant; the correlation coefficient is not defined.r   c                 "   > [        TXTS9u  p#U$ N)r   r  r  )r  r   r   r  r  r   s       r   r   pearsonr.<locals>.statistic  s    #AqMLIr   pairings)permutation_typer   r  )r   r   r  r  r   r  r   c                 "   > [        XUTS9u  p4U$ r  r  )r   r  r   r   r  r  s        r   r   r    s    #AtMLIr   r;  rvsr   r   r  z:`method` must be `None` if arguments are not NumPy arrays.zP`method` must be an instance of `PermutationMethod`,`MonteCarloMethod`, or None.TrD  r   r&  zZAn input array is nearly constant; the computed correlation coefficient may be inaccurate.r   locr<  r   )3r8   r   r9   r   r   r   r   broadcast_arraysRuntimeErrorr;   r   r   r   r   rT  rU  r   r   r   r   r4   r  r   r#   r&   r  r  r   r   r"   popr   randomdefault_rngr0  r%   r  r   rV  r   r=   NearConstantInputWarningr  r  r   rF  r   r   _SimpleBetar  r   )#r   r  r  r4  r   r   axis_intr  r  r   r   	thresholdconst_xconst_yconst_xyr  r   r$  r;  xmeanymeanxmymxmaxymaxnormxmnormymnconst_xnconst_y	nconst_xyr  oner   abdists#   ` `                                r   re   re     s   D 
A	B


1A


1AB<<F.|JJq% JJq% 4yH566D	AGGDMNOO1uCDD)""1a(1 	1d*A1r*ADNN177AGG,E	zz%$$

2$$	zz%+,,FGG
		!U	'A
		!	'A##t+I ffQ!C1H+%Bf/GffQC1H+%Bf/G H	vvh!e005!D&+,,	 tY W$(kWEK^^EUW cjjA*5aL 	L	F,	-	-	 !::eT**C7))'',CJJ

2F5M1w B)$+6B:@B cjjA*5aL 	L	9	N!!		2!!GGAD4G0EGGA4G0E	
UB	
UB 66"&&*4$67D66"&&*4$67D	Xh	7r$wTDIIr$wTDII 
8 vvfy66TvBHvvfy66TvBH8#I	vviH9%&&<e44S9aH	Xh	7FF2f9r>&(tF4 
8
 **Qe*
$C


2771sdC()A&&AhK 	AvHHQKjj%j("**RXXa[1266#:sC ZZ!a 2rr3Qkb91"!A!;;!+VBZFAf&1Q!H Hi % )6!q()Z 
8	7 
8	7s0   
W #X'XW?,W::W?
X
X#)r4  c                ~  ^^^^^ [         R                  m[        R                  " U [        R                  S9nUR
                  S:X  d  [        S5      e[        R                  " US:  5      (       a  [        S5      eUR                  S:X  a  Ub  [        X1U5      $ Uc  SOUnSUR                  SS9;   d  SUR                  S	S9;   a  [        [        R                  S
5      $ US   S:  a!  US   S:  a  US   US   -  US   US   -  -  nO[        R                  nUS   US   -   mUS   US   -   mUS   US   -   mUUUU4S jmUS:X  a  TR                  US   TT-   TT5      nGOUS:X  a%  TR                  US   TT-   TUS   US   -   5      nGOUS:X  Ga  [        TS	-   TS	-   -  TT-   S-   -  5      nTR!                  US   TT-   TT5      nTR!                  UTT-   TT5      nSn	S	U	-   n
[        R"                  " Xx-
  5      [        R$                  " Xx5      -  U	::  a  [        US
5      $ US   U:  as  TR                  US   TT-   TT5      nTR!                  TTT-   TT5      Xz-  :  a  [        XK5      $ ['        U4S jU* U
-  UT5      nUTR)                  UTT-   TT5      -   nO}TR)                  US   S	-
  TT-   TT5      nTR!                  STT-   TT5      Xz-  :  a  [        XM5      $ ['        TXz-  SU5      nUTR                  UTT-   TT5      -   nOSn[        U5      e[+        US
5      n[        XE5      $ )a$!  Perform a Fisher exact test on a contingency table.

For a 2x2 table,
the null hypothesis is that the true odds ratio of the populations
underlying the observations is one, and the observations were sampled
from these populations under a condition: the marginals of the
resulting table must equal those of the observed table.
The statistic is the unconditional maximum likelihood estimate of the odds
ratio, and the p-value is the probability under the null hypothesis of
obtaining a table at least as extreme as the one that was actually
observed.

For other table sizes, or if `method` is provided, the null hypothesis
is that the rows and columns of the tables have fixed sums and are
independent; i.e., the table was sampled from a `scipy.stats.random_table`
distribution with the observed marginals. The statistic is the
probability mass of this distribution evaluated at `table`, and the
p-value is the percentage of the population of tables with statistic at
least as extreme (small) as that of `table`. There is only one alternative
hypothesis available: the rows and columns are not independent.

There are other possible choices of statistic and two-sided
p-value definition associated with Fisher's exact test; please see the
Notes for more information.

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

    * 'two-sided': the odds ratio of the underlying population is not one
    * 'less': the odds ratio of the underlying population is less than one
    * 'greater': the odds ratio of the underlying population is greater
      than one

    See the Notes for more details.

method : ResamplingMethod, optional
    Defines the method used to compute the p-value.
    If `method` is an instance of `PermutationMethod`/`MonteCarloMethod`,
    the p-value is computed using
    `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the
    provided configuration options and other appropriate settings.
    Note that if `method` is an instance of `MonteCarloMethod`, the ``rvs``
    attribute must be left unspecified; Monte Carlo samples are always drawn
    using the ``rvs`` method of `scipy.stats.random_table`.
    Otherwise, the p-value is computed as documented in the notes.

    .. versionadded:: 1.15.0

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

    statistic : float
        For a 2x2 table with default `method`, this is the odds ratio - the
        prior odds ratio not a posterior estimate. In all other cases, this
        is the probability density of obtaining the observed table under the
        null hypothesis of independence with marginals fixed.
    pvalue : float
        The probability under the null hypothesis of obtaining a
        table at least as extreme as the one that was actually observed.

Raises
------
ValueError
    If `table` is not two-dimensional or has negative entries.

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.
contingency.odds_ratio : Compute the odds ratio (sample or conditional
    MLE) for a 2x2 contingency table.
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.
:ref:`hypothesis_fisher_exact` : Extended example

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

The null hypothesis is that the true odds ratio of the populations
underlying the observations is one, and the observations were sampled at
random from these populations under a condition: the marginals of the
resulting table must equal those of the observed table. Equivalently,
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::

    >>> import numpy as np
    >>> 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
    >>> res = fisher_exact(table, alternative='two-sided')
    >>> res.pvalue
    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``::

    >>> res = fisher_exact(table, alternative='greater')
    >>> res.pvalue
    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``::

    >>> res = fisher_exact(table, alternative='less')
    >>> res.pvalue
    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 value computed by the
R function ``fisher.test``.  This implementation returns the "sample"
or "unconditional" maximum likelihood estimate, while ``fisher.test``
in R uses the conditional maximum likelihood estimate.  To compute the
conditional maximum likelihood estimate of the odds ratio, use
`scipy.stats.contingency.odds_ratio`.

References
----------
.. [1] Fisher, Sir Ronald A, "The Design of Experiments:
       Mathematics of a Lady Tasting Tea." ISBN 978-0-486-41151-4, 1935.
.. [2] "Fisher's exact test",
       https://en.wikipedia.org/wiki/Fisher's_exact_test

Examples
--------

>>> from scipy.stats import fisher_exact
>>> res = fisher_exact([[8, 2], [1, 5]])
>>> res.statistic
20.0
>>> res.pvalue
0.034965034965034975

For tables with shape other than ``(2, 2)``, provide an instance of
`scipy.stats.MonteCarloMethod` or `scipy.stats.PermutationMethod` for the
`method` parameter:

>>> import numpy as np
>>> from scipy.stats import MonteCarloMethod
>>> rng = np.random.default_rng(4507195762371367)
>>> method = MonteCarloMethod(rng=rng)
>>> fisher_exact([[8, 2, 3], [1, 5, 4]], method=method)
SignificanceResult(statistic=np.float64(0.005782), pvalue=np.float64(0.0603))

For a more detailed example, see :ref:`hypothesis_fisher_exact`.
r   r   z+The input `table` must have two dimensions.r   z*All values in `table` must be nonnegative.r   r   r  r   r   r   r   r   r  )r   r   )r   r   c                 2   > TR                  U TT-   TT5      $ r   )pmf)r   	hypergeomr  n1n2s    r   r  fisher_exact.<locals>.pmf9  s    }}QRQ//r   r  r  g+=c                    > T" U 5      * $ r   r   )r   r  s    r   r   fisher_exact.<locals>.<lambda>Q  s    c!fWr   z?`alternative` should be one of {'two-sided', 'less', 'greater'})r   r  r   r   int64r   r   r   r   _fisher_exact_rxcr  r   r   r!  r  r   r  rV  maximum_binary_searchr  r"  )tabler  r4  rY  	oddsratior   rE   pexactpmodeepsilongammaplowerguesspupperr  r  r  r  r  r  s                  @@@@@r   rf   rf   D  sN   t ''I


5)A66Q;FGG	vva!e}}EFF77f 2 88!,!4++KAEEqEMQ!%%Q%-/ ""&&#..w{qw{dGag%41T7):;	FF		
41T7	B	
41T7	B	$!D'A0 0 fqwRQ7			!qwRQtWqw5FG		#AEb1f%b156qwRQ7dBGR3G66&.!BJJv$==H%i44tWt^]]1T7BGR;F}}QRQ/&.@))<<"#4vgotQOEill5"r'2qAAF\\!D'A+rBwA>F}}QRQ/&.@))<<"34@EimmE27BBBFOoFi00r   c                 d   Ub  Sn[        U5      eU R                  S:X  a  [        S5      eU R                  S   S:X  d1  U R                  S   S:X  d  [        R                  " U S:H  5      (       a  [        SS5      $ Uc  [        R                  " 5       n[        U[        R                  5      (       a  [        X5      nO=[        U[        R                  5      (       a  [        X5      nOSU< S3n[        U5      e[        [        R                  " UR                  S S5      UR                  5      $ )Nz``alternative` must be the default (None) unless `table` has shape `(2, 2)` and `method is None`.r   z2`table` must have at least one row and one column.r   r   z`method=zi` not recognized; if provided, `method` must be an instance of `PermutationMethod` or `MonteCarloMethod`.)r   r   r   r   r   r   r4   r"   r   r#    _fisher_exact_permutation_method _fisher_exact_monte_carlo_methodr  r   r   )r  r  r4  r   r$  s        r   r  r  c  s    E!!zzQMNN{{1~ekk!n1RVVEQJ5G5G!#s++~'')&%1122.u=	FE22	3	3.u=vi  L L!!bggcmmT3?LLr   c                   ^^ [        U 5      u  nm[        R                  " U SS9n[        R                  " U SS9n[        R                  " XC5      mUU4S jn[        R
                  " U4U4SSS.UR                  5       D6$ )Nr   r   r   c                 l   > [         R                  R                  U T5      S   nTR                  U5      $ r?  )r4   contingencycrosstabr  )r   r  Xr  s     r   r   3_fisher_exact_permutation_method.<locals>.statistic  s.    !!**1a03uuU|r   r  r  )r  r  )_untabulater   r  r4   random_tabler&   r  )r  r4  r   colsumsrowsumsr   r,  r  s         @@r   r&  r&    s~    uDAqffU#GffU#G7,A !!1$	 JJ.4J8>8HJ Jr   c                   ^^	^
 UR                  5       nUR                  SS 5      b  Sn[        U5      e[        R                  R                  UR                  SS 5      5      nU R                  m	[        R                  " U SS9n[        R                  " U SS9n[        R                  " U 5      m
[        R                  " XTUS9mU4S jnUU	U
4S	 jn[        R                  " U R                  5       Xg4S
S0UD6$ )Nr  zIf the `method` argument of `fisher_exact` is an instance of `MonteCarloMethod`, its `rvs` attribute must be unspecified. Use the `MonteCarloMethod` `rng` argument to control the random state.r;  r   r   r   )seedc                 J   > U S   nTR                  US9R                  U 5      $ )Nr   )r   )r  r   )r   n_resamplesr,  s     r   r  -_fisher_exact_monte_carlo_method.<locals>.rvs  s(    1guu+u&..t44r   c                 r   > U R                   T:  a  ST-   OTnTR                  U R                  U5      5      $ )Nr   )r   r  r   )r  r   shape_r,  r   totsums      r   r   3_fisher_exact_monte_carlo_method.<locals>.statistic  s1    "'**v"55uuU]]6*++r   r  r  )r  r  r   r   r  r  r   r  r4   r/  r%   r   )r  r4  r   r;  r0  r1  r  r   r,  r   r9  s           @@@r   r'  r'    s    ^^Fzz%*2 !!
))



5$ 7
8C KKEffU#GffU#GVVE]F7#6A5,
 !!%++- @.4@8>@ @r   c                 (   U R                   u  p/ / pC[        U5       HG  n[        U5       H5  nUR                  U/XU4   -  5        UR                  U/XU4   -  5        M7     MI     [        R                  " U5      [        R                  " U5      4$ r   )r   rG  rH  r   r  )r  r  rY  r   r  r   r  s          r   r.  r.    s     ;;DArq1XqAHHaS5A;&'HHaS5A;&'   >>!bnnQ///r   c                    Ub  US:  a  [        SU S35      e[        X5      u  pU R                  S:  a  [        S5      eUc  U R                  S:  a  [        S5      eOB[        X5      u  pUS:X  a  [        R                  " X45      n O[        R
                  " X45      n U R                  SU-
     nU R                  U   nUS::  a?  [        [        R                  [        R                  5      n	[        R                  U	l	        U	$ S	n
US:X  a  U SS2S4   S   U SS2S4   :H  R                  5       (       d)  U SS2S4   S   U SS2S4   :H  R                  5       (       ah  [        R                  " [        R                  " U
5      SS
9  [        [        R                  [        R                  5      n	[        R                  U	l	        U	$ OU SSS24   S   U SSS24   :H  R                  5       (       d)  U SSS24   S   U SSS24   :H  R                  5       (       ah  [        R                  " [        R                  " U
5      SS
9  [        [        R                  [        R                  5      n	[        R                  U	l	        U	$ [        X5      u  p[        R                   " U["        S9nU(       a  US:X  a  [$        R&                  " XUUS9$ US:X  ax  U R                  S:X  d  US::  a?  [        [        R                  [        R                  5      n	[        R                  U	l	        U	$ [        R(                  " U 5      R+                  US9n[        R,                  " [.        XP5      n[        R0                  " XS9nUS-
  n[        R2                  " SS9   U[        R4                  " XS-   SU-
  -  -  R7                  S5      5      -  nSSS5        [9        U5      n[;        WUU[        S9nUR                  S:X  a  [        US   US   5      n	US   U	l	        U	$ [        R                  XSS24'   [        R                  USS2U4'   [        US   US   5      n	Xl	        U	$ ! , (       d  f       N= f)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.
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. Although calculation of the
p-value does not make strong assumptions about the distributions underlying
the samples, it is only accurate for very large samples (>500
observations). For smaller sample sizes, consider a permutation test (see
Examples section below).

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
-------
res : SignificanceResult
    An object containing attributes:

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

Raises
------
ValueError
    If `axis` is not 0, 1 or None, or if the number of dimensions of `a`
    is greater than 2, or if `b` is None and the number of dimensions of
    `a` is less than 2.

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

See Also
--------
:ref:`hypothesis_spearmanr` : Extended example

References
----------
.. [1] Zwillinger, D. and Kokoska, S. (2000). CRC Standard
   Probability and Statistics Tables and Formulae. Chapman & Hall: New
   York. 2000.
   Section  14.7
.. [2] Kendall, M. G. and Stuart, A. (1973).
   The Advanced Theory of Statistics, Volume 2: Inference and Relationship.
   Griffin. 1973.
   Section 31.18

Examples
--------

>>> import numpy as np
>>> from scipy import stats
>>> res = stats.spearmanr([1, 2, 3, 4, 5], [5, 6, 7, 8, 7])
>>> res.statistic
0.8207826816681233
>>> res.pvalue
0.08858700531354381

>>> rng = np.random.default_rng()
>>> x2n = rng.standard_normal((100, 2))
>>> y2n = rng.standard_normal((100, 2))
>>> res = stats.spearmanr(x2n)
>>> res.statistic, res.pvalue
(-0.07960396039603959, 0.4311168705769747)

>>> res = stats.spearmanr(x2n[:, 0], x2n[:, 1])
>>> res.statistic, res.pvalue
(-0.07960396039603959, 0.4311168705769747)

>>> res = stats.spearmanr(x2n, y2n)
>>> res.statistic
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. ]])
>>> res.pvalue
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. ]])

>>> res = stats.spearmanr(x2n.T, y2n.T, axis=1)
>>> res.statistic
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. ]])

>>> res = stats.spearmanr(x2n, y2n, axis=None)
>>> res.statistic, res.pvalue
(0.044981624540613524, 0.5270803651336189)

>>> res = stats.spearmanr(x2n.ravel(), y2n.ravel())
>>> res.statistic, res.pvalue
(0.044981624540613524, 0.5270803651336189)

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

For small samples, consider performing a permutation test instead of
relying on the asymptotic p-value. Note that to calculate the null
distribution of the statistic (for all possibly pairings between
observations in sample ``x`` and ``y``), only one of the two inputs needs
to be permuted.

>>> x = [1.76405235, 0.40015721, 0.97873798,
... 2.2408932, 1.86755799, -0.97727788]
>>> y = [2.71414076, 0.2488, 0.87551913,
... 2.6514917, 2.01160156, 0.47699563]

>>> def statistic(x): # permute only `x`
...     return stats.spearmanr(x, y).statistic
>>> res_exact = stats.permutation_test((x,), statistic,
...     permutation_type='pairings')
>>> res_asymptotic = stats.spearmanr(x, y)
>>> res_exact.pvalue, res_asymptotic.pvalue # asymptotic pvalue is too low
(0.10277777777777777, 0.07239650145772594)

For a more detailed example, see :ref:`hypothesis_spearmanr`.
Nr   zAspearmanr only handles 1-D or 2-D arrays, supplied axis argument z., 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  r   r   r  )r   r   r  r   r   )rowvarr   r   r   r   r  r  r   )r   r   r   r   column_stackvstackr   r   r   r  r   r   r   r4   r  r   r   r   r  rg   r   r   rP  ry   corrcoefr   r  r  _SimpleStudentTr  )r   r   r   r   r  axisoutr  n_varsr3  r$  warn_msga_contains_nanvariable_has_nana_rankedrsdofr  r  ro  s                      r   rg   rg     s   V D1H 337& 988 9 	9 a&JAvvzCDDy66A: 4 5 5  A$a<'A		1&!AWWQ[!FGGGEz 0&&
"H!|adGAJ!AqD'!&&((Qq!tWQZ1QT7-B,G,G,I,I MM%44X>1M$RVVRVV4C ffCOJ -J adGAJ!AqD'!&&((Qq!tWQZ1QT7-B,G,G,I,I MM%44X>1M$RVVRVV4C ffCOJ!.q!=Nxxd3))!:6AC C;&vv{fk(8"$&&
 $&88A;???#@ ""8W8H	X	.B
!)C 
H	% #3R0177:;; 
&
 3Dq$3D 
xx6 D4:6T(
"$&&Q"$&&1 Bb2
% 
&	%s   4Q  
Q.c                 B    [        X5      u  p#[        X#5      nX$l        U$ )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 may be computed using a shortcut formula but produces the
same result as `pearsonr`.

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

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

    statistic : float
        The R value.
    pvalue : float
        The 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_0 N_1}
                        {N (N - 1)}}

Where :math:`\overline{Y_{0}}` and :math:`\overline{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
--------
>>> import numpy as np
>>> 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   r  rpbro  r$  s        r   rh   rh     s$    p IC
S
'COJr   autor   )r   r4  variantr  c                
   [         R                  " U 5      R                  5       n [         R                  " U5      R                  5       nU R                  UR                  :w  a%  [	        SU R                   SUR                   35      eU R                  (       a  UR                  (       d?  [        [         R                  [         R                  5      n[         R                  Ul        U$ [        X5      u  px[        X5      u  pU=(       d    U	nUS:X  d  U
S:X  a  SnU(       aE  US:X  a?  [        [         R                  [         R                  5      n[         R                  Ul        U$ U(       a\  US:X  aV  [        R                  " U 5      n [        R                  " U5      nUS:X  a  [        R                  " XUSUS9$ Sn[	        U5      eS	 nU R                  n[         R                  " U5      nX   X   p[         R                  SUS
S USS :g  4   R                  [         R                   S9n[         R                  " U SS9nX   X   p[         R                  SU S
S U SS :g  4   R                  [         R                   S9n [#        X5      n[         R                  SU S
S U SS :g  US
S USS :g  -  S4   n[         R$                  " [         R&                  " U5      S   5      R)                  SSS9n[+        UUS
-
  -  S-  R-                  5       5      nU" U 5      u  nnnU" U5      u  nnnXS
-
  -  S-  nUU:X  d  UU:X  a?  [        [         R                  [         R                  5      n[         R                  Ul        U$ UU-
  U-
  U-   SU-  -
  nUS:X  a7  U[         R.                  " UU-
  5      -  [         R.                  " UU-
  5      -  nOZUS:X  aE  [1        [3        [5        U 5      5      [3        [5        U5      5      5      nSU-  US-  US
-
  -  U-  -  nO[	        SU S35      e[         R6                  " S[9        SU5      5      nUS:X  a  US:w  d  US:w  a  [	        S5      eUS:X  a*  US:X  a"  US:X  a  US::  d  [1        UUU-
  5      S
::  a  SnOSnUS:X  a(  US:X  a"  US:X  a  [        R:                  " UUU-
  U5      nOUS:X  ak  XS-
  -  nUSU-  S-   -  U-
  U-
  S -  SU-  U-  U-  -   UU-  S!U-  US-
  -  -  -   n U[         R.                  " U 5      -  n![=        U![?        5       U[         S"9nO[	        S#U S$35      e[        US%   US%   5      nUS%   Ul        U$ )&a7  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.
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'.
alternative : {'two-sided', 'less', 'greater'}, optional
    Defines the alternative hypothesis. Default is 'two-sided'.
    The following options are available:

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

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

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

Raises
------
ValueError
    If `nan_policy` is 'omit' and `variant` is not 'b' or
    if `method` is 'exact' and there are ties between `x` and `y`.

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.
:ref:`hypothesis_kendalltau` : Extended example

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]
>>> res = stats.kendalltau(x1, x2)
>>> res.statistic
-0.47140452079103173
>>> res.pvalue
0.2827454599327748

For a more detailed example, see :ref:`hypothesis_kendalltau`.
zBAll inputs to `kendalltau` must be of the same size, found x-size  and y-size r  r   r   T)r4  use_tiesr  z@nan_policy='omit' is currently compatible only with variant='b'.c                 .   [         R                  " U 5      R                  SSS9nXS:     n[        XS-
  -  S-  R	                  5       5      [        XS-
  -  US-
  -  R	                  5       5      [        XS-
  -  SU-  S-   -  R	                  5       5      4$ )Nr  Fr   r   r   r   rS  )r   bincountr   r   r  )rankscnts     r   count_rank_tie"kendalltau.<locals>.count_rank_tie  s    kk% ''e'<'lS!G_)..01S"H%q16689S"H%3388:;= 	=r   r   Nr   r   	mergesortr  r   r  Fr   r   rY  z&Unknown variant of the method chosen: z. variant must be 'b' or 'c'.r         exactz(Ties found, exact method cannot be used.rL  r  
asymptoticrS     r  r   zUnknown method z1 specified.  Use 'auto', 'exact' or 'asymptotic'.r   ) r   r   r   r   r   r   r   r  r   r   r  r  ri   argsortr_r  intpr   diffnonzeror   r   r  r  r"  r   setr  r   _kendall_p_exactr  r  )"r   r  r   r4  rM  r  r$  cnxnpxcnynpyr  r   rU  r   permdisobsrT  ntiextiex0x1ytiey0y1totcon_minus_distau
minclassesr   r  rf  r,  s"                                     r   ri   ri   $  s!   b 	

1A


1Avv //0vvhl166(L M 	MVV166 0&&
 Q+HCQ+HC:#L
f}v

k1 0&&
	*.a a c>**17BD D&GW%%= 66D::a=D7AGq
dAabEQsVO#$++"''+:A ::ak*D7AGq
dAabEQsVO#$++"''+:A
q
C
%%qu#21QR5AcrF?;TA
BC
''"**S/!$
%
,
,W5
,
ACsQw1$))+,D!!$LD"b!!$LD"b!8
"Cs{dck 0&&
 $J%,q3w6M#~bggcDj11BGGC$J4GG	CSVc#a&k2
oqJqL!9*!DEA' K7 7 8 	8 **RS#
'C dai419CDDAI$!)$"**-c3s7*;q*@F!FqyTQY6W#4..tSWkJ	<	2IQtVaZ 2%*b0D41$%')Bw!a%4!82D'EFBGGCL(QD?6( 34 4 5 	5 SWfRj
1C"gCOJr   c                 P   [         R                  " U 5      R                  5       n [         R                  " U5      R                  5       nU R                  UR                  :w  a%  [	        SU R                   SUR                   35      eU R                  (       d?  [        [         R                  [         R                  5      n[         R                  Ul        U$ [         R                  " [         R                  " U 5      5      (       a  [        U 5      n [         R                  " [         R                  " U5      5      (       a  [        U5      nU R                  UR                  :w  aS  U R                  [         R                  :w  a  [        U 5      n UR                  [         R                  :w  a  [        U5      nObU R                  [         R                  [         R                  [         R                  [         R                  4;  a  [        U 5      n [        U5      nUSL a@  [!        XSX45      [!        XSX45      -   S-  n[        U[         R                  5      nXel        U$ USL a.  [         R"                  " U R                  [         R$                  S9nOfUbc  [         R                  " U5      R                  5       nUR                  U R                  :w  a%  [	        SU R                   SUR                   35      e[!        XX#U5      n[        U[         R                  5      nXel        U$ )	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
-------
res: SignificanceResult
    An object containing attributes:

    statistic : float
       The weighted :math:`\tau` correlation index.
    pvalue : float
       Presently ``np.nan``, as the null distribution of the statistic 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
--------
>>> import numpy as np
>>> from scipy import stats
>>> x = [12, 2, 1, 12, 2]
>>> y = [1, 4, 7, 1, 0]
>>> res = stats.weightedtau(x, y)
>>> res.statistic
-0.56694968153682723
>>> res.pvalue
nan
>>> res = stats.weightedtau(x, y, additive=False)
>>> res.statistic
-0.62205716951801038

NaNs are considered the smallest possible score:

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

This is exactly Kendall's tau:

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

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

zCAll inputs to `weightedtau` must be of the same size, found x-size rO  TNr   Fr   z and rank-size )r   r   r   r   r   r   r   r  r   r  r   r   r  int32float32rE  r   aranger_  )r   r  r  weigheradditiver$  rt  s          r   rj   rj     sD   J 	

1A


1Avv ))*QVVHF G 	G 66 0&&
 
xxq	QK	xxq	QK 	ww!''77bhhA77bhhA77288RXXrzz2::FFAAt|qT7=qT7=> !bff-
u}yyrww/		zz$%%'99  !xtyykC 
 Q4(
;C
S"&&
)COJr   TtestResultBaser  c                   <   ^  \ rS rSrSr SU 4S jjrSS jrSrU =r$ )TtestResulti  a  
Result of a t-test.

See the documentation of the particular t-test function for more
information about the definition of the statistic and meaning of
the confidence interval.

Attributes
----------
statistic : float or array
    The t-statistic of the sample.
pvalue : float or array
    The p-value associated with the given alternative.
df : float or array
    The number of degrees of freedom used in calculation of the
    t-statistic; this is one less than the size of the sample
    (``a.shape[axis]-1`` if there are no masked elements or omitted NaNs).

Methods
-------
confidence_interval
    Computes a confidence interval around the population statistic
    for the given confidence level.
    The confidence interval is returned in a ``namedtuple`` with
    fields `low` and `high`.

c	                    > [         T	U ]  XUS9  X@l        XPl        X`l        Uc  UOUU l        UR                  U l        Uc  [        X5      U l	        g UU l	        g )Nr  )
r  r  r  _standard_error	_estimate_statistic_npr   _dtyper8   _xp)
r  r   r   r  r  standard_errorestimatestatistic_npr   r  s
            r   r  TtestResult.__init__  sX     	r2'-!*6*>YLoo9;?95r   c                    [        U R                  U R                  XR                  U R                  U R
                  5      u  p#X R                  -  U R                  -   nX0R                  -  U R                  -   n[        X#S9$ )a  
Parameters
----------
confidence_level : float
    The confidence level for the calculation of the population mean
    confidence interval. Default is 0.95.

Returns
-------
ci : namedtuple
    The confidence interval is returned in a ``namedtuple`` with
    fields `low` and `high`.

r  )	_t_confidence_intervalr  r  r  r  r  r  r  r  )r  r  rW  rX  s       r   r  TtestResult.confidence_interval  sp     +477D4F4F+;=N=N+/;;B	 (((4>>9***T^^;!c55r   )r  r  r  r  r  r  NNr  r  r  s   @r   r~  r~    s    < (,	L6 6r   r~  c           	          [         R                  " U5      nU[         R                  " U5         nUR                  (       a  US   O[         R                  n[        XX#XES9$ )Nr   r  r  r  r  )r   r   isfiniter   r   r~  )r   r   r  r  r  r  s         r   pack_TtestResultr    sR     --,Kbkk+67K$/$4$4+a."&&KyR&4I Ir   c                     U R                   U R                  U R                  U R                  U R                  U R
                  4$ r   )r   r   r  r  r  r  r$  s    r   unpack_TtestResultr    s6    MM3::svvs/?/?0 0r   r   r  )r	  r   r   r   c                    [        U 5      n[        XUS9u  pU R                  U   nUS-
  nUS:X  a  [        U 5      n[	        XXXS9$ UR                  XS9n	 UR                  U5      nUR                  S:  a  UR                  XS9OUnX-
  n[        XSS9nUR                  X-  5      n[        R                  " S	S	S
9   UR                  X5      nUR                  S:X  a  US   OUnSSS5        [        UR                  UWR                   S95      n[#        XXES9nUR                  S:X  a  US   OUnUR%                  UR                  U5      UR                  5      nUR                  S:X  a  US   OUnSSSS.U   n[	        UUUUXUR                  U5      US9$ ! [         a  n
[        S5      U
eSn
A
ff = f! , (       d  f       N= f)a  Calculate the T-test for the mean of ONE group of scores.

This is a 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 observations.
popmean : float or array_like
    Expected value in null hypothesis. If array_like, then its length along
    `axis` must equal 1, and it must otherwise be broadcastable with `a`.
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 mean of the underlying distribution of the sample
      is different than the given population mean (`popmean`)
    * 'less': the mean of the underlying distribution of the sample is
      less than the given population mean (`popmean`)
    * 'greater': the mean of the underlying distribution of the sample is
      greater than the given population mean (`popmean`)

Returns
-------
result : `~scipy.stats._result_classes.TtestResult`
    An object with the following attributes:

    statistic : float or array
        The t-statistic.
    pvalue : float or array
        The p-value associated with the given alternative.
    df : float or array
        The number of degrees of freedom used in calculation of the
        t-statistic; this is one less than the size of the sample
        (``a.shape[axis]``).

        .. versionadded:: 1.10.0

    The object also has the following method:

    confidence_interval(confidence_level=0.95)
        Computes a confidence interval around the population
        mean for the given confidence level.
        The confidence interval is returned in a ``namedtuple`` with
        fields `low` and `high`.

        .. versionadded:: 1.10.0

Notes
-----
The statistic is calculated as ``(np.mean(a) - popmean)/se``, where
``se`` is the standard error. Therefore, the statistic will be positive
when the sample mean is greater than the population mean and negative when
the sample mean is less than the population mean.

Examples
--------
Suppose we wish to test the null hypothesis that the mean of a population
is equal to 0.5. We choose a confidence level of 99%; that is, we will
reject the null hypothesis in favor of the alternative if the p-value is
less than 0.01.

When testing random variates from the standard uniform distribution, which
has a mean of 0.5, we expect the data to be consistent with the null
hypothesis most of the time.

>>> import numpy as np
>>> from scipy import stats
>>> rng = np.random.default_rng()
>>> rvs = stats.uniform.rvs(size=50, random_state=rng)
>>> stats.ttest_1samp(rvs, popmean=0.5)
TtestResult(statistic=2.456308468440, pvalue=0.017628209047638, df=49)

As expected, the p-value of 0.017 is not below our threshold of 0.01, so
we cannot reject the null hypothesis.

When testing data from the standard *normal* distribution, which has a mean
of 0, we would expect the null hypothesis to be rejected.

>>> rvs = stats.norm.rvs(size=50, random_state=rng)
>>> stats.ttest_1samp(rvs, popmean=0.5)
TtestResult(statistic=-7.433605518875, pvalue=1.416760157221e-09, df=49)

Indeed, the p-value is lower than our threshold of 0.01, so we reject the
null hypothesis in favor of the default "two-sided" alternative: the mean
of the population is *not* equal to 0.5.

However, suppose we were to test the null hypothesis against the
one-sided alternative that the mean of the population is *greater* than
0.5. Since the mean of the standard normal is less than 0.5, we would not
expect the null hypothesis to be rejected.

>>> stats.ttest_1samp(rvs, popmean=0.5, alternative='greater')
TtestResult(statistic=-7.433605518875, pvalue=0.99999999929, df=49)

Unsurprisingly, with a p-value greater than our threshold, we would not
reject the null hypothesis.

Note that when working with a confidence level of 99%, a true null
hypothesis will be rejected approximately 1% of the time.

>>> rvs = stats.uniform.rvs(size=(100, 50), random_state=rng)
>>> res = stats.ttest_1samp(rvs, popmean=0.5, axis=1)
>>> np.sum(res.pvalue < 0.01)
1

Indeed, even though all 100 samples above were drawn from the standard
uniform distribution, which *does* have a population mean of 0.5, we would
mistakenly reject the null hypothesis for one of them.

`ttest_1samp` can also compute a confidence interval around the population
mean.

>>> rvs = stats.norm.rvs(size=50, random_state=rng)
>>> res = stats.ttest_1samp(rvs, popmean=0)
>>> ci = res.confidence_interval(confidence_level=0.95)
>>> ci
ConfidenceInterval(low=-0.3193887540880017, high=0.2898583388980972)

The bounds of the 95% confidence interval are the
minimum and maximum values of the parameter `popmean` for which the
p-value of the test would be 0.05.

>>> res = stats.ttest_1samp(rvs, popmean=ci.low)
>>> np.testing.assert_allclose(res.pvalue, 0.05)
>>> res = stats.ttest_1samp(rvs, popmean=ci.high)
>>> np.testing.assert_allclose(res.pvalue, 0.05)

Under certain assumptions about the population from which a sample
is drawn, the confidence interval with confidence level 95% is expected
to contain the true population mean in 95% of sample replications.

>>> rvs = stats.norm.rvs(size=(50, 1000), loc=1, random_state=rng)
>>> res = stats.ttest_1samp(rvs, popmean=0)
>>> ci = res.confidence_interval()
>>> contains_pop_mean = (ci.low < 1) & (ci.high > 1)
>>> contains_pop_mean.sum()
953

r   r   r   r  r   z#`popmean.shape[axis]` must equal 1.Nr.  r   r   r   r   r   r  r  r  )r  r  r  r  r  r   )r8   r   r   r   r~  r  r   r   rp  r   rg  r  r   r   r   rA  r   r  r'  )r   popmeanr   r   r  r   r  r  r   r  r  dr  r  r  r  ro  alternative_nums                     r   rl   rl     s   | 
	B1r*GA	A	
QBAv qk3*-= 	= 7717 DG**W%4;LL14D"**W*0' 	AQ"AGGAENE	Hh	7IIaVVq[AbEa 
8 2::b:89Dq3DyyA~484D 
B	1B77a<BRB!a@MOq$2?&+$&JJqMb: :'  G>?QFG 
8	7s$   2F  )F<
F9(F44F9<
G
c                    Uc  UR                   OUnUc  [        U5      OUn[        R                  " U 5      [        R                  " U5      pUS:  d  US:  a  Sn[	        U5      eUS:  a?  Un[        R
                  " [        R                  * [        R                  " X5      5      u  pOUS:  aA  SU-
  n[        R
                  " [        R                  " X5      [        R                  5      u  pOUS:X  ae  SU-
  S-  n
U
SU
-
  4n[        R                  " US/S/[        R                  " U 5      R                  -  -   5      n[        R                  " X5      u  pO)[        R
                  " U[        R                  5      u  p{XpUR                  XS9nUR                  S:X  a  US   OUnUR                  XS9n	U	R                  S:X  a  U	S   OU	n	X4$ )Nr   r   4`confidence_level` must be a number between 0 and 1.r   r   r   )r   r8   r   r   r   r  r!  r  stdtritr   r   r   )r  r  r  r  r   r   r   r   rW  rX  tail_probabilitynanss               r   r  r    s    }AGG%E!z	rB JJrNBJJqM!/!3H!!Q''1GH	T	q  ''(>G	T		 00!3a 000JJq1#BJJrN$7$7 778OOB*	T%%a0T
**S*
&CXX]#b'C::d:(DyyA~484D9r   c                    Uc  [        XU5      OUnX-
  n[        R                  " SSS9   UR                  Xb5      nS S S 5        [        R                  " W5      n[        R                  " U5      n	[        U[        R                  " U	5      U[        S9n
UR	                  XR                  S9n
UR                  S:X  a  US   OUnU
R                  S:X  a  U
S   OU
n
Xz4$ ! , (       d  f       N= f)Nr   r   r   r   r   r   )
r8   r   r   r   r   r  r   r  r   r   )mean1mean2r  r  r  r   r  r  t_npdf_npro  s              r   _ttest_ind_from_statsr    s    13u	-BA	Hh	7IIa 
8 ::a=DJJrNEt]__U3[RHD::d'':*D1"!AyyA~484D7N 
8	7s   C
C-c                 \   Uc  [        X5      OUnX-  nX#-  n[        R                  " SSS9   XV-   S-  US-  US-
  -  US-  US-
  -  -   -  nS S S 5        UR                  UR	                  W5      UR                  S5      U5      nUR                  XV-   5      nXx4$ ! , (       d  f       NU= f)Nr   r   r   r   r   )r8   r   r   r   r   r   r  )	v1r  v2r  r   vn1vn2r  r  s	            r   _unequal_var_ttest_denomr    s    $&J	 BB
'C
'C	Hh	7i!^sAva036R!V3DDE 
8
 
"((2,

2	3BGGCIE9 
8	7s    B
B+c                 J   Uc  [        X5      OUnUR                  S5      nUR                  UR                  US:H  5      XP5      n UR                  UR                  US:H  5      XR5      nX-   S-
  nUS-
  U -  US-
  U-  -   U-  nUR                  USU-  SU-  -   -  5      nXh4$ )Nr  r   ro  r   )r8   r   r   r  )	r  r  r  r  r   ru  r  svarr  s	            r   _equal_var_ttest_denomr  &  s    $&J	 BB ::b>D	"**R1W%t	0B	"**R1W%t	0B	3B!VrMR!VrM)R/DGGDC"HsRx/01E9r   Ttest_indResultc                 (   [        XX45      nUR                  U 5      n UR                  U5      nUR                  U5      nUR                  U5      nU(       a  [        US-  X$S-  XXS9u  pO[        US-  X$S-  XXS9u  p[	        XXU5      n[        U6 $ )aQ  
T-test for means of two independent samples from descriptive statistics.

This is a 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 corrected sample standard deviation of sample 1 (i.e. ``ddof=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 corrected sample standard deviation of sample 2 (i.e. ``ddof=1``).
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': the means of the distributions are unequal.
    * 'less': the mean of the first distribution is less than the
      mean of the second distribution.
    * 'greater': the mean of the first distribution is greater than the
      mean of the second distribution.

    .. 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
-----
The statistic is calculated as ``(mean1 - mean2)/se``, where ``se`` is the
standard error. Therefore, the statistic will be positive when `mean1` is
greater than `mean2` and negative when `mean1` is less than `mean2`.

This method does not check whether any of the elements of `std1` or `std2`
are negative. If any elements of the `std1` or `std2` parameters are
negative in a call to this method, this method will return the same result
as if it were passed ``numpy.abs(std1)`` and ``numpy.abs(std2)``,
respectively, instead; no exceptions or warnings will be emitted.

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 (with the
Sample Variance being the corrected sample variance)::

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

>>> import numpy as np
>>> 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)
TtestResult(statistic=0.905135809331027,
            pvalue=0.3751996797581486,
            df=22.0)

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.161073
    Sample 2    200      45         0.225      0.175251

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.161073), nobs1=150,
...                      mean2=0.225, std2=np.sqrt(0.175251), nobs2=200)
Ttest_indResult(statistic=-0.5627187905196761, pvalue=0.5739887114209541)

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)
TtestResult(statistic=-0.5627179589855622,
            pvalue=0.573989277115258,
            df=348.0)

r   r   )r8   r   r  r  r  r  )r  std1nobs1r  std2nobs2	equal_varr  r   r  r  r$  s               r   rn   rn   ;  s    | 
e	2BJJuE::dDJJuE::dD*47E7EQ	E,T1We1WeS	
e
ECC  r   z-Use ``method`` to perform a permutation test.z1.17.0permutationsrandom_state)versiondeprecated_argscustom_message)r   r  r   r  r  r  trimr4  c                   [        X5      n
U
R                  S5      R                  nU
R                  U R                  S5      (       a  U
R	                  X5      n U
R                  UR                  S5      (       a  U
R	                  X5      nSUs=::  a  S:  d  O  [        S5      e[        U	[        [        -  S-  5      (       d  Sn[        U5      e[        U
5      (       d  U	b  Sn[        U5      e[        X4US	9nU
R                  U[        XU
S
95      nUR                  S:X  a  US   OUn[        U 5      S:X  d  [        U5      S:X  a  [!        XXXS9$ SSSS.nUb\  US:w  aV  Sn[        U
5      (       d  [        U5      eSnUS:w  a  [        U5      e[#        XUX#UUUS9u  nnXUnnn[!        UUUX   UUS9$ U
R                  U R$                  U   U R                  S9nU
R                  UR$                  U   UR                  S9nUS:X  aS  [&        R(                  " SSS9   [+        XSU
S9n[+        XSU
S9nSSS5        U
R-                  XS	9nU
R-                  XS	9nO=Sn[        U
5      (       d  [        U5      e[/        XU5      u  nnn[/        XU5      u  nnnU(       a  [1        WUWUU
S
9u  nnO[3        WUWUU
S
9u  nnU	c  [5        UUUUU5      u  nnO[7        X8S9n[9        XX'UU	5      u  nnU
R;                  UUR$                  5      nUR                  S:X  a  US   OUnUU-
  n[!        UUUX   UUS9$ ! , (       d  f       GN= f)aH,  
Calculate the T-test for the means of *two independent* samples of scores.

This is a 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 asymptotic 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.

    .. deprecated:: 1.17.0
        `permutations` is deprecated and will be removed in SciPy 1.7.0.
        Use the `n_resamples` argument of `PermutationMethod`, instead,
        and pass the instance as the `method` argument.

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

    .. deprecated:: 1.17.0
        `random_state` is deprecated and will be removed in SciPy 1.7.0.
        Use the `rng` argument of `PermutationMethod`, instead,
        and pass the instance as the `method` argument.

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

    * 'two-sided': the means of the distributions underlying the samples
      are unequal.
    * 'less': the mean of the distribution underlying the first sample
      is less than the mean of the distribution underlying the second
      sample.
    * 'greater': the mean of the distribution underlying the first
      sample is greater than the mean of the distribution underlying
      the second sample.

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).
method : ResamplingMethod, optional
    Defines the method used to compute the p-value. If `method` is an
    instance of `PermutationMethod`/`MonteCarloMethod`, the p-value is
    computed using
    `scipy.stats.permutation_test`/`scipy.stats.monte_carlo_test` with the
    provided configuration options and other appropriate settings.
    Otherwise, the p-value is computed by comparing the test statistic
    against a theoretical t-distribution.

    .. versionadded:: 1.15.0

Returns
-------
result : `~scipy.stats._result_classes.TtestResult`
    An object with the following attributes:

    statistic : float or ndarray
        The t-statistic.
    pvalue : float or ndarray
        The p-value associated with the given alternative.
    df : float or ndarray
        The number of degrees of freedom used in calculation of the
        t-statistic. This is always NaN for a permutation t-test.

        .. versionadded:: 1.11.0

    The object also has the following method:

    confidence_interval(confidence_level=0.95)
        Computes a confidence interval around the difference in
        population means for the given confidence level.
        The confidence interval is returned in a ``namedtuple`` with
        fields ``low`` and ``high``.
        When a permutation t-test is performed, the confidence interval
        is not computed, and fields ``low`` and ``high`` contain NaN.

        .. versionadded:: 1.11.0

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.

(In the following, note that the argument `permutations` itself is
deprecated, but a nearly identical test may be performed by creating
an instance of `scipy.stats.PermutationMethod` with ``n_resamples=permutuations``
and passing it as the `method` argument.)
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.
Specifically, the p-value reported is the "achieved significance level"
(ASL) as defined in 4.4 of [3]_. Note that there are other ways of
estimating p-values using randomized permutation tests; for other
options, see the more general `permutation_test`.

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
recommended if the underlying distribution is long-tailed or contaminated
with outliers [4]_.

The statistic is calculated as ``(np.mean(a) - np.mean(b))/se``, where
``se`` is the standard error. Therefore, the statistic will be positive
when the sample mean of `a` is greater than the sample mean of `b` and
negative when the sample mean of `a` is less than the sample mean of
`b`.

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] B. Efron and T. Hastie. Computer Age Statistical Inference. (2016).

.. [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
--------
>>> import numpy as np
>>> 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)
TtestResult(statistic=-0.4390847099199348,
            pvalue=0.6606952038870015,
            df=998.0)
>>> stats.ttest_ind(rvs1, rvs2, equal_var=False)
TtestResult(statistic=-0.4390847099199348,
            pvalue=0.6606952553131064,
            df=997.4602304121448)

`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)
TtestResult(statistic=-1.6370984482905417,
            pvalue=0.1019251574705033,
            df=998.0)
>>> stats.ttest_ind(rvs1, rvs3, equal_var=False)
TtestResult(statistic=-1.637098448290542,
            pvalue=0.10202110497954867,
            df=765.1098655246868)

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)
TtestResult(statistic=-1.9481646859513422,
            pvalue=0.05186270935842703,
            df=598.0)
>>> stats.ttest_ind(rvs1, rvs4, equal_var=False)
TtestResult(statistic=-1.3146566100751664,
            pvalue=0.1913495266513811,
            df=110.41349083985212)

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)
TtestResult(statistic=-2.8415950600298774,
            pvalue=0.0046418707568707885,
            df=598.0)
>>> stats.ttest_ind(rvs1, rvs5, equal_var=False)
TtestResult(statistic=-1.8686598649188084,
            pvalue=0.06434714193919686,
            df=109.32167496550137)

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)
TtestResult(statistic=3.4463884028073513,
            pvalue=0.01369338726499547,
            df=6.0)
r   r   r   r.  z/Trimming percentage should be 0 <= `trim` < .5.Nzj`method` must be an instance of `PermutationMethod`, an instance of `MonteCarloMethod`, or None (default).z?Use of resampling methods is compatible only with NumPy arrays.r   r   r   r  r   r   r  z;Use of `permutations` is compatible only with NumPy arrays.z>Use of `permutations` is incompatible with with use of `trim`.)r  r   r  r   r  r  r   r   r   )r  r   z3Use of `trim` is compatible only with NumPy arrays.)r  r  )r8   r   r   r   r   r   r   r#   r"   r9   NotImplementedErrorr,   r  r   r   r:   r~  _permutation_ttestr   r   r   rg  r  _ttest_trim_var_mean_lenr  r  r  dict_ttest_resamplingr'  )r   r   r   r  r   r  r  r  r  r4  r   default_floatr   result_shaper   alternative_numsr  ro  r  r  r  r  r  r  r  m1rs  ttest_kwargss                               r   rm   rm     s`   l 
	BJJrN((M	zz!'':&&IIa'	zz!'':&&IIa'NNJKKf/2BBTIJJ?!!B<<F.S!'**6vDIL
''," 5
6CXX]#b'CqzQ'!*/3*-= 	= !#qA LA$5O||%g..R19%g..$Q*.0:2>1<	>4
 "8E 1dr7G7T*/(D 	D 
AGGDM	1B	AGGDM	1Bqy[[(;aA"-BaA"-B < WWQW"WWQW"G||%g..-at<
B-at<
B*2r2rbA	E,RRC	E~'Br;G4 i;#A$\6R4 
QWW	%B77Q;BBBBwHq$23C3P&+h@ @? <;s   $L??
Mc                 l  ^ U4S jn[        U[        5      (       a  [        O[        nUR	                  5       nU[        L aO  UR                  SS 5      =nb:  [        R                  R                  U5      nUR                  UR                  4US'   U" X44XbUS.UD6n	U	R                  U	R                  4$ )Nc                 4   > [        X4SU0TD6R                  $ )Nr   )rm   r   )r   r  r   r  s      r   r   $_ttest_resampling.<locals>.statistic:  s    9D9L9CCCr   r;  r  r  )r   r#   r&   r%   r  r  r   r  r  r0  r   r   )
r   r  r   r  r  r4  r   testr;  r$  s
       `     r   r  r  9  s    D !+63D E E! 	^^F ::eT**C7))'',CJJ

2F5M
w 2)&2*02C ==#**$$r   c                     [         R                  " XS9n U R                  U   n[        X1-  5      n[	        XU5      nUSU-  -  n[        XUS9nXVU4$ )zCVariance, mean, and length of winsorized input along specified axisr   r   )r   r  r   r   _calculate_winsorized_variancerc   )r   r  r   r  gr  r  s          r   r  r  N  s`    
 	A 	
AAHA 	'qT2A QJA 	!%A7Nr   c                 \   US:X  a  [        U SUS9$ [        R                  " XS5      n[        R                  " [        R                  " U5      SS9nUSU/4   USSU24'   USU* S-
  /4   USU* S24'   [        R
                  " [        USU-  S-   SS95      n[        R                  XT'   U$ )	z;Calculates g-times winsorized variance along specified axisr   r   )r  r   r   r   .Nr   )rg  r   r  r   r   r   r   )r   r  r   a_winnans_indicesvar_wins         r   r  r  f  s     	AvAAD))KK$E 66"((5/3L 38_E#rr'NC1"q&M*E#rs(O jje1q519B?@G
 FFGNr   c                   ^^ [        T5      mU R                  S   m[        R                  " TU5      nX:  a  UU4S j[	        U5       5       nOUnS [        UTU-
  5       5       n/ n[        USS9 He  n[        R                  " U5      nU SU4   n	[        R                  " U	SS5      n	U	SS	U24   n
U	SUS	24   nUR                  [        XU5      5        Mg     [        R                  " USS
9nXqU4$ )z2Generation permutation distribution of t statisticr   c              3   F   >#    U  H  nTR                  T5      v   M     g 7fr   )permutation)rI  r   r  r   s     r   rK  ._permutation_distribution_t.<locals>.<genexpr>  s&      8#6a '22488#6r}  c              3   N   #    U  H  n[         R                  " U5      v   M     g 7fr   )r   r  )rI  r,  s     r   rK  r    s$      I#Ga ..++#Gs   #%2   )batch.r^  r   Nr   )r   r   r  combrG  r    r(   r   r   r  rH  _calc_t_statr  )datar  size_ar  r  n_maxperm_generatort_statindices	data_permr   r   r   s       `       @r   _permutation_distribution_tr    s    &l3L ::b>DLLv&E8#(#68 I#264;#GI F#N"=((7#g&	 KK	2q1	c7F7l#c67l#l134 > ^^F+F&&r   c                    U R                   U   nUR                   U   n[        R                  " XS9n[        R                  " XS9n[        XSS9n[        XSS9n	U(       d  [	        XX5      u  pO[        XX5      u  pXg-
  U-  $ )z4Calculate the t statistic along the given dimension.r   r   r.  )r   r   r  rg  r  r  )r   r   r  r   nanbavg_aavg_bvar_avar_br  r  s               r   r  r    s~    	
B	
BGGA!EGGA!EA&EA&E+EuA5)%U?Kr   c                    US:  d*  [         R                  " U5      (       a  [        U5      U:w  a  [        S5      e[	        U5      n[        XXCS9nU R                  U   n	[        X4US9n
[         R                  " XS5      n
[        XXUS9u  pn[         R                  [         R                  S S.nX   " X5      nX:  a  SOSnUR                  SS9U-   X/-   -  nUS	:X  a  [         R                  " U5      R                  5       (       ai  [         R                  " U5      S:X  a(  [         R                   " [         R"                  5      nUU4$ [         R"                  U[         R                  " U5      '   UU4$ )
aS  
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 p-value.

r   z,Permutations must be a non-negative integer.r   r   )r  r  r  c                 j    U [         R                  " U5      * :*  U [         R                  " U5      :  -  $ r   )r   rV  r  s     r   r   $_permutation_ttest.<locals>.<lambda>  s#    !q	z/a266!9n)Mr   )r  r  r  r   r   )r   r  r   r   r   r  r   r*   r  r  
less_equalgreater_equalr  r   r   r   rE  r   )r   r   r  r   r  r   r  r  t_stat_observedr  matr  r  r)  cmps
adjustmentpvaluess                    r   r  r    sX   R aBKK55-=GHH%l3L"1>O	
B
 !d
3C
++c
$C"="!##F% }}**MOG
 8D *JxxQx*,1JKG [ RXXo%>%B%B%D%D777q jj(G W%% 24GBHH_-.W%%r   c                 p     U R                   U   nU$ ! [         a    [        XR                  U5      S ef = fr   )r   
IndexErrorr   r   )r   r   r  r  s       r   _get_lenr    s?    5GGDM H  5ffc*45s    "5)r	  r   r   r   r   c                     [        X-
  SX$SS9$ )ap  Calculate the t-test on TWO RELATED samples of scores, a and b.

This is a test for the null hypothesis that two 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': the means of the distributions underlying the samples
      are unequal.
    * 'less': the mean of the distribution underlying the first sample
      is less than the mean of the distribution underlying the second
      sample.
    * 'greater': the mean of the distribution underlying the first
      sample is greater than the mean of the distribution underlying
      the second sample.

    .. versionadded:: 1.6.0

Returns
-------
result : `~scipy.stats._result_classes.TtestResult`
    An object with the following attributes:

    statistic : float or array
        The t-statistic.
    pvalue : float or array
        The p-value associated with the given alternative.
    df : float or array
        The number of degrees of freedom used in calculation of the
        t-statistic; this is one less than the size of the sample
        (``a.shape[axis]``).

        .. versionadded:: 1.10.0

    The object also has the following method:

    confidence_interval(confidence_level=0.95)
        Computes a confidence interval around the difference in
        population means for the given confidence level.
        The confidence interval is returned in a ``namedtuple`` with
        fields `low` and `high`.

        .. versionadded:: 1.10.0

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.

The t-statistic is calculated as ``np.mean(a - b)/se``, where ``se`` is the
standard error. Therefore, the t-statistic will be positive when the sample
mean of ``a - b`` is greater than zero and negative when the sample mean of
``a - b`` is less than zero.

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

Examples
--------
>>> import numpy as np
>>> 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)
TtestResult(statistic=-0.4549717054410304, pvalue=0.6493274702088672, df=499)
>>> 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)
TtestResult(statistic=-5.879467544540889, pvalue=7.540777129099917e-09, df=499)

r   T)r  r   r  r-  )rl   )r   r   r   r   r  s        r   ro   ro     s    L quad $& &r   g      r^  gUUUUUU?)pearsonzlog-likelihoodzfreeman-tukeyzmod-log-likelihoodneymanzcressie-readc                    [        U S5      (       aK  U R                  US9n[        U[        R                  5      (       a  UR
                  S:X  a  [        U5      nU$ Uc  [        U 5      nU$ U R                  U   nU$ )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   )	hasattrr   r   r   ndarrayr   r   r:   r   )r   r   r   nums       r   _m_countr    sy     q'gg4g c2::&&388q= c(C J	 <!*C J ''$-CJr   c                   [         R                  R                  U 5      (       aQ  [         R                  R                  [         R                  " X5      [         R                  " U R
                  U5      S9$ UR	                  X5      $ )N)r   )r   r   isMaskedArraymasked_arrayr'  r   )r   r   r   s      r   _m_broadcast_tor    sa    	uu1uu!!"//!";')qvvu'E " G 	G??1$$r   c                    [         R                  R                  U 5      (       a0  U R                  U5      nU(       a  U$ [         R                  " U5      $ UR                  XS9$ r  )r   r   r   r  r   )r   r   preserve_maskr   r  s        r   _m_sumr    sJ    	uu1eeDk#s8C866!6r   c                    [         R                  R                  U 5      (       a#  [         R                  " U R	                  XS95      $ UR	                  XUS9$ )NrD  )r   r   r   r   r  )r   r   r   r   s       r   _m_meanr    sD    	uu1zz!&&d&>??771(733r   Power_divergenceResultc                     [        XX#US9$ )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.

    .. deprecated:: 1.14.0
        Support for masked array input was deprecated in
        SciPy 1.14.0 and will be removed in version 1.16.0.

f_exp : array_like, optional
    Expected frequencies in each category.  By default the categories are
    assumed to be equally likely.

    .. deprecated:: 1.14.0
        Support for masked array input was deprecated in
        SciPy 1.14.0 and will be removed in version 1.16.0.

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:

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

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

    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 ``eps**0.5``, where ``eps``
is the precision of the input dtype.

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.

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

>>> import numpy as np
>>> 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]))

)f_expr  r   lambda__power_divergence)f_obsr
  r  r   r  s        r   rt   rt     s    P UdwWWr   c                 4	   [        U 5      nUR                  S5      R                  n[        U[        5      (       aO  U[
        ;  a;  [        [        [
        R                  5       5      5      SS n[        SU< SU 35      e[
        U   nOUc  SnS n	U	" U 5        [        R                  R                  U 5      (       a  U OUR                  U 5      n UR                  U R                  S5      (       a  UOU R                  n
[        R                  R                  U 5      (       a  U R                  U
5      OUR                  X
S9n [        U S	5      (       a  U R                  [        R                   5      OUR                  XR                   S9nUGb  U	" U5        [        R                  R                  U 5      (       a  UOUR                  U5      nUR                  UR                  S5      (       a  UOUR                  n
[        R                  R                  U5      (       a  UR                  U
5      OUR                  XS9n[#        UR$                  UR$                  45      n['        XUS
9n['        XUS
9nU(       a  UR)                  U R                  UR                  5      nUR+                  U5      R,                  S-  n[        R.                  " SS9   [1        XSUS9n[1        XSUS9nUR3                  UU-
  5      UR5                  UU5      -  nUR7                  UU:  S S9nS S S 5        W(       a  SU SW 3n[        U5      eO([        R.                  " SS9   [9        XSUS9nS S S 5        US:X  a  X-
  S-  U-  nOaUS:X  a  S[:        R<                  " X U-  5      -  nO>US:X  a  S[:        R<                  " XU -  5      -  nOX U-  U-  S-
  -  nUSU-  US-   -  -  n[1        UUSUS9n[?        UX6S9nUR                  U5      nUR                  US-
  U-
  5      n[A        U5      n[C        UUSSUS9nURD                  S:X  a  US   OUnURD                  S:X  a  US   OUn[G        UU5      $ ! , (       d  f       GNT= f! , (       d  f       GN#= f)Nr   r   r   zinvalid string for lambda_: z. Valid strings are c                 |    [        U [        R                  5      (       a  Sn[        R                  " U[
        SS9  g g )Nz`power_divergence` and `chisquare` support for masked array input was deprecated in SciPy 1.14.0 and will be removed in version 1.16.0.r   r   )r   r   r$  r   r   r/  )argr   s     r   warn_masked&_power_divergence.<locals>.warn_maskedq  s6    c2>>**T  MM'#5!D	 +r   r   r   r   r   r.  r   rR  F)r   r  r   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:
T)r   r   r   r   r   ro  r  r  r  r   )$r8   r   r   r   r5  _power_div_lambda_namesrN  r_  keysr   r   r   r   r   r   r  rE  r+   r   r  r   rT  rU  r   r  rV  r  r   r  r  xlogyr  r  r  r   r  )r  r
  r  r   r  	sum_checkr   r  namesr  r   f_obs_floatbshape	dtype_resrtol	f_obs_sum	f_exp_sumrelative_diffdiff_gt_tolr  termsstatnum_obsr  r  r   s                             r   r  r  c  s   		BJJrN((M '3115::<=>qDE;G; G227: ; ;)'2	E UU((//ERZZ5FEZZZ@@MekkE$&EE$7$7$>$>U\\% **U*0 
/6uf/E/E5<<

+

5


;  E,,U33E9J!#EKK!D!D%++(*(;(;E(B(Be$jjj4 	 #K$5$5u{{#CD%kbA"5u{{EKK@I88I&**C/DX.";SUV	"55RP	!#	I(=!>!#Iy!A"B ff]T%9fE /  "F"F'	*
 !o%
 [[*EtCE + !|"U*	AgmmE5=99	BgmmE5=99 %-'1A56w'A+..%d$2>Du4/G::dD	GaK$&	'Br?Dt)uQSTFyyA~484D!;;!+VBZF!$//c /." +*s   AQ6 R6
R
R)r  c          	          [        XX#SUS9$ )a  Perform Pearson's chi-squared test.

Pearson's chi-squared test [1]_ is a goodness-of-fit test for a multinomial
distribution with given probabilities; that is, it assesses the null hypothesis
that the observed frequencies (counts) are obtained by independent
sampling of *N* observations from a categorical distribution with given
expected 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 categories.  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.
sum_check : bool, optional
    Whether to perform a check that ``sum(f_obs) - sum(f_exp) == 0``. If True,
    (default) raise an error when the relative difference exceeds the square root
    of the precision of the data type. See Notes for rationale and possible
    exceptions.

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

    statistic : 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.
    pvalue : float or ndarray
        The p-value of the test.  The value is a float if `ddof` and the
        result attribute `statistic` 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.
:ref:`hypothesis_chisquare` : Extended example

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 [2]_, the
total number of observations is recommended to be greater than 13,
otherwise exact tests (such as Barnard's Exact test) should be used
because they do not overreject.

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.

For Pearson's chi-squared test, the total observed and expected counts must match
for the p-value to accurately reflect the probability of observing such an extreme
value of the statistic under the null hypothesis.
This function may be used to perform other statistical tests that do not require
the total counts to be equal. For instance, to test the null hypothesis that
``f_obs[i]`` is Poisson-distributed with expectation ``f_exp[i]``, set ``ddof=-1``
and ``sum_check=False``. This test follows from the fact that a Poisson random
variable with mean and variance ``f_exp[i]`` is approximately normal with the
same mean and variance; the chi-squared statistic standardizes, squares, and sums
the observations; and the sum of ``n`` squared standard normal variables follows
the chi-squared distribution with ``n`` degrees of freedom.

References
----------
.. [1] "Pearson's chi-squared test".
       *Wikipedia*. https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test
.. [2] 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 only the mandatory `f_obs` argument is given, it is assumed that the
expected frequencies are uniform and given by the mean of the observed
frequencies:

>>> import numpy as np
>>> from scipy.stats import chisquare
>>> chisquare([16, 18, 16, 14, 12, 12])
Power_divergenceResult(statistic=2.0, pvalue=0.84914503608460956)

The optional `f_exp` argument gives the expected frequencies.

>>> chisquare([16, 18, 16, 14, 12, 12], f_exp=[16, 16, 16, 16, 16, 8])
Power_divergenceResult(statistic=3.5, pvalue=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)
Power_divergenceResult(statistic=array([2.        , 6.66666667]), pvalue=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)
Power_divergenceResult(statistic=23.31034482758621, pvalue=0.015975692534127565)
>>> chisquare(obs.ravel())
Power_divergenceResult(statistic=23.310344827586206, pvalue=0.01597569253412758)

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

>>> chisquare([16, 18, 16, 14, 12, 12], ddof=1)
Power_divergenceResult(statistic=2.0, pvalue=0.7357588823428847)

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])
Power_divergenceResult(statistic=2.0, pvalue=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)
Power_divergenceResult(statistic=array([3.5 , 9.25]), pvalue=array([0.62338763, 0.09949846]))

For a more detailed example, see :ref:`hypothesis_chisquare`.
r  )r
  r  r   r  r  r  )r  r
  r  r   r  s        r   rs   rs     s    ` Ud%.)E Er   KstestResultstatistic_locationstatistic_signc                     [        U 5      n[        R                  " SUS-   5      U-  U -
  nUR                  5       nX   nX4   U4$ )a  Computes D+ as used in the Kolmogorov-Smirnov test.

Parameters
----------
cdfvals : array_like
    Sorted array of CDF values between 0 and 1
x: array_like
    Sorted array of the stochastic variable itself

Returns
-------
res: Pair with the following elements:
    - The maximum distance of the CDF values below Uniform(0, 1).
    - The location at which the maximum is reached.

r   r   r   r   ry  r   )cdfvalsr   r  dplusamaxloc_maxs         r   _compute_dplusr.  Z  sJ    " 	GAYYsAE"Q&0E<<>DgGK!!r   c                     [        U 5      nU [        R                  " SU5      U-  -
  nUR                  5       nX   nX4   U4$ )ay  Computes D- as used in the Kolmogorov-Smirnov test.

Parameters
----------
cdfvals : array_like
    Sorted array of CDF values between 0 and 1
x: array_like
    Sorted array of the stochastic variable itself

Returns
-------
res: Pair with the following elements:
    - Maximum distance of the CDF values above Uniform(0, 1)
    - The location at which the maximum is reached.
r  r)  )r*  r   r  dminusr,  r-  s         r   _compute_dminusr1  r  sF      	GA		#q)!++F==?DgGL'""r   c                     [        XUUS9$ )Nr&  r'  )r%  )r   r   r&  r'  s       r   _tuple_to_KstestResultr4    s    	+='57 7r   c                 <    / U QU R                   PU R                  P7$ r   r3  r  s    r   _KstestResult_to_tupler6    s#    ;C;'';););;;r   )r   r   r   rE   r4  c                    UnSSSS.R                  UR                  5       S   U5      nUS;  a  [        SU< 35      e[        U 5      n[        R
                  " U 5      n U" U /UQ76 n[        R                  " S5      nUS:X  a6  [        Xp5      u  p[        U	[        R                  R                  X5      U
US	9$ US:X  a7  [        Xp5      u  p[        U[        R                  R                  X5      U
U* S	9$ [        Xp5      u  p[        Xp5      u  pX:  a  U	nUn
UnOUnUn
U* nUS
:X  a  SnUS:X  a   [        R                  R                  X5      nO_US:X  a7  [        R                  R                  U[        R                  " U5      -  5      nO"S[        R                  R                  X5      -  n[        R                   " USS5      n[        UUU
US	9$ )aF  
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.
method : {'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
-------
res: KstestResult
    An object containing attributes:

    statistic : float
        KS test statistic, either D+, D-, or D (the maximum of the two)
    pvalue : float
        One-tailed or two-tailed p-value.
    statistic_location : float
        Value of `x` corresponding with the KS statistic; i.e., the
        distance between the empirical distribution function and the
        hypothesized cumulative distribution function is measured at this
        observation.
    statistic_sign : int
        +1 if the KS statistic is the maximum positive difference between
        the empirical distribution function and the hypothesized cumulative
        distribution function (D+); -1 if the KS statistic is the maximum
        negative difference (D-).


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
--------
Suppose we wish to test the null hypothesis that a sample is distributed
according to the standard normal.
We choose a confidence level of 95%; that is, we will reject the null
hypothesis in favor of the alternative if the p-value is less than 0.05.

When testing uniformly distributed data, we would expect the
null hypothesis to be rejected.

>>> import numpy as np
>>> from scipy import stats
>>> rng = np.random.default_rng()
>>> stats.ks_1samp(stats.uniform.rvs(size=100, random_state=rng),
...                stats.norm.cdf)
KstestResult(statistic=0.5001899973268688,
             pvalue=1.1616392184763533e-23,
             statistic_location=0.00047625268963724654,
             statistic_sign=-1)

Indeed, the p-value is lower than our threshold of 0.05, so we reject the
null hypothesis in favor of the default "two-sided" alternative: the data
are *not* distributed according to the standard normal.

When testing random variates from the standard normal distribution, we
expect the data to be consistent with the null hypothesis most of the time.

>>> x = stats.norm.rvs(size=100, random_state=rng)
>>> stats.ks_1samp(x, stats.norm.cdf)
KstestResult(statistic=0.05345882212970396,
             pvalue=0.9227159037744717,
             statistic_location=-1.2451343873745018,
             statistic_sign=1)

As expected, the p-value of 0.92 is not below our threshold of 0.05, so
we cannot reject the null hypothesis.

Suppose, however, that the random variates are distributed according to
a normal distribution that is shifted toward greater values. In this case,
the cumulative density function (CDF) of the underlying distribution tends
to be *less* than the CDF of the standard normal. Therefore, we would
expect the null hypothesis to be rejected with ``alternative='less'``:

>>> x = stats.norm.rvs(size=100, loc=0.5, random_state=rng)
>>> stats.ks_1samp(x, stats.norm.cdf, alternative='less')
KstestResult(statistic=0.17482387821055168,
             pvalue=0.001913921057766743,
             statistic_location=0.3713830565352756,
             statistic_sign=-1)

and indeed, with p-value smaller than our threshold, we reject the null
hypothesis in favor of the alternative.

r  r  r  r  r  r  r   r  r  r  zUnexpected value alternative=r   r3  rL  rZ  asympr   )r7  r  r   r   r   r  int8r.  r%  r   ksoner  r1  kstwo	kstwobignr  r  )r   r  r<  r  r4  rE   Nr*  np_oneDplus
d_locationDminusdplus_locationdminus_locationDd_signro  s                    r   rq   rq     s   F D#)&AEEA-K::9[N;<<AA

A!mdmGWWQZFi*76E=#6#6#9#9%#C/9+13 	3 f,W8FM$7$7$:$:6$E/9,274 	4
 +76E-g9F~#
$
v~w""%%a+	&&))!bggaj.9 =&&))!//774AD4+5'-/ /r   c                     Sn[        [        R                  " X-  5      5      nUS:  aD  Sn[        U5       H  nXU-  -
  U-
  U-  XU-  -   U-   S-   -  nM      USU-
  -  nUS-  nUS:  a  MD  SU-  $ )z
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   r   r  rG  )r  r  Pr  p1r  s         r   _compute_prob_outside_squarerK  M  s    2 	ABHHQUOA
q& qA!e)a-2%UQ):;B #'N	Q q& q5Lr   c                 r   X:  a  XpX-  nX-  nXU-
  U-  -   n[        U5       Vs/ s H  osXG-  -   U-   S-
  U-  PM     nnUS:X  a  [        R                  " X-   U5      $ [        R                  " U5      n	SU	S'   [        SU5       Hd  n[        R                  " X   U-   U5      n
[        U5       H2  n[        R                  " X   X   -
  U-   U-
  X{-
  5      nXX   -  -  n
M4     XU'   Mf     Sn[        U5       H1  n[        R                  " XU   -
  X-
  -   X-
  5      nX   U-  nX-  nM3     U$ s  snf )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.

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.

r   r   )rG  r  binomr   r   )r  r  r  r  mgnglxjr  xjBBjr   bin	num_pathsterms                  r   _count_paths_outside_methodrW  s  sM   T 	u1	
B	
B
 !tbj.C+0:	6:arv:?1r
!:B	6 ax}}QUA&&
AAaD1c]]]2519a(qA-- 1A 5qs;C*B  !  I3ZmmQ!uW/5tcz	  ) 
7s   D4c                 B   X-  U-  n[        [        R                  " X5-  5      5      nUS-  U-  nUS:X  a  SUS4$ S[        R                  p [        R                  " SSS9   US:X  a  X:X  a  [        X5      nO[        XX&5      nOX:X  a7  [        R                  " U5      n	[        R                  " X	-
  X	-   S-   -  5      nOj[        R                  " SS9   [        XX&5      n
S	S	S	5        [        R                  " X-   U 5      nW
U:  d  [        R                  " U5      (       a  SnOX-  nS	S	S	5        U(       a  SU[        R                  4$ SUs=::  a  S
::  d  O  SX84$ SX84$ ! , (       d  f       N= f! , (       d  f       NP= f! [        [        4 a    Sn Ngf = f)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   overr  )rY  Nr   )r   r   rF  r   r   rK  r!   ry  rW  rW  r  rM  isinfFloatingPointErrorOverflowError)r  r  r  r  r  lcmr  saw_fp_errorro  jrangerU  rT  s               r   _attempt_exact_2kssampr`    si    7b.CBHHQWA	C#AAvQ|$[[w7k)87>D<RQJD8  YYq\F77BKBK#4E#FGD'2$?$M	 3!--4C 3"((3--'+() 82 aNNa~= 32 87, . sJ   F	 #A5E8E'%A	E8.F	 '
E5	1E88
FF	 F	 	FFc                    UnUS;  a  [        SU 35      eSSSS.R                  UR                  5       S   U5      nUS;  a  [        S	U 35      eS
n[        R                  R                  U 5      (       a  U R                  5       n [        R                  R                  U5      (       a  UR                  5       n[        R                  " U 5      n [        R                  " U5      nU R                  S   nUR                  S   n[        Xg5      S:X  a  [        S5      e[        R                  " X/5      n[        R                  " XSS9U-  n	[        R                  " XSS9U-  n
X-
  n[        R                  " U5      n[        R                  " U5      nX   nX   n[        R                  " X   * SS5      nX   nUS:X  d  US:X  a  UU:  a  UnUnSnOUnUnSn[        Xg5      nUU-  nUU-  n[        R                   * nUS:X  a  [#        Xg5      U::  a  SOSnO^US:X  aX  U[        R$                  " [        R&                  5      R"                  U-  :  a#  Sn[(        R*                  " SU SU S3[,        SS9  US:X  a9  [/        XgUUU5      u  nnnU(       d   Sn[(        R*                  " SU S3[,        SS9  US:X  a  [1        [3        U5      [3        U5      /SS9u  nnUU-  UU-   -  nUS:X  a5  [4        R6                  R9                  U[        R:                  " U5      5      nOi[        R<                  " U5      U-  nSUS-  -  SU-  USU-  -   -  [        R<                  " UU-  UU-   -  5      -  S-  -
  n[        R>                  " U5      n[        R                  " USS5      n[A        [        RB                  " U5      UU[        RD                  " U5      S9$ ) 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.
method : {'auto', 'exact', 'asymp'}, optional
    Defines the method used for calculating the p-value.
    The following options are available (default is 'auto'):

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

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

    statistic : float
        KS test statistic.
    pvalue : float
        One-tailed or two-tailed p-value.
    statistic_location : float
        Value from `data1` or `data2` corresponding with the KS statistic;
        i.e., the distance between the empirical distribution functions is
        measured at this observation.
    statistic_sign : int
        +1 if the empirical distribution function of `data1` exceeds
        the empirical distribution function of `data2` at
        `statistic_location`, otherwise -1.

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.

- `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. The statistic
  is the magnitude of the minimum (most negative) difference between the
  empirical distribution functions of the samples.

- `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. The statistic
  is the maximum (most positive) difference between the empirical
  distribution functions of the samples.

- `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. The statistic is the maximum absolute difference between the
  empirical distribution functions of the samples.

Note that the alternative hypotheses describe the *CDFs* of the
underlying distributions, not the observed values of the data. 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 large, then the p-value will be small, and this may
be taken as evidence against the null hypothesis in favor of the
alternative.

If ``method='exact'``, `ks_2samp` attempts to compute an exact p-value,
that is, the probability under the null hypothesis of obtaining a test
statistic value as extreme as the value computed from the data.
If ``method='asymp'``, the asymptotic Kolmogorov-Smirnov distribution is
used to compute an approximate p-value.
If ``method='auto'``, an exact p-value computation is attempted if both
sample sizes are less than 10000; otherwise, the asymptotic method is used.
In any case, if an exact p-value calculation is attempted and fails, a
warning will be emitted, and the asymptotic p-value will be returned.

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-486.

Examples
--------
Suppose we wish to test the null hypothesis that two samples were drawn
from the same distribution.
We choose a confidence level of 95%; that is, we will reject the null
hypothesis in favor of the alternative if the p-value is less than 0.05.

If the first sample were drawn from a uniform distribution and the second
were drawn from the standard normal, we would expect the null hypothesis
to be rejected.

>>> import numpy as np
>>> from scipy import stats
>>> rng = np.random.default_rng()
>>> sample1 = stats.uniform.rvs(size=100, random_state=rng)
>>> sample2 = stats.norm.rvs(size=110, random_state=rng)
>>> stats.ks_2samp(sample1, sample2)
KstestResult(statistic=0.5454545454545454,
             pvalue=7.37417839555191e-15,
             statistic_location=-0.014071496412861274,
             statistic_sign=-1)


Indeed, the p-value is lower than our threshold of 0.05, so we reject the
null hypothesis in favor of the default "two-sided" alternative: the data
were *not* drawn from the same distribution.

When both samples are drawn from the same distribution, we expect the data
to be consistent with the null hypothesis most of the time.

>>> sample1 = stats.norm.rvs(size=105, random_state=rng)
>>> sample2 = stats.norm.rvs(size=95, random_state=rng)
>>> stats.ks_2samp(sample1, sample2)
KstestResult(statistic=0.10927318295739348,
             pvalue=0.5438289009927495,
             statistic_location=-0.1670157701848795,
             statistic_sign=-1)

As expected, the p-value of 0.54 is not below our threshold of 0.05, so
we cannot reject the null hypothesis.

Suppose, however, that the first sample were drawn from
a normal distribution shifted toward greater values. In this case,
the cumulative density function (CDF) of the underlying distribution tends
to be *less* than the CDF underlying the second sample. Therefore, we would
expect the null hypothesis to be rejected with ``alternative='less'``:

>>> sample1 = stats.norm.rvs(size=105, loc=0.5, random_state=rng)
>>> stats.ks_2samp(sample1, sample2, alternative='less')
KstestResult(statistic=0.4055137844611529,
             pvalue=3.5474563068855554e-08,
             statistic_location=-0.13249370614972575,
             statistic_sign=-1)

and indeed, with p-value smaller than our threshold, we reject the null
hypothesis in favor of the alternative.

)rL  rZ  r:  zInvalid value for mode: r  r  r  r8  r   )r  r  r  zInvalid value for alternative: i'  z)Data passed to ks_2samp must not be emptyr  )sider   r   rL  rZ  r:  z;Exact ks_2samp calculation not possible with samples sizes z and z. Switching to 'asymp'.rl  r   z>ks_2samp: Exact calculation unsuccessful. Switching to method=rv  T)reverser^  r   r|  r3  )#r   r7  r  r   r   	is_masked
compressedr  r   r"  r  searchsortedargminr   r  r   r!  r   iinforw  r   r   r   r`  r9  r   r   r=  r  rF  r  r   r%  rE  r;  )data1data2r  r4  rE   
MAX_AUTO_Nr  r  data_allcdf1cdf2cddiffsargminSargmaxSloc_minSloc_maxSminSmaxSr  rB  rG  r  n1gn2gro  successr  r  enr,  expts                                  r   rr   rr     s   ~ D--3D6:;;#)&AEEA-K:::;-HIIJ	uuu  "	uuu  "GGENEGGENE	QB	QB
2{aDEE~~un-H??59B>D??59B>DkG ii Gii G H H 77G$$a+DDf!;t

BA
'C
'CFF7Dv~b+3w	"((288$((3..DMMM$eB4689G
 w1"!QLDDMM 115a9:H%&( w uRy%),d;1Ua!e_+% &&))!RXXb\:DaA 19q1uAaC01ac1CCCGGD66$<D774AD 

1t
')wwv8 8r   c                 l   Su  pE[        U [        5      (       a  [        [        U 5      R                  nO[        U 5      (       a  U n[        U[        5      (       a  [        [        U5      R                  nS nO[        U5      (       a  UnS n[        R                  " U(       a  U" USU06OU 5      n XU4$ )Nr  r   )	r   r5  getattrr   r  rM  r  r   r  )ri  rj  r<  r?  rvsfuncr  s         r   _parse_kstest_argsr~    s     LG%-/33	%%mU+//	%GGgGT**5AEr   c                 ^    U S   n[        U[        5      (       d  [        U5      (       a  S$ S$ )Nr  r   r   )r   r5  rM  )r  r  s     r   _kstest_n_samplesr     s*    
-CC%%#1>Q>r   c           	          US:X  a  SnUS;  a  [        SU 35      e[        XX#5      u  pgnU(       a  [        XaX$USS9$ [        XgXESS9$ )a  
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.
method : {'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
-------
res: KstestResult
    An object containing attributes:

    statistic : float
        KS test statistic, either D+, D-, or D (the maximum of the two)
    pvalue : float
        One-tailed or two-tailed p-value.
    statistic_location : float
        In a one-sample test, this is the value of `rvs`
        corresponding with the KS statistic; i.e., the distance between
        the empirical distribution function and the hypothesized cumulative
        distribution function is measured at this observation.

        In a two-sample test, this is the value from `rvs` or `cdf`
        corresponding with the KS statistic; i.e., the distance between
        the empirical distribution functions is measured at this
        observation.
    statistic_sign : int
        In a one-sample test, this is +1 if the KS statistic is the
        maximum positive difference between the empirical distribution
        function and the hypothesized cumulative distribution function
        (D+); it is -1 if the KS statistic is the maximum negative
        difference (D-).

        In a two-sample test, this is +1 if the empirical distribution
        function of `rvs` exceeds the empirical distribution
        function of `cdf` at `statistic_location`, otherwise -1.

See Also
--------
ks_1samp, 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
--------
Suppose we wish to test the null hypothesis that a sample is distributed
according to the standard normal.
We choose a confidence level of 95%; that is, we will reject the null
hypothesis in favor of the alternative if the p-value is less than 0.05.

When testing uniformly distributed data, we would expect the
null hypothesis to be rejected.

>>> import numpy as np
>>> from scipy import stats
>>> rng = np.random.default_rng()
>>> stats.kstest(stats.uniform.rvs(size=100, random_state=rng),
...              stats.norm.cdf)
KstestResult(statistic=0.5001899973268688,
             pvalue=1.1616392184763533e-23,
             statistic_location=0.00047625268963724654,
             statistic_sign=-1)

Indeed, the p-value is lower than our threshold of 0.05, so we reject the
null hypothesis in favor of the default "two-sided" alternative: the data
are *not* distributed according to the standard normal.

When testing random variates from the standard normal distribution, we
expect the data to be consistent with the null hypothesis most of the time.

>>> x = stats.norm.rvs(size=100, random_state=rng)
>>> stats.kstest(x, stats.norm.cdf)
KstestResult(statistic=0.05345882212970396,
             pvalue=0.9227159037744717,
             statistic_location=-1.2451343873745018,
             statistic_sign=1)


As expected, the p-value of 0.92 is not below our threshold of 0.05, so
we cannot reject the null hypothesis.

Suppose, however, that the random variates are distributed according to
a normal distribution that is shifted toward greater values. In this case,
the cumulative density function (CDF) of the underlying distribution tends
to be *less* than the CDF of the standard normal. Therefore, we would
expect the null hypothesis to be rejected with ``alternative='less'``:

>>> x = stats.norm.rvs(size=100, loc=0.5, random_state=rng)
>>> stats.kstest(x, stats.norm.cdf, alternative='less')
KstestResult(statistic=0.17482387821055168,
             pvalue=0.001913921057766743,
             statistic_location=0.3713830565352756,
             statistic_sign=-1)

and indeed, with p-value smaller than our threshold, we reject the null
hypothesis in favor of the alternative.

For convenience, the previous test can be performed using the name of the
distribution as the second argument.

>>> stats.kstest(x, "norm", alternative='less')
KstestResult(statistic=0.17482387821055168,
             pvalue=0.001913921057766743,
             statistic_location=0.3713830565352756,
             statistic_sign=-1)

The examples above have all been one-sample tests identical to those
performed by `ks_1samp`. Note that `kstest` can also perform two-sample
tests identical to those performed by `ks_2samp`. For example, when two
samples are drawn from the same distribution, we expect the data to be
consistent with the null hypothesis most of the time.

>>> sample1 = stats.laplace.rvs(size=105, random_state=rng)
>>> sample2 = stats.laplace.rvs(size=95, random_state=rng)
>>> stats.kstest(sample1, sample2)
KstestResult(statistic=0.11779448621553884,
             pvalue=0.4494256912629795,
             statistic_location=0.6138814275424155,
             statistic_sign=1)

As expected, the p-value of 0.45 is not below our threshold of 0.05, so
we cannot reject the null hypothesis.

	two_sidedr  r9  zUnexpected alternative: T)r<  r  r4  r-  )r  r4  r-  )r   r~  rq   rr   )r  r  r<  r?  r  r4  xvalsyvalss           r   rp   rp      sl    p k!!::3K=ABB*3T=E#
%6 	6Ek!# #r   c                    [         R                  " U 5      n[         R                  " [         R                  SUSS USS :g  S4   5      S   n[         R                  " U5      R                  [         R                  5      n[         R                  " UR                  5      nUS:  a  S$ SUS-  U-
  R                  5       US-  U-
  -  -
  $ )	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   rl  )	r   r  ra  r^  r`  r   rE  r   r  )rankvalsr  r  rT  r   s        r   ru   ru      s    J ''(
C
**RUU4QRCH!4d:;
<Q
?C
''#,

bjj
)C::chhD(3MsAv|&8&8&:dAgn&M MMr   RanksumsResult)r   c                    [        [        R                  X45      u  p[        U 5      n[        U5      n[        R                  " X45      n[        U5      nUSU n [        R                  " U SS9nX3U-   S-   -  S-  nXx-
  [        R                  " X4-  X4-   S-   -  S-  5      -  n	[        U	[        5       U[        S9n
[        U	S   U
S   5      $ )	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.

>>> import numpy as np
>>> 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   ro        (@r   r   )mapr   r   r   r  ry   r  r  r  r  r  )r   r  r  r  r  r  rankedrd  expectedr,  r   s              r   rv   rv      s    H rzzA6"DA	QB	QBnnaV$GgFsA
qqAU1W~#H	
a!566AMO[R@F!B%,,r   KruskalResult)r   c           	         [        [        [        R                  U5      5      n[	        U5      nUS:  a  [        S5      e[        R                  " [        [        [        U5      5      5      n[        R                  " U5      n[        U5      n[        U5      nUS:X  a  [        S5      e[        R                  " [        R                  " U5      SS5      nSn[        U5       H   n	U[        XWU	   XyS-       5      X9   -  -  nM"     [        R                  " U[        S9n
SXS-   -  -  U-  SU
S-   -  -
  nUS-
  nX-  n[        U5      n[!        XS	S
[        S9n[#        X5      $ )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   z$All numbers are identical in kruskalr   r   r  rl  r  Fr  )r_  r  r   r   r   r   r  ry   ru   insertr  rG  r  r  r   r  r  r  )r   r  r  r  r  r  tiesr  r  r   totalnr  r  r  r   s                  r   rw   rw   Q!  sD   F 3rzz7+,GWJA~FGG


4C)*+AnnW%GgFfDqy?@@ 			"))A,1%AD:tAcF 34qt;;  VVAU#F1*%&-VaZ0@@A	aBIAr?Di5RPF##r   FriedmanchisquareResult)r   r   c                     [        U 5      nUS:  a  [        SU S35      e[        U S   5      n[        SU5       H  n[        X   5      U:w  d  M  [        S5      e   [        R                  " U 5      R
                  nUR                  [        5      n[        [        U5      5       H  n[        XC   5      XC'   M     SnU HF  n[        [        R                  " U[        R                  S95      u  pxU H  n	XYX-  S-
  -  -  nM     MH     SXQX-  S-
  -  U-  -  -
  n
[        R                  " UR                  SS9S	-  5      nS
X-  US-   -  -  U-  SU-  US-   -  -
  U
-  n[        US-
  5      n[        XSS[        S9n[        X5      $ )a  Compute the Friedman test for repeated samples.

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

Parameters
----------
sample1, sample2, sample3... : array_like
    Arrays of observations.  All of the arrays must have the same number
    of elements.  At least three samples 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.

See Also
--------
:ref:`hypothesis_friedmanchisquare` : Extended example

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 samples.

References
----------
.. [1] https://en.wikipedia.org/wiki/Friedman_test
.. [2] Demsar, J. (2006). Statistical comparisons of classifiers over
       multiple data sets. Journal of Machine Learning Research, 7, 1-30.

Examples
--------

>>> import numpy as np
>>> rng = np.random.default_rng(seed=18)
>>> x = rng.random((6, 10))
>>> from scipy.stats import friedmanchisquare
>>> res = friedmanchisquare(x[0], x[1], x[2], x[3], x[4], x[5])
>>> res.statistic, res.pvalue
(11.428571428571416, 0.043514520866727614)

The p-value is less than 0.05; however, as noted above, the results may not
be reliable since we have a small number of repeated samples.

For a more detailed example, see :ref:`hypothesis_friedmanchisquare`.
rl  z@At least 3 sets of samples must be given for Friedman test, got rv  r   r   z*Unequal N in friedmanchisquare.  Aborting.r   r   r   r  r  Fr  )r   r   rG  r   r?  Tr   r   ry   r   r   rE  r  r  r  r  )r  r  r  r   r  r  r  r  repnumr  rY  r  r   r  r   s                  r   rx   rx   !  s   r 	GA1u 334#Q8 9 	9 	GAJA1a[wz?aIJJ 
 99WD;;uD3t947#  D!"((1BJJ"?@	AqM!D   	
DqsQwKM""A66$((("A%&Dac#d*QqS!A#Y6!;Iq1uDi5UWXF"955r   BrunnerMunzelResultc                 `   [        U 5      n[        U5      n[        [        R                  " X45      5      nUSU nXuXV-    n	[        R                  " U5      n
[        R                  " U	5      n[        U 5      n[        U5      n[        R                  " U5      n[        R                  " U5      n[        R
                  " [        R                  " X-
  U
-
  U-   S5      5      nUUS-
  -  n[        R
                  " [        R                  " X-
  U-
  U-   S5      5      nUUS-
  -  nXV-  X-
  -  nUXV-   [        R                  " UU-  UU-  -   5      -  -  nUS:X  a  [        R                  " UU-  UU-  -   S5      n[        R                  " UU-  S5      US-
  -  nU[        R                  " UU-  S5      US-
  -  -  nUU-  nUS:X  a"  US:X  a  Sn[        R                  " U[        SS9  [        U5      nOUS:X  a  [        5       nO[        S	5      e[        U* X2[        S
9n[        UU5      $ )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

r   ro  r   r  zp-value cannot be estimated with `distribution='t' because degrees of freedom parameter is undefined (0/0). Try using `distribution='normal'r   r   r0  z&distribution should be 't' or 'normal'r   )r   ry   r   r  r  r  powerr  r   r   r   rA  r  r   r  r  )r   r  r  r  r   nxnyrankcrankcxrankcyrankcx_meanrankcy_meanrankxranky
rankx_mean
ranky_meanSxSywbfndf_numerdf_denomr  r   r   s                           r   r   r   "  s   Z 
QB	QBR^^QF+,E1R[Fbe_F''&/K''&/KQKEQKEJJ	+5
BCH	IB"q&LB	+5
BCH	IB"q&LB7k/0DRWR"r' 1222Ds88BGb2g-s388BGS)R!V4BHHR"Wc*b1f55 MAAG MM'>a@&r*		!$46 	6 	TE<<AtQ''r   )r   r   c                   [        U 5      nUR                  U 5      n [        U 5      S:X  a  [        U 5      n[	        XU5      $ U R
                  U   nUR                  SU R                  S9nUS:X  aA  SUR                  UR                  U 5      US9-  n[        SU-  U-  5      n	[        XSS	US
9n
GOUS:X  aD  SUR                  UR                  U * 5      US9-  n[        SU-  U-  5      n	[        U* U	SS	US
9n
GOuUS:X  a  [        R                  " SU-  5      UR                  -  nUR                  UR                  U 5      US9* UR                  UR                  U * 5      US9-   nSU-  S-   n[        R                  " XS-
  -  5      n[        X-  5      n[        X-  U-  USUS9n
OUS:X  a*  UR!                  XS9n[#        XvU-  5      n[        XSS	US
9n
OUS:X  a  Uc  UR%                  X R                  S9nOUR
                  U   U:w  a  ['        S5      e[)        5       nUR+                  U 5      nUR                  UU-  US9[-        X#S9-  n[        UUSUS9n
O['        SU< S35      e[	        X5      $ )a  
Combine p-values from independent tests that bear upon the same hypothesis.

These methods are intended only for combining p-values from hypothesis
tests based upon continuous distributions.

Each method assumes that under the null hypothesis, the p-values are
sampled independently and uniformly from the interval [0, 1]. A test
statistic (different for each method) is computed and a combined
p-value is calculated based upon the distribution of this test statistic
under the null hypothesis.

Parameters
----------
pvalues : array_like
    Array of p-values assumed to come from independent tests based on
    continuous distributions.
method : {'fisher', 'pearson', 'tippett', 'stouffer', 'mudholkar_george'}

    Name of method to use to combine p-values.

    The available methods are (see Notes for details):

    * 'fisher': Fisher's method (Fisher's combined probability test)
    * 'pearson': Pearson's method
    * 'mudholkar_george': Mudholkar's and George's method
    * 'tippett': Tippett's method
    * 'stouffer': Stouffer's Z-score method
weights : array_like, optional
    Optional array of weights used only for Stouffer's Z-score method.
    Ignored by other methods.

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

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

Examples
--------
Suppose we wish to combine p-values from four independent tests
of the same null hypothesis using Fisher's method (default).

>>> from scipy.stats import combine_pvalues
>>> pvalues = [0.1, 0.05, 0.02, 0.3]
>>> combine_pvalues(pvalues)
SignificanceResult(statistic=20.828626352604235, pvalue=0.007616871850449092)

When the individual p-values carry different weights, consider Stouffer's
method.

>>> weights = [1, 2, 3, 4]
>>> res = combine_pvalues(pvalues, method='stouffer', weights=weights)
>>> res.pvalue
0.009578891494533616

Notes
-----
If this function is applied to tests with a discrete statistics such as
any rank test or contingency-table test, it will yield systematically
wrong results, e.g. Fisher's method will systematically overestimate the
p-value [1]_. This problem becomes less severe for large sample sizes
when the discrete distributions become approximately continuous.

The differences between the methods can be best illustrated by their
statistics and what aspects of a combination of p-values they emphasise
when considering significance [2]_. For example, methods emphasising large
p-values are more sensitive to strong false and true negatives; conversely
methods focussing on small p-values are sensitive to positives.

* The statistics of Fisher's method (also known as Fisher's combined
  probability test) [3]_ is :math:`-2\sum_i \log(p_i)`, which is
  equivalent (as a test statistics) to the product of individual p-values:
  :math:`\prod_i p_i`. Under the null hypothesis, this statistics follows
  a :math:`\chi^2` distribution. This method emphasises small p-values.
* Pearson's method uses :math:`-2\sum_i\log(1-p_i)`, which is equivalent
  to :math:`\prod_i \frac{1}{1-p_i}` [2]_.
  It thus emphasises large p-values.
* Mudholkar and George compromise between Fisher's and Pearson's method by
  averaging their statistics [4]_. Their method emphasises extreme
  p-values, both close to 1 and 0.
* Stouffer's method [5]_ uses Z-scores and the statistic:
  :math:`\sum_i \Phi^{-1} (p_i)`, where :math:`\Phi` is the CDF of the
  standard normal distribution. The advantage of this 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]_.
* Tippett's method uses the smallest p-value as a statistic.
  (Mind that this minimum is not the combined p-value.)

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

.. versionadded:: 0.15.0

References
----------
.. [1] Kincaid, W. M., "The Combination of Tests Based on Discrete
       Distributions." Journal of the American Statistical Association 57,
       no. 297 (1962), 10-19.
.. [2] Heard, N. and Rubin-Delanchey, P. "Choosing between methods of
       combining p-values."  Biometrika 105.1 (2018): 239-246.
.. [3] https://en.wikipedia.org/wiki/Fisher%27s_method
.. [4] George, E. O., and G. S. Mudholkar. "On the convolution of logistic
       random variables." Metrika 30.1 (1983): 1-13.
.. [5] https://en.wikipedia.org/wiki/Fisher%27s_method#Relation_to_Stouffer.27s_Z-score_method
.. [6] 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.
.. [7] 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.
.. [8] https://en.wikipedia.org/wiki/Extensions_of_Fisher%27s_method

r   r   r   r}  r^  r   r   r  Fr  r  r  mudholkar_georgerl  rS  r{  )r  r   tippettstoufferz<pvalues and weights must be of the same length along `axis`.zInvalid method zV. Valid methods are 'fisher', 'pearson', 'mudholkar_george', 'tippett', and 'stouffer')r8   r   r:   r   r   r   r   r  r   r  r  log1pr  r  pirA  r"  r  r  r   r  isfr=   )r  r4  r   r   r   r   r  r
  r   r  pvalnormalizing_factornuapprox_factorr  betanormZis                     r   rz   rz   "  s   t 
	!Bjj!Gw1 w!#++dA
**Qgmm*
,Cwd;;	1Q3s7#9	%*r3	9	rxx1==	1Q3s7#I:t5UWX	%	%!YYqs^BEE1ffRVVG_4f88vvbhhx0tv<=	qSAX		"Q-0BF#99MI1'0R9	9	FF7F.	3#&9%TVW	:	?ll7--l@G]]4 A% 4 5 5 XXg VVGbLtV4%g9:	9d	bI fZ (G G
 	

 i..r   c                       \ rS rSr% Sr\\S'   \\S'   \\S'   \" SS9r	\
\   \S'   \" SS9r\R                  \S	'   \" SS9r\\S
'   SS jrSrg)QuantileTestResultiA#  aO  
Result of `scipy.stats.quantile_test`.

Attributes
----------
statistic: float
    The statistic used to calculate the p-value; either ``T1``, the
    number of observations less than or equal to the hypothesized quantile,
    or ``T2``, the number of observations strictly less than the
    hypothesized quantile. Two test statistics are required to handle the
    possibility the data was generated from a discrete or mixed
    distribution.

statistic_type : int
    ``1`` or ``2`` depending on which of ``T1`` or ``T2`` was used to
    calculate the p-value respectively. ``T1`` corresponds to the
    ``"greater"`` alternative hypothesis and ``T2`` to the ``"less"``.  For
    the ``"two-sided"`` case, the statistic type that leads to smallest
    p-value is used.  For significant tests, ``statistic_type = 1`` means
    there is evidence that the population quantile is significantly greater
    than the hypothesized value and ``statistic_type = 2`` means there is
    evidence that it is significantly less than the hypothesized value.

pvalue : float
    The p-value of the hypothesis test.
r   statistic_typer   F)rN  r  r  _pc                 t   U R                   nU R                  n[        R                  " U R                  5      n[        U5      n[        R                  " XS5      nUS::  d  US:  a  Sn[        U5      e[        R                  n[        R                  n	US:X  aJ  SU-
  n[        R                  * n
[        UR                  U5      5      n	X:  a  XI   O[        R                  nOUS:X  aM  SU-
  n[        UR                  U5      5      S-
  nUS:  a  XH   O[        R                  n
[        R                  nOxUS:X  ar  SU-
  S-  n[        UR                  U5      5      S-
  nUS:  a  XH   O[        R                  n
[        UR                  U5      5      n	X:  a  XI   O[        R                  n[        W
W5      $ )aq  
Compute the confidence interval of the quantile.

Parameters
----------
confidence_level : float, default: 0.95
    Confidence level for the computed confidence interval
    of the quantile. Default is 0.95.

Returns
-------
ci : ``ConfidenceInterval`` object
    The object has attributes ``low`` and ``high`` that hold the
    lower and upper bounds of the confidence interval.

Examples
--------
>>> import numpy as np
>>> import scipy.stats as stats
>>> p = 0.75  # quantile of interest
>>> q = 0  # hypothesized value of the quantile
>>> x = np.exp(np.arange(0, 1.01, 0.01))
>>> res = stats.quantile_test(x, q=q, p=p, alternative='less')
>>> lb, ub = res.confidence_interval()
>>> lb, ub
(-inf, 2.293318740264183)
>>> res = stats.quantile_test(x, q=q, p=p, alternative='two-sided')
>>> lb, ub = res.confidence_interval(0.9)
>>> lb, ub
(1.9542373206359396, 2.293318740264183)
r   r   r  r  r  r  r   )r  r  r   r  r  r   r4   rM  r   r   r!  r   r  ppfr  )r  r  r  r   r   r  bdr   	low_index
high_indexrW  rX  s               r   r  &QuantileTestResult.confidence_intervald#  si   B ''GGGGDGGF[[q $4$9LGW%%FF	VV
& $$A66'CRVVAYJ$.N1=DI%$$ABFF1I*I"+q.!,bffC66DK'%%*ABFF1I*I"+q.!,bffCRVVAYJ$.N1=D!#t,,r   r   Nr  )r  r  r  r  r  r   r  r   r   r  r_  r5  r  r   r  r  r  r  r   r   r   r  r  A#  sT    4 M#/L$s)/'B'E"B"?-r   r  c                 b   [         R                  " U 5      n SnU R                  S:w  d4  [         R                  " U R                  [         R
                  5      (       d  [        U5      e[         R                  " U5      S   nSnUR                  S:w  d4  [         R                  " UR                  [         R
                  5      (       d  [        U5      e[         R                  " U5      S   nSnUR                  S:w  d  US:  d  US::  a  [        U5      e1 SknSU 3nX5;  a  [        U5      eXX#4$ )	Nz/`x` must be a one-dimensional array of numbers.r   r   z`q` must be a scalar.r   z-`p` must be a float strictly between 0 and 1.>   r  r  r  z`alternative` must be one of )r   r   r   r   r   r   r   r   )r   qr   r  r   alternativess         r   quantile_test_ivr  #  s    
aA?Gvv{"--;;!!
BA%Gvv{"--;;!!
BA=Gvv{a1fQ!!3L-l^<G&!!r   )r  r   r  c          	         [        XX#5      u  pEpgXE:*  R                  5       nXE:  R                  5       n	[        U5      n
[        R                  " XS9nUS:X  a  UR                  U	S-
  5      nU	nSnOUS:X  a  UR                  U5      nUnSnOsUS:X  am  UR                  U5      UR                  U	S-
  5      /n[        R                  " U5      n[        R                  " SUUS      -  SS5      nUS   (       a  U	SpOUSp[        WWWUUUS9$ )	am+  
Perform a quantile test and compute a confidence interval of the quantile.

This function tests the null hypothesis that `q` is the value of the
quantile associated with probability `p` of the population underlying
sample `x`. For example, with default parameters, it tests that the
median of the population underlying `x` is zero. The function returns an
object including the test statistic, a p-value, and a method for computing
the confidence interval around the quantile.

Parameters
----------
x : array_like
    A one-dimensional sample.
q : float, default: 0
    The hypothesized value of the quantile.
p : float, default: 0.5
    The probability associated with the quantile; i.e. the proportion of
    the population less than `q` is `p`. Must be strictly between 0 and
    1.
alternative : {'two-sided', 'less', 'greater'}, optional
    Defines the alternative hypothesis.
    The following options are available (default is 'two-sided'):

    * 'two-sided': the quantile associated with the probability `p`
      is not `q`.
    * 'less': the quantile associated with the probability `p` is less
      than `q`.
    * 'greater': the quantile associated with the probability `p` is
      greater than `q`.

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

    statistic : float
        One of two test statistics that may be used in the quantile test.
        The first test statistic, ``T1``, is the proportion of samples in
        `x` that are less than or equal to the hypothesized quantile
        `q`. The second test statistic, ``T2``, is the proportion of
        samples in `x` that are strictly less than the hypothesized
        quantile `q`.

        When ``alternative = 'greater'``, ``T1`` is used to calculate the
        p-value and ``statistic`` is set to ``T1``.

        When ``alternative = 'less'``, ``T2`` is used to calculate the
        p-value and ``statistic`` is set to ``T2``.

        When ``alternative = 'two-sided'``, both ``T1`` and ``T2`` are
        considered, and the one that leads to the smallest p-value is used.

    statistic_type : int
        Either `1` or `2` depending on which of ``T1`` or ``T2`` was
        used to calculate the p-value.

    pvalue : float
        The p-value associated with the given alternative.

    The object also has the following method:

    confidence_interval(confidence_level=0.95)
        Computes a confidence interval around the the
        population quantile associated with the probability `p`. The
        confidence interval is returned in a ``namedtuple`` with
        fields `low` and `high`.  Values are `nan` when there are
        not enough observations to compute the confidence interval at
        the desired confidence.

Notes
-----
This test and its method for computing confidence intervals are
non-parametric. They are valid if and only if the observations are i.i.d.

The implementation of the test follows Conover [1]_. Two test statistics
are considered.

``T1``: The number of observations in `x` less than or equal to `q`.

    ``T1 = (x <= q).sum()``

``T2``: The number of observations in `x` strictly less than `q`.

    ``T2 = (x < q).sum()``

The use of two test statistics is necessary to handle the possibility that
`x` was generated from a discrete or mixed distribution.

The null hypothesis for the test is:

    H0: The :math:`p^{\mathrm{th}}` population quantile is `q`.

and the null distribution for each test statistic is
:math:`\mathrm{binom}\left(n, p\right)`. When ``alternative='less'``,
the alternative hypothesis is:

    H1: The :math:`p^{\mathrm{th}}` population quantile is less than `q`.

and the p-value is the probability that the binomial random variable

.. math::
    Y \sim \mathrm{binom}\left(n, p\right)

is greater than or equal to the observed value ``T2``.

When ``alternative='greater'``, the alternative hypothesis is:

    H1: The :math:`p^{\mathrm{th}}` population quantile is greater than `q`

and the p-value is the probability that the binomial random variable Y
is less than or equal to the observed value ``T1``.

When ``alternative='two-sided'``, the alternative hypothesis is

    H1: `q` is not the :math:`p^{\mathrm{th}}` population quantile.

and the p-value is twice the smaller of the p-values for the ``'less'``
and ``'greater'`` cases. Both of these p-values can exceed 0.5 for the same
data, so the value is clipped into the interval :math:`[0, 1]`.

The approach for confidence intervals is attributed to Thompson [2]_ and
later proven to be applicable to any set of i.i.d. samples [3]_. The
computation is based on the observation that the probability of a quantile
:math:`q` to be larger than any observations :math:`x_m (1\leq m \leq N)`
can be computed as

.. math::

    \mathbb{P}(x_m \leq q) = 1 - \sum_{k=0}^{m-1} \binom{N}{k}
    q^k(1-q)^{N-k}

By default, confidence intervals are computed for a 95% confidence level.
A common interpretation of a 95% confidence intervals is that if i.i.d.
samples are drawn repeatedly from the same population and confidence
intervals are formed each time, the confidence interval will contain the
true value of the specified quantile in approximately 95% of trials.

A similar function is available in the QuantileNPCI R package [4]_. The
foundation is the same, but it computes the confidence interval bounds by
doing interpolations between the sample values, whereas this function uses
only sample values as bounds. Thus, ``quantile_test.confidence_interval``
returns more conservative intervals (i.e., larger).

The same computation of confidence intervals for quantiles is included in
the confintr package [5]_.

Two-sided confidence intervals are not guaranteed to be optimal; i.e.,
there may exist a tighter interval that may contain the quantile of
interest with probability larger than the confidence level.
Without further assumption on the samples (e.g., the nature of the
underlying distribution), the one-sided intervals are optimally tight.

References
----------
.. [1] W. J. Conover. Practical Nonparametric Statistics, 3rd Ed. 1999.
.. [2] W. R. Thompson, "On Confidence Ranges for the Median and Other
   Expectation Distributions for Populations of Unknown Distribution
   Form," The Annals of Mathematical Statistics, vol. 7, no. 3,
   pp. 122-128, 1936, Accessed: Sep. 18, 2019. [Online]. Available:
   https://www.jstor.org/stable/2957563.
.. [3] H. A. David and H. N. Nagaraja, "Order Statistics in Nonparametric
   Inference" in Order Statistics, John Wiley & Sons, Ltd, 2005, pp.
   159-170. Available:
   https://onlinelibrary.wiley.com/doi/10.1002/0471722162.ch7.
.. [4] N. Hutson, A. Hutson, L. Yan, "QuantileNPCI: Nonparametric
   Confidence Intervals for Quantiles," R package,
   https://cran.r-project.org/package=QuantileNPCI
.. [5] M. Mayer, "confintr: Confidence Intervals," R package,
   https://cran.r-project.org/package=confintr


Examples
--------

Suppose we wish to test the null hypothesis that the median of a population
is equal to 0.5. We choose a confidence level of 99%; that is, we will
reject the null hypothesis in favor of the alternative if the p-value is
less than 0.01.

When testing random variates from the standard uniform distribution, which
has a median of 0.5, we expect the data to be consistent with the null
hypothesis most of the time.

>>> import numpy as np
>>> from scipy import stats
>>> rng = np.random.default_rng(6981396440634228121)
>>> rvs = stats.uniform.rvs(size=100, random_state=rng)
>>> stats.quantile_test(rvs, q=0.5, p=0.5)
QuantileTestResult(statistic=45, statistic_type=1, pvalue=0.36820161732669576)

As expected, the p-value is not below our threshold of 0.01, so
we cannot reject the null hypothesis.

When testing data from the standard *normal* distribution, which has a
median of 0, we would expect the null hypothesis to be rejected.

>>> rvs = stats.norm.rvs(size=100, random_state=rng)
>>> stats.quantile_test(rvs, q=0.5, p=0.5)
QuantileTestResult(statistic=67, statistic_type=2, pvalue=0.0008737198369123724)

Indeed, the p-value is lower than our threshold of 0.01, so we reject the
null hypothesis in favor of the default "two-sided" alternative: the median
of the population is *not* equal to 0.5.

However, suppose we were to test the null hypothesis against the
one-sided alternative that the median of the population is *greater* than
0.5. Since the median of the standard normal is less than 0.5, we would not
expect the null hypothesis to be rejected.

>>> stats.quantile_test(rvs, q=0.5, p=0.5, alternative='greater')
QuantileTestResult(statistic=67, statistic_type=1, pvalue=0.9997956114162866)

Unsurprisingly, with a p-value greater than our threshold, we would not
reject the null hypothesis in favor of the chosen alternative.

The quantile test can be used for any quantile, not only the median. For
example, we can test whether the third quartile of the distribution
underlying the sample is greater than 0.6.

>>> rvs = stats.uniform.rvs(size=100, random_state=rng)
>>> stats.quantile_test(rvs, q=0.6, p=0.75, alternative='greater')
QuantileTestResult(statistic=64, statistic_type=1, pvalue=0.00940696592998271)

The p-value is lower than the threshold. We reject the null hypothesis in
favor of the alternative: the third quartile of the distribution underlying
our sample is greater than 0.6.

`quantile_test` can also compute confidence intervals for any quantile.

>>> rvs = stats.norm.rvs(size=100, random_state=rng)
>>> res = stats.quantile_test(rvs, q=0.6, p=0.75)
>>> ci = res.confidence_interval(confidence_level=0.95)
>>> ci
ConfidenceInterval(low=0.284491604437432, high=0.8912531024914844)

When testing a one-sided alternative, the confidence interval contains
all observations such that if passed as `q`, the p-value of the
test would be greater than 0.05, and therefore the null hypothesis
would not be rejected. For example:

>>> rvs.sort()
>>> q, p, alpha = 0.6, 0.75, 0.95
>>> res = stats.quantile_test(rvs, q=q, p=p, alternative='less')
>>> ci = res.confidence_interval(confidence_level=alpha)
>>> for x in rvs[rvs <= ci.high]:
...     res = stats.quantile_test(rvs, q=x, p=p, alternative='less')
...     assert res.pvalue > 1-alpha
>>> for x in rvs[rvs > ci.high]:
...     res = stats.quantile_test(rvs, q=x, p=p, alternative='less')
...     assert res.pvalue < 1-alpha

Also, if a 95% confidence interval is repeatedly generated for random
samples, the confidence interval will contain the true quantile value in
approximately 95% of replications.

>>> dist = stats.rayleigh() # our "unknown" distribution
>>> p = 0.2
>>> true_stat = dist.ppf(p) # the true value of the statistic
>>> n_trials = 1000
>>> quantile_ci_contains_true_stat = 0
>>> for i in range(n_trials):
...     data = dist.rvs(size=100, random_state=rng)
...     res = stats.quantile_test(data, p=p)
...     ci = res.confidence_interval(0.95)
...     if ci[0] < true_stat < ci[1]:
...         quantile_ci_contains_true_stat += 1
>>> quantile_ci_contains_true_stat >= 950
True

This works with any distribution and any quantile, as long as the samples
are i.i.d.
)r  r   r  r   r   r  r  r   )r   r  r   r  r  r  )r  r  r   r4   rM  r  r  r   r]  r  r  )r   r  r   r  r,  x_starp_starH1T1T2r  Yr   r   r  r  
sorted_idxs                    r   r{   r{   #  s!   l -Q1BAv
 +			B
*			B 	AAa"A 
V| bd		y r		{	 559add26l+ZZ(
7:a=111a8a=(*A~(*A~% r   c                 r   [        U 5      [        U5      pT[        U 5      n [        U5      nU R                  S:  d  UR                  S:  a  [        S5      eU R                  UR                  :w  a  [        S5      eU R                  S:X  a  UR                  S:X  a  [	        SXX#5      $ [        X5      u  p[        X5      u  pU R                  S   UR                  S   :w  a  [        S5      e[        R                  " [        R                  " U 5      5      [        R                  " [        R                  " U5      5      -  (       a  [        R                  $ [        R                  " [        R                  " U 5      5      (       a?  [        R                  " [        R                  " U5      5      (       a  [        R                  $ [        R                  " [        R                  " SU45      4U-  5      n[        R                  " [        R                   " U5      4U-  5      n[        R"                  " Xg45      n[        R$                  " U5      n['        XSS9n	U	R)                  5       n
Uc  [        R*                  " USU-  5      OU[        R,                  " U5      -  nUc  [        R*                  " USU-  5      OU[        R,                  " U5      -  n[        R.                  " X4SS9n[1        UR2                  U
S	9n[5        U* U[        R                  * [        R                  4S
9nUR6                  * $ )uz  
Compute the Wasserstein-1 distance between two N-D discrete distributions.

The Wasserstein distance, also called the Earth mover's distance or the
optimal transport distance, is a similarity metric between two probability
distributions [1]_. In the discrete case, the Wasserstein distance can be
understood as the cost of an optimal transport plan to convert one
distribution into the other. The cost is calculated as the product of the
amount of probability mass being moved and the distance it is being moved.
A brief and intuitive introduction can be found at [2]_.

.. versionadded:: 1.13.0

Parameters
----------
u_values : 2d array_like
    A sample from a probability distribution or the support (set of all
    possible values) of a probability distribution. Each element along
    axis 0 is an observation or possible value, and axis 1 represents the
    dimensionality of the distribution; i.e., each row is a vector
    observation or possible value.

v_values : 2d array_like
    A sample from or the support of a second distribution.

u_weights, v_weights : 1d array_like, optional
    Weights or counts corresponding with the sample or probability masses
    corresponding with the support values. Sum of elements must be positive
    and finite. If unspecified, each value is assigned the same weight.

Returns
-------
distance : float
    The computed distance between the distributions.

Notes
-----
Given two probability mass functions, :math:`u`
and :math:`v`, the first Wasserstein distance between the distributions
using the Euclidean norm is:

.. math::

    l_1 (u, v) = \inf_{\pi \in \Gamma (u, v)} \int \| x-y \|_2 \mathrm{d} \pi (x, y)

where :math:`\Gamma (u, v)` is the set of (probability) distributions on
:math:`\mathbb{R}^n \times \mathbb{R}^n` whose marginals are :math:`u` and
:math:`v` on the first and second factors respectively. For a given value
:math:`x`, :math:`u(x)` gives the probability of :math:`u` at position
:math:`x`, and the same for :math:`v(x)`.

This is also called the optimal transport problem or the Monge problem.
Let the finite point sets :math:`\{x_i\}` and :math:`\{y_j\}` denote
the support set of probability mass function :math:`u` and :math:`v`
respectively. The Monge problem can be expressed as follows,

Let :math:`\Gamma` denote the transport plan, :math:`D` denote the
distance matrix and,

.. math::

    x = \text{vec}(\Gamma)          \\
    c = \text{vec}(D)               \\
    b = \begin{bmatrix}
            u\\
            v\\
        \end{bmatrix}

The :math:`\text{vec}()` function denotes the Vectorization function
that transforms a matrix into a column vector by vertically stacking
the columns of the matrix.
The transport plan :math:`\Gamma` is a matrix :math:`[\gamma_{ij}]` in
which :math:`\gamma_{ij}` is a positive value representing the amount of
probability mass transported from :math:`u(x_i)` to :math:`v(y_i)`.
Summing over the rows of :math:`\Gamma` should give the source distribution
:math:`u` : :math:`\sum_j \gamma_{ij} = u(x_i)` holds for all :math:`i`
and summing over the columns of :math:`\Gamma` should give the target
distribution :math:`v`: :math:`\sum_i \gamma_{ij} = v(y_j)` holds for all
:math:`j`.
The distance matrix :math:`D` is a matrix :math:`[d_{ij}]`, in which
:math:`d_{ij} = d(x_i, y_j)`.

Given :math:`\Gamma`, :math:`D`, :math:`b`, the Monge problem can be
transformed into a linear programming problem by
taking :math:`A x = b` as constraints and :math:`z = c^T x` as minimization
target (sum of costs) , where matrix :math:`A` has the form

.. math::

    \begin{array} {rrrr|rrrr|r|rrrr}
        1 & 1 & \dots & 1 & 0 & 0 & \dots & 0 & \dots & 0 & 0 & \dots &
            0 \cr
        0 & 0 & \dots & 0 & 1 & 1 & \dots & 1 & \dots & 0 & 0 &\dots &
            0 \cr
        \vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \ddots
            & \vdots & \vdots & \vdots & \vdots & \ddots & \vdots  \cr
        0 & 0 & \dots & 0 & 0 & 0 & \dots & 0 & \dots & 1 & 1 & \dots &
            1 \cr \hline

        1 & 0 & \dots & 0 & 1 & 0 & \dots & \dots & \dots & 1 & 0 & \dots &
            0 \cr
        0 & 1 & \dots & 0 & 0 & 1 & \dots & \dots & \dots & 0 & 1 & \dots &
            0 \cr
        \vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \ddots &
            \vdots & \vdots & \vdots & \vdots & \ddots & \vdots \cr
        0 & 0 & \dots & 1 & 0 & 0 & \dots & 1 & \dots & 0 & 0 & \dots & 1
    \end{array}

By solving the dual form of the above linear programming problem (with
solution :math:`y^*`), the Wasserstein distance :math:`l_1 (u, v)` can
be computed as :math:`b^T y^*`.

The above solution is inspired by Vincent Herrmann's blog [3]_ . For a
more thorough explanation, see [4]_ .

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] Lili Weng, "What is Wasserstein distance?", Lil'log,
       https://lilianweng.github.io/posts/2017-08-20-gan/#what-is-wasserstein-distance.
.. [3] Hermann, Vincent. "Wasserstein GAN and the Kantorovich-Rubinstein
       Duality". https://vincentherrmann.github.io/blog/wasserstein/.
.. [4] Peyré, Gabriel, and Marco Cuturi. "Computational optimal
       transport." Center for Research in Economics and Statistics
       Working Papers 2017-86 (2017).

See Also
--------
wasserstein_distance: Compute the Wasserstein-1 distance between two
    1D discrete distributions.

Examples
--------
Compute the Wasserstein distance between two three-dimensional samples,
each with two observations.

>>> from scipy.stats import wasserstein_distance_nd
>>> wasserstein_distance_nd([[0, 2, 3], [1, 2, 5]], [[3, 2, 3], [4, 2, 5]])
3.0

Compute the Wasserstein distance between two two-dimensional distributions
with three and two weighted observations, respectively.

>>> wasserstein_distance_nd([[0, 2.75], [2, 209.3], [0, 0]],
...                      [[0.2, 0.322], [4.5, 25.1808]],
...                      [0.4, 5.2, 0.114], [0.8, 1.5])
174.15840245217169
r   zHInvalid input values. The inputs must have either one or two dimensions.z9Invalid input values. Dimensions of inputs must be equal.r   ziInvalid input values. If two-dimensional, `u_values` and `v_values` must have the same number of columns.)r   r   r   )r  ub)rY  constraintsbounds)r   r   r   r   _cdf_distance_validate_distributionr   r   r   rZ  r!  r   r	   
block_diagr`  hstackeyer?  	coo_arrayr
   r   r  r  r  r   r  r   fun)u_valuesv_values	u_weights	v_weightsr  r  A_upper_partA_lower_partr  rF  costp_up_vr   r  opt_ress                   r   r}   r}   %  sq   v x=#h-qx Hx H}}qHMMA- 2 3 	3 }}% " # 	# }}hmmq0QIII0EH0EH~~aHNN1-- . / 	/
 
vvbhhx !BFF288H+=$>>vv	"	#	#rxx/A(B(Bvv $$bggq!fo%81%<=L==&**Q-!2Q!67L|23AA 	a0A779D '."''!QqS/IbffY>O4OC&."''!QqS/IbffY>O4OC
z*A #QSST2KaR[266'2669JKGKK<r   c                     [        SXX#5      $ )a|  
Compute the Wasserstein-1 distance between two 1D discrete distributions.

The Wasserstein distance, also called the Earth mover's distance or the
optimal transport distance, is a similarity metric between two probability
distributions [1]_. In the discrete case, the Wasserstein distance can be
understood as the cost of an optimal transport plan to convert one
distribution into the other. The cost is calculated as the product of the
amount of probability mass being moved and the distance it is being moved.
A brief and intuitive introduction can be found at [2]_.

.. versionadded:: 1.0.0

Parameters
----------
u_values : 1d array_like
    A sample from a probability distribution or the support (set of all
    possible values) of a probability distribution. Each element is an
    observation or possible value.

v_values : 1d array_like
    A sample from or the support of a second distribution.

u_weights, v_weights : 1d array_like, optional
    Weights or counts corresponding with the sample or probability masses
    corresponding with the support values. Sum of elements must be positive
    and finite. If unspecified, each value is assigned the same weight.

Returns
-------
distance : float
    The computed distance between the distributions.

Notes
-----
Given two 1D probability mass functions, :math:`u` and :math:`v`, the first
Wasserstein distance between the distributions 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. For a given value
:math:`x`, :math:`u(x)` gives the probability of :math:`u` at position
:math:`x`, and the same for :math:`v(x)`.

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 [3]_ 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] Lili Weng, "What is Wasserstein distance?", Lil'log,
       https://lilianweng.github.io/posts/2017-08-20-gan/#what-is-wasserstein-distance.
.. [3] Ramdas, Garcia, Cuturi "On Wasserstein Two Sample Testing and Related
       Families of Nonparametric Tests" (2015). :arXiv:`1509.02237`.

See Also
--------
wasserstein_distance_nd: Compute the Wasserstein-1 distance between two N-D
    discrete distributions.

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   )r  r  r  r  r  s       r   r|   r|   %  s    r H	EEr   c                 J    [         R                  " S5      [        SXX#5      -  $ )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`).

Sometimes the square of this quantity is referred to as the "energy
distance" (e.g. in [2]_, [4]_), but as noted in [1]_ and [3]_, only the
definition above satisfies the axioms of a distance function (metric).

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] Rizzo, Szekely "Energy distance." Wiley Interdisciplinary Reviews:
       Computational Statistics, 8(1):27-38 (2015).
.. [2] Szekely "E-statistics: The energy of statistical samples." Bowling
       Green State University, Department of Mathematics and Statistics,
       Technical Report 02-16 (2002).
.. [3] "Energy distance", https://en.wikipedia.org/wiki/Energy_distance
.. [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   )r   r  r  r  s       r   r~   r~   ;&  s(    d 771:a&/< < <r   c                    [        X5      u  p[        X$5      u  p$[        R                  " U5      n[        R                  " U5      n[        R                  " X45      nUR	                  SS9  [        R
                  " U5      nX   R                  USS S5      n	X&   R                  USS S5      n
Uc  XR                  -  nO9[        R                  " S/[        R                  " X5   5      45      nX   US   -  nUc  XR                  -  nO9[        R                  " S/[        R                  " XF   5      45      nX   US   -  nU S:X  aA  [        R                  " [        R                  " [        R                  " X-
  5      U5      5      $ U S:X  aU  [        R                  " [        R                  " [        R                  " [        R                  " X-
  5      U5      5      5      $ [        R                  " [        R                  " [        R                  " [        R                  " [        R                  " X-
  5      U 5      U5      5      SU -  5      $ )	ay  
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`.

rW  rX  Nr   r  r   r   r   )r  r   r]  r  r  r`  rf  r   r  r  multiplyrV  r  squarer  )r   r  r  r  r  u_sorterv_sorter
all_valuesdeltasu_cdf_indicesv_cdf_indicesu_cdfu_sorted_cumweightsv_cdfv_sorted_cumweightss                  r   r  r  &  s   X 1EH0EHzz(#Hzz(#H 45JOOO% WWZ F &33JsOWMM&33JsOWMM - nnqc.0ii	8K.L.N O#25H5LL- nnqc.0ii	8K.L.N O#25H5LL
 	Avvvbkk"&&"7@AAAvwwrvvbkk"))EM*BFKLMM88BFF2;;rxxu}0Eq'I'-/ 01216 6r   c                    [         R                  " U [        S9n [        U 5      S:X  a  [	        S5      eUb  [         R                  " U[        S9n[        U5      [        U 5      :w  a  [	        S5      e[         R
                  " US:  5      (       a  [	        S5      eS[         R                  " U5      s=:  a  [         R                  :  d  O  [	        S5      eX4$ U S4$ )ae  
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.)r   r   r   r   r   r   r  r!  )valuesr   s     r   r  r  &  s    * ZZe,F
6{a788 **WE2w<3v;& P Q Q66'A+@AA266'?+RVV+ ' ( ( 4<r   RepeatedResults)r  r   z`scipy.stats.find_repeats` is deprecated as of SciPy 1.15.0 and will be removed in SciPy 1.17.0. Please use `numpy.unique`/`numpy.unique_counts` instead.c           	      f    [        [        [        R                  " U [        R                  S95      6 $ )av  Find repeats and repeat counts.

.. deprecated:: 1.15.0

    This function is deprecated as of SciPy 1.15.0 and will be removed
    in SciPy 1.17.0. Please use `numpy.unique` / `numpy.unique_counts` instead.

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   r   r   rE  )r  s    r   rA   rA   '  s$    P M"((3bjj*IJKKr   c                 N    [        X5      u  p[        R                  " X -  U5      $ )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   r   r  )r   r   s     r   r  r  E'  s#    , 1#GA66!#tr   c                     [        X5      u  p[        R                  " X5      n[        R                  " U5      (       d  UR	                  [
        5      U-  $ [        U5      U-  $ )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`).

)r   r   r  r  r   r   )r   r   rd  s      r   r  r  _'  sK    * 1#GA
qA;;q>>xx""Qx!|r   )r   r   c                   SnX;  a  [        SU S35      e[        R                  " U 5      nUc  UR                  5       nSnUR                  S:X  aA  US:X  a  [
        O[        R                  " S5      n[        R                  " UR                  US9$ [        XS5      u  ps[        R                  " XRS5      n[        XQ5      nU(       ae  US	:X  a  [        R                  " U5      O"[        R                  " U5      R                  SS
9n	UR                  [
        SS9n[        R                  X'   [        R                  " XS5      nU$ )ai  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.
nan_policy : {'propagate', 'omit', 'raise'}, optional
    Defines how to handle when input contains nan.
    The following options are available (default is 'propagate'):

      * 'propagate': propagates nans through the rank calculation
      * 'omit': performs the calculations ignoring nan values
      * 'raise': raises an error

    .. note::

        When `nan_policy` is 'propagate', the output is an array of *all*
        nans because ranks relative to nans in the input are undefined.
        When `nan_policy` is 'omit', nans in `a` are ignored when ranking
        the other values, and the corresponding locations of the output
        are nan.

    .. versionadded:: 1.10

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
--------
>>> import numpy as np
>>> 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. ]])
>>> rankdata([0, 2, 3, np.nan, -2, np.nan], nan_policy="propagate")
array([nan, nan, nan, nan, nan, nan])
>>> rankdata([0, 2, 3, np.nan, -2, np.nan], nan_policy="omit")
array([ 2.,  3.,  4., nan,  1., nan])

)averager"  r   denseordinalzunknown method ""r   r   r  longr   r  r   Fr   )r   r   r   r   r   r   r   emptyr   r   swapaxes	_rankdatar   r   r   r   )
r   r4  r   r   methodsr   r   r  rS  i_nans
             r   ry   ry   |'  s   n <G+F81566


1A|GGIvv{9,"((62Bxxu--,Q;L
AR Aa E *f 4!hhqkoo2o. 	U/vvKKR(ELr   c                     [         R                  " UR                  U R                  S9n[         R                  " X!U SS9  U$ )Nr   r   r   )r   r  r   r   put_along_axis)rS  r  ordered_rankss      r   _order_ranksr  '  s2    HHQWWEKK8MmB7r   c                    U R                   nUS:X  a  SOSn[        R                  " U SUS9n[        R                  " [        R                  " SUS   S-   [
        S9U5      nUS:X  a  [        Xe5      $ [        R                  " XSS9n[        R                  " [        R                  " US S S	-   [        R                  S9US
S S24   US
SS 24   :g  /SS9n[        R                  " UR                  5      UR                  5          n	[        R                  " XR                  S9n
US:X  a  Xh   nOCUS:X  a  Xh   U
-   S-
  nO2US:X  a  Xh   U
S-
  S-  -   nOUS:X  a  [        R                  " USS9U   n[        R                  " WU
5      R!                  U5      n[        X5      nU(       a   [        R"                  " U[$        S9nXU'   X4$ U$ )Nr  rW  	quicksortr   )r   r  r   r   r   r  .)rH  r"  r   r  r   r  )r   r   r]  r'  ry  r   r  rs  r  r`  bool_r   r   r`  r  repeatr   r   r   )r   r4  return_tiesr   r  r  ordinal_ranksr  r   r  r   rS  r  s                r   r   r   '  s   GGE !I-;;D


12D)AOOBIIar1C$H%PM M-- 	1b)A
cr
T 1Bcrc{aQRj028:	<A ii	*GWWWVV,F  	5 6)A-	9	 FQJ>1	7			!"%a(IIeV$,,U3E"E" HHU%(!xLr   c                  ^ ^^ TS:  d  TS:  a  [        S5      e[        R                  " T 5      m Tb!  [        R                  " TT R                  5      mU UU4S jnTS:  a,  [        R
                  " T TS9n[        R                  " T 5      nO+[        R
                  " T TS9n[        R                  " T 5      nXE:X  a  U$ [        X4US9nUR                  $ )a  Compute the expectile at the specified level.

Expectiles are a generalization of the expectation in the same way as
quantiles are a generalization of the median. The expectile at level
`alpha = 0.5` is the mean (average). See Notes for more details.

Parameters
----------
a : array_like
    Array containing numbers whose expectile is desired.
alpha : float, default: 0.5
    The level of the expectile; e.g., ``alpha=0.5`` gives the mean.
weights : array_like, optional
    An array of weights associated with the values in `a`.
    The `weights` must be broadcastable to the same shape as `a`.
    Default is None, which gives each value a weight of 1.0.
    An integer valued weight element acts like repeating the corresponding
    observation in `a` that many times. See Notes for more details.

Returns
-------
expectile : ndarray
    The empirical expectile at level `alpha`.

See Also
--------
numpy.mean : Arithmetic average
numpy.quantile : Quantile

Notes
-----
In general, the expectile at level :math:`\alpha` of a random variable
:math:`X` with cumulative distribution function (CDF) :math:`F` is given
by the unique solution :math:`t` of:

.. math::

    \alpha E((X - t)_+) = (1 - \alpha) E((t - X)_+) \,.

Here, :math:`(x)_+ = \max(0, x)` is the positive part of :math:`x`.
This equation can be equivalently written as:

.. math::

    \alpha \int_t^\infty (x - t)\mathrm{d}F(x)
    = (1 - \alpha) \int_{-\infty}^t (t - x)\mathrm{d}F(x) \,.

The empirical expectile at level :math:`\alpha` (`alpha`) of a sample
:math:`a_i` (the array `a`) is defined by plugging in the empirical CDF of
`a`. Given sample or case weights :math:`w` (the array `weights`), it
reads :math:`F_a(x) = \frac{1}{\sum_i w_i} \sum_i w_i 1_{a_i \leq x}`
with indicator function :math:`1_{A}`. This leads to the definition of the
empirical expectile at level `alpha` as the unique solution :math:`t` of:

.. math::

    \alpha \sum_{i=1}^n w_i (a_i - t)_+ =
        (1 - \alpha) \sum_{i=1}^n w_i (t - a_i)_+ \,.

For :math:`\alpha=0.5`, this simplifies to the weighted average.
Furthermore, the larger :math:`\alpha`, the larger the value of the
expectile.

As a final remark, the expectile at level :math:`\alpha` can also be
written as a minimization problem. One often used choice is

.. math::

    \operatorname{argmin}_t
    E(\lvert 1_{t\geq X} - \alpha\rvert(t - X)^2) \,.

References
----------
.. [1] W. K. Newey and J. L. Powell (1987), "Asymmetric Least Squares
       Estimation and Testing," Econometrica, 55, 819-847.
.. [2] T. Gneiting (2009). "Making and Evaluating Point Forecasts,"
       Journal of the American Statistical Association, 106, 746 - 762.
       :doi:`10.48550/arXiv.0912.0902`

Examples
--------
>>> import numpy as np
>>> from scipy.stats import expectile
>>> a = [1, 4, 2, -1]
>>> expectile(a, alpha=0.5) == np.mean(a)
True
>>> expectile(a, alpha=0.2)
0.42857142857142855
>>> expectile(a, alpha=0.8)
2.5714285714285716
>>> weights = [1, 3, 1, 1]

r   r   z6The expectile level alpha must be in the range [0, 1].c                 n   > [         R                  " [         R                  " TU :*  T-
  5      U T-
  -  TS9$ )Nr   )r   r  rV  )r  r   r  r   s    r   first_orderexpectile.<locals>.first_order(  s/    zz"&&!q&E!12a!e<gNNr   r.  r   )rm  rn  )
r   r   r   r'  r   r  r,  aminr5   root)r   r  r   r  rm  rn  r$  s   ```    r   r   r   3(  s    | qyEAID
 	
 	

1A//'1773
O |ZZ7+WWQZZZ7+WWQZ	x	 kR
0C88Or   c                 d   [         R                  " U 5      n Sn[         R                  " U R                  [         R                  5      (       a  U R                  [         R                  5      n [         R                  " U R                  [         R                  5      (       d  [        U5      eSnUc  [         R                  " SS5      O[         R                  " U5      n[         R                  " UR                  [         R                  5      (       a  [         R                  " US:*  5      (       a  [        U5      e[         R                  " U5      S   nSn[         R                  " UR                  [         R                  5      (       a  UR                  S:w  a  [        U5      e[         R                  " U5      S   nSn[         R                  " UR                  [         R                  5      (       a  UR                  S:w  a  [        U5      e[         R                  " U5      S   nS	n[         R                  " UR                  [         R                  5      (       a  UR                  S:w  a  [        U5      e[         R                  " XS
5      n U(       d  [         R                  " U S
S9OU n XX#U4$ )Nz*`sample` must be an array of real numbers.zC`order` must be a scalar or a non-empty array of positive integers.r   rS  r   r   r  z`sorted` must be True or False.z$`standardize` must be True or False.r   r   )r   r   r   r   integerr   rE  floatingr   ry  r   r   r	  r  r  )r  r5  r   r9  standardizer   s         r   _lmoment_ivr  (  s   ZZF:G	}}V\\2::..rzz*==r{{33!!SG$}BIIaO"**U2CE==bjj11RVVEQJ5G5G!!::dBD*G==RZZ00DIIN!!ZZ#F/G==rxx00FKK14D!!**[)"-K4G==**BHH559I9IQ9N!![[r*F-3RWWV"%F$33r   r  c                   U R                   S   n[        R                  " U SS9n [        R                  " X R                   S S [	        U5      U4-   5      n [        R
                  " U 5      n [        R                  " X R                  S9n[        R                  " X R                  S9S   n[        R                  " [        R                  " X1S S 2[        R                  4   5      U -  SS9[        R                  " US-
  U5      -  U-  $ )Nr   r^  r   r   r   r   )r   r   rQ  r'  r   triury  r   r   r  r  rM  rJ  )r   r  r  r  s       r   _brr  (  s    	A
qr"A
773B<3q61+56A

A
		!77#A


1GG$R(AFF7==am$45a7bAmmAaC#$&'( )r   c                 r    SX-
  -  [         R                  " X5      -  [         R                  " X-   U5      -  $ r  )r  rM  )r  r  s     r   _prkr  (  s0     !#;w}}Q**7==a+@@@r   c                     [        U / SQ5      $ )N)r   r   rl  r{  )r:  )r8  s    r   r   r   (  s    ?4>r   )r   r9  r  c                   [        XX#U5      nUu  pp#n[        R                  " U5      n[        R                  " X`R                  S9n[        [        R                  " U[        [        SU R                  S-   5      5      5      U5      n[        XS9n	U R                  S   n
SU	SU
S24'   [        R                  " X-  SS9nU(       a  US	:  a  US	S=== US   -  sss& [        R                  XS& XS-
     $ )
a	  Compute L-moments of a sample from a continuous distribution

The L-moments of a probability distribution are summary statistics with
uses similar to those of conventional moments, but they are defined in
terms of the expected values of order statistics.
Sample L-moments are defined analogously to population L-moments, and
they can serve as estimators of population L-moments. They tend to be less
sensitive to extreme observations than conventional moments.

Parameters
----------
sample : array_like
    The real-valued sample whose L-moments are desired.
order : array_like, optional
    The (positive integer) orders of the desired L-moments.
    Must be a scalar or non-empty 1D array. Default is [1, 2, 3, 4].
axis : int or None, default=0
    If an int, the axis of the input along which to compute the statistic.
    The statistic of each axis-slice (e.g. row) of the input will appear
    in a corresponding element of the output. If None, the input will be
    raveled before computing the statistic.
sorted : bool, default=False
    Whether `sample` is already sorted in increasing order along `axis`.
    If False (default), `sample` will be sorted.
standardize : bool, default=True
    Whether to return L-moment ratios for orders 3 and higher.
    L-moment ratios are analogous to standardized conventional
    moments: they are the non-standardized L-moments divided
    by the L-moment of order 2.

Returns
-------
lmoments : ndarray
    The sample L-moments of order `order`.

See Also
--------
moment

References
----------
.. [1] D. Bilkova. "L-Moments and TL-Moments as an Alternative Tool of
       Statistical Data Analysis". Journal of Applied Mathematics and
       Physics. 2014. :doi:`10.4236/jamp.2014.210104`
.. [2] J. R. M. Hosking. "L-Moments: Analysis and Estimation of Distributions
       Using Linear Combinations of Order Statistics". Journal of the Royal
       Statistical Society. 1990. :doi:`10.1111/j.2517-6161.1990.tb01775.x`
.. [3] "L-moment". *Wikipedia*. https://en.wikipedia.org/wiki/L-moment.

Examples
--------
>>> import numpy as np
>>> from scipy import stats
>>> rng = np.random.default_rng(328458568356392)
>>> sample = rng.exponential(size=100000)
>>> stats.lmoment(sample)
array([1.00124272, 0.50111437, 0.3340092 , 0.16755338])

Note that the first four standardized population L-moments of the standard
exponential distribution are 1, 1/2, 1/3, and 1/6; the sample L-moments
provide reasonable estimates.

r   r   r  r   r   .Nr   r   )r  r   r   ry  r   r  rQ  r   rG  r   r  r   r  r   )r  r5  r   r9  r  r<  	n_momentsr  prkbkr  lmomss               r   r   r   (  s    H vdK@D/3,F4uI
		)<<0A
r~~auQA'>!?@!
DC	V	BRABsABwKFF38"%Ey1}ab	U1X	E"Iq>r   LinregressResult)slope	interceptrvaluer   stderrintercept_stderr)extra_field_namesc           	      2   SnUc  Sn[         R                  " U[        SS9  [        R                  " U 5      n U R
                  S   S:X  a  U u  pOgU R
                  S   S:X  a  U R                  u  pOE[        SU R
                   S	35      e[        R                  " U 5      n [        R                  " U5      nU R                  S:X  d  UR                  S:X  a  [        S
5      e[        R                  " U 5      [        R                  " U 5      :X  a  [        U 5      S:  a  [        S5      e[        U 5      n[        R                  " U S5      n[        R                  " US5      n[        R                  " XSS9R                  u  ppUS:X  d  US:X  a  SnO,U	[        R                  " X-  5      -  nUS:  a  SnOUS:  a  SnX-  nX}U-  -
  nUS:X  a  US   US   :X  a  SnOSnSnSnOUS-
  nU[        R                  " USU-
  U-   SU-   U-   -  -  5      -  n[!        U5      n[#        UUU[        S9nUR$                  S:X  a  US   OUn[        R                  " SUS-  -
  U-  U-  U-  5      nU[        R                  " XS-  -   5      -  n['        XUUUUS9$ )aK  
Calculate a linear least-squares regression for two sets of measurements.

Parameters
----------
x, y : array_like
    Two sets of measurements.  Both arrays should have the same length N.  If
    only `x` is given (and ``y=None``), then it must be a two-dimensional
    array where one dimension has length 2.  The two sets of measurements
    are then found by splitting the array along the length-2 dimension. In
    the case where ``y=None`` and `x` is a 2xN array, ``linregress(x)`` is
    equivalent to ``linregress(x[0], x[1])``.

    .. deprecated:: 1.14.0
        Inference of the two sets of measurements from a single argument `x`
        is deprecated will result in an error in SciPy 1.16.0; the sets
        must be specified separately as `x` and `y`.
alternative : {'two-sided', 'less', 'greater'}, optional
    Defines the alternative hypothesis. Default is 'two-sided'.
    The following options are available:

    * 'two-sided': the slope of the regression line is nonzero
    * 'less': the slope of the regression line is less than zero
    * 'greater':  the slope of the regression line is greater than zero

    .. versionadded:: 1.7.0

Returns
-------
result : ``LinregressResult`` instance
    The return value is an object with the following attributes:

    slope : float
        Slope of the regression line.
    intercept : float
        Intercept of the regression line.
    rvalue : float
        The Pearson correlation coefficient. The square of ``rvalue``
        is equal to the coefficient of determination.
    pvalue : float
        The p-value for a hypothesis test whose null hypothesis is
        that the slope is zero, using Wald Test with t-distribution of
        the test statistic. See `alternative` above for alternative
        hypotheses.
    stderr : float
        Standard error of the estimated slope (gradient), under the
        assumption of residual normality.
    intercept_stderr : float
        Standard error of the estimated intercept, under the assumption
        of residual normality.

See Also
--------
scipy.optimize.curve_fit :
    Use non-linear least squares to fit a function to data.
scipy.optimize.leastsq :
    Minimize the sum of squares of a set of equations.

Notes
-----
For compatibility with older versions of SciPy, the return value acts
like a ``namedtuple`` of length 5, with fields ``slope``, ``intercept``,
``rvalue``, ``pvalue`` and ``stderr``, so one can continue to write::

    slope, intercept, r, p, se = linregress(x, y)

With that style, however, the standard error of the intercept is not
available.  To have access to all the computed values, including the
standard error of the intercept, use the return value as an object
with attributes, e.g.::

    result = linregress(x, y)
    print(result.intercept, result.intercept_stderr)

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

Generate some data:

>>> x = rng.random(10)
>>> y = 1.6*x + rng.random(10)

Perform the linear regression:

>>> res = stats.linregress(x, y)

Coefficient of determination (R-squared):

>>> print(f"R-squared: {res.rvalue**2:.6f}")
R-squared: 0.717533

Plot the data along with the fitted line:

>>> plt.plot(x, y, 'o', label='original data')
>>> plt.plot(x, res.intercept + res.slope*x, 'r', label='fitted line')
>>> plt.legend()
>>> plt.show()

Calculate 95% confidence interval on slope and intercept:

>>> # Two-sided inverse Students t-distribution
>>> # p - probability, df - degrees of freedom
>>> from scipy.stats import t
>>> tinv = lambda p, df: abs(t.ppf(p/2, df))

>>> ts = tinv(0.05, len(x)-2)
>>> print(f"slope (95%): {res.slope:.6f} +/- {ts*res.stderr:.6f}")
slope (95%): 1.453392 +/- 0.743465
>>> print(f"intercept (95%): {res.intercept:.6f}"
...       f" +/- {ts*res.intercept_stderr:.6f}")
intercept (95%): 0.616950 +/- 0.544475

g#B;NzInference of the two sets of measurements from a single "argument `x` is deprecated will result in an error in "SciPy 1.16.0; the sets must be specified separately as "`x` and `y`.r   r   r   r   zZIf only `x` is given as input, it has to be of shape (2, N) or (N, 2); provided shape was rv  zInputs must not be empty.zBCannot calculate a linear regression if all x values are identicalr  r  r   rY  r   r   )r%  r&  r'  r   r(  r)  )r   r   r/  r   r   r   r  r   r   r,  r  r   r  covflatr  rA  r  r   r$  )r   r  r  r  r   r  r  r   ssxmssxymr  ssymr  r%  r&  ro  slope_stderrr)  r  r  r  s                        r   rk   rk   C)  s   l Dy" 	g1a@JJqM771:?DAqWWQZ1_33DAq $$%GG9A/ 0 0 JJqMJJqMvv{affk455	wwqzRWWQZCFQJ 9 : 	: 	AAGGAtEGGAtE
 66!Q/44D s{dckBGGDK((s7AXALEe#IAvQ41Q4<DDU sQw~a$?@AAr"1dKB799>tBxtwwAqDD047"<= ("''$/*BB%Q#'-=? ?r   )r   r   r   r   r   r   c               `   Uc  [        U 5      OUn[        XSS9n Ub  UR                  X%S9OUn[        U5      (       a+  [	        U 5      S:X  d  Ub  [	        U5      S:X  a
  [        XXS9$ [        XSS9u  pU R                  S:X  d  Uc  [        O[        n[	        U 5      S:X  ao  [        R                  " 5          [        R                  " S	5        UR                  XUS
9nSSS5        [	        W5      S:w  a  [        R                  " U[        SS9  U$ [!        XSUS9u  pUb  [!        X$SUS9u  pX-  n	U R                  S:X  d  Uc  ["        O[$        nU	(       a  US:X  a  UR'                  U 5      nUb  XR'                  U5      -  nUR)                  UR+                  XS95      (       a  [        R                  " U[        SS9  Uc  UR-                  U 5      OUnUR/                  XR                  SU R0                  S9U 5      n UR/                  XR                  SU R0                  S9U5      nUc  UR                  XUS
9$ UR3                  X!S9nUR3                  X-  US9n[4        R6                  " S	S	S9   X-  nSSS5        U(       ak  Uc  S[9        U R:                  5      -  nO=[=        U[>        5      (       d  U4OUn[A        U R:                  5      nU H  nSUU'   M
     URC                  WU5      nWR                  S:X  a  US   $ U$ ! , (       d  f       GN4= f! , (       d  f       N= f)a  Compute the arithmetic mean along the specified axis.

Parameters
----------
x : real array
    Array containing real numbers whose mean is desired.
axis : int or tuple of ints, default: None
    If an int or tuple of ints, the axis or axes of the input along which
    to compute the statistic. The statistic of each axis-slice (e.g. row)
    of the input will appear in a corresponding element of the output.
    If ``None``, the input will be raveled before computing the statistic.
weights : real array, optional
    If specified, an array of weights associated with the values in `x`;
    otherwise ``1``. If `weights` and `x` do not have the same shape, the
    arrays will be broadcasted before performing the calculation. See
    Notes for details.
keepdims : boolean, optional
    If this is set to ``True``, the axes which are reduced are left
    in the result as dimensions with length one. With this option,
    the result will broadcast correctly against the input array.
nan_policy : {'propagate', 'omit', 'raise'}, default: 'propagate'
    Defines how to handle input NaNs.

    - ``propagate``: if a NaN is present in the axis slice (e.g. row) along
      which the statistic is computed, the corresponding entry of the output
      will be NaN.
    - ``omit``: NaNs will be omitted when performing the calculation.
      If insufficient data remains in the axis slice along which the
      statistic is computed, the corresponding entry of the output will be
      NaN.
    - ``raise``: if a NaN is present, a ``ValueError`` will be raised.

dtype : dtype, optional
    Type to use in computing the mean. For integer inputs, the default is
    the default float type of the array library; for floating point inputs,
    the dtype is that of the input.

Returns
-------
out : array
    The mean of each slice

Notes
-----
Let :math:`x_i` represent element :math:`i` of data `x` and let :math:`w_i`
represent the corresponding element of `weights` after broadcasting. Then the
(weighted) mean :math:`\bar{x}_w` is given by:

.. math::

    \bar{x}_w = \frac{ \sum_{i=0}^{n-1} w_i x_i }
                     { \sum_{i=0}^{n-1} w_i }

where :math:`n` is the number of elements along a slice. Note that this simplifies
to the familiar :math:`(\sum_i x_i) / n` when the weights are all ``1`` (default).

The behavior of this function with respect to weights is somewhat different
from that of `np.average`. For instance,
`np.average` raises an error when `axis` is not specified and the shapes of `x`
and the `weights` array are not the same; `xp_mean` simply broadcasts the two.
Also, `np.average` raises an error when weights sum to zero along a slice;
`xp_mean` computes the appropriate result. The intent is for this function's
interface to be consistent with the rest of `scipy.stats`.

Note that according to the formula, including NaNs with zero weights is not
the same as *omitting* NaNs with ``nan_policy='omit'``; in the former case,
the NaNs will continue to propagate through the calculation whereas in the
latter case, the NaNs are excluded entirely.

NTr   r   r   r   )r   r   r   )force_floatingr   r   rD  r   r   )xp_omit_okayr   r  r   r   r  r   )"r8   r7   r   r9   r:   rB   r>   r   r.   r0   r   r  r  r  r   r-   r   r/   r1   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  contains_nan_wnan_maskr  wsumfinal_shapeaxesr   s                     r   r   r   *  s   R  "z	rBt,A292Ebjjj.7G ||q$0WW5E5JQdFF%aFJA *+1$) qzQ$$&!!(+''!':C ' 3<1MM'#5!D
#ALOL)'DUWX#4 &'VVq[DL % 
f,88A;))H66"&&&-..MM'#5!D%,_",,q/'HHXzz!177z;Q?((8ZZZ%A7K wwqhw7766'6%D66!+D6)D	Hh	7i 
8 <QWW-K #-T8"<"<D7$Dqww-K!"A  jjk*hh!m3r7,,c '&@ 
8	7s   9'L7L
L
L-)r   r  r   r   r   r   c               4  ^  Uc  [        T 5      OUn[        T SS9m [        XXVS9n[        T 4SS0UD6n[        T UR                  SS9m [        T XUS9n	UR                  U	R                  S5      (       a  UR                  U	5      OU	n
[        X-  4SU0UD6nUS:w  a  Uc  [        T 5      nOK[        R                  " U5      (       a!  [        R                  " U 4S	 jU 5       5      nOT R                  U   nUR                  XR                  S
9nUS:X  a=  UR                  UR!                  T 5      UR                  5      nXR#                  XUS9-
  n[%        X-
  S:  XU-
  4UR&                  UR(                  5      nX-  nUR*                  S:X  a  US   $ U$ )NTr   )r   r   r   r   r   r3  r   r  r   c              3   B   >#    U  H  nTR                   U   v   M     g 7fr   ry  )rI  r   r   s     r   rK  _xp_var.<locals>.<genexpr>*  s     3d!''!*ds   r   r  rD  r   )r8   r7   r  r   r   r[  r   conjr:   r   iterabler  rW  r   r   r   r   r  r   r   r   r   )r   r   r  r   r   r   r   r  r  x_meanx_mean_conjrf  r  r7  factors   `              r   r  r  *  s~     "z	rB$A t%GFA///D$**D1AQr*F&(jj?Q&R&R2776? 
6'
E(
Ef
ECQ<
A[[		3d33AA
 JJq		J*yy!cii8HFF8FBBA AL1,qJ,.?BFFShh!m3r7,,r   c                   &    \ rS rSrS rS rS rSrg)r  i*  c                 .    [         R                  " U5      $ r   r  ndtrr  r   s     r   r  _SimpleNormal.cdf*  s    ||Ar   c                 0    [         R                  " U* 5      $ r   rE  rG  s     r   r  _SimpleNormal.sf*  s    ||QBr   c                 0    [         R                  " U5      * $ r   )r  r  rG  s     r   r  _SimpleNormal.isf*  s    a   r   r   N)r  r  r  r  r  r  r  r  r   r   r   r  r  *  s    
 !r   r  c                   &    \ rS rSrS rS rS rSrg)r  i*  c                     Xl         g r   r  r  r  s     r   r  _SimpleChi2.__init__*      r   c                 D    [         R                  " U R                  U5      $ r   )r  chdtrr  rG  s     r   r  _SimpleChi2.cdf*      }}TWWa((r   c                 D    [         R                  " U R                  U5      $ r   )r  chdtrcr  rG  s     r   r  _SimpleChi2.sf*  s    ~~dggq))r   r  Nr  r  r  r  r  r  r  r  r   r   r   r  r  *      )*r   r  c                   0    \ rS rSrSSS.S jrS rS rSrg)r  i*  Nr  c                4    Xl         X l        X0l        X@l        g r   r   r   r  r<  )r  r   r   r  r<  s        r   r  _SimpleBeta.__init__*  s    
r   c                 \   U R                   c  U R                  bg  U R                   c  SOU R                   nU R                  c  SOU R                  n[        R                  " U R                  U R
                  X-
  U-  5      $ [        R                  " U R                  U R
                  U5      $ Nr   r   )r  r<  r  betaincr   r   r  r   r  r<  s       r   r  _SimpleBeta.cdf*  sy    884::#9xx'!TXXC+AE??466466AGU?CCtvvtvvq11r   c                 \   U R                   c  U R                  bg  U R                   c  SOU R                   nU R                  c  SOU R                  n[        R                  " U R                  U R
                  X-
  U-  5      $ [        R                  " U R                  U R
                  U5      $ r`  )r  r<  r  betainccr   r   rb  s       r   r  _SimpleBeta.sf*  s}    884::#9xx'!TXXC+AE##DFFDFFQWeODD22r   r]  rY  r   r   r   r  r  *  s     %) 23r   r  c                   &    \ rS rSrS rS rS rSrg)rA  i*  c                     Xl         g r   r  rO  s     r   r  _SimpleStudentT.__init__ +  rQ  r   c                 D    [         R                  " U R                  U5      $ r   r  stdtrr  r  r  s     r   r  _SimpleStudentT.cdf+  rU  r   c                 F    [         R                  " U R                  U* 5      $ r   rk  rm  s     r   r  _SimpleStudentT.sf+  s    }}TWWqb))r   r  NrY  r   r   r   rA  rA  *  rZ  r   rA  )r   NNrx  )r   r   F)NTTN)Nrq  r   r   )Nr   Tr   r  )r   r   r   )r   r   NN)r   Tr   )r   TTr   )r   r   Tr   )TN)r   r   r  )r   r   )r   r  N)r  r   )rQ  NNF)rQ  NN)r   r   r   )r   r   r   r  )N)   K   r   r   linearF)r  r  )r   )r  r   r  r   )Nr   r   r  )TNTr  )Tr  r   )r   Tr   Nr  )Nr   r   N)T)Nr   r   )r   r  rL  )r  rL  )r   r  r  rL  )r  )r  r  r   )r}  N)r  )F)r.  )Nr  (  r  r   r  r   collectionsr   collections.abcr   numpyr   r   r   r   scipyr	   scipy.spatialr
   scipy.optimizer   r   scipy._lib._utilr   r   r   r   r   r   scipy._lib.deprecationr   scipy.specialr  r    r   r   r  _stats_mstats_commonr   r   r   _statsr   r   r   dataclassesr   r   
_hypotestsr    _stats_pythranr!   _resamplingr"   r#   r$   r%   r&   r'   r(   _axis_nan_policyr)   r*   r+   r,   r-   r.   r/   r0   r1   
_binomtestr2   r  scipy._lib._bunchr3   r4   r5   r6   scipy._lib._array_apir7   r8   r9   r:   r;   r<   r=   r>   
scipy._libr?   r  r@   __all__r   r   r   r   rB   rC   rD   r   r   rE   r   r  rF   rG   rH   rI   rJ   rK   r:  r=  rA  rL   r[  rI  rg  rM   rN   r  rO   r  r  rP   r  rQ   r  rR   rS   rT   r  rU   r  r   r  rV   r
  rW   rX   rY   r   r[   r\   rZ   r^   erfinvr  r6  r]   rF  rC  r_   rS  r`   ra   rb   rc   rj  rp  rt  r  rd   r  r   r  r  r  r  r  r  re   rf   r  r&  r'  r.  rg   rh   ri   rj   r|  r~  r  r  rl   r  r  r  r  r  rn   _ttest_ind_dep_msgrm   r  r  r  r  r  r  r  ro   r  r  r  r  r  r  rt   r  rs   r%  r.  r1  r4  r6  rq   Ks_2sampResultrK  rW  r`  rr   r~  r  rp   ru   r  rv   r  rw   r  rx   r  r   rz   r  r  r{   r}   r|   r~   r  r  r  rA   r  r  ry   r  r   r   r  r  r  r   r$  rk   r   r  r  r  r  rA  r   r   r   <module>r     s#  &	    " $  $ $  ) 15 5 >     + J J > > ( ' =, , ,I I I
 G /  & 1	 	 	 . .#. !% "$ '+ : '';(3X'>D 
 qA4&YKAM?AM?` qA4&YKA^CD ^CA^CB qA4&YKA t zHAzHz &78
	# ,4EJ2L MM-MM-` 24D $N 14"00	00f 1n5P5Pn 1n9-9-x 1n8-8-v 1n.F.Fb 1n99B+6 8W%Qf4 f4	 &
f4R 59 : %)T 6!r 1
^0
^0B 1
g0
g0T ,)*
Z1B& ,.EF .ACb% Db%J   46MN  ,QGo) Ho)d 02IJ  *a1EI/ FI/X ,4@ O1 AO1n >HMMb(PVVr .NP ;? KI\ ?+,
J+Z ?+,
I%`Vr 1;;|. RCj q[ [G|M`ph s 3c 9DIIcN JK  1!2E : ;F).P	Pf, "#299C$/W~ .0MNB4JSlTnQ/h ,.EF
+F
( d.DF \#F\#~   
 T5
 *51 N'
N'b
'1T8    4ufoF &';(3X'>D Z' Zz #.d QHh\1D \1~M8J$@D	0 -8%CL\~ $/c{aHy@ $$5%0($;dVE=6/ =6@I0
 *a*<K@:	K@:F!H"$ .0GH 6AK!\ E H-;^,L+=? *a*<K+dTg@K?
g@T%*0 H .2#'L" >B<@#.L&^ *a*<!%'d&'d&R  (% 4 $$<$;= hXV\0~QEd QEh !+x1H"68H!IK"0#.7< 0A*@B68$p/ %Bp/f #LGT-` 0A*@B68$s8 %Bs8l:?
 0<M$%7MO68$~# %O~#B*NZ ,.EF .A6N- 7N-b ?,CD -48!, ]$ 9]$@ %%>%<>  1T$OU6 PU6p !!6!8:  -;>A(v( <v(r ,9+dSp/A p/ Tp/f a- a- a-H 2 s Jd
K\YFxS<lT6n(^ .0DE  = >%L>%LP4:q$; q qh9x{t {| 4F  )A Q>P%T P	Pf %%7&:8J7KM F?R  +DJ-Z 1u4*- *-Z! !* *3 32* *r   