L i̐VddlZddlmZmZddlmZddlZddlZddlZddlm Z ddl m Z ddl m Z mZddlmZmZddlmZmZdd lmZdd lmZmZdd lmZmZdd lmZm Z dd l!m"Z"ddl#m$Z$e%Z&dZ'gdZ(dZ)dZ*GddeZ+Gdde+Z,Gdde,Z-Gdde,Z.GddeZ/Gdde/Z0Gdd Z1d!Z2d"Z3d#Z4d$Z5d%Z6dd&Z7d'Z8d(Z9d)Z:d*d+d,Z;d-ZGd1d2e>Z?Gd3d4e>Z@id5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVidWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxidydzd{d|d}d~ddddddddddddddddddddddddddddiddddddddddddddddddddddddddddddddddiddddddddÓddœddǓddɓdd˓dd͓ddϓddѓddӓddՓddדddٓddۓddݓddiZAdZBdZCdZDdZEdZFdZGdZHGdde?ZIGddeIZJej ejfdZKGddeIZLGddeIZMdZNGdde"ZOGddeIZPGddeIZQdZRdZSdZTy)N)ABCabstractmethod)cached_property)inf) xp_promote) _rng_spawn _RichResult)ClassDocNumpyDocString)specialstats) _log1mexp)tanhsinhnsum) _bracket_root_bracket_minimum) _chandrupatla_chandrupatla_minimize)_ProbabilityDistribution)qmcc0t|tuxs|duSN)typeobjectxs n/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/stats/_distribution_infrastructure.py_isnullrs 7f  )T ))make_distributionMixtureorder_statistictruncateabsexplogskip_allno_cacheceZdZdZej dej dej dej diZedZ edZ edZ ed Z y ) _Domaina Representation of the applicable domain of a parameter or variable. A `_Domain` object is responsible for storing information about the domain of a parameter or variable, determining whether a value is within the domain (`contains`), and providing a text/mathematical representation of itself (`__str__`). Because the domain of a parameter/variable can have a complicated relationship with other parameters and variables of a distribution, `_Domain` itself does not try to represent all possibilities; in fact, it has no implementation and is meant for subclassing. Attributes ---------- symbols : dict A map from special numerical values to symbols for use in `__str__` Methods ------- contains(x) Determine whether the argument is contained within the domain (True) or not (False). Used for input validation. get_numerical_endpoints() Gets the numerical values of the domain endpoints, which may have been defined symbolically or through a callable. __str__() Returns a text representation of the domain (e.g. ``[0, b)``). Used for generating documentation. \infty-\inftyz\piz-\pictrNotImplementedErrorselfrs rcontainsz_Domain.contains !##rctrr.)r1ns rdrawz _Domain.drawr3rctrr.r0s rget_numerical_endpointsz_Domain.get_numerical_endpointsr3rctrr.r1s r__str__z_Domain.__str__r3rN) __name__ __module__ __qualname____doc__nprpisymbolsrr2r6r8r;rrr*r*s8vvy266':ruufruufgVG$$$$$$$$rr*cJeZdZdZe efdffd ZdZdZddZddZ xZ S) _Intervalap Representation of an interval defined by two endpoints. Each endpoint may be a finite scalar, positive or negative infinity, or be given by a single parameter. The domain may include the endpoints or not. This class still does not provide an implementation of the __str__ method, so it is meant for subclassing (e.g. a subclass for domains on the real line). Attributes ---------- symbols : dict Inherited. A map from special values to symbols for use in `__str__`. endpoints : 2-tuple of float(s) and/or str(s) and/or callable(s). A tuple with two values. Each may be either a float (the numerical value of the endpoints of the domain), a string (the name of the parameters that will define the endpoint), or a callable taking the parameters used to define the endpoints of the domain as keyword only arguments and returning a numerical value for the endpoint. inclusive : 2-tuple of bools A tuple with two boolean values; each indicates whether the corresponding endpoint is included within the domain or not. Methods ------- define_parameters(*parameters) Records any parameters used to define the endpoints of the domain get_numerical_endpoints(parameter_values) Gets the numerical values of the domain endpoints, which may have been defined symbolically or through a callable. contains(item, parameter_values) Determines whether the argument is contained within the domain draw(size, rng, proportions, parameter_values) Draws random values based on the domain. )FFct|j|_|\}}tj|dtj|df|_||_yNrC)superrBcopyr@asarray endpoints inclusive)r1rKrLab __class__s r__init__z_Interval.__init__sMw++- 1Ar*BJJqM",=="rc|Dcic]}|j|j}}|jj|ycc}w)a% Records any parameters used to define the endpoints of the domain. Adds the keyword name of each parameter and its text representation to the `symbols` attribute as key:value pairs. For instance, a parameter may be passed into to a distribution's initializer using the keyword `log_a`, and the corresponding string representation may be '\log(a)'. To form the text representation of the domain for use in documentation, the _Domain object needs to map from the keyword name used in the code to the string representation. Returns None, but updates the `symbols` attribute. Parameters ---------- *parameters : _Parameter objects Parameters that may define the endpoints of the domain. N)namesymbolrBupdate)r1 parametersparam new_symbolss rdefine_parametersz_Interval.define_parameterss=(>HHEuzz5<</H H K(IsAc|j\}} t|r |di|}n%tj|j ||}t|r |di|}n%tj|j ||}t||dt\}}||fS#t $r!}d|j d}t ||d}~wwxYw)a0 Get the numerical values of the domain endpoints. Domain endpoints may be defined symbolically or through a callable. This returns numerical values of the endpoints given numerical values for any variables. Parameters ---------- parameter_values : dict A dictionary that maps between string variable names and numerical values of parameters, which may define the endpoints. Returns ------- a, b : ndarray Numerical values of the endpoints zThe endpoints of the distribution are defined by parameters, but their values were not provided. When using a private method of zA, pass all required distribution parameters as keyword arguments.NT)force_floatingxprC)rKcallabler@rJget TypeErrorrOr)r1parameter_valuesrMrNemessages rr8z!_Interval.get_numerical_endpoints1s&~~1 ,{)()JJ/33Aq9:{)()JJ/33Aq9:!Qt;1!t  ,448NN3CD$$G G$! +  ,sA2B C&CCc|xsi}|j|\}}|j\}}|r||k\n||kD}|r||kn||k}||zS)aDetermine whether the argument is contained within the domain. Parameters ---------- item : ndarray The argument parameter_values : dict A dictionary that maps between string variable names and numerical values of parameters, which may define the endpoints. Returns ------- out : bool True if `item` is within the domain; False otherwise. )r8rL) r1itemr_rMrNleft_inclusiveright_inclusivein_leftin_rights rr2z_Interval.contains`sa",1r++,<=1*...'-$!)4!8 /419TAX!!rctjjfd}t|tr j n|}|j |j } } tj| tj| z} d| | <d| | <|f|z} |dk(r || | | } | S|dk(r9| }tj|} j|dk} || | <|| | <| S|dk(r;| |dd | z } | |dd | z}j|dk} || | | <| S|d k(r$tj| tj}  S) a Draw random values from the domain. Parameters ---------- n : int The number of values to be drawn from the domain. type_ : str A string indicating whether the values are - strictly within the domain ('in'), - at one of the two endpoints ('on'), - strictly outside the domain ('out'), or - NaN ('nan'). min, max : ndarray The endpoints of the domain. squeezed_based_shape : tuple of ints See _RealParameter.draw. rng : np.Generator The Generator used for drawing random values. c0j|i|ddiS)NendpointT)integers)argskwargsrngs rintsz_Interval.draw..intss,#,,*V*VQU*V#Vrrin)sizeon?outnan) r@random default_rng isinstance _RealIntervaluniformrIisnanonesfullrw)r1r5type_minmaxsqueezed_base_shapernror|min_nnmax_nnishapez z_on_shapezrs ` rr6z_Interval.drawsd,ii##C(V!+D-!@#++dSXXZ HHV rxx/ /q q ** D=U3A$!d]J #A  "S(AAaDAqbEe^AE22A'!QU33B  "S(Aa5AaD e^rvv&Arr) r<r=r>r?rrPrXr8r2r6 __classcell__rOs@rrErEs1$J$'$# ).-^ "D6rrEceZdZdZdZdZy)r{a Represents a simply-connected subset of the real line; i.e., an interval Completes the implementation of the `_Interval` class for intervals on the real line. Methods ------- define_parameters(*parameters) (Inherited) Records any parameters used to define the endpoints of the domain. get_numerical_endpoints(parameter_values) (Inherited) Gets the numerical values of the domain endpoints, which may have been defined symbolically. contains(item, parameter_values) (Inherited) Determines whether the argument is contained within the domain __str__() Returns a string representation of the domain, e.g. "[a, b)". c|j\}}|j|d|j|d}}|j\}}|rdnd}|rdnd}||d||S)Nf1f2[(]), )rK_get_endpoint_strrL)r1rMrNrdreleftrights rr;z_RealInterval.__str__sk~~1%%a.0F0Fq$0O1*...'$s#&Cs"QCw''rct|r|j |jStj|jj }|Dcgc]6}|j tjjk(s+|j8}}|ddj|dS|jj||Scc}w)Nr,r) r\r?inspect signaturerUvalueskind Parameter KEYWORD_ONLYrRjoinrBr])r1rjfuncnameparamsps rrz_RealInterval._get_endpoint_strs H +'''&&x0;;BBDF &!&&G4E4E4R4R*RFZq&!1 2!4 4||XJ88 s ,CCN)r<r=r>r?r;rrCrrr{r{s(( 9rr{c*eZdZdZdfd ZdZxZS)_IntegerIntervala+ Represents an interval of integers Completes the implementation of the `_Interval` class for simple domains on the integers. Methods ------- define_parameters(*parameters) (Inherited) Records any parameters used to define the endpoints of the domain. get_numerical_endpoints(parameter_values) (Inherited) Gets the numerical values of the domain endpoints, which may have been defined symbolically. contains(item, parameter_values) (Overridden) Determines whether the argument is contained within the domain draw(n, type_, min, max, squeezed_base_shape, rng=None) (Inherited) Draws random values based on the domain. __str__() Returns a string representation of the domain, e.g. "{a, a+1, ..., b-1, b}". c^t|||}|tj|k(}||zSr)rHr2r@round)r1rcr_super_containsintegralrOs rr2z_IntegerInterval.containss2)$0@ABHHTN*((rc |j\}}|jj||}|jj||}t|tt|t}}|r|dk(nt j |}|r|dk(nt j |}|r|dn|dz}|r|dn|dz }|sE|sC||z } | dk(rd|d|d|d|d S| d k(r d|d|d|d S| dk(r d|d|d S| d k(rd|d S|s|r|r|d n|d z} d|d|d| d S|r|s|r|dn|d z } d|d|d| d S|r|ryd|d|d|d|d S)Nr,r+z + 1rpz - 1z\{rz\}rz + 2z, ...\}z - 2z\{..., -2, -1, 0, 1, 2, ...\}z, ..., )rKrBr]rzstrr@isinf) r1rMrNa_strb_stra_infb_infap1bm1gapap2bm2s rr;z_IntegerInterval.__str__s~~1 LL  Q " LL  Q "!!S):a+=u#(Zbhhqk"'YRXXa["4j!a%!4j!a%Ua%CaxaS3%r#b488axaS3%r!D11axaS1#T**axaS~% %QCt*a!eWC!Bse2cU)4 4  %QCt*a!eWC!Bse2cU)4 4 U4aS3%wse2aS55rr)r<r=r>r?r2r;rrs@rrrs,) %6rrcHeZdZdZddddZdZd ddddddZed Zy) _Parametera Representation of a distribution parameter or variable. A `_Parameter` object is responsible for storing information about a parameter or variable, providing input validation/standardization of values passed for that parameter, providing a text/mathematical representation of the parameter for the documentation (`__str__`), and drawing random values of itself for testing and benchmarking. It does not provide a complete implementation of this functionality and is meant for subclassing. Attributes ---------- name : str The keyword used to pass numerical values of the parameter into the initializer of the distribution symbol : str The text representation of the variable in the documentation. May include LaTeX. domain : _Domain The domain of the parameter for which the distribution is valid. typical : 2-tuple of floats or strings (consider making a _Domain) Defines the endpoints of a typical range of values of the parameter. Used for sampling. Methods ------- __str__(): Returns a string description of the variable for use in documentation, including the keyword used to represent it in code, the symbol used to represent it mathemtatically, and a description of the valid domain. draw(size, *, rng, domain, proportions) Draws random values of the parameter. Proportions of values within the valid domain, on the endpoints of the domain, outside the domain, and having value NaN are specified by `proportions`. validate(x): Validates and standardizes the argument for use as numerical values of the parameter. N)rStypicalc||_|xs||_||_|!t|ts|j |}|xs||_yr)rRrSdomainrzr*rOr)r1rRrrSrs rrPz_Parameter.__init__QsF n   z'7'C&&w/G(& rchd|jd|jdt|jdS)zA String representation of the parameter for use in documentation.`z ` for :math:`z \in )rRrSrrr:s rr;z_Parameter.__str__Ys/499+]4;;-vc$++>N=OqQQrr)rnregion proportionsr_cJ|xsi}|j}|dn|}|tj|z }|j|\}} tj|| \}} |j } tj || } tj| } tj| } | rt| | z nd}tjj|}|j||\}}}}dt| t| z z| z}tjtj|dk(d}tt!t|}tj| |}tj|j#}tj| j#}|j }|dk(r|j$}|j|\}} tj|| \}} tj|j#}tj| j#}|j'|d||||}n|j'|d||||}|j'|d||||}|j'|d ||||}|j'|d ||||} tj(|||| fd }!|j+|!d }!tj,|!t||z}!tj.|!||}!|!S) aS Draw random values of the parameter for use in testing. Parameters ---------- size : tuple of ints The shape of the array of valid values to be drawn. rng : np.Generator The Generator used for drawing random values. region : str The region of the `_Parameter` from which to draw. Default is "domain" (the *full* domain); alternative is "typical". An enhancement would give a way to interpolate between the two. proportions : tuple of numbers A tuple of four non-negative numbers that indicate the expected relative proportion of elements that: - are strictly within the domain, - are at one of the two endpoints, - are strictly outside the domain, and - are NaN, respectively. Default is (1, 0, 0, 0). The number of elements in each category is drawn from the multinomial distribution with `np.prod(size)` as the number of trials and `proportions` as the event probabilities. The values in `proportions` are automatically normalized to sum to 1. parameter_values : dict Map between the names of parameters (that define the endpoints of `typical`) and numerical values (arrays). )rprrrrrprprrqrnrsrurwaxis)rr@sumr8broadcast_arraysrbroadcast_shapesprodintrxry multinomiallenwhererJtuplerangesqueezerr6 concatenatepermutedreshapemoveaxis)"r1rrrnrrr_rpvalsrMrN base_shapeextended_shape n_extendedn_baser5n_inn_onn_outn_nanbase_shape_paddedbase_singletonsnew_base_singletonsshape_expansionrrrrmin_heremax_herez_inz_onz_outz_nanrs" rr6z_Parameter.draw]sB,1r&1&9l{ bff[11--.>?1""1a(1WW ,,T:>WW^, $(2C V# $ii##C(#&??1e#< dE5"3~#6Z#HI)*((2::.?#@!#CDQG#E#o*>$?@**^4_Ejj%jj%!ii Y llG223CDDAq&&q!,DAqzz!))+.Hzz!))+.H<<dHh@S$' )D;;tT35Hc;RD{{4sC1D#{N E5#s4GS Q{{5%c3FC{P NND$u5A > LLL # JJq%03FF G KK. @rctrr.)r1arrs rvalidatez_Parameter.validater3rr) r<r=r>r?rPr;r6rrrCrrrr)sD&N04T)RiT("iV$$rrceZdZdZdZy)_RealParameterz Represents a real-valued parameter. Implements the remaining methods of _Parameter for real parameters. All attributes are inherited. ctj|}d}|jtjk(s|jtjk(rn|jtj k(s|jtj k(r&tj|tj}ntj|jtjrnotj|jtjr&tj|tj}nd|jd}t||jj||}|||zn|}|d|j|fS)a\ Input validation/standardization of numerical values of a parameter. Checks whether elements of the argument `arr` are reals, ensuring that the dtype reflects this. Also produces a logical array that indicates which elements meet the requirements. Parameters ---------- arr : ndarray The argument array to be validated and standardized. parameter_values : dict Map of parameter names to parameter value arrays. Returns ------- arr : ndarray The argument array that has been validated and standardized (converted to an appropriate dtype, if necessary). dtype : NumPy dtype The appropriate floating point dtype of the parameter. valid : boolean ndarray Logical array indicating which elements are valid (True) and which are not (False). The arrays of all distribution parameters will be broadcasted, and elements for which any parameter value does not meet the requirements will be replaced with NaN. Ndtypez Parameter `z` must be of real dtype.rC)r@rJrfloat64float32int32int64 issubdtypefloatingintegerrRr^rr2)r1rr_ valid_dtyperavalids rrz_RealParameter.validates 8jjo  99 "cii2::&=  YY"(( "cii288&;**S 3C ]]399bkk 2  ]]399bjj 1**S 3C#DII;.FGGG$ $ $$S*:;'2'> #E2w 5((rN)r<r=r>r?rrCrrrrs  0)rrc<eZdZdZdZdZdZdZdZdZ d d Z y) _Parameterizationa Represents a parameterization of a distribution. Distributions can have multiple parameterizations. A `_Parameterization` object is responsible for recording the parameters used by the parameterization, checking whether keyword arguments passed to the distribution match the parameterization, and performing input validation of the numerical values of these parameters. Attributes ---------- parameters : dict String names (of keyword arguments) and the corresponding _Parameters. Methods ------- __len__() Returns the number of parameters in the parameterization. __str__() Returns a string representation of the parameterization. copy Returns a copy of the parameterization. This is needed for transformed distributions that add parameters to the parameterization. matches(parameters) Checks whether the keyword arguments match the parameterization. validation(parameter_values) Input validation / standardization of parameterization. Validates the numerical values of all parameters. draw(sizes, rng, proportions) Draw random values of all parameters of the parameterization for use in testing. cN|Dcic]}|j|c}|_ycc}wr)rRrU)r1rUrVs rrPz_Parameterization.__init__'s :DE5::u,EEs"c,t|jSr)rrUr:s r__len__z_Parameterization.__len__*s4??##rcBt|jjSr)rrUrr:s rrIz_Parameterization.copy-s $//"8"8":;;rcN|t|jjk(S)a Checks whether the keyword arguments match the parameterization. Parameters ---------- parameters : set Set of names of parameters passed into the distribution as keyword arguments. Returns ------- out : bool True if the keyword arguments names match the names of the parameters of this parameterization. )setrUkeysr1rUs rmatchesz_Parameterization.matches0s!S!5!5!7888rc<d}t}|jD]E\}}|j|}|j||\}}}|j |||z}|||<Gt |dk(r j ntjt|}||fS)aB Input validation / standardization of parameterization. Parameters ---------- parameter_values : dict The keyword arguments passed as parameter values to the distribution. Returns ------- all_valid : ndarray Logical array indicating the elements of the broadcasted arrays for which all parameter values are valid. dtype : dtype The common dtype of the parameter arrays. This will determine the dtype of the output of distribution methods. Trp) ritemsrUraddrrr@ result_typelist) r1r_ all_validdtypesrRr parameterrrs r validationz_Parameterization.validationAs$ )//1 )ID#-I ) 2 238H I C JJu !E)I%( T "  ) ![!^ f1N%rc|jjDcgc]\}}t|}}}dj|Scc}}w)z8Returns a string representation of the parameterization.r)rUrrr)r1rRrVmessagess rr;z_Parameterization.__str___s?26//2G2G2IJ;4CJJJyy""KsANc$i}|#t|rtj|ds|gt|jz}t ||jj D](\}}|j |||||||j<*|S)aDraw random values of all parameters for use in testing. Parameters ---------- sizes : iterable of shape tuples The size of the array to be generated for each parameter in the parameterization. Note that the order of sizes is arbitary; the size of the array generated for a specific parameter is not controlled individually as written. rng : NumPy Generator The generator used to draw random values. proportions : tuple A tuple of four non-negative numbers that indicate the expected relative proportion of elements that are within the parameter's domain, are on the boundary of the parameter's domain, are outside the parameter's domain, and have value NaN. For more information, see the `draw` method of the _Parameter subclasses. domain : str The domain of the `_Parameter` from which to draw. Default is "domain" (the *full* domain); alternative is "typical". Returns ------- parameter_values : dict (string: array) A dictionary of parameter name/value pairs. r)rnrr_r)rr@iterablerUziprr6rR)r1sizesrnrrr_rrrVs rr6z_Parameterization.drawds< =E "++eAh2GGC00Eudoo&<&<&>? KD%+0::#;!1,6, UZZ (  r)NNNr) r<r=r>r?rPrrIrr r;r6rCrrrrs+>F$<9" <# * rrc :ddtj dftj dfdt t fdt t fdt dfdt fdddhdhdd d hd d hhdtjfd }|S)Nrrpr)icdficcdfilogcdfilogccdf)rr)rpr)logpdfpdflogpmfpmf_logcdf1 _logccdf1_cdf1_ccdf1>rrrr>rrrrr r!rrc@ |jtk(r %||g|i|S%j}tj|}|j }|j }t|t}|xr|dv}|j|k7r7tj|j|}tj||}|j|k(s7 tj|j|}tj||}$j!||j#\} } |j$j&j(\} }|(vr| s|r|| kn|| k}|(vr|r|| kDn|| k\}||z}|jdk(r|ntj*|}d}|&vr5|| k(}|| k(}||z}|jdk(r|ntj*|}d}|rB|'vr>|tj,|k7}|jdk(r|ntj*|}|r+tj.||d }tj0||<tj%||g|i|}d}|j|k7r"tj||j }d}|j|k7r.tj||j }|xs |xs|xs|}|rtj.||d }|r3|d vrtj2 nd }||tj4|z<|r=)j!|tj0tj0f\}}|||<|||<|r|j#\}}|j|k7rVtj.tj||d }tj.tj||d }|j7d r|n|} |j7d r|n|}!|s| ||<|!||<|"vrtj8|dd}|dS|#vr#|j:}tj8|dd}|dS#t$r.} d|jjd|d} t| | d} ~ wwxYw)N>r r!rrrzThe argument provided to `.zJ` cannot be be broadcast to the same shape as the distribution parameters.rCFTrrI>rrrrIccdf?)validation_policy _SKIP_ALLr<r@rJ_dtype_shaperzDiscreteDistributionrrrr broadcast_to ValueErrorrOr]support _variablerrLanyfloorarrayrwrr}endswithclipreal)*r1rrlrm method_namerrdiscretekeep_low_endpointr`ralowhighleft_inc right_incmask_low mask_high mask_invalid any_invalid any_endpointmask_low_endpointmask_high_endpoint mask_endpointany_non_integralmask_non_integralresres_needs_copyzero replace_low replace_highrMrNreplace_low_endpointreplace_high_endpointr6clip_logrKf replace_exactreplace_non_integralreplace_strict replacementss* rfilteredz"_set_invalid_nan..filtereds  ! !Y .T1.t.v. .jj JJqM  d$89$P9P*P 77e NN177E2E 1E*Aww% 1++AGGU;OOAu-MM+t||~> T#nn33==) +~ =((G./3h "-"?IQXt)  9, '3'9'9R'?|FF<0   - '!"c "#t) .1CCM-:-@-@B-FM!# !6  !  ';;!"bhhqk!1 5F5L5LPR5R 1%'VV,=%>  %d3A ffAlOjj44T4V45 99 NN5$++6E!N 99 //#t{{3C,B B!-B1A  ((3e$7C )-AABFF7qD6:C!RXXc]N2 3   rvvrvv.>? &K'CM)C N <<>DAqww%HHR__Q6TBHHR__Q6TB)4(<(.filtered;s  ! !Y .T+D+F+ +&t&v& ;%d&;&;< <jjo   DKK NN5$++6EJ 99 #//#t{{3C#8t'8'8J **5t*4C   "$C 2wrrWrX)rQrVs` r_set_invalid_nan_propertyrb2s'__Q> OrcHtjddfd }|S)Nmethodcj}|xs|jj|d}t|rn_|(|dk(rdn|}|j d|}t ||}n5|g|d|i|}|dk7r"|j tk7r||j|< ||i|S#t$r}t|j|d}~wwxYw)Nzlog/explogexpdispatchre_sample_dispatch) r< _method_cacher]r\replacegetattr cache_policy _NO_CACHEKeyErrorr/r\)r1rerlrm func_namer8r`rQs rwrappedz_dispatch..wrappedpsJJ B4--11)TB F    !'9!4X&F#++J?KT;/Ft_cdf2_ccdf2r'r(rvrwg@_logcdf2?rrC)r<r0r@rrrr+r^r6rJr2rA _logexpxmexpyr&r7) r1ryrlrmrpr;r<ri_swaprrIrQs rrqz'_cdf2_input_validation..wrappedsJJ LLN T--aC>1c4qww=xxDx)188E8+E1 Q y!F)& 1V9 G1v! G1v! HAw! HAw!a,T,V, + +''#r2&C''#tR(Cjjo   K3 K2w( " K2 K K2 K2w* $*,&&."**S2X&cCf+b0CK 2w(q 3v;?DDCK2wrrarrs` r_cdf2_input_validationrs($__Q--^ Nrctj|jtjrtj|jStj |Sr)r@rrinexactfinfoiinfors r_fiinfors9 }}QWWbjj)xx  xx{rc|xsg}|xsi}t|jt|fd}t|t|j z}||fS)Nc N|g|ditt|dSr)dictr)rrlrQn_argsnamess rrqz_kwargs2args..wrappeds0FT'6]Fd3ud67m+D&EFFr)r rrrr)rQrlrmrqrrs` @@r _kwargs2argsrs[ :2D \rF  E YFG ;v}}/ /D D=rctjtj|}tj|rOtj|j }tj |jj||<tj||\}}tjtj||tjdzzgd}||k(}tj ||<|S)z Compute the log of the difference of the exponentials of two arguments. Avoids over/underflow, but does not prevent loss of precision otherwise. r|rr)r@isneginfr7r2rJrIrrrrr logsumexprAr)rr~rrIs rr}r}s BGGAJA vvay JJqvvx xx $$!  q! $DAq **W&&1RUU2X:Q? @C aAffWCF Jrctj|d}tj|}tj|tj|z}||||<||||<tj|tj|z}||||<||dz||<tj|tj|z}||dz ||<||||<||fS)Nrxrp)r@ full_like ones_likeisfinite)xminxmaxrMrNrs r_guess_bracketrs T4 A TA DBKK--A 7AaD 7AaD DR[[...A 7AaD 7Q;AaD DR[[...A 7Q;AaD 7AaD a4Krcd|j}tj|}tj|j |j }tj |}|}tj|dzdk}||tjdzz||<|j|dS)aStandardizes the (complex) logarithm of a real number. The logarithm of a real number may be represented by a complex number with imaginary part that is a multiple of pi*1j. Even multiples correspond with a positive real and odd multiples correspond with a negative real. Given a logarithm of a real number `x`, this function returns an equivalent representation in a standard form: the log of a positive real has imaginary part `0` and the log of a negative real has imaginary part `pi`. r|rtrC) rr@ atleast_1dr7r^rimagr%rAr)rrr7complexr~negatives r_log_real_standardizers GGE aA 771:  QWW %DggajG Avvgbj!C'HH+ *AhK 99U B rTinclude_examplescttj}|jd|s|jdt |}t t }|D]\}|dvr ||||<|dvr|dk(r||j t|8|dk(rt|g||<M||xx||z cc<^t|S)NindexExamples>Methods Attributes>SummaryzExtended Summary) rr sectionsremover UnivariateDistributionappend_generate_domain_support_generate_exampler) dist_familyrfieldsdocsuperdocfields r _combine_docsr%s (( )F MM'  j! ; C./H * - -!%CJ k !  ( ( J  6{C D j +K89CJ J(5/ )J * s8Orct|j}d|jjd}|dk(rd}nk|dk(rdt |jdd}nIdd d d d |}|jDcgc]}d t |}}dj |}d|d|d}dj |j dDcgc]}|jc}dd}||zScc}wcc}w)Nz for :math:`x \in z`. rz@ This class accepts no distribution parameters. rpz: This class accepts one parameterization: z . twothreefourfive)rrrvz-  z This class accepts z parameterizations: )r_parameterizationsr1rrrsplitlstrip)rn_parameterizationsrr0numberrparameterizationslines rrr;s*k<<=#K$9$9$@$@#A FFa   ! [ + +A . /01   w6f= !);;=qr#a&]== II&78"8$    ii7==3FG4GKLG G =Hs 2C'C,c f|jd}dg|z}tjjd}d}|j |||}tjjd}|j }|rt |j|j}|Dcgc]}tt||d}}t||D cgc] \}} |d| } }} dd j| d } d j|jD cgc]} d |  c} } |ditt||}n|d } |}d }t|j|d}t|jd|zd}d|d| d|j!d}|r-|d dt#|jj%dz }|d|d|d|j'||j)|fdz }t+|t,r d|d}||z }|d|j/|j1|j3fd|j5|j7fd|j9|j;fdz }t+|t,r|dz }n|d|j=dz }|d t?|jAd!"d#z }d$j|jCd$Dcgc]}|jEc}d%d}|Scc}wcc} }wcc} wcc}w)&NrrClj?)rni_parameterizationllr=rrrzX.z()g{Gz?a To use the distribution class, it must be instantiated using keyword parameters corresponding with one of the accepted parameterizations. >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy import stats >>> from scipy.stats import z >>> X = a For convenience, the ``plot`` method can be used to visualize the density and other functions of the distribution. >>> X.plot() >>> plt.show() The support of the underlying distribution is available using the ``support`` method. >>> X.support() z z The numerical values of parameters associated with all parameterizations are available as attributes. >>> rzj To evaluate the probability density/mass function of the underlying distribution at argument ``x=z``: >>> x = z >>> X.pdf(x), X.pmf(x) z The cumulative distribution function, its complement, and the logarithm of these functions are evaluated similarly. >>> np.allclose(np.exp(X.logccdf(x)), 1 - X.cdf(x)) True a The inverse of these functions with respect to the argument ``x`` is also available. >>> logp = np.log(1 - X.ccdf(x)) >>> np.allclose(X.ilogcdf(logp), x) True Note that distribution functions and their logarithms also have two-argument versions for working with the probability mass between two arguments. The result tends to be more accurate than the naive implementation because it avoids subtractive cancellation. >>> y = zO >>> np.allclose(X.ccdf(x, y), 1 - (X.cdf(y) - X.cdf(x))) True z There are methods for computing measures of central tendency, dispersion, higher moments, and entropy. >>> X.mean(), X.median(), X.mode() z3 >>> X.variance(), X.standard_deviation() z) >>> X.skewness(), X.kurtosis() z >>> np.allclose(X.moment(order=6, kind='standardized'), ... X.moment(order=6, kind='central') / X.variance()**3) True zK >>> np.allclose(np.exp(X.logentropy()), X.entropy()) True z! >>> X.entropy() z Pseudo-random samples can be drawn from the underlying distribution using ``sample``. >>> X.sample(shape=(4,)) )rrz # may vary rrp)#_num_parametersr@rxry_drawr<r rrUrrlrr _parametersrrr0rrrr issubclassContinuousDistributionmeanmedianmodevariancestandard_deviationskewnesskurtosisentropyreprsamplerr)r n_parametersshapesrnrdistrRparameter_namesr_value name_values instantiationrV attributesXrrr~exampleexample_continuousrs rrrXs..q1LTL F ))   0C A   V  CD ))   +C   Dt66q9DDE+-dE'$"5q9--?,<=?[T5$q(? ?&$))K"8!9; YY$:J:JK"UG KL  G$s?4DEF G&  A affQiA affQUmQA!"&' O YY[M)G. L q}}##% &'(    C CUU1XquuQx  G"+56 " C  " %%  VVXqxxz1668#$%ZZ\1''))*+ZZ\1::< !G&+56            !(((  ! Gii7==3FG4GKLG Ny-? LlHs LL# L);L.ceZdZdZdZgZeddddZdddZdZ d Z d Z d Z d Z d ZdZedZej$dZedZej$dZedZej$dZdZdZdZdZdZdZdZdZdZdZdZd Z d!Z!d"Z"d#Z#d$Z$e% dd%Z&e%d&Z'e%dd'Z( dd)Z)dddd*d+Z*d,Z+d-Z,d.Z-e.dd/d0Z/e0dd1Z1d2Z2d3Z3d4Z4d5Z5e.dd/d6Z6e0dd7Z7d8Z8d9Z9d:Z:e.dd/d;Z;e0dd<ZZ>e.dd/d?Z?e0dd@Z@dAZAddBZBdd/dCZCdd/dDZDdd/dEZEdd/dFZFddGdHdIZGeHdd/dJZIe0dd/dKZJdLZKdMZLeHdd/dNZMe0dd/dOZNdPZOdQZPeHdd/dRZQe0dd/dSZRdTZSdUZTeHdd/dVZUe0dd/dWZVdXZWdYZXddd/dZZYeZd[Z[e0dd/d\Z\d]Z]d^Z^d_Z_d`Z`daZaeHdd/dbZbe0dd/dcZcddZddeZedfZfdgZgdhZhddd/diZieZdjZje0dd/dkZkdlZldmZmdnZndoZodpZpeHdqZqe0dd/drZrdsZsdtZtduZudvZvdwZwddd/dxZxeZdyZye0dd/dzZzd{Z{d|Z|eHdd/d}Z}e0dd~Z~dZdZdZdZdZddd/dZeZdZe0dd/dZdZdZeHdZe0ddZdZdZdZdZdZeHdd/dZe0ddZdZdZdZeHdd/dZe0ddZdZdZdZdZeHdd/dZe0ddZdZdZdZeHdd/dZe0ddZdZdZdZdZdddddZe0dZdZdZdZedZedZedZdZe.ddd/dZddd/dZdZdZdZdZddd/dZdZdZdZdZdZddd/dZdZdZdZdZdZd„ZdÄZddd(dĜdńZdƄZddddǜdȄZy)ra2 Class that represents a continuous statistical distribution. Parameters ---------- tol : positive float, optional The desired relative tolerance of calculations. Left unspecified, calculations may be faster; when provided, calculations may be more likely to meet the desired accuracy. validation_policy : {None, "skip_all"} Specifies the level of input validation to perform. Left unspecified, input validation is performed to ensure appropriate behavior in edge case (e.g. parameters out of domain, argument outside of distribution support, etc.) and improve consistency of output dtype, shape, etc. Pass ``'skip_all'`` to avoid the computational overhead of these checks when rough edges are acceptable. cache_policy : {None, "no_cache"} Specifies the extent to which intermediate results are cached. Left unspecified, intermediate results of some calculations (e.g. distribution support, moments, etc.) are cached to improve performance of future calculations. Pass ``'no_cache'`` to reduce memory reserved by the class instance. Attributes ---------- All parameters are available as attributes. Methods ------- support plot sample moment mean median mode variance standard_deviation skewness kurtosis pdf logpdf cdf icdf ccdf iccdf logcdf ilogcdf logccdf ilogccdf entropy logentropy See Also -------- :ref:`rv_infrastructure` : Tutorial Notes ----- The following abbreviations are used throughout the documentation. - PDF: probability density function - CDF: cumulative distribution function - CCDF: complementary CDF - entropy: differential entropy - log-*F*: logarithm of *F* (e.g. log-CDF) - inverse *F*: inverse function of *F* (e.g. inverse CDF) The API documentation is written to describe the API, not to serve as a statistical reference. Effort is made to be correct at the level required to use the functionality, not to be mathematically rigorous. For example, continuity and differentiability may be implicitly assumed. For precise mathematical definitions, consult your preferred mathematical text. rpN)tolr)rmc ||_||_||_d|jjd|_i|_t|jDcic] \}}||| }}}|jdi|ycc}}w)Nrz` does not provide an accurate implementation of the required method. Consider leaving `method` and `tol` unspecified to use another implementation.rC) rr)rmrOr<r\_original_parameterssortedr_update_parameters)r1rr)rmrUkeyvals rrPzUnivariateDistribution.__init__=s!2(''()L L  %'! Z--/0E8347O3hE E-*-EsA=r)c |jjx}}|jd i|d}tjd|_d|_t|_d|_ d|_ tj|_ |xs |jtk(r|jd i|}nt!|j"s3|rd|j$j&dt)|d}t+||j-|}|j/|\}}}} |j1||\}} } } |jd i|}| |_| |_||_||_ | |_ | |_ |j3||_||_||_|j4j9D]<} t;|j$| rt=|j$| t?| fd>y) a Update the numerical values of distribution parameters. Parameters ---------- **params : array_like Desired numerical values of the distribution parameters. Any or all of the parameters initially used to instantiate the distribution may be modified. Parameters used in alternative parameterizations are not accepted. validation_policy : str To be documented. See Question 3 at the top. NFrrpThe `zB` distribution family does not accept parameters, but parameters `z` were provided.cB|j|jdSrG)rrI)self_name_s rz;UnivariateDistribution._update_parameters..s$383D3DU3K3P3P3RSU3VrrC) rrIrTr@rJr_r]rr,_ndim_sizerr+r)r*_process_parametersrrrOr<rr/_identify_parameterization _broadcast _validate reset_cacher_parameterizationrhasattrsetattrproperty)r1r)rrUoriginal_parametersparameterizationrarrrndiminvalidrBrrRs rrz)UnivariateDistribution._update_parametersPs,0+D+D+I+I+KK ( #F# 5) !g   jj  7!7!7I E111?J?JT,,-"4>>#:#:";<"://?A!))( $>>zJ ,0OOJ,G )JtT/< 4Je111?J?J#DM +D DKDJDJDK %!1$7!$$))+ YDt~~t, DNND(t4W+X Y  YrcXi|_i|_i|_d|_i|_d|_y)z Clear all cached values. To improve the speed of some calculations, the distribution's support and moments are cached. This function is called automatically whenever the distribution parameters are updated. N)_moment_raw_cache_moment_central_cache_moment_standardized_cache_support_cacherj_constant_cacher:s rrz"UnivariateDistribution.reset_caches4"$%'"*,'"#rc"t|}|jD]}|j|s|S|s%d|jjd}t ||j |}d|d|jjd}t |)NrzB` distribution family requires parameters, but none were provided.zThe provided parameters `z4` do not match a supported parameterization of the `z` distribution family.)rrrrOr<_get_parameter_strr/)r1rUparameter_names_setrrars rrz1UnivariateDistribution._identify_parameterizations"*o $ 7 7 & ''(;<  &'"4>>#:#:";<''W% % #'"9"9*"E66GH#~~6677MOW% %rc^|jDcgc]}tj|}}td|D}t |dk(r-||dj |dj |djfS tj|}tt|j||dj |dj |djfScc}w#t$r?}|j|}d|d|jjd}t||d}~wwxYw)Nc34K|]}|jywrr).0r s r z4UnivariateDistribution._broadcast..sO9yOrprzThe parameters `z` provided to the `z<` distribution family cannot be broadcast to the same shape.)rr@rJrrrrrrrr/rrOr<rrr)r1rUr parameter_valsparameter_shapesr`rras rrz!UnivariateDistribution._broadcastsO ,6+<+<+>@'**Y/@@OOO  A %q 1 7 7"1%**N1,=,B,BD D -00.ANS*N;<q!''q!&&q!&&( (@ -"55jAO)/):;>>2234@@GW%1 ,  -sC?C$$ D,-:D''D,c|j|\}}|}|jdk(r|ntj|}|r8|D]3}tj||||<tj |||<5||||fSrG)r rr@r2rIrw)r1rrUrrrrBparameter_names rrz UnivariateDistribution._validates(22:> u&!("!4g"&&/ ", =-/WW~..0 >*68ff >*73 = 7K66rc |S)a/ Process and cache distribution parameters for reuse. This is intended to be overridden by subclasses. It allows distribution authors to pre-process parameters for re-use. For instance, when a user parameterizes a LogUniform distribution with `a` and `b`, it makes sense to calculate `log(a)` and `log(b)` because these values will be used in almost all distribution methods. The dictionary returned by this method is passed to all private methods that calculate functions of the distribution. rCr1rs rrz*UnivariateDistribution._process_parameterss  rcHddj|jdS)N{r})rrrs rrz)UnivariateDistribution._get_parameter_strs"DIIjoo/0144rc|jj|_tt|jD],}|j|j|j|<.yr)rrIrr)r1rs r_copy_parameterizationz-UnivariateDistribution._copy_parameterizations^"&"9"9">">"@s42234 KA)-)@)@)C)H)H)JD # #A & Krc|jS)zpositive float: The desired relative tolerance of calculations. Left unspecified, calculations may be faster; when provided, calculations may be more likely to meet the desired accuracy. )_tolr:s rrzUnivariateDistribution.tolsyyrc6t|r||_ytj|}|jdk7s3|dkDr.tj |j tjs%d|jjd}t||d|_y)NrCrzAttribute `tol` of `z)` must be a positive float, if specified.) rrr@rJrrrrrOr<r/)r1rras rrzUnivariateDistribution.tol(s| 3<DI jjo IIO37MM#))R[[9-dnn.E.E-FG<.s Ercftj|tj|dz zzSNrp)r@signr$r@s rrz0UnivariateDistribution.__pow__..s%bffQi!e).D!DrcLdz tj|dz dz zzSrD)r@r$r@s rrz0UnivariateDistribution.__pow__..s%!E'BFF1I%! ,D"Drg repr_pattern str_patternhdh increasingT) r@isscalarrr/r&rrr$r MonotonicTransformedDistribution)r1rBrarIrJrfuncss ` r__pow__zUnivariateDistribution.__pow__s{{5!UaZ5CJ3FNG%g. .__r * 9tDzl#d5k];Lc$i[CJ<8K 9aCIT) !,DDF 0LULtLL 9 9s 5CCc$|j|Sr)r4r1rBs r__radd__zUnivariateDistribution.__radd__||E""rc@|jj|Sr)__neg__r4rSs r__rsub__zUnivariateDistribution.__rsub__s||~%%e,,rc$|j|Sr)r;rSs r__rmul__zUnivariateDistribution.__rmul__rUrc |j\}}tjd5tdt |dt |dt |dt |ddd}dddtj |d k\stj |d krt|fid d i}n d }t|tj |d k(r|S||zS#1swYvxYw)Nr#r$c d|z SrDrCrAs rrz5UnivariateDistribution.__rtruediv__.. QUrz/(rc d|z SrDrCr]s rrz5UnivariateDistribution.__rtruediv__..r^rcd|dzz S)NrprrCr]s rrz5UnivariateDistribution.__rtruediv__..sQ!VrrGrrMFzjDivision by a random variable is only implemented when the support is either non-negative or non-positive.rp) r0r@r&rrrallrOr/)r1rBrMrNrPruras r __rtruediv__z#UnivariateDistribution.__rtruediv__s||~1 __r * E?)-e RT |1&E(+E |2c$i[%B*/CEE E 66!q&>RVVAF^24S5SUSCRG%g. . 66%1* J;  E Es AC##C,c tjd5tfdfdfdtdt|dt dt |d}dddtj r d ksd k(r d }t |d kDrt|fid d iSt|fid diS#1swYZxYw)Nr#r$c|zSrrCr@s rrz1UnivariateDistribution.__rpow__..s UAXrcZtj|tjz Srr@r&r@s rrz1UnivariateDistribution.__rpow__..sRVVAY%>rc`dtj|tjzz SrD)r@r$r&r@s rrz1UnivariateDistribution.__rpow__..s"a"&&RVVE]1B*C&Crz**(r)rHrKrLrIrJrrpz~Raising an argument to the power of a random variable is only implemented when the argument is a positive scalar other than 1.rMTF)r@r&rrrrNr/rO)r1rBrPras ` r__rpow__zUnivariateDistribution.__rpow__s __r * F->C)-e Sd A&F(+E |3s4yk%C FE F{{5!UaZ5A:G&g. . 193DSESdS S3DTETeT T! F Fs A B;;Cc |dzS)NryrCr:s rrWzUnivariateDistribution.__neg__s byrct|SrFoldedDistributionr:s r__abs__zUnivariateDistribution.__abs__s !$''rc|jtk(r|Stj||jd}d|j j d} t|j}|dks||k7r t|d|j j dt|d}|j|vr t||S#t$r}t||d}~wwxYw) NrrCzArgument `order` of `z,.moment` must be a finite, positive integer.rzArgument `kind` of `z.moment` must be one of r#) r)r*r@rJr+rOr<rrc Exceptionr/rr)r1orderrkindsra order_intr`s r_validate_order_kindz+UnivariateDistribution._validate_order_kinds  ! !Y .L 5 4R8*4>>+B+B*CD99 -ejjl+I a<9-W% %)$..*A*A)BC%%(ZL3 ::.f2JsQ>&>B& &rr}xl0xr0rrrlr)xrtolrfatolfrtolrMrNrlrC)rr@rrrr rrr+xlrxrflfrrrrrrrrrr)r1rQrrrrrrrIrrf3rlrrrrrs ` r_solve_boundedz%UnivariateDistribution._solve_bounded<s|17]T]],V,F d~6++AtT: 4vv-CHHQWWDKK8E$)5% !CFCE36"ENCFCF ' !V<D ]]4. d!$-S||E"||E"kk% kk% BCSt$TR )txx 5U!1E RM366SVV$M*MMrcZt|j|d}tt|d}||uSr)rlrOr)r1r8re super_methods r _overridesz!UnivariateDistribution._overrideses0d;5{DI \))rc|j |jS|jdi|j\}}|j|jk7r t j ||j}|j|jk7r t j ||j}|jrt j|jt j|j}}t jt jc||j<||j<|d|d}}||f}|jtk7r||_|SrG)rrrrr,r@r.r]rJrIrwr_rmrn)r1rMrNr0s rr0zUnivariateDistribution.supports    *&& &t}}0t//01 77dkk !4;;/A 77dkk !4;;/A   ::a=%%'A););)=qA13 .Admm a .R5!B%qAa&    )")D rc |jjj|\}}t|rvt |j }|dj }|j |k7rtj||n|}|j |k7rtj||n|}|j||j|fSr{) r1rr8rr rrr@r.ru)r1rrMrNvalsrs rrzUnivariateDistribution._supports~~$$<.logintegrands2*T**177FBFF2f9-- -rTrr&r|)rrr@rA)r1rrrIs` rrz-UnivariateDistribution._logentropy_quadratures8 .|FE$S2558^44rc>|jdd|i|jSNrerC)rrrs rrzUnivariateDistribution.entropys#%t%%HVHt7G7GHHrc |jdr|j}|S|jdr|j}|S|j}|S)Nrr)rr_entropy_logexp_entropy_quadraturers rrz(UnivariateDistribution._entropy_dispatchsT ??- .**F  __2 3))F --F rc ,t|jrrrs rrz'UnivariateDistribution._entropy_formula rrc rtjtj|jdi|SrG)r@r7r%rrs rrz&UnivariateDistribution._entropy_logexp s+wwrvv7d77A&ABCCrc 6fd}j|| S)Ncj|fi|}j|fi|}tj|}|dk7}||||z||<|Sr{) _pxf_dispatchrr@rJ)rrpxfrtemprr1s rrz=UnivariateDistribution._entropy_quadrature..integrand sb$$$$Q1&1C*T**177F::c?DA!fVAY&DGKrrr)r1rrs` rrz*UnivariateDistribution._entropy_quadrature s#   6 :::rc>|jdd|i|jSr)_median_dispatchrrs rrzUnivariateDistribution.median s#$t$$GFGd6F6FGGrc \|jdr|j}|S|j}|S)N_median_formula)rr _median_icdfrs rrz'UnivariateDistribution._median_dispatch s3 ??, -))F &&F rc ,t|jrrrs rrz&UnivariateDistribution._median_formula# rrc &|jdi|S)N)rt_icdf_dispatchrs rrz#UnivariateDistribution._median_icdf& s"t""1&11rc>|jdd|i|jSr)_mode_dispatchrrs rrzUnivariateDistribution.mode) s#"t""E&ED4D4DEErc \|jdr|j}|S|j}|S)N _mode_formula)rr_mode_optimizationrs rrz%UnivariateDistribution._mode_dispatch- s4 ??? +''F ,,F rc ,t|jrrrs rrz$UnivariateDistribution._mode_formula7 rrc \js+tjjjSj di|\}}j di|}tfdd|\}}t|||||}t||j|j|j||} tj| j} |jdk(} | |j |j"kz} | |j$|j"kz} || | | <|| | | <| dS)Nrc,j|fi| Srr)rrr1s rrz;UnivariateDistribution._mode_optimization..A s4FD4F4Fq4SF4S3SrrCr})rrrl)rlrry)rr@rr,r+rrrrrrxmrrJrstatusrfmr)r1rrrMrNmrQrlres_brIrmode_at_boundary mode_at_left mode_at_rights` rrz)UnivariateDistribution._mode_optimization: szz88DKKt{{; ;t}}&v&1 !D ! ! +F +S$&v74 AAADA$Q%((EHH*.e=zz#%%  <<2-'588uxx+?@ (EHHuxx,?@ |_\ .]Bxrc*|jdd|S)Nrprawrremomentrs rrzUnivariateDistribution.meanN s{{15{88rc*|jdd|S)Nrcentralrrrs rrzUnivariateDistribution.varianceQ s{{19V{<&{AAr non-excess)re conventioncddh}d|jjd|d}|j}||vr t||j dd|}|dk(r|d z S|S) NrexcesszParameter `convention` of `z.kurtosis` must be one of r#rrrr)rOr<rr/r)r1rer conventionsraks rrzUnivariateDistribution.kurtosisZ s}#X. 01H1H0IJ%%0M4%%' [ (W% % KKvK >"h.q1u5A5rc@|j|fd|i|jSNre)_logpdf_dispatchrr1rres rrzUnivariateDistribution.logpdf %$t$$QJvJ9I9IJJrc |jdr|j}|St|jr |j}|S)N_logpdf_formula)rrrr_logpdf_logexpr1rrers rrz'UnivariateDistribution._logpdf_dispatch ? ??, -))F TXX ((F rc ,t|jrrr1rrs rrz&UnivariateDistribution._logpdf_formula rrc Ntj|j|fi|Sr)r@r& _pdf_dispatchrs rrz%UnivariateDistribution._logpdf_logexp $vv(d((5f566rc@|j|fd|i|jSr)rrrs rrzUnivariateDistribution.pdf %!t!!!GFGd6F6FGGrc \|jdr|j}|S|j}|S)N _pdf_formula)rr _pdf_logexprs rrz$UnivariateDistribution._pdf_dispatch 2 ??> *&&F %%F rc ,t|jrrrs rrz#UnivariateDistribution._pdf_formula rrc Ntj|j|fi|Sr)r@r%rrs rrz"UnivariateDistribution._pdf_logexp $vv+d++A8899rc@|j|fd|i|jSr)_logpmf_dispatchrrs rrzUnivariateDistribution.logpmf rrc |jdr|j}|St|jr |j}|S)N_logpmf_formula)rrrr_logpmf_logexprs rrz'UnivariateDistribution._logpmf_dispatch rrc ,t|jrrrs rrz&UnivariateDistribution._logpmf_formula rrc tjd5tj|j|fi|cdddS#1swYyxYw)Nignoredivide)r@errstater& _pmf_dispatchrs rrz%UnivariateDistribution._logpmf_logexp sB [[ ) ;66,$,,Q9&9: ; ; ;s &AAc@|j|fd|i|jSr)rrrs rrzUnivariateDistribution.pmf rrc \|jdr|j}|S|j}|S)N _pmf_formula)rr _pmf_logexprs rrz$UnivariateDistribution._pmf_dispatch r rc ,t|jrrrs rrz#UnivariateDistribution._pmf_formula rrc Ntj|j|fi|Sr)r@r%rrs rrz"UnivariateDistribution._pmf_logexp r rcT||j||S|j|||Sr)rrzr1rr~res rlogcdfzUnivariateDistribution.logcdf s/ 9==6=2 2==Af=5 5rc|j||fd|i|j}tj|jtj s|dzS|S)Nrer{)_logcdf2_dispatchrr@rrcomplexfloating)r1rr~rerus rrzzUnivariateDistribution._logcdf2 sM$d$$QM&MD;'sCTZZ @ FF;K;**S/C0004!D'Q[QCI2w ;s.Cc H|j|j||fd|}|S)NT)rr&r)rr)r1rr~rlogress rr-z*UnivariateDistribution._logcdf2_quadrature s/!!$"7"7A&*6"; rc@|j|fd|i|jSr)r4rrs rrzUnivariateDistribution._logcdf1 rrc |jdr|j}|S|jdr|j}|S|jdr|j}|S|j}|S)Nr'r(r))rr'_logcdf_complement_logcdf_logexp_safe_logcdf_quadraturers rr4z'UnivariateDistribution._logcdf_dispatch st ??, -))F __/ 0,,F  __^ ,--F ,,F rc ,t|jrrrs rr'z&UnivariateDistribution._logcdf_formula% rrc :t|j|fi|Sr)rr5rs rrJz)UnivariateDistribution._logcdf_complement( s ///;'sCrsDJJ?EE;K;**S/C///$G;GCI2w ;.B5c n|jdi|\}}|j|j||f|dSNT)rrr&rCrrrr1rrrM_s rrLz)UnivariateDistribution._logcdf_quadrature8 Dt}}&v&1 5 5q!f'-4 9 9rcT||j||S|j|||Sr)r rvr s rcdfzUnivariateDistribution.cdf= s/ 9::a:/ /::a6:2 2rcB|j||fd|i|jSr)rBrr s rrvzUnivariateDistribution._cdf2C s'"t""1aKK$:J:JKKrc |jdr|j}|S|jds|jdr|j}|S|jds|jdr|j}|S|j}|S)N _cdf2_formular'r(r)r*)rr_ _cdf2_logexp_cdf2_subtraction_safe_cdf2_quadraturer.s rrBz%UnivariateDistribution._cdf2_dispatchG s ??? +''F oo/0!34&&F  __^ ,0P00F **F rc ,t|jrrr0s rr_z$UnivariateDistribution._cdf2_formulaU rrc vtjtj|j||fi|Sr)r@r7r%r#r0s rr`z#UnivariateDistribution._cdf2_logexpX s/wwrvv4d44QDVDEFFrc |j|fi|}|j|fi|}|j|fi|}|j|fi|}|dk|dkz}tj|||z ||z SNrt)rP_ccdf_dispatchr@r) r1rr~rcdf_xcdf_yccdf_xccdf_yrs r_cdf2_subtractionz(UnivariateDistribution._cdf2_subtraction[ s#""1//"""1//$$$Q1&1$$$Q1&1 c\fsl +xx6&=%+66rc |j|fi|}|j|fi|}|j|fi|}|j|fi|}|dk|dkz}tj|||z ||z } tj|j j } t|js |jntj| } tj||} tj||} tjtj|| | }tj| | z|k}tj|rv|jDcic])\}}|tj||j |+}}}tj"| } |j$||||fi|| |<| dScc}}w)NrtrC)rPrgr@rrr+epsrrrr3spacingr$r2rr.rrJrb)r1rr~rrhrirjrkrrurnrcdf_maxccdf_maxrorrrrs rraz-UnivariateDistribution._cdf2_subtraction_safef s"""1//"""1//$$$Q1&1$$$Q1&1 c\fsl +hhq&-u5hht{{#''%dhh/dhhRWWS\**UE*::ff-**RXXa7;<vvcCi 7* 66$<+1<<>;'sCTZZ @ FF;K;**S/C---agqwN+NCI2w ;s-.Gc B|j|j||f|S)Nrr)rrr0s rrbz'UnivariateDistribution._cdf2_quadrature} s$ 2 2Aq6&QQrc@|j|fd|i|jSr)rPrrs rr zUnivariateDistribution._cdf1 rrc |jdr|j}|S|jdr|j}|S|jdr|j}|S|j}|S)Nr)r'r*)rr) _cdf_logexp_cdf_complement_safe_cdf_quadraturers rrPz$UnivariateDistribution._cdf_dispatch ss ??> *&&F __. /%%F  ___ -..F ))F rc ,t|jrrrs rr)z#UnivariateDistribution._cdf_formula rrc Ntj|j|fi|Sr)r@r%r4rs rrvz"UnivariateDistribution._cdf_logexp r rc .d|j|fi|z SrD)rgrs r_cdf_complementz&UnivariateDistribution._cdf_complement s &4&&q3F333rc J|j|fi|}d|z }tj|jj}t |j s |j ntj|}||ztj|k}tj|rr|jD cic])\}} |tj| |j|+} }} tj|}|j||g| ||<|dScc} }wNrprC)rgr@rr+rnrrrror2rr.rrJrx) r1rrr&rurnrrrrrs rrwz+UnivariateDistribution._cdf_complement_safe s"t""1//$hhht{{#''%dhh/dhhRWWS\Sy2::d++ 66$<+1<<>;'sCTZZ @ FF;K;**S/C,,,QtWC{CCI2w ;;.Dc l|jdi|\}}|j|j||f|SNrsrCrrrrXs rrxz&UnivariateDistribution._cdf_quadrature Bt}}&v&1 2 2Aq6'- / /rcT||j||S|j|||Sr)r _logccdf2r s rlogccdfzUnivariateDistribution.logccdf s/ 9>>!F>3 3>>!Qv>6 6rcB|j||fd|i|jSr)_logccdf2_dispatchrr s rrz UnivariateDistribution._logccdf2 s'&t&&q!OFOd>N>NOOrc \|jdr|j}|S|j}|S)N_logccdf2_formula)rr_logccdf2_additionr.s rrz)UnivariateDistribution._logccdf2_dispatch s5 ??. /++F ,,F rc ,t|jrrr0s rrz(UnivariateDistribution._logccdf2_formula rrc |j|fi|}|j|fi|}tj||gdS)Nrr)r4r5r r)r1rr~rr8r;s rrz)UnivariateDistribution._logccdf2_addition sH(4((5f5*D**177   (I!6Q??rc@|j|fd|i|jSr)r5rrs rrz UnivariateDistribution._logccdf1 s%%t%%aKK$:J:JKKrc |jdr|j}|S|jdr|j}|S|jdr|j}|S|j}|S)Nr(r'r*)rr(_logccdf_complement_logccdf_logexp_safe_logccdf_quadraturers rr5z(UnivariateDistribution._logccdf_dispatch st ??- .**F __. /--F  ___ -..F --F rc ,t|jrrrs rr(z'UnivariateDistribution._logccdf_formula rrc :t|j|fi|Sr)rr4rs rrz*UnivariateDistribution._logccdf_complement s ...q;F;<;'sCTZZ @ FF;K;**S/C0004HKHCI2w ;rTc n|jdi|\}}|j|j||f|dSrVrWr1rrrYrNs rrz*UnivariateDistribution._logccdf_quadrature rZrcT||j||S|j|||Sr)r!rwr s rr&zUnivariateDistribution.ccdf s/ 9;;q;0 0;;q!F;3 3rcB|j||fd|i|jSr)_ccdf2_dispatchrr s rrwzUnivariateDistribution._ccdf2 s'#t##AqLL4;K;KLLrc \|jdr|j}|S|j}|S)N_ccdf2_formula)rr_ccdf2_additionr.s rrz&UnivariateDistribution._ccdf2_dispatch s3 ??+ ,((F ))F rc ,t|jrrr0s rrz%UnivariateDistribution._ccdf2_formula rrc X|j|fi|}|j|fi|}||zSr)rPrg)r1rr~rrhrks rrz&UnivariateDistribution._ccdf2_addition s:"""1//$$$Q1&1v~rc@|j|fd|i|jSr)rgrrs rr!zUnivariateDistribution._ccdf1 %"t""1HVHt7G7GHHrc |jdr|j}|S|jdr|j}|S|jdr|j}|S|j}|S)Nr*r(r))rr* _ccdf_logexp_ccdf_complement_safe_ccdf_quadraturers rrgz%UnivariateDistribution._ccdf_dispatch ss ??? +''F __/ 0&&F  __^ ,//F **F rc ,t|jrrrs rr*z$UnivariateDistribution._ccdf_formula rrc Ntj|j|fi|Sr)r@r%r5rs rrz#UnivariateDistribution._ccdf_logexp s$vv,d,,Q9&9::rc .d|j|fi|z SrD)rPrs r_ccdf_complementz'UnivariateDistribution._ccdf_complement s %4%%a26222rc J|j|fi|}d|z }tj|jj}t |j s |j ntj|}||ztj|k}tj|rr|jD cic])\}} |tj| |j|+} }} tj|}|j||fi| ||<|dScc} }wr~)rPr@rr+rnrrrror2rr.rrJr) r1rrr\rurnrrrrrs rrz,UnivariateDistribution._ccdf_complement_safe# s d  -f-#ghht{{#''%dhh/dhhRWWS\Sy2::c?* 66$<+1<<>;'sCTZZ @ FF;K;**S/C---agEECI2w ;rc l|jdi|\}}|j|j||f|Srrrs rrz'UnivariateDistribution._ccdf_quadrature0 rrc@|j|fd|i|jSr)_ilogcdf_dispatchrr1logpres rrzUnivariateDistribution.ilogcdf7 s%%t%%dN6NT=M=MNNrc |jdr|j}|S|jdr|j}|S|j}|S)N_ilogcdf_formula_ilogccdf_formula)rr_ilogcdf_complement_ilogcdf_inversionrs rrz(UnivariateDistribution._ilogcdf_dispatch; sT ??- .**F  __0 1--F ,,F rc ,t|jrrrs rrz'UnivariateDistribution._ilogcdf_formulaE rrc :|jt|fi|Sr)_ilogccdf_dispatchrrs rrz*UnivariateDistribution._ilogcdf_complementH s&t&&y|>v>>rc >|j|j||SNr)_solve_bounded_continuousr4rs rrz)UnivariateDistribution._ilogcdf_inversionK s --d.C.CQv-VVrc@|j|fd|i|jSr)rrr1rres rrzUnivariateDistribution.icdfN rrc |jdr|j}|S|jdr|j}|S|j}|S)N _icdf_formula_iccdf_formula)rr_icdf_complement_safe_icdf_inversionrs rrz%UnivariateDistribution._icdf_dispatchR sS ??? +''F  __- .//F ))F rc ,t|jrrrs rrz$UnivariateDistribution._icdf_formula\ rrc .|jd|z fi|SrD)_iccdf_dispatchrs r_icdf_complementz'UnivariateDistribution._icdf_complement_ s#t##AE4V44rc F|j|fi|}tj|jj}t |j s |j ntj|}||ztjd|z k}tj|rr|jDcic])\}}|tj||j|+} }}tj|}|j||g| ||<|dScc}}wr~)rr@rr+rnrrrror2rr.rrJr r1rrrurnrrrrrs rrz,UnivariateDistribution._icdf_complement_safeb s#d##A00hht{{#''%dhh/dhhRWWS\QwAE** 66$<+1<<>;'sCTZZ @ FF;K;**S/C,,,QtWC{CCI2w ;9.Dc >|j|j||Sr)rrPrs rrz&UnivariateDistribution._icdf_inversionn s --d.@.@!F-SSrc@|j|fd|i|jSr)rrrs rrzUnivariateDistribution.ilogccdfq s%&t&&tOFOd>N>NOOrc |jdr|j}|S|jdr|j}|S|j}|S)Nrr)rr_ilogccdf_complement_ilogccdf_inversionrs rrz)UnivariateDistribution._ilogccdf_dispatchu sT ??. /++F  __/ 0..F --F rc ,t|jrrrs rrz(UnivariateDistribution._ilogccdf_formula rrc :|jt|fi|Sr)rrrs rrz+UnivariateDistribution._ilogccdf_complement s%t%%il=f==rc >|j|j||Sr)rr5rs rrz*UnivariateDistribution._ilogccdf_inversion s!--d.D.DaPV-WWrc@|j|fd|i|jSr)rrrs rrzUnivariateDistribution.iccdf s%#t##AIfI8H8HIIrc |jdr|j}|S|jdr|j}|S|j}|S)Nrr)rr_iccdf_complement_safe_iccdf_inversionrs rrz&UnivariateDistribution._iccdf_dispatch sS ??+ ,((F  ___ -00F **F rc ,t|jrrrs rrz%UnivariateDistribution._iccdf_formula rrc .|jd|z fi|SrDrrs r_iccdf_complementz(UnivariateDistribution._iccdf_complement s"t""1q53F33rc F|j|fi|}tj|jj}t |j s |j ntj|}||ztjd|z k}tj|rr|jDcic])\}}|tj||j|+} }}tj|}|j||g| ||<|dScc}}wr~)rr@rr+rnrrrror2rr.rrJrrs rrz-UnivariateDistribution._iccdf_complement_safe s$d$$Q1&1hht{{#''%dhh/dhhRWWS\QwAE** 66$<+1<<>;'sCTZZ @ FF;K;**S/C---agD DCI2w ;rc >|j|j||Sr)rrgrs rrz'UnivariateDistribution._iccdf_inversion s --d.A.A1V-TTrrerncVtj|s|fn t|}||jz}t |t j stjj|n|}|j|f||d|j}|j|jdS)NrFr%) r@rrr,rzr QMCEnginerxryrirr^r+)r1rrern sample_shape full_shaperIs rrzUnivariateDistribution.sample s(*{{5'9xuU| !DKK/ 0:3 0Nbii##C(TW#d##J8v38&*&6&68zz$++Ez22rc |jdr(t|tjs|j}|S|j }|S)N_sample_formula)rrzrrr_sample_inverse_transform)r1rrernrs rriz'UnivariateDistribution._sample_dispatch sB ??, -jcmm6T))F 33F rc ,t|jrr)r1rrnrs rrz&UnivariateDistribution._sample_formula rrc t|tjr|j|fd|i|}n|j ||j }|j |fi|S)Nqrng)rrr)rzrr _qmc_uniformrxr+r)r1rrnrr|s rrz0UnivariateDistribution._sample_inverse_transform sZ c3== )'d'' GGGGjjj jDG"t""75f55rc |dt|t|jz }|r|dnd}tj|r|ddn|}t |j |}|j }td|j|j} t|tjr|j| d<g} |D]F} |dd| i| }|j|} | j|r|ndd} | j!| H| r*t#j$t#j&| ddnt#j(g} | j|S)Nrrp)dscramble optimizationbitsseedrCry)rr,mathrrrnrOrr _optimizationrzrSobolrrxrrr@rstackrJ) r1rrrrn_low_discrepancy n_independentrngs qrng_classrmuniformsrnr|s rrz#UnivariateDistribution._qmc_uniform s-""C3z?3t{{3C#CD /;LO L*QR.jQ $((M2^^ DMM@R@RS dCII &!YYF6N %C131&1Dkk"34Goo<&7RPQSTG OOG $  %=E"++bhhx0"a8"**UW.z**rc hdS)N>cacheformulageneral normalize transform quadraturerCr:s r_moment_methodsz&UnivariateDistribution._moment_methods( s 6 6rc(|jdSr{ _constantsr:s r_zerozUnivariateDistribution._zero-  ##rc(|jdSrDrr:s r_onezUnivariateDistribution._one1 rrc|j |jS|jddg}|jtk7r||_|SNrrp)rrurmrn)r1 constantss rrz!UnivariateDistribution._constants5 sJ    +'' '''A/    )#,D rc|j|j|jd}|j|||}||}|||S)Nrrrrd) _moment_raw_moment_central_moment_standardizedrsr1rprrerq moment_kinds rrzUnivariateDistribution.moment@ sP(( 00!%!:!:<))%u=Dk 500rcb| |jn|h}|j|fd|i|jS)z)Raw distribution moment about the origin.methods)r_moment_raw_dispatchrr1rprers rr z"UnivariateDistribution._moment_rawI s: +1.$&&vh(t((TT4CSCSTTrc d}d|vr|jj|d}|d|vr|j|fi|}|d|vr|dkDr|j|fi|}|d|vr|j|fi|}|#d|vr|j |fd|j i|}|#d|vr|j|fd|j i|}|"|jtk7r||j|<|S) Nrrrrprrcenterquadrature_icdf) rr]_moment_raw_formula_moment_raw_transform_moment_raw_general_moment_from_pxfr_moment_integrate_icdfrmrnr1rprrrs rrz+UnivariateDistribution._moment_raw_dispatchQ s g ++//ti72-T--e>v>F >kW4/T//@@F >i72-T--e>v>F >lg5*T**5NNvNF >/7:0T00TtzzTVTF  $"3"3y"@,2D " "5 ) rc yrrCr1rprs rrz*UnivariateDistribution._moment_raw_formulak rc &g}tt|dzD]0}hd}|jd||d|}|y|j|2hd}|j|j fd|i|}|y|j ||||j} | S)Nrp>rrrrrpr>rrrrrC)rr_moment_central_dispatchrrr_moment_transform_centerr) r1rprcentral_momentsrrmoment_i mean_methodsrrs rrz,UnivariateDistribution._moment_raw_transformn ss5zA~& -ABG4t44X1gXQWXH  " "8 ,  -: (t((SLSFS <..uotTZZX rc (|dk(r |jSdSr{)rrs rrz*UnivariateDistribution._moment_raw_general s"QJtyy0D0rcb| |jn|h}|j|fd|i|jS)z#Distribution moment about the mean.r)rr"rrs rr z&UnivariateDistribution._moment_central s8*0.$&&vh,t,,UXGXtGWGWXXrc |d}d|vr|jj|d}|d|vr|j|fi|}|d|vr|j|fi|}|d|vr|dkDr|j|fi|}|d|vr|j |fi|}|Dd|vr@|j |jfi|d|ji}|j|fd |i|}|Dd |vr@|j |jfi|d|ji}|j|fd |i|}|"|jtk7r||j|<|S) Nrrrrrrrrrr) rr]_moment_central_formula_moment_central_transform_moment_central_normalize_moment_central_generalrrrrrrmrn)r1rprrrrs rr"z/UnivariateDistribution._moment_central_dispatch s g //33E4@F >i721T11%B6BF >kW43T33EDVDF >kW43T33EDVDF >i721T11%B6BF >lg5,4,,TYYK&K595I5IKD*T**5HHHF >/7:,4,,TYYK&K595I5IKD0T00NtNvNF  $"3"3y"@06D & &u - rc yrrCrs rr*z.UnivariateDistribution._moment_central_formula rrc 0g}tt|dzD]0}hd}|jd||d|}|y|j|2|j}|j|j fd|i|}|j |||j|} | S)Nrp>rrrr!rrC)rrrrrrr#r) r1rpr raw_momentsrrr%r&rrs rr+z0UnivariateDistribution._moment_central_transform s s5zA~& )A5G0t00Tq'TVTH   x (  )++ (t((SLSFS..uk4::tT rc hd}|j|fi|d|i}|y|jdd|ji|}|||dz zzS)N>rrrrrr)_moment_standardized_dispatchr"r)r1rprrstandard_momentvars rr,z0UnivariateDistribution._moment_central_normalize si1<$<i726T66uGGF >kW48T88PPF >i726T66uGGF >kW48T88OOF  $"3"3y"@5;D + +E 2 rc yrrCrs rr;z3UnivariateDistribution._moment_standardized_formula rrc |rdhnhd}|j|fi|d|i}|y|jdd|ji|}|||dz zz S)Nr>rrrrrr2)r"r)r1rpuse_quadraturerrcentral_momentr5s rr<z5UnivariateDistribution._moment_standardized_normalize sz%3L>9 666uHH?FH  !+d++6t7K7K6.46cE!Gn,,rc n|j|j|jd}|j|dS)N)rrprr7)r1rprgeneral_standard_momentss rr=z3UnivariateDistribution._moment_standardized_general s.'+yyTZZDII#N '++E488rc :fd}j|||f|S)Nc@j|fi|}|||z |zzSrr)rrprrrr1s rrz:UnivariateDistribution._moment_from_pxf..integrand s.$$$$Q1&1C&5(( (r)rlrrr1rprrrs` rrz'UnivariateDistribution._moment_from_pxf s& ) OOrc <fd}j|d||f|S)Nc:j|fi|}||z |zSrr)rrprrr1s rrz@UnivariateDistribution._moment_integrate_icdf..integrand s)###A00AfHu$ $r)r'r()rrlrrrFs` rrz-UnivariateDistribution._moment_integrate_icdf s1 % (&+V_V E Erctj||g|^}}}|}tj|dzjdgdg|jzz}|j |}t j||}tjd5tj||z||z ||z zzd}ddd|S#1swYSxYw)Nrpryr)rrr) r@rarangerrrur binomrr) r1rp moment_asrMrNr5r n_choose_imoment_bs rr#z/UnivariateDistribution._moment_transform_center s..q!@i@1y  IIacN " "B4AFF ? 3    "]]1a( [[ * Ivvj2AaC1Q3<?aHH I Is 'CC) logcenterrc$||dur8|j|jtj fi|j}nd}||n|}|j||fi|j}|r)|jd|fi|j}|||dz zz }|S)NTr)_logmoment_quadrr@rr)r1rprOrlogmeanrIlogvars r _logmomentz!UnivariateDistribution._logmoment s    4*d**499rvvgRAQAQRGG(0Gi "d""5)Ht7G7GH )T))!WI8H8HIF%'**C rc <fd}j|||f|dS)Nczj|fi|}||ttj|dz|zzSr)rr}r@r&)rrprOrrr1s rrz.logintegrand! s=*T**177FEM"&&R.)$LLL LrT)rlrr&r)r1rprOrrs` rrQz&UnivariateDistribution._logmoment_quad s1 M E93E'-4 9 9r)taxc : t|t}hd}hd}|j|}|jhd} |rdnd} || n|}|j} ||} } |dn|d}|j \}}t j t j|rdnd }||n|d }t j t j|rd nd }||n|d }t j||g}| r|ddt jfn|}d |jjd|}||vr t|d|jjd| }| | vr t|d|jjd| }| | vr t|d|jjd}|jr t|d}| d kDr t| ddlm}||j#n|}||vr|nt%|d|z|}d|jjdd|zd|d|d }t j t j|s t||re| |vrat j&t j(|dt j*|d d z}| r|ddt jfn|}n_t j,dd d}| r|ddt jfn|}|d|d |dz |zz}|rt j.|n|}| |vr|nt%|| |}| |vr|nt%|| |}t j0|j2t j4|j2\}}t7||D]\}}|rA| |vr=| dk(r8|j9||t j:d |j<dz I|r9| |vr5|}t j>||dd zgf}|jA||d|jC|||jEd| d|jGd| d|jItK|tM|jNrg} |jPjR}!tU|!}"|"D#cgc]$}#t jV|jN|#&}$}#t7|$D]T}%t7|"|%D&'cgc]\}&}'d|!|&jXd |'d!}(}&}'| j[d"j]|(V|j_| |S#t $r+}d|jjd}t!||d}~wwxYwcc}#wcc}'}&w)#a& Plot a function of the distribution. Convenience function for quick visualization of the distribution underlying the random variable. Parameters ---------- x, y : str, optional String indicating the quantities to be used as the abscissa and ordinate (horizontal and vertical coordinates), respectively. Defaults are ``'x'`` (the domain of the random variable) and either ``'pdf'`` (the probability density function) (continuous) or ``'pdf'`` (the probability density function) (discrete). Valid values are: 'x', 'pdf', 'pmf', 'cdf', 'ccdf', 'icdf', 'iccdf', 'logpdf', 'logpmf', 'logcdf', 'logccdf', 'ilogcdf', 'ilogccdf'. t : 3-tuple of (str, float, float), optional Tuple indicating the limits within which the quantities are plotted. The default is ``('cdf', 0.0005, 0.9995)`` if the domain is infinite, indicating that the central 99.9% of the distribution is to be shown; otherwise, endpoints of the support are used where they are finite. Valid values are: 'x', 'cdf', 'ccdf', 'icdf', 'iccdf', 'logcdf', 'logccdf', 'ilogcdf', 'ilogccdf'. ax : `matplotlib.axes`, optional Axes on which to generate the plot. If not provided, use the current axes. Returns ------- ax : `matplotlib.axes` Axes on which the plot was generated. The plot can be customized by manipulating this object. Examples -------- Instantiate a distribution with the desired parameters: >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy import stats >>> X = stats.Normal(mu=1., sigma=2.) Plot the PDF over the central 99.9% of the distribution. Compare against a histogram of a random sample. >>> ax = X.plot() >>> sample = X.sample(10000) >>> ax.hist(sample, density=True, bins=50, alpha=0.5) >>> plt.show() Plot ``logpdf(x)`` as a function of ``x`` in the left tail, where the log of the CDF is between -10 and ``np.log(0.5)``. >>> X.plot('x', 'logpdf', t=('logcdf', -10, np.log(0.5))) >>> plt.show() Plot the PDF of the normal distribution as a function of the CDF for various values of the scale parameter. >>> X = stats.Normal(mu=0., sigma=[0.5, 1., 2]) >>> X.plot('cdf', 'pdf') >>> plt.show() >rrrrr>r\r&r!r>rrrrrrNr\rgMb@?rpgCl?rzArgument `t` of `z.plot` "must be one of zArgument `x` of `zArgument `y` of `rz.plot` was called on a random variable with at least one invalid shape parameters. When a parameter is invalid, no plot can be shown.z^To use `plot`, distribution parameters must be scalars or arrays with one or fewer dimensions.z'`matplotlib` must be installed to use `z.plot`.rz/.plot` received invalid input for `t`: calling rz ) produced r#i,)alphary)baseline$z$ = z.4gr)0rzr-unionrr0r@rarrJnewaxisrOr<r/r]matplotlib.pyplotpyplotModuleNotFoundErrorgcarlrJrrlinspacerrT atleast_2drbarrrrstairsplot set_xlabel set_ylabel set_titlerrrrrUr rrSrrlegend))r1rr~rWrXr9 t_is_quantilet_is_probabilityvalid_tvalid_xy y_defaultrx_namey_namet_namerMrN tliml_defaulttliml tlimr_defaulttlimrtlimrapltexcqlimqgridxiyiredgeslabelrU param_namespname param_arrays param_valsrRr assignmentss) rrhzUnivariateDistribution.plot2 s`d$89E ?%%&67MM"DE%E5 IzzA)1||~1VVBKKN3 !" !VVBKKN3 !" !zz5%.)&*tArzzM"'t~~'>'>&?@%%,I/  W% %&t~~'>'>&?@%%-J0  !W% %&t~~'>'>&?@%%-J0  !W% %t~~../0CC   W% %E !8W% % 8 + *SWWY".t4MGD#f*4Md4St~~../0!&j\4& D6Dvvbkk$'(W% % -/ "&&a/266$q'?Q+>?A$(!RZZ- aA;;q!S)D*.42:: &DDQ47T!W,44A' QA=(A.CgdF.CA.F=(A.CgdF.CA.F""133 acc(:;1!Qi FBFm3%r2RWWQqwwqz\%:;f 5RVAXJ'78 &%$ 7B  &m$ &m$ SY t E//::Jz*K)46 %MM$*:*:5*AB6L6!<0 5 03K0LN#,4"#:d#3#:#:";4CyIN N TYY{34 5 IIe  u# 8>>2237)V V V$&V  V)NNNN)r)NNNFrrCrprr)rN)r<r=r>r?__array_priority__r_nullrPrrrrrrrrrrsetterrmr)r+r;r4r6r;r=rQrTrXrZrbrhrWrmrsru classmethodrrwrrrrr0rrbrrsrrrrrrrrrrrrrrrrrrrrrrrrYrrrrrrrrrrrrrrrrr!rrzr#r&r+rDr,r-rr4r'rJrQrKrLr\rvrBr_r`rlrarbr rPr)rvr|rwrxrrrrrrr5r(rrrrr&rwrrrr!rgr*rrrrrrrrrrrrrrrrrrrrrrrrrrrrirrrrrrrrrr rrrrr r"r*r+r,r-r r3r;r<r=rrr#rTrQrhrCrrrrs Tj$t$.&7;JYX$* >!(F7& 5K ZZ  ""** ' '442"289<>M(#-#$U&(8<@!!$++FF8<%*@.2$d%NR*T4 >#'QQ9*5 $II9D;#HH92!FF9("9"&=,05"&B"&,6Z%)KK,097"&HH)-9:%)KK,09;"&HH)-9: 6T6 WW04  9H"  $(KK,0  9>79 3$3 LL-1  9G 7.RHH)-  9:4 / 7d7 PP159@ %)LL  9=89 444 MM.29 II  9;3 /)-OO9?W#'II95 T*.PP9>X$(JJ94 UB 34 396+B66$$$$ 1D11UTU4&1 YY B .8FdF . -9P E t% 9$}t}rrcJeZdZfdZdZdZdddZdddZd dZxZ S) rc,|dvryt||S)N>rrTrHrr1r8rOs rrz!ContinuousDistribution._overrides = =w!+..rc ,tj|Sr)r@ zeros_likers rrz#ContinuousDistribution._pmf_formulas}}Qrc Ltj|tj Sr)r@rrrs rrz&ContinuousDistribution._logpmf_formulas||Aw''rNrdc ,|j|fd|i|Sr)rrs rrz$ContinuousDistribution._pxf_dispatch!t!!!=F=f==rc ,|j|fd|i|Sr)rrs rrz'ContinuousDistribution._logpxf_dispatch$t$$Q@v@@@rc@|j||||jS)Nrr)rr)r1funcrrrs rrz0ContinuousDistribution._solve_bounded_continuous!s"""46"GIIIrr) r<r=r>rrrrrrrrs@rrrs-/  (*.>-1AJrrceZdZfdZdZdZdddZdddZfdZfd Z fd Z fd Z d Z d Z dZdZdZdZdZdZdZdZfdZdZxZS)r-c,|dvryt||S)N>rrTrrs rrzDiscreteDistribution._overrides&rrc 2|rNtt|j}tj|tj|z}ntj|}tj |tj tjSrnextiterrr@r}rrwrr1rrr nan_results rrz$DiscreteDistribution._logpdf_formula+\ T&--/*+A!rxx{2J!Jxx BFFBFF33rc 2|rNtt|j}tj|tj|z}ntj|}tj |tj tjSrrrs rrz!DiscreteDistribution._pdf_formula3rrNrdc ,|j|fd|i|Sr)rrs rrz"DiscreteDistribution._pxf_dispatch;rrc ,|j|fd|i|Sr)rrs rrz%DiscreteDistribution._logpxf_dispatch>rrc Jt|tj|fi|Sr)rHrxr@r3r1rrrOs rrxz$DiscreteDistribution._cdf_quadratureAs w&rxx{=f==rc Jt|tj|fi|Sr)rHrLr@r3rs rrLz'DiscreteDistribution._logcdf_quadratureDs w)"((1+@@@rc Pt|tj|dzfi|SrD)rHrr@r3rs rrz%DiscreteDistribution._ccdf_quadratureGs$w'QB6BBrc Pt|tj|dzfi|SrD)rHrr@r3rs rrz(DiscreteDistribution._logccdf_quadratureJs$w*288AE?EfEErctdNzUTwo argument cdf functions are currently only supported for continuous distributions.r.r s rrvzDiscreteDistribution._cdf2M! () )rctdrr.r s rrwzDiscreteDistribution._ccdf2Rrrctdrr.r s rrzzDiscreteDistribution._logcdf2Wrrctdrr.r s rrzDiscreteDistribution._logccdf2\rrc|j|||d}tjtj|j}|j dk(}tj|j |||<|jdi|\}} tj||| \}}} |||fi||}||||<|S)N?rrrC) rr@rJr3rfunrrr) r1rrrcomprIrrrrs r_solve_bounded_discretez,DiscreteDistribution._solve_bounded_discreteas!!$&!D JJrxx' (ww!|((355;'$"T]],V, d++AtT: 4D((!,t*$rc |j||||}||fi|}tj|||||dz}tj|tj|tj|z<|dS)N)rrr(rC)rr@rrwr})r1rrrrrrQrIs r_base_discrete_inversionz-DiscreteDistribution._base_discrete_inversionqsv  ( (qd ( K  f hhtAqz1a#g.*,BHHQK"((1+ %&2wrc \|j||jtjfi|Sr)rrPr@ greater_equalrs rrz$DiscreteDistribution._icdf_inversions5,t,,Q0B0B-/-=-=IAGI Irc \|j||jtjfi|Sr)rr4r@rrs rrz'DiscreteDistribution._ilogcdf_inversions5,t,,Q0E0E-/-=-=IAGI Irc \|j||jtjfi|Sr)rrgr@ less_equalrs rrz%DiscreteDistribution._iccdf_inversions3,t,,Q0C0C-/]]F>DF Frc \|j||jtjfi|Sr)rr5r@rrs rrz(DiscreteDistribution._ilogccdf_inversions3,t,,Q0F0F-/]]F>DF Frc t |dddi|}|j\}}tj|tj |}}tj |}tj|tjd||z z||}tj|||g}tj|j|fi|d} tj| |||gS)NrrtrprrrC) rHrr0r@r3ceilrr6copysignrargmaxrchoose) r1rrr;r<rrnearestxoidxrOs rrz'DiscreteDistribution._mode_optimizations G & ;S ;F ;LLN T!bggajB((1+WWWr{{1gk::C F HHb"b\ "ii***177a@yyr2rl++rc 6fd}j||dS)Ncj|fi|}tjtj||tj| ztj Sr)rr@rrr&r)rrrr1s rrzADiscreteDistribution._logentropy_quadrature..logintegrandsM*T**177F 88BKK/"&&&/1IBFF7S SrTrr)r1rrs` rrz+DiscreteDistribution._logentropy_quadratures# T VFFr)r<r=r>rrrrrrxrLrrrvrwrzrrrrrrrrrrrs@rr-r-%s/ 44*.>-1A>ACF) ) ) )  *IIFF,( Grr-argusARGUS betaprime BetaPrimechi2 ChiSquared crystalball CrystalBalldgamma DoubleGammadweibull DoubleWeibullexpon Exponential exponnormExponentiallyModifiedNormal exponweibExponentialWeibullexponpowExponentialPower fatiguelife FatigueLife foldcauchy FoldedCauchyfoldnorm FoldedNormal genlogisticGeneralizedLogisticgennormGeneralizedNormal genparetoGeneralizedParetogenexponGeneralizedExponential genextremeGeneralizedExtremeValue gausshyperGaussHypergeometricgengammaGeneralizedGammagenhalflogisticGeneralizedHalfLogistic geninvgaussGeneralizedInverseGaussiangumbel_rGumbelgumbel_lReflectedGumbel halfcauchy HalfCauchy halflogistic HalfLogistichalfnorm HalfNormal halfgennormHalfGeneralizedNormal hypsecantHyperbolicSecantinvgamma InverseGammmainvgaussInverseGaussian invweibullInverseWeibull irwinhall IrwinHall jf_skew_tJonesFaddySkewT johnsonsb JohnsonSB johnsonsu JohnsonSUksone KSOneSidedkstwo KSTwoSided kstwobignKSTwoSidedAsymptoticlaplace_asymmetricLaplaceAsymmetriclevy_lLevyLeft levy_stable LevyStableloggammaExpGamma loglaplace LogLaplacelognorm LogNormal loguniform LogUniformncx2NoncentralChiSquarednct NoncentralTnormNormal norminvgaussNormalInverseGaussianpowerlawPowerLaw powernorm PowerNormalrdistRrel_breitwignerRelativisticBreitWigner recipinvgaussReciprocalInverseGaussian reciprocal semicircular SemiCircular skewcauchy SkewCauchyskewnorm SkewNormalstudentized_rangeStudentizedRangerWStudentT trapezoid Trapezoidaltriang Triangular truncexponTruncatedExponential truncnormTruncatedNormal truncparetoTruncatedParetotruncweibull_minTruncatedWeibull tukeylambda TukeyLambda vonmises_line VonMisesLine weibull_minWeibull weibull_maxReflectedWeibull wrapcauchyWrappedCauchyLine betabinom BetaBinomial betanbinomBetaNegativeBinomialdlaplaceLaplaceDiscretegeom Geometric hypergeomHypergeometriclogserLogarithmicSeriesnbinomNegativeBinomialnchypergeom_fisherNoncentralHypergeometricFishernchypergeom_wallenius!NoncentralHypergeometricWallenius nhypergeomNegativeHypergeometric poisson_binomPoissonBinomialrandintUniformDiscrete yulesimon YuleSimonzipfZetac|tjtjtjtjtj tj hvrtd|jdt|tjtjzr t|St|dddk\r t|Sd}t|)a&Generate a `UnivariateDistribution` class from a compatible object The argument may be an instance of `rv_continuous` or an instance of another class that satisfies the interface described below. The returned value is a `ContinuousDistribution` subclass if the input is an instance of `rv_continuous` or a `DiscreteDistribution` subclass if the input is an instance of `rv_discrete`. Like any subclass of `UnivariateDistribution`, it must be instantiated (i.e. by passing all shape parameters as keyword arguments) before use. Once instantiated, the resulting object will have the same interface as any other instance of `UnivariateDistribution`; e.g., `scipy.stats.Normal`, `scipy.stats.Binomial`. .. note:: `make_distribution` does not work perfectly with all instances of `rv_continuous`. Known failures include `levy_stable`, `vonmises`, `hypergeom`, 'nchypergeom_fisher', 'nchypergeom_wallenius', and `poisson_binom`. Some methods of some distributions will not support array shape parameters. Parameters ---------- dist : `rv_continuous` Instance of `rv_continuous`, `rv_discrete`, or an instance of any class with the following attributes: __make_distribution_version__ : str A string containing the version number of SciPy in which this interface is defined. The preferred interface may change in future SciPy versions, in which case support for an old interface version may be deprecated and eventually removed. parameters : dict or tuple If a dictionary, each key is the name of a parameter, and the corresponding value is either a dictionary or tuple. If the value is a dictionary, it may have the following items, with default values used for entries which aren't present. endpoints : tuple, default: (-inf, inf) A tuple defining the lower and upper endpoints of the domain of the parameter; allowable values are floats, the name (string) of another parameter, or a callable taking parameters as keyword only arguments and returning the numerical value of an endpoint for given parameter values. inclusive : tuple of bool, default: (False, False) A tuple specifying whether the endpoints are included within the domain of the parameter. typical : tuple, default: ``endpoints`` Defining endpoints of a typical range of values of a parameter. Can be used for sampling parameter values for testing. Behaves like the ``endpoints`` tuple above, and should define a subinterval of the domain given by ``endpoints``. A tuple value ``(a, b)`` associated to a key in the ``parameters`` dictionary is equivalent to ``{endpoints: (a, b)}``. Custom distributions with multiple parameterizations can be defined by having the ``parameters`` attribute be a tuple of dictionaries with the structure described above. In this case, ``dist``'s class must also define a method ``process_parameters`` to map between the different parameterizations. It must take all parameters from all parameterizations as optional keyword arguments and return a dictionary mapping parameters to values, filling in values from other parameterizations using values from the supplied parameterization. See example. support : dict or tuple A dictionary describing the support of the distribution or a tuple describing the endpoints of the support. This behaves identically to the values of the parameters dict described above, except that the key ``typical`` is ignored. The class **must** also define a ``pdf`` method and **may** define methods ``logentropy``, ``entropy``, ``median``, ``mode``, ``logpdf``, ``logcdf``, ``cdf``, ``logccdf``, ``ccdf``, ``ilogcdf``, ``icdf``, ``ilogccdf``, ``iccdf``, ``moment``, and ``sample``. If defined, these methods must accept the parameters of the distribution as keyword arguments and also accept any positional-only arguments accepted by the corresponding method of `ContinuousDistribution`. When multiple parameterizations are defined, these methods must accept all parameters from all parameterizations. The ``moment`` method must accept the ``order`` and ``kind`` arguments by position or keyword, but may return ``None`` if a formula is not available for the arguments; in this case, the infrastructure will fall back to a default implementation. The ``sample`` method must accept ``shape`` by position or keyword, but contrary to the public method of the same name, the argument it receives will be the *full* shape of the output array - that is, the shape passed to the public method prepended to the broadcasted shape of random variable parameters. Returns ------- CustomDistribution : `UnivariateDistribution` A subclass of `UnivariateDistribution` corresponding with `dist`. The initializer requires all shape parameters to be passed as keyword arguments (using the same names as the instance of `rv_continuous`/`rv_discrete`). Notes ----- The documentation of `UnivariateDistribution` is not rendered. See below for an example of how to instantiate the class (i.e. pass all shape parameters of `dist` to the initializer as keyword arguments). Documentation of all methods is identical to that of `scipy.stats.Normal`. Use ``help`` on the returned class or its methods for more information. Examples -------- >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy import stats >>> from scipy import special Create a `ContinuousDistribution` from `scipy.stats.loguniform`. >>> LogUniform = stats.make_distribution(stats.loguniform) >>> X = LogUniform(a=1.0, b=3.0) >>> np.isclose((X + 0.25).median(), stats.loguniform.ppf(0.5, 1, 3, loc=0.25)) np.True_ >>> X.plot() >>> sample = X.sample(10000, rng=np.random.default_rng()) >>> plt.hist(sample, density=True, bins=30) >>> plt.legend(('pdf', 'histogram')) >>> plt.show() Create a custom distribution. >>> class MyLogUniform: ... @property ... def __make_distribution_version__(self): ... return "1.16.0" ... ... @property ... def parameters(self): ... return {'a': {'endpoints': (0, np.inf), ... 'inclusive': (False, False)}, ... 'b': {'endpoints': ('a', np.inf), ... 'inclusive': (False, False)}} ... ... @property ... def support(self): ... return {'endpoints': ('a', 'b'), 'inclusive': (True, True)} ... ... def pdf(self, x, a, b): ... return 1 / (x * (np.log(b)- np.log(a))) >>> >>> MyLogUniform = stats.make_distribution(MyLogUniform()) >>> Y = MyLogUniform(a=1.0, b=3.0) >>> np.isclose(Y.cdf(2.), X.cdf(2.)) np.True_ Create a custom distribution with variable support. >>> class MyUniformCube: ... @property ... def __make_distribution_version__(self): ... return "1.16.0" ... ... @property ... def parameters(self): ... return {"a": (-np.inf, np.inf), ... "b": {'endpoints':('a', np.inf), 'inclusive':(True, False)}} ... ... @property ... def support(self): ... def left(*, a, b): ... return a**3 ... ... def right(*, a, b): ... return b**3 ... return (left, right) ... ... def pdf(self, x, *, a, b): ... return 1 / (3*(b - a)*np.cbrt(x)**2) ... ... def cdf(self, x, *, a, b): ... return (np.cbrt(x) - a) / (b - a) >>> >>> MyUniformCube = stats.make_distribution(MyUniformCube()) >>> X = MyUniformCube(a=-2, b=2) >>> Y = stats.Uniform(a=-2, b=2)**3 >>> X.support() (-8.0, 8.0) >>> np.isclose(X.cdf(2.1), Y.cdf(2.1)) np.True_ Create a custom distribution with multiple parameterizations. Here we create a custom version of the beta distribution that has an alternative parameterization in terms of the mean ``mu`` and a dispersion parameter ``nu``. >>> class MyBeta: ... @property ... def __make_distribution_version__(self): ... return "1.16.0" ... ... @property ... def parameters(self): ... return ({"a": (0, np.inf), "b": (0, np.inf)}, ... {"mu": (0, 1), "nu": (0, np.inf)}) ... ... def process_parameters(self, a=None, b=None, mu=None, nu=None): ... if a is not None and b is not None: ... nu = a + b ... mu = a / nu ... else: ... a = mu * nu ... b = nu - a ... return dict(a=a, b=b, mu=mu, nu=nu) ... ... @property ... def support(self): ... return {'endpoints': (0, 1)} ... ... def pdf(self, x, a, b, mu, nu): ... return special._ufuncs._beta_pdf(x, a, b) ... ... def cdf(self, x, a, b, mu, nu): ... return special.betainc(a, b, x) >>> >>> MyBeta = stats.make_distribution(MyBeta()) >>> X = MyBeta(a=2.0, b=2.0) >>> Y = MyBeta(mu=0.5, nu=4.0) >>> np.isclose(X.pdf(0.3), Y.pdf(0.3)) np.True_ rz` is not supported.__make_distribution_version__z0.0.0z1.16.0zThe argument must be an instance of `rv_continuous`, `rv_discrete`, or an instance of a class with attribute `__make_distribution_version__ >= 1.16`.)r rvonmisesrargrirmr/rRrz rv_continuous rv_discrete_make_distribution_rv_genericrl_make_distribution_customr/)rras rr r sF !!5>>5??((%*E*E##%%"Adii[0C"DEE$++e.?.??@,T22 6 @H L(..>!!rc Zgg}tdjjf}jD]f}t |j |j }t|j|}j||j|jhtjjjjttjrtjt c}ntj"t$c}fd}|drfd}fd} || f} n|} t | d} td | d Gfd d |} d/ddfd } fd}fd}fd}fd}ddddddddddddd }d!d"d#hi}|j'D]e\}}j|vr||jvr&tj(|d}t|d}||usOt+| |t|g|d$r|| _|d%r| | _|d&r|| _|d$s|| _|| _t5| d'(j7}d)jd*|d+d,d+d-|g}d.j9|| _| S)0NrrKrLrcLtj|dt|duSr)rlrO)r8r old_classs rrz1_make_distribution_rv_generic.._overridess) T:y+t<= >r _get_supportc^jdi|\}}tj|dSrGrr@rJ)r_rMrYrs rrz+_make_distribution_rv_generic..left0$4$$8'78DAq::a=$ $rc^jdi|\}}tj|dSrGr)r_rYrNrs rrz,_make_distribution_rv_generic..right rrTTr)ryrprrcLeZdZWreWgngZWZfdZfdZxZS)9_make_distribution_rv_generic..CustomDistributioncDt|}|jdSNCustomDistributionrHr+rkr1srOrepr_strs rr+zB_make_distribution_rv_generic..CustomDistribution.__repr__0" "A9918< .CustomDistribution.__str__4!!A9918< rrr1r+r;r)rO_x_paramrUrs@rrr+s-BL0*=>#%   = = =rrrc.jd||d|S)N)rr random_staterC)_rvs)r1rrnrmrs rrz6_make_distribution_rv_generic.._sample_formula8styyEjsEfEErc<jt|fi|Sr)_munprr1rprmrs rrz:_make_distribution_rv_generic.._moment_raw_formula;stzz#e*///rc:|dk7ryjdi|dS)NrprrC_statsrs r_moment_raw_formula_1z<_make_distribution_rv_generic.._moment_raw_formula_1>& A:t{{$V$Q''rc:|dk7ryjdi|dS)NrrprCrrs rr*z>_make_distribution_rv_generic.._moment_central_formulaCrrc|dk(r2jrd|d<jdi|t|dz S|dk(r;jrd|d<jdi|t|dz }||S|dzSy)NrrmomentsrprrrC)_stats_has_momentsrr)r1rprmrrs r_moment_standard_formulaz?_make_distribution_rv_generic.._moment_standard_formulaHs A:&&$'y!4;;((UQY8 8 aZ&&$'y! %f%c%!)n5A 1 ,q1u ,rrrrrr'r)r(r*rrrr) _logpdf_pdf_logpmf_pmf_logcdf_cdf_logsf_sf_ppf_isf_entropy_medianr-rrrrrFrz#This class represents `scipy.stats.z` as a subclass of `z`.z(The `repr`/`str` of class instances is `'The PDF of the distribution is defined rr)rlrMrN _shape_infor{rKrLrrRr_distribution_namesr] capitalizerzr rxrryr-rrOrrrr;r*rrrr?)rrr0 shape_inforrV new_classrrrrK _x_supportrrrrr*rr skip_override old_method new_methodrer support_etcdocsrrrUrs` @@@@rrzrzsJ EdJ(89G&&(& )=)='1';';=zv>%  Z__% &#&&tyy$))2F2F2HIH$++,$224J 9$002F 9>.! % %5M  lKJc*gFH = =Y =FDF0( ( ,%+%+%+%&'-+ -G$eV_5M")--/O J 99 %* dii8P*P T:y*d;  % & GD*4M NO'1D.&-<*(:R7'"5J  29P  6 2UKRRTK -dii[9 ;b  28*B? 1+?  D #'))D/ rcZt|trd|in|}|jdd}||fS)NrKr)rzrpop)r) domain_infors r_get_domain_infors2)3D%)@;%dKooi.G  rc tjtr jn jf}g|D]o}g}|jD]=\}}t |\}}t di|}t |||} |j| ?j|rt|ngqt j\}} t di|} t d| jjGfddt} hd} | D],}t|sd|d}t| |t|.td r$fd }fd }fd }|| _|| _|| _td rt| dtd t'| dj)}ddd|g}dj+|| _| S)Nrrr~c:eZdZWZWZfdZfdZxZS)5_make_distribution_custom..CustomDistributioncDt|}|jdSrrrs rr+z>_make_distribution_custom..CustomDistribution.__repr__rrcDt|}|jdSrrrs rr;z=_make_distribution_custom..CustomDistribution.__str__rr)r<r=r>rr1r+r;r)rOrrrs@rrrs.  = = =rr>r\rr&cdf2rrccdf2rr!rrrrrrlogcdf2rlogccdf2rrY_formularc.j|fddi|S)Nrrrrs rrz6_make_distribution_custom.._moment_raw_formulas4;;u;5;F; ;rc.j|fddi|S)Nrrrrs rr*z:_make_distribution_custom.._moment_central_formulas4;;u?9?? ?rc.j|fddi|S)Nrrrrs rr;z?_make_distribution_custom.._moment_standardized_formulas4;;uD>DVD Drprocess_parametersrFrzThis class represents `z,` as a subclass of `ContinuousDistribution`.rrrC)rzrUrrrr{rrrr0rOr<rrrrlrr*r;rrrr?)rdist_parametersrrUrRr)rrrrVrYrrrrerrr*r;rrrrrs` @@@rr{r{s%doou=DOOCV+ W  *002 %JD$#3D#9 K"1[1F"4HE   e $  %   :!2J!?SUV W&dll3NK--Jc*5H~~&&H = =3 =7G K 4 VHH-J & GD&4I J K tX < @ E2E.5L2:V7t)*  ! D. /  2UKRRTK !(,$ $ 1+? D #'))D/ rcfd}|S)Nc"j}t|j|} |j|||} |j|||} | | | g|i|} | | | g|i|} t j t j || | dSrG)r<rl_dist _transformr@ real_if_closer)r1rr~r0r9rErlrmrcrQxtytfxyfyxrs rrqz8_shift_scale_distribution_function_2arg..wrappeds}} DJJ %__QU + __QU +B(((B(((sC 89"==rrC)rrqs` r'_shift_scale_distribution_function_2argrs > Nrc$dddddfd}|S)Nr5rgr4rP)r4rPr5rgcj}t|j|}t|j |} |j|||} || g|i|} | | g|i|} t j || | dSrG)r<rlrrr@r)r1rr0r9rErlrmrcrQcfrfxcfxcitemrs rrqz3_shift_scale_distribution_function..wrappeds}} DJJ % TZZt -__QU + r #D #F #%d%f%xxb#&r**rrCrrqrs` @r"_shift_scale_distribution_functionrs"!4."4. 0E + Nrc$dddddfd}|S)Nrrrr)rrrrc" j}t|j|}t|j |} |j||g|i|||} |j| |g|i|||} t j || | dSrG)r<rlr _itransformr@r)r1rr0r9rErlrmrcrQrrrrrs rrqz._shift_scale_inverse_function..wrappeds}} DJJ % TZZt -q4T4V4c5Ar!5d5f5sEBxxb#&r**rrCrs` @r_shift_scale_inverse_functionrs""60#6 0 2E + NrcTeZdZfdZfdZfdZddfd ZdZdZd Z xZ S) TransformedDistributioncDt|ts d}t||j|j|_||_|j r|j j}t|}|js#|jjt|jD]`}|j|jr(d|d|jjd}t||jj!|bt#|H|i|y)Nz@Transformations are currently only supported for continuous RVs.z!One or more of the parameters of z% has the same name as a parameter of z;. Name collisions create ambiguities and are not supported.)rzrr/rr1rrrUrrrr intersectionrOr<r/rTrHrP) r1rrlrmrar set_paramsrrOs rrPz TransformedDistribution.__init__$s!34XG%g. . ##%  11<rPrrrrr+r;rrs@rrr#s,*.47; V8$$rrc6eZdZdZee dfdZeddedZedefd Z edd e d Z e ee e ee e gZ e j e j d fd ZddZdZdZdZdZdZdZdZdZdZdZdZdZxZS)TruncatedDistributionzTruncated distribution.ub)TFr}lbb_l)皙?g?rSrr)FTb_u)g?rrrc0t||g|||d|S)NrrHrP)r1rrrrlrmrOs rrPzTruncatedDistribution.__init__ks$wADARBA&AArc ||n'tj|tj d}||n&tj|tjd}|jjdi|}|j d||d|\}}|jj ||fi|}|jt||||||S)NrCr)rr_a_blogmass) r@rrrrrr#rTr)r1rrrrUrMrNrs rrz)TruncatedDistribution._process_parametersns>Rr||B'@'D>Rr||B'?'C3TZZ33=f= t}}8r8Z81.$**..q!BzB$"aIJrc |jjdi|\}}tj||tj||fSrG)rrr@r3r2)r1rrrrMrNs rrzTruncatedDistribution._supportws@"tzz"",V,1zz!R "**Q"333rcyNFrCr1r8s rrz TruncatedDistribution._overrides{srcL|jj|g|i|} | |z Sr)rr) r1rrrrrrrlrrs rrz&TruncatedDistribution._logpdf_dispatch~s-,,,Q@@@rcN|jj||g|i|} | |z Srrr#) r1rrrrrrrlrr!s rr4z&TruncatedDistribution._logcdf_dispatchs/---b!EdEfErcN|jj||g|i|} | |z Srr) r1rrrrrrrlrrs rr5z'TruncatedDistribution._logccdf_dispatchs/.$**..q"FtFvF  rcN|jj||g|i| } | |z Srr) r1rr~rrrrrrlrrs rr#z'TruncatedDistribution._logcdf2_dispatchs/.$**..q!EdEfE  rc|jj|g|i|} tj| ||z} |jj| g|i|Sr)rr4r@r6r) r1rrrrrrrlrlog_Fa logp_adjusteds rrz'TruncatedDistribution._ilogcdf_dispatchsW,,,RA$A&A VTG^< +tzz++MKDKFKKrc|jj|g|i|} tj| ||z} |jj| g|i|Sr)rr5r@r6r) r1rrrrrrrlrlog_cFbr s rrz(TruncatedDistribution._ilogccdf_dispatchsW.$**..rCDCFC WdWn= ,tzz,,]LTLVLLrc|jj|g|i|} | |tj|zz} |jj| g|i|Sr)rrPr@r%r) r1rrrrrrrlrFa p_adjusteds rrz$TruncatedDistribution._icdf_dispatchsZ %TZZ % %b :4 :6 :!BFF7O++ (tzz((EdEfEErc|jj|g|i|} | |tj|zz} |jj| g|i|Sr)rrgr@r%r) r1rrrrrrrlrcFbrs rrz%TruncatedDistribution._iccdf_dispatchsZ'djj''DJJ01dgg,uS\N!= > > >rNN)r<r=r>r?r{r _lb_domainr _lb_param _ub_domain _ub_paramrrr@rPrrrrr4r5r#rrrrr+r;rrs@rrrXs! 3$OJtF'1:GI$ NJtF)3ZII,IyA+I6+I68)+w266B4  !!L M F G @ >rrct|||S)aTruncate the support of a random variable. Given a random variable `X`, `truncate` returns a random variable with support truncated to the interval between `lb` and `ub`. The underlying probability density function is normalized accordingly. Parameters ---------- X : `ContinuousDistribution` The random variable to be truncated. lb, ub : float array-like The lower and upper truncation points, respectively. Must be broadcastable with one another and the shape of `X`. Returns ------- X : `ContinuousDistribution` The truncated random variable. References ---------- .. [1] "Truncated Distribution". *Wikipedia*. https://en.wikipedia.org/wiki/Truncated_distribution Examples -------- Compare against `scipy.stats.truncnorm`, which truncates a standard normal, *then* shifts and scales it. >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy import stats >>> loc, scale, lb, ub = 1, 2, -2, 2 >>> X = stats.truncnorm(lb, ub, loc, scale) >>> Y = scale * stats.truncate(stats.Normal(), lb, ub) + loc >>> x = np.linspace(-3, 5, 300) >>> plt.plot(x, X.pdf(x), '-', label='X') >>> plt.plot(x, Y.pdf(x), '--', label='Y') >>> plt.xlabel('x') >>> plt.ylabel('PDF') >>> plt.title('Truncated, then Shifted/Scaled Normal') >>> plt.legend() >>> plt.show() However, suppose we wish to shift and scale a normal random variable, then truncate its support to given values. This is straightforward with `truncate`. >>> Z = stats.truncate(scale * stats.Normal() + loc, lb, ub) >>> Z.plot() >>> plt.show() Furthermore, `truncate` can be applied to any random variable: >>> Rayleigh = stats.make_distribution(stats.rayleigh) >>> W = stats.truncate(Rayleigh(), lb=0.5, ub=3) >>> W.plot() >>> plt.show() r)r)rrrs rr#r#sz !rb 11rc>eZdZdZee efdZeddedZee efdZ edd e d Z e ee e ee e gZ d1d Z d ZdZdZdZdZdZdZdZdZdZdZdZdZdZdZed ddZed ddZed ddZ ed dd Z!e"d dd!Z#e"d dd"Z$e"d dd#Z%e"d dd$Z&e'd dd%Z(e'd dd&Z)e'd dd'Z*e'd dd(Z+d)Z,d*Z-d+Z.d,Z/d-Z0d.Z1d/Z2d0Z3y )2r2z8Distribution with a standard shift/scale transformation.rr}r0z\murprrr9z\sigma)rr#Nc ||ntj|d}||ntj|d}|dkD}|jjdi|}|j t ||||S)NrCrr0r9rE)r@rrrrrTr)r1r0r9rrErUs rrz-ShiftedScaledDistribution._process_parametersst_c"--*>r*B* S0A"0Eqy3TZZ33=f= $3e$?@rc ||z |z SrrCr1rr0r9rms rrz$ShiftedScaledDistribution._transformsCrc ||z|zSrrCr$s rrz%ShiftedScaledDistribution._itransforms5y3rc |jjdi|\}}|j||||j|||}}tj|||dtj|||dfSrG)rrrr@r)r1r0r9rErrMrNs rrz"ShiftedScaledDistribution._support su"tzz"",V,13.0@0@C0O1xxa#B'$1)=b)AAArc2tjd5t|jdt|j}|j j s,|j dkr|dt|j z }n{tj|j dk7s>tj|j j|jjs|dt|j z }ddd|S#1swYSxYwNr#r$*rz - z + ) r@r&rr9rr0rr2can_castrr1results rr+z"ShiftedScaledDistribution.__repr__s __r * 1djj)*!D,<+=>F88==TXX\CdhhY011&&Q'TXX^^TZZ5E5EFCTXX/00 1  1 C+D  Dc2tjd5t|jdt|j}|j j s,|j dkr|dt|j z }n{tj|j dk7s>tj|j j|jjs|dt|j z }ddd|S#1swYSxYwr() r@r&rr9rr0rr2r*rr+s rr;z!ShiftedScaledDistribution.__str__s __r * 0TZZ)3tzz?*;v>ffRVVBFF5M*2-.  !4!4S#!>QGGrc d|jjdd|i|}|j|||Sr)rrrr1rer0r9rErrs rrz*ShiftedScaledDistribution._median_dispatch?s5)djj))BB6BS%00rc d|jjdd|i|}|j|||Sr)rrrr4s rrz(ShiftedScaledDistribution._mode_dispatchCs5'djj''@v@@S%00rc|j|||}|jj|g|i|}|tjtj |z Sr)rrrr@r&r$)r1rr0r9rErlrrs rrz*ShiftedScaledDistribution._logpdf_dispatchGP OOAsE *,,,Q@@@rvve}---rc|j|||}|jj|g|i|}|tj|z Sr)rrrr@r$)r1rr0r9rErlrrs rrz'ShiftedScaledDistribution._pdf_dispatchLG OOAsE *&djj&&q:4:6:RVVE]""rc|j|||}|jj|g|i|}|tjtj |z Sr)rrrr@r&r$)r1rr0r9rErlrrs rrz*ShiftedScaledDistribution._logpmf_dispatchQr7rc|j|||}|jj|g|i|}|tj|z Sr)rrrr@r$)r1rr0r9rErlrrs rrz'ShiftedScaledDistribution._pmf_dispatchVr9rc|j|||}|jj|g|i|}|tjtj |z Sr)rrrr@r&r$)r1rr0r9rErlrrs rrz*ShiftedScaledDistribution._logpxf_dispatch[r7rc|j|||}|jj|g|i|}|tj|z Sr)rrrr@r$)r1rr0r9rErlrrs rrz'ShiftedScaledDistribution._pxf_dispatch`r9rrdc yrrCrs rr4z*ShiftedScaledDistribution._logcdf_dispatchf rc yrrCrs rrPz'ShiftedScaledDistribution._cdf_dispatchjr?rc yrrCrs rr5z+ShiftedScaledDistribution._logccdf_dispatchnr?rc yrrCrs rrgz(ShiftedScaledDistribution._ccdf_dispatchrr?rc yrrCr.s rr#z+ShiftedScaledDistribution._logcdf2_dispatchvr?rc yrrCr.s rrBz(ShiftedScaledDistribution._cdf2_dispatchzr?rc yrrCr.s rrz,ShiftedScaledDistribution._logccdf2_dispatch~r?rc yrrCr.s rrz)ShiftedScaledDistribution._ccdf2_dispatchr?rc yrrCrs rrz+ShiftedScaledDistribution._ilogcdf_dispatchr?rc yrrCrs rrz(ShiftedScaledDistribution._icdf_dispatchr?rc yrrCrs rrz,ShiftedScaledDistribution._ilogccdf_dispatchr?rc yrrCrs rrz)ShiftedScaledDistribution._iccdf_dispatchr?rc ~|jj|fd|i|}|dS|tj||zzSNr)rr3r@rEr1rpr0r9rErrrIs rr3z7ShiftedScaledDistribution._moment_standardized_dispatchsL7tzz77 .".&,.{tCbggene.C(CCrc X|jj|fd|i|}|dS|||zzSrL)rr"rMs rr"z2ShiftedScaledDistribution._moment_central_dispatchsC2tzz22 .".&,.{t:eUl(::rc g}|}tt|dzD]Q} | |kr |jn|}|jj| fd|i|} | y| || zz} |j | S|j ||||jS)Nrpr)rrrrrrr#r) r1rpr0r9rErrr0methods_highest_orderrrr%s rrz.ShiftedScaledDistribution._moment_raw_dispatchs 's5zA~& )A/05yt++1 1$**11!OWOOC{UAX~H   x ( ),, ;TZZ1 1rc p|jj|f||d|}|j|f|||d|S)Nrr")rrir) r1rrnr0r9rErerrvss rriz*ShiftedScaledDistribution._sample_dispatchsF)djj))*WVWPVWtOEOOOrc`t|j|j|z|jSN)r0r9r2rr0r9r3s rr4z!ShiftedScaledDistribution.__add__&(C/3zz; ;rc`t|j|j|z |jSrTrUr3s rr6z!ShiftedScaledDistribution.__sub__rVrcft|j|j|z|j|zSrTrUr:s rr;z!ShiftedScaledDistribution.__mul__/(-1XX-=/3zzE/AC Crcft|j|j|z |j|z SrTrUr:s rr=z%ShiftedScaledDistribution.__truediv__rYrr)4r<r=r>r?r{r _loc_domainr _loc_param _scale_domain _scale_paramrrrrrrr+r;rrrrrrrrrrrr4rPr5rgrr#rBrrrrrrrr3r"rrir4r6r;r=rCrrr2r2s BC4+NKf'2FDJ"cT3K<PM!'))6 KL,J E+J7+L9;B  2)H 11. # . # . # (,0 ( ()- ( (-1 ( (*. ( -04 - --1 - -15 - -.2 - #-1 # #*. # #.2 # #+/ # D ; 1 P ;;C Crr2ceZdZdZeddZededZedejfdZ ed e d Z eje e ee gZfd Zd Zdd ZdZdZdZdZdZdZdZdZdZxZS)OrderStatisticDistributionaProbability distribution of an order statistic An instance of this class represents a random variable that follows the distribution underlying the :math:`r^{\text{th}}` order statistic of a sample of :math:`n` observations of a random variable :math:`X`. Parameters ---------- dist : `ContinuousDistribution` The random variable :math:`X` n : array_like The (integer) sample size :math:`n` r : array_like The (integer) rank of the order statistic :math:`r` Notes ----- If we make :math:`n` observations of a continuous random variable :math:`X` and sort them in increasing order :math:`X_{(1)}, \dots, X_{(r)}, \dots, X_{(n)}`, :math:`X_{(r)}` is known as the :math:`r^{\text{th}}` order statistic. If the PDF, CDF, and CCDF underlying math:`X` are denoted :math:`f`, :math:`F`, and :math:`F'`, respectively, then the PDF underlying math:`X_{(r)}` is given by: .. math:: f_r(x) = \frac{n!}{(r-1)! (n-r)!} f(x) F(x)^{r-1} F'(x)^{n - r} The CDF and other methods of the distribution underlying :math:`X_{(r)}` are calculated using the fact that :math:`X = F^{-1}(U)`, where :math:`U` is a standard uniform random variable, and that the order statistics of observations of `U` follow a beta distribution, :math:`B(r, n - r + 1)`. References ---------- .. [1] Order statistic. *Wikipedia*. https://en.wikipedia.org/wiki/Order_statistic Examples -------- Suppose we are interested in order statistics of samples of size five drawn from the standard normal distribution. Plot the PDF underlying the fourth order statistic and compare with a normalized histogram from simulation. >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy import stats >>> from scipy.stats._distribution_infrastructure import OrderStatisticDistribution >>> >>> X = stats.Normal() >>> data = X.sample(shape=(10000, 5)) >>> ranks = np.sort(data, axis=1) >>> Y = OrderStatisticDistribution(X, r=4, n=5) >>> >>> ax = plt.gca() >>> Y.plot(ax=ax) >>> ax.hist(ranks[:, 3], density=True, bins=30) >>> plt.show() )rpr5rr}rr rrpr5)rprc2t||g|||d|y)Nrar5r)r1rrar5rlrmrOs rrPz#OrderStatisticDistribution.__init__s! 99Q9&9rc:|jj|i|Sr)rr)r1rar5rlrms rrz#OrderStatisticDistribution._supports"tzz""D3F33rc v|jjdi|}|jt|||S)NrcrC)rrrTr)r1rar5rrUs rrz.OrderStatisticDistribution._process_parameterss53TZZ33=f= $a.)rc |dvS)N>r)rr*rrrrCrs rrz%OrderStatisticDistribution._overrides!sBB Brc tj|||z dz}|jj|fi|}|jj|j fi|}|jj |j fi|}tj|dz dk(tj|zd|dz |z} tj||z dk(tj|zd||z |z} || z| z|z S)Nrpr) r betalnrrr4r7r5r@rr) r1rrar5rm log_factorlog_fXlog_FXlog_cFX rm1_log_FX nmr_log_cFXs rrz*OrderStatisticDistribution._logpdf_formula&s^^Aq1uqy1 ,,,Q9&9-,,QVV>v>.$**..qvv@@XXq1uzR[[-@@!ac6\R hhA bkk'.BBA!W}U  "[0:==rc tj|||z dz}|jj|fi|}|jj|fi|}|jj |fi|}|||dz zz|||z zz|z SrD)r betarrrPrg) r1rrar5rmfactorfXFXcFXs rrz'OrderStatisticDistribution._pdf_formula4saQ+ %TZZ % %a 26 2 %TZZ % %a 26 2'djj''4V4B1I~ac *V33rc v|jj|fi|}tj|||z dz|SrD)rrPr betaincr1rrar5rmx_s rr)z'OrderStatisticDistribution._cdf_formula<s8 %TZZ % %a 26 2q!A#a%,,rc v|jj|fi|}tj|||z dz|SrD)rrPr betainccrws rr*z(OrderStatisticDistribution._ccdf_formula@s: %TZZ % %a 26 21Q3q5"--rc vtj|||z dz|}|jj|fi|SrD)r betaincinvrrr1rrar5rmp_s rrz(OrderStatisticDistribution._icdf_formulaDs:   1Q3q5! ,(tzz((6v66rc vtj|||z dz|}|jj|fi|SrD)r betainccinvrrr}s rrz)OrderStatisticDistribution._iccdf_formulaHs:  AaCE1 -(tzz((6v66rc tjd5dt|jdt|jdt|j dcdddS#1swYyxYwNr#r$zorder_statistic(z, r=z, n=r)r@r&rrrar5r:s rr+z#OrderStatisticDistribution.__repr__Ls\ __r * *&tDJJ'7&8T$&&\NKdffa) * * *rc tjd5dt|jdt|jdt|j dcdddS#1swYyxYwr)r@r&rrrar5r:s rr;z"OrderStatisticDistribution.__str__Qs[ __r * )&s4::&7tCK=ITVV Q( ) ) )rr)r<r=r>r?r{ _r_domainr_r_paramr@r _n_domain_n_paramrXrrrPrrrrrr)r*rrr+r;rrs@rr`r`s=BLIIc)VDHBFF |LIc)VDH )+Hh?@:4 B >4-.77* )rr`cPtj|tj|}}tj|tj|k7|dkzs1tj|tj|k7|dkzr d}t |t |||S)av Probability distribution of an order statistic Returns a random variable that follows the distribution underlying the :math:`r^{\text{th}}` order statistic of a sample of :math:`n` observations of a random variable :math:`X`. Parameters ---------- X : `ContinuousDistribution` The random variable :math:`X` r : array_like The (positive integer) rank of the order statistic :math:`r` n : array_like The (positive integer) sample size :math:`n` Returns ------- Y : `ContinuousDistribution` A random variable that follows the distribution of the prescribed order statistic. Notes ----- If we make :math:`n` observations of a continuous random variable :math:`X` and sort them in increasing order :math:`X_{(1)}, \dots, X_{(r)}, \dots, X_{(n)}`, :math:`X_{(r)}` is known as the :math:`r^{\text{th}}` order statistic. If the PDF, CDF, and CCDF underlying math:`X` are denoted :math:`f`, :math:`F`, and :math:`F'`, respectively, then the PDF underlying math:`X_{(r)}` is given by: .. math:: f_r(x) = \frac{n!}{(r-1)! (n-r)!} f(x) F(x)^{r-1} F'(x)^{n - r} The CDF and other methods of the distribution underlying :math:`X_{(r)}` are calculated using the fact that :math:`X = F^{-1}(U)`, where :math:`U` is a standard uniform random variable, and that the order statistics of observations of `U` follow a beta distribution, :math:`B(r, n - r + 1)`. References ---------- .. [1] Order statistic. *Wikipedia*. https://en.wikipedia.org/wiki/Order_statistic Examples -------- Suppose we are interested in order statistics of samples of size five drawn from the standard normal distribution. Plot the PDF underlying each order statistic and compare with a normalized histogram from simulation. >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy import stats >>> >>> X = stats.Normal() >>> data = X.sample(shape=(10000, 5)) >>> sorted = np.sort(data, axis=1) >>> Y = stats.order_statistic(X, r=[1, 2, 3, 4, 5], n=5) >>> >>> ax = plt.gca() >>> colors = plt.rcParams['axes.prop_cycle'].by_key()['color'] >>> for i in range(5): ... y = sorted[:, i] ... ax.hist(y, density=True, bins=30, alpha=0.1, color=colors[i]) >>> Y.plot(ax=ax) >>> plt.show() rz0`r` and `n` must contain only positive integers.rc)r@rJr2r3r/r`)rrar5ras rr"r"WsL ::a="**Q-qA vvqBHHQKAE*+rvvqBHHQK7GAPQE6R/SD!! %a1 22rceZdZdZdZdddZedZedZdZ d Z d Z d Z d Z dd dZdd dZdd dZdd dZdd dZdd dZdd dZdd dZdd dZd,dd dZdZdZdZdd dZdd dZdd dZdd dZd-dd dZd-dd d Z d-dd d!Z!d-dd d"Z"d#Z#dd d$Z$dd d%Z%dd d&Z&dd d'Z'd.ddd(d)Z(d*Z)d+Z*y)/r!a Representation of a mixture distribution. A mixture distribution is the distribution of a random variable defined in the following way: first, a random variable is selected from `components` according to the probabilities given by `weights`, then the selected random variable is realized. Parameters ---------- components : sequence of `ContinuousDistribution` The underlying instances of `ContinuousDistribution`. All must have scalar shape parameters (if any); e.g., the `pdf` evaluated at a scalar argument must return a scalar. weights : sequence of floats, optional The corresponding probabilities of selecting each random variable. Must be non-negative and sum to one. The default behavior is to weight all components equally. Attributes ---------- components : sequence of `ContinuousDistribution` The underlying instances of `ContinuousDistribution`. weights : ndarray The corresponding probabilities of selecting each random variable. Methods ------- support sample moment mean median mode variance standard_deviation skewness kurtosis pdf logpdf cdf icdf ccdf iccdf logcdf ilogcdf logccdf ilogccdf entropy Notes ----- The following abbreviations are used throughout the documentation. - PDF: probability density function - CDF: cumulative distribution function - CCDF: complementary CDF - entropy: differential entropy - log-*F*: logarithm of *F* (e.g. log-CDF) - inverse *F*: inverse function of *F* (e.g. inverse CDF) References ---------- .. [1] Mixture distribution, *Wikipedia*, https://en.wikipedia.org/wiki/Mixture_distribution Examples -------- A mixture of normal distributions: >>> import numpy as np >>> from scipy import stats >>> import matplotlib.pyplot as plt >>> X1 = stats.Normal(mu=-2, sigma=1) >>> X2 = stats.Normal(mu=2, sigma=1) >>> mixture = stats.Mixture([X1, X2], weights=[0.4, 0.6]) >>> print(f'mean: {mixture.mean():.2f}, ' ... f'median: {mixture.median():.2f}, ' ... f'mode: {mixture.mode():.2f}') mean: 0.40, median: 1.04, mode: 2.00 >>> x = np.linspace(-10, 10, 300) >>> plt.plot(x, mixture.pdf(x)) >>> plt.title('PDF of normal distribution mixture') >>> plt.show() cnt|dk(r d}t||D];}t|ts d}t||jdk(r0d}t||||fSt j |}|jt|fk7r d}t|t j|jt js d}t|t jt j|ds d }t|t j|dk\s d }t|||fS) Nrz7`components` must contain at least one random variable.zMEach element of `components` must be an instance of `ContinuousDistribution`.rCz5All elements of `components` must have scalar shapes.z5`components` and `weights` must have the same length.z)`weights` must have floating point dtype.r(z`weights` must sum to 1.0.z#All `weights` must be non-negative.)rr/rzrr,r@rJrrrriscloserra)r1 componentsweightsrar5s r_input_validationzMixture._input_validations" z?a PGW% % *Cc#9:7 ))::#Q )) * ?w& &**W% ==S_. .MGW% %}}W]]BJJ7AGW% %zz"&&/3/2GW% %vvgl#;GW% %7""rN)rc&|j||\}}t|}tjd|D}tjd|D|_||c|_|_|tj|d|z |n||_ d|_ y)Nc34K|]}|jywr)r+rr5s rrz#Mixture.__init__..0s B Brc34K|]}|jywr)r,rs rrz#Mixture.__init__..1s+M3CJJ+Mrrpr) rrr@rrr,r+ _componentsr_weightsr))r1rrr5rs rrPzMixture.__init__-s"44ZI G  O Bz BC))+M*+MN (-z% T%8?1Q3e4W !%rc,t|jSr)r rr:s rrzMixture.components6sD$$%%rc6|jjSr)rrIr:s rrzMixture.weights:s}}!!##rc|Dcgc]}tj|}}tj|jgd|D}tj|j gd|D}tj |||Scc}w)Nc34K|]}|jywrrrargs rrz Mixture._full..@s-HCcii-Hrc34K|]}|jywrrrs rrz Mixture._full..As2M3992Mrr)r@rJrr+rr,r)r1rrlrrrs r_fullz Mixture._full>sq+/0C 300t{{I-H4-HI##DKKN2M2MNwwuc//1sB c|jdg|}t|j|jD]\}}|t ||||zz }|dSNrrC)rrrrrl)r1rrlrur5weights r_sumz Mixture._sumDsbdjj"T"t//? 5KC $73$d+f4 4C 52wrc |jtj g|}t|jtj |j D]-\}}tj|t||||z|/|dS)N)rurC) rr@rrrr&rr6rl)r1rrlrur5 log_weights r_logsumzMixture._logsumJsydjj"&&(4("4#3#3RVVDMM5JK NOC LL/gc3/6C M N2wrcF|jtj}|jtj }|jD]P}tj||j d}tj ||j d}R||fSr)rr@rrr2r0r3)r1rMrNr5s rr0zMixture.supportPs~ JJrvv  JJw ## 0C 1ckkmA./A 1ckkmA./A 0!t rc| tdy)Nz/`method` not implemented for this distribution.r.rs r_raise_if_methodzMixture._raise_if_methodXs  %&WX X rrdcj|fd}t|gjddij}t |t j dzzS)Ncj|jtjj|jdzzSr)rr7r@r&rr1s r log_integrandz)Mixture.logentropy..log_integrand^s8 ;;qvv& AFF0Cb0H)II Irr&Tr|)rrr0rrr@rA)r1rerrIs` rrzMixture.logentropy\sP f% J A ADAJJ$S2558^44rctj|tfdgjjS)NcLj| j|zSr)rrrs rrz!Mixture.entropy..jsDHHQK<$++a.#@r)rrr0rrs` rrzMixture.entropyhs4 f%@*,,.**2( 3rcj|j\}}fd}t|d||}t||j|j |j }|jS)Nc(j| Sr)rrs rrQzMixture.mode..fps$((1+%rr()rr)rr0rrrrrr)r1rerMrNrQrIs` rrz Mixture.modemsX f%||~1%q"115$Q?uu rcF|j||jdSrf)rrrs rrzMixture.medianus f%yy~rcF|j||jdS)Nrrrrs rrz Mixture.meanys f%yy  rcF|j||jdS)Nr)rr rs rrzMixture.variance}s! f%##A&&rcJ|j||jdzSrf)rrrs rrzMixture.standard_deviations! f%}}##rcF|j||jdS)Nrrr rs rrzMixture.skewness! f%((++rcF|j||jdS)Nrrrs rrzMixture.kurtosisrrc|j||j|j|jd}tj ||||}||}||S)Nr )rr r r rrsrs rrzMixture.moments^ f%(( 00!%!:!:<';;D%uUDk 5!!rc|jd}t|j|jD]\}}||j |d|zz } |dS)NrrrrC)rrrrr)r1rprur5rs rr zMixture._moment_rawsXjjmt//? :KC 3::e%:069 9C :2wrcnt|}|jd}t|j|jD]m\}}t |dzDcgc]}|j |d}}|j|j}}|j|||}|||zz }o|dScc}w)NrrprrrC) rrrrrrrrr#) r1rprur5rrLrMrNrs rr zMixture._moment_centralsE jjmt//? #KC&+EAI&68"E :8I888:tyy{qA11%AqIF 6F? "C  # 2w 8sB2cL|j||j|zz Sr)r r)r1rps rr zMixture._moment_standardizeds&##E*T-D-D-F-MMMrcH|j||jd|S)Nrrrs rrz Mixture.pdf! f%yy""rcH|j||jd|S)Nrrrrs rrzMixture.logpdf! f%||Ha((rcH|j||jd|S)Nrrrs rrz Mixture.pmfrrcH|j||jd|S)Nrrrs rrzMixture.logpmfrrc\|j|||fn||f}|jdg|SNr\rr1rr~rerls rr\z Mixture.cdfs7 f%ytq!ftyy&&&rc\|j|||fn||f}|jdg|SNr!rrs rr!zMixture.logcdfs7 f%ytq!ft||H,t,,rc\|j|||fn||f}|jdg|SNr&rrs rr&z Mixture.ccdfs7 f%ytq!ftyy'$''rc\|j|||fn||f}|jdg|SNrrrs rrzMixture.logccdfs7 f%ytq!ft||I---rc|j\}}t|fd}t||\}}t||||||f}t ||j |j |fjS)Nc||z SrrC)rrrs rrz!Mixture._invert..sQ!rrr)r0rlrrrrrr) r1rrrrrQrrrIs ` r_invertzMixture._invertsj\\^ ddC  #!$-SA3CdQDQQ#&&CFF!>@@@rcH|j||jd|Srrrrs rrz Mixture.icdfs! f%||E1%%rcH|j||jd|Srrrs rrz Mixture.iccdfs! f%||FA&&rcH|j||jd|Srrrs rrzMixture.ilogcdfrrcH|j||jd|Srrrs rrzMixture.ilogccdfs! f%||Iq))r)rnrec|j|tjj|}tjtj |}|j ||j}t||jDcgc]\}}|j||}}}tj|jtj||}|dScc}}w)N)rrnrC)rr@rxryrrrrrrrrrr) r1rrnrerrnsr5r5rs rrzMixture.samples f%ii##C(wwr}}U+, __T4== 18;B@P@P8Q RfaSZZaSZ ) R R JJs||BNN1$56 >u  SsC+cd}|dz }tjd5|jD]}|dt|dz }|dz }|dt|jdz }ddd|d z }|S#1swYxYw Nz Mixture( z [ r#r$z z, z ], z weights=r)r@r&rrrr1r, components rr+zMixture.__repr__s) __r * =!__ : HT)_$5S99 : j F  T$,,%7$8< r?rrPrrrrrrr0rrrrrrrrrrrr r r rrrrr\r!r&rrrrrrrr+r;rCrrr!r!so^D$#L/3&&&$$0   Y$( 5!%3 " $"!"&',0$"&,"&,"D" N#'#&*)#'#&*)'$' -T- (4( .d. A$(&%)''+)(,*d4  rr!ceZdZdZdddddfd ZdZdZdZd Zd Z d Z d Z d Z dZ dZdZdZdZdZdZxZS)rOaDistribution underlying a strictly monotonic function of a random variable Given a random variable :math:`X`; a strictly monotonic function :math:`g(u)`, its inverse :math:`h(u) = g^{-1}(u)`, and the derivative magnitude :math: `|h'(u)| = \left| \frac{dh(u)}{du} \right|`, define the distribution underlying the random variable :math:`Y = g(X)`. Parameters ---------- X : `ContinuousDistribution` The random variable :math:`X`. g, h, dh : callable Elementwise functions representing the mathematical functions :math:`g(u)`, :math:`h(u)`, and :math:`|h'(u)|` logdh : callable, optional Elementwise function representing :math:`\log(h'(u))`. The default is ``lambda u: np.log(dh(u))``, but providing a custom implementation may avoid over/underflow. increasing : bool, optional Whether the function is strictly increasing (True, default) or strictly decreasing (False). repr_pattern : str, optional A string pattern for determining the __repr__. The __repr__ for X will be substituted into the position where `***` appears. For example: ``"exp(***)"`` for the repr of an exponentially transformed distribution The default is ``f"{g.__name__}(***)"``. str_pattern : str, optional A string pattern for determining `__str__`. The `__str__` for X will be substituted into the position where `***` appears. For example: ``"exp(***)"`` for the repr of an exponentially transformed distribution The default is the value `repr_pattern` takes. NT)logdhrMrIrJcBt ||g| i| ||_||_|_||nfd|_|r|j j|_|j j|_ |j j|_ |j j|_|j j|_|j j"|_|j j&|_|j j*|_n|j j|_|j j|_ |j j|_ |j j|_|j j"|_|j j|_|j j*|_|j j&|_||_|xs|j0d|_|xs |j2|_y)Nc:tj|Srrf)rArLs rrz;MonotonicTransformedDistribution.__init__..4sbffRUmrz(***))rHrP_g_h_dh_logdhrrP_xdfrg_cxdfr_ixdfr_icxdfr4_logxdfr5_logcxdfr_ilogxdfr _ilogcxdf _increasingr< _repr_pattern _str_pattern) r1rrHrKrLrrMrIrJrlrmrOs ` rrPz)MonotonicTransformedDistribution.__init__,s ,T,V, % 1u3  00DI22DJ22DJ**44DK::66DL JJ88DM JJ88DM!ZZ::DN 11DI11DJ33DJ**33DK::77DL JJ77DM JJ99DM!ZZ99DN%)A |5-A'=4+=+=rctjd5|jjdt |j cdddS#1swYyxYwNr#r$z***)r@r&rrkrrr:s rr+z)MonotonicTransformedDistribution.__repr__KsF __r * G%%--eT$**5EF G G G /AActjd5|jjdt |j cdddS#1swYyxYwr)r@r&rrkrrr:s rr;z(MonotonicTransformedDistribution.__str__OsE __r * E$$,,UC OD E E ErcyrrCrs rrz+MonotonicTransformedDistribution._overridesSrc |jjdi|\}}tj|dk(tjd|j |}tj d5|jr+|j||j|fcdddS|j||j|fcdddS#1swYyxYw)Nrz-0rrrrC) rrr@rrJrrrr)r1rrMrNs rrz)MonotonicTransformedDistribution._supportWs"tzz"",V,1 HHQT2::d!'':A > [[ ) .wwqz4771:- . .wwqz4771:-  . . .s/.C'!CCc|jj|j|g|i||j|zSr)rrrrr1rrlrs rrz1MonotonicTransformedDistribution._logpdf_dispatchas9*tzz**4771:GGG$++VW.XXrc|jj|j|g|i||j|zSr)rrrrrs rrz.MonotonicTransformedDistribution._pdf_dispatchds9'tzz'' DTDVDtxxPQ{RRrcL|j|j|g|i|Sr)rrrs rr4z1MonotonicTransformedDistribution._logcdf_dispatchgs%t||DGGAJ8888rcL|j|j|g|i|Sr)rrrs rrPz.MonotonicTransformedDistribution._cdf_dispatchjs%tyy5d5f55rcL|j|j|g|i|Sr)rrrs rr5z2MonotonicTransformedDistribution._logccdf_dispatchms%t}}TWWQZ9$9&99rcL|j|j|g|i|Sr)rrrs rrgz/MonotonicTransformedDistribution._ccdf_dispatchps%tzz$''!*6t6v66rcL|j|j|g|i|Sr)rrr1rrlrs rrz2MonotonicTransformedDistribution._ilogcdf_dispatchss&ww}t}}Q88899rcL|j|j|g|i|Sr)rrrs rrz/MonotonicTransformedDistribution._icdf_dispatchvs&wwztzz!5d5f566rcL|j|j|g|i|Sr)rrrs rrz3MonotonicTransformedDistribution._ilogccdf_dispatchys&ww~t~~a9$9&9::rcL|j|j|g|i|Sr)rrrs rrz0MonotonicTransformedDistribution._iccdf_dispatch|s&ww{t{{16t6v677rc d|jj|f||d|}|j|SNr)rrirr1rrernrrRs rriz1MonotonicTransformedDistribution._sample_dispatchs3)djj))*WVWPVWwws|r)r<r=r>r?rPr+r;rrrrr4rPr5rgrrrrrirrs@rrOrOsj#J59 t!>>GE.YS96:7:7;8rrOceZdZdZfdZdZdZdddZdddZddd Z ddd Z ddd Z ddd Z d Z dZdZxZS)rlaDistribution underlying the absolute value of a random variable Given a random variable :math:`X`; define the distribution underlying the random variable :math:`Y = |X|`. Parameters ---------- X : `ContinuousDistribution` The random variable :math:`X`. Returns ------- Y : `ContinuousDistribution` The random variable :math:`Y = |X|` ct||g|i|d|jjjdf|jj_y)NTrp)rHrPr1rrL)r1rrlrmrOs rrPzFoldedDistribution.__init__sI ,T,V, ,01F1F1P1PQR1S*T'rcyrrCrs rrzFoldedDistribution._overridesrrc J|jjdi|\}}tj|tj|}}tj||tj ||}}|dk|dkDz}tj |}d||<|d|dfSr)rrr@r$r2r3rJ)r1rrMrNa_b_rs rrzFoldedDistribution._supports"tzz"",V,1BFF1IBB#RZZB%7B Uq1u  ZZ^1"vr"v~rNrdctj|}|jj|g|d|i|}|jj| g|d|i|}tj|}tj|}|jj di|\}}tj || |k<tj |||kD<tj||g} tj| dS)NrerrrC) r@r$rrrJrrrr r) r1rrerlrrrrMrNlogpdfss rrz#FoldedDistribution._logpdf_dispatchs FF1I+ ++ANNVNvN*tzz**A2NNVNvNzz$ 5!"tzz"",V,1waR!V wa!e ((D%=)  q11rcttj|}|jj|g|d|i|}|jj| g|d|i|}tj|}tj|}|jj di|\}}d|| |k<d|||kD<||zS)NrerrC)r@r$rrrJr) r1rrerlrrrrMrNs rrz FoldedDistribution._pdf_dispatchs FF1I( ((KTK&KFK'tzz''KTK&KFKzz$ 5!"tzz"",V,1aR!V a!e e|rctj|}|jjdi|\}}tj| |}tj ||}|jj ||g|d|i|jSr)r@r$rrr3r2r#r7 r1rrerlrrMrNrrs rr4z#FoldedDistribution._logcdf_dispatchs| FF1I"tzz"",V,1 ZZA  ZZ1 +tzz++BSTS&SFSXXXrctj|}|jjdi|\}}tj| |}tj ||}|jj ||g|i|SrG)r@r$rrr3r2rBrs rrPz FoldedDistribution._cdf_dispatchsq FF1I"tzz"",V,1 ZZA  ZZ1 (tzz((RA$A&AArctj|}|jjdi|\}}tj| |}tj ||}|jj ||g|d|i|jSr)r@r$rrr3r2rr7rs rr5z$FoldedDistribution._logccdf_dispatchs FF1I"tzz"",V,1 ZZA  ZZ1 ,tzz,,R7d767/577;t r?rPrrrrr4rPr5rgrir+r;rrs@rrlrlsf&U15 2.2 15Y.2B26</3R.-rrlct|S)aNAbsolute value of a random variable Parameters ---------- X : `ContinuousDistribution` The random variable :math:`X`. Returns ------- Y : `ContinuousDistribution` A random variable :math:`Y = |X|`. Examples -------- Suppose we have a normally distributed random variable :math:`X`: >>> import numpy as np >>> from scipy import stats >>> X = stats.Normal() We wish to have a random variable :math:`Y` distributed according to the folded normal distribution; that is, a random variable :math:`|X|`. >>> Y = stats.abs(X) The PDF of the distribution in the left half plane is "folded" over to the right half plane. Because the normal PDF is symmetric, the resulting PDF is zero for negative arguments and doubled for positive arguments. >>> import matplotlib.pyplot as plt >>> x = np.linspace(0, 5, 300) >>> ax = plt.gca() >>> Y.plot(x='x', y='pdf', t=('x', -1, 5), ax=ax) >>> plt.plot(x, 2 * X.pdf(x), '--') >>> plt.legend(('PDF of `Y`', 'Doubled PDF of `X`')) >>> plt.show() rkrs rr$r$sN a  rc^t|tjtjddS)aNatural exponential of a random variable Parameters ---------- X : `ContinuousDistribution` The random variable :math:`X`. Returns ------- Y : `ContinuousDistribution` A random variable :math:`Y = \exp(X)`. Examples -------- Suppose we have a normally distributed random variable :math:`X`: >>> import numpy as np >>> from scipy import stats >>> X = stats.Normal() We wish to have a lognormally distributed random variable :math:`Y`, a random variable whose natural logarithm is :math:`X`. If :math:`X` is to be the natural logarithm of :math:`Y`, then we must take :math:`Y` to be the natural exponential of :math:`X`. >>> Y = stats.exp(X) To demonstrate that ``X`` represents the logarithm of ``Y``, we plot a normalized histogram of the logarithm of observations of ``Y`` against the PDF underlying ``X``. >>> import matplotlib.pyplot as plt >>> rng = np.random.default_rng(435383595582522) >>> y = Y.sample(shape=10000, rng=rng) >>> ax = plt.gca() >>> ax.hist(np.log(y), bins=50, density=True) >>> X.plot(ax=ax) >>> plt.legend(('PDF of `X`', 'histogram of `log(y)`')) >>> plt.show() c d|z SrDrCr]s rrzexp..Bs PQTUPUrc.tj| Srrfr]s rrzexp..CsRVVAYJrrHrKrLr)rOr@r%r&rs rr%r%s'T ,A266o2F HHrctj|jddkr d}t|t |tj tj tj dS)a!Natural logarithm of a non-negative random variable Parameters ---------- X : `ContinuousDistribution` The random variable :math:`X` with positive support. Returns ------- Y : `ContinuousDistribution` A random variable :math:`Y = \exp(X)`. Examples -------- Suppose we have a gamma distributed random variable :math:`X`: >>> import numpy as np >>> from scipy import stats >>> Gamma = stats.make_distribution(stats.gamma) >>> X = Gamma(a=1.0) We wish to have a exp-gamma distributed random variable :math:`Y`, a random variable whose natural exponential is :math:`X`. If :math:`X` is to be the natural exponential of :math:`Y`, then we must take :math:`Y` to be the natural logarithm of :math:`X`. >>> Y = stats.log(X) To demonstrate that ``X`` represents the exponential of ``Y``, we plot a normalized histogram of the exponential of observations of ``Y`` against the PDF underlying ``X``. >>> import matplotlib.pyplot as plt >>> rng = np.random.default_rng(435383595582522) >>> y = Y.sample(shape=10000, rng=rng) >>> ax = plt.gca() >>> ax.hist(np.exp(y), bins=50, density=True) >>> X.plot(ax=ax) >>> plt.legend(('PDF of `X`', 'histogram of `exp(y)`')) >>> plt.show() rzXThe logarithm of a random variable is only implemented when the support is non-negative.c|SrrCr]s rrzlog..vsArr)r@r2r0r/rOr&r%)rras rr&r&FsVV vvaiik!nq !.!'** +A266bff2= ??rr)UrWabcrrrrrnumpyr@rscipy._lib._array_apirscipy._lib._utilrr scipy._lib._docscraper r scipyr r scipy.special._ufuncsrscipy.integraterrrscipy.optimize._bracketrrscipy.optimize._chandrupatlarr%scipy.stats._probability_distributionr scipy.statsrrrr__all__r*rnr*rEr{rrrrrYrbrsrrrr}rrrrrrrr-rr rzrr{rrrrrr#r2r`r"r!rOrlr$r%r&rCrrr.s#% ,4: +7CNJ * ,   h-$c-$`JJZ'9I'9TA6yA6Ha$a$H7)Z7)tG G T^B)X&RBJ,&& ,48,:GTM 5M ZAJ3J,NG1NGdY WYY L Y = Y  m YY ]Y.Y%Y"Y=Y.YY(Y "!Y"$#Y$(%Y&+'Y(')Y*"+Y,0-Y.//Y01Y2!3Y4,5Y6N7Y8 9Y:*;Y<#=Y>?Y@!AYB"CYDEYF"GYHIYJKYL \MYN \OYP'QYR-SYT jUYV3S>lFF7rvv=2@YC 7YCxJ)!8J)ZJ3Z_&_D {'>{|g-0g-T'!T+H\0?r