L iSddlmZddlZddlZddlZddlZddlZddlm Z ddl m Z ddl m Z mZddlmZddlmcmZddlmZmZdd lmZdd lmZdd lmZdd lmZdd lmZmZm 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/ddlZ0ddl1m2Z2m3Z3ddl4m5Z5ddl6m7Z7ddddZ8dZ9dZ:dZ;dZdZ?dZ@dZAdZBdZCd ZDd!ZEd"ZFd#ZGd$ZHd%ZId&ZJd'ZKd(ZLd)ZMd*ZNd+je8d,e9e:e;e>e?e@eAeBeCeDeEeFeGeHeJeKeLeMeNgZPd-ZQd.ZRd/ZSd0ZTd+jeQePd1eSgZUd+jeQePgZVid2e9d3e:d4e;d5e>d6e?d7e@d8eAd9eBd:eCd;eEdeDd?eHd@eNdAeKdBeMeLeJePeQeReSeUeVeTdC ZWeWjZYe`__ 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. aWExamples -------- >>> import numpy as np >>> from scipy.stats import %(name)s >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 1) Get the support: %(set_vals_stmt)s >>> lb, ub = %(name)s.support(%(shapes)s) Calculate the first four moments: >>> 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() aThe 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.  rvspdflogpdfcdflogcdfsflogsfppfisfrentropyfitmomentexpectintervalmeanstd) varmedian allmethods longsummary frozennoteexampledefault before_notes after_notespmflogpmf)r+rDrEr.r/r0r1r2r3rr4r7r<r9r;r:r8z , scale=1)r.r/r0r1z(x, z(k, 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?aExamples -------- >>> import numpy as np >>> from scipy.stats import %(name)s >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 1) Get the support: %(set_vals_stmt)s >>> lb, ub = %(name)s.support(%(shapes)s) Calculate the first four moments: >>> 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@rCrBrA_doc_zdel cR||j}||z |zjSN)r9)datanmus g/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/stats/_distn_infrastructure.py_momentrOts) z YY[ BYN ""c|dk(ry|dk(r| |dg|}|S|}|S|dk(r|| |dg|}|S|||zz}|S|dk(r@||| |dg|}|S|tj|dz}|d|z|zz||z|zz}|S|dk(r\|||| |dg|}|S|dz|d zz} |tj|dz}| d|z|zzd |z|z|zz||z|z|zz}|S||g|}|S) Nr?r?@@)nppower) rLrMmu2g1g2 moment_funcargsvalmu3mu4s rN_moment_from_statsrdzs Q q& :a'$'C0 J-C, J+ q& ;"*a'$'C& J#2+C" J! q& : a'$'C JrxxS))Cad3h,r"uRx'C J q& :s{bja'$'C J c6CH%CRXXc3''Cad3h,qtBws{*2b58B;6C J!#d# JrPctj|}|j}||z dzj}||z dzj}|tj|dz S)z8 skew is third central moment / variance**(1.5) rSrTrU)rZravelr9r[)rKrMm2m3s rN_skewris^ 88D>D B "9q.   B "9q.   B S! !!rPctj|}|j}||z dzj}||z dzj}||dzz dz S)zDFisher's excess kurtosis is fourth central moment / variance**2 - 3.rSrVrT)rZrfr9)rKrMrgm4s rN _kurtosisrlsX 88D>D B "9q.   B "9q.   B A:>rPcfd}|S)z?Decorator that vectorizes _rvs method to work on ndarray shapesc t|dj|\}}tj|}tj|}tj|}tj|r  g|||Stj |}tj |j}tj||||f}tj|||}tj||D]5} g|D cgc]} tj| |c} ||||<7tj|||Scc} wNr) _check_shaperrZarrayallr!rndimhstackmoveaxisndindexsqueeze) size random_stater` _rvs1_size _rvs1_indicesoutj0j1iarg_rvs1s rN_rvsz(_vectorize_rvs_over_shapes.._rvss4$0a$E! Mxx~XXj) / 66- 3$33l3 3hhtn YYsxx  YYM>*B},=> ?kk#r2&T=.12 5A54@CRZZ_Q/@5%5'35CF 5 {{3B''AsE )rrs` rN_vectorize_rvs_over_shapesrs(4 KrPct|s@t|tr0|jdsd|z}|dk(rd} t t |}|S|S#t $r}t|d|d}~wwxYw)Nfmin_fminz is not a valid optimizer)callable isinstancestr startswithgetattrr AttributeError ValueError) optimizeres rN_fit_determine_optimizerrs I :i#=##G, )I  I M)4I 9 M {*CDE1 L MsA A+A&&A+c2|tj|k(SrJ)rZround)xs rN _isintegralrs  rPctj|}|jtj|z }tj|||fS)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 )rZisfiniterx count_nonzerosum)rfinite_x bad_counts rN _sum_finitersB${{1~H  0 0 ::I 66!H+  ))rPceZdZdZedZej dZdZdZdZ dZ dd Z d Z d Z dd Zd ZdZdZdZddZdZddZddZdZy) rv_frozenc||_||_|jdi|j|_|jj |i|\}}}|jj |\|_|_y)Nr) r`kwds __class___updated_ctor_paramdist _parse_args _get_supportab)selfrr`rshapes_s rN__init__zrv_frozen.__init__so  #DNN@T%=%=%?@ ,tyy,,d;d; 1///8rPc.|jjSrJ)r _random_staters rNryzrv_frozen.random_statesyy&&&rPc8t||j_yrJ)r rrrseeds rNryzrv_frozen.random_state s"4T": rPcj|jj|g|ji|jSrJ)rr.r`rrrs rNr.z rv_frozen.cdf)tyy}}Q88dii88rPcj|jj|g|ji|jSrJ)rr/r`rrs rNr/zrv_frozen.logcdf+tyy;DII;;;rPcj|jj|g|ji|jSrJ)rr2r`rrqs rNr2z rv_frozen.ppfrrPcj|jj|g|ji|jSrJ)rr3r`rrs rNr3z rv_frozen.isfrrPNc|jj}|j||d|jj|j i|S)Nrxry)rcopyupdaterr+r`)rrxryrs rNr+z rv_frozen.rvssAyy~~ T<@Atyy}}dii0400rPcj|jj|g|ji|jSrJ)rr0r`rrs rNr0z rv_frozen.sfs)tyy||A7 7TYY77rPcj|jj|g|ji|jSrJ)rr1r`rrs rNr1zrv_frozen.logsf"s)tyyq:499: ::rPc|jj}|jd|i|jj|j i|SNmoments)rrrrrr`)rrrs rNrzrv_frozen.stats%sAyy~~ Y()tyy 2T22rPcb|jj|ji|jSrJ)rr<r`rrs rNr<zrv_frozen.median*s&tyy8dii88rPcb|jj|ji|jSrJ)rr9r`rrs rNr9zrv_frozen.mean-s$tyy~~tyy6DII66rPcb|jj|ji|jSrJ)rr;r`rrs rNr;z rv_frozen.var0$tyy}}dii549955rPcb|jj|ji|jSrJ)rr:r`rrs rNr:z rv_frozen.std3rrPcj|jj|g|ji|jSrJ)rr6r`r)rorders rNr6zrv_frozen.moment6s+tyy? ?TYY??rPcb|jj|ji|jSrJ)rr4r`rrs rNr4zrv_frozen.entropy9& tyy  $))9tyy99rPcj|jj|g|ji|jSrJ)rr8r`r)r confidences rNr8zrv_frozen.interval<s+!tyy!!*FtyyFDIIFFrPc (|jj|ji|j\}}}t |jt r"|jj ||||||fi|S|jj |||||||fi|SrJ)rrr`rrrGr7) rfunclbub conditionalrrlocscales rNr7zrv_frozen.expect?s . --tyyFDIIF 3 dii -#499##D!S"b+NN N#499##D!S%R$/9379 9rPcb|jj|ji|jSrJ)rsupportr`rrs rNrzrv_frozen.supportKrrPNN)mvrJ)NNNF)__name__ __module__ __qualname__rpropertyrysetterr.r/r2r3r+r0r1rr<r9r;r:r6r4r8r7rrrPrNrrs9'';;9<991 8;3 9766@:G 9:rPrceZdZdZdZy)rv_discrete_frozencj|jj|g|ji|jSrJ)rrDr`rrks rNrDzrv_discrete_frozen.pmfQrrPcj|jj|g|ji|jSrJ)rrEr`rrs rNrEzrv_discrete_frozen.logpmfTrrPN)rrrrDrErrPrNrrO 9 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,) r) rZ atleast_1drlisttuplerrbroadcast_arraysrfrrxextract broadcast_to)condr`newargsrss rN argsreducerasHmmT"G gu .* vvd|,,z,rv_generic._construct_doc..GsAcCy\Asc3"K|]}| ywrJrr:s rNr<z,rv_generic._construct_doc..Is=#uX=s valsshapes_rrz>>> z = set_vals_stmt)rArBz- %(shapes)s : array_like shape parametersrSz %(shapes)s, z0Unable to construct docstring for distribution "z": z(, (z, ))) rrrr)rrrrange__doc__r docformat Exceptionrepr)rdocdict shapes_valstempdictr>r3rrs rN_construct_doczrv_generic._construct_doc>s<<>992 ![[.B  K >99A[AAD "kk/R ;;4<<1, Y 3 &  ;;*.t{{m3tf(EH_ %(*H_ % ;; 3 K!)$!7!7Er"K Kq SA{{"#||33NBG  S%// hG  S||++E37??sK ; >99===D >0 S!226))Da !KLQRS Ss)E;"%F#;!F F # G,%GGc||d}dj|d|ddtddg|_|j|y) z7Construct instance docstring from the default template.NAr)rz random variable.z %(before_notes)s r'z %(example)s)r) docheadersrDrK)rlongnamerHdiscretes rN_construct_default_docz!rv_generic._construct_default_docgsQ  Hww8*AhZ7H I 8*W:M / 12  G$rPc^t|trt|g|i|St|g|i|S)aFreeze 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. )rrFrrrr`rs rNfreezezrv_generic.freezeqs8 dM *'s rN_munpzrv_generic._munps? [[X & 1&4&&q040D 1  1 s5?c |jdd}tj|}d}|Dcgc] }|| }}|dj}|dj}||} nt tj |} |t| z } | dkr d| z|z}n | dkDrd| z| z} tt|| D cgc]\} } | dk(xs| | k(c} } } | std|d| d||dd}|d}|d }|||| fScc}wcc} } w) Nrxc|jdkDr9|jddk(r'|d}|jdkDr|jddk(r'|Sr)rsr)rs rN squeeze_leftz.rv_generic._argcheck_rvs..squeeze_leftsD&&1*qaD&&1*qHrPr)rrz;size does not match the broadcast shape of the parameters. r) getrZrrrsrrr-rrzipr)rr`kwargsrx all_bcastr`r bcast_shape bcast_ndimsize_ndiffbcdimszdimok param_bcast loc_bcast scale_bcasts rN _argcheck_rvszrv_generic._argcheck_rvssazz&$'''.   /88\!_8 8l(( q\&& <E"---.ESZ' 19-+5K QYJ&E (+K(?A$ue1*..AB004vRwb OP P n bM m I{E99O9:As D<D cHd}|D]}t|t|dkD}|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. rr)rr)rr`rrs rN _argcheckzrv_generic._argchecks2 9CtgclQ&68D 9 rPc2|j|jfS)aReturn 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. rr)rr`res rNrzrv_generic._get_supports(vvtvv~rPc|j|\}}tjd5||k||kzcdddS#1swYyxYwNrZinvalidrrZr[rrr`rrs rN _support_maskzrv_generic._support_masksI t  $'1 [[ * 'FqAv& ' ' ' >Ac|j|\}}tjd5||k||kzcdddS#1swYyxYwrwrzr{s rN_open_support_maskzrv_generic._open_support_mask sI t  $'1 [[ * %Ea!e$ % % %r}rcP|j|}|j|g|}|S)Nrx)uniform_ppf)rrxryr`UYs rNrzrv_generic._rvss1  d + DIIa $ rPctjd5t|j|g|cdddS#1swYyxYwNrZdivide)rZr[r_cdfrrr`s rN_logcdfzrv_generic._logcdf; [[ ) ,ytyy*T*+ , , , =Ac.d|j|g|z SNrRrrs rN_sfzrv_generic._sfs9499Q&&&&rPctjd5t|j|g|cdddS#1swYyxYwr)rZr[rrrs rN_logsfzrv_generic._logsf s; [[ ) +xtxx)D)* + + +rc(|j|g|SrJ)_ppfvecrrr`s rNrzrv_generic._ppf$t||A%%%rPc.|jd|z g|Sr)rrs rN_isfzrv_generic._isf'styyQ&&&rPc||jdd}|jdd}|j|i|\}}}}t|j||dk\}t j |sd|j d} t| t j |dk(r|t|dzS||j} t|} n |j} |j||| d} | |z|z} | |_ |rAt|ts1|d k(r t| } | S| jtj } | S) aVRandom 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`. rPNryrzDomain 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.drr)popr rrsrZrrrrrrr rr rv_sampleintastypeint64) rr`rrPrndmrrrxrmessagerandom_state_savedryr>s rNr+zrv_generic.rvs,sN<88J-xx-!5!5!5t!Dt!Dc5$>4>>405A:?vvd|67;ii[A44G W% % 66%1* tD#& &  !%!3!3 -d3L--Ltyy$T Ee|c!  !3D  JtY7rz4y {{288, rPc |j|i|\}}}}tt||f\}}ttt|}|j||dkDz||k(z}g}t j t||j}t j|rt|g|||fz} | d| d| dd} }}|jr|j| id|i\} } } } n|j| \} } } } d|vrI| |jdg| } |j}t||| |z|z|j!|d |vr| |jd g| }| |jdg| } t j"d 5t j$t j&| || d zz t j(} ddd|j}t||| |z|z|j!|d |vr| |jdg| }| |jdg| } | :|jd g| }t j"d 5|| | zz } dddt j"d 5| | zd| zz | z|z}|t j*| dz } ddd|j}t||| |j!|d|vr\|  |jdg| }| |jdg| } | :|jd g| }t j"d 5|| | zz } ddd| d}n| t j*| dz}|D|jdg| }t j"d 5| | zd| zz | z|z}dddt j"d 5| d z d| zz | zd|zz | z|z}|| dzz dz } ddd|j}t||| |j!|n|Dcgc]}|j}}|Dcgc]}|d }}t-|dk(r|dSt|S#1swYxYw#1swY xYw#1swYxYw#1swYVxYw#1swYxYw#1swYxYwcc}wcc}w)aSome 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_valuerarbNrmrvrSrZrxrrTrUrrVrYrXrWr)r maprrrsrZfullrbadvalueanyrrrr]rrr&r[wherer rr[r-)rr`rrrrroutputrAgoodargsrMr\r]r^out0mu2pmu3prbmu4prcrr|s rNrzrv_generic.statsqs4%;D$:$:D$ID$I!c5'3,/ US$'(t~~t$ 2cSjA''%+$--@ 66$<!$=$s|*;=H#+B<"x}3E&&"-$++x#F1:G0D#FCR#.$++x"8CRg~:#A11B||~dD"u*s"23 d#g~;%4::a3(3Dz'TZZ5H5X6L hh }dRUlBFFKL||~dD#+"56 d#g~:%4::a3(3Dz'TZZ5H5{)tzz!7h7[[:1"&b.C1X66 "s2v#~r1D8 288C#556||~dD"% d#g~:%4::a3(3Dz'TZZ5H5{)tzz!7h7[[:1"&b.C1z"!288C#55{)tzz!7h7[[:C$&38a#g#5";d"BCCX62!#Q3"4qu>> 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 rrrNr) rrrrrsrrrrr vecentropyr) rr`rrrcond0rr goodscales rNr4zrv_generic.entropys0,4++T:T:c53,/ US$'(%3sczBuU|S) fqw/eU2T2QK AB< fe_T__h7#i.HIbzrPc |}|j|i|\}}}tjg|||}|^}}}tj|j||dkD}tj||dk(} tj||dk7} t |g|||}|^}}}t ||k7r td|dkr tdd\} } } }|dkDr7|dkr2|jr dddd d d |i}ni}|j|i|\} } } }tj|j}t|| | | ||j||d <t|j}t|||j | j#r!||dk(|z||dk(z}t|| || j#r | | | |g}|Dcgc]}|| }}t%d Dcgc] }|| | }}t#|r%t |dk7g|}d}|D]}||||<|dz }|\} } } }t |dk7g||||}|^}}}}t|jd}||z }t%|D]7}t|| | | ||j|}|t'||d||zz|zz }9|||z|zz }|||zz}t|| ||dScc}wcc}w)anon-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) rzMoment must be an integer.zMoment must be positive.rXrrrvsmvsk)rrSrTrV.rVrrdtypeT)exactr)rrZrrrsrrrrrr!rrdr]rrrrrCr )rrr`rrLrrri0i1i2rMr\r]r^mdictraresultres1momrarrsidxjres2facrvalks rNr6zrv_generic.momentsE -T--t.log_psf@sIIat4EAr./ffytyy*T*"HFFq8B</14nnqc8aS%9:^^R!I.nnqc8_5rwws|b011 1rP)rrsrrZsortr)rrrrrr`rs` rN_penalized_nlpsfzrv_generic._penalized_nlpsf5sh  11%8UDt~~t$ J WWQZ# u $ 2%%aw77rPrJ)NN continuous)-rrrrDrrryrrrrr6rKrQrTrVrr]rqrsrr|rrrrrrrr+rr4r6r<r9r;r:r8rrrrrr __classcell__rs@rNrrs 6 " "66 " BO'b'LR/36B%;(*~~H &  E:T ,' % $$ ,'+&' CJo!b#JKZ,422.,\!F2 7 & K8rPrcHeZdZdej ejfdfdZy) _ShapeInfoF)TTc~||_||_||_||_t |}t j |dr/|ds*t j|dt j|d<t j |dr0|ds+t j|dt j |d<||_ yr) r integrality endpoints inclusiverrZr nextafterrdomain)rrrr rs rNrz_ShapeInfo.__init__Ps &"f ;;vay !)A, VAY7F1I ;;vay !)A, VAY8F1I rPN)rrrrZrrrrPrNrrOs).7H' rPrc|Dcgc]}||vs||j|f}}t|dkDr1|Dcgc]\}}| }}}tddj|z|r|ddSdScc}wcc}}w)a' Given names such as ``['f0', 'fa', 'fix_a']``, check that there is at most one non-None value in `kwds` associated 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. rzOfit method got multiple keyword arguments to specify the same fixed parameter: rrN)rr-rr))rnamesrr>rarepeateds rN_get_fixed_fit_valuer_s05 Et T488D> " ED E 4y1}*./YT3D//>8,-. .471:'4' F/s A1A1 A6ceZdZdZ d+fd ZdZdZdZdZdZ d Z d Z d Z d Z d ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZdZd,dZ d,d Z!d!Z"d"Z#d#Z$d$Z%d%Z& d-d'Z'd(Z(d&dd)d*Z)xZ*S).rFa6A 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. Attributes ---------- a, b : float, optional Lower/upper bound of the support of the unshifted/unscaled distribution. This value is unaffected by the `loc` and `scale` parameters. To calculate the support of the shifted/scaled distribution, use the `support` method. 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(, 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``. rc t || t|||||||||  |_|t}|d}||_||_||_||_| t |_| t|_||_ ||_ ||_ |j|j|jgdd|j!||ddvrd} nd } | |z}t"j$j&d krd|j(|j+|t,d ytt.} |j1t,| j3|j yy) N) momtyperrxtolrrrOrr Distributionzloc=0, scale=1z loc, scaler.rrr aeiouAEIOUAn A rSrrOrHrP)rrr*rrrrrrrr moment_typerr6_pdfrrsysflagsr rDrQrHrrKrc) rrrrrrrrOrrhstrr5rs rNrzrv_continuous.__init__GsY  qADD8&  H <!D    9TDF 9DF "  !!DIItyy3I.>/; " =   Aw.(d{H 99   !||#++X4;5A,C8n##GSWWTYY-?@ "rPc|jj}gd}|Dcgc]}|j|dc}|Scc}w)N)rr r _cdfvecrrr\rrrrr5attrsattrs rN __getstate__zrv_continuous.__getstate__ys?mm  "G)./t /  0Ac|jt|jd|_|jdz|j_t|j d|_t|jd|_ |jdz|j_|jdk(rt|jd|_ nt|jd|_ |jdz|j_y)zU Attaches dynamically created methods to the rv_continuous instance. rotypesrrN)rr _ppf_singlerrnin_entropyr _cdf_singler r_mom0_scr\_mom1_scrs rNrzrv_continuous._attach_methodss &&(!!1!1#> < !1!1#> <w&D$$$$T14t4r9"VmTe%$$$T14t4r9 88E?%E$$$$UA55:#UV^e%$$$UA55:t11#U!dL LrPc4||z|j|g|zSrJr,)rrrr`s rN _mom_integ0zrv_continuous._mom_integ0s!!thdhhq(4(((rPcz|j|\}}tj|j|||f|zdSNr`r)rr quadr?)rrr`rrs rNr.zrv_continuous._mom0_scsF"""D)B~~d..B$%49../1 1rPc.|j|g||zSrJr)rrrr`s rN _mom_integ1zrv_continuous._mom_integ1s"T"Q&&rPcVtj|jdd|f|zdS)NrrrB)r rCrE)rrr`s rNr/zrv_continuous._mom1_scs(~~d..1A49EaHHrPc6t|j|d|dS)Ngh㈵>r)dxr`r)rrrs rNrzrv_continuous._pdfs499aDt1EErPc|j|g|}tjd5t|cdddS#1swYyxYwr)rrZr[r)rrr`ps rN_logpdfzrv_continuous._logpdfs? DIIa $  [[ ) q6   s ?Ac(|j|g|SrJ)rKrs rNrzrv_continuous._logpxft||A%%%rPcr|j|\}}tj|j|||dSrA)rr rCr)rrr`rrs rNr-zrv_continuous._cdf_singles6"""D)B~~diiQT:1==rPc(|j|g|SrJ)r rs rNrzrv_continuous._cdfrrPcjdg|}tjd5tj||k|f|zfdfdcdddS#1swYyxYw)NrrZrcPtjj|g|SrJ)rZrrrr`rs rNz'rv_continuous._logcdf..s   !(;d(;!<rPcRtjj|g| SrJ)rZlog1prrRs rNrSz'rv_continuous._logcdf..s#8488A+=+=*=!>rPrrZr[xpx apply_whererrr`r<s` rNrzrv_continuous._logcdfs_3&& [[ ) @??F QD4K<>@ @ @ @ %AA#cjdg|}tjd5tj||kD|f|zfdfdcdddS#1swYyxYw)NrrZrcPtjj|g|SrJ)rZrrrRs rNrSz&rv_continuous._logsf..s (:T(:!;rPcRtjj|g| SrJ)rZrUrrRs rNrSz&rv_continuous._logsf..s#9499Q+>+>*>!?rPrVrYs` rNrzrv_continuous._logsfs_3&& [[ ) A??F QD4K;?A A A ArZc|j|i|\}}}tt|||f\}}}ttt|}t j |j tj}t j||z |z |}|j||dkDz}|j|g||dkDz}||z} tt| |} t| d|z t j|z|jt j| r;t!| g|f|z|fz} | d| dd} }t#| | |j$| |z | j&dk(r| dS| S)aDProbability 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 rrrrbNr)rrrrrZ promote_typesrfloat64rsr|rrrisnanrrrrrrs rrr`rrrdtyprcond1rrrs rNr,zrv_continuous.pdfsa*,4++T:T:c5Gae_5 3S$'(4 JJCd 3%3"""1,t, :u}uT{D)5"((1+-t}}= 66$<!$>1$t)UH*<>H&rlHSbM8E &$  8 4u < = ;;! ":  rPc|j|i|\}}}tt|||f\}}}ttt|}t j |j tj}t j||z |z |}|j||dkDz}|j|g||dkDz}||z} tt| |} | jt t| d|z t j|z|j t j"| rDt%| g|f|z|fz} | d| dd} }t'| | |j(| t+|z | j,dk(r| dS| S)aLog 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 rrrrbNr)rrrrrZr_rr`rsr|r!rfillrrrarrrrrKrrsrbs rNr-zrv_continuous.logpdfss.,4++T:T:c5Gae_5 3S$'(4 JJCd 3%3"""1,t, :u}uT{D) SD5"((1+-t}}= 66$<!$>1$t)UH*<>H&rlHSbM8E &$  h 7#e* D E ;;! ":  rPc2|j|i|\}}}tt|||f\}}}ttt|}|j|\}}t j |jt j}t j||z |z |}|j||dkDz} |j|g||dkDz} |t j|k\| z} | | z} tt| |} t| d| z t j|z|jt| | dt j | r*t#| g|f|z}t| | |j$|| j&dk(r| dS| 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` rrrrRr)rrrrrrZr_rr`rsrrrrrarrrrrsrrr`rrrrrrcrrdcond2rrrs rNr.zrv_continuous.cdfIs{,,4++T:T:c5Gae_5 3S$'("""D)B4 JJCd 3%3'''1D1UQY?bjjn$-u}uT{D) fqw +T]]; feS! 66$<!$51$t)5H &$  8 4 5 ;;! ":  rPcD|j|i|\}}}tt|||f\}}}ttt|}|j|\}}t j |jt j}t j||z |z |}|j||dkDz} |j|g||dkDz} ||k\| z} | | z} tt| |} | jt t| d| z | | k(zt j |z|j"t| | dt j$| r*t'| g|f|z}t| | |j(|| j*dk(r| dS| S)ahLog 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 rrrr6r)rrrrrrZr_rr`rsrr!rrfrrrarrrrrsrhs rNr/zrv_continuous.logcdfss*,4++T:T:c5Gae_5 3S$'("""D)B4 JJCd 3%3'''1D1UQY?bE!u}uT{D) SD fqw%0!? feZ{;A>? 66$<!$B1$t)UCL*@BH#+B<"x}3E &$  8 4u .objective s))%LAArPzMethod 'z ' not available; must be one of rz3All parameters fixed. There is nothing to optimize.cPd}tD]}|vs||||<|dz }|Sr)rC)r`rrrLNargsfixedns rNrestorez+rv_continuous._reduce_func..restore sAuA"'(QQ rPc.dd|}||SrJr)rrnewthetar`rrs rNrz(rv_continuous._reduce_func..func s "47E2 1--rP)rrr  enumeraterrrr-rCr&rlowerrZrnewaxisrrr)rr`rrKrrrkeyr rarLx0r&rn_params exponentsrrrrrrs`` @@@@@rN _reduce_funczrv_continuous._reduce_func s1 ;;[[((c288:F!&) $1CFlcAgvz2*47? #DI  $DzD "' "23Q1QC3vx6HH & #FAsd{ a ((3-Q $q'"  #$-(E*002 T>6{QV4H1hqj11bjj=AI66$tQw-":3t9"D1ML Bu_,,Ixx0//6i9: : v;! DG6{e# IKK  .4$&&a4s( Hc |j|\}}}|j|r|dkrtStjt t |Dcgc]}|j|dzg|||dc}}tjtj|r td||z tjtj|dz dzjScc}w)NrrrrzqMethod of moments encountered a non-finite distribution moment and cannot continue. Consider trying method='MLE'.:0yE>rS)rrsrrZrqrCr-r6rrarmaximumabsr) rrrrrrr`r dist_momentss rNrzrv_continuous._moment_error s11%8UDt~~t$ Jxx*/L0A*B!D%&"-QqS!N4!NS!N!DE 66"((<( )=> >-BFF<0$78:;<=@SU C!Ds!C0cd|jddj}t|t}|r1|dk7r t d|j dk(r|j }d}t|}||jkDr td|sQtj|j}tj|js t ddgd z}||jksd |vrd |vs|j|}|||d z }|j!d |d }|j!d |d } ||| fz }|j#|||\} } } }|j!dt$j&} t)| } |rtd|d| | | |fd}| ||}| | ||}t+|}|j-|\}} }tj|j.|r| dkDs t1d|dk(r tj|s t1d|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) rrz,For censored data, the method must be "MLE".rFzToo many input arguments.z$The data contains non-finite values.NrSrrrarb)rKrzUnknown arguments: .)r`dispz\Optimization converged to parameters that are outside the range allowed by the distribution.rzVOptimization failed: either a data moment or fitted distribution moment is non-finite.)rcrrr$rrr}r-rrrZrrfrrrrrrr rrrrrsr%)rrKr`rrcensoredNargstartrrrrrrr>objrs rNr5zrv_continuous.fit sG\(E*002dL1  ".//  "a''' 4y $,, 78 8 ::d#))+D;;t$((* !GHHq 4<< $)0DNN4(E E$rN "DhhueBi(%), e "&"3"3D$T"3"JD'4HH[(--8 ,Y7 1$q9: : ra84  4&DT{!33D9UF~t~~v./EAILM M T>;;s# -.. rPc~t|tr|j}ntj|}|j |g|\}}|j ||j|\}}||}}||z } | dkr||fS|||zz} |||zz} tj|} tj|} | | kr | | kr||fS| | z }d}||z}| tjkr| |z |z }|d|zz| z }||fS|tj kDr | |z |z dfS|tjkr | |z |zdfSt)aEstimate 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. rg?rSr) rr$ _uncensorrZr fit_loc_scalersrr7r8r RuntimeError)rrKr`loc_hat scale_hatrrrr support_widtha_hatb_hatdata_adata_b data_width rel_marginmargins rNrz$rv_continuous._fit_loc_scale_support s& dL )>>#D::d#D0T//funI% %f_  j( 266 !zV+G#a&j0MAII% % w;QJ&(!+ + ZQJ&(!+ + rPcv|j|iddi\}}t|}|j}|j}t ||z }t j d5|||zz } dddt j sd} t j|rd|ksd}| |fS#1swY@xYw)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. rrrZrxNrr)rrr9r;rrZr[r) rrKr`rMr\tmpmuhatmu2hatShatLhats rNrzrv_continuous.fit_loc_scale" s($**d8y$&78Cdm FSL! [[ * #47?D #{{4 D D!q4xDTz  # #s ' B//B8cfd}j\}}tjd5tj|||d}dddtj s|Sj ddgg\}}tj|r|}n|}tj|r|} n|} tj|| |dS#1swYxYw)Nc@j|g}t|SrJ)rr )rrar`rs rNintegz%rv_continuous._entropy..integD s"$))A%%C9 rPrZ)overr绽|=gA?)rrZr[r rCrar2r ) rr`rrrhlowuppupperrs `` rNr,zrv_continuous._entropyC s  #""D)B [[h ' 1ub"-a0A 1xx{H txx 3;d;HCxx|xx|>>%6q9 9! 1 1s CCrc b||dj|j|\} } fd} nfd} ||| |zz}||| |zz}j||gg|i} | d| dz } ||d<d}tj|d|z g}| d| |zz}|j |g||zz\}}t j| ||fi|d}t j| ||fi|d}t j| ||fi|d}||z|z}|r|| z}tj|dS) aCalculate 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 rc6|j|g|izSrJr>)rr`lockwdsrs rNfunz!rv_continuous.expect..fun s#8488A88888rPcB|j|g|izSrJr>)rr`rrrs rNrz!rv_continuous.expect..fun s'Aw!!>d!>g!>>>rPrrr`g?r)rsrr.rZrqrr rC)rrr`rrrrrrrrr cdf_boundsinvfacr inner_boundscdf_inner_boundscrlbccddubr>rs`` @rNr7zrv_continuous.expect\ s}F!#"""D)B < 9 ? :rEz!B :rEz!BTXXr2h999 AA.V xx% 01 %a=6L+@@YTYY/7$7%??1nnS"a0403 ^^CA . .q 1nnS!R0403b3  FNDxx~b!!rPc|j}tddtj tjfd}tdddtjfd}|||gz}|S)NrFFFrr _shape_inforrZr)r shape_infoloc_info scale_info param_infos rN _param_infozrv_continuous._param_info s\%%' eUbffWbff,=~NBFF ^L 8Z"88 rPrc |j|g|||d}tj|dkD|j|g|||d|j|g|||dz |j|g|||d|z }|jdk(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, ...)`. rrrr)r.rZrr0rs)rx1x2rrr`cdf1rs rNrzrv_continuous._delta_cdf stxx8T8s%8 $*"4772CC#UC$TWWRE$ECuEF"$((2CC#UCdJL ;;! BZF rP) rNNg+=NNNNNrJ)NrrrNNF)+rrrrDrr%rrr4r*r?r.rEr/rrKrr-rrrr,r-r.r/r0r1r2r3rrrrrrr5rrr,r7rrrrs@rNrFrFysKZ8=48#'0Ad3, 'L*)1 'IF & >&@A%N(T(T(T'R+Z+Z+Z "/H=$#F'P CobENB:2FJ E"N-.QrPc fd}j\}}t|||jdgjS)z,Non-central moment of discrete distribution.cXtj|j|gzSrJ)rZr[_pmf)rr`rLrs rNrz_drv2_moment..fun s(xx1~  ! 3d 333rPr)r_expectrinc)rrLr`rrrs``` rN _drv2_momentr sG4T   %FB 3B  # 5 5txx @@rPc@|j|\}}|}|}d}t|rFttd|zd} ||k\rd}n'|j|g|}||kr ||z }|dz}nn-d}d}t|rFtt d|zd} ||krd}n8|j|g|} | |kDr ||z}|dz}nn-|j|g|} t j|st j|r d } t| d } t| D]}  |k(r|cS||k(r|cS||dzkr | |kDr|cS|cSt||zd z } |j| g|}||kr|| k7r| }n td |} i||kDr|| k7r| }n td |}| cSy) N rrrRrSiir6zAArguments that bracket the requested quantile could not be found.irXzupdating stopped, endless loop) rr floatr8rr7rZrrCr)rrr`rrrrstepqbqarmaxiterrrqcs rN_drv2_ppfsingler s T   %FB A A D Qx #c!eR. !Bw1$t$BQT   D Qx #d1fc" #Bw1$t$BQT  TYYq 4  xx{bhhqkU7##G 7^ !GH !GH !8Av 1c N TYYq 4  FAv"#CDDB1fAv"#CDDBH3rPc eZdZdZdeddddddddf fd Zdeddddddddf fd ZdZd Zd Z d Z d Z d Z dZ dZdZdZdZfdZdZdZdZdZdZdZdZdZdZ ddZdZxZS) rGaA 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. Attributes ---------- a, b : float, optional Lower/upper bound of the support of the unshifted/unscaled distribution. This value is unaffected by the `loc` and `scale` parameters. To calculate the support of the shifted/scaled distribution, use the `support` method. 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) rNrrc L|t |tSt ||SrJ)r__new__r) clsrrrr moment_tolvaluesrrOrrrs rNrzrv_discrete.__new__ s+  7?9- -7?3' 'rPc nt || t||||||||| |  |_|t}||_||_||_||_||_ | |_ | td|j|j|jgdd|j|j!||y)N rrrrrrrrOrrz.rv_discrete.__init__(..., values != None, ...)loc=0loc, 1r)rrr*rrrrrrrrrr6rrr_construct_docstrings) rrrrrrrrrOrrrs rNrzrv_discrete.__init__ s  14(!&cf49  H  $  MN N !!DIItyy3I.5/7 " 9  ""42rPc|jj}gd}|Dcgc]}|j|dc}|Scc}w)N)rr r r rr\r!r"s rNr%zrv_discrete.__getstate__ s>mm  "9)./t /  0r&ct|jd|_t|j|_|j tt d}|jdz|_tj|||_ ttd}|jdz|_tj|||_ |jdz|j_y)zAAttaches dynamically created methods to the rv_discrete instance.rr(rSrN)rr-r r,rrrrr+rrr\rr)r_vec_generic_moment_vppfs rNrzrv_discrete._attach_methods s !1!1#> #DMM2 &&(( SA"&,,"2#../BDI/#6LL1$ ''t4  <tt}|jt |j|j|jjd d |_yy) NrrrrrrSrPrzE scale : array_like, optional scale parameter (default=1)r)) rrrr rDrQdocdict_discreter*rrKrcr)rrrOrr5s rNrz!rv_discrete._construct_docstrings4 s <!D   Aw.(d{H 99   !||#++X4D5?,A<(##$4cggdii6HI <<//@ACEDL "rPc |jj}|j|d<|j|d<|j|d<|j |d<|j |d<|j|d<|j|d<|S)r1rrrrrrr) rrrrrrrrrr2s rNrzrv_discrete._updated_ctor_paramP sy ##%66C66C--J OOLXXE iiF  H  rPct||k(SrJ)rrrr`s rN_nonzerozrv_discrete._nonzero` sQx1}rPcV|j|g||j|dz g|z S)Nrrr s rNrzrv_discrete._pmfc s1tyy"T"YTYYqs%:T%:::rPctjd5t|j|g|cdddS#1swYyxYwr)rZr[rrr s rN_logpmfzrv_discrete._logpmff rrc(|j|g|SrJ)rr s rNrzrv_discrete._logpxfj rMrPcr |d}d}t|dd}|||fS#t$r}td|d}~wwxYw)Nrbrrurvrxs rNrzrv_discrete._unpack_loc_scalep sW C)CEs$DE4 C:; B Cs 6 16c|j|\}}tt||dz}tj|j |g|dS)Nrrr)rrrrZrr)rrr`rrrs rNr-zrv_discrete._cdf_singley sM"""D)B 3r7AaC vvidii)D)22rPcxt|jtj}|j|g|SrJ)rrrZr`r )rrr`rs rNrzrv_discrete._cdf~ s. !HOOBJJ 't||A%%%rPc,d|d<t||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`. TrP)rr+)rr`rers rNr+zrv_discrete.rvs s#:"zw{D+F++rPc |j|i|\}}}tt||f\}}ttt|}|j|\}}t||z }|j |}||k\||kz} t |ts| |j|g|z} || z} tt| d} t| d|z tj|z|jtj| r?t!| g|f|z} t| | tj"|j$| dd| j&dk(r| dS| S)aProbability 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 rrrr)rrrrrrsrrrrrrrZrarrrcliprrs rrr`rrrrrrrdrrrs rNrDzrv_discrete.pmf sH&(t''66 c1Wq#h'3S$'("""D)B AcEN%bQ"W%$ *MDMM!3d33Eu}uT{C( fqw"((1+-t}}= 66$<!$51$t)5H &$  8(.sT)$))A*=*=%>rPr)r,rr4r%rrrr)rr`rrs`` rNr,zrv_discrete._entropyse 4 ==) )&T&&-FB>r9499S#84#8$((D DrPc j\} } fd} nfd} j\} } || }n|z }|| }n|z }|r+j|dz gj|gz }nd}ttrj | ||}||z Sj dg}t | |||j||| }||z 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. c6|zj|gzSrJr)rr`rrs rNrzrv_discrete.expect..fun.s"#ytyy2T222rPcB|zj|gzSrJr))rr`rrrs rNrzrv_discrete.expect..fun2s&AcE{9499Q#6#666rPrrRr)rrr0rrrrr)rrr`rrrrmaxcount tolerance chunksizerrrrrrrs```` rNr7zrv_discrete.expectsp&T%%t, a < 3 7#""D)B :BcB :BcB TWWRT)D)GDGGB,>,>>FF dI &,,sB+C< TYYs "T "c2r2txx9iPV|rPc|j}tddtj tjfd}||gz}|S)NrTrr)rrrrs rNrzrv_discrete._param_infoPsA%%' eTRVVGRVV+,,E8 ;,&  3 & ,@$L%N(T&P$L(T&P.`D=ALN[zrPc||z |kr7tj||dz|}||} tj| S||kr|}||kDr|}d\} } t||dz||D]s} | | jz } tj|| } | | z } t | || jzkrn'| |kDsUt jdtd| cSt|dz |dz || D]s} | | jz } tj|| } | | z } t | || jzkr| S| |kDsVt jdtd| S| S)z4Helper for computing the expectation value of `fun`.r)rr6)r-rzexpect(): sum did not convergerT) stacklevel) rZrr _iter_chunkedrxrwarningswarnRuntimeWarning)rrrrrr+r,r-suppr>counttotrdeltas rNrrWsw RIyyRT3'4yvvd| Bw  Bw JE3 2r!tyc B  s1v u  u: AFF* *  8  MM:(Q 8J 2a4A E  s1v u  u: AFF* *  J 8  MM:(Q 8  J  JrPc#\K|dk(r td|dkrtd|d|dkDrdnd}t||z}tj|}||z |zdkrMt |t||z }||z}tj |||z|} ||z }| ||z |zdkrLyyw)aIterate 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])] rzCannot increment by zero.z!Chunk size must be positive; got rrrbN)rrrZrr7r) rrr-rrstepsizerr:rr7s rNr3r3s& ax455A~GH H 14(!&cf49  H  $ --B 88B<288B< 'BC C 772s    !GH H{{266":q)?@ @3rxx|$%4CD Dzz"((2,'''"((2,a0''"((2,a0YYtwwQ/   !!DII;.5/7 " 9  ""42rPc|jj}gd}|Dcgc]}|j|dc}|Scc}w)Nr r!r"s rNr%zrv_sample.__getstate__s?mm  "H)./t /  0r&c$|jy)z/Attaches dynamically created argparser methods.N)rrs rNrzrv_sample._attach_methodss &&(rPc2|j|jfS)aReturn 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. ru)rr`s rNrzrv_sample._get_supportsvvtvv~rPc tj|jDcgc]}||k( c}|jDcgc]}tj||dc}dScc}wcc}wro)rZselectrDr%r)rrrrJs rNrzrv_sample._pmfsVyy$''2Q!q&2@DH1"--a3A6H!M M2Hs A" A' ctj|dddf|j\}}tj||kDddz }|j|S)Nrbrr)rZrrDrrF)rrxxxxkrGs rNrzrv_sample._cdfsL%%a4j$'':Cyyr+a/zz$rPctj|d|j\}}t||k\d}|j|S)N).Nrbr)rZrrFrrD)rrqqsqqrGs rNrzrv_sample._ppfs>%%a lDJJ?CcRib)wwt}rPc|j|}|-tj|d}|j|d}|S|j|}|S)Nrr)ndminr)rrZrqr)rrxryrrs rNrzrv_sample._rvs sX  d + <!$A ! QA ! ArPc@tj|jSrJ)rr4r%rs rNr,zrv_sample._entropys}}TWW%%rPct|}tj|j|tjdfz|j zdS)N.rr)rrZrrDrr%)rrLs rNr\zrv_sample.generic_moments; AJvvdggqS11DGG;!DDrPc|j||jk|j|kz}||}tj|SrJ)rDrZr)rrrrr`rr7r>s rNrzrv_sample._expects<wwdgg $''R-894yvvd|rPr)rrrrDrrr%rrrrrrr,r\rrrs@rNrrs[ ct 1t433j) M  &ErPrc g}g}t|ddd|ddddD]L\}}||kDs||cxk(rdk(r&nn#|j||jd<|jdNt|dddt|dddfS)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(). Nrbr) fillvalueTF)rr&r)argshaperx scalar_shapebcargdimsizedims rNrprp&s4L B&x"~tDbDz124 V ' 6Q 6    ( IIdO IIe   dd# $eBttHo 55rPcg}g}|D]c\}}|jdr|jdrt||r|j|t ||sS|j|e||fS)awCollect 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_gen)rendswith issubclassr&r)namespace_pairs rv_base_class distn_namesdistn_gen_namesrvalues rNget_distribution_namesrhLsx(KO&% e ??3   == Z}%E  " "4 ( e] +   t $ %  ''rPrJ)r/rr0)rVr)~scipy._lib._utilrrrr!r$rr4 itertoolsr scipy._libr _distr_paramsrrr scipy._lib.array_api_extra_libarray_api_extrarW scipy.specialr r scipyr r scipy.stats._finite_differencesrrnumpyrrrrrrrrrrrrrrrrr r!rZ _constantsr"r#_censored_datar$scipy.stats._warnings_errorsr%rN_doc_rvs_doc_pdf _doc_logpdf_doc_pmf _doc_logpmf_doc_cdf _doc_logcdf_doc_sf _doc_logsf_doc_ppf_doc_isf _doc_moment _doc_stats _doc_entropy_doc_fit _doc_expect_doc_expect_discrete _doc_median _doc_mean_doc_var_doc_std _doc_intervalr)_doc_allmethods_doc_default_longsummary_doc_default_frozen_note_doc_default_example_doc_default_locscale _doc_default_doc_default_before_notesrHrr _doc_disc_methodsrr_doc_disc_methods_err_varnamer_doc_default_discrete_example_doc_default_discrete_locscale_doc_default_discdirrrrOrdrirlrrrrrrrrr+rrrrFrrrGrr3rrprh)rrs00rNrs G  !1/(($ 8+++++'(1 4-68                        '':i0(H&+w%x;%|X& $h- IJ 2hww0',./ GG%=%4%67  8  8  k  8    k    '   Z  8  8  Z |  8  k  k     I! " 8# $ !+*#-(5 ><<>"(17 KC,S199+rJSK!A (JC,S199&&ISJUX''