a
    BCCfRC                    @   sn  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlm	Z	 d dl
mZ ddlmZmZ d dl mZ d dlmZmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ d dlZ,ddl-m.Z.m/Z/ ddl0m1Z1 d dl2m3Z3 ddddZ4dZ5dZ6dZ7dZ8dZ9dZ:dZ;dZ<dZ=dZ>dZ?d Z@d!ZAd"ZBd#ZCd$ZDd%ZEd&ZFd'ZGd(ZHd)ZId*ZJd+Ke4d, e5e6e7e:e;e<e=e>e?e@eAeBeCeDeFeGeHeIeJgZLd-ZMd.ZNd/ZOd0ZPd+KeMeLd1eOgZQd+KeMeLgZRe5e6e7e:e;e<e=e>e?eAeBeCe@eDeJeGeIeHeFeLeMeNeOeQeRePd2ZSeST ZUe8eUd3< e9eUd4< eEeUd5< g d6ZVeVD ]ZWeUeW Xd7d+eUeW< qXg d8ZYeYD ]ZWeUeW Xd9d:eUeW< qeUZd; eUZd< d+Kd=d> eVD ZLe4d, eL eUd?< eMXd@dAeUdB< dCZNeNeUdD< dEZ[dFZ\e[eUdG< e\eUdH< d+KeUdB eUd? gZReReUdI< d+KeUdB eUd? eUdD eUdG gZ]e]eUdJ< dKd> e^ D D ]ZWe_dLeW  q`[Wd|dMdNZ`dOdP ZadQdR ZbdSdT ZcdUdV ZddWdX ZeG dYdZ dZZfG d[d\ d\efZgG d]d^ d^efZhd_d` ZidaZjG dbdc dcZkG ddde deZldfdg ZmG dhd@ d@ekZndidj Zodkdl ZpG dmdA dAekZqd}dqdrZrd~dtduZsG dvdw dweqZtdxdy Zudzd{ ZvdS )    )getfullargspec_no_selfN)zip_longest)doccer   )distcontdistdiscrete)check_random_state)combentr)optimize)	integrate)_derivative)stats)arangeputmaskonesshapendarrayzerosfloorlogical_andlogsqrtplaceargmax	vectorizeasarraynaninfisinfempty)_XMAX_LOGXMAX)CensoredData)FitErrorz
Methods
-------
z
Notes
-----
z
Examples
--------
)methodsnotesZexampleszPrvs(%(shapes)s, loc=0, scale=1, size=1, random_state=None)
    Random variates.
zEpdf(x, %(shapes)s, loc=0, scale=1)
    Probability density function.
zSlogpdf(x, %(shapes)s, loc=0, scale=1)
    Log of the probability density function.
zBpmf(k, %(shapes)s, loc=0, scale=1)
    Probability mass function.
zPlogpmf(k, %(shapes)s, loc=0, scale=1)
    Log of the probability mass function.
zIcdf(x, %(shapes)s, loc=0, scale=1)
    Cumulative distribution function.
zWlogcdf(x, %(shapes)s, loc=0, scale=1)
    Log of the cumulative distribution function.
z}sf(x, %(shapes)s, loc=0, scale=1)
    Survival function  (also defined as ``1 - cdf``, but `sf` is sometimes more accurate).
zGlogsf(x, %(shapes)s, loc=0, scale=1)
    Log of the survival function.
zdppf(q, %(shapes)s, loc=0, scale=1)
    Percent point function (inverse of ``cdf`` --- percentiles).
zVisf(q, %(shapes)s, loc=0, scale=1)
    Inverse survival function (inverse of ``sf``).
zYmoment(order, %(shapes)s, loc=0, scale=1)
    Non-central moment of the specified order.
zostats(%(shapes)s, loc=0, scale=1, moments='mv')
    Mean('m'), variance('v'), skew('s'), and/or kurtosis('k').
zJentropy(%(shapes)s, loc=0, scale=1)
    (Differential) entropy of the RV.
a  fit(data)
    Parameter estimates for generic data.
    See `scipy.stats.rv_continuous.fit <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rv_continuous.fit.html#scipy.stats.rv_continuous.fit>`__ for detailed documentation of the
    keyword arguments.
zexpect(func, args=(%(shapes_)s), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds)
    Expected value of a function (of one argument) with respect to the distribution.
zexpect(func, args=(%(shapes_)s), loc=0, lb=None, ub=None, conditional=False)
    Expected value of a function (of one argument) with respect to the distribution.
zCmedian(%(shapes)s, loc=0, scale=1)
    Median of the distribution.
z?mean(%(shapes)s, loc=0, scale=1)
    Mean of the distribution.
zBvar(%(shapes)s, loc=0, scale=1)
    Variance of the distribution.
zLstd(%(shapes)s, loc=0, scale=1)
    Standard deviation of the distribution.
zminterval(confidence, %(shapes)s, loc=0, scale=1)
    Confidence interval with equal areas around the median.
 r%   zAs an instance of the `rv_continuous` class, `%(name)s` object inherits from it
a collection of generic methods (see below for the full list),
and completes them with details specific for this particular distribution.
a+  
Alternatively, the object may be called (as a function) to fix the shape,
location, and scale parameters returning a "frozen" continuous RV object:

rv = %(name)s(%(shapes)s, loc=0, scale=1)
    - Frozen RV object with the same methods but holding the given shape,
      location, and scale fixed.
a  Examples
--------
>>> import numpy as np
>>> from scipy.stats import %(name)s
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots(1, 1)

Calculate the first four moments:

%(set_vals_stmt)s
>>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk')

Display the probability density function (``pdf``):

>>> x = np.linspace(%(name)s.ppf(0.01, %(shapes)s),
...                 %(name)s.ppf(0.99, %(shapes)s), 100)
>>> ax.plot(x, %(name)s.pdf(x, %(shapes)s),
...        'r-', lw=5, alpha=0.6, label='%(name)s pdf')

Alternatively, the distribution object can be called (as a function)
to fix the shape, location and scale parameters. This returns a "frozen"
RV object holding the given parameters fixed.

Freeze the distribution and display the frozen ``pdf``:

>>> rv = %(name)s(%(shapes)s)
>>> ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')

Check accuracy of ``cdf`` and ``ppf``:

>>> vals = %(name)s.ppf([0.001, 0.5, 0.999], %(shapes)s)
>>> np.allclose([0.001, 0.5, 0.999], %(name)s.cdf(vals, %(shapes)s))
True

Generate random numbers:

>>> r = %(name)s.rvs(%(shapes)s, size=1000)

And compare the histogram:

>>> ax.hist(r, density=True, bins='auto', histtype='stepfilled', alpha=0.2)
>>> ax.set_xlim([x[0], x[-1]])
>>> ax.legend(loc='best', frameon=False)
>>> plt.show()

a  The probability density above is defined in the "standardized" form. To shift
and/or scale the distribution use the ``loc`` and ``scale`` parameters.
Specifically, ``%(name)s.pdf(x, %(shapes)s, loc, scale)`` is identically
equivalent to ``%(name)s.pdf(y, %(shapes)s) / scale`` with
``y = (x - loc) / scale``. Note that shifting the location of a distribution
does not make it a "noncentral" distribution; noncentral generalizations of
some distributions are available in separate classes.

)rvspdflogpdfcdflogcdfsflogsfppfisfr   entropyfitmomentexpectintervalmeanstdvarmedian
allmethodslongsummary
frozennoteexampledefaultbefore_notesafter_notespmflogpmfr5   )r)   rB   rC   r,   r-   r.   r/   r0   r1   r   r2   r5   r:   r7   r9   r8   r6   z	, scale=1)r,   r-   r.   r/   z(x, z(k, r*   r+   c                 C   s   g | ]}t | qS  )docdict_discrete).0objrD   rD   ]/var/www/html/django/DPS/env/lib/python3.9/site-packages/scipy/stats/_distn_infrastructure.py
<listcomp>      rI   r;   rv_continuousrv_discreter<   a  
Alternatively, the object may be called (as a function) to fix the shape and
location parameters returning a "frozen" discrete RV object:

rv = %(name)s(%(shapes)s, loc=0)
    - Frozen RV object with the same methods but holding the given shape and
      location fixed.
r=   a  Examples
--------
>>> import numpy as np
>>> from scipy.stats import %(name)s
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots(1, 1)

Calculate the first four moments:

%(set_vals_stmt)s
>>> mean, var, skew, kurt = %(name)s.stats(%(shapes)s, moments='mvsk')

Display the probability mass function (``pmf``):

>>> x = np.arange(%(name)s.ppf(0.01, %(shapes)s),
...               %(name)s.ppf(0.99, %(shapes)s))
>>> ax.plot(x, %(name)s.pmf(x, %(shapes)s), 'bo', ms=8, label='%(name)s pmf')
>>> ax.vlines(x, 0, %(name)s.pmf(x, %(shapes)s), colors='b', lw=5, alpha=0.5)

Alternatively, the distribution object can be called (as a function)
to fix the shape and location. This returns a "frozen" RV object holding
the given parameters fixed.

Freeze the distribution and display the frozen ``pmf``:

>>> rv = %(name)s(%(shapes)s)
>>> ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-', lw=1,
...         label='frozen pmf')
>>> ax.legend(loc='best', frameon=False)
>>> plt.show()

Check accuracy of ``cdf`` and ``ppf``:

>>> prob = %(name)s.cdf(x, %(shapes)s)
>>> np.allclose(x, %(name)s.ppf(prob, %(shapes)s))
True

Generate random numbers:

