
    F\h              
          % S r / SQrSSKrSSKrSSKrSSK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  SSKJrJrJrJrJrJrJrJrJr  SS	KJrJrJrJr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)J*r*J+r+  \" S5      r,\r- " S S\.5      r/S r0SbS jr1S r2S r3S r4S r5ScS jr6SSSSS.S\7\8   4S jjr9S\:S\:S\:4S jr;S \Rx                  Rz                  -  S!-   r>\:\?S"'   S\:S\:S\84S# jr@S\:S\:S\	4S$ jrAS% rBSbS& jrCS' rDSbS( jrES) rFS* rGS+ rHSdS, jrIS- rJS. rKSeSS0.S1 jjrLS2S3S4.S5 jrMSbS6 jrNSbS7 jrOSbS8 jrPSbS9 jrQS: rRS;\8S<\8S\84S= jrSS> rTS?S@.SA jrU\*" SBSC5      rVSSD.SE jrWSF rX SSGKYJXrX   " SH SI5      r[SfSJ jr\SK r]\\" \]SL SM SN9r^SO r_\\" \_SP SQ SN9r`\[" 5       R                  SR SS ST SU \^\`SV SW SX.	rb\bS/   \bSY'   \bSZ   \bS['   \bS\   \bS]'   \bS^   \bS_'   SeSS`.Sa jjrcg! \Z a     N|f = f)ga  
Basic statistics module.

This module provides functions for calculating statistics of data, including
averages, variance, and standard deviation.

Calculating averages
--------------------

==================  ==================================================
Function            Description
==================  ==================================================
mean                Arithmetic mean (average) of data.
fmean               Fast, floating-point arithmetic mean.
geometric_mean      Geometric mean of data.
harmonic_mean       Harmonic mean of data.
median              Median (middle value) of data.
median_low          Low median of data.
median_high         High median of data.
median_grouped      Median, or 50th percentile, of grouped data.
mode                Mode (most common value) of data.
multimode           List of modes (most common values of data).
quantiles           Divide data into intervals with equal probability.
==================  ==================================================

Calculate the arithmetic mean ("the average") of data:

>>> mean([-1.0, 2.5, 3.25, 5.75])
2.625


Calculate the standard median of discrete data:

>>> median([2, 3, 4, 5])
3.5


Calculate the median, or 50th percentile, of data grouped into class intervals
centred on the data values provided. E.g. if your data points are rounded to
the nearest whole number:

>>> median_grouped([2, 2, 3, 3, 3, 4])  #doctest: +ELLIPSIS
2.8333333333...

This should be interpreted in this way: you have two data points in the class
interval 1.5-2.5, three data points in the class interval 2.5-3.5, and one in
the class interval 3.5-4.5. The median of these data points is 2.8333...


Calculating variability or spread
---------------------------------

==================  =============================================
Function            Description
==================  =============================================
pvariance           Population variance of data.
variance            Sample variance of data.
pstdev              Population standard deviation of data.
stdev               Sample standard deviation of data.
==================  =============================================

Calculate the standard deviation of sample data:

>>> stdev([2.5, 3.25, 5.5, 11.25, 11.75])  #doctest: +ELLIPSIS
4.38961843444...

If you have previously calculated the mean, you can pass it as the optional
second argument to the four "spread" functions to avoid recalculating it:

>>> data = [1, 2, 2, 4, 4, 4, 5, 6]
>>> mu = mean(data)
>>> pvariance(data, mu)
2.5


Statistics for relations between two inputs
-------------------------------------------

==================  ====================================================
Function            Description
==================  ====================================================
covariance          Sample covariance for two variables.
correlation         Pearson's correlation coefficient for two variables.
linear_regression   Intercept and slope for simple linear regression.
==================  ====================================================

Calculate covariance, Pearson's correlation, and simple linear regression
for two inputs:

>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> covariance(x, y)
0.75
>>> correlation(x, y)  #doctest: +ELLIPSIS
0.31622776601...
>>> linear_regression(x, y)  #doctest:
LinearRegression(slope=0.1, intercept=1.5)


Exceptions
----------

