L iG ddlZddlZddlZddlmZddlmZddlm Z m Z m Z ddl mZddlm Z dd gZd Zd Zd Zd ZdZdZdZdZdZdZdZdZdZdZdZdZ dZ!dZ"dZ#dZ$dZ%dZ&d Z'id!ed"d#d$d%d&dd'd(ed)d*eed+d,d-ed.ed/d0d1d2ed3ed4d5ed6d7d$d8ed9d:d4d;ed<d=d4d>d?dd'd@edAdBd$dCedDdEd$dFdGdd'dHedIdJd$dKdLdMd'dNedOdPd$dQdRdSdJd$dTe$dUe#d$idVdWdXd'dYdZd[d'd\d]dJd'd^ed_d`d$dae&dbe%d$dce!dddMd$dedfdJd'dgdhdJd'didjdkd'dldmdnd'dodpdJd'dqdrdsdtd4due'dMdvd4dwdxdydJd$dzd{dMd'd|d}dd'd~e"dMd'e ddd$eddMd$dZ(dZ)GddZ*GddZ+Gdd Z,y)N)stats)special)check_random_stateHalton QMCEngine)NumericalInversePolynomial)rFastGeneratorInversion RatioUniformsc|dkr?d||zz }|tj|ztjd|dzz|zzStj|tj| zS)Nr)mathsqrtexp)xchiys [/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/stats/_sampling.py argus_pdfrsc ax AI499Q<$((4#q&=1+<"=== 99Q<$((A2, &&cR|dkr|Stjdd|z|dzz z S)Nr ?r)nprrrs rargus_gamma_trfrs. ax 773Qa' ((rc2|dkr|Sd|dzzd|dzz zS)Nr ?rrrs rargus_gamma_inv_trfr! s) ax a<1q!t8 $$rc:|dkDrc|dz tj|z||ztj|zz tj||z }tj |S|dkDry|dkrt jSdtj||z SNrr) rloglog1pscbetalnrrinfbeta)rablogfs r betaprime_pdfr-&s1uA!$AA'>>1aPxx~ q5 U66Mrwwq!}$ $rcBt||dk\xrt||dkS)N皙?iminmaxr*r+s rbeta_valid_paramsr44s# 1I  43q!9#34rc|dkDrHtjtj| |dz tj|zz|z S|dk\rdStj SNrrr)rrlgammar$rr(rr*s r gamma_pdfr98sR1uxxQ1s7dhhqk*AAAEFFFq&&rc|dkDrKtj|dz tj|ztj|z d|z z S|dk\rdStj Sr6rrr$r7rr(r8s r invgamma_pdfr<?sV1uxx!c' TXXa[04;;q>AAEIJJFq&&rc |dkDrdtj|}tj|dz |z|dztjtj| |zzz Syr#)rr$rrr%)rccddlxs rburr_pdfrAFsZ 1u XXa[vvQi"nQ$**RVVRC"H=M2N'NNOOrc|dkDr}tj|}tjtj||z}tj|dz |z|dz|zz tj||zzSyr#)rr$r%r)rr>r?r@logterms r burr12_pdfrDQsk1u XXa[**TXXb2g./xxa2 a7(::TXXb2g=NNOOrc|dkDrotj|dz tj|zd||zzz |dz dz tjdzz tjd|zz S|dk\rdStj S)Nrrrrr;r8s rchi_pdfrFZs1uxx Udhhqk !QUm 1uqyDHHQK' (kk#'" #  Fq&&rc|dkDrltj|dz dz tj|zd|zz |dz tjdzz tjd|zz S|dk\rdStj S)Nrrrrr;rdfs rchi2_pdfrJfs1uxx !VaZ488A; &Ag Av!$ %kk#(# $  !Gq''rc|dkDr:tjdtj|zd|d|z z dzzz Sy)Nrgrrrrrr$r8s r alpha_pdfrNrs?1uxxtxx{*SAaKA3E-EEFF rc6d|cxkrdkrnydd||zzz Sy)NrrrrLr rcs r bradford_pdfrRxs(A{{ cAEk"" rc|| kDrtjd|z|zStj|tj||z zd|z|zz |tj||z |z |z zz S)NrrrM)rr+ms rcrystalball_pdfrU~soA2vxxq1 %% 88AQ'#'A+5DHHQUQYQR]1u488QUdhhrl2rai@AAA rc|dkDr9|tj|dz tj|z|| zz zSyrWrMrPs rinvweibull_pdfr\s>1u488a!eHtxx{2QA2Y>??? rc|dkDr;tj|dz dz d|zz tj|dzz Sy)NrrrrL)rrrrs rwald_pdfr`s?1uxx1q5Q,1q512TYYq!t_DD rc|dkDr*tjd|z dz|dzzd|z z |z S|tjd|z dz|dzzd|z zz SNrrrrpr+s rgeninvgauss_moderfse1u 1q5Q,A-.!a%8A==  1q5Q,A-.!a%8 99rct||}|dz tj|zd|z|d|z zzz }|dkDr@tj|dz tj|zd|z|d|z zzz |z Sy)NrrrrL)rfrr$r)rrer+rTlfms rgeninvgauss_pdfrisAA q5DHHQK #'QQY"7 7C1uxxQ$((1+-a1q1u90EEKLL rcJdtjdd||zz zdzz S)Nrg@r?rcmus r invgauss_moderns( $))IR"W 56< ==rct|}dtj|z||z dzd|z|dzzz z }|dkDrCtjdtj|z||z dzd|z|dzzz z |z Sy)NgrrrL)rnrr$r)rrmrTrhs r invgauss_pdfrpsbA ! B1}AA > >C1uxxtxx{*a"f]a!eb!em-LLsRSS rc|dkDr||dz zSyrWr r8s r powerlaw_pdfrrs1uQU| ralphac"d|cxkxrdkScS)Ngdy=g Ar r*s rrvsw!';e';';rcDdtj||zdz|z zS)N?g @rcrus rrvrvs!DDIIa!eck$:Q$>?r)pdfcheck_pinv_paramscenteranglitc8tjd|zdzS)NrgvIh%<=rcosr_s rrvrvs!a%72r)ryr{argusc|dkrdSdS)Nr gffffff?rr rs rrvrvsSAXc3rc"d|cxkxrdkScS)Ng#B ;ir rs rrvrvs):s):):rc |dkDS)Nr r rs rrvrvs cAgr)ryr{rz rvs_transformrvs_transform_invmirror_uniformr)c,td|dz |dzz SNr/rr2r3s rrvrvs3Q1q5(9:rc|d|zz SNrr rargss rrvrvs!q1u+rc<|dkr|d|z z StjSr)rr(rs rrvrvsQUa1q5kr)ryr{rzrr betaprimec,td|dz |dzz Srrr3s rrvrvrr)ryr{rzbradfordc"d|cxkxrdkScS)Ngư>eAr rus rrvrvsv'9c'9'9rrburrc$dd|z zdz d|z zS)Nrrr r3s rrvrvsa!e q 0b1f=rcBt||dk\xrt||dkS)Ng333333?2r0r3s rrvrv 3q!9+;*R#a)r/rburr12c$dd|z zdz d|z zS)Nrrr r3s rrvrvsa!e q 0a!e<rcBt||dk\xrt||dkS)Ng?rr0r3s rrvrvrrcauchycdd||zzz Srr r_s rrvrvsa1q5k*rrc"d|cxkxrdkScS)Ng?.Ar rIs rrvrv s(;e(;(;rc,tj|SNrcrus rrvrv sDIIaLrchi2c"d|cxkxrdkScSNgQ?rr rs rrvrvs(9c(9(9rc|Srr rus rrvrvArcosinec2dtj|zSrr~r_s rrvrvsTXXa[r crystalballcFd|cxkxrdkncxrd|cxkxrdkScS)Ng{Gz?g@g?gfffffR@r )r+rTs rrvrvs-41+;+;+ A   rrLexponc.tj| Srrrr_s rrvrvs1"rrgammac"d|cxkxrdkScSNg{Gz?rr rus rrvrv$tq'7C'7'7rc|Srr rus rrvrv%rrgennormcFtjt||z Srrrabsrr+s rrvrv(sDHHc!fk\2rc"d|cxkxrdkScS)Ng#~j?gF@r r+s rrvrv)su'9T'9'9r geninvgausscBt|dkxrd|cxkxrdkScS)Ng@绽|=)rrds rrvrv.s,3q6V+;+%  #V # #rgumbel_lcXtj|tj|z Srrr_s rrvrv3s!dhhqk/2rg333333gumbel_rc\tj| tj| z Srrr_s rrvrv7s 1"txx|"34rg333333? hypsecantc`dtj|tj| zz SNrrr_s rrvrv;s" dhhrl :;rinvgammac"d|cxkxrdkScSrr rus rrvrv@rrc d|z Srr rus rrvrvAs AErinvgaussc"d|cxkxrdkScS)Nrrr rls rrvrvEs2(>(>(>r invweibullc"d|cxkxrdkScS)NgQ?r rus rrvrvJrrlaplacec@tjt| Srrr_s rrvrvNs3q6'*rlogisticchtj| dtj| zdzz Srbrr_s rrvrvRs)1"TXXqb\)9a(??rmaxwellcD||ztjd|z|zzSNrrr_s rrvrvVs Q$(Q,!77rg:?moyalcbtj|tj| z dz SNrrr_s rrvrvZs&A! $4"5"9:rg333333?normc:tj| |zdz Srrr_s rrvrv^s1"q&1*-rparetoc||dz zSrr rs rrvrvbsA1q5Mrc |dkDr||dz z SdS)Nrrrkr rs rrvrvcs1q5AQKcrc"d|cxkxrdkScS)Ng{Gz?ir rs rrvrvdstq':F':':rpowerlawc"d|cxkxrdkScS)NgQ?gj@r rus rrvrvistq'9E'9'9rtc*d||z|z zd|dzzzS)Nrrr rHs rrvrvlsa!a%"*n$"q&/Brc"d|cxkxrdkScSrr rus rrvrvmrrrayleighc>|tjd||zzzSrrr_s rrvrvqsTXXda!en55r semicircularc8tjd||zz Srrcr_s rrvrvus3!a%=1rwaldc"d|cxkxrdkScSNrxrr rus rrvrv~rrgc"d|cxkxrdkScSrr rus rrvrvrr) weibull_max weibull_minct|tr2||j|k7r d}t|| |jn|}||fS||dn|}t ||}||fSd}t|)Nz6`d` must be consistent with dimension of `qmc_engine`.r)seedzJ`qmc_engine` must be an instance of `scipy.stats.qmc.QMCEngine` or `None`.) isinstancerd ValueErrorr) qmc_enginerrmessages r_validate_qmc_inputrs*i( =Z\\Q.NGW% %IJLL1 q=  AAD)  q=  5 !!rceZdZdZdZy)CustomDistPINVcfd|_y)Nc|gSrr )rrrys rrvz)CustomDistPINV.__init__..sc!mdmr_pdf)selfryrs ``r__init__zCustomDistPINV.__init__s + rc$|j|Srr)rrs rryzCustomDistPINV.pdfsyy|rN)__name__ __module__ __qualname__rryr rrrrs ,rrceZdZdZdddddZedZejdZedZejd Zed Z e jd Z d Z d Z ddZ dZ ddZddZdZdZdZy)r uD Fast sampling by numerical inversion of the CDF for a large class of continuous distributions in `scipy.stats`. Parameters ---------- dist : rv_frozen object Frozen distribution object from `scipy.stats`. The list of supported distributions can be found in the Notes section. The shape parameters, `loc` and `scale` used to create the distributions must be scalars. For example, for the Gamma distribution with shape parameter `p`, `p` has to be a float, and for the beta distribution with shape parameters (a, b), both a and b have to be floats. domain : tuple of floats, optional If one wishes to sample from a truncated/conditional distribution, the domain has to be specified. The default is None. In that case, the random variates are not truncated, and the domain is inferred from the support of the distribution. ignore_shape_range : boolean, optional. If False, shape parameters that are outside of the valid range of values to ensure that the numerical accuracy (see Notes) is high, raise a ValueError. If True, any shape parameters that are valid for the distribution are accepted. This can be useful for testing. The default is False. random_state : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional A NumPy random number generator or seed for the underlying NumPy random number generator used to generate the stream of uniform random numbers. If `random_state` is None, it uses ``self.random_state``. If `random_state` is an int, ``np.random.default_rng(random_state)`` is used. If `random_state` is already a ``Generator`` or ``RandomState`` instance then that instance is used. Attributes ---------- loc : float The location parameter. random_state : {`numpy.random.Generator`, `numpy.random.RandomState`} The random state used in relevant methods like `rvs` (unless another `random_state` is passed as an argument to these methods). scale : float The scale parameter. Methods ------- cdf evaluate_error ppf qrvs rvs support Notes ----- The class creates an object for continuous distributions specified by `dist`. The method `rvs` uses a generator from `scipy.stats.sampling` that is created when the object is instantiated. In addition, the methods `qrvs` and `ppf` are added. `qrvs` generate samples based on quasi-random numbers from `scipy.stats.qmc`. `ppf` is the PPF based on the numerical inversion method in [1]_ (`NumericalInversePolynomial`) that is used to generate random variates. Supported distributions (`distname`) are: ``alpha``, ``anglit``, ``argus``, ``beta``, ``betaprime``, ``bradford``, ``burr``, ``burr12``, ``cauchy``, ``chi``, ``chi2``, ``cosine``, ``crystalball``, ``expon``, ``gamma``, ``gennorm``, ``geninvgauss``, ``gumbel_l``, ``gumbel_r``, ``hypsecant``, ``invgamma``, ``invgauss``, ``invweibull``, ``laplace``, ``logistic``, ``maxwell``, ``moyal``, ``norm``, ``pareto``, ``powerlaw``, ``t``, ``rayleigh``, ``semicircular``, ``wald``, ``weibull_max``, ``weibull_min``. `rvs` relies on the accuracy of the numerical inversion. If very extreme shape parameters are used, the numerical inversion might not work. However, for all implemented distributions, the admissible shape parameters have been tested, and an error will be raised if the user supplies values outside of the allowed range. The u-error should not exceed 1e-10 for all valid parameters. Note that warnings might be raised even if parameters are within the valid range when the object is instantiated. To check numerical accuracy, the method `evaluate_error` can be used. Note that all implemented distributions are also part of `scipy.stats`, and the object created by `FastGeneratorInversion` relies on methods like `ppf`, `cdf` and `pdf` from `rv_frozen`. The main benefit of using this class can be summarized as follows: Once the generator to sample random variates is created in the setup step, sampling and evaluation of the PPF using `ppf` are very fast, and performance is essentially independent of the distribution. Therefore, a substantial speed-up can be achieved for many distributions if large numbers of random variates are required. It is important to know that this fast sampling is achieved by inversion of the CDF. Thus, one uniform random variate is transformed into a non-uniform variate, which is an advantage for several simulation methods, e.g., when the variance reduction methods of common random variates or antithetic variates are be used ([2]_). In addition, inversion makes it possible to - to use a QMC generator from `scipy.stats.qmc` (method `qrvs`), - to generate random variates truncated to an interval. For example, if one aims to sample standard normal random variates from the interval (2, 4), this can be easily achieved by using the parameter `domain`. The location and scale that are initially defined by `dist` can be reset without having to rerun the setup step to create the generator that is used for sampling. The relation of the distribution `Y` with `loc` and `scale` to the standard distribution `X` (i.e., ``loc=0`` and ``scale=1``) is given by ``Y = loc + scale * X``. References ---------- .. [1] Derflinger, Gerhard, Wolfgang Hörmann, and Josef Leydold. "Random variate generation by numerical inversion when only the density is known." ACM Transactions on Modeling and Computer Simulation (TOMACS) 20.4 (2010): 1-25. .. [2] Hörmann, Wolfgang, Josef Leydold and Gerhard Derflinger. "Automatic nonuniform random number generation." Springer, 2004. Examples -------- >>> import numpy as np >>> from scipy import stats >>> from scipy.stats.sampling import FastGeneratorInversion Let's start with a simple example to illustrate the main features: >>> gamma_frozen = stats.gamma(1.5) >>> gamma_dist = FastGeneratorInversion(gamma_frozen) >>> r = gamma_dist.rvs(size=1000) The mean should be approximately equal to the shape parameter 1.5: >>> r.mean() 1.52423591130436 # may vary Similarly, we can draw a sample based on quasi-random numbers: >>> r = gamma_dist.qrvs(size=1000) >>> r.mean() 1.4996639255942914 # may vary Compare the PPF against approximation `ppf`. >>> q = [0.001, 0.2, 0.5, 0.8, 0.999] >>> np.max(np.abs(gamma_frozen.ppf(q) - gamma_dist.ppf(q))) 4.313394796895409e-08 To confirm that the numerical inversion is accurate, we evaluate the approximation error (u-error), which should be below 1e-10 (for more details, refer to the documentation of `evaluate_error`): >>> gamma_dist.evaluate_error() (7.446320551265581e-11, nan) # may vary Note that the location and scale can be changed without instantiating a new generator: >>> gamma_dist.loc = 2 >>> gamma_dist.scale = 3 >>> r = gamma_dist.rvs(size=1000) The mean should be approximately 2 + 3*1.5 = 6.5. >>> r.mean() 6.399549295242894 # may vary Let us also illustrate how truncation can be applied: >>> trunc_norm = FastGeneratorInversion(stats.norm(), domain=(3, 4)) >>> r = trunc_norm.rvs(size=1000) >>> 3 < r.min() < r.max() < 4 True Check the mean: >>> r.mean() 3.250433367078603 # may vary >>> stats.norm.expect(lb=3, ub=4, conditional=True) 3.260454285589997 In this particular, case, `scipy.stats.truncnorm` could also be used to generate truncated normal random variates. NF)domainignore_shape_range random_statec t|tjjrX|jj }|t jvr7td|dtt jtd|jjdd}|jjdd}|j}tj|s tdtj|s td tt||||d |_||_tj$|dj&} |j jj(} | | k7rtd | d | d ||_|.|j j-|_d|_d|_np||_|j j5|j.d|_|j j5|j.d|j0z } | |_|j7||_|j.|_|j=||}|j>R|j>|j.dg|} |j>|j.dg|} | | kDr| | } } | | f|_|j@a|j@|j:dkr|j:d|_ n0|j@|j:dkDr|j:d|_ tC||j*|j:|j@|_"y)NzDistribution 'z%' is not supported.It must be one of z+`dist` must be a frozen distribution objectlocrscalerloc must be scalar.scale must be scalar.)rr z Each of the z( shape parameters must be a scalar, but z values are provided.rLr)rrr{)#rr distributions rv_frozendistname PINV_CONFIGkeysrlistkwdsgetrrisscalargetattr _frozendist _distnamebroadcast_arrayssizenumargsrsupport_domain_p_lower _p_domaincdf_set_domain_adj_ignore_shape_range _domain_pinv_process_config_rvs_transform_inv_centerr _rng)rrrrrdistnamerr rnargsnargs_expectedrd0d1s rrzFastGeneratorInversion.__init__hs dE//99 :yy~~H{//11 $XJ/))-k.>.>.@)A(BD JK KiimmE1% gq)yy{{323 3{{5!45 5375(3   "##D)!,11))..66 N "~./$g%:<  ) >++335DLDM DN!DL ,,00aADM((,,T\\!_= MI&DN #5 !LL##Hd3  " " .(((a@4@B(((a@4@BBwRB!#BD  << #||d//22#003  1 1! 44#003 . **$$<<  rc|jSr) _random_staters rrz#FastGeneratorInversion.random_states!!!rc$t||_yr)check_random_state_qmcr.)rrs rrz#FastGeneratorInversion.random_states3LArcN|jjjddS)Nrrrrrr/s rrzFastGeneratorInversion.locs!$$((22rctj|s td||jjd<|j y)Nr rrrrrrr!)rrs rrzFastGeneratorInversion.locs<{{323 3'*e$ rcN|jjjddS)Nr rr3r/s rr zFastGeneratorInversion.scales!$$((!44rctj|s td||jjd<|j y)Nr r r5)rr s rr zFastGeneratorInversion.scales<{{5!45 5).g& rc|j}|j}|jd|z|z}|jd|z|z}||f|_y)z+ Adjust the domain based on loc and scale. rrN)rr r _domain_adj)rrr lbubs rr!z&FastGeneratorInversion._set_domain_adjsNhh  \\!_u $s * \\!_u $s *8rct|}d|vr%|js|d|sd|d}t|d|jvr1t j |ds|d||_n|d|_nd|_|jdd|_|jdd|_ |jdd}|d|_ n |||_ t|d |S) Nrzz1No generator is defined for the shape parameters z=. Use ignore_shape_range to proceed with the selected values.r{rrrFry) rr"rrrrr&r_rvs_transformr%_mirror_uniformr)rr(rcfgmsgr>s rr$z&FastGeneratorInversion._process_configs(# # %++/s./6N"V$77C%S/) sxxz !;;s8}-,s8}d3 "8} DL!ggot<"%''*=t"D''"2D9  "#(D #2D#9D c%j$//rc0|jj|}|jrd|z }|jj |}|j '|j |g|j j}|j|j|zzS)a Sample from the distribution by inversion. Parameters ---------- size : int or tuple, optional The shape of samples. Default is ``None`` in which case a scalar sample is returned. Returns ------- rvs : array_like A NumPy array of random variates. Notes ----- Random variates are generated by numerical inversion of the CDF, i.e., `ppf` computed by `NumericalInversePolynomial` when the class is instantiated. Note that the default ``rvs`` method of the rv_continuous class is overwritten. Hence, a different stream of random numbers is generated even if the same seed is used. rr) runiformr>r'ppfr=rrrr )rrurs rrvszFastGeneratorInversion.rvss4    % %4 % 0   AA IIMM!     *###A>(8(8(=(=>Axx$**q.((rcVtj|}|jr|jj d|z }n|jj |}|j '|j |g|j j}|j|z|jzS)a Very fast PPF (inverse CDF) of the distribution which is a very close approximation of the exact PPF values. Parameters ---------- u : array_like Array with probabilities. Returns ------- ppf : array_like Quantiles corresponding to the values in `u`. Notes ----- The evaluation of the PPF is very fast but it may have a large relative error in the far tails. The numerical precision of the PPF is controlled by the u-error, that is, ``max |u - CDF(PPF(u))|`` where the max is taken over points in the interval [0,1], see `evaluate_error`. Note that this PPF is designed to generate random samples. r) rasarrayr>r'rDr=rrr rrqrs rrDzFastGeneratorInversion.ppf)s2 JJqM    a!e$A a A    *###A>(8(8(=(=>AzzA~((rc6t|||j\}} |d}n t|}|dnt j |}|j |}|jrd|z }|j|}|j'|j|g|jj}||jd}n,|dk(r|j|}n|j||fz}|j|j|zzS#t$r|f}YwxYw)a Quasi-random variates of the given distribution. The `qmc_engine` is used to draw uniform quasi-random variates, and these are converted to quasi-random variates of the given distribution using inverse transform sampling. Parameters ---------- size : int, tuple of ints, or None; optional Defines shape of random variates array. Default is ``None``. d : int or None, optional Defines dimension of uniform quasi-random variates to be transformed. Default is ``None``. qmc_engine : scipy.stats.qmc.QMCEngine(d=1), optional Defines the object to use for drawing quasi-random variates. Default is ``None``, which uses `scipy.stats.qmc.Halton(1)`. Returns ------- rvs : ndarray or scalar Quasi-random variates. See Notes for shape information. Notes ----- The shape of the output array depends on `size`, `d`, and `qmc_engine`. The intent is for the interface to be natural, but the detailed rules to achieve this are complicated. - If `qmc_engine` is ``None``, a `scipy.stats.qmc.Halton` instance is created with dimension `d`. If `d` is not provided, ``d=1``. - If `qmc_engine` is not ``None`` and `d` is ``None``, `d` is determined from the dimension of the `qmc_engine`. - If `qmc_engine` is not ``None`` and `d` is not ``None`` but the dimensions are inconsistent, a ``ValueError`` is raised. - After `d` is determined according to the rules above, the output shape is ``tuple_shape + d_shape``, where: - ``tuple_shape = tuple()`` if `size` is ``None``, - ``tuple_shape = (size,)`` if `size` is an ``int``, - ``tuple_shape = size`` if `size` is a sequence, - ``d_shape = tuple()`` if `d` is ``None`` or `d` is 1, and - ``d_shape = (d,)`` if `d` is greater than 1. The elements of the returned array are part of a low-discrepancy sequence. If `d` is 1, this means that none of the samples are truly independent. If `d` > 1, each slice ``rvs[..., i]`` will be of a quasi-independent sequence; see `scipy.stats.qmc.QMCEngine` for details. Note that when `d` > 1, the samples returned are still those of the provided univariate distribution, not a multivariate generalization of that distribution. rrr )rrtuple TypeErrorrprodrandomr>_ppfr=rrsqueezereshaperr )rrrr tuple_sizeNrEqrvss rrWzFastGeneratorInversion.qrvsKsn,J4;L;LM A !|! "4[ A2774=   a    AAyy|    *&4&&tDd.>.>.C.CDD <<<>"%DAv||J/||J!$56xx$**t+++% !J !sD DDct|tjtjzs t dt |}|j|}|jrd|z }|j|}tjtj|j||z }|s|tjfS|j|}tj|j||z } | tj|z } tj| | gj!d} |tj| fS)u Evaluate the numerical accuracy of the inversion (u- and x-error). Parameters ---------- size : int, optional The number of random points over which the error is estimated. Default is ``100000``. random_state : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional A NumPy random number generator or seed for the underlying NumPy random number generator used to generate the stream of uniform random numbers. If `random_state` is None, use ``self.random_state``. If `random_state` is an int, ``np.random.default_rng(random_state)`` is used. If `random_state` is already a ``Generator`` or ``RandomState`` instance then that instance is used. Returns ------- u_error, x_error : tuple of floats A NumPy array of random variates. Notes ----- The numerical precision of the inverse CDF `ppf` is controlled by the u-error. It is computed as follows: ``max |u - CDF(PPF(u))|`` where the max is taken `size` random points in the interval [0,1]. `random_state` determines the random sample. Note that if `ppf` was exact, the u-error would be zero. The x-error measures the direct distance between the exact PPF and `ppf`. If ``x_error`` is set to ``True`, it is computed as the maximum of the minimum of the relative and absolute x-error: ``max(min(x_error_abs[i], x_error_rel[i]))`` where ``x_error_abs[i] = |PPF(u[i]) - PPF_fast(u[i])|``, ``x_error_rel[i] = max |(PPF(u[i]) - PPF_fast(u[i])) / PPF(u[i])|``. Note that it is important to consider the relative x-error in the case that ``PPF(u)`` is close to zero or very large. By default, only the u-error is evaluated and the x-error is set to ``np.nan``. Note that the evaluation of the x-error will be very slow if the implementation of the PPF is slow. Further information about these error measures can be found in [1]_. References ---------- .. [1] Derflinger, Gerhard, Wolfgang Hörmann, and Josef Leydold. "Random variate generation by numerical inversion when only the density is known." ACM Transactions on Modeling and Computer Simulation (TOMACS) 20.4 (2010): 1-25. Examples -------- >>> import numpy as np >>> from scipy import stats >>> from scipy.stats.sampling import FastGeneratorInversion Create an object for the normal distribution: >>> d_norm_frozen = stats.norm() >>> d_norm = FastGeneratorInversion(d_norm_frozen) To confirm that the numerical inversion is accurate, we evaluate the approximation error (u-error and x-error). >>> u_error, x_error = d_norm.evaluate_error(x_error=True) The u-error should be below 1e-10: >>> u_error 8.785783212061915e-11 # may vary Compare the PPF against approximation `ppf`: >>> q = [0.001, 0.2, 0.4, 0.6, 0.8, 0.999] >>> diff = np.abs(d_norm_frozen.ppf(q) - d_norm.ppf(q)) >>> x_error_abs = np.max(diff) >>> x_error_abs 1.2937954707581412e-08 This is the absolute x-error evaluated at the points q. The relative error is given by >>> x_error_rel = np.max(diff / np.abs(d_norm_frozen.ppf(q))) >>> x_error_rel 4.186725600453555e-09 The x_error computed above is derived in a very similar way over a much larger set of random values q. At each value q[i], the minimum of the relative and absolute error is taken. The final value is then derived as the maximum of these values. In our example, we get the following value: >>> x_error 4.507068014335139e-07 # may vary zsize must be an integer.rBrr)axis)rnumbersIntegralrintegerrr1rCr>rDr2r_cdfnanrRarrayr1) rrrx_errorurngrEruerrppf_u x_error_abs x_error_relx_error_combineds revaluate_errorz%FastGeneratorInversion.evaluate_errors P$ 0 02:: =>78 8 &l3 LLdL #   AA HHQKvvbffTYYq\A-./<  ! ffTXXa[./ !BFF5M1 88[+$>?CCCKRVV,---rc|jS)aSupport of the distribution. Returns ------- a, b : float end-points of the distribution's support. Notes ----- Note that the support of the distribution depends on `loc`, `scale` and `domain`. Examples -------- >>> from scipy import stats >>> from scipy.stats.sampling import FastGeneratorInversion Define a truncated normal distribution: >>> d_norm = FastGeneratorInversion(stats.norm(), domain=(0, 1)) >>> d_norm.support() (0, 1) Shift the distribution: >>> d_norm.loc = 2.5 >>> d_norm.support() (2.5, 3.5) )r9r/s rrzFastGeneratorInversion.supportsBrc|jj|}|jdk(r|Stj||j z |jz ddS)zCumulative distribution function (CDF) Parameters ---------- x : array_like The values where the CDF is evaluated Returns ------- y : ndarray CDF evaluated at x rrr)rr rrclipr)rrrs rr]zFastGeneratorInversion._cdf>sP     # >>S HwwDMM)T^^;QBBrcH|jdk(r|jj|S|jj|jtj|z|j z}tj ||jd|jdS)aPercent point function (inverse of `cdf`) Parameters ---------- q : array_like lower tail probability Returns ------- x : array_like quantile corresponding to the lower tail probability q. rrr)rrrDrr_rrjr9rJs rrRzFastGeneratorInversion._ppfQs >>S ##''* *    "((1+!= !M Nwwq$**1-t/?/?/BCCrr)NNN)iNF)rrr__doc__rpropertyrsetterrr r!r$rGrDrWrgrr]rRr rrr r s~H  Zx""BB33 ZZ55 \\$06 )D )DR,hz.x! FC&Drc&eZdZdZddddZddZy)r ag Generate random samples from a probability density function using the ratio-of-uniforms method. Parameters ---------- pdf : callable A function with signature `pdf(x)` that is proportional to the probability density function of the distribution. umax : float The upper bound of the bounding rectangle in the u-direction. vmin : float The lower bound of the bounding rectangle in the v-direction. vmax : float The upper bound of the bounding rectangle in the v-direction. c : float, optional. Shift parameter of ratio-of-uniforms method, see Notes. Default is 0. random_state : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional If `seed` is None (or `np.random`), the `numpy.random.RandomState` singleton is used. If `seed` is an int, a new ``RandomState`` instance is used, seeded with `seed`. If `seed` is already a ``Generator`` or ``RandomState`` instance then that instance is used. Methods ------- rvs Notes ----- Given a univariate probability density function `pdf` and a constant `c`, define the set ``A = {(u, v) : 0 < u <= sqrt(pdf(v/u + c))}``. If ``(U, V)`` is a random vector uniformly distributed over ``A``, then ``V/U + c`` follows a distribution according to `pdf`. The above result (see [1]_, [2]_) can be used to sample random variables using only the PDF, i.e. no inversion of the CDF is required. Typical choices of `c` are zero or the mode of `pdf`. The set ``A`` is a subset of the rectangle ``R = [0, umax] x [vmin, vmax]`` where - ``umax = sup sqrt(pdf(x))`` - ``vmin = inf (x - c) sqrt(pdf(x))`` - ``vmax = sup (x - c) sqrt(pdf(x))`` In particular, these values are finite if `pdf` is bounded and ``x**2 * pdf(x)`` is bounded (i.e. subquadratic tails). One can generate ``(U, V)`` uniformly on ``R`` and return ``V/U + c`` if ``(U, V)`` are also in ``A`` which can be directly verified. The algorithm is not changed if one replaces `pdf` by k * `pdf` for any constant k > 0. Thus, it is often convenient to work with a function that is proportional to the probability density function by dropping unnecessary normalization factors. Intuitively, the method works well if ``A`` fills up most of the enclosing rectangle such that the probability is high that ``(U, V)`` lies in ``A`` whenever it lies in ``R`` as the number of required iterations becomes too large otherwise. To be more precise, note that the expected number of iterations to draw ``(U, V)`` uniformly distributed on ``R`` such that ``(U, V)`` is also in ``A`` is given by the ratio ``area(R) / area(A) = 2 * umax * (vmax - vmin) / area(pdf)``, where `area(pdf)` is the integral of `pdf` (which is equal to one if the probability density function is used but can take on other values if a function proportional to the density is used). The equality holds since the area of ``A`` is equal to ``0.5 * area(pdf)`` (Theorem 7.1 in [1]_). If the sampling fails to generate a single random variate after 50000 iterations (i.e. not a single draw is in ``A``), an exception is raised. If the bounding rectangle is not correctly specified (i.e. if it does not contain ``A``), the algorithm samples from a distribution different from the one given by `pdf`. It is therefore recommended to perform a test such as `~scipy.stats.kstest` as a check. References ---------- .. [1] L. Devroye, "Non-Uniform Random Variate Generation", Springer-Verlag, 1986. .. [2] W. Hoermann and J. Leydold, "Generating generalized inverse Gaussian random variates", Statistics and Computing, 24(4), p. 547--557, 2014. .. [3] A.J. Kinderman and J.F. Monahan, "Computer Generation of Random Variables Using the Ratio of Uniform Deviates", ACM Transactions on Mathematical Software, 3(3), p. 257--260, 1977. Examples -------- >>> import numpy as np >>> from scipy import stats >>> from scipy.stats.sampling import RatioUniforms >>> rng = np.random.default_rng() Simulate normally distributed random variables. It is easy to compute the bounding rectangle explicitly in that case. For simplicity, we drop the normalization factor of the density. >>> f = lambda x: np.exp(-x**2 / 2) >>> v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2) >>> umax = np.sqrt(f(0)) >>> gen = RatioUniforms(f, umax=umax, vmin=-v, vmax=v, random_state=rng) >>> r = gen.rvs(size=2500) The K-S test confirms that the random variates are indeed normally distributed (normality is not rejected at 5% significance level): >>> stats.kstest(r, 'norm')[1] 0.250634764150542 The exponential distribution provides another example where the bounding rectangle can be determined explicitly. >>> gen = RatioUniforms(lambda x: np.exp(-x), umax=1, vmin=0, ... vmax=2*np.exp(-1), random_state=rng) >>> r = gen.rvs(1000) >>> stats.kstest(r, 'expon')[1] 0.21121052054580314 rN)rQrc||k\r td|dkr td||_||_||_||_||_t ||_y)Nzvmin must be smaller than vmax.rzumax must be positive.)rr_umax_vmin_vmax_crr')rryumaxvminvmaxrQrs rrzRatioUniforms.__init__sW 4<>? ? 1956 6    &|4 rcttj|}tj|}tj|}d\}}||kr||z }|j |j j|z}|j j|j|j|} | |z |jz} |dz|j| k} tj| } | dkDr| | |||| z|| z }|dk(r||zdk\rd||zd} t| |dz }||krtj||S) amSampling of random variates Parameters ---------- size : int or tuple of ints, optional Number of random variates to be generated (default is 1). Returns ------- rvs : ndarray The random variates distributed according to the probability distribution defined by the pdf. )rrrBrriPz2Not a single random variate could be generated in z attempts. The ratio of uniforms method does not appear to work for the provided parameters. Please check the pdf and the bounds.r)rNr atleast_1drPzerosrqr'rCrrrsrtrsum RuntimeErrorrT)rrsize1drVr simulatediku1v1rGaccept num_acceptr@s rrGzRatioUniforms.rvssJr}}T*+ GGFO HHQK 1!mI Adii//Q/77B""4::tzz"BBr'DGG#C!etyy~-FJA~8;F )Y35Z' QQqSE\H1N** #3'' FA+!m.zz!V$$rrM)rrrrlrrGr rrr r eszx454 52%r)-rrZnumpyrscipyrrr&_qmcrr1rr_unuran.unuran_wrapperr scipy._lib._util__all__rrr!r-r4r9r<rArDrFrJrNrRrUrXrZr\r`rfrirnrprrrrrr r r rrrsr &&>/ $_ 5 ') % %5'' ' (  U     : >Bo ;?o  2  o 6:(0- o( :.5N  )o6:.7o@9AoJ =R KoT <RUo^ *_of ;( gop 9 qoz ({oB CoN %OoV 7Wo`29aoj%" kov2wo~4oF;GoN7!OoX>Yob7col*mot?uo|7}oD :EoL - MoT )9:Uo^9_ohB7 ior5soz1{oB  CoL7 7Uo d,{ D{ D|}%}%r