>>> r = %(name)s.rvs(%(shapes)s, size=1000)
zThe probability mass function above is defined in the "standardized" form.
To shift distribution use the ``loc`` parameter.
Specifically, ``%(name)s.pmf(k, %(shapes)s, loc)`` is identically
equivalent to ``%(name)s.pmf(k - loc, %(shapes)s)``.
r>   rA   r@   r?   c                 C   s   g | ]}| d r|qS )Z_doc_)
startswith)rF   srD   rD   rH   rI   f  rJ   zdel c                 C   s    |d u r|   }| | |   S N)r7   )datanmurD   rD   rH   _momentk  s    rS   c           
      C   sz  | dkrdS | dkr6|d u r.|dg|R  }n|}n@| dkrp|d u sN|d u r`|dg|R  }n|||  }n| dkr|d u s|d u s|d u r|dg|R  }n,|t |d }|d| |  || |  }n| dkrf|d u s|d u s|d u s|d u r|dg|R  }nP|d |d	  }	|t |d }|	d| |  d
| | |  || | |  }n|| g|R  }|S )Nr         ?r               ?         @       @   )nppower)
rQ   rR   mu2g1g2Zmoment_funcargsvalmu3mu4rD   rD   rH   _moment_from_statsq  s.    
(2re   c                 C   sB   t | } |  }| | d  }| | d  }|t |d S )z8
    skew is third central moment / variance**(1.5)
    rU   rV   rW   )r\   ravelr7   r]   )rP   rR   m2Zm3rD   rD   rH   _skew  s
    
rh   c                 C   sB   t | } |  }| | d  }| | d  }||d  d S )z4kurtosis is fourth central moment / variance**2 - 3.rU   rX   rV   )r\   rf   r7   )rP   rR   rg   Zm4rD   rD   rH   	_kurtosis  s
    
ri   c              
   C   sv   t | srt| trr| ds$d|  } | dkr0d} ztt| } W n2 typ } ztd|  |W Y d }~n
d }~0 0 | S )NZfmin_fminz%s is not a valid optimizer)callable
isinstancestrrM   getattrr   AttributeError
ValueError)	optimizererD   rD   rH   _fit_determine_optimizer  s    
$rs   c                 C   s,   t | }|jt | }t | | |fS )a  
    For a 1D array x, return a tuple containing the sum of the
    finite values of x and the number of nonfinite values.

    This is a utility function used when evaluating the negative
    loglikelihood for a distribution and an array of samples.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.stats._distn_infrastructure import _sum_finite
    >>> tot, nbad = _sum_finite(np.array([-2, -np.inf, 5, 1]))
    >>> tot
    4.0
    >>> nbad
    1
    )r\   isfinitesizecount_nonzerosum)xZfinite_xZ	bad_countrD   rD   rH   _sum_finite  s    
ry   c                   @   s   e Zd Zdd Zedd Zejdd Zdd Zdd	 Zd
d Z	dd Z
d+ddZdd Zdd Zd,ddZdd Zdd Zdd Zdd Zd-d d!Zd"d# Zd.d$d%Zd/d'd(Zd)d* ZdS )0	rv_frozenc                 O   sR   || _ || _|jf i | | _| jj|i |\}}}| jj| \| _| _d S rO   )	ra   kwds	__class___updated_ctor_paramdist_parse_args_get_supportab)selfr~   ra   r{   shapes_rD   rD   rH   __init__  s
    zrv_frozen.__init__c                 C   s   | j jS rO   )r~   _random_stater   rD   rD   rH   random_state  s    zrv_frozen.random_statec                 C   s   t || j_d S rO   )r   r~   r   r   seedrD   rD   rH   r     s    c                 C   s   | j j|g| jR i | jS rO   )r~   r,   ra   r{   r   rx   rD   rD   rH   r,     s    zrv_frozen.cdfc                 C   s   | j j|g| jR i | jS rO   )r~   r-   ra   r{   r   rD   rD   rH   r-     s    zrv_frozen.logcdfc                 C   s   | j j|g| jR i | jS rO   )r~   r0   ra   r{   r   qrD   rD   rH   r0     s    zrv_frozen.ppfc                 C   s   | j j|g| jR i | jS rO   )r~   r1   ra   r{   r   rD   rD   rH   r1     s    zrv_frozen.isfNc                 C   s.   | j  }|||d | jj| ji |S )Nru   r   )r{   copyupdater~   r)   ra   )r   ru   r   r{   rD   rD   rH   r)     s    
zrv_frozen.rvsc                 C   s   | j j|g| jR i | jS rO   )r~   r.   ra   r{   r   rD   rD   rH   r.     s    zrv_frozen.sfc                 C   s   | j j|g| jR i | jS rO   )r~   r/   ra   r{   r   rD   rD   rH   r/     s    zrv_frozen.logsfmvc                 C   s,   | j  }|d|i | jj| ji |S Nmoments)r{   r   r   r~   r   ra   )r   r   r{   rD   rD   rH   r     s    
zrv_frozen.statsc                 C   s   | j j| ji | jS rO   )r~   r:   ra   r{   r   rD   rD   rH   r:     s    zrv_frozen.medianc                 C   s   | j j| ji | jS rO   )r~   r7   ra   r{   r   rD   rD   rH   r7     s    zrv_frozen.meanc                 C   s   | j j| ji | jS rO   )r~   r9   ra   r{   r   rD   rD   rH   r9      s    zrv_frozen.varc                 C   s   | j j| ji | jS rO   )r~   r8   ra   r{   r   rD   rD   rH   r8     s    zrv_frozen.stdc                 C   s   | j j|g| jR i | jS rO   )r~   r4   ra   r{   )r   orderrD   rD   rH   r4     s    zrv_frozen.momentc                 C   s   | j j| ji | jS rO   )r~   r2   ra   r{   r   rD   rD   rH   r2   	  s    zrv_frozen.entropyc                 C   s   | j j|g| jR i | jS rO   )r~   r6   ra   r{   )r   
confidencerD   rD   rH   r6     s    zrv_frozen.intervalFc           	      K   sj   | j j| ji | j\}}}t| j trF| j j||||||fi |S | j j|||||||fi |S d S rO   )r~   r   ra   r{   rl   rL   r5   )	r   funclbubconditionalr{   r   locscalerD   rD   rH   r5     s    zrv_frozen.expectc                 C   s   | j j| ji | jS rO   )r~   supportra   r{   r   rD   rD   rH   r     s    zrv_frozen.support)NN)r   )N)N)NNNF)__name__
__module____qualname__r   propertyr   setterr,   r-   r0   r1   r)   r.   r/   r   r:   r7   r9   r8   r4   r2   r6   r5   r   rD   rD   rD   rH   rz     s,   







rz   c                   @   s   e Zd Zdd Zdd ZdS )rv_discrete_frozenc                 C   s   | j j|g| jR i | jS rO   )r~   rB   ra   r{   r   krD   rD   rH   rB   !  s    zrv_discrete_frozen.pmfc                 C   s   | j j|g| jR i | jS rO   )r~   rC   ra   r{   r   rD   rD   rH   rC   $  s    zrv_discrete_frozen.logpmfN)r   r   r   rB   rC   rD   rD   rD   rH   r     s   r   c                   @   s   e Zd Zdd Zdd ZdS )rv_continuous_frozenc                 C   s   | j j|g| jR i | jS rO   )r~   r*   ra   r{   r   rD   rD   rH   r*   *  s    zrv_continuous_frozen.pdfc                 C   s   | j j|g| jR i | jS rO   )r~   r+   ra   r{   r   rD   rD   rH   r+   -  s    zrv_continuous_frozen.logpdfN)r   r   r   r*   r+   rD   rD   rD   rH   r   (  s   r   c                    sj   t j| }t|ttfs|f}t  rPt jg | R  ^ } dd |D S  j fdd|D S )a  Clean arguments to:

    1. Ensure all arguments are iterable (arrays of dimension at least one
    2. If cond != True and size > 1, ravel(args[i]) where ravel(condition) is
       True, in 1D.

    Return list of processed arguments.

    Examples
    --------
    >>> import numpy as np
    >>> from scipy.stats._distn_infrastructure import argsreduce
    >>> rng = np.random.default_rng()
    >>> A = rng.random((4, 5))
    >>> B = 2
    >>> C = rng.random((1, 5))
    >>> cond = np.ones(A.shape)
    >>> [A1, B1, C1] = argsreduce(cond, A, B, C)
    >>> A1.shape
    (4, 5)
    >>> B1.shape
    (1,)
    >>> C1.shape
    (1, 5)
    >>> cond[2,:] = 0
    >>> [A1, B1, C1] = argsreduce(cond, A, B, C)
    >>> A1.shape
    (15,)
    >>> B1.shape
    (1,)
    >>> C1.shape
    (15,)

    c                 S   s   g | ]}|  qS rD   )rf   rF   argrD   rD   rH   rI   _  rJ   zargsreduce.<locals>.<listcomp>c              	      s2   g | ]*}t |d kr|nt  t |qS r   )r\   ru   extractZbroadcast_tor   condrN   rD   rH   rI   d  s   )r\   
atleast_1drl   listtupleallbroadcast_arraysr   )r   ra   ZnewargsrD   r   rH   
argsreduce1  s    $

r   a  
def _parse_args(self, %(shape_arg_str)s %(locscale_in)s):
    return (%(shape_arg_str)s), %(locscale_out)s

def _parse_args_rvs(self, %(shape_arg_str)s %(locscale_in)s, size=None):
    return self._argcheck_rvs(%(shape_arg_str)s %(locscale_out)s, size=size)

def _parse_args_stats(self, %(shape_arg_str)s %(locscale_in)s, moments='mv'):
    return (%(shape_arg_str)s), %(locscale_out)s, moments
c                       sp  e Zd ZdZdR fdd	Zedd Zejdd Zdd	 Zd
d Z	dd Z
dd ZdSddZdTddZdd Zdd Zeje_dd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zddd'd(d)Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zd:d; Z d<d= Z!d>d? Z"d@dA Z#dBdC Z$dDdE Z%dFdG Z&dHdI Z'dJdK Z(dLdM Z)dNdO Z*dPdQ Z+  Z,S )U
rv_genericz^Class which encapsulates common functionality between rv_discrete
    and rv_continuous.

    Nc                    sB   t    t| j}|jd up0d|jv p0d|jv | _t|| _	d S r   )
superr   _getfullargspec_statsvarkwra   
kwonlyargs_stats_has_momentsr   r   )r   r   sigr|   rD   rH   r   {  s    


zrv_generic.__init__c                 C   s   | j S )a  Get or set the generator object for generating random variates.

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

        )r   r   rD   rD   rH   r     s    zrv_generic.random_statec                 C   s   t || _d S rO   )r   r   r   rD   rD   rH   r     s    c                 C   sL   z| j | |   W n. tyF   |d | _|d | _|   Y n0 d S Nr   r   )__dict__r   _attach_methodsrp   _ctor_paramr   r   )r   staterD   rD   rH   __setstate__  s    

zrv_generic.__setstate__c                 C   s   t dS )a  Attaches dynamically created methods to the rv_* instance.

        This method must be overridden by subclasses, and must itself call
         _attach_argparser_methods. This method is called in __init__ in
         subclasses, and in __setstate__
        N)NotImplementedErrorr   rD   rD   rH   r     s    zrv_generic._attach_methodsc                 C   s6   i }t | j| dD ]}t| |t|| |  qdS )z
        Generates the argument-parsing functions dynamically and attaches
        them to the instance.

        Should be called from `_attach_methods`, typically in __init__ and
        during unpickling (__setstate__)
        r   _parse_args_stats_parse_args_rvsN)exec_parse_arg_templatesetattrtypes
MethodType)r   nsnamerD   rD   rH   _attach_argparser_methods  s    z$rv_generic._attach_argparser_methodsc                 C   s`  | j r^t| j tstd| j dd }|D ]*}t|rFtdt	
d|s0tdq0ng }|D ]l}t|}|jdd }	|	rf||	 |jdurtd	|jdurtd
|jrtd|jdurftdqf|r|d }|D ]}
|
|krtdqng }|rd|d nd}t|||d}t| | _|r@d|nd| _ t| ds\t|| _dS )a  Construct the parser string for the shape arguments.

        This method should be called in __init__ of a class for each
        distribution. It creates the `_parse_arg_template` attribute that is
        then used by `_attach_argparser_methods` to dynamically create and
        attach the `_parse_args`, `_parse_args_stats`, `_parse_args_rvs`
        methods to the instance.

        If self.shapes is a non-empty string, interprets it as a
        comma-separated list of shape parameters.

        Otherwise inspects the call signatures of `meths_to_inspect`
        and constructs the argument-parsing functions from these.
        In this case also sets `shapes` and `numargs`.
        zshapes must be a string., z"keywords cannot be used as shapes.z^[_a-zA-Z][_a-zA-Z0-9]*$z'shapes must be valid python identifiersr   Nz+*args are not allowed w/out explicit shapesz,**kwds are not allowed w/out explicit shapesz1kwonly args are not allowed w/out explicit shapesz#defaults are not allowed for shapesr   z!Shape arguments are inconsistent., r'   )Zshape_arg_strlocscale_inlocscale_outnumargs)r   rl   rm   	TypeErrorreplacesplitkeyword	iskeywordSyntaxErrorrematchr   ra   appendvarargsr   r   defaultsjoindictparse_arg_templater   hasattrlenr   )r   meths_to_inspectr   r   r   fieldZshapes_listmethZshapes_argsra   itemZ
shapes_strdctrD   rD   rH   _construct_argparser  s\    






zrv_generic._construct_argparserc                 C   sd  |  }| jpd|d< | jpd|d< |du r0d}ddd	 |D }||d
< | jpTd|d< | jrz| jdkrz|d  d7  < | jrd| j d| |d< nd|d< | jdu rdD ]}|| dd||< qtdD ]v}| jdu r| jdd| _zt	| j|| _W q t
yD } z(td| j dt| |W Y d}~qd}~0 0 q| jdddd| _dS )z;Construct the instance docstring with string substitutions.distnamer   r'   r   NrD   r   c                 s   s   | ]}d | V  qdS )z%.3gNrD   )rF   rb   rD   rD   rH   	<genexpr>  rJ   z,rv_generic._construct_doc.<locals>.<genexpr>valsZshapes_r   r   z>>> z = Zset_vals_stmt)r?   r@   z-
%(shapes)s : array_like
    shape parametersrU   z%(shapes)s, z0Unable to construct docstring for distribution "z": z(, (z, )))r   r   r   r   r   r   range__doc__r   Z	docformatr   	Exceptionrepr)r   docdictZshapes_valsZtempdictr   r   irr   rD   rD   rH   _construct_doc  s@    


zrv_generic._construct_doc
continuousc                 C   s>   |du rd}d | d| ddtd dg| _| | dS )	z7Construct instance docstring from the default template.NAr'   r   z random variable.z

%(before_notes)s
r&   z
%(example)s)r   
docheadersr   r   )r   longnamer   discreterD   rD   rH   _construct_default_doc4  s    z!rv_generic._construct_default_docc                 O   s:   t | tr t| g|R i |S t| g|R i |S dS )a  Freeze the distribution for the given arguments.

        Parameters
        ----------
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution.  Should include all
            the non-optional arguments, may include ``loc`` and ``scale``.

        Returns
        -------
        rv_frozen : rv_frozen instance
            The frozen distribution.

        N)rl   rK   r   r   r   ra   r{   rD   rD   rH   freeze>  s    
zrv_generic.freezec                 O   s   | j |i |S rO   )r   r   rD   rD   rH   __call__R  s    zrv_generic.__call__c                 O   s   dS )NNNNNrD   r   rD   rD   rH   r   Y  s    zrv_generic._statsc                 G   sB   t jdd" | j|g|R  }W d    n1 s40    Y  |S )Nignore)r   )r\   errstategeneric_moment)r   rQ   ra   r   rD   rD   rH   _munp_  s    0zrv_generic._munpc                    s   | dd }tj| }dd   fdd|D }|d j}|d j}|d u rR|}ntt|}|t| }|dk rd|  | }n|dkrd| | }tdd t	||D }	|	st
d	| d
| d
| |d d }
|d }|d }|
|||fS )Nru   c                 S   s&   | j dkr"| jd dkr"| d } q | S r   )ndimr   )r   rD   rD   rH   squeeze_lefts  s    
z.rv_generic._argcheck_rvs.<locals>.squeeze_leftc                    s   g | ]} |qS rD   rD   )rF   r   r  rD   rH   rI     rJ   z,rv_generic._argcheck_rvs.<locals>.<listcomp>r   r   c                 S   s    g | ]\}}|d kp||kqS r   rD   )rF   ZbcdimZszdimrD   rD   rH   rI     s   z;size does not match the broadcast shape of the parameters. r   )getr\   r   r   r  r   r   r   r   ziprp   )r   ra   kwargsru   Z	all_bcastZbcast_shapeZ
bcast_ndimZsize_ZndiffokZparam_bcastZ	loc_bcastZscale_bcastrD   r  rH   _argcheck_rvse  s:    