A single exception is defined: StatisticsError is a subclass of ValueError.

)
NormalDistStatisticsErrorcorrelation
covariancefmeangeometric_meanharmonic_meankde
kde_randomlinear_regressionmeanmedianmedian_groupedmedian_high
median_lowmode	multimodepstdev	pvariance	quantilesstdevvariance    NFraction)Decimal)countgroupbyrepeat)bisect_leftbisect_right)	hypotsqrtfabsexperftaulogfsumsumprod)
isfiniteisinfpicossintancoshasinatanacos)reduce)
itemgetter)Counter
namedtupledefaultdict       @c                       \ rS rSrSrg)r       N)__name__
__module____qualname____firstlineno____static_attributes__r<       !/usr/lib/python3.13/statistics.pyr   r      s    rB   r   c                    Sn[        5       nUR                  n0 nUR                  n[        U [        5       H9  u  pgU" U5        [        [        U5       H  u  pUS-  nU" U	S5      U-   XI'   M     M;     SU;   a  US   n
[        U
5      (       a   eO [        S UR                  5        5       5      n
[        [        U[        5      nXU4$ )aT  _sum(data) -> (type, sum, count)

Return a high-precision sum of the given numeric data as a fraction,
together with the type to be converted to and the count of items.

Examples
--------

>>> _sum([3, 2.25, 4.5, -0.5, 0.25])
(<class 'float'>, Fraction(19, 2), 5)

Some sources of round-off error will be avoided:

# Built-in sum returns zero.
>>> _sum([1e50, 1, -1e50] * 1000)
(<class 'float'>, Fraction(1000, 1), 3000)

Fractions and Decimals are also supported:

>>> from fractions import Fraction as F
>>> _sum([F(2, 3), F(7, 5), F(1, 4), F(5, 6)])
(<class 'fractions.Fraction'>, Fraction(63, 20), 4)

>>> from decimal import Decimal as D
>>> data = [D("0.1375"), D("0.2108"), D("0.3061"), D("0.0419")]
>>> _sum(data)
(<class 'decimal.Decimal'>, Fraction(6963, 10000), 4)

Mixed types are currently treated as an error, except that int is
allowed.
r      Nc              3   <   #    U  H  u  p[        X!5      v   M     g 7fNr   .0dns      rC   	<genexpr>_sum.<locals>.<genexpr>   s     @/?tqHQNN/?   )setaddgetr   typemap_exact_ratio	_isfinitesumitemsr4   _coerceint)datar   types	types_addpartialspartials_gettypvaluesrK   rJ   totalTs               rC   _sumrc      s    @ EEE		IH<<LtT*#f-DAQJE&q!,q0HK . +
 x U##### @x~~/?@@ws#AerB   c                   ^^ Tb  [        UU4S jU  5       5      u  p#nX#TU4$ Sn[        5       nUR                  n[        [        5      n[        [        5      n[        U [        5       HH  u  pU" U	5        [        [        U
5       H'  u  nmUS-  nUT==   U-  ss'   UT==   X-  -  ss'   M)     MJ     U(       d  [        S5      =nmOpSU;   a  US   =nm[        U5      (       a   eOP[        S UR                  5        5       5      n[        S UR                  5        5       5      nXM-  X-  -
  U-  nX-  m[        [        U[        5      nX#TU4$ )a#  Return the exact mean and sum of square deviations of sequence data.

Calculations are done in a single pass, allowing the input to be an iterator.

If given *c* is used the mean; otherwise, it is calculated from the data.
Use the *c* argument with care, as it can lead to garbage results.

Nc              3   6   >#    U  H  oT-
  =mT-  v   M     g 7frG   r<   )rI   xcrJ   s     rC   rL   _ss.<locals>.<genexpr>   s     <t!q5jaA-ts   r   rE   c              3   <   #    U  H  u  p[        X!5      v   M     g 7frG   r   rH   s      rC   rL   rh      s     @,?DA!,?rN   c              3   B   #    U  H  u  p[        X!U-  5      v   M     g 7frG   r   rH   s      rC   rL   rh      s      D/Ctq(1c""/Cs   )rc   rO   rP   r8   rY   r   rR   rS   rT   r   rU   rV   rW   r4   rX   )rZ   rg   rb   ssdr   r[   r\   sx_partialssxx_partialsr_   r`   rK   sxsxxrJ   s    `            @rC   _ssrp      sP    	}<t<<5!!EEE		Ic"Ks#LtT*#f-DAqQJENaNOqu$O . + 1+a		 d##aS>>!!>@K,=,=,?@@D|/A/A/CDD {RW$-Jws#AAurB   c                 p     U R                  5       $ ! [         a    [        R                  " U 5      s $ f = frG   )	is_finiteAttributeErrormathr*   )rf   s    rC   rU   rU      s1     {{}  }}Q s     55c                 
   U [         Ld   S5       eXL a  U $ U[        L d	  U[         L a  U $ U [        L a  U$ [        X5      (       a  U$ [        X5      (       a  U $ [        U [        5      (       a  U$ [        U[        5      (       a  U $ [        U [        5      (       a  [        U[        5      (       a  U$ [        U [        5      (       a  [        U[        5      (       a  U $ Sn[        X R                  UR                  4-  5      e)zCoerce types T and S to a common type, or raise TypeError.

Coercion rules are currently an implementation detail. See the CoerceTest
test class in test_statistics for details.
zinitial type T is boolz"don't know how to coerce %s and %s)boolrY   
issubclassr   float	TypeErrorr=   )rb   Smsgs      rC   rX   rX     s     D=222= 	vqCx19axCx(!(!(!S1H!S1H!X:a#7#7!U
1h 7 7
.C
C::qzz22
33rB   c                 (    U R                  5       $ ! [         a     O+[        [        4 a    [	        U 5      (       a   eU S4s $ f = f U R
                  U R                  4$ ! [         a%    S[        U 5      R                   S3n[        U5      ef = f)zReturn Real number x to exact (numerator, denominator) pair.

>>> _exact_ratio(0.25)
(1, 4)

x is expected to be an int, Fraction, Decimal or float.
Nzcan't convert type 'z' to numerator/denominator)
as_integer_ratiors   OverflowError
ValueErrorrU   	numeratordenominatorrR   r=   ry   )rf   r{   s     rC   rT   rT   #  s    <!!## :& Q<<4yQ]]++ $T!W%5%5$66PQns     
A%AA
A" "/Bc                     [        U 5      UL a  U $ [        U[        5      (       a  U R                  S:w  a  [        n U" U 5      $ ! [
         a>    [        U[        5      (       a'  U" U R                  5      U" U R                  5      -  s $ e f = f)z&Convert value to given numeric type T.rE   )rR   rw   rY   r   rx   ry   r   r   )valuerb   s     rC   _convertr   Q  s    E{a !Se//14x a!!U__%%*;*;(<<<	s   A ABBc              #   H   #    U  H  nUS:  a  [        U5      eUv   M     g7f)z7Iterate over values, failing if any are less than zero.r   N)r   )r`   errmsgrf   s      rC   	_fail_negr   c  s&     q5!&)) s    "FaveragerE   )keyreversetiesstartreturnc               J   US:w  a  [        SU< 35      eUb  [        X5      n [        [        U [	        5       5      US9nUS-
  nS/[        U5      -  n[        U[        S5      S9 H8  u  p[        U	5      n
[        U
5      nXkS-   S-  -   nU
 H	  u  pXU'   M     Xk-  nM:     U$ )a  Rank order a dataset. The lowest value has rank 1.

Ties are averaged so that equal values receive the same rank:

    >>> data = [31, 56, 31, 25, 75, 18]
    >>> _rank(data)
    [3.5, 5.0, 3.5, 2.0, 6.0, 1.0]

The operation is idempotent:

    >>> _rank([3.5, 5.0, 3.5, 2.0, 6.0, 1.0])
    [3.5, 5.0, 3.5, 2.0, 6.0, 1.0]

It is possible to rank the data in reverse order so that the
highest value has rank 1.  Also, a key-function can extract
the field to be ranked:

    >>> goals = [('eagles', 45), ('bears', 48), ('lions', 44)]
    >>> _rank(goals, key=itemgetter(1), reverse=True)
    [2.0, 1.0, 3.0]

Ranks are conventionally numbered starting from one; however,
setting *start* to zero allows the ranks to be used as array indices:

    >>> prize = ['Gold', 'Silver', 'Bronze', 'Certificate']
    >>> scores = [8.1, 7.3, 9.4, 8.3]
    >>> [prize[int(i)] for i in _rank(scores, start=0, reverse=True)]
    ['Bronze', 'Certificate', 'Gold', 'Silver']

r   zUnknown tie resolution method: )r   rE   r   )r      )	r   rS   sortedzipr   lenr   r5   list)rZ   r   r   r   r   val_posiresult_ggroupsizerankr   orig_poss                  rC   _rankr   k  s    J y:4(CDD
3~Suw'9G	AS3w<FZ]3Q5z1H>!$OE#8  %		 4 MrB   rK   mc                 L    [         R                  " X-  5      nX"U-  U-  U :g  -  $ )zFSquare root of n/m, rounded to the nearest integer using round-to-odd.)rt   isqrt)rK   r   as      rC   _integer_sqrt_of_frac_rtor     s)     	

16A!A
rB   r      _sqrt_bit_widthc                     U R                  5       UR                  5       -
  [        -
  S-  nUS:  a  [        XSU-  -  5      U-  nSnX4-  $ [        U SU-  -  U5      nSU* -  nX4-  $ )z1Square root of n/m as a float, correctly rounded.r   r   rE   )
bit_lengthr   r   )rK   r   qr   r   s        rC   _float_sqrt_of_fracr     s|     
!,,.	(?	:q@AAv-aa!e<A	 "" .a26k1=	A2g""rB   c                    U S::  a  U (       d  [        S5      $ U * U* p[        U 5      [        U5      -  R                  5       nUR                  5       u  p4UR                  5       nUR                  5       u  pgSU -  XG-  S-  -  XU-  Xs-  -   S-  -  :  a  U$ UR	                  5       nUR                  5       u  pSU -  XJ-  S-  -  XU	-  X-  -   S-  -  :  a  U$ U$ )z3Square root of n/m as a Decimal, correctly rounded.r   z0.0   r   )r   r"   r}   	next_plus
next_minus)rK   r   rootnrdrplusnpdpminusnmdms              rC   _decimal_sqrt_of_fracr     s    
 	Av5>!rA21AJ#))+D""$FB>>D""$FB1uzAB 222OOE##%FB1uzAB 222KrB   c                 \    [        U 5      u  pnUS:  a  [        S5      e[        X#-  U5      $ )a[  Return the sample arithmetic mean of data.

>>> mean([1, 2, 3, 4, 4])
2.8

>>> from fractions import Fraction as F
>>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
Fraction(13, 21)

>>> from decimal import Decimal as D
>>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
Decimal('0.5625')

If ``data`` is empty, StatisticsError will be raised.
rE   z%mean requires at least one data point)rc   r   r   )rZ   rb   ra   rK   s       rC   r   r     s3      t*KAa1uEFFEIq!!rB   c                 ~  ^ Uc.   [        U 5      m[        U 5      nT(       d  [        S5      eUT-  $ [	        U[
        [        45      (       d  [        U5      n [        X5      n[        U5      nU(       d  [        S5      eXE-  $ ! [         a    SmU4S jnU" U 5      n  Nf = f! [         a    [        S5      ef = f)zConvert data to floats and compute the arithmetic mean.

This runs faster than the mean() function and it always returns a float.
If the input dataset is empty, it raises a StatisticsError.

>>> fmean([3.5, 4.0, 5.25])
4.25
r   c              3   >   >#    [        U SS9 H
  u  mnUv   M     g 7f)NrE   r   )	enumerate)iterablerf   rK   s     rC   r   fmean.<locals>.count  s      %ha8DAqG 9s   z&fmean requires at least one data pointz(data and weights must be the same lengthzsum of weights must be non-zero)	r   ry   r(   r   
isinstancer   tupler)   r   )rZ   weightsr   ra   numdenrK   s         @rC   r   r     s     		D	A T
!"JKKqyge}--w-Jd$ w-C?@@9+  	A ;D	   JHIIJs   B B& B#"B#&B<c                 J  ^^ SmSmUU4S jn[        [        [        U" U 5      5      5      nT(       d  [        S5      e[        R
                  " U5      (       a  [        R                  $ T(       a&  U[        R                  :X  a  [        R                  $ S$ [        UT-  5      $ )aU  Convert data to floats and compute the geometric mean.

Raises a StatisticsError if the input dataset is empty
or if it contains a negative value.

Returns zero if the product of inputs is zero.

No special efforts are made to achieve exact results.
(However, this may change in the future.)

>>> round(geometric_mean([54, 24, 36]), 9)
36.0
r   Fc              3      >#    [        U SS9 HA  u  mnUS:  d  [        R                  " U5      (       a  Uv   M-  US:X  a  SmM7  [        SU5      e   g 7f)NrE   r           TzNo negative inputs allowed)r   rt   isnanr   )r   rf   
found_zerorK   s     rC   count_positive&geometric_mean.<locals>.count_positive"  sM     ha0DAq3w$**Q--c!
%&BAFF 1s   AAzMust have a non-empty datasetr   )	r(   rS   r'   r   rt   r   naninfr$   )rZ   r   ra   r   rK   s      @@rC   r   r     s     	
AJG S../0E=>>zz%xx DHH,txx5#5uqy>rB   c                    [        U 5      U L a  [        U 5      n Sn[        U 5      nUS:  a  [        S5      eUS:X  aK  UcH  U S   n[	        U[
        R                  [        45      (       a  US:  a  [        U5      eU$ [        S5      eUc  [        SU5      nUnOQ[        U5      UL a  [        U5      n[        U5      U:w  a  [        S5      e[        S [        X5       5       5      u  pen [        X5      n [        S [        X5       5       5      u  pxn	US::  a  [        S	5      e[        XX-  U5      $ ! [         a     gf = f)
a  Return the harmonic mean of data.

The harmonic mean is the reciprocal of the arithmetic mean of the
reciprocals of the data.  It can be used for averaging ratios or
rates, for example speeds.

Suppose a car travels 40 km/hr for 5 km and then speeds-up to
60 km/hr for another 5 km. What is the average speed?

    >>> harmonic_mean([40, 60])
    48.0

Suppose a car travels 40 km/hr for 5 km, and when traffic clears,
speeds-up to 60 km/hr for the remaining 30 km of the journey. What
is the average speed?

    >>> harmonic_mean([40, 60], weights=[5, 30])
    56.0

If ``data`` is empty, or any element is less than zero,
``harmonic_mean`` will raise ``StatisticsError``.
z.harmonic mean does not support negative valuesrE   z.harmonic_mean requires at least one data pointr   zunsupported typez*Number of weights does not match data sizec              3   $   #    U  H  ov   M     g 7frG   r<   )rI   ws     rC   rL    harmonic_mean.<locals>.<genexpr>b  s      G,Fq,Fs   c              3   @   #    U  H  u  pU(       a  X-  OS v   M     g7f)r   Nr<   )rI   r   rf   s      rC   rL   r   e  s     P=OTQquq0=Os   zWeighted sum must be positive)iterr   r   r   r   numbersRealr   ry   r   rc   r   r   ZeroDivisionErrorr   )
rZ   r   r   rK   rf   sum_weightsr   rb   ra   r   s
             rC   r   r   5  sD   . DzTDz=FD	A1uNOO	
aGOGa',,0111u%f--H.//A,=G#7mGw<1!"NOO  GIg,F GG&PS=OPP% z=>>K'++	  s   -)D5 5
EEc                     [        U 5      n [        U 5      nUS:X  a  [        S5      eUS-  S:X  a  XS-     $ US-  nXS-
     X   -   S-  $ )a"  Return the median (middle value) of numeric data.

When the number of data points is odd, return the middle data point.
When the number of data points is even, the median is interpolated by
taking the average of the two middle values:

>>> median([1, 3, 5])
3
>>> median([1, 3, 5, 7])
4.0

r   no median for empty datar   rE   r   r   r   )rZ   rK   r   s      rC   r   r   m  sa     $<DD	AAv8991uzF|FUdg%**rB   c                     [        U 5      n [        U 5      nUS:X  a  [        S5      eUS-  S:X  a  XS-     $ XS-  S-
     $ )zReturn the low median of numeric data.

When the number of data points is odd, the middle value is returned.
When it is even, the smaller of the two middle values is returned.

>>> median_low([1, 3, 5])
3
>>> median_low([1, 3, 5, 7])
3

r   r   r   rE   r   rZ   rK   s     rC   r   r     sQ     $<DD	AAv8991uzF|FQJrB   c                 ^    [        U 5      n [        U 5      nUS:X  a  [        S5      eXS-     $ )zReturn the high median of data.

When the number of data points is odd, the middle value is returned.
When it is even, the larger of the two middle values is returned.

>>> median_high([1, 3, 5])
3
>>> median_high([1, 3, 5, 7])
5

r   r   r   r   r   s     rC   r   r     s5     $<DD	AAv899Q<rB   c                 $   [        U 5      n [        U 5      nU(       d  [        S5      eXS-     n[        X5      n[	        XUS9n [        U5      n[        U5      nX1S-  -
  nUnXT-
  nXaUS-  U-
  -  U-  -   $ ! [         a    [        S5      ef = f)a  Estimates the median for numeric data binned around the midpoints
of consecutive, fixed-width intervals.

The *data* can be any iterable of numeric data with each value being
exactly the midpoint of a bin.  At least one value must be present.

The *interval* is width of each bin.

For example, demographic information may have been summarized into
consecutive ten-year age groups with each group being represented
by the 5-year midpoints of the intervals:

    >>> demographics = Counter({
    ...    25: 172,   # 20 to 30 years old
    ...    35: 484,   # 30 to 40 years old
    ...    45: 387,   # 40 to 50 years old
    ...    55:  22,   # 50 to 60 years old
    ...    65:   6,   # 60 to 70 years old
    ... })

The 50th percentile (median) is the 536th person out of the 1071
member cohort.  That person is in the 30 to 40 year old age group.

The regular median() function would assume that everyone in the
tricenarian age group was exactly 35 years old.  A more tenable
assumption is that the 484 members of that age group are evenly
distributed between 30 and 40.  For that, we use median_grouped().

    >>> data = list(demographics.elements())
    >>> median(data)
    35
    >>> round(median_grouped(data, interval=10), 1)
    37.5

The caller is responsible for making sure the data points are separated
by exact multiples of *interval*.  This is essential for getting a
correct result.  The function does not check this precondition.

Inputs may be any numeric type that can be coerced to a float during
the interpolation step.

r   r   )loz$Value cannot be converted to a floatr9   )r   r   r   r   r    rx   r   ry   )	rZ   intervalrK   rf   r   jLcffs	            rC   r   r     s    V $<DD	A899 	!VA 	DAT#AA?!H 	
sNA	
B	A1q52:&***  A>@@As   A9 9Bc                     [        [        U 5      5      R                  S5      n US   S   $ ! [         a    [	        S5      Sef = f)aD  Return the most common data point from discrete or nominal data.

``mode`` assumes discrete data, and returns a single value. This is the
standard treatment of the mode as commonly taught in schools:

    >>> mode([1, 1, 2, 3, 3, 3, 3, 4])
    3

This also works with nominal (non-numeric) data:

    >>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
    'red'

If there are multiple modes with same frequency, return the first one
encountered:

    >>> mode(['red', 'red', 'green', 'blue', 'blue'])
    'red'

If *data* is empty, ``mode``, raises StatisticsError.

rE   r   zno mode for empty dataN)r6   r   most_common
IndexErrorr   )rZ   pairss     rC   r   r     sP    . DJ++A.EBQx{ B67TABs	   - Ac                     [        [        U 5      5      nU(       d  / $ [        UR                  5       5      nUR	                  5        VVs/ s H  u  p4XB:X  d  M  UPM     snn$ s  snnf )a
  Return a list of the most frequently occurring values.

Will return more than one result if there are multiple modes
or an empty list if *data* is empty.

>>> multimode('aabbbbbbbbcc')
['b']
>>> multimode('aabbbbccddddeeffffgg')
['b', 'd', 'f']
>>> multimode('')
[]
)r6   r   maxr`   rW   )rZ   countsmaxcountr   r   s        rC   r   r     sO     T$Z F	6==?#H&,llnJnle8IEnJJJs   
A#A#normal)
cumulativec                  ^ ^^^^	^
^^^^^ [        T 5      mT(       d  [        S5      e[        T S   [        [        45      (       d  [        S5      eTS::  a  [        ST< 35      eU==S:X  a  O	=S:X  a  O  O.    [        S[        -  5      m[        S5      mU4S	 jmU4S
 jmSnO=S:X  a
    S mS mSnO=S:X  a"    S[        -  m
S[        -  mU
4S jmU4S jmSnO==S:X  a  O	=S:X  a  O  O    S mS mSnO=S:X  a
    S mS mSnO==S:X  a  O	=S:X  a  O  O    S mS mSnOc==S:X  a  O	=S :X  a  O  O    S! mS" mSnOG=S#:X  a
    S$ mS% mSnO7S&:X  a"  [        S'-  m
[        S-  mU
U4S( jmU4S) jmSnO [        S*U< 35      eUc  UU U4S+ jnUU U4S, jnO&[        T 5      mTU-  m	UU	U UUU4S- jnUU	U UUU4S. jnU(       a  S/T< S0U< 3Ul	        U$ S1T< S0U< 3Ul	        U$ )2a  Kernel Density Estimation:  Create a continuous probability density
function or cumulative distribution function from discrete samples.

The basic idea is to smooth the data using a kernel function
to help draw inferences about a population from a sample.

The degree of smoothing is controlled by the scaling parameter h
which is called the bandwidth.  Smaller values emphasize local
features while larger values give smoother results.

The kernel determines the relative weights of the sample data
points.  Generally, the choice of kernel shape does not matter
as much as the more influential bandwidth smoothing parameter.

Kernels that give some weight to every sample point:

   normal (gauss)
   logistic
   sigmoid

Kernels that only give weight to sample points within
the bandwidth:

   rectangular (uniform)
   triangular
   parabolic (epanechnikov)
   quartic (biweight)
   triweight
   cosine

If *cumulative* is true, will return a cumulative distribution function.

A StatisticsError will be raised if the data sequence is empty.

Example
-------

Given a sample of six data points, construct a continuous
function that estimates the underlying probability density:

    >>> sample = [-2.1, -1.3, -0.4, 1.9, 5.1, 6.2]
    >>> f_hat = kde(sample, h=1.5)

Compute the area under the curve:

    >>> area = sum(f_hat(x) for x in range(-20, 20))
    >>> round(area, 4)
    1.0

Plot the estimated probability density function at
evenly spaced points from -6 to 10:

    >>> for x in range(-6, 11):
    ...     density = f_hat(x)
    ...     plot = ' ' * int(density * 400) + 'x'
    ...     print(f'{x:2}: {density:.3f} {plot}')
    ...
    -6: 0.002 x
    -5: 0.009    x
    -4: 0.031             x
    -3: 0.070                             x
    -2: 0.111                                             x
    -1: 0.125                                                   x
     0: 0.110                                            x
     1: 0.086                                   x
     2: 0.068                            x
     3: 0.059                        x
     4: 0.066                           x
     5: 0.082                                 x
     6: 0.082                                 x
     7: 0.058                        x
     8: 0.028            x
     9: 0.009    x
    10: 0.002 x

Estimate P(4.5 < X <= 7.5), the probability that a new sample value
will be between 4.5 and 7.5:

    >>> cdf = kde(sample, h=1.5, cumulative=True)
    >>> round(cdf(7.5) - cdf(4.5), 2)
    0.22

References
----------

Kernel density estimation and its application:
https://www.itm-conferences.org/articles/itmconf/pdf/2018/08/itmconf_sam2018_00037.pdf

Kernel functions in common use:
https://en.wikipedia.org/wiki/Kernel_(statistics)#kernel_functions_in_common_use

Interactive graphical demonstration and exploration:
https://demonstrations.wolfram.com/KernelDensityEstimation/

Kernel estimation of cumulative distribution function of a random variable with bounded support
https://www.econstor.eu/bitstream/10419/207829/1/10.21307_stattrans-2016-037.pdf

Empty data sequencer   )Data sequence must contain ints or floatsr   $Bandwidth h must be positive, not h=r   gaussr   c                 ,   > [        SU -  U -  5      T-  $ )N      ࿩r$   )tsqrt2pis    rC   <lambda>kde.<locals>.<lambda>  s    #dQhl+g5rB   c                 ,   > SS[        U T-  5      -   -  $ N      ?      ?)r%   )r   sqrt2s    rC   r   r     s    #s1u9~!56rB   Nlogisticc                 $    SS[        U 5      -   -  $ r   r0   r   s    rC   r   r     s    #tAw/rB   c                 *    SS[        U 5      S-   -  -
  $ Nr   r   r  s    rC   r   r     s    #s1v| 44rB   sigmoidrE   c                     > T[        U 5      -  $ rG   r  )r   c1s    rC   r   r     s    "tAw,rB   c                 2   > T[        [        U 5      5      -  $ rG   )r2   r$   r   c2s    rC   r   r     s    "tCF|+rB   rectangularuniformc                     gNr   r<   r  s    rC   r   r     s    #rB   c                     SU -  S-   $ r  r<   r  s    rC   r   r     s    #'C-rB   r   
triangularc                     S[        U 5      -
  $ r  absr  s    rC   r   r     s    #A,rB   c                 ,    X -  U S:  a  SOS-  U -   S-   $ )Nr   r   r   r<   r  s    rC   r   r     s    !#CT:Q>DrB   	parabolicepanechnikovc                     SSX -  -
  -  $ )N      ?r   r<   r  s    rC   r   r     s    #qu-rB   c                 $    SU S-  -  SU -  -   S-   $ )Ng      пr   r  r   r<   r  s    rC   r   r     s    $A+a/#5rB   quarticbiweightc                     SSX -  -
  S-  -  $ N      ?r   r   r<   r  s    rC   r   r         %3;1"44rB   c                 6    SU S-  -  SU S-  -  -
  SU -  -   S-   $ Ng      ?   g      ?r   r  r   r<   r  s    rC   r   r     s'    $A+ad
2UQY>DrB   	triweightc                     SSX -  -
  S-  -  $ N     ?r   r   r<   r  s    rC   r   r     r  rB   c                 B    SSU S-  -  SU S-  -  -   U S-  -
  U -   -  S-   $ Nr&  g$I$I¿   g333333?r"  r   r   r<   r  s    rC   r   r     s1    %419s1a4x#7!Q$#>#BCcIrB   cosiner   c                 &   > T[        TU -  5      -  $ rG   )r-   )r   r  r
  s    rC   r   r     s    "s26{*rB   c                 ,   > S[        TU -  5      -  S-   $ r  r.   r	  s    rC   r   r     s    #BF+c1rB   Unknown kernel name: c                 V   >^  [        T5      n[        UUU 4S jT 5       5      UT-  -  $ )Nc              3   @   >#    U  H  nT" TU-
  T-  5      v   M     g 7frG   r<   rI   x_iKhrf   s     rC   rL   #kde.<locals>.pdf.<locals>.<genexpr>  !     84Cq!c'Q''4   r   rV   )rf   rK   r3  rZ   r4  s   ` rC   pdfkde.<locals>.pdf  s&    D	A8488AEBBrB   c                 P   >^  [        T5      n[        UUU 4S jT 5       5      U-  $ )Nc              3   @   >#    U  H  nT" TU-
  T-  5      v   M     g 7frG   r<   rI   r2  Wr4  rf   s     rC   rL   #kde.<locals>.cdf.<locals>.<genexpr>  r6  r7  r8  )rf   rK   r>  rZ   r4  s   ` rC   cdfkde.<locals>.cdf  s"    D	A84881<<rB   c                    >^  [        T5      T:w  a  [        T5      m	[        T5      m[        T	T T-
  5      n[        T	T T-   5      nT	X n[	        UUU 4S jU 5       5      TT-  -  $ )Nc              3   @   >#    U  H  nT" TU-
  T-  5      v   M     g 7frG   r<   r1  s     rC   rL   r5    s!     =9Cq!c'Q''9r7  r   r   r   r    rV   )
rf   r   r   	supportedr3  	bandwidthrZ   r4  rK   samples
   `   rC   r9  r:    sc    4yA~IFA	M2AVQ]3AqI=9==QGGrB   c                    >^  [        T5      T:w  a  [        T5      m	[        T5      m[        T	T T-
  5      n[        T	T T-   5      nT	X n[	        UUU 4S jU 5       U5      T-  $ )Nc              3   @   >#    U  H  nT" TU-
  T-  5      v   M     g 7frG   r<   r=  s     rC   rL   r?    s!     >IS1s7a-((Ir7  rD  )
rf   r   r   rE  r>  rF  rZ   r4  rK   rG  s
   `   rC   r@  rA    sa    4yA~IFA	M2AVQ]3AqI>I>BQFFrB   zCDF estimate with h= and kernel=zPDF estimate with h=)
r   r   r   rY   rx   ry   r"   r,   r   __doc__)rZ   r4  kernelr   supportr9  r@  r3  r>  rF  r  r
  rK   rG  r   r   s   ``     @@@@@@@@@rC   r	   r	   (  s   H 	D	A344d1gU|,,CDDCx E1&IJJ
X1r6lGGE5A6AG/A4AGRBRB&A+AG&]Y&A'AG&ADAG)[>)-A5AG#Y#4ADAG4AIAGaBaB*A1AG!$9&"DEE	C	= 	= K		H 	H	G 	G -1&f[A
 .1&f[A
rB   r   	exclusive)rK   methodc                @   US:  a  [        S5      e[        U 5      n [        U 5      nUS:  a  US:X  a  XS-
  -  $ [        S5      eUS:X  aT  US-
  n/ n[        SU5       H;  n[	        Xd-  U5      u  pxX   X-
  -  XS-      U-  -   U-  n	UR                  U	5        M=     U$ US:X  ak  US-   n/ n[        SU5       HR  nXd-  U-  nUS:  a  SOXsS-
  :  a  US-
  OUnXd-  Xq-  -
  nXS-
     X-
  -  X   U-  -   U-  n	UR                  U	5        MT     U$ [        SU< 35      e)ae  Divide *data* into *n* continuous intervals with equal probability.

Returns a list of (n - 1) cut points separating the intervals.

Set *n* to 4 for quartiles (the default).  Set *n* to 10 for deciles.
Set *n* to 100 for percentiles which gives the 99 cuts points that
separate *data* in to 100 equal sized groups.

The *data* can be any iterable containing sample.
The cut points are linearly interpolated between data points.

If *method* is set to *inclusive*, *data* is treated as population
data.  The minimum value is treated as the 0th percentile and the
maximum value is treated as the 100th percentile.
rE   zn must be at least 1r   z!must have at least one data point	inclusiverN  Unknown method: )r   r   r   rangedivmodappendr   )
rZ   rK   rO  ldr   r   r   r   deltainterpolateds
             rC   r   r   !  s\     	1u455$<D	TB	Av7q5>!ABBFq!AaeQ'HA Gqy1DQK%4GG1LLMM,'  Fq!A
AUqD1aAC!#IE QK195%G1LLMM,'  
'z2
33rB   c                 b    [        X5      u  p#pEUS:  a  [        S5      e[        X5S-
  -  U5      $ )a^  Return the sample variance of data.

data should be an iterable of Real-valued numbers, with at least two
values. The optional argument xbar, if given, should be the mean of
the data. If it is missing or None, the mean is automatically calculated.

Use this function when your data is a sample from a population. To
calculate the variance from the entire population, see ``pvariance``.

Examples:

>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> variance(data)
1.3720238095238095

If you have already calculated the mean of your data, you can pass it as
the optional second argument ``xbar`` to avoid recalculating it:

>>> m = mean(data)
>>> variance(data, m)
1.3720238095238095

This function does not check that ``xbar`` is actually the mean of
``data``. Giving arbitrary values for ``xbar`` may lead to invalid or
impossible results.

Decimals and Fractions are supported:

>>> from decimal import Decimal as D
>>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
Decimal('31.01875')

>>> from fractions import Fraction as F
>>> variance([F(1, 6), F(1, 2), F(5, 3)])
Fraction(67, 108)

r   z*variance requires at least two data pointsrE   rp   r   r   )rZ   xbarrb   ssrg   rK   s         rC   r   r   W  s8    L d/KA11uJKKBa%L!$$rB   c                 \    [        X5      u  p#pEUS:  a  [        S5      e[        X5-  U5      $ )a  Return the population variance of ``data``.

data should be a sequence or iterable of Real-valued numbers, with at least one
value. The optional argument mu, if given, should be the mean of
the data. If it is missing or None, the mean is automatically calculated.

Use this function to calculate the variance from the entire population.
To estimate the variance from a sample, the ``variance`` function is
usually a better choice.

Examples:

>>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
>>> pvariance(data)
1.25

If you have already calculated the mean of the data, you can pass it as
the optional second argument to avoid recalculating it:

>>> mu = mean(data)
>>> pvariance(data, mu)
1.25

Decimals and Fractions are supported:

>>> from decimal import Decimal as D
>>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
Decimal('24.815')

>>> from fractions import Fraction as F
>>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
Fraction(13, 72)

rE   z*pvariance requires at least one data pointrZ  )rZ   murb   r\  rg   rK   s         rC   r   r     s4    F d-KA11uJKKBFArB   c                     [        X5      u  p#pEUS:  a  [        S5      eX5S-
  -  n[        U[        5      (       a   [	        UR
                  UR                  5      $ [        UR
                  UR                  5      $ )zReturn the square root of the sample variance.

See ``variance`` for arguments and other details.

>>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
1.0810874155219827

r   'stdev requires at least two data pointsrE   rp   r   rw   r   r   r   r   r   )rZ   r[  rb   r\  rg   rK   msss          rC   r   r     sf     d/KA11uGHH
A,C!W$S]]COODDs}}coo>>rB   c                     [        X5      u  p#pEUS:  a  [        S5      eX5-  n[        U[        5      (       a   [	        UR
                  UR                  5      $ [        UR
                  UR                  5      $ )zReturn the square root of the population variance.

See ``pvariance`` for arguments and other details.

>>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
0.986893273527251

rE   z'pstdev requires at least one data pointra  )rZ   r^  rb   r\  rg   rK   rb  s          rC   r   r     sb     d-KA11uGHH
&C!W$S]]COODDs}}coo>>rB   c                 
   [        U 5      u  pp4US:  a  [        S5      eX$S-
  -  n [        U5      [        UR                  UR
                  5      4$ ! [         a%    [        U5      [        U5      [        U5      -  4s $ f = f)zFIn one pass, compute the mean and sample standard deviation as floats.r   r`  rE   )rp   r   rx   r   r   r   rs   )rZ   rb   r\  r[  rK   rb  s         rC   _mean_stdevre    s|    YNA41uGHH
A,C4T{/sOOO 4T{E$K%)3334s   *A ,BBrf   yc                 T   [        X-  5      n[        U5      (       dG  [        U5      (       a5  [        U 5      (       d%  [        U5      (       d  Sn[        X0-  X1-  5      U-  $ U$ U(       d%  U (       a  U(       a  Sn[        X0-  X1-  5      U-  $ U$ [	        X4X* 45      nX$SU-  -  -   $ )zRReturn sqrt(x * y) computed with improved accuracy and without overflow/underflow.g      g      ar9   )r"   r*   r+   	_sqrtprodr)   )rf   rf  r4  scalerJ   s        rC   rh  rh    s    QUAA;;88E!HHU1XXEUY	2U:: EUY	2U:: 	B AC!G}rB   c                   ^^ [        U 5      n[        U5      U:w  a  [        S5      eUS:  a  [        S5      e[        U 5      U-  m[        U5      U-  m[        U4S jU  5       U4S jU 5       5      nX2S-
  -  $ )a@  Covariance

Return the sample covariance of two inputs *x* and *y*. Covariance
is a measure of the joint variability of two inputs.

>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> covariance(x, y)
0.75
>>> z = [9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> covariance(x, z)
-7.5
>>> covariance(z, x)
-7.5

zDcovariance requires that both inputs have same number of data pointsr   z,covariance requires at least two data pointsc              3   ,   >#    U  H	  oT-
  v   M     g 7frG   r<   )rI   xir[  s     rC   rL   covariance.<locals>.<genexpr>  s     )q9q   c              3   ,   >#    U  H	  oT-
  v   M     g 7frG   r<   rI   yiybars     rC   rL   rm    s     +B"Irn  rE   )r   r   r(   r)   )rf   rf  rK   sxyr[  rr  s       @@rC   r   r     sv    " 	AA
1v{dee1uLMM7Q;D7Q;D
)q)+B+B
CCa%=rB   linear)rO  c                  [        U 5      n[        U5      U:w  a  [        S5      eUS:  a  [        S5      eUS;  a  [        SU< 35      eUS:X  a  US-
  S-  n[        XS	9n [        XS	9nOD[	        U 5      U-  n[	        U5      U-  nU  Vs/ s H  owU-
  PM	     n nU Vs/ s H  oU-
  PM	     nn[        X5      n	[        X 5      n
[        X5      n U	[        X5      -  $ s  snf s  snf ! [         a    [        S
5      ef = f)a(  Pearson's correlation coefficient

Return the Pearson's correlation coefficient for two inputs. Pearson's
correlation coefficient *r* takes values between -1 and +1. It measures
the strength and direction of a linear relationship.

>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> correlation(x, x)
1.0
>>> correlation(x, y)
-1.0

If *method* is "ranked", computes Spearman's rank correlation coefficient
for two inputs.  The data is replaced by ranks.  Ties are averaged
so that equal values receive the same rank.  The resulting coefficient
measures the strength of a monotonic relationship.

Spearman's rank correlation coefficient is appropriate for ordinal
data or for continuous data that doesn't meet the linear proportion
requirement for Pearson's correlation coefficient.
zEcorrelation requires that both inputs have same number of data pointsr   z-correlation requires at least two data points>   rt  rankedrR  rv  rE   r   r   z&at least one of the inputs is constant)r   r   r   r   r(   r)   rh  r   )rf   rf  rO  rK   r   r[  rr  rl  rq  rs  ro   syys               rC   r   r     s   . 	AA
1v{eff1uMNN))+F:677Q"!!!!Aw{Aw{!"#2$Y#!"#2$Y#
!-C
!-C
!-CHYs((( $#  HFGGHs   C!!C&C+ +DLinearRegressionslope	intercept)proportionalc                 ^
 [        U 5      n[        U5      U:w  a  [        S5      eUS:  a  [        S5      eU(       d<  [        U 5      U-  n[        U5      U-  m
U  Vs/ s H  oUU-
  PM	     n nU
4S jU 5       n[        X5      S-   n[        X 5      n Xg-  nU(       a  SOT
UW-  -
  n	[        XS9$ s  snf ! [         a    [        S5      ef = f)aO  Slope and intercept for simple linear regression.

Return the slope and intercept of simple linear regression
parameters estimated using ordinary least squares. Simple linear
regression describes relationship between an independent variable
*x* and a dependent variable *y* in terms of a linear function:

    y = slope * x + intercept + noise

where *slope* and *intercept* are the regression parameters that are
estimated, and noise represents the variability of the data that was
not explained by the linear regression (it is equal to the
difference between predicted and actual values of the dependent
variable).

The parameters are returned as a named tuple.

>>> x = [1, 2, 3, 4, 5]
>>> noise = NormalDist().samples(5, seed=42)
>>> y = [3 * x[i] + 2 + noise[i] for i in range(5)]
>>> linear_regression(x, y)  #doctest: +ELLIPSIS
LinearRegression(slope=3.17495..., intercept=1.00925...)

If *proportional* is true, the independent variable *x* and the
dependent variable *y* are assumed to be directly proportional.
The data is fit to a line passing through the origin.

Since the *intercept* will always be 0.0, the underlying linear
function simplifies to:

    y = slope * x + noise

>>> y = [3 * x[i] + noise[i] for i in range(5)]
>>> linear_regression(x, y, proportional=True)  #doctest: +ELLIPSIS
LinearRegression(slope=2.90475..., intercept=0.0)

zKlinear regression requires that both inputs have same number of data pointsr   z3linear regression requires at least two data pointsc              3   ,   >#    U  H	  oT-
  v   M     g 7frG   r<   rp  s     rC   rL   $linear_regression.<locals>.<genexpr>w  s     #2$Yrn  r   zx is constantry  )r   r   r(   r)   r   rx  )rf   rf  r|  rK   r[  rl  rs  ro   rz  r{  rr  s             @rC   r   r   H  s    L 	AA
1v{kll1uSTTAw{Aw{!"#2$Y###
!-#
C
!-C/	 $)<I%== $  /o../s   B3B8 8Cc                    U S-
  n[        U5      S::  am  SX3-  -
  nSU-  S-   U-  S-   U-  S-   U-  S-   U-  S	-   U-  S
-   U-  S-   U-  nSU-  S-   U-  S-   U-  S-   U-  S-   U-  S-   U-  S-   U-  S-   nXV-  nXU-  -   $ US::  a  U OSU -
  n[        [        U5      * 5      nUS::  a^  US-
  nSU-  S-   U-  S-   U-  S-   U-  S-   U-  S-   U-  S-   U-  S-   nSU-  S -   U-  S!-   U-  S"-   U-  S#-   U-  S$-   U-  S%-   U-  S-   nO]US-
  nS&U-  S'-   U-  S(-   U-  S)-   U-  S*-   U-  S+-   U-  S,-   U-  S--   nS.U-  S/-   U-  S0-   U-  S1-   U-  S2-   U-  S3-   U-  S4-   U-  S-   nXV-  nUS:  a  U* nXU-  -   $ )5Nr   g333333?gQ?g^}o)@gE.kR@g Ul@g*u>l@gN@g"]Ξ@gnC`@gu@giK~j@gv|E@gd|1@gfRr@gu.2@g~y@gn8(E@r   r   g      @g?g鬷ZaI?ggElD?g7\?guSS?g=.@gj%b@gHw@gjRe?g9dh?>g('߿A?g~z ?g@3?gɅ3?g3fRx?gIFl @gt>g*Yn>gESB\T?gN;A+?gUR1?gEF?gPn@g&>@gi<g@F>gtcI,\>gŝI?g*F2v?gC4?gO1?)r#   r"   r'   )pr^  sigmar   rr   r   rf   s           rC   _normal_dist_inv_cdfr    s    	
CAAw%qu0140145601456 11 566 1	1 56	6
 11
 566 11 566 11 566 1140145601456 11 566 1	1 56	6
 11
 566 11 566  IY#X37Ac!fWACxG1A51256712567 22 677 2	2 67	7
 22
 677 22 677 22 2A51256712567 22 677 2	2 67	7
 22
 677 22 677  G1A51256712567 22 677 2	2 67	7
 22
 677 22 677 22 3Q61256712567 22 677 2	2 67	7
 22
 677 22 677  		A3wBUrB   )r  c                      \ rS rSrSrSSS.rS"S jr\S 5       rSS	.S
 jr	S r
S rS rS#S jrS rS r\S 5       r\S 5       r\S 5       r\S 5       r\S 5       rS rS rS rS rS rS r\rS r\rS rS r S r!S  r"S! r#Sr$g)$r   i  z(Normal distribution of a random variablez(Arithmetic mean of a normal distributionz+Standard deviation of a normal distribution_mu_sigmac                 f    US:  a  [        S5      e[        U5      U l        [        U5      U l        g)zDNormalDist where mu is the mean and sigma is the standard deviation.r   zsigma must be non-negativeN)r   rx   r  r  )selfr^  r  s      rC   __init__NormalDist.__init__  s+    3;!">??9ElrB   c                     U " [        U5      6 $ )z5Make a normal distribution instance from sample data.)re  )clsrZ   s     rC   from_samplesNormalDist.from_samples  s     K%&&rB   Nseedc                    Uc  [         R                   O[         R                  " U5      R                   n[        nU R                  nU R                  n[        SU5       Vs/ s H  ot" U" 5       XV5      PM     sn$ s  snf )z=Generate *n* samples for a given mean and standard deviation.N)randomRandomr  r  r  r   )r  rK   r  rndinv_cdfr^  r  r   s           rC   samplesNormalDist.samples  s^    #|fmmt1D1K1K&XX39$?C?ar)?CCCs    A:c                     U R                   U R                   -  nU(       d  [        S5      eXR                  -
  n[        X3-  SU-  -  5      [	        [
        U-  5      -  $ )z4Probability density function.  P(x <= X < x+dx) / dxz$pdf() not defined when sigma is zerog       )r  r   r  r$   r"   r&   )r  rf   r   diffs       rC   r9  NormalDist.pdf  sR    ;;,!"HII88|4;$/23d3>6JJJrB   c                     U R                   (       d  [        S5      eSS[        XR                  -
  U R                   [        -  -  5      -   -  $ )z,Cumulative distribution function.  P(X <= x)z$cdf() not defined when sigma is zeror   r   )r  r   r%   r  _SQRT2r  rf   s     rC   r@  NormalDist.cdf  s>    {{!"HIIcCXX$++2F GHHIIrB   c                 p    US::  d  US:  a  [        S5      e[        XR                  U R                  5      $ )a#  Inverse cumulative distribution function.  x : P(X <= x) = p

Finds the value of the random variable such that the probability of
the variable being less than or equal to that value equals the given
probability.

This function is also called the percent point function or quantile
function.
r   r   z$p must be in the range 0.0 < p < 1.0)r   r  r  r  )r  r  s     rC   r  NormalDist.inv_cdf  s2     8qCx!"HII#Axx==rB   c                 f    [        SU5       Vs/ s H  o R                  X!-  5      PM     sn$ s  snf )aF  Divide into *n* continuous intervals with equal probability.

Returns a list of (n - 1) cut points separating the intervals.

Set *n* to 4 for quartiles (the default).  Set *n* to 10 for deciles.
Set *n* to 100 for percentiles which gives the 99 cuts points that
separate the normal distribution in to 100 equal sized groups.
rE   )rS  r  )r  rK   r   s      rC   r   NormalDist.quantiles  s+     .31a[9[QU#[999s   .c           	      4   [        U[        5      (       d  [        S5      eXp2UR                  UR                  4UR                  UR                  4:  a  X2p2UR
                  UR
                  pTU(       a  U(       d  [        S5      eXT-
  n[        UR                  UR                  -
  5      nU(       d%  S[        USUR                  -  [        -  -  5      -
  $ UR                  U-  UR                  U-  -
  nUR                  UR                  -  [        Xw-  U[        XT-  5      -  -   5      -  n	X-   U-  n
X-
  U-  nS[        UR                  U
5      UR                  U
5      -
  5      [        UR                  U5      UR                  U5      -
  5      -   -
  $ )az  Compute the overlapping coefficient (OVL) between two normal distributions.

Measures the agreement between two normal probability distributions.
Returns a value between 0.0 and 1.0 giving the overlapping area in
the two underlying probability density functions.

    >>> N1 = NormalDist(2.4, 1.6)
    >>> N2 = NormalDist(3.2, 2.0)
    >>> N1.overlap(N2)
    0.8035050657330205
z$Expected another NormalDist instancez(overlap() not defined when sigma is zeror   r9   )r   r   ry   r  r  r   r   r#   r%   r  r"   r'   r@  )r  otherXYX_varY_vardvr   r   bx1x2s               rC   overlapNormalDist.overlap  sN     %,,BCC1HHaee!%%00qzz1::uE!"LMM]!%%!%%- R3>F#:;<<<EEEMAEEEM)HHqxx$rwc%-6H1H'H"IIer\er\d1559quuRy01DrQUU2Y9N4OOPPrB   c                 p    U R                   (       d  [        S5      eXR                  -
  U R                   -  $ )zCompute the Standard Score.  (x - mean) / stdev

Describes *x* in terms of the number of standard deviations
above or below the mean of the normal distribution.
z'zscore() not defined when sigma is zero)r  r   r  r  s     rC   zscoreNormalDist.zscore=  s,     {{!"KLLHH++rB   c                     U R                   $ )z+Arithmetic mean of the normal distribution.r  r  s    rC   r   NormalDist.meanH       xxrB   c                     U R                   $ )z,Return the median of the normal distributionr  r  s    rC   r   NormalDist.medianM  r  rB   c                     U R                   $ )zReturn the mode of the normal distribution

The mode is the value x where which the probability density
function (pdf) takes its maximum value.
r  r  s    rC   r   NormalDist.modeR  s     xxrB   c                     U R                   $ )z.Standard deviation of the normal distribution.r  r  s    rC   r   NormalDist.stdev[  s     {{rB   c                 4    U R                   U R                   -  $ )z!Square of the standard deviation.r  r  s    rC   r   NormalDist.variance`  s     {{T[[((rB   c                     [        U[        5      (       aA  [        U R                  UR                  -   [        U R                  UR                  5      5      $ [        U R                  U-   U R                  5      $ )a:  Add a constant or another NormalDist instance.

If *other* is a constant, translate mu by the constant,
leaving sigma unchanged.

If *other* is a NormalDist, add both the means and the variances.
Mathematically, this works only if the two distributions are
independent or if they are jointly normally distributed.
r   r   r  r!   r  r  r  s     rC   __add__NormalDist.__add__e  R     b*%%bffrvvouRYY		/JKK"&&2+ryy11rB   c                     [        U[        5      (       aA  [        U R                  UR                  -
  [        U R                  UR                  5      5      $ [        U R                  U-
  U R                  5      $ )aC  Subtract a constant or another NormalDist instance.

If *other* is a constant, translate by the constant mu,
leaving sigma unchanged.

If *other* is a NormalDist, subtract the means and add the variances.
Mathematically, this works only if the two distributions are
independent or if they are jointly normally distributed.
r  r  s     rC   __sub__NormalDist.__sub__s  r  rB   c                 `    [        U R                  U-  U R                  [        U5      -  5      $ )zMultiply both mu and sigma by a constant.

Used for rescaling, perhaps to change measurement units.
Sigma is scaled with the absolute value of the constant.
r   r  r  r#   r  s     rC   __mul__NormalDist.__mul__  &     "&&2+ryy48';<<rB   c                 `    [        U R                  U-  U R                  [        U5      -  5      $ )zDivide both mu and sigma by a constant.

Used for rescaling, perhaps to change measurement units.
Sigma is scaled with the absolute value of the constant.
r  r  s     rC   __truediv__NormalDist.__truediv__  r  rB   c                 B    [        U R                  U R                  5      $ )zReturn a copy of the instance.r   r  r  r  s    rC   __pos__NormalDist.__pos__  s    "&&")),,rB   c                 D    [        U R                  * U R                  5      $ )z(Negates mu while keeping sigma the same.r  r  s    rC   __neg__NormalDist.__neg__  s    266'299--rB   c                     X-
  * $ )z<Subtract a NormalDist from a constant or another NormalDist.r<   r  s     rC   __rsub__NormalDist.__rsub__  s    zrB   c                     [        U[        5      (       d  [        $ U R                  UR                  :H  =(       a    U R                  UR                  :H  $ )zFTwo NormalDist objects are equal if their mu and sigma are both equal.)r   r   NotImplementedr  r  r  s     rC   __eq__NormalDist.__eq__  s:    "j))!!vv:BII$::rB   c                 D    [        U R                  U R                  45      $ )zCNormalDist objects hash equal if their mu and sigma are both equal.)hashr  r  r  s    rC   __hash__NormalDist.__hash__  s    TXXt{{+,,rB   c                 j    [        U 5      R                   SU R                  < SU R                  < S3$ )Nz(mu=z, sigma=))rR   r=   r  r  r  s    rC   __repr__NormalDist.__repr__  s.    t*%%&d488,ht{{oQOOrB   c                 2    U R                   U R                  4$ rG   r  r  s    rC   __getstate__NormalDist.__getstate__  s    xx$$rB   c                 "    Uu  U l         U l        g rG   r  )r  states     rC   __setstate__NormalDist.__setstate__  s     %$+rB   )r   r   )r   )%r=   r>   r?   r@   rK  	__slots__r  classmethodr  r  r9  r@  r  r   r  r  propertyr   r   r   r   r   r  r  r  r  r  r  __radd__r  __rmul__r  r  r  r  r  rA   r<   rB   rC   r   r     s	   .
 :?I
# ' ' "& DKJ>	: QD	,         ) )22==-. H H;-P%&rB   r   c                     ^ ^^^ UU UU4S jnU$ )Nc                    > T" U 5      n[        T" U5      U -
  =n5      T:  a)  XT" U5      -  -  n[        T" U5      U -
  =n5      T:  a  M)  U$ )u=   Return x such that f(x) ≈ y within the specified tolerance.r  )rf  rf   r  r   f_inv_estimatef_prime	tolerances      rC   f_inv_newton_raphson.<locals>.f_inv  sY    1!A$("$#i/
""A !A$("$#i/rB   r<   )r  r   r  r  r  s   ```` rC   _newton_raphsonr    s      LrB   c                     U S::  a  SU 4OSSU -
  4u  pSU -  S-  S-
  nU Ss=:  a  S:  a  O  X!-  $ US[        S	U -  S
-   5      -  -  nX!-  $ )Nr   r         r9   g鼹A?gMbp?gV-?gMp^v?g$2h@g_@r-  r  signrf   s      rC   _quartic_invcdf_estimater    sk    s(sAhsQwGD	q_$s*AEE8O 	
[3{Q1AABBB8OrB   c                 6    SU S-  -  SU S-  -  -
  SU -  -   S-   $ r!  r<   r  s    rC   r   r     s'    $A+ad
*UQY6<rB   c                     SSX -  -
  S-  -  $ r  r<   r  s    rC   r   r         qu 22rB   )r  r   r  c                 F    U S::  a  SU 4OSSU -
  4u  pSU -  S-  S-
  nX!-  $ )Nr   r   r  r9   gc?r<   r   s      rC   _triweight_invcdf_estimater    s8    s(sAhsQwGD	q''#-A8OrB   c                 B    SSU S-  -  SU S-  -  -   U S-  -
  U -   -  S-   $ r(  r<   r  s    rC   r   r     s1    %419s1a4x/!Q$6:;cArB   c                     SSX -  -
  S-  -  $ r%  r<   r  s    rC   r   r     r  rB   c                 $    [        U SU -
  -  5      $ )NrE   )r'   r  s    rC   r   r     s    #a1q5k*rB   c                 >    [        [        U [        -  S-  5      5      $ )Nr   )r'   r/   r,   r  s    rC   r   r     s    SR]+rB   c                     SU -  S-
  $ Nr   rE   r<   r  s    rC   r   r     s    QqS1WrB   c                 P    S[        [        SU -  S-
  5      [        -   S-  5      -  $ )Nr   rE   r   )r-   r3   r,   r  s    rC   r   r     s$    1sD1QK"$4#9::rB   c                 X    U S:  a  [        SU -  5      S-
  $ S[        SSU -  -
  5      -
  $ )Nr   r   rE   )r"   r  s    rC   r   r     s/    QWD1IMK!d1qs7m:KKrB   c                 8    S[        SU -  S-
  5      -  [        -  $ r  )r1   r,   r  s    rC   r   r     s    D1qM)B.rB   )	r   r   r  r  r  r  r#  r  r*  r   r  r  r  r  r  r  r  c                  ^ ^^^^	 [        T 5      nU(       d  [        S5      e[        T S   [        [        45      (       d  [        S5      eTS::  a  [        ST< 35      e[        R                  U5      mTc  [        SU< 35      e[        R                  U5      nUR                  m	UR                  mUU UUU	4S jnST< S	U< 3Ul        U$ )
a<  Return a function that makes a random selection from the estimated
probability density function created by kde(data, h, kernel).

Providing a *seed* allows reproducible selections within a single
thread.  The seed may be an integer, float, str, or bytes.

A StatisticsError will be raised if the *data* sequence is empty.

Example:

>>> data = [-2.1, -1.3, -0.4, 1.9, 5.1, 6.2]
>>> rand = kde_random(data, h=1.5, seed=8675309)
>>> new_selections = [rand() for i in range(10)]
>>> [round(x, 1) for x in new_selections]
[0.7, 6.2, 1.2, 6.9, 7.0, 1.8, 2.5, -0.5, -1.8, 5.6]

r   r   r   r   r   r.  c                  6   > T " T5      TT" T" 5       5      -  -   $ rG   r<   )choicerZ   r4  kernel_invcdfr  s   rC   randkde_random.<locals>.rand
  s    d|a-"9999rB   zRandom KDE selection with h=rJ  )r   r   r   rY   rx   ry   _kernel_invcdfsrQ   _randomr  r  r  rK  )
rZ   r4  rL  r  rK   prngr  r  r  r  s
   ``     @@@rC   r
   r
     s    $ 	D	A344d1gU|,,CDDCx E1&IJJ#''/M 5fZ@AA>>$D[[F[[F: : 3v]6+FDLKrB   rG   )znegative value)r   )r   )g-q=)drK  __all__rt   r   r  sys	fractionsr   decimalr   	itertoolsr   r   r   bisectr   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   	functoolsr4   operatorr5   collectionsr6   r7   r8   r  r  r   r   rc   rp   rU   rX   rT   r   r   r   rx   r   rY   r   
float_infomant_digr   __annotations__r   r   r   r   r   r   r   r   r   r   r   r   r	   r   r   r   r   r   re  rh  r   r   rx  r   r  _statisticsImportErrorr   r  r  _quartic_invcdfr  _triweight_invcdfr  r  r
   r<   rB   rC   <module>r+     s  hT2    
   , , , E E E K K K   8 8	c
	j 	3l&R 4>+\$ IQ 34PU; 3l    3>>222Q6 6
#3 
#3 
#5 
#S S W <",!H F5,p+0 ,&E+PB<K(Q Qr ; -4l)%X&R?$?$
4 5 U :8 $, -H` 02HI  05 7>zGV	0
\& \&B "-<24

 $/A24  l""*+$:"K.
 +84 ,];	 "1+"> -i8
 ) )i  		s   0G* *G32G3