
    (phc                     @   S SK r S SKJr  S SKrS SKJrJr  S SKJ	r	J
r
  S r " S S5      rSSS\R                  S	.S
 jjr\" SS5      r\
" S5      SSSSSSS.S j5       rS rSS jr\R&                  \0rS rS rS rS S jrS rS rS\l        S r\\\\S.rS rg)!    N)
namedtuple)optimizestats)check_random_state_transition_to_rngc                 2   [         R                  " U5      nUS   US   :  a  SU  S[        U5       S3n[        U5      e[	        US   US   5      [        US   US   5      4nU(       aE  [         R                  " US   5      [         R                  " US   5      :  a  SU  S3n[        U5      eU(       d  US   US   :  a  SU  S3n[        U5      e[         R                  " [         R                  " U5      5      (       d  SU  S	U  S
3n[        U5      eU$ )zCIntersection of user-defined bounds and distribution PDF/PMF domainr      zThere are no values for `z` on the interval .z!There are no integer values for `zY` on the interval defined by the user-provided bounds and the domain of the distribution.z.The intersection of user-provided bounds for `z\` and the domain of the distribution is not finite. Please provide finite bounds for shape `z` in `bounds`.)
np
atleast_1dlist
ValueErrormaxminceilfloorallisfinite)nameuser_boundsshape_domainintegralmessageboundss         C/var/www/html/venv/lib/python3.13/site-packages/scipy/stats/_fit.py_combine_boundsr      s4    --,K1~A&.tf4F;'(+!!+a.,q/2+a.,q/24F RWWVAY'"((6!9*==6tf =* * !!6!9vay0.tf 5* * !!66"++f%&&CD6 J77;fNL !!M    c                   h    \ rS rSrSrS rS rSS jrSSS.S	 jjrS
 r	S r
S rS rSS jrS rSrg)	FitResult)   a  Result of fitting a discrete or continuous distribution to data

Attributes
----------
params : namedtuple
    A namedtuple containing the maximum likelihood estimates of the
    shape parameters, location, and (if applicable) scale of the
    distribution.
success : bool or None
    Whether the optimizer considered the optimization to terminate
    successfully or not.
message : str or None
    Any status message provided by the optimizer.

c                    Xl         X l        X0l        [        USS 5      =(       d    [        USS 5      U l        UR
                  c  / OUR
                  R                  S5      nU(       d  [        SUSS/-   5      nO[        SUS/-   5      nU" UR                  6 U l	        UR                  (       a7  [        R                  " U R                  5       5      (       d  SUl
        SUl        [        US	S 5      U l
        [        US
S 5      U l        g )Npmfpdf, 	FitParamslocscaleFzOOptimization converged to parameter values that are inconsistent with the data.successr   )_dist_datadiscretegetattrpxfshapessplitr   xparamsr(   r   r   nllfr   )selfdistdatar+   resshape_namesr%   s          r   __init__FitResult.__init__:   s    

 4-Kud1K KK/bT[[5F5Ft5L";ug>N0NOI";ug0EFI' ;;r{{499;77CK=CKsIt4sIt4r   c                     / SQn[        [        [        U5      5      S-   nSR                  U Vs/ s H:  n[	        X5      c  M  UR                  U5      S-   [        [	        X5      5      -   PM<     sn5      $ s  snf )N)r1   r(   r   r	   
z: )r   maplenjoinr,   rjustrepr)r3   keysmkeys       r   __repr__FitResult.__repr__P   sx    /C!#yy%)M%)cWT-? I#))A,-WT5G0HH%)M N 	N Ms   A8-A8Nc                 x    Ub  UOU R                   nUb  UOU R                  nU R                  R                  XS9$ )aS  Negative log-likelihood function

Evaluates the negative of the log-likelihood function of the provided
data at the provided parameters.

Parameters
----------
params : tuple, optional
    The shape parameters, location, and (if applicable) scale of the
    distribution as a single tuple. Default is the maximum likelihood
    estimates (``self.params``).
data : array_like, optional
    The data for which the log-likelihood function is to be evaluated.
    Default is the data to which the distribution was fit.

Returns
-------
nllf : float
    The negative of the log-likelihood function.

)thetar0   )r1   r*   r)   nnlf)r3   r1   r5   s      r   r2   FitResult.nllfV   s9    , "-4;;'tTZZzzV44r   hist)	plot_typec                    SSK nU R                  U R                  U R                  U R
                  U R                  S.nUR                  5       U;  a'  S[        UR                  5       5       3n[        U5      eXbR                  5          nUc  SSK
Jn  UR                  5       n[        R                  " U R                  5      n	U" XS9$ ! [         a  nSn[        U5      UeSnAff = f)a|  Visually compare the data against the fitted distribution.

Available only if `matplotlib` is installed.

Parameters
----------
ax : `matplotlib.axes.Axes`
    Axes object to draw the plot onto, otherwise uses the current Axes.
plot_type : {"hist", "qq", "pp", "cdf"}
    Type of plot to draw. Options include:

    - "hist": Superposes the PDF/PMF of the fitted distribution
      over a normalized histogram of the data.
    - "qq": Scatter plot of theoretical quantiles against the
      empirical quantiles. Specifically, the x-coordinates are the
      values of the fitted distribution PPF evaluated at the
      percentiles ``(np.arange(1, n) - 0.5)/n``, where ``n`` is the
      number of data points, and the y-coordinates are the sorted
      data points.
    - "pp": Scatter plot of theoretical percentiles against the
      observed percentiles. Specifically, the x-coordinates are the
      percentiles ``(np.arange(1, n) - 0.5)/n``, where ``n`` is
      the number of data points, and the y-coordinates are the values
      of the fitted distribution CDF evaluated at the sorted
      data points.
    - "cdf": Superposes the CDF of the fitted distribution over the
      empirical CDF. Specifically, the x-coordinates of the empirical
      CDF are the sorted data points, and the y-coordinates are the
      percentiles ``(np.arange(1, n) - 0.5)/n``, where ``n`` is
      the number of data points.

Returns
-------
ax : `matplotlib.axes.Axes`
    The matplotlib Axes object on which the plot was drawn.

Examples
--------
>>> import numpy as np
>>> from scipy import stats
>>> import matplotlib.pyplot as plt  # matplotlib must be installed
>>> rng = np.random.default_rng()
>>> data = stats.nbinom(5, 0.5).rvs(size=1000, random_state=rng)
>>> bounds = [(0, 30), (0, 1)]
>>> res = stats.fit(stats.nbinom, data, bounds)
>>> ax = res.plot()  # save matplotlib Axes object

The `matplotlib.axes.Axes` object can be used to customize the plot.
See `matplotlib.axes.Axes` documentation for details.

>>> ax.set_xlabel('number of trials')  # customize axis label
>>> ax.get_children()[0].set_linewidth(5)  # customize line widths
>>> ax.legend()
>>> plt.show()
r   Nz2matplotlib must be installed to use method `plot`.)	histogramqqppcdfrJ   z`plot_type` must be one of )ax
fit_params)
matplotlibModuleNotFoundError
_hist_plot_qq_plot_pp_plot	_cdf_plotlowersetrA   r   matplotlib.pyplotpyplotgcar   r   r1   )
r3   rQ   rK   rS   excr   plotsplotpltrR   s
             r   r`   FitResult.plotp   s    p	8
 #ooT]]}}T^^* ??E)3C

4E3FGGW%%__&':+B]]4;;/
r11% # 	8JG%g.C7	8s   C 
C)C$$C)c                    SSK Jn  U R                  R                  " U6 n[        R
                  " US   5      (       a  US   O[        U R                  5      n[        R
                  " US   5      (       a  US   O[        U R                  5      nU R                  (       a  SOSnU R                  (       a  [        R                  " XVS-   5      nU R                  " U/UQ76 n	UR                  US S SU	S S SS	S
9  [        SUSSS9n
UR                  R                  U" SS95        UR!                  S5        UR#                  S5        Oj[        R$                  " XVS5      nU R                  " U/UQ76 n	UR'                  XSSS	S
9  [        SSSSS9n
UR!                  S5        UR#                  S5        [)        U R                  5      S:  d  U R                  (       a   UR*                  " U R                  4SS0U
D6  O;UR'                  U R                  [        R,                  " U R                  5      SSSS
9  UR/                  SU R                  R0                   SU S35        UR2                  " UR5                  5       6   U$ )Nr   )MaxNLocatorr	   PMFPDF   zFitted Distribution PMFC0)labelcolorTleftC1)densitybinsalignrk   )integerk   --zFitted Distribution PDF2   midr0   rj   zHistogram of Data*DataFitted $\tt $ z and Histogram)matplotlib.tickerrd   r)   supportr   r   r   r*   r   r+   aranger-   vlinesdictxaxisset_major_locator
set_xlabel
set_ylabellinspacer`   r=   rJ   
zeros_like	set_titler   legendget_legend_handles_labels)r3   rQ   rR   rd   r|   lbubr-   r0   yoptionss              r   rU   FitResult._hist_plot   s   1**$$j1;;wqz22WQZDJJ;;wqz22WQZDJJ}}e%==		"1f%A(Z(AIIafa3B/H   "4avTJGHH&&{4'@AMM#MM% BC(A(Z(AGGA$&?tGL4bTJGMM#MM% tzz?R4==GGDJJE&9EWEGGDJJdjj 93   . 	TZZ__$5RuNKL
		2//12	r   c                    [         R                  " U R                  5      nU R                  [	        U R                  5      5      nU(       a$  SnSnU R
                  R                  " U/UQ76 nUn	O#SnSnUnU R
                  R                  " U/UQ76 n	UR                  XSSU 3SSS	9  UR                  5       n
UR                  5       n[        U
S
   US
   5      [        U
S   US   5      /nU(       d  [        US
   S
5      [        US   S5      4nU R                  (       aR  U(       aK  [        US
   5      [        US   S-   5      p[         R                  " X5      nUR                  XSSSSSSS9  GOU R                  (       a  U(       d  Uu  nnU R
                  R                   " U6 u  nn[        U[         R"                  " U5      (       a  S
OS5      n[        U[         R"                  " U5      (       a  SOS5      nU R
                  R                  " UU//UQ76 u  p[         R                  " US-
  US-   5      nU R
                  R                  " U/UQ76 nUR%                  XUSSSSSS9  OUR                  XSSSSSS9  UR'                  U5        UR)                  U5        UR+                  SU R
                  R,                   SU 35        UR/                  SU 35        UR1                  SU R
                  R,                   SU S35        UR2                  " UR5                  5       6   UR7                  S5        U$ )N	QuantileszQ-QPercentileszP-Pr
   zFitted Distribution ri   r	   rj   rk   zorderr   o	Referencerr   g      ?noneT)rj   rk   alphamarkerfacecolorclip_ongMbP?g+?-)rj   rk   r   r   ry   z$ Theoretical zData rz   z Plotequal)r   sortr*   _plotting_positionsr=   r)   ppfrP   r`   get_xlimget_ylimr   r   r+   intr}   r|   r   stepset_xlimset_ylimr   r   r   r   r   r   
set_aspect)r3   rQ   rR   rN   r5   psqprK   r0   r   xlimylimlimq_minq_maxq_idealp_minp_maxabqss                        r   _qp_plotFitResult._qp_plot   s   wwtzz"%%c$**o6BI

r/J/AABIA

t1j1A
c#7	{!C1 	 	&{{}{{}47DG$c$q'47&;<c!fa.#c!fa.0C==Rs1v;CF1H5ii-GGGGcC  F]]2 LE5::%%z2DAqBKKNNq=EBKKNNq?E::>>5%.F:FLE57E!G,B0Z0BGGBC{#T   " GGCcCt   " 	C
C
djjoo%6nRDIJ
bTl#
TZZ__$5R	{%HI
		2//12
g	r   c                 *    U R                   " SSS0UD6$ )NrN   T r   r3   kwargss     r   rV   FitResult._qq_plot  s    }}////r   c                 *    U R                   " SSS0UD6$ )NrN   Fr   r   r   s     r   rW   FitResult._pp_plot  s    }}0000r   c                 V    [         R                  " SUS-   5      nX2-
  US-   SU-  -
  -  $ )Nr	   rg   )r   r}   )r3   nr   rr   s       r   r   FitResult._plotting_positions!  s/    IIa1A!$$r   c           	         [         R                  " U R                  5      nU R                  [	        U R                  5      5      n[	        [         R
                  " U5      5      S:  a  SOSnU R                  (       a  SOSnUR                  X4USSSS	9  UR                  5       n[         R                  " / UQS
P76 nU R                  R                  " U/UQ76 n	UR                  XSSSS	9  UR                  U5        UR                  SS5        UR                  U5        UR!                  S5        UR#                  SU R                  R$                   S35        UR'                  5       u  pUR)                  U
S S S2   US S S2   5        U$ )N   rt   r
   rr   r0   zEmpirical CDFrm   r   r   i,  zFitted Distribution CDFri   r	   CDFry   z$ and Empirical CDFrh   )r   r   r*   r   r=   uniquer+   r   r   r   r)   rP   r`   r   r   r   r   r   r   r   r   )r3   rQ   rR   r5   ecdflsxlabelr   qtcdfhandleslabelss               r   rX   FitResult._cdf_plot&  s;   wwtzz"''DJJ84)B.TC3
BoT!L{{}KK##s#zz~~a-*-
8QO
D
Aq
f
e
TZZ__$55HIJ668
		'$B$-".	r   )r*   r)   r+   r   r1   r-   r(   NNN)g      ?)__name__
__module____qualname____firstlineno____doc__r8   rD   r2   r`   rU   r   rV   rW   r   rX   __static_attributes__r   r   r   r   r   )   sF     5,N54L2 L2\!F8t01%
r   r   mle)guessmethod	optimizerc                  ^  UnUn[        T S5      (       a  SSS.nSn	O%[        T S5      (       a  SS0nSn	OS	n
[        U
5      e T R                  5       n[
        R                  " U5      nUR                  S:w  a  Sn
[        U
5      e[
        R                  " UR                  [
        R                  5      (       a/  [
        R                  " [
        R                  " U5      5      (       d  Sn
[        U
5      e[        U5      nX(       a  SOS-
  nU Vs/ s H  oR                  PM     nnSR                  U5      nSR                  USU 5      nUc  0 n[        U[         5      (       a  UR#                  U5        Un[
        R$                  " US45      n['        U5       H;  nUU   R                  nUR)                  US5      nUc  UU   R*                  nUUU'   M=     U(       a(  S[-        U5       3n
[.        R0                  " U
[2        SS9  GO  [
        R                  " U[4        S9nUR6                  S:X  a  [
        R$                  " S5      nUR                  S:w  d  UR8                  S   S:w  a  Sn
[        U
5      eUR8                  S   U:  a  SU SU S3n
[        U
5      eUR8                  S   U:  a  SU SU S3n
[        U
5      e[
        R$                  " US45      n[;        UR=                  5       5      UUS& UUS[        U5      & Un/ n['        U5       HT  nUU   R                  nUU   nUU   R*                  nUU   R>                  n[A        UUUU5      nURC                  U5        MV     [
        R                  " U5      nU Vs/ s H  oR>                  PM     nnUc  SnGO[        U[         5      (       a  [E        X5       VVs0 s H'  u  nnUR                  [
        RF                  " U5      _M)     nnn[-        U5      [-        U5      -
  n U (       a  SU  3n
[.        R0                  " U
[2        SS9  UR#                  U5        Sn
 [
        R                  " U Vs/ s H  nUUR                     PM     sn[4        S9nOSn
 [
        R                  " U[4        S9nUR                  S:w  a  [        U
5      eUR8                  S   U:  a  S U S!U S3n
[        U
5      eUR8                  S   U:  a  S"U S#U S3n
[        U
5      e[
        RF                  " USS$9nUUS[        U5      & UGb  URI                  5       n![
        RJ                  " U!U   5      U!U'   [
        RL                  " U!U:g  5      S   n"U" H<  nS%UU   R                   S&UU    S'U!U    S3n
[.        R0                  " U
[2        SS9  M>     [
        RN                  " U!USS2S4   USS2S4   5      n#[
        RL                  " U#U!:g  5      S   n$U$ H<  nS%UU   R                   S(U!U    S'U#U    S3n
[.        R0                  " U
[2        SS9  M>     U#nOSnU4U 4S) jjn%U4U 4S* jjn&U%U&S+.n'U'URQ                  5          n([
        RR                  " S,S,S-9   0 n)Ub  UU)S.'   [
        RT                  " U5      (       a  UU)S/'   Ub  UU)S0'   U" U(40 U)D6n*SSS5        [W        T XW*5      $ ! [         a!  nS
T R                   S3n
[        U
5      UeSnAff = fs  snf ! [         a  nSn
[        U
5      UeSnAff = fs  snf s  snnf s  snf ! [         a  n[        U
5      UeSnAff = f! [         a  n[        U
5      UeSnAff = f! , (       d  f       N= f)1a%  Fit a discrete or continuous distribution to data

Given a distribution, data, and bounds on the parameters of the
distribution, return maximum likelihood estimates of the parameters.

Parameters
----------
dist : `scipy.stats.rv_continuous` or `scipy.stats.rv_discrete`
    The object representing the distribution to be fit to the data.
data : 1D array_like
    The data to which the distribution is to be fit. If the data contain
    any of ``np.nan``, ``np.inf``, or -``np.inf``, the fit method will
    raise a ``ValueError``.
bounds : dict or sequence of tuples, optional
    If a dictionary, each key is the name of a parameter of the
    distribution, and the corresponding value is a tuple containing the
    lower and upper bound on that parameter.  If the distribution is
    defined only for a finite range of values of that parameter, no entry
    for that parameter is required; e.g., some distributions have
    parameters which must be on the interval [0, 1]. Bounds for parameters
    location (``loc``) and scale (``scale``) are optional; by default,
    they are fixed to 0 and 1, respectively.

    If a sequence, element *i* is a tuple containing the lower and upper
    bound on the *i*\ th parameter of the distribution. In this case,
    bounds for *all* distribution shape parameters must be provided.
    Optionally, bounds for location and scale may follow the
    distribution shape parameters.

    If a shape is to be held fixed (e.g. if it is known), the
    lower and upper bounds may be equal. If a user-provided lower or upper
    bound is beyond a bound of the domain for which the distribution is
    defined, the bound of the distribution's domain will replace the
    user-provided value. Similarly, parameters which must be integral
    will be constrained to integral values within the user-provided bounds.
guess : dict or array_like, optional
    If a dictionary, each key is the name of a parameter of the
    distribution, and the corresponding value is a guess for the value
    of the parameter.

    If a sequence, element *i* is a guess for the *i*\ th parameter of the
    distribution. In this case, guesses for *all* distribution shape
    parameters must be provided.

    If `guess` is not provided, guesses for the decision variables will
    not be passed to the optimizer. If `guess` is provided, guesses for
    any missing parameters will be set at the mean of the lower and
    upper bounds. Guesses for parameters which must be integral will be
    rounded to integral values, and guesses that lie outside the
    intersection of the user-provided bounds and the domain of the
    distribution will be clipped.
method : {'mle', 'mse'}
    With ``method="mle"`` (default), the fit is computed by minimizing
    the negative log-likelihood function. A large, finite penalty
    (rather than infinite negative log-likelihood) is applied for
    observations beyond the support of the distribution.
    With ``method="mse"``, the fit is computed by minimizing
    the negative log-product spacing function. The same penalty is applied
    for observations beyond the support. We follow the approach of [1]_,
    which is generalized for samples with repeated observations.
optimizer : callable, optional
    `optimizer` is a callable that accepts the following positional
    argument.

    fun : callable
        The objective function to be optimized. `fun` accepts one argument
        ``x``, candidate shape parameters of the distribution, and returns
        the objective function value given ``x``, `dist`, and the provided
        `data`.
        The job of `optimizer` is to find values of the decision variables
        that minimizes `fun`.

    `optimizer` must also accept the following keyword argument.

    bounds : sequence of tuples
        The bounds on values of the decision variables; each element will
        be a tuple containing the lower and upper bound on a decision
        variable.

    If `guess` is provided, `optimizer` must also accept the following
    keyword argument.

    x0 : array_like
        The guesses for each decision variable.

    If the distribution has any shape parameters that must be integral or
    if the distribution is discrete and the location parameter is not
    fixed, `optimizer` must also accept the following keyword argument.

    integrality : array_like of bools
        For each decision variable, True if the decision variable
        must be constrained to integer values and False if the decision
        variable is continuous.

    `optimizer` must return an object, such as an instance of
    `scipy.optimize.OptimizeResult`, which holds the optimal values of
    the decision variables in an attribute ``x``. If attributes
    ``fun``, ``status``, or ``message`` are provided, they will be
    included in the result object returned by `fit`.

Returns
-------
result : `~scipy.stats._result_classes.FitResult`
    An object with the following fields.

    params : namedtuple
        A namedtuple containing the maximum likelihood estimates of the
        shape parameters, location, and (if applicable) scale of the
        distribution.
    success : bool or None
        Whether the optimizer considered the optimization to terminate
        successfully or not.
    message : str or None
        Any status message provided by the optimizer.

    The object has the following method:

    nllf(params=None, data=None)
        By default, the negative log-likelihood function at the fitted
        `params` for the given `data`. Accepts a tuple containing
        alternative shapes, location, and scale of the distribution and
        an array of alternative data.

    plot(ax=None)
        Superposes the PDF/PMF of the fitted distribution over a normalized
        histogram of the data.

See Also
--------
rv_continuous,  rv_discrete

Notes
-----
Optimization is more likely to converge to the maximum likelihood estimate
when the user provides tight bounds containing the maximum likelihood
estimate. For example, when fitting a binomial distribution to data, the
number of experiments underlying each sample may be known, in which case
the corresponding shape parameter ``n`` can be fixed.

References
----------
.. [1] Shao, Yongzhao, and Marjorie G. Hahn. "Maximum product of spacings
       method: a unified formulation with illustration of strong
       consistency." Illinois Journal of Mathematics 43.3 (1999): 489-499.

Examples
--------
Suppose we wish to fit a distribution to the following data.

>>> import numpy as np
>>> from scipy import stats
>>> rng = np.random.default_rng()
>>> dist = stats.nbinom
>>> shapes = (5, 0.5)
>>> data = dist.rvs(*shapes, size=1000, random_state=rng)

Suppose we do not know how the data were generated, but we suspect that
it follows a negative binomial distribution with parameters *n* and *p*\.
(See `scipy.stats.nbinom`.) We believe that the parameter *n* was fewer
than 30, and we know that the parameter *p* must lie on the interval
[0, 1]. We record this information in a variable `bounds` and pass
this information to `fit`.

>>> bounds = [(0, 30), (0, 1)]
>>> res = stats.fit(dist, data, bounds)

`fit` searches within the user-specified `bounds` for the
values that best match the data (in the sense of maximum likelihood
estimation). In this case, it found shape values similar to those
from which the data were actually generated.

>>> res.params
FitParams(n=5.0, p=0.5028157644634368, loc=0.0)  # may vary

We can visualize the results by superposing the probability mass function
of the distribution (with the shapes fit to the data) over a normalized
histogram of the data.

>>> import matplotlib.pyplot as plt  # matplotlib must be installed to plot
>>> res.plot()
>>> plt.show()

Note that the estimate for *n* was exactly integral; this is because
the domain of the `nbinom` PMF includes only integral *n*, and the `nbinom`
object "knows" that. `nbinom` also knows that the shape *p* must be a
value between 0 and 1. In such a case - when the domain of the distribution
with respect to a parameter is finite - we are not required to specify
bounds for the parameter.

>>> bounds = {'n': (0, 30)}  # omit parameter p using a `dict`
>>> res2 = stats.fit(dist, data, bounds)
>>> res2.params
FitParams(n=5.0, p=0.5016492009232932, loc=0.0)  # may vary

If we wish to force the distribution to be fit with *n* fixed at 6, we can
set both the lower and upper bounds on *n* to 6. Note, however, that the
value of the objective function being optimized is typically worse (higher)
in this case.

>>> bounds = {'n': (6, 6)}  # fix parameter `n`
>>> res3 = stats.fit(dist, data, bounds)
>>> res3.params
FitParams(n=6.0, p=0.5486556076755706, loc=0.0)  # may vary
>>> res3.nllf() > res.nllf()
True  # may vary

Note that the numerical results of the previous examples are typical, but
they may vary because the default optimizer used by `fit`,
`scipy.optimize.differential_evolution`, is stochastic. However, we can
customize the settings used by the optimizer to ensure reproducibility -
or even use a different optimizer entirely - using the `optimizer`
parameter.

>>> from scipy.optimize import differential_evolution
>>> rng = np.random.default_rng(767585560716548)
>>> def optimizer(fun, bounds, *, integrality):
...     return differential_evolution(fun, bounds, strategy='best2bin',
...                                   rng=rng, integrality=integrality)
>>> bounds = [(0, 30), (0, 1)]
>>> res4 = stats.fit(dist, data, bounds, optimizer=optimizer)
>>> res4.params
FitParams(n=5.0, p=0.5015183149259951, loc=0.0)

r#   )r   r   )r	   r	   )r&   r'   Fr"   r&   Tz?`dist` must be an instance of `rv_continuous` or `rv_discrete.`zDistribution `z[` is not yet supported by `scipy.stats.fit` because shape information has not been defined.Nr	   z'`data` must be exactly one-dimensional.z.All elements of `data` must be finite numbers.rg   r$   zKBounds provided for the following unrecognized parameters will be ignored: )
stackleveldtyper   )r   rg   zEach element of a `bounds` sequence must be a tuple containing two elements: the lower and upper bound of a distribution parameter.zcEach element of `bounds` must be a tuple specifying the lower and upper bounds of a shape parameterz*A `bounds` sequence must contain at least zP elements: tuples specifying the lower and upper bounds of all shape parameters r
   z.A `bounds` sequence may not contain more than zS elements: tuples specifying the lower and upper bounds of distribution parameters zLGuesses provided for the following unrecognized parameters will be ignored: zLEach element of `guess` must be a scalar guess for a distribution parameter.z)A `guess` sequence must contain at least z@ elements: scalar guesses for the distribution shape parameters z-A `guess` sequence may not contain more than z: elements: scalar guesses for the distribution parameters axiszGuess for parameter `z` rounded from z to z` clipped from c                    > [         R                  " SSS9   TR                  X5      sS S S 5        $ ! , (       d  f       g = fNignoreinvaliddivide)r   errstate_penalized_nnlffree_paramsr5   r4   s     r   r2   fit.<locals>.nllf  s+    [[(;'': <;;	   2
A c                    > [         R                  " SSS9   TR                  X5      sS S S 5        $ ! , (       d  f       g = fr   )r   r   _penalized_nlpsfr   s     r   nlpsffit.<locals>.nlpsf  s+    [[(;((; <;;r   )r   mser   r   r   integralityx0),hasattrr   _param_infoAttributeErrorr   r   asarrayndim
issubdtyper   numberr   r   r=   r>   
isinstancer   updateemptyrangepopdomainrZ   warningswarnRuntimeWarningfloatsizeshaper   valuesr   r   appendzipmeancopyroundwherecliprY   r   anyr   )+r4   r5   r   r   r   r   r   
user_guessdefault_boundsr+   r   
param_infoen_paramsn_shapesparam
param_listparam_namesr7   user_bounds_arrayi
param_name
user_boundvalidated_boundsr   param_domainr   combinedr   guess_arraybounddefault_guessunrecognizedguess_roundedroundedguess_clippedclippedr2   r   methods	objectivekwdsr6   s+   `                                          r   fitr'  <  s   F KJ tU!'&9	u		'!!)%%'
 ::dDyyA~;!!MM$**bii00r{{4())B!! :H1a0H*45****J5))J'K))Jy12K+t$$k*$HHh]3xA#A++J$T:J!']11
#-a  ! 669+6F5GIGMM'>a@	-**[>K1$ hhv. ![%6%6q%9Q%>IGW%%Q(*CH: N99DQHG W%%Q(*G" $B%a)G W%%HHh]3'+N,A,A,C'D()$/:+3{+,#K8_!}!!&q)
!!}++a=,,"4\8L)  ZZ()F2<=*$$*K= 	J	%	%-0-DF-D\UE RWWU^3-D 	 F:]);;66B^EGMM'>a@Z(9	-**3=&?3=% '4EJJ&?3=&?FKMK9	-Je<J ??aW%%A)B8* M%%0M4G W%%A)F" $22=aAG W%%ggf1-(2$S_%#((*%'XXmK.H%Ik"((=K78;A.z!}/A/A.B C''21~&6d=;K:LAOGMM'>a@ 
 vad|VAqD\J((=M9:1=A.z!}/A/A.B C''4Q'7&8'*+1.G MM'>a@	    $ ; !% < 5)G'I	Xh	7#DN66+"-DDJ	*T* 
8 T43//[  )#DII; /' ' !q(	)& 66  	-3G W%1,		-H >F&? 	-W%1,	-  	-W%1,	-h 
8	7s   [ \	?\ \..\3\> (\9
\> ] 
<]:
\%\\
\+\&&\+9\> >
]]]
]7&]22]7:
^GoodnessOfFitResult)
fit_result	statisticpvaluenull_distributionrandom_stateadi'  )known_paramsrR   guessed_paramsr*  n_mc_samplesrngc          
        ^ ^^^^ [        T XX4XVT5      nUu	  m pppnm[        T XU	5      nU" U5      nT " U6 mUU4S jn[        T XU
5      m[        U5      (       a  UmO	[        U   m[	        TSS5      nUU U4S jn[
        R                  " UUUSUSUS9n[        R                  " 5       nSUl	        SUl
        UUl        [        [        T US	U5      UR                  UR                  UR                   5      $ )
uG  
Perform a goodness of fit test comparing data to a distribution family.

Given a distribution family and data, perform a test of the null hypothesis
that the data were drawn from a distribution in that family. Any known
parameters of the distribution may be specified. Remaining parameters of
the distribution will be fit to the data, and the p-value of the test
is computed accordingly. Several statistics for comparing the distribution
to data are available.

Parameters
----------
dist : `scipy.stats.rv_continuous`
    The object representing the distribution family under the null
    hypothesis.
data : 1D array_like
    Finite, uncensored data to be tested.
known_params : dict, optional
    A dictionary containing name-value pairs of known distribution
    parameters. Monte Carlo samples are randomly drawn from the
    null-hypothesized distribution with these values of the parameters.
    Before the statistic is evaluated for the observed `data` and each
    Monte Carlo sample, only remaining unknown parameters of the
    null-hypothesized distribution family are fit to the samples; the
    known parameters are held fixed. If all parameters of the distribution
    family are known, then the step of fitting the distribution family to
    each sample is omitted.
fit_params : dict, optional
    A dictionary containing name-value pairs of distribution parameters
    that have already been fit to the data, e.g. using `scipy.stats.fit`
    or the ``fit`` method of `dist`. Monte Carlo samples are drawn from the
    null-hypothesized distribution with these specified values of the
    parameter. However, these and all other unknown parameters of the
    null-hypothesized distribution family are always fit to the sample,
    whether that is the observed `data` or a Monte Carlo sample, before
    the statistic is evaluated.
guessed_params : dict, optional
    A dictionary containing name-value pairs of distribution parameters
    which have been guessed. These parameters are always considered as
    free parameters and are fit both to the provided `data` as well as
    to the Monte Carlo samples drawn from the null-hypothesized
    distribution. The purpose of these `guessed_params` is to be used as
    initial values for the numerical fitting procedure.
statistic : {"ad", "ks", "cvm", "filliben"} or callable, optional
    The statistic used to compare data to a distribution after fitting
    unknown parameters of the distribution family to the data. The
    Anderson-Darling ("ad") [1]_, Kolmogorov-Smirnov ("ks") [1]_,
    Cramer-von Mises ("cvm") [1]_, and Filliben ("filliben") [7]_
    statistics are available.  Alternatively, a callable with signature
    ``(dist, data, axis)`` may be supplied to compute the statistic. Here
    ``dist`` is a frozen distribution object (potentially with array
    parameters), ``data`` is an array of Monte Carlo samples (of
    compatible shape), and ``axis`` is the axis of ``data`` along which
    the statistic must be computed.
n_mc_samples : int, default: 9999
    The number of Monte Carlo samples drawn from the null hypothesized
    distribution to form the null distribution of the statistic. The
    sample size of each is the same as the given `data`.
rng : `numpy.random.Generator`, optional
    Pseudorandom number generator state. When `rng` is None, a new
    `numpy.random.Generator` is created using entropy from the
    operating system. Types other than `numpy.random.Generator` are
    passed to `numpy.random.default_rng` to instantiate a ``Generator``.

Returns
-------
res : GoodnessOfFitResult
    An object with the following attributes.

    fit_result : `~scipy.stats._result_classes.FitResult`
        An object representing the fit of the provided `dist` to `data`.
        This  object includes the values of distribution family parameters
        that fully define the null-hypothesized distribution, that is,
        the distribution from which Monte Carlo samples are drawn.
    statistic : float
        The value of the statistic comparing provided `data` to the
        null-hypothesized distribution.
    pvalue : float
        The proportion of elements in the null distribution with
        statistic values at least as extreme as the statistic value of the
        provided `data`.
    null_distribution : ndarray
        The value of the statistic for each Monte Carlo sample
        drawn from the null-hypothesized distribution.

Notes
-----
This is a generalized Monte Carlo goodness-of-fit procedure, special cases
of which correspond with various Anderson-Darling tests, Lilliefors' test,
etc. The test is described in [2]_, [3]_, and [4]_ as a parametric
bootstrap test. This is a Monte Carlo test in which parameters that
specify the distribution from which samples are drawn have been estimated
from the data. We describe the test using "Monte Carlo" rather than
"parametric bootstrap" throughout to avoid confusion with the more familiar
nonparametric bootstrap, and describe how the test is performed below.

*Traditional goodness of fit tests*

Traditionally, critical values corresponding with a fixed set of
significance levels are pre-calculated using Monte Carlo methods. Users
perform the test by calculating the value of the test statistic only for
their observed `data` and comparing this value to tabulated critical
values. This practice is not very flexible, as tables are not available for
all distributions and combinations of known and unknown parameter values.
Also, results can be inaccurate when critical values are interpolated from
limited tabulated data to correspond with the user's sample size and
fitted parameter values. To overcome these shortcomings, this function
allows the user to perform the Monte Carlo trials adapted to their
particular data.

*Algorithmic overview*

In brief, this routine executes the following steps:

  1. Fit unknown parameters to the given `data`, thereby forming the
     "null-hypothesized" distribution, and compute the statistic of
     this pair of data and distribution.
  2. Draw random samples from this null-hypothesized distribution.
  3. Fit the unknown parameters to each random sample.
  4. Calculate the statistic between each sample and the distribution that
     has been fit to the sample.
  5. Compare the value of the statistic corresponding with `data` from (1)
     against the values of the statistic corresponding with the random
     samples from (4). The p-value is the proportion of samples with a
     statistic value greater than or equal to the statistic of the observed
     data.

In more detail, the steps are as follows.

First, any unknown parameters of the distribution family specified by
`dist` are fit to the provided `data` using maximum likelihood estimation.
(One exception is the normal distribution with unknown location and scale:
we use the bias-corrected standard deviation ``np.std(data, ddof=1)`` for
the scale as recommended in [1]_.)
These values of the parameters specify a particular member of the
distribution family referred to as the "null-hypothesized distribution",
that is, the distribution from which the data were sampled under the null
hypothesis. The `statistic`, which compares data to a distribution, is
computed between `data` and the null-hypothesized distribution.

Next, many (specifically `n_mc_samples`) new samples, each containing the
same number of observations as `data`, are drawn from the
null-hypothesized distribution. All unknown parameters of the distribution
family `dist` are fit to *each resample*, and the `statistic` is computed
between each sample and its corresponding fitted distribution. These
values of the statistic form the Monte Carlo null distribution (not to be
confused with the "null-hypothesized distribution" above).

The p-value of the test is the proportion of statistic values in the Monte
Carlo null distribution that are at least as extreme as the statistic value
of the provided `data`. More precisely, the p-value is given by

.. math::

    p = \frac{b + 1}
             {m + 1}

where :math:`b` is the number of statistic values in the Monte Carlo null
distribution that are greater than or equal to the statistic value
calculated for `data`, and :math:`m` is the number of elements in the
Monte Carlo null distribution (`n_mc_samples`). The addition of :math:`1`
to the numerator and denominator can be thought of as including the
value of the statistic corresponding with `data` in the null distribution,
but a more formal explanation is given in [5]_.

*Limitations*

The test can be very slow for some distribution families because unknown
parameters of the distribution family must be fit to each of the Monte
Carlo samples, and for most distributions in SciPy, distribution fitting
performed via numerical optimization.

*Anti-Pattern*

For this reason, it may be tempting
to treat parameters of the distribution pre-fit to `data` (by the user)
as though they were `known_params`, as specification of all parameters of
the distribution precludes the need to fit the distribution to each Monte
Carlo sample. (This is essentially how the original Kilmogorov-Smirnov
test is performed.) Although such a test can provide evidence against the
null hypothesis, the test is conservative in the sense that small p-values
will tend to (greatly) *overestimate* the probability of making a type I
error (that is, rejecting the null hypothesis although it is true), and the
power of the test is low (that is, it is less likely to reject the null
hypothesis even when the null hypothesis is false).
This is because the Monte Carlo samples are less likely to agree with the
null-hypothesized distribution as well as `data`. This tends to increase
the values of the statistic recorded in the null distribution, so that a
larger number of them exceed the value of statistic for `data`, thereby
inflating the p-value.

References
----------
.. [1] M. A. Stephens (1974). "EDF Statistics for Goodness of Fit and
       Some Comparisons." Journal of the American Statistical Association,
       Vol. 69, pp. 730-737.
.. [2] W. Stute, W. G. Manteiga, and M. P. Quindimil (1993).
       "Bootstrap based goodness-of-fit-tests." Metrika 40.1: 243-256.
.. [3] C. Genest, & B Rémillard. (2008). "Validity of the parametric
       bootstrap for goodness-of-fit testing in semiparametric models."
       Annales de l'IHP Probabilités et statistiques. Vol. 44. No. 6.
.. [4] I. Kojadinovic and J. Yan (2012). "Goodness-of-fit testing based on
       a weighted bootstrap: A fast large-sample alternative to the
       parametric bootstrap." Canadian Journal of Statistics 40.3: 480-500.
.. [5] B. Phipson and G. K. Smyth (2010). "Permutation P-values Should
       Never Be Zero: Calculating Exact P-values When Permutations Are
       Randomly Drawn." Statistical Applications in Genetics and Molecular
       Biology 9.1.
.. [6] H. W. Lilliefors (1967). "On the Kolmogorov-Smirnov test for
       normality with mean and variance unknown." Journal of the American
       statistical Association 62.318: 399-402.
.. [7] Filliben, James J. "The probability plot correlation coefficient
       test for normality." Technometrics 17.1 (1975): 111-117.

Examples
--------
A well-known test of the null hypothesis that data were drawn from a
given distribution is the Kolmogorov-Smirnov (KS) test, available in SciPy
as `scipy.stats.ks_1samp`. Suppose we wish to test whether the following
data:

>>> import numpy as np
>>> from scipy import stats
>>> rng = np.random.default_rng()
>>> x = stats.uniform.rvs(size=75, random_state=rng)

were sampled from a normal distribution. To perform a KS test, the
empirical distribution function of the observed data will be compared
against the (theoretical) cumulative distribution function of a normal
distribution. Of course, to do this, the normal distribution under the null
hypothesis must be fully specified. This is commonly done by first fitting
the ``loc`` and ``scale`` parameters of the distribution to the observed
data, then performing the test.

>>> loc, scale = np.mean(x), np.std(x, ddof=1)
>>> cdf = stats.norm(loc, scale).cdf
>>> stats.ks_1samp(x, cdf)
KstestResult(statistic=0.1119257570456813,
             pvalue=0.2827756409939257,
             statistic_location=0.7751845155861765,
             statistic_sign=-1)

An advantage of the KS-test is that the p-value - the probability of
obtaining a value of the test statistic under the null hypothesis as
extreme as the value obtained from the observed data - can be calculated
exactly and efficiently. `goodness_of_fit` can only approximate these
results.

>>> known_params = {'loc': loc, 'scale': scale}
>>> res = stats.goodness_of_fit(stats.norm, x, known_params=known_params,
...                             statistic='ks', rng=rng)
>>> res.statistic, res.pvalue
(0.1119257570456813, 0.2788)

The statistic matches exactly, but the p-value is estimated by forming
a "Monte Carlo null distribution", that is, by explicitly drawing random
samples from `scipy.stats.norm` with the provided parameters and
calculating the stastic for each. The fraction of these statistic values
at least as extreme as ``res.statistic`` approximates the exact p-value
calculated by `scipy.stats.ks_1samp`.

However, in many cases, we would prefer to test only that the data were
sampled from one of *any* member of the normal distribution family, not
specifically from the normal distribution with the location and scale
fitted to the observed sample. In this case, Lilliefors [6]_ argued that
the KS test is far too conservative (that is, the p-value overstates
the actual probability of rejecting a true null hypothesis) and thus lacks
power - the ability to reject the null hypothesis when the null hypothesis
is actually false.
Indeed, our p-value above is approximately 0.28, which is far too large
to reject the null hypothesis at any common significance level.

Consider why this might be. Note that in the KS test above, the statistic
always compares data against the CDF of a normal distribution fitted to the
*observed data*. This tends to reduce the value of the statistic for the
observed data, but it is "unfair" when computing the statistic for other
samples, such as those we randomly draw to form the Monte Carlo null
distribution. It is easy to correct for this: whenever we compute the KS
statistic of a sample, we use the CDF of a normal distribution fitted
to *that sample*. The null distribution in this case has not been
calculated exactly and is tyically approximated using Monte Carlo methods
as described above. This is where `goodness_of_fit` excels.

>>> res = stats.goodness_of_fit(stats.norm, x, statistic='ks',
...                             rng=rng)
>>> res.statistic, res.pvalue
(0.1119257570456813, 0.0196)

Indeed, this p-value is much smaller, and small enough to (correctly)
reject the null hypothesis at common significance levels, including 5% and
2.5%.

However, the KS statistic is not very sensitive to all deviations from
normality. The original advantage of the KS statistic was the ability
to compute the null distribution theoretically, but a more sensitive
statistic - resulting in a higher test power - can be used now that we can
approximate the null distribution
computationally. The Anderson-Darling statistic [1]_ tends to be more
sensitive, and critical values of the this statistic have been tabulated
for various significance levels and sample sizes using Monte Carlo methods.

>>> res = stats.anderson(x, 'norm')
>>> print(res.statistic)
1.2139573337497467
>>> print(res.critical_values)
[0.549 0.625 0.75  0.875 1.041]
>>> print(res.significance_level)
[15.  10.   5.   2.5  1. ]

Here, the observed value of the statistic exceeds the critical value
corresponding with a 1% significance level. This tells us that the p-value
of the observed data is less than 1%, but what is it? We could interpolate
from these (already-interpolated) values, but `goodness_of_fit` can
estimate it directly.

>>> res = stats.goodness_of_fit(stats.norm, x, statistic='ad',
...                             rng=rng)
>>> res.statistic, res.pvalue
(1.2139573337497467, 0.0034)

A further advantage is that use of `goodness_of_fit` is not limited to
a particular set of distributions or conditions on which parameters
are known versus which must be estimated from data. Instead,
`goodness_of_fit` can estimate p-values relatively quickly for any
distribution with a sufficiently fast and reliable ``fit`` method. For
instance, here we perform a goodness of fit test using the Cramer-von Mises
statistic against the Rayleigh distribution with known location and unknown
scale.

>>> rng = np.random.default_rng()
>>> x = stats.chi(df=2.2, loc=0, scale=2).rvs(size=1000, random_state=rng)
>>> res = stats.goodness_of_fit(stats.rayleigh, x, statistic='cvm',
...                             known_params={'loc': 0}, rng=rng)

This executes fairly quickly, but to check the reliability of the ``fit``
method, we should inspect the fit result.

>>> res.fit_result  # location is as specified, and scale is reasonable
  params: FitParams(loc=0.0, scale=2.1026719844231243)
 success: True
 message: 'The fit was performed successfully.'
>>> import matplotlib.pyplot as plt  # matplotlib must be installed to plot
>>> res.fit_result.plot()
>>> plt.show()

If the distribution is not fit to the observed data as well as possible,
the test may not control the type I error rate, that is, the chance of
rejecting the null hypothesis even when it is true.

We should also look for extreme outliers in the null distribution that
may be caused by unreliable fitting. These do not necessarily invalidate
the result, but they tend to reduce the test's power.

>>> _, ax = plt.subplots()
>>> ax.hist(np.log10(res.null_distribution))
>>> ax.set_xlabel("log10 of CVM statistic under the null hypothesis")
>>> ax.set_ylabel("Frequency")
>>> ax.set_title("Histogram of the Monte Carlo null distribution")
>>> plt.show()

This plot seems reassuring.

If ``fit`` method is working reliably, and if the distribution of the test
statistic is not particularly sensitive to the values of the fitted
parameters, then the p-value provided by `goodness_of_fit` is expected to
be a good approximation.

>>> res.statistic, res.pvalue
(0.2231991510248692, 0.0525)

c                 $   > TR                  U TS9$ )N)r  r-  )rvs)r  nhd_distr2  s    r   r5  goodness_of_fit.<locals>.rvsg  s    ||C|88r   alternativegreaterc                 Z   > [         R                  " XS5      n T" U 5      nT" U6 nT" X0SS9$ )Nrh   r   )r   moveaxis)r5   r   rfd_valsrfd_distcompare_funr4   fit_funs       r   statistic_fun&goodness_of_fit.<locals>.statistic_funr  s2    {{4r*4=?833r   Trh   )
vectorizedn_resamplesr   r8  z#The fit was performed successfully.F)_gof_iv_get_fit_funcallable_compare_dictr,   r   monte_carlo_testr   OptimizeResultr(   r   r0   r(  r   r*  r+  r,  )r4   r5   r/  rR   r0  r*  r1  r2  argsfixed_nhd_paramsfixed_rfd_paramsguessed_nhd_paramsguessed_rfd_paramsn_mc_samples_intnhd_fit_funnhd_valsr5  r8  r@  r6   opt_resr>  r?  r6  s   `      `             @@@r   goodness_of_fitrS    s   n 4ZC1D >B;T4#3$4c tT/1K4 HXH9 4;KLG	#I.+}i@K4 
 
 sMd-9-8:C %%'GGO;GOGI ytUGD"}}cjj"446 6r   c                   ^ ^^^
^^ T R                   c  / OT R                   R                  S5      nUSS/-   nU Vs/ s H  nSU-   PM
     snm[        T5      R                  T5      (       + nU Vs/ s H  oT;   d  M
  TR	                  US 5      PM     snmU(       a	  UU4S jn	U	$ T [
        ;   a	  U U4S jn	U	$ U UUU4S jm
U
4S jn	U	$ s  snf s  snf )	Nr$   r&   r'   fc                 :   > T Vs/ s H  nTU   PM
     sn$ s  snf r   r   )r5   r   fixed_paramsfparam_namess     r   r?  _get_fit_fun.<locals>.fit_fun  s     3?@<4L&<@@@s   c                    > [         T   " U 40 TD6n[        R                  " [        R                  " U6 5      nUR                  S:  a  US[        R
                  4   nU$ )Nr	   .)	_fit_funsr   r   broadcast_arraysr   newaxis)r5   r1   r4   rW  s     r   r?  rY    sQ    t_T:\:FZZ 3 3V <=F{{QRZZ0Mr   c                 4   > TR                   " U /TQ70 TDTD6$ r   )r'  )r5   r4   rW  r0  guessed_shapess    r   
fit_fun_1d _get_fit_fun.<locals>.fit_fun_1d  s,    88D ,> ,^ ,*, ,r   c                    > [         R                  " TSU S9nUR                  S:  a  UR                  S[         R                  4   nU$ )Nrh   )r   arrr	   .)r   apply_along_axisr   Tr]  )r5   r1   r`  s     r   r?  rY    s=    (("$GF{{Q#rzz/2Mr   )r.   r/   rZ   
differencer   r[  )r4   r5   r0  rW  r7   r  r   	all_fixedr0   r?  r`  rX  r_  s   ` ``      @@@r   rE  rE    s    +"1B1B41HK 00K)45CH5L%00>>I*C*!>.A 2n((D1*CN 	A* N% 
		" N	, 	,	 N7 6Cs   C1	C>Cc                    UnUnUc1  Uc.  [         R                  " U SS9n[         R                  " U SSS9nX44$ Uc  [         R                  " U SS9nX44$ Uc(  [         R                  " X-
  S-  R                  SS95      nX44$ )Nrh   r   r	   )ddofr   rg   )r   r  stdsqrt)r5   flocfscaler&   r'   s        r   	_fit_normrn    s    
CE
{u}ggd$t!"-
 :	 
ggd$ : 
$*q..B.78:r   c           	      "   [         R                  " USS9nUR                  S   n[         R                  " SUS-   5      nSU-  S-
  U-  U R	                  U5      U R                  USS S S24   5      -   -  n[         R                  " USS9nU* U-
  $ )Nrh   r   r	   rg   .)r   r   r  r}   logcdflogsfsum)r4   r5   r   r0   r   r  SiSs           r   _anderson_darlingru    s    
2A

2A
		!QqSA
A#'1AAc4R4iL)AA	BB
rA26Mr   c                 z    U R                   S   n[        R                  " SUS-   5      U-  U -
  R                  SS9$ )Nrh   g      ?r	   r   r  r   r}   r   cdfvalsr   s     r   _compute_dplusrz    s=    bAIIc1q5!A%/44"4==r   c                 t    U R                   S   nU [        R                  " SU5      U-  -
  R                  SS9$ )Nrh   g        r   rw  rx  s     r   _compute_dminusr|    s9    bAbiiQ'))..B.77r   c                     [         R                  " XS9nU R                  U5      n[         R                  " XBS5      n[	        U5      n[        U5      n[         R                  " XV5      $ )Nr   rh   )r   r   rP   r;  rz  r|  maximum)r4   r5   r   r0   ry  DplusDminuss          r   _kolmogorov_smirnovr    sP    
 AhhqkGkk',G7#EW%F::e$$r   c                    U R                  SSS9nUR                  SSS9n[        R                  " X-
  X-
  -  SS9n[        R                  " [        R                  " X-
  S-  SS9[        R                  " X-
  S-  SS9-  5      nXE-  $ )Nrh   T)r   keepdimsr   rg   )r  r   rr  rk  )XMXmMmnumdens         r   _corrr    s}     
R$	'B	
R$	'B
&&!&QV$2
.C
''"&&!&12.!"1MM
NC7Nr   c                 
   [         R                  " USS9nUR                  S   n[         R                  " SUS-   5      n[        R
                  " XTS-   U-
  5      R                  5       nU R                  U5      n[        X75      $ )Nrh   r   r	   )	r   r   r  r}   r   betamedianr   r  )r4   r5   r   r  r   rr   rB   r  s           r   	_fillibenr    sq    
2A 	

2A
		!QqSA 	

1!eai '')A 	A ;r   lessc                    [         R                  " USS9nUR                  S   nU R                  U5      nS[         R                  " SUS-   5      -  S-
  SU-  -  nSSU-  -  [         R
                  " Xe-
  S-  SS9-   nU$ )Nrh   r   rg   r	      )r   r   r  rP   r}   rr  )r4   r5   r   r0   r   ry  uws           r   _cramer_von_misesr    s|    
2A

2AhhqkG	
299Q!	q	 1Q3'A	RT
RVVQ[1,266AHr   )r.  kscvmfillibenc           	         [        U [        R                  5      (       d  Sn[        U5      e[        R
                  " U[        S9nUR                  S:X  d  Sn[        U5      eU=(       d
    [        5       nU=(       d
    [        5       nU=(       d
    [        5       nUR                  5        V	V
s0 s H  u  pSU	-   U
_M     nn	n
UR                  5        V	V
s0 s H  u  pSU	-   U
_M     nn	n
UR                  5       nUR                  U5        UR                  5       nUR                  5       nUR                  5       nUR                  U5        [        U5      (       d+  UR                  5       n1 SknUU;  a  SU S3n[        U5      e[        U5      nUU:w  a  S	n[        U5      e[!        U5      nXXUUUUU4	$ s  sn
n	f s  sn
n	f )
Nz@`dist` must be a (non-frozen) instance of `stats.rv_continuous`.r   r	   z2`data` must be a one-dimensional array of numbers.rU  >   r.  r  r  r  z`statistic` must be one of r
   z"`n_mc_samples` must be an integer.)r   r   rv_continuous	TypeErrorr   r   r   r   r   r   itemsr  r   rF  rY   r   r   )r4   r5   r/  rR   r0  r*  r1  r2  r   rC   valknown_params_ffit_params_frK  rL  rM  rN  
statisticsrO  s                      r   rD  rD    s    dE//00,  ::d%(D99>F!!  )46L%tvJ#-tvN5A5G5G5IJ5Is3w}5INJ3=3C3C3EF3ExsSWs]3ELF &**,L) &**, (,,. $*n-IOO%	4
J&3J<qAGW%%<(<'6  
S
!C(<N	+;SB BE KFs   /F;Gr   r   )rh   )r   collectionsr   numpyr   scipyr   r   scipy._lib._utilr   r   r   r   differential_evolutionr'  r(  rS  rE  rn  normr[  ru  rz  r|  r  r  r  r8  r  rG  rD  r   r   r   <module>r     s     "  ! CBP Pfa0$u11a0H !!6"78 
 N#04#'4da6 $a6HJ
 ZZ#	>
8
%, 	  )0C)yB6Br   