zrv_generic._argcheck_rvsc                 G   s$   d}|D ]}t |t|dk}q|S )zDefault check for correct values on args and keywords.

        Returns condition array of 1's where arguments are correct and
         0's where they are not.

        r   r   )r   r   )r   ra   r   r   rD   rD   rH   	_argcheck  s    zrv_generic._argcheckc                 O   s   | j | jfS )a  Return the support of the (unscaled, unshifted) distribution.

        *Must* be overridden by distributions which have support dependent
        upon the shape parameters of the distribution.  Any such override
        *must not* set or change any of the class members, as these members
        are shared amongst all instances of the distribution.

        Parameters
        ----------
        arg1, arg2, ... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).

        Returns
        -------
        a, b : numeric (float, or int or +/-np.inf)
            end-points of the distribution's support for the specified
            shape parameters.
        r   r   r   ra   r  rD   rD   rH   r     s    zrv_generic._get_supportc                 G   sN   | j | \}}tjdd  ||k||k@ W  d    S 1 s@0    Y  d S Nr   invalidr   r\   r  r   rx   ra   r   r   rD   rD   rH   _support_mask  s    zrv_generic._support_maskc                 G   sN   | j | \}}tjdd  ||k ||k @ W  d    S 1 s@0    Y  d S r  r  r  rD   rD   rH   _open_support_mask  s    zrv_generic._open_support_maskr   c                G   s"   |j |d}| j|g|R  }|S )Nru   )uniform_ppf)r   ru   r   ra   UYrD   rD   rH   _rvs  s    zrv_generic._rvsc                 G   sF   t jdd& t| j|g|R  W  d    S 1 s80    Y  d S Nr   )divide)r\   r  r   _cdfr   rx   ra   rD   rD   rH   _logcdf  s    zrv_generic._logcdfc                 G   s   d| j |g|R   S NrT   r   r!  rD   rD   rH   _sf  s    zrv_generic._sfc                 G   sF   t jdd& t| j|g|R  W  d    S 1 s80    Y  d S r  )r\   r  r   r%  r!  rD   rD   rH   _logsf  s    zrv_generic._logsfc                 G   s   | j |g|R  S rO   )_ppfvecr   r   ra   rD   rD   rH   r    s    zrv_generic._ppfc                 G   s   | j d| g|R  S r#  )r  r(  rD   rD   rH   _isf  s    zrv_generic._isfc                 O   s   | dd}| dd}| j|i |\}}}}t| j| |dk}t|sdd| j d}	t|	t|dkr|t|d S |dur| j	}
t
|}n| j	}| j|||d}|| | }|dur|
| _	|rt| ts|d	krt|}n|tj}|S )
aV  Random variates of given type.

        Parameters
        ----------
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).
        loc : array_like, optional
            Location parameter (default=0).
        scale : array_like, optional
            Scale parameter (default=1).
        size : int or tuple of ints, optional
            Defining number of random variates (default is 1).
        random_state : {None, int, `numpy.random.Generator`,
                        `numpy.random.RandomState`}, optional

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

        Returns
        -------
        rvs : ndarray or scalar
            Random variates of given `size`.

        r   Nr   r   zDomain error in arguments. The `scale` parameter must be positive for all distributions, and many distributions have restrictions on shape parameters. Please see the `scipy.stats.z` documentation for details.dr   rD   )popr   r   r  r\   r   r   rp   r   r   r   r  rl   	rv_sampleintastypeZint64)r   ra   r{   r   Zrndmr   r   ru   r   messageZrandom_state_savedr   r   rD   rD   rH   r)     s0    


zrv_generic.rvsc                    s  | j |i |\}}}}tt||f\}}ttt|}| j| |dk@ ||k@ }g }tjt|| jd t	|rt
|g|||f R  }|d |d |dd   }}}| jr| j|i d|i\}	}
}}n| j| \}	}
}}d|v r0|	du r
| jdg|R  }	  }t|||	| |  || d	|v r|
du r| jd
g|R  }|	du rr| jdg|R  }	tjdd0 tt|	 ||	d
  tj}
W d   n1 s0    Y    }t|||
| |  || d|v r|du r| jdg|R  }|	du r(| jdg|R  }	|
du r~| jd
g|R  }tjdd ||	|	  }
W d   n1 st0    Y  tjdd: |	 |	 d|
  |	 | }|t|
d }W d   n1 s0    Y    }t||| || d|v r|du rt| jdg|R  }|	du r6| jdg|R  }	|
du r| jd
g|R  }tjdd ||	|	  }
W d   n1 s0    Y  |du rd}n|t|
d }|du r| jdg|R  }tjdd* |	 |	 d|
  |	 | }W d   n1 s0    Y  tjddF |	d
  d|
  |	 d|  |	 | }||
d  d }W d   n1 sj0    Y    }t||| || n fdd|D }dd |D }t|dkr|d S t|S dS )a  Some statistics of the given RV.

        Parameters
        ----------
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information)
        loc : array_like, optional
            location parameter (default=0)
        scale : array_like, optional (continuous RVs only)
            scale parameter (default=1)
        moments : str, optional
            composed of letters ['mvsk'] defining which moments to compute:
            'm' = mean,
            'v' = variance,
            's' = (Fisher's) skew,
            'k' = (Fisher's) kurtosis.
            (default is 'mv')

        Returns
        -------
        stats : sequence
            of requested moments.

        r   
fill_valuer  r  Nr   mr   vrU   r   r  rN   rV   rW   r   rX   r[   rZ   rY   c                    s   g | ]}   qS rD   )r   )rF   r   r?   rD   rH   rI     rJ   z$rv_generic.stats.<locals>.<listcomp>c                 S   s   g | ]}|d  qS )rD   rD   )rF   outrD   rD   rH   rI     rJ   )r   mapr   r   r  r\   fullr   badvalueanyr   r   r   r  r   r   r   r  wherer   r   r]   r   )r   ra   r{   r   r   r   r   outputgoodargsrR   r^   r_   r`   Zout0Zmu2pZmu3prc   Zmu4prd   rD   r4  rH   r   >  s     





@




,0




,

:&0zrv_generic.statsc           	      O   s   | j |i |\}}}tt||f\}}ttt|}| j| |dk@ ||k@ }tt|d}t|d| | j t	||g|R  }|d }|dd }t||| j
| t|  |d S )a  Differential entropy of the RV.

        Parameters
        ----------
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).
        loc : array_like, optional
            Location parameter (default=0).
        scale : array_like, optional  (continuous distributions only).
            Scale parameter (default=1).

        Notes
        -----
        Entropy is defined base `e`:

        >>> import numpy as np
        >>> from scipy.stats._distn_infrastructure import rv_discrete
        >>> drv = rv_discrete(values=((0, 1), (0.5, 0.5)))
        >>> np.allclose(drv.entropy(), np.log(2.0))
        True

        r   r*  r   NrD   )r   r6  r   r   r  r   r   r   r8  r   
vecentropyr   )	r   ra   r{   r   r   cond0r;  r<  Z	goodscalerD   rD   rH   r2     s    zrv_generic.entropyc              	      s  |}| j |i |\}}}tjg |||R  }|^ }}}t| j| |dk}t||dk}	t||dk}
t|g|||R  }|^ }}}t||krtd|dk rtdd\}}}}|dkr|dk r| jrdddd	d
d| i}ni }| j	|i |\}}}}t
|j}t|||||| j||d< t|j}t|| | j |	 r||dk | ||dk  }t||	| |
 r||||g dd  D } fddtdD }t|rt|dkg|R  }d}|D ]}||  |< |d7 }q \}}}}t|dkg||||R  }|^ }}}}t|jdd}|| }t|D ]:}t|||||| j|}|t||dd||  | 7 }q\||| | 7 }||| 9 }t||
| |d S )a  non-central moment of distribution of specified order.

        Parameters
        ----------
        order : int, order >= 1
            Order of moment.
        arg1, arg2, arg3,... : float
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).
        loc : array_like, optional
            location parameter (default=0)
        scale : array_like, optional
            scale parameter (default=1)

        r   zMoment must be an integer.zMoment must be positive.r      r   r2  r3  vsZmvsk)r   rU   rV   rX   .c                 S   s   g | ]}|d ur|qS rO   rD   rF   r   rD   rD   rH   rI   	  rJ   z%rv_generic.moment.<locals>.<listcomp>c                    s   g | ]} | d ur|qS rO   rD   rA  ZmomrD   rH   rI   
  rJ   rX   r   r*  dtypeT)exactrD   )r   r\   r   r   r  r   r   rp   r   r   r    r   re   r  r   r   r8  r9  r   r	   )r   r   ra   r{   rQ   r   r   r   Zi0i1i2rR   r^   r_   r`   Zmdictrb   resultZres1arrsidxjr   Zres2Zfacr   ZvalkrD   rB  rH   r4     sd    



 "zrv_generic.momentc                 O   s   | j dg|R i |S )aU  Median of the distribution.

        Parameters
        ----------
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information)
        loc : array_like, optional
            Location parameter, Default is 0.
        scale : array_like, optional
            Scale parameter, Default is 1.

        Returns
        -------
        median : float
            The median of the distribution.

        See Also
        --------
        rv_discrete.ppf
            Inverse of the CDF

              ?r0   r   rD   rD   rH   r:   !  s    zrv_generic.medianc                 O   s8   d|d< | j |i |}t|tr4|jdkr4|d S |S )a  Mean of the distribution.

        Parameters
        ----------
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information)
        loc : array_like, optional
            location parameter (default=0)
        scale : array_like, optional
            scale parameter (default=1)

        Returns
        -------
        mean : float
            the mean of the distribution

        r2  r   r   rD   r   rl   r   r  r   ra   r{   resrD   rD   rH   r7   ;  s
    zrv_generic.meanc                 O   s8   d|d< | j |i |}t|tr4|jdkr4|d S |S )a  Variance of the distribution.

        Parameters
        ----------
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information)
        loc : array_like, optional
            location parameter (default=0)
        scale : array_like, optional
            scale parameter (default=1)

        Returns
        -------
        var : float
            the variance of the distribution

        r3  r   r   rD   rN  rO  rD   rD   rH   r9   T  s
    zrv_generic.varc                 O   s    d|d< t | j|i |}|S )a  Standard deviation of the distribution.

        Parameters
        ----------
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information)
        loc : array_like, optional
            location parameter (default=0)
        scale : array_like, optional
            scale parameter (default=1)

        Returns
        -------
        std : float
            standard deviation of the distribution

        r3  r   )r   r   rO  rD   rD   rH   r8   m  s    zrv_generic.stdc           	      O   sz   |}t |}t|dk|dk B r*tdd| d }d| d }| j|g|R i |}| j|g|R i |}||fS )a|  Confidence interval with equal areas around the median.

        Parameters
        ----------
        confidence : array_like of float
            Probability that an rv will be drawn from the returned range.
            Each value should be in the range [0, 1].
        arg1, arg2, ... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).
        loc : array_like, optional
            location parameter, Default is 0.
        scale : array_like, optional
            scale parameter, Default is 1.

        Returns
        -------
        a, b : ndarray of float
            end-points of range that contain ``100 * alpha %`` of the rv's
            possible values.

        Notes
        -----
        This is implemented as ``ppf([p_tail, 1-p_tail])``, where
        ``ppf`` is the inverse cumulative distribution function and
        ``p_tail = (1-confidence)/2``. Suppose ``[c, d]`` is the support of a
        discrete distribution; then ``ppf([0, 1]) == (c-1, d)``. Therefore,
        when ``confidence=1`` and the distribution is discrete, the left end
        of the interval will be beyond the support of the distribution.
        For discrete distributions, the interval will limit the probability
        in each tail to be less than or equal to ``p_tail`` (usually
        strictly less).

        r   r   z'alpha must be between 0 and 1 inclusiverT   rU   )r   r\   r9  rp   r0   )	r   r   ra   r{   alphaq1q2r   r   rD   rD   rH   r6     s    #zrv_generic.intervalc                 O   s  | j |i |\}}}tjg |||R  }|dd |d |d   }}}| j| |dk@ }| j| \}}| r|| | || | fS |jdkr| j| jfS t|	dt|	d }}|| | || |  }	}
t
|	d| | j t
|
d| | j |	|
fS )a  Support of the distribution.

        Parameters
        ----------
        arg1, arg2, ... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).
        loc : array_like, optional
            location parameter, Default is 0.
        scale : array_like, optional
            scale parameter, Default is 1.

        Returns
        -------
        a, b : array_like
            end-points of the distribution's support.

        Nr  r  r   r*  r   )r   r\   r   r  r   r   r  r8  r   r.  r   )r   ra   r  r   r   rI  r   _a_bZout_aZout_brD   rD   rH   r     s     
"zrv_generic.supportc                 C   sz   |  |\}}}| j| r"|dkr&tS t|| | }t|t| }t| j|g|R   rdtS | j	|g|R  | S )zNegative loglikelihood function.
        Notes
        -----
        This is ``-sum(log pdf(x, theta), axis=0)`` where `theta` are the
        parameters (including loc and scale).
        r   )
_unpack_loc_scaler  r   r   r   r   r\   r9  r  _nnlfr   thetarx   r   r   ra   Zn_log_scalerD   rD   rH   nnlf  s    zrv_generic.nnlfc                 G   s   t j| j|g|R  dd S )Nr   Zaxis)r\   rw   _logpxfr!  rD   rD   rH   rW    s    zrv_generic._nnlfc           	      C   s   | j |g|R   }tj|dd}|dkr:t| |d }||g|R  }t|}|tj| dd7 }|dkr|tt d }tj|| dd | S tj|dd S )Nr   r[  d   )r  r\   rv   r   rt   rw   r   r!   )	r   rx   ra   Z
log_fitfunr>  n_badZlogffZfinite_logffZpenaltyrD   rD   rH   _nlff_and_penalty  s    
zrv_generic._nlff_and_penaltyc                 C   sZ   |  |\}}}| j| r"|dkr&tS t|| | }t|t| }| ||| j| S )zPenalized negative loglikelihood function.
        i.e., - sum (log pdf(x, theta), axis=0) + penalty
        where theta are the parameters (including loc and scale)
        r   )rV  r  r   r   r   r   r_  r\  rX  rD   rD   rH   _penalized_nnlf  s    zrv_generic._penalized_nnlfc                    sR     |\}}} j| r"|dkr&tS t|| | } fdd} |||S )zPenalized negative log product spacing function.
        i.e., - sum (log (diff (cdf (x, theta))), axis=0) + penalty
        where theta are the parameters (including loc and scale)
        Follows reference [1] of scipy.stats.fit
        r   c                    s   t j| dd\} }| jr* j| g|R  ng }| jrDd|d  dksjt dg|dgf}t |dgf}nt dg|f}|t t ||  S )NT)Zreturn_countsr   r  r   )r\   uniqueru   r   Zconcatenater   diff)rx   ra   ZljZcdf_datar,   r   rD   rH   log_psf  s    z,rv_generic._penalized_nlpsf.<locals>.log_psf)rV  r  r   r\   sortr_  )r   rY  rx   r   r   ra   rc  rD   r   rH   _penalized_nlpsf  s    zrv_generic._penalized_nlpsf)N)N)NNr   )-r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r   r  r  r  r"  r%  r&  r  r)  r)   r   r2   r4   r:   r7   r9   r8   r6   r   rZ  rW  r_  r`  re  __classcell__rD   rD   r   rH   r   u  sZ   


	Q
&  

JEq%M.#r   c                   @   s&   e Zd Zdej ejfdfddZdS )
_ShapeInfoF)TTc                 C   sx   || _ || _t|}t|d r@|d s@t|d tj|d< t|d rn|d snt|d tj |d< || _d S r   )r   integralityr   r\   rt   	nextafterr   domain)r   r   rh  rj  Z	inclusiverD   rD   rH   r     s    z_ShapeInfo.__init__N)r   r   r   r\   r   r   rD   rD   rD   rH   rg    s   rg  c                    sR    fdd|D }t |dkr>dd |D }tdd| |rN|d d S dS )	a$  
    Given names such as `['f0', 'fa', 'fix_a']`, check that there is
    at most one non-None value in `kwds` associaed with those names.
    Return that value, or None if none of the names occur in `kwds`.
    As a side effect, all occurrences of those names in `kwds` are
    removed.
    c                    s"   g | ]}| v r|  |fqS rD   r+  )rF   r   r{   rD   rH   rI   2  rJ   z(_get_fixed_fit_value.<locals>.<listcomp>r   c                 S   s   g | ]\}}|qS rD   rD   )rF   r   rb   rD   rD   rH   rI   4  rJ   zOfit method got multiple keyword arguments to specify the same fixed parameter: r   r   N)r   rp   r   )r{   namesr   ZrepeatedrD   rl  rH   _get_fixed_fit_value*  s    rn  c                	       sH  e Zd ZdZdQ fdd	Zdd Zd	d
 Zdd Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 ZdRd9d:ZdSd;d<Zd=d> Z d?d@ Z!dAdB Z"dCdD Z#dEdF Z$dTdJdKZ%dLdM Z&dHddNdOdPZ'  Z(S )UrK   a  A generic continuous random variable class meant for subclassing.

    `rv_continuous` is a base class to construct specific distribution classes
    and instances for continuous random variables. It cannot be used
    directly as a distribution.

    Parameters
    ----------
    momtype : int, optional
        The type of generic moment calculation to use: 0 for pdf, 1 (default)
        for ppf.
    a : float, optional
        Lower bound of the support of the distribution, default is minus
        infinity.
    b : float, optional
        Upper bound of the support of the distribution, default is plus
        infinity.
    xtol : float, optional
        The tolerance for fixed point calculation for generic ppf.
    badvalue : float, optional
        The value in a result arrays that indicates a value that for which
        some argument restriction is violated, default is np.nan.
    name : str, optional
        The name of the instance. This string is used to construct the default
        example for distributions.
    longname : str, optional
        This string is used as part of the first line of the docstring returned
        when a subclass has no docstring of its own. Note: `longname` exists
        for backwards compatibility, do not use for new subclasses.
    shapes : str, optional
        The shape of the distribution. For example ``"m, n"`` for a
        distribution that takes two integers as the two shape arguments for all
        its methods. If not provided, shape parameters will be inferred from
        the signature of the private methods, ``_pdf`` and ``_cdf`` of the
        instance.
    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
        singleton is used.
        If `seed` is an int, a new ``RandomState`` instance is used,
        seeded with `seed`.
        If `seed` is already a ``Generator`` or ``RandomState`` instance then
        that instance is used.

    Methods
    -------
    rvs
    pdf
    logpdf
    cdf
    logcdf
    sf
    logsf
    ppf
    isf
    moment
    stats
    entropy
    expect
    median
    mean
    std
    var
    interval
    __call__
    fit
    fit_loc_scale
    nnlf
    support

    Notes
    -----
    Public methods of an instance of a distribution class (e.g., ``pdf``,
    ``cdf``) check their arguments and pass valid arguments to private,
    computational methods (``_pdf``, ``_cdf``). For ``pdf(x)``, ``x`` is valid
    if it is within the support of the distribution.
    Whether a shape parameter is valid is decided by an ``_argcheck`` method
    (which defaults to checking that its arguments are strictly positive.)

    **Subclassing**

    New random variables can be defined by subclassing the `rv_continuous` class
    and re-defining at least the ``_pdf`` or the ``_cdf`` method (normalized
    to location 0 and scale 1).

    If positive argument checking is not correct for your RV
    then you will also need to re-define the ``_argcheck`` method.

    For most of the scipy.stats distributions, the support interval doesn't
    depend on the shape parameters. ``x`` being in the support interval is
    equivalent to ``self.a <= x <= self.b``.  If either of the endpoints of
    the support do depend on the shape parameters, then
    i) the distribution must implement the ``_get_support`` method; and
    ii) those dependent endpoints must be omitted from the distribution's
    call to the ``rv_continuous`` initializer.

    Correct, but potentially slow defaults exist for the remaining
    methods but for speed and/or accuracy you can over-ride::

      _logpdf, _cdf, _logcdf, _ppf, _rvs, _isf, _sf, _logsf

    The default method ``_rvs`` relies on the inverse of the cdf, ``_ppf``,
    applied to a uniform random variate. In order to generate random variates
    efficiently, either the default ``_ppf`` needs to be overwritten (e.g.
    if the inverse cdf can expressed in an explicit form) or a sampling
    method needs to be implemented in a custom ``_rvs`` method.

    If possible, you should override ``_isf``, ``_sf`` or ``_logsf``.
    The main reason would be to improve numerical accuracy: for example,
    the survival function ``_sf`` is computed as ``1 - _cdf`` which can
    result in loss of precision if ``_cdf(x)`` is close to one.

    **Methods that can be overwritten by subclasses**
    ::

      _rvs
      _pdf
      _cdf
      _sf
      _ppf
      _isf
      _stats
      _munp
      _entropy
      _argcheck
      _get_support

    There are additional (internal and private) generic methods that can
    be useful for cross-checking and for debugging, but might work in all
    cases when directly called.

    A note on ``shapes``: subclasses need not specify them explicitly. In this
    case, `shapes` will be automatically deduced from the signatures of the
    overridden methods (`pdf`, `cdf` etc).
    If, for some reason, you prefer to avoid relying on introspection, you can
    specify ``shapes`` explicitly as an argument to the instance constructor.


    **Frozen Distributions**

    Normally, you must provide shape parameters (and, optionally, location and
    scale parameters to each call of a method of a distribution.

    Alternatively, the object may be called (as a function) to fix the shape,
    location, and scale parameters returning a "frozen" continuous RV object:

    rv = generic(<shape(s)>, loc=0, scale=1)
        `rv_frozen` object with the same methods but holding the given shape,
        location, and scale fixed

    **Statistics**

    Statistics are computed using numerical integration by default.
    For speed you can redefine this using ``_stats``:

     - take shape parameters and return mu, mu2, g1, g2
     - If you can't compute one of these, return it as None
     - Can also be defined with a keyword argument ``moments``, which is a
       string composed of "m", "v", "s", and/or "k".
       Only the components appearing in string should be computed and
       returned in the order "m", "v", "s", or "k"  with missing values
       returned as None.

    Alternatively, you can override ``_munp``, which takes ``n`` and shape
    parameters and returns the n-th non-central moment of the distribution.

    **Deepcopying / Pickling**

    If a distribution or frozen distribution is deepcopied (pickled/unpickled,
    etc.), any underlying random number generator is deepcopied with it. An
    implication is that if a distribution relies on the singleton RandomState
    before copying, it will rely on a copy of that random state after copying,
    and ``np.random.seed`` will no longer control the state.

    Examples
    --------
    To create a new Gaussian distribution, we would do the following:

    >>> from scipy.stats import rv_continuous
    >>> class gaussian_gen(rv_continuous):
    ...     "Gaussian distribution"
    ...     def _pdf(self, x):
    ...         return np.exp(-x**2 / 2.) / np.sqrt(2.0 * np.pi)
    >>> gaussian = gaussian_gen(name='gaussian')

    ``scipy.stats`` distributions are *instances*, so here we subclass
    `rv_continuous` and create an instance. With this, we now have
    a fully functional distribution with all relevant methods automagically
    generated by the framework.

    Note that above we defined a standard normal distribution, with zero mean
    and unit variance. Shifting and scaling of the distribution can be done
    by using ``loc`` and ``scale`` parameters: ``gaussian.pdf(x, loc, scale)``
    essentially computes ``y = (x - loc) / scale`` and
    ``gaussian._pdf(y) / scale``.

    r   N+=c
                    s  t  |	 t|||||||||	d	| _|d u r4t}|d u r@d}|| _|| _|| _|| _|d u rht	 | _|d u rvt	| _|| _
|| _|| _| j| j| jgddd |   |d u r|d dv rd}
nd	}
|
| }tjjd
k r| jd u r| j|tdd ntt}| t|| j d S )N)	momtyper   r   xtolr8  r   r   r   r   Distributionzloc=0, scale=1z
loc, scaler   r   r   r   Z
aeiouAEIOUAn A rU   r   r   r   r   )r   r   r   r   r   r8  r   r   r   r   rq  moment_typer   r   _pdfr   r   sysflagsr   r   r   r   r   r   r	  )r   rp  r   r   rq  r8  r   r   r   r   hstrr   r   rD   rH   r   
  sN    
zrv_continuous.__init__c                    s(   | j   g d} fdd|D   S )N)r   r   r   _cdfvecr'  r=  r  c                    s   g | ]}  |d qS rO   rk  rF   attrr   rD   rH   rI   C  rJ   z.rv_continuous.__getstate__.<locals>.<listcomp>r   r   r   attrsrD   r  rH   __getstate__<  s    
zrv_continuous.__getstate__c                 C   s   |    t| jdd| _| jd | j_t| jdd| _t| jdd| _	| jd | j	_| j
dkrpt| jdd| _nt| jdd| _| jd | j_dS )zU
        Attaches dynamically created methods to the rv_continuous instance.
        r*  Zotypesr   r   N)r   r   _ppf_singler'  r   nin_entropyr=  _cdf_singler}  rx  _mom0_scr  _mom1_scr   rD   rD   rH   r   F  s    
zrv_continuous._attach_methodsc                 C   sJ   | j  }| j|d< | j|d< | j|d< | j|d< | j|d< | j|d< |S )Return the current version of _ctor_param, possibly updated by user.

        Used by freezing.
        Keep this in sync with the signature of __init__.
        r   r   rq  r8  r   r   )r   r   r   r   rq  r8  r   r   r   r   rD   rD   rH   r}   \  s    






z!rv_continuous._updated_ctor_paramc                 G   s   | j |f|  | S rO   )r,   )r   rx   r   ra   rD   rD   rH   _ppf_to_solvek  s    zrv_continuous._ppf_to_solvec                 G   s   d}| j | \}}t|rPt| |}| j||g|R  dkrP|| | }}q(t|rt||}| j||g|R  dk r|||  }}qdtj| j|||f| | jdS )Ng      $@        )ra   rq  )	r   r\   r   minr  maxr   Zbrentqrq  )r   r   ra   factorleftrightrD   rD   rH   r  n  s    


zrv_continuous._ppf_singlec                 G   s   || | j |g|R   S rO   r*   )r   rx   r2  ra   rD   rD   rH   _mom_integ0  s    zrv_continuous._mom_integ0c                 G   s,   | j | \}}tj| j|||f| dd S Nra   r   )r   r   quadr  )r   r2  ra   rT  rU  rD   rD   rH   r    s    zrv_continuous._mom0_scc                 G   s   | j |g|R  | S rO   rM  )r   r   r2  ra   rD   rD   rH   _mom_integ1  s    zrv_continuous._mom_integ1c                 G   s   t j| jdd|f| dd S )Nr   r   r  )r   r  r  )r   r2  ra   rD   rD   rH   r    s    zrv_continuous._mom1_scc                 G   s   t | j|d|ddS )Ngh㈵>r?  )Zdxra   r   )r   r   r!  rD   rD   rH   ry    s    zrv_continuous._pdfc                 G   sJ   | j |g|R  }tjdd t|W  d    S 1 s<0    Y  d S r  )ry  r\   r  r   )r   rx   ra   prD   rD   rH   _logpdf  s    zrv_continuous._logpdfc                 G   s   | j |g|R  S rO   )r  r!  rD   rD   rH   r\    s    zrv_continuous._logpxfc                 G   s&   | j | \}}tj| j|||dd S r  )r   r   r  ry  )r   rx   ra   rT  rU  rD   rD   rH   r    s    zrv_continuous._cdf_singlec                 G   s   | j |g|R  S rO   )r}  r!  rD   rD   rH   r     s    zrv_continuous._cdfc                 O   s*  | j |i |\}}}tt|||f\}}}ttt|}t|jtj}tj|| | |d}| j| |dk@ }| j	|g|R  |dk@ }||@ }	t
t|	|}
t|
d| t| | j t|	rt|	g|f| |f R  }|d |dd  }}t|
|	| j| |  |
jdkr&|
d S |
S )aD  Probability density function at x of the given RV.

        Parameters
        ----------
        x : array_like
            quantiles
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information)
        loc : array_like, optional
            location parameter (default=0)
        scale : array_like, optional
            scale parameter (default=1)

        Returns
        -------
        pdf : ndarray
            Probability density function evaluated at x

        rC  r   r   r  NrD   )r   r6  r   r   r\   promote_typesrD  float64r  r  r   r   r   isnanr8  r9  r   r   ry  r  r   rx   ra   r{   r   r   dtypr>  cond1r   r;  r<  rD   rD   rH   r*     s"    zrv_continuous.pdfc                 O   s:  | j |i |\}}}tt|||f\}}}ttt|}t|jtj}tj|| | |d}| j| |dk@ }| j	|g|R  |dk@ }||@ }	t
t|	|}
|
t  t|
d| t| | j t|	r"t|	g|f| |f R  }|d |dd  }}t|
|	| j| t|  |
jdkr6|
d S |
S )a  Log of the probability density function at x of the given RV.

        This uses a more numerically accurate calculation if available.

        Parameters
        ----------
        x : array_like
            quantiles
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information)
        loc : array_like, optional
            location parameter (default=0)
        scale : array_like, optional
            scale parameter (default=1)

        Returns
        -------
        logpdf : array_like
            Log of the probability density function evaluated at x

        rC  r   r   r  NrD   )r   r6  r   r   r\   r  rD  r  r  r  r    r   fillr   r   r  r8  r9  r   r   r  r   r  r  rD   rD   rH   r+     s$    zrv_continuous.logpdfc                 O   s6  | j |i |\}}}tt|||f\}}}ttt|}| j| \}}t|jtj}tj|| | |d}| j	| |dk@ }	| j
|g|R  |dk@ }
|t|k|	@ }|	|
@ }tt||}t|d|	 t| | j t||d t|rt|g|f| R  }t||| j|  |jdkr2|d S |S )aR  
        Cumulative distribution function of the given RV.

        Parameters
        ----------
        x : array_like
            quantiles
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information)
        loc : array_like, optional
            location parameter (default=0)
        scale : array_like, optional
            scale parameter (default=1)

        Returns
        -------
        cdf : ndarray
            Cumulative distribution function evaluated at `x`

        rC  r   r   rT   rD   )r   r6  r   r   r   r\   r  rD  r  r  r  r   r   r   r  r8  r9  r   r   r  r   rx   ra   r{   r   r   rT  rU  r  r>  r  cond2r   r;  r<  rD   rD   rH   r,     s&    zrv_continuous.cdfc                 O   sD  | j |i |\}}}tt|||f\}}}ttt|}| j| \}}t|jtj}tj|| | |d}| j	| |dk@ }	| j
|g|R  |dk@ }
||k|	@ }|	|
@ }tt||}|t  t|d|	 |
|
k t| | j t||d t|r,t|g|f| R  }t||| j|  |jdkr@|d S |S )ah  Log of the cumulative distribution function at x of the given RV.

        Parameters
        ----------
        x : array_like
            quantiles
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information)
        loc : array_like, optional
            location parameter (default=0)
        scale : array_like, optional
            scale parameter (default=1)

        Returns
        -------
        logcdf : array_like
            Log of the cumulative distribution function evaluated at x

        rC  r   r   r  rD   )r   r6  r   r   r   r\   r  rD  r  r  r  r    r   r  r   r   r  r8  r9  r   r"  r  r  rD   rD   rH   r-   &  s(    $zrv_continuous.logcdfc                 O   s0  | j |i |\}}}tt|||f\}}}ttt|}| j| \}}t|jtj}tj|| | |d}| j	| |dk@ }	| j
|g|R  |dk@ }
|	||k@ }|	|
@ }tt||}t|d|	 t| | j t||d t|rt|g|f| R  }t||| j|  |jdkr,|d S |S )a<  Survival function (1 - `cdf`) at x of the given RV.

        Parameters
        ----------
        x : array_like
            quantiles
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information)
        loc : array_like, optional
            location parameter (default=0)
        scale : array_like, optional
            scale parameter (default=1)

        Returns
        -------
        sf : array_like
            Survival function evaluated at x

        rC  r   r   rT   rD   )r   r6  r   r   r   r\   r  rD  r  r  r  r   r   r   r  r8  r9  r   r%  r  r  rD   rD   rH   r.   P  s&    zrv_continuous.sfc                 O   s<  | j |i |\}}}tt|||f\}}}ttt|}| j| \}}t|jtj}tj|| | |d}| j	| |dk@ }	| j
|g|R  |dk@ }
|	||k@ }|	|
@ }tt||}|t  t|d|	 t| | j t||d t|r$t|g|f| R  }t||| j|  |jdkr8|d S |S )a  Log of the survival function of the given RV.

        Returns the log of the "survival function," defined as (1 - `cdf`),
        evaluated at `x`.

        Parameters
        ----------
        x : array_like
            quantiles
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information)
        loc : array_like, optional
            location parameter (default=0)
        scale : array_like, optional
            scale parameter (default=1)

        Returns
        -------
        logsf : ndarray
            Log of the survival function evaluated at `x`.

        rC  r   r   r  rD   )r   r6  r   r   r   r\   r  rD  r  r  r  r    r   r  r   r   r  r8  r9  r   r&  r  r  rD   rD   rH   r/   y  s(    zrv_continuous.logsfc                 O   sf  | j |i |\}}}tt|||f\}}}ttt|}| j| \}}| j| |dk@ ||k@ }d|k |dk @ }	||dk@ }
||dk@ }||	@ }tjt|| j	d}|| | }|| | }t
||
t|
|d  t
||t||d  t|rNt|g|f| ||f R  }|d |d |dd   }}}t
||| j| | |  |jdkrb|d S |S )ak  Percent point function (inverse of `cdf`) at q of the given RV.

        Parameters
        ----------
        q : array_like
            lower tail probability
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information)
        loc : array_like, optional
            location parameter (default=0)
        scale : array_like, optional
            scale parameter (default=1)

        Returns
        -------
        x : array_like
            quantile corresponding to the lower tail probability q.

        r   r   r0  r  r  NrD   )r   r6  r   r   r   r  r\   r7  r   r8  r   r   r9  r  r  r   r   ra   r{   r   r   rT  rU  r>  r  r  cond3r   r;  lower_boundupper_boundr<  rD   rD   rH   r0     s*     zrv_continuous.ppfc                 O   sf  | j |i |\}}}tt|||f\}}}ttt|}| j| \}}| j| |dk@ ||k@ }d|k |dk @ }	||dk@ }
||dk@ }||	@ }tjt|| j	d}|| | }|| | }t
||
t|
|d  t
||t||d  t|rNt|g|f| ||f R  }|d |d |dd   }}}t
||| j| | |  |jdkrb|d S |S )at  Inverse survival function (inverse of `sf`) at q of the given RV.

        Parameters
        ----------
        q : array_like
            upper tail probability
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information)
        loc : array_like, optional
            location parameter (default=0)
        scale : array_like, optional
            scale parameter (default=1)

        Returns
        -------
        x : ndarray or scalar
            Quantile corresponding to the upper tail probability q.

        r   r   r0  r  r  NrD   )r   r6  r   r   r   r  r\   r7  r   r8  r   r   r9  r)  r  r  rD   rD   rH   r1     s*     zrv_continuous.isfc              
   C   s^   z$|d }|d }t |d d }W n. tyR } ztd|W Y d }~n
d }~0 0 |||fS )Nr  r  Not enough input arguments.r   
IndexErrorrp   r   rY  r   r   ra   rr   rD   rD   rH   rV   	  s     zrv_continuous._unpack_loc_scalec                 C   s  t |tr|j| j|  }t|t| }|jj\}}| j|jg|R  | j	|j
g|R  | j|jg|R  t| j||g|R  g}nJ| j|g|R   }t|}|dkrt| |d }| j|g|R  g}tdd |D  \}	}
t|	}|t|
7 }| |t d  S )a  
        Compute the penalized negative log-likelihood for the
        "standardized" data (i.e. already shifted by loc and
        scaled by scale) for the shape parameters in `args`.

        `x` can be a 1D numpy array or a CensoredData instance.
        r   c                 S   s   g | ]}t |qS rD   )ry   )rF   termrD   rD   rH   rI   '	  rJ   z3rv_continuous._nnlf_and_penalty.<locals>.<listcomp>r]  )rl   r#   Z
_supportedr   r   Z	_intervalTr  _uncensoredr"  _leftr&  _rightr\   r   
_delta_cdfr  rv   r   r
  rw   r"   )r   rx   ra   Zxsr^  rF  rG  Ztermsr>  ZtotalsZ
bad_countstotalrD   rD   rH   _nnlf_and_penalty		  s$    

zrv_continuous._nnlf_and_penaltyc                 C   s   |  |\}}}| j| r"|dkr&tS t|trV|| | }t||  t| }n|| | }t|t| }| ||| S )zPenalized negative loglikelihood function.

        i.e., - sum (log pdf(x, theta), axis=0) + penalty
        where theta are the parameters (including loc and scale)
        r   )	rV  r  r   rl   r#   r   num_censoredr   r  rX  rD   rD   rH   r`  -	  s    
zrv_continuous._penalized_nnlfc                 C   s4   |du rd| j  }| j|g|R  \}}|||f S )z7Starting point for fit (shape arguments + loc + scale).N)rT   )r   _fit_loc_scale_support)r   rP   ra   r   r   rD   rD   rH   	_fitstart?	  s    
zrv_continuous._fitstartc                    s  g }j rfj dd }t|D ]@\}}dt| }|d| d| g}t||}	|	dur$|	||< q$tt g dd t d D d	d
g }g }
t|D ]8\}}||v rΈ	| |
||< q|
	|  qddh}|
dd }|dkrht|d t }td|d ddtjf }tj|dddf | t| ddfddn&|dkrzjntd| d| tdkr}dn4t krtd fddfdd}|
|fS )z
        Return the (possibly reduced) function to optimize in order to find MLE
        estimates for the .fit method.
        r   r   fZfix_Nc                 S   s   g | ]}d | qS )zf%drD   )rF   rQ   rD   rD   rH   rI   \	  rJ   z.rv_continuous._reduce_func.<locals>.<listcomp>rU   ZflocZfscalemlemmmethodr   r[  c                    s    | | S rO   )_moment_error)rY  rx   )data_momentsr   rD   rH   	objectivel	  s    z-rv_continuous._reduce_func.<locals>.objectivezMethod 'z ' not available; must be one of r   z3All parameters fixed. There is nothing to optimize.c                    s2   d}t  D ] }|vr|| | |< |d7 }q| S r   )r   )ra   rY  r   rQ   )NargsfixednrD   rH   restore}	  s    
z+rv_continuous._reduce_func.<locals>.restorec                    s    d d  | }||S rO   rD   )rY  rx   Znewtheta)ra   r  r  rD   rH   r   	  s    z(rv_continuous._reduce_func.<locals>.func)r   r   r   	enumeraterm   rn  r   r   r   r   r+  lowerr\   r   newaxisrw   r`  rp   )r   ra   r{   rP   r   rK  rN   keyrm  rb   x0rQ   r%   r  Zn_paramsZ	exponentsr   rD   )r  ra   r  r  r  r  r   rH   _reduce_funcF	  sR    	



&

zrv_continuous._reduce_funcc                    s    |\ j  r"dkr&tS t fddtt|D }tt|rdt	d|| t
t|d d  S )Nr   c                    s*   g | ]"}j |d  g R dqS )r   r   r   )r4   rA  ra   r   r   r   rD   rH   rI   	  s   z/rv_continuous._moment_error.<locals>.<listcomp>zqMethod of moments encountered a non-finite distribution moment and cannot continue. Consider trying method='MLE'.:0yE>rU   )rV  r  r   r\   arrayr   r   r9  r  rp   maximumabsrw   )r   rY  rx   r  Zdist_momentsrD   r  rH   r  	  s    
zrv_continuous._moment_errorc                 O   s  | dd }t|t}|rD|dkr.td| dkrD|j}d}t|}|| jkr^t	d|st
| }t
| stddgd	 }|| jk sd
|v rd|v s| |}|||d 7 }|d
|d }|d|d }	|||	f7 }| j|||d\}
}}}|dtj}t|}|r0t	d| |||
|fdd}|||}|dur`|||}t|}| |\}}	}t
| j| r|	dkstd|dkrt
|std|S )a  
        Return estimates of shape (if applicable), location, and scale
        parameters from data. The default estimation method is Maximum
        Likelihood Estimation (MLE), but Method of Moments (MM)
        is also available.

        Starting estimates for the fit are given by input arguments;
        for any arguments not provided with starting estimates,
        ``self._fitstart(data)`` is called to generate such.

        One can hold some parameters fixed to specific values by passing in
        keyword arguments ``f0``, ``f1``, ..., ``fn`` (for shape parameters)
        and ``floc`` and ``fscale`` (for location and scale parameters,
        respectively).

        Parameters
        ----------
        data : array_like or `CensoredData` instance
            Data to use in estimating the distribution parameters.
        arg1, arg2, arg3,... : floats, optional
            Starting value(s) for any shape-characterizing arguments (those not
            provided will be determined by a call to ``_fitstart(data)``).
            No default value.
        **kwds : floats, optional
            - `loc`: initial guess of the distribution's location parameter.
            - `scale`: initial guess of the distribution's scale parameter.

            Special keyword arguments are recognized as holding certain
            parameters fixed:

            - f0...fn : hold respective shape parameters fixed.
              Alternatively, shape parameters to fix can be specified by name.
              For example, if ``self.shapes == "a, b"``, ``fa`` and ``fix_a``
              are equivalent to ``f0``, and ``fb`` and ``fix_b`` are
              equivalent to ``f1``.

            - floc : hold location parameter fixed to specified value.

            - fscale : hold scale parameter fixed to specified value.

            - optimizer : The optimizer to use.  The optimizer must take
              ``func`` and starting position as the first two arguments,
              plus ``args`` (for extra arguments to pass to the
              function to be optimized) and ``disp``. 
              The ``fit`` method calls the optimizer with ``disp=0`` to suppress output.
              The optimizer must return the estimated parameters.

            - method : The method to use. The default is "MLE" (Maximum
              Likelihood Estimate); "MM" (Method of Moments)
              is also available.

        Raises
        ------
        TypeError, ValueError
            If an input is invalid
        `~scipy.stats.FitError`
            If fitting fails or the fit produced would be invalid

        Returns
        -------
        parameter_tuple : tuple of floats
            Estimates for any shape parameters (if applicable), followed by
            those for location and scale. For most random variables, shape
            statistics will be returned, but there are exceptions (e.g.
            ``norm``).

        Notes
        -----
        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="MM"``, the fit is computed by minimizing the L2 norm
        of the relative errors between the first *k* raw (about zero) data
        moments and the corresponding distribution moments, where *k* is the
        number of non-fixed parameters.
        More precisely, the objective function is::

            (((data_moments - dist_moments)
              / np.maximum(np.abs(data_moments), 1e-8))**2).sum()

        where the constant ``1e-8`` avoids division by zero in case of
        vanishing data moments. Typically, this error norm can be reduced to
        zero.
        Note that the standard method of moments can produce parameters for
        which some data are outside the support of the fitted distribution;
        this implementation does nothing to prevent this.

        For either method,
        the returned answer is not guaranteed to be globally optimal; it
        may only be locally optimal, or the optimization may fail altogether.
        If the data contain any of ``np.nan``, ``np.inf``, or ``-np.inf``,
        the `fit` method will raise a ``RuntimeError``.

        When passing a ``CensoredData`` instance to ``data``, the log-likelihood
        function is defined as:

        .. math::

            l(\pmb{\theta}; k) & = \sum
                                    \log(f(k_u; \pmb{\theta}))
                                + \sum
                                    \log(F(k_l; \pmb{\theta})) \\
                                & + \sum 
                                    \log(1 - F(k_r; \pmb{\theta})) \\
                                & + \sum
                                    \log(F(k_{\text{high}, i}; \pmb{\theta})
                                    - F(k_{\text{low}, i}; \pmb{\theta}))

        where :math:`f` and :math:`F` are the pdf and cdf, respectively, of the
        function being fitted, :math:`\pmb{\theta}` is the parameter vector,
        :math:`u` are the indices of uncensored observations,
        :math:`l` are the indices of left-censored observations,
        :math:`r` are the indices of right-censored observations,
        subscripts "low"/"high" denote endpoints of interval-censored observations, and
        :math:`i` are the indices of interval-censored observations.

        Examples
        --------

        Generate some data to fit: draw random variates from the `beta`
        distribution

        >>> import numpy as np
        >>> from scipy.stats import beta
        >>> a, b = 1., 2.
        >>> rng = np.random.default_rng(172786373191770012695001057628748821561)
        >>> x = beta.rvs(a, b, size=1000, random_state=rng)

        Now we can fit all four parameters (``a``, ``b``, ``loc`` and
        ``scale``):

        >>> a1, b1, loc1, scale1 = beta.fit(x)
        >>> a1, b1, loc1, scale1
        (1.0198945204435628, 1.9484708982737828, 4.372241314917588e-05, 0.9979078845964814)

        The fit can be done also using a custom optimizer:

        >>> from scipy.optimize import minimize
        >>> def custom_optimizer(func, x0, args=(), disp=0):
        ...     res = minimize(func, x0, args, method="slsqp", options={"disp": disp})
        ...     if res.success:
        ...         return res.x
        ...     raise RuntimeError('optimization routine failed')
        >>> a1, b1, loc1, scale1 = beta.fit(x, method="MLE", optimizer=custom_optimizer)
        >>> a1, b1, loc1, scale1
        (1.0198821087258905, 1.948484145914738, 4.3705304486881485e-05, 0.9979104663953395)

        We can also use some prior knowledge about the dataset: let's keep
        ``loc`` and ``scale`` fixed:

        >>> a1, b1, loc1, scale1 = beta.fit(x, floc=0, fscale=1)
        >>> loc1, scale1
        (0, 1)

        We can also keep shape parameters fixed by using ``f``-keywords. To
        keep the zero-th shape parameter ``a`` equal 1, use ``f0=1`` or,
        equivalently, ``fa=1``:

        >>> a1, b1, loc1, scale1 = beta.fit(x, fa=1, floc=0, fscale=1)
        >>> a1
        1

        Not all distributions return estimates for the shape parameters.
        ``norm`` for example just returns estimates for location and scale:

        >>> from scipy.stats import norm
        >>> x = norm.rvs(a, b, size=1000, random_state=123)
        >>> loc1, scale1 = norm.fit(x)
        >>> loc1, scale1
        (0.92087172783841631, 2.0015750750324668)
        r  r  z,For censored data, the method must be "MLE".r   FzToo many input arguments.z$The data contains non-finite values.NrU   r   r   r  r  )rP   rq   zUnknown arguments: %s.)ra   Zdispz\Optimization converged to parameters that are outside the range allowed by the distribution.r  zVOptimization failed: either a data moment or fitted distribution moment is non-finite.)r	  r  rl   r#   rp   r  r  r   r   r   r\   r   rf   rt   r   r  r+  r  r   rj   rs   r   rV  r  r$   )r   rP   ra   r{   r  ZcensoredZNargstartr   r   r  r   r  rq   r   rG   r   rD   rD   rH   r3   	  sT     /







zrv_continuous.fitc                 G   s6  t |tr| }n
t|}| j|g|R  \}}| j|  | j| \}}|| }}|| }	|	dkrn||fS |||  }
|||  }t|}t	|}|
|k r||k r||fS || }d}|| }|	tj
k r|| | }|d|  |	 }||fS |tj
 kr|| | dfS |tj
k r.|| | dfS tdS )a  Estimate loc and scale parameters from data accounting for support.

        Parameters
        ----------
        data : array_like
            Data to fit.
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).

        Returns
        -------
        Lhat : float
            Estimated location parameter for the data.
        Shat : float
            Estimated scale parameter for the data.

        r   g?rU   r   N)rl   r#   Z	_uncensorr\   r   fit_loc_scaler  r   r  r  r   RuntimeError)r   rP   ra   Zloc_hatZ	scale_hatrT  rU  r   r   Zsupport_widthZa_hatZb_hatZdata_aZdata_bZ
data_widthZ
rel_marginmarginrD   rD   rH   r  
  s8    







z$rv_continuous._fit_loc_scale_supportc           
      G   s   | j |i ddi\}}t|}| }| }t|| }tjdd |||  }	W d   n1 sj0    Y  t|	sd}	t|rd|k sd}|	|fS )a  
        Estimate loc and scale parameters from data using 1st and 2nd moments.

        Parameters
        ----------
        data : array_like
            Data to fit.
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).

        Returns
        -------
        Lhat : float
            Estimated location parameter for the data.
        Shat : float
            Estimated scale parameter for the data.

        r   r   r   r  Nr   r   )r   r   r7   r9   r   r\   r  rt   )
r   rP   ra   rR   r^   tmpZmuhatZmu2hatZShatZLhatrD   rD   rH   r  
  s    *
zrv_continuous.fit_loc_scalec           
         s    fdd}j   \}}tjdd" t|||d }W d    n1 sP0    Y  t|sh|S jddgg R  \}}t|r|}n|}t|r|}	n|}	t||	|d S d S )Nc                    s   j | g R  }t|S rO   )ry  r
   )rx   rb   ra   r   rD   rH   integ
  s    z%rv_continuous._entropy.<locals>.integr   )Zoverr   绽|=gA?)r   r\   r  r   r  r  r0   r   )
r   ra   r  rT  rU  hlowZuppupperr  rD   r  rH   r  
  s    0


zrv_continuous._entropyrD   r   Fc                    s`  ||dj |  j| \}	}
 du r:fdd}n fdd}|du r^||	|  }|du rr||
|  }j||gg|R i }|d |d  }||d< d	}t|d| g}|d ||  }|j|g|R  |  \}}tj|||fi |d }tj|||fi |d }tj|||fi |d }|| | }|rR|| }t|d
 S )a  Calculate expected value of a function with respect to the
        distribution by numerical integration.

        The expected value of a function ``f(x)`` with respect to a
        distribution ``dist`` is defined as::

                    ub
            E[f(x)] = Integral(f(x) * dist.pdf(x)),
                    lb

        where ``ub`` and ``lb`` are arguments and ``x`` has the ``dist.pdf(x)``
        distribution. If the bounds ``lb`` and ``ub`` correspond to the
        support of the distribution, e.g. ``[-inf, inf]`` in the default
        case, then the integral is the unrestricted expectation of ``f(x)``.
        Also, the function ``f(x)`` may be defined such that ``f(x)`` is ``0``
        outside a finite interval in which case the expectation is
        calculated within the finite range ``[lb, ub]``.

        Parameters
        ----------
        func : callable, optional
            Function for which integral is calculated. Takes only one argument.
            The default is the identity mapping f(x) = x.
        args : tuple, optional
            Shape parameters of the distribution.
        loc : float, optional
            Location parameter (default=0).
        scale : float, optional
            Scale parameter (default=1).
        lb, ub : scalar, optional
            Lower and upper bound for integration. Default is set to the
            support of the distribution.
        conditional : bool, optional
            If True, the integral is corrected by the conditional probability
            of the integration interval.  The return value is the expectation
            of the function, conditional on being in the given interval.
            Default is False.

        Additional keyword arguments are passed to the integration routine.

        Returns
        -------
        expect : float
            The calculated expected value.

        Notes
        -----
        The integration behavior of this function is inherited from
        `scipy.integrate.quad`. Neither this function nor
        `scipy.integrate.quad` can verify whether the integral exists or is
        finite. For example ``cauchy(0).mean()`` returns ``np.nan`` and
        ``cauchy(0).expect()`` returns ``0.0``.

        Likewise, the accuracy of results is not verified by the function.
        `scipy.integrate.quad` is typically reliable for integrals that are
        numerically favorable, but it is not guaranteed to converge
        to a correct value for all possible intervals and integrands. This
        function is provided for convenience; for critical applications,
        check results against other integration methods.

        The function is not vectorized.

        Examples
        --------

        To understand the effect of the bounds of integration consider

        >>> from scipy.stats import expon
        >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0)
        0.6321205588285578

        This is close to

        >>> expon(1).cdf(2.0) - expon(1).cdf(0.0)
        0.6321205588285577

        If ``conditional=True``

        >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0, conditional=True)
        1.0000000000000002

        The slight deviation from 1 is due to numerical integration.

        The integrand can be treated as a complex-valued function
        by passing ``complex_func=True`` to `scipy.integrate.quad` .

        >>> import numpy as np
        >>> from scipy.stats import vonmises
        >>> res = vonmises(loc=2, kappa=1).expect(lambda x: np.exp(1j*x),
        ...                                       complex_func=True)
        >>> res
        (-0.18576377217422957+0.40590124735052263j)

        >>> np.angle(res)  # location of the (circular) distribution
        2.0

        r  Nc                    s   | j | g|R i   S rO   r  rx   ra   )lockwdsr   rD   rH   funw  s    z!rv_continuous.expect.<locals>.func                    s     | j | g|R i  S rO   r  r  r   r  r   rD   rH   r  z  s    r   r   ra   g?rD   )r  r   r,   r\   r  r  r   r  )r   r   ra   r   r   r   r   r   r{   rT  rU  r  Z
cdf_boundsinvfacrQ  Zinner_boundsZcdf_inner_boundscr*  ZlbccdZdubr   rD   r  rH   r5     s4    c
zrv_continuous.expectc                 C   sD   |   }tddtj tjfd}tdddtjfd}|||g }|S )Nr   FFFr   r   Z_shape_inforg  r\   r   )r   
shape_infoloc_infoZ
scale_info
param_inforD   rD   rH   _param_info  s
    zrv_continuous._param_infor  c             	   G   s   | j |g|R ||d}t|dk| j|g|R ||d| j|g|R ||d | j |g|R ||d| }|jdkr|d }|S )a8  
        Compute CDF(x2) - CDF(x1).

        Where x1 is greater than the median, compute SF(x1) - SF(x2),
        otherwise compute CDF(x2) - CDF(x1).

        This function is only useful if `dist.sf(x, ...)` has an implementation
        that is numerically more accurate than `1 - dist.cdf(x, ...)`.
        r  rL  r   rD   )r,   r\   r:  r.   r  )r   x1Zx2r   r   ra   Zcdf1rH  rD   rD   rH   r    s    


zrv_continuous._delta_cdf)	r   NNro  NNNNN)N)N)NrD   r   r   NNF))r   r   r   r   r   r  r   r}   r  r  r  r  r  r  ry  r  r\  r  r   r*   r+   r,   r-   r.   r/   r0   r1   rV  r  r`  r  r  r  r3   r  r  r  r5   r  r  rf  rD   rD   r   rH   rK   D  sZ    F   2
'***)---	$

H rG!  
 c                    s>    fdd}j   \}}t|||jdg R  jS )z,Non-central moment of discrete distribution.c                    s   t | j| g R   S rO   )r\   r]   _pmfrx   ra   rQ   r   rD   rH   r    s    z_drv2_moment.<locals>.funrL  )r   _expectr0   inc)r   rQ   ra   r  rT  rU  rD   r  rH   _drv2_moment  s    r  c                 G   s  | j | \}}|}|}t|rhttd| d}||kr>d}ql| j|g|R  }||k rf|d7 }q0qlq0nd}t|rttd| d}||krd}q| j|g|R  }||kr|d8 }qqqn| j|g|R  }||kr|S ||kr|S ||d kr||kr|S |S t|| d }	| j|	g|R  }
|
|k rR||	krD|	}ntd	|
}q|
|krz||	krl|	}ntd	|
}q|	S qd S )
Nr]  
   rT   iir  r   rZ   zupdating stopped, endless loop)r   r   r-  r  r   r  r  )r   r   ra   rT  rU  r   r   ZqbZqar  ZqcrD   rD   rH   _drv2_ppfsingle  sX    






r  c                
       s  e Zd ZdZdeddddddddf
 fdd	Zdeddddddddf
 fdd		Zd
d Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Z fd d!Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd=d9d:Zd;d< Z  ZS )>rL   ai  A generic discrete random variable class meant for subclassing.

    `rv_discrete` is a base class to construct specific distribution classes
    and instances for discrete random variables. It can also be used
    to construct an arbitrary distribution defined by a list of support
    points and corresponding probabilities.

    Parameters
    ----------
    a : float, optional
        Lower bound of the support of the distribution, default: 0
    b : float, optional
        Upper bound of the support of the distribution, default: plus infinity
    moment_tol : float, optional
        The tolerance for the generic calculation of moments.
    values : tuple of two array_like, optional
        ``(xk, pk)`` where ``xk`` are integers and ``pk`` are the non-zero
        probabilities between 0 and 1 with ``sum(pk) = 1``. ``xk``
        and ``pk`` must have the same shape, and ``xk`` must be unique.
    inc : integer, optional
        Increment for the support of the distribution.
        Default is 1. (other values have not been tested)
    badvalue : float, optional
        The value in a result arrays that indicates a value that for which
        some argument restriction is violated, default is np.nan.
    name : str, optional
        The name of the instance. This string is used to construct the default
        example for distributions.
    longname : str, optional
        This string is used as part of the first line of the docstring returned
        when a subclass has no docstring of its own. Note: `longname` exists
        for backwards compatibility, do not use for new subclasses.
    shapes : str, optional
        The shape of the distribution. For example "m, n" for a distribution
        that takes two integers as the two shape arguments for all its methods
        If not provided, shape parameters will be inferred from
        the signatures of the private methods, ``_pmf`` and ``_cdf`` of
        the instance.
    seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
        singleton is used.
        If `seed` is an int, a new ``RandomState`` instance is used,
        seeded with `seed`.
        If `seed` is already a ``Generator`` or ``RandomState`` instance then
        that instance is used.

    Methods
    -------
    rvs
    pmf
    logpmf
    cdf
    logcdf
    sf
    logsf
    ppf
    isf
    moment
    stats
    entropy
    expect
    median
    mean
    std
    var
    interval
    __call__
    support

    Notes
    -----
    This class is similar to `rv_continuous`. Whether a shape parameter is
    valid is decided by an ``_argcheck`` method (which defaults to checking
    that its arguments are strictly positive.)
    The main differences are as follows.

    - The support of the distribution is a set of integers.
    - Instead of the probability density function, ``pdf`` (and the
      corresponding private ``_pdf``), this class defines the
      *probability mass function*, `pmf` (and the corresponding
      private ``_pmf``.)
    - There is no ``scale`` parameter.
    - The default implementations of methods (e.g. ``_cdf``) are not designed
      for distributions with support that is unbounded below (i.e.
      ``a=-np.inf``), so they must be overridden.

    To create a new discrete distribution, we would do the following:

    >>> from scipy.stats import rv_discrete
    >>> class poisson_gen(rv_discrete):
    ...     "Poisson distribution"
    ...     def _pmf(self, k, mu):
    ...         return exp(-mu) * mu**k / factorial(k)

    and create an instance::

    >>> poisson = poisson_gen(name="poisson")

    Note that above we defined the Poisson distribution in the standard form.
    Shifting the distribution can be done by providing the ``loc`` parameter
    to the methods of the instance. For example, ``poisson.pmf(x, mu, loc)``
    delegates the work to ``poisson._pmf(x-loc, mu)``.

    **Discrete distributions from a list of probabilities**

    Alternatively, you can construct an arbitrary discrete rv defined
    on a finite set of values ``xk`` with ``Prob{X=xk} = pk`` by using the
    ``values`` keyword argument to the `rv_discrete` constructor.

    **Deepcopying / Pickling**

    If a distribution or frozen distribution is deepcopied (pickled/unpickled,
    etc.), any underlying random number generator is deepcopied with it. An
    implication is that if a distribution relies on the singleton RandomState
    before copying, it will rely on a copy of that random state after copying,
    and ``np.random.seed`` will no longer control the state.

    Examples
    --------
    Custom made discrete distribution:

    >>> import numpy as np
    >>> from scipy import stats
    >>> xk = np.arange(7)
    >>> pk = (0.1, 0.2, 0.3, 0.1, 0.1, 0.0, 0.2)
    >>> custm = stats.rv_discrete(name='custm', values=(xk, pk))
    >>>
    >>> import matplotlib.pyplot as plt
    >>> fig, ax = plt.subplots(1, 1)
    >>> ax.plot(xk, custm.pmf(xk), 'ro', ms=12, mec='r')
    >>> ax.vlines(xk, 0, custm.pmf(xk), colors='r', lw=4)
    >>> plt.show()

    Random number generation:

    >>> R = custm.rvs(size=100)

    r   Nr  r   c                    s$   |d urt  tS t  | S d S rO   )r   __new__r,  )clsr   r   r   r8  
moment_tolvaluesr  r   r   r   r   rD   rH   r    s    zrv_discrete.__new__c                    s   t  |
 t|||||||||	|
d
| _|d u r6t}|| _|| _|| _|| _|| _	|	| _
|d urjtd| j| j| jgddd |   | || d S )N
r   r   r   r8  r  r  r  r   r   r   z.rv_discrete.__init__(..., values != None, ...)loc=0loc, 1rs  )r   r   r   r   r   r8  r   r   r  r  r   rp   r   r  r   r   _construct_docstrings)r   r   r   r   r8  r  r  r  r   r   r   r   rD   rH   r     s,    zrv_discrete.__init__c                    s(   | j   g d} fdd|D   S )N)r   r   r   r}  r'  r  c                    s   g | ]}  |d qS rO   rk  r~  r  rD   rH   rI     rJ   z,rv_discrete.__getstate__.<locals>.<listcomp>r  r  rD   r  rH   r    s    
zrv_discrete.__getstate__c                 C   s   t | jdd| _t | j| _|   t tdd}| jd |_t	
|| | _t tdd}| jd |_t	
|| | _| jd | j_dS )zAAttaches dynamically created methods to the rv_discrete instance.r*  r  rU   r   N)r   r  r}  r  r=  r   r  r   r  r   r   r  r  r'  )r   Z_vec_generic_momentZ_vppfrD   rD   rH   r     s    zrv_discrete._attach_methodsc                 C   s   |d u rd}|| _ |d u r8|d dv r,d}nd}|| }tjjdk r| jd u r`| j|tdd ntt}| 	t|
| j  | jd	d
| _d S )Nrr  r   rt  ru  rv  rU   r   rw  zE
    scale : array_like, optional
        scale parameter (default=1)r'   )r   rz  r{  r   r   r   rE   r   r   r   r	  r   )r   r   r   r|  r   rD   rD   rH   r    s(    
z!rv_discrete._construct_docstringsc                 C   sT   | j  }| j|d< | j|d< | j|d< | j|d< | j|d< | j|d< | j|d< |S )r  r   r   r8  r  r  r   r   )	r   r   r   r   r8  r  r  r   r   r  rD   rD   rH   r}     s    







zrv_discrete._updated_ctor_paramc                 G   s   t ||kS rO   )r   r   r   ra   rD   rD   rH   _nonzero  s    zrv_discrete._nonzeroc                 G   s(   | j |g|R  | j |d g|R   S )Nr   r$  r  rD   rD   rH   r    s    zrv_discrete._pmfc                 G   s   t | j|g|R  S rO   )r   r  r  rD   rD   rH   _logpmf  s    zrv_discrete._logpmfc                 G   s   | j |g|R  S rO   )r  r  rD   rD   rH   r\    s    zrv_discrete._logpxfc              
   C   sZ   z |d }d}t |d d }W n. tyN } ztd|W Y d }~n
d }~0 0 |||fS )Nr  r   r  r  r  rD   rD   rH   rV    s     zrv_discrete._unpack_loc_scalec                 G   s<   | j | \}}tt||d }tj| j|g|R  ddS )Nr   r   r[  )r   r   r-  r\   rw   r  )r   r   ra   rT  rU  r2  rD   rD   rH   r    s    zrv_discrete._cdf_singlec                 G   s   t |}| j|g|R  S rO   )r   r}  )r   rx   ra   r   rD   rD   rH   r     s    zrv_discrete._cdfc                    s   d|d< t  j|i |S )a]  Random variates of given type.

        Parameters
        ----------
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).
        loc : array_like, optional
            Location parameter (default=0).
        size : int or tuple of ints, optional
            Defining number of random variates (Default is 1). Note that `size`
            has to be given as keyword, not as positional argument.
        random_state : {None, int, `numpy.random.Generator`,
                        `numpy.random.RandomState`}, optional

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

        Returns
        -------
        rvs : ndarray or scalar
            Random variates of given `size`.

        Tr   )r   r)   r  r   rD   rH   r)   !  s    zrv_discrete.rvsc                 O   s  | j |i |\}}}tt||f\}}ttt|}| j| \}}t|| }| j| }||k||k@ }	t| ts|	| j|g|R  @ }	||	@ }
t	t
|
d}t|d| t| | j t|
rt|
g|f| R  }t||
t| j| dd |jdkr|d S |S )a  Probability mass function at k of the given RV.

        Parameters
        ----------
        k : array_like
            Quantiles.
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information)
        loc : array_like, optional
            Location parameter (default=0).

        Returns
        -------
        pmf : array_like
            Probability mass function evaluated at k

        r*  r   r   rD   )r   r6  r   r   r   r  rl   r,  r  r   r   r   r\   r  r8  r9  r   clipr  r  r   r   ra   r{   r   r   rT  rU  r>  r  r   r;  r<  rD   rD   rH   rB   A  s$    


zrv_discrete.pmfc                 O   s  | j |i |\}}}tt||f\}}ttt|}| j| \}}t|| }| j| }||k||k@ }	t| ts|	| j|g|R  @ }	||	@ }
t	t
|
d}|t  t|d| t| | j t|
rt|
g|f| R  }t||
| j|  |jdkr|d S |S )a  Log of the probability mass function at k of the given RV.

        Parameters
        ----------
        k : array_like
            Quantiles.
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).
        loc : array_like, optional
            Location parameter. Default is 0.

        Returns
        -------
        logpmf : array_like
            Log of the probability mass function evaluated at k.

        r*  r   r   rD   )r   r6  r   r   r   r  rl   r,  r  r    r   r  r   r   r\   r  r8  r9  r   r  r  r  rD   rD   rH   rC   g  s&    


zrv_discrete.logpmfc                 O   s6  | j |i |\}}}tt||f\}}ttt|}| j| \}}t|| }| j| }||k||k @ }	||k}
t|}||	@ t|@ }t	t
|d}t||
||k d t||||k d t|d| t| | j t|rt|g|f| R  }t||t| j| dd |jdkr2|d S |S )a  Cumulative distribution function of the given RV.

        Parameters
        ----------
        k : array_like, int
            Quantiles.
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).
        loc : array_like, optional
            Location parameter (default=0).

        Returns
        -------
        cdf : ndarray
            Cumulative distribution function evaluated at `k`.

        r*  rT   r  r   r   rD   )r   r6  r   r   r   r  r\   isneginfrt   r   r   r   r  r8  r9  r   r  r   r  )r   r   ra   r{   r   r   rT  rU  r>  r  r  r  r   r;  r<  rD   rD   rH   r,     s(    

zrv_discrete.cdfc                 O   s  | j |i |\}}}tt||f\}}ttt|}| j| \}}t|| }| j| }||k||k @ }	||k}
||	@ }tt|d}|t	  t
|d| t| | j t
||
||k d t|rt|g|f| R  }t
||| j|  |jdkr
|d S |S )a$  Log of the cumulative distribution function at k of the given RV.

        Parameters
        ----------
        k : array_like, int
            Quantiles.
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).
        loc : array_like, optional
            Location parameter (default=0).

        Returns
        -------
        logcdf : array_like
            Log of the cumulative distribution function evaluated at k.

        r*  r   r  r   rD   )r   r6  r   r   r   r  r    r   r  r   r   r\   r  r8  r9  r   r"  r  r   r   ra   r{   r   r   rT  rU  r>  r  r  r   r;  r<  rD   rD   rH   r-     s&    

zrv_discrete.logcdfc                 O   s  | j |i |\}}}tt||f\}}ttt|}| j| \}}t|| }| j| }||k||k @ }	||k t|B |@ }
||	@ t|@ }t	t
|d}t|d| t| | j t||
d t|rt|g|f| R  }t||t| j| dd |jdkr|d S |S )a  Survival function (1 - `cdf`) at k of the given RV.

        Parameters
        ----------
        k : array_like
            Quantiles.
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).
        loc : array_like, optional
            Location parameter (default=0).

        Returns
        -------
        sf : array_like
            Survival function evaluated at k.

        r*  r   rT   r   rD   )r   r6  r   r   r   r  r\   r  rt   r   r   r   r  r8  r9  r   r  r%  r  r  rD   rD   rH   r.     s$    
zrv_discrete.sfc                 O   s
  | j |i |\}}}tt||f\}}ttt|}| j| \}}t|| }| j| }||k||k @ }	||k |@ }
||	@ }tt|d}|t	  t
|d| t| | j t
||
d t|rt|g|f| R  }t
||| j|  |jdkr|d S |S )a_  Log of the survival function of the given RV.

        Returns the log of the "survival function," defined as 1 - `cdf`,
        evaluated at `k`.

        Parameters
        ----------
        k : array_like
            Quantiles.
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).
        loc : array_like, optional
            Location parameter (default=0).

        Returns
        -------
        logsf : ndarray
            Log of the survival function evaluated at `k`.

        r*  r   r  r   rD   )r   r6  r   r   r   r  r    r   r  r   r   r\   r  r8  r9  r   r&  r  r  rD   rD   rH   r/     s&    

zrv_discrete.logsfc                 O   s,  | j |i |\}}}tt||f\}}ttt|}| j| \}}| j| ||k@ }|dk|dk @ }	|dk|@ }
||	@ }tjt|| j	dd}t
||dk||k |d |  t
||
||  t|rt|g|f| |f R  }|d |dd  }}t
||| j| |  |jdkr(|d S |S )a"  Percent point function (inverse of `cdf`) at q of the given RV.

        Parameters
        ----------
        q : array_like
            Lower tail probability.
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).
        loc : array_like, optional
            Location parameter (default=0).

        Returns
        -------
        k : array_like
            Quantile corresponding to the lower tail probability, q.

        r   r   r*  r1  rD  r  NrD   )r   r6  r   r   r   r  r\   r7  r   r8  r   r9  r   r  r  )r   r   ra   r{   r   r   rT  rU  r>  r  r  r   r;  r<  rD   rD   rH   r0   0  s$     zrv_discrete.ppfc                 O   sD  | j |i |\}}}tt||f\}}ttt|}| j| \}}| j| ||k@ }|dk|dk @ }	|dk|@ }
|dk|@ }||	@ }tjt|| j	dd}|d | }|| }t
||
||k | t
||||k | t|r,t|g|f| |f R  }|d |dd  }}t
||| j| |  |jdkr@|d S |S )a+  Inverse survival function (inverse of `sf`) at q of the given RV.

        Parameters
        ----------
        q : array_like
            Upper tail probability.
        arg1, arg2, arg3,... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).
        loc : array_like, optional
            Location parameter (default=0).

        Returns
        -------
        k : ndarray or scalar
            Quantile corresponding to the upper tail probability, q.

        r   r   r*  r  r  NrD   )r   r6  r   r   r   r  r\   r7  r   r8  r   r9  r   r)  r  )r   r   ra   r{   r   r   rT  rU  r>  r  r  r  r   r;  r  r  r<  rD   rD   rH   r1   X  s*    zrv_discrete.isfc                    sR   t drtjS j  \}}t fdd||jdg R  jS d S )Npkc                    s   t j| g R  S rO   )r
   rB   r  r  rD   rH   <lambda>  rJ   z&rv_discrete._entropy.<locals>.<lambda>rL  )r   r   r2   r   r   r  r0   r  )r   ra   rT  rU  rD   r  rH   r    s    
zrv_discrete._entropyrD   F  r      c
              	      s   du r fdd}
n fdd}
j   \}}|du rH|}n| }|du r^|}n| }|rj|d g R  j|g R   }nd}ttr|
||}|| S jdg R  }t|
|||j|||	}|| S )a)  
        Calculate expected value of a function with respect to the distribution
        for discrete distribution by numerical summation.

        Parameters
        ----------
        func : callable, optional
            Function for which the expectation value is calculated.
            Takes only one argument.
            The default is the identity mapping f(k) = k.
        args : tuple, optional
            Shape parameters of the distribution.
        loc : float, optional
            Location parameter.
            Default is 0.
        lb, ub : int, optional
            Lower and upper bound for the summation, default is set to the
            support of the distribution, inclusive (``lb <= k <= ub``).
        conditional : bool, optional
            If true then the expectation is corrected by the conditional
            probability of the summation interval. The return value is the
            expectation of the function, `func`, conditional on being in
            the given interval (k such that ``lb <= k <= ub``).
            Default is False.
        maxcount : int, optional
            Maximal number of terms to evaluate (to avoid an endless loop for
            an infinite sum). Default is 1000.
        tolerance : float, optional
            Absolute tolerance for the summation. Default is 1e-10.
        chunksize : int, optional
            Iterate over the support of a distributions in chunks of this size.
            Default is 32.

        Returns
        -------
        expect : float
            Expected value.

        Notes
        -----
        For heavy-tailed distributions, the expected value may or
        may not exist,
        depending on the function, `func`. If it does exist, but the
        sum converges
        slowly, the accuracy of the result may be rather low. For instance, for
        ``zipf(4)``, accuracy for mean, variance in example is only 1e-5.
        increasing `maxcount` and/or `chunksize` may improve the result,
        but may also make zipf very slow.

        The function is not vectorized.

        Nc                    s   |  j | g R   S rO   r  r  )ra   r   r   rD   rH   r    s    zrv_discrete.expect.<locals>.func                    s   |  j | g R   S rO   r  r  ra   r   r   r   rD   rH   r    s    r   rT   rL  )r   r.   rl   r,  r  r0   r  )r   r   ra   r   r   r   r   maxcount	tolerance	chunksizer  rT  rU  r  rP  r  rD   r  rH   r5     s&    6*
zrv_discrete.expectc                 C   s.   |   }tddtj tjfd}||g }|S )Nr   Tr  r  )r   r  r  r  rD   rD   rH   r    s    
zrv_discrete._param_info)	NrD   r   NNFr  r  r  )r   r   r   r   r   r  r   r  r   r  r}   r  r  r  r\  rV  r  r   r)   rB   rC   r,   r-   r.   r/   r0   r1   r  r5   r  rf  rD   rD   r   rH   rL     sF    	 &'*(&*(0  
Yr  r  r  c                 C   s<  || |kr0t ||d |}| |}	t |	S ||k r<|}||krH|}d\}
}t||d ||dD ]Z}|
|j7 }
t | |}||7 }t|||j k r q|
|krdtjdtdd |  S qdt|d |d || dD ]\}|
|j7 }
t | |}||7 }t|||j k r q8|
|krtjdtdd  q8q|S )z4Helper for computing the expectation value of `fun`.r   )r   r  )r  r  zexpect(): sum did not convergerV   )
stacklevel)	r\   r   rw   _iter_chunkedru   r  warningswarnRuntimeWarning)r  r   r   r  r  r  r  r  suppr   countZtotrx   deltarD   rD   rH   r    s@    



r  rX   c           
      c   s   |dkrt d|dkr$t d| |dkr0dnd}t|| }| }|| | dk rt|t|| }|| }t||| |}	||7 }|	V  qDdS )a  Iterate from x0 to x1 in chunks of chunksize and steps inc.

    x0 must be finite, x1 need not be. In the latter case, the iterator is
    infinite.
    Handles both x0 < x1 and x0 > x1. In the latter case, iterates downwards
    (make sure to set inc < 0.)

    >>> from scipy.stats._distn_infrastructure import _iter_chunked
    >>> [x for x in _iter_chunked(2, 5, inc=2)]
    [array([2, 4])]
    >>> [x for x in _iter_chunked(2, 11, inc=2)]
    [array([2, 4, 6, 8]), array([10])]
    >>> [x for x in _iter_chunked(2, -5, inc=-2)]
    [array([ 2,  0, -2, -4])]
    >>> [x for x in _iter_chunked(2, -9, inc=-2)]
    [array([ 2,  0, -2, -4]), array([-6, -8])]

    r   zCannot increment by zero.z$Chunk size must be positive; got %s.r   r  N)rp   r  r  r\   r   )
r  r  r  r  rN   Zstepsizerx   r  stepr  rD   rD   rH   r
    s    r
  c                
       s   e Zd ZdZdeddddddddf
 fdd	Zdd	 Zd
d Zdd Zdd Z	dd Z
dd ZdddZdd Zdd Zdd Z  ZS )r,  zA 'sample' discrete distribution defined by the support and values.

    The ctor ignores most of the arguments, only needs the `values` argument.
    r   Nr  r   c                    s|  t t| |
 |d u r tdt|||||||||	|
d
| _|d u rJt}|| _|| _|| _	|	| _
| j| _|\}}t|t|krtdt|d rtdtt|dstdttt|t|kstdtt|}tt||d	| _tt||d	| _| jd	 | _| jd
 | _tj| jd	d| _d| _
| j| j gddd | !  | "|| d S )Nz(rv_sample.__init__(..., values=None,...)r  z#xk and pk must have the same shape.r  z(All elements of pk must be non-negative.r   z The sum of provided pk is not 1.z$xk may not contain duplicate values.r   r  r[  r   r  r  rs  )#r   rL   r   rp   r   r   r   r8  r  r  r   r  r=  r\   r   lessr9  Zallcloserw   r   setrf   ru   ZargsortZtakexkr   r   r   Zcumsumqvalsr   r  r   r  )r   r   r   r   r8  r  r  r  r   r   r   r  r   indxr   rD   rH   r   E  sJ    
zrv_sample.__init__c                    s(   | j   g d} fdd|D   S )Nr   c                    s   g | ]}  |d qS rO   rk  r~  r  rD   rH   rI     rJ   z*rv_sample.__getstate__.<locals>.<listcomp>r  r  rD   r  rH   r  z  s    
zrv_sample.__getstate__c                 C   s   |    dS )z/Attaches dynamically created argparser methods.N)r   r   rD   rD   rH   r     s    zrv_sample._attach_methodsc                 G   s   | j | jfS )a  Return the support of the (unscaled, unshifted) distribution.

        Parameters
        ----------
        arg1, arg2, ... : array_like
            The shape parameter(s) for the distribution (see docstring of the
            instance object for more information).

        Returns
        -------
        a, b : numeric (float, or int or +/-np.inf)
            end-points of the distribution's support.
        r  )r   ra   rD   rD   rH   r     s    zrv_sample._get_supportc                    s.   t  fdd| jD  fdd| jD dS )Nc                    s   g | ]} |kqS rD   rD   )rF   r   r  rD   rH   rI     rJ   z"rv_sample._pmf.<locals>.<listcomp>c                    s   g | ]}t | d  qS )r   )r\   r   )rF   r  r  rD   rH   rI     rJ   r   )r\   selectr  r   r   rD   r  rH   r    s    zrv_sample._pmfc                 C   s>   t |d d d f | j\}}t j||kddd }| j| S )Nr  r[  r   )r\   r   r  r   r  )r   rx   xxZxxkr  rD   rD   rH   r     s    zrv_sample._cdfc                 C   s0   t |d | j\}}t||kdd}| j| S )N).Nr  r[  )r\   r   r  r   r  )r   r   ZqqZsqqr  rD   rD   rH   r    s    zrv_sample._ppfc                 C   s@   |j |d}|d u r2tj|dd}| |d }n
| |}|S )Nr  r   )Zndminr   )r  r\   r  r  )r   ru   r   r  r  rD   rD   rH   r    s    
zrv_sample._rvsc                 C   s   t | jS rO   )r   r2   r   r   rD   rD   rH   r    s    zrv_sample._entropyc                 C   s,   t |}tj| j|tjdf  | j ddS )N.r   r[  )r   r\   rw   r  r  r   )r   rQ   rD   rD   rH   r    s    zrv_sample.generic_momentc                 O   s,   | j || j k| j |k@  }||}t|S rO   )r  r\   rw   )r   r  r   r   ra   r{   r  r   rD   rD   rH   r    s    zrv_sample._expect)NN)r   r   r   r   r   r   r  r   r   r  r   r  r  r  r  r  rf  rD   rD   r   rH   r,  ?  s   5

r,  c                 C   s   g }g }t | ddd |ddd ddD ]H\}}||ksR||  krNdkrhn n|| |d q*|d q*t|ddd t|ddd fS )a  
    This is a utility function used by `_rvs()` in the class geninvgauss_gen.
    It compares the tuple argshape to the tuple size.

    Parameters
    ----------
    argshape : tuple of integers
        Shape of the arguments.
    size : tuple of integers or integer
        Size argument of rvs().

    Returns
    -------
    The function returns two tuples, scalar_shape and bc.

    scalar_shape : tuple
        Shape to which the 1-d array of random variates returned by
        _rvs_scalar() is converted when it is copied into the
        output array of _rvs().

    bc : tuple of booleans
        bc is an tuple the same length as size. bc[j] is True if the data
        associated with that index is generated in one call of _rvs_scalar().

    Nr  r   )	fillvalueTF)r   r   r   )Zargshaperu   Zscalar_shapebcZargdimZsizedimrD   rD   rH   _check_shape  s     
r  c                 C   s\   g }g }| D ]F\}}| dr q|dr>t||r>|| t||r|| q||fS )aw  Collect names of statistical distributions and their generators.

    Parameters
    ----------
    namespace_pairs : sequence
        A snapshot of (name, value) pairs in the namespace of a module.
    rv_base_class : class
        The base class of random variable generator classes in a module.

    Returns
    -------
    distn_names : list of strings
        Names of the statistical distributions.
    distn_gen_names : list of strings
        Names of the generators of the statistical distributions.
        Note that these are not simply the names of the statistical
        distributions, with a _gen suffix added.

    r   Z_gen)rM   endswith
issubclassr   rl   )Znamespace_pairsZrv_base_classZdistn_namesZdistn_gen_namesr   valuerD   rD   rH   get_distribution_names  s    


r  )N)r  r  r  )rX   r   )wZscipy._lib._utilr   r   rz  r   r   r   r  	itertoolsr   Z
scipy._libr   Z_distr_paramsr   r   r   Zscipy.specialr	   r
   Zscipyr   r   Zscipy._lib._finite_differencesr   r   numpyr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r\   
_constantsr!   r"   Z_censored_datar#   Zscipy.stats._warnings_errorsr$   r   Z_doc_rvsZ_doc_pdfZ_doc_logpdfZ_doc_pmfZ_doc_logpmfZ_doc_cdfZ_doc_logcdfZ_doc_sfZ
_doc_logsfZ_doc_ppfZ_doc_isfZ_doc_momentZ
_doc_statsZ_doc_entropyZ_doc_fitZ_doc_expectZ_doc_expect_discreteZ_doc_medianZ	_doc_meanZ_doc_varZ_doc_stdZ_doc_intervalr   Z_doc_allmethodsZ_doc_default_longsummaryZ_doc_default_frozen_noteZ_doc_default_exampleZ_doc_default_locscaleZ_doc_defaultZ_doc_default_before_notesr   r   rE   Z_doc_disc_methodsrG   r   Z_doc_disc_methods_err_varnamer+  Z_doc_default_discrete_exampleZ_doc_default_discrete_locscaleZ_doc_default_discdirr   rS   re   rh   ri   rs   ry   rz   r   r   r   r   r   rg  rn  rK   r  r  rL   r  r
  r,  r  r  rD   rD   rD   rH   <module>   s^  P0


,


 	U		8       .          }	?     v  
+
$ &