
    (phH              	          S SK r S SKrS SKrS SKJr  S SKJr  SSKJ	r
JrJr  SSKJr  S SKJ	r	  SS	/rS
 rS rS rS rS rS rS rS rS rS rS rS rS rS rS rS r S r!S r"S r#S r$S r%S r&S  r'0 S!\S" S# S$._S%S& S S'._S(\S) S* \\S+ S,._S-\S. \S/ S0 S1._S2\S3 \S4._S5\S6 S7S$._S8\S9 S: S4._S;\S< S= S4._S>S? S S'._S@\SA SB S$._SC\SD SE S$._SFSG S S'._SH\SI SJS$._SKSL SMS'._SN\SO SP S$._SQSR SS SJS$._ST\$SU \#S$._0 SVSW SXS'._SYSZ S[S'._S\S] SJS'._S^\S_ S` S$._Sa\&Sb \%S$._Sc\!Sd SMS$._SeSf SJS'._SgSh SJS'._SiSj SkS'._SlSm SnS'._SoSp SJS'._SqSr Ss St S4._Su\'SMSv S4._SwSx Sy SJS$._SzS{ SMS'._S|S} S S'._S~\"SMS'._E\ S SS$.\S SMS$.S.Er(S r) " S S5      r* " S S5      r+ " S S	5      r,g)    N)stats)special   )check_random_stateHalton	QMCEngine)NumericalInversePolynomial)r   FastGeneratorInversionRatioUniformsc                     US::  a@  SX -  -
  nU [         R                  " U5      -  [         R                  " SUS-  -  U-  5      -  $ [         R                  " U 5      [         R                  " U * 5      -  $ )N   r            )mathsqrtexp)xchiys      H/var/www/html/venv/lib/python3.13/site-packages/scipy/stats/_sampling.py	argus_pdfr      sa     axI499Q<$((4#q&=1+<"===99Q<$((A2,&&    c                 V    US::  a  U $ [         R                  " SSU -  US-  -  -
  5      $ )Nr         ?r   )npr   r   r   s     r   argus_gamma_trfr      s.    
ax773Qa'((r   c                 4    US::  a  U $ SUS-  -  SU S-  -
  -  $ )Nr         ?r   r    r   s     r   argus_gamma_inv_trfr!       s)    
axa<1q!t8$$r   c                 D   U S:  ae  US-
  [         R                  " U 5      -  X-   [         R                  " U 5      -  -
  [        R                  " X5      -
  n[         R
                  " U5      $ US:  a  gUS:  a  [        R                  $ S[        R                  " X5      -  $ Nr   r   )	r   loglog1pscbetalnr   r   infbeta)r   ablogfs       r   betaprime_pdfr-   &   s}    1uA!$A'>>1Pxx~ q5U66Mrwwq}$$r   c                 H    [        X5      S:  =(       a    [        X5      S:*  $ )N皙?i  minmaxr*   r+   s     r   beta_valid_paramsr4   4   s    I43q9#34r   c                     U S:  aK  [         R                  " [         R                  " U5      * US-
  [         R                  " U 5      -  -   U -
  5      $ US:  a  S$ [        R
                  $ Nr   r   r   )r   r   lgammar$   r   r(   r   r*   s     r   	gamma_pdfr9   8   sR    1uxxQ1s7dhhqk*AAAEFFFq&&r   c                     U S:  aN  [         R                  " US-   * [         R                  " U 5      -  [         R                  " U5      -
  SU -  -
  5      $ US:  a  S$ [        R
                  $ r6   r   r   r$   r7   r   r(   r8   s     r   invgamma_pdfr<   ?   sV    1uxx!c'
TXXa[04;;q>AAEIJJFq&&r   c           
          U S:  ah  [         R                  " U 5      n[        R                  " US-   * U-  US-   [         R                  " [        R                  " U* U-  5      5      -  -
  5      $ gr#   )r   r$   r   r   r%   )r   ccddlxs       r   burr_pdfrA   F   sZ     	1uXXa[vvQi"nQ$**RVVRC"H=M2N'NNOOr   c                    U S:  a  [         R                  " U 5      n[         R                  " [         R                  " X-  5      5      n[         R                  " US-
  U-  US-   U-  -
  [         R                  " X-  5      -   5      $ gr#   )r   r$   r%   r   )r   r>   r?   r@   logterms        r   
burr12_pdfrD   Q   sg    1uXXa[**TXXbg./xxa2a7(::TXXbg=NNOOr   c                 "   U S:  ar  [         R                  " US-
  [         R                  " U 5      -  SX -  -  -
  US-  S-
  [         R                  " S5      -  -
  [         R                  " SU-  5      -
  5      $ US:  a  S$ [        R
                  $ )Nr   r   r   r   r;   r8   s     r   chi_pdfrF   Z   s    1uxxUdhhqk!QUm1uqyDHHQK'( kk#'"#
 	
 Fq&&r   c                    U S:  ap  [         R                  " US-  S-
  [         R                  " U 5      -  SU -  -
  US-  [         R                  " S5      -  -
  [         R                  " SU-  5      -
  5      $ US:  a  S$ [        R
                  $ )Nr   r   r   r   r;   r   dfs     r   chi2_pdfrJ   f   s    1uxx!VaZ488A;&AgAv!$% kk#(#$
 	
 !Gq''r   c                     U S:  a<  [         R                  " S[         R                  " U 5      -  SUSU -  -
  S-  -  -
  5      $ g)Nr   g       r   r   r           r   r   r$   r8   s     r   	alpha_pdfrN   r   s?    1uxxtxx{*SAaKA3E-EEFFr   c                 8    SU s=::  a  S::  a  O  gSSX-  -   -  $ g)Nr   r   r   rL   r    r   cs     r   bradford_pdfrR   x   s&    A{{ cAEk""r   c                     X* :  a  [         R                  " SU -  U -  5      $ [         R                  " U[         R                  " X!-  5      -  SU-  U-  -
  U[         R                  " X!-  U-
  U -
  5      -  -
  5      $ )Nr   r   rM   )r   r+   ms      r   crystalball_pdfrU   ~   si    2vxxq1%%88A'#'A+5DHHQUQYQR]<S8SSTTr   c                     U S:  a8  U[         R                  " US-
  [         R                  " U 5      -  X-  -
  5      -  $ gNr   r   rL   rM   rP   s     r   weibull_min_pdfrX      s8    1u488QUdhhqk1AD8999r   c                     U S:  a;  U[         R                  " US-
  [         R                  " U * 5      -  U * U-  -
  5      -  $ grW   rM   rP   s     r   weibull_max_pdfrZ      s>    1u488QUdhhrl2rai@AAAr   c                     U S:  a:  U[         R                  " US-   * [         R                  " U 5      -  X* -  -
  5      -  $ grW   rM   rP   s     r   invweibull_pdfr\      s<    1u488a!eHtxx{2Q2Y>???r   c                     U S:  a=  [         R                  " U S-
  S-  * SU -  -  5      [         R                  " U S-  5      -  $ g)Nr   r   r      rL   )r   r   r   r   s    r   wald_pdfr`      s?    1uxx1q5Q,1q512TYYq!t_DDr   c                     U S:  a+  [         R                  " SU -
  S-  US-  -   5      SU -
  -
  U-  $ U[         R                  " SU -
  S-  US-  -   5      SU -
  -   -  $ Nr   r   r   r   pr+   s     r   geninvgauss_moderf      se    1u		1q5Q,A-.!a%8A==		1q5Q,A-.!a%899r   c                     [        X5      nUS-
  [        R                  " U5      -  SU-  USU-  -   -  -
  nU S:  aB  [        R                  " US-
  [        R                  " U 5      -  SU-  U SU -  -   -  -
  U-
  5      $ g)Nr   r   r   rL   )rf   r   r$   r   )r   re   r+   rT   lfms        r   geninvgauss_pdfri      s}    Aq5DHHQK
#'QQY"7
7C1uxxQ$((1+-a1q1u90EEKLLr   c                 J    S[         R                  " SSX -  -  -   5      S-   -  $ )Nr   g      @r         ?rc   mus    r   invgauss_modern      s&    $))IRW56<==r   c                    [        U5      nS[        R                  " U5      -  X!-
  S-  SU-  US-  -  -  -
  nU S:  aD  [        R                  " S[        R                  " U 5      -  X-
  S-  SU -  US-  -  -  -
  U-
  5      $ g)Ng      r   r   rL   )rn   r   r$   r   )r   rm   rT   rh   s       r   invgauss_pdfrp      s    bA
!
1}AA>
>C1uxxtxx{*af]a!eb!em-LLsRSSr   c                     U S:  a  XS-
  -  $ grW   r    r8   s     r   powerlaw_pdfrr      s    1uU|r   alphac                 ,    SU s=:*  =(       a    S:  $ s  $ )Ngdy=g    	Ar    r*   s    r   <lambda>rv      s    w!';';e';r   c                 D    S[         R                  " X -  S-   5      U -
  -  $ )N      ?g       @rc   ru   s    r   rv   rv      s    DDIIaeck$:Q$>?r   )pdfcheck_pinv_paramscenteranglitc                 :    [         R                  " SU -  5      S-   $ )Nr   gvIh%<=r   cosr_   s    r   rv   rv      s    !a%72r   )ry   r{   argusc                     U S::  a  S$ S$ )Nr   gffffff?r   r    r   s    r   rv   rv      s    SAXc636r   c                 ,    SU s=:  =(       a    S:  $ s  $ )Ng#B;i  r    r   s    r   rv   rv      s    ):):s):r   c                     U S:  $ )Nr   r    r   s    r   rv   rv      s    cAgr   )ry   r{   rz   rvs_transformrvs_transform_invmirror_uniformr)   c                 ,    [        SU S-
  US-   -  5      $ Nr/   r   r2   r3   s     r   rv   rv          s3Q1q5(9:r   c                     U SU -   -  $ Nr   r    r   argss     r   rv   rv      s    !q1u+r   c                 >    U S:  a  U SU -
  -  $ [         R                  $ r   )r   r(   r   s     r   rv   rv      s    QUa1q5k.N.Nr   )ry   r{   rz   r   r   	betaprimec                 ,    [        SU S-
  US-   -  5      $ r   r   r3   s     r   rv   rv      r   r   )ry   r{   rz   bradfordc                 ,    SU s=:*  =(       a    S:*  $ s  $ )Ngư>    eAr    ru   s    r   rv   rv      s    v'9'9c'9r   r   burrc                 $    SSU-  -  S-
  SU -  -  $ )Nr   r   r    r3   s     r   rv   rv      s    a!eq 0b1f=r   c                 H    [        X5      S:  =(       a    [        X5      S:*  $ )Ng333333?2   r0   r3   s     r   rv   rv          3q9+;*R#a)r/*Rr   burr12c                 $    SSU-  -  S-
  SU -  -  $ )Nr   r   r    r3   s     r   rv   rv     s    a!eq 0a!e<r   c                 H    [        X5      S:  =(       a    [        X5      S:*  $ )Ng?r   r0   r3   s     r   rv   rv     r   r   cauchyc                     SSX -  -   -  $ r   r    r_   s    r   rv   rv     s    a15k*r   r   c                 ,    SU s=:*  =(       a    S:*  $ s  $ )Ng?    .Ar    rI   s    r   rv   rv     s    (;(;e(;r   c                 .    [         R                  " U 5      $ Nrc   ru   s    r   rv   rv     s    DIIaLr   chi2c                 ,    SU s=:*  =(       a    S:*  $ s  $ NgQ?r   r    r   s    r   rv   rv     s    (9(9c(9r   c                     U $ r   r    ru   s    r   rv   rv         Ar   cosinec                 4    S[         R                  " U 5      -   $ r   r~   r_   s    r   rv   rv     s    TXXa[r   crystalballc                 d    SU s=:*  =(       a    S:*  Os  =(       a    SUs=:*  =(       a    S:*  $ s  $ )Ng{Gz?g      @g?gfffffR@r    )r+   rT   s     r   rv   rv     s3    41+;+;+; +A++r   rL   exponc                 0    [         R                  " U * 5      $ r   r   r   r_   s    r   rv   rv     s    1"r   r   gammac                 ,    SU s=:*  =(       a    S:*  $ s  $ Ng{Gz?r   r    ru   s    r   rv   rv   $      tq'7'7C'7r   c                     U $ r   r    ru   s    r   rv   rv   %  r   r   gennormc                 H    [         R                  " [        U 5      U-  * 5      $ r   r   r   absr   r+   s     r   rv   rv   (  s    DHHc!fk\2r   c                 ,    SU s=:*  =(       a    S:*  $ s  $ )Ng#~j?g     F@r    r+   s    r   rv   rv   )  s    u'9'9T'9r   geninvgaussc                 V    [        U 5      S:*  =(       a    SUs=:*  =(       a    S:*  $ s  $ )Ng     @绽|=)r   rd   s     r   rv   rv   .  s/    3q6V+; +%##V#+%#+%r   gumbel_lc                 \    [         R                  " U [         R                  " U 5      -
  5      $ r   r   r_   s    r   rv   rv   3  s    !dhhqk/2r   g333333gumbel_rc                 `    [         R                  " U * [         R                  " U * 5      -
  5      $ r   r   r_   s    r   rv   rv   7  s    1"txx|"34r   g333333?	hypsecantc                 d    S[         R                  " U 5      [         R                  " U * 5      -   -  $ Nr   r   r_   s    r   rv   rv   ;  s     dhhrl :;r   invgammac                 ,    SU s=:*  =(       a    S:*  $ s  $ r   r    ru   s    r   rv   rv   @  r   r   c                     SU -  $ r   r    ru   s    r   rv   rv   A  s    AEr   invgaussc                 ,    SU s=:*  =(       a    S:*  $ s  $ )Nr   r   r    rl   s    r   rv   rv   E  s    2(>(>(>r   
invweibullc                 ,    SU s=:*  =(       a    S:*  $ s  $ )NgQ?   r    ru   s    r   rv   rv   J  r   r   laplacec                 B    [         R                  " [        U 5      * 5      $ r   r   r_   s    r   rv   rv   N  s    3q6'*r   logisticc                 l    [         R                  " U * 5      S[         R                  " U * 5      -   S-  -  $ rb   r   r_   s    r   rv   rv   R  s'    1"TXXqb\)9a(??r   maxwellc                 D    X -  [         R                  " SU -  U -  5      -  $ Nr   r   r_   s    r   rv   rv   V  s    $(Q,!77r   g:?moyalc                 f    [         R                  " U [         R                  " U * 5      -   * S-  5      $ Nr   r   r_   s    r   rv   rv   Z  s$    A!$4"5"9:r   g333333?normc                 <    [         R                  " U * U -  S-  5      $ r   r   r_   s    r   rv   rv   ^  s    1"q&1*-r   paretoc                     XS-   * -  $ r   r    r   s     r   rv   rv   b  s    Aq5Mr   c                      U S:  a  X S-
  -  $ S$ )Nr   r   rk   r    r   s    r   rv   rv   c  s    1q5AQK9c9r   c                 ,    SU s=:*  =(       a    S:*  $ s  $ )Ng{Gz?i r    r   s    r   rv   rv   d  s    tq':':F':r   powerlawc                 ,    SU s=:*  =(       a    S:*  $ s  $ )NgQ?g     j@r    ru   s    r   rv   rv   i  s    tq'9'9E'9r   tc                 (    SX -  U-  -   SUS-   -  -  $ )Nr   r   r    rH   s     r   rv   rv   l  s    a!%"*n$"q&/Br   c                 ,    SU s=:*  =(       a    S:*  $ s  $ r   r    ru   s    r   rv   rv   m  r   r   rayleighc                 >    U [         R                  " SX -  -  5      -  $ r   r   r_   s    r   rv   rv   q  s    TXXdaen55r   semicircularc                 8    [         R                  " SX -  -
  5      $ r   rc   r_   s    r   rv   rv   u  s    3!%=1r   waldc                 ,    SU s=:*  =(       a    S:*  $ s  $ Nrx   r   r    ru   s    r   rv   rv   ~  r   r   g      c                 ,    SU s=:*  =(       a    S:*  $ s  $ r   r    ru   s    r   rv   rv     r   r   )weibull_maxweibull_minc                     [        U [        5      (       a4  Ub  U R                  U:w  a  Sn[        U5      eUc  U R                  OUnX4$ U c  Uc  SOUn[	        XS9n X4$ Sn[        U5      e)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`.)
isinstancer   d
ValueErrorr   )
qmc_enginer   r   messages       r   _validate_qmc_inputr     s     *i((=Z\\Q.NGW%%IJLL1 = 
	AA)
 =5 	 !!r   c                        \ rS rSrS rS rSrg)CustomDistPINVi  c                     ^^ UU4S jU l         g )Nc                    > T" U /TQ76 $ r   r    )r   r   ry   s    r   rv   )CustomDistPINV.__init__.<locals>.<lambda>  s    c!mdmr   _pdf)selfry   r   s    ``r   __init__CustomDistPINV.__init__  s
    +	r   c                 $    U R                  U5      $ r   r   )r   r   s     r   ry   CustomDistPINV.pdf  s    yy|r   r   N)__name__
__module____qualname____firstlineno__r   ry   __static_attributes__r    r   r   r   r     s    ,r   r   c                      \ rS rSrSrSSSS.S jr\S 5       r\R                  S 5       r\S	 5       r	\	R                  S
 5       r	\S 5       r
\
R                  S 5       r
S rS rSS jrS rSS jrSS jrS rS rS rSrg)r
   i  u  
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)domainignore_shape_rangerandom_statec          	         [        U[        R                  R                  5      (       a[  UR                  R
                  nU[        R                  5       ;  a,  [        SU S[        [        R                  5       5       35      eO[        S5      eUR                  R                  SS5      nUR                  R                  SS5      nUR                  n[        R                  " U5      (       d  [        S5      e[        R                  " U5      (       d  [        S	5      e[        [        U5      " UUUS
.6U l        XPl        [        R$                  " U5      S   R&                  n	U R                   R                  R(                  n
X:w  a  [        SU
 SU	 S35      eX@l        Uc.  U R                   R-                  5       U l        SU l        SU l        OnX l        U R                   R5                  U R.                  S   5      U l        U R                   R5                  U R.                  S   5      U R0                  -
  nXl        U R7                  5         X0l        U R.                  U l        U R=                  XX5      nU R>                  bO  U R>                  " U R.                  S   /UQ76 nU R>                  " U R.                  S   /UQ76 nX:  a  XpX4U l        U R@                  bc  U R@                  U R:                  S   :  a  U R:                  S   U l         O1U R@                  U R:                  S   :  a  U R:                  S   U l         [C        UU R*                  U R:                  U R@                  S9U l"        g )NzDistribution 'z%' is not supported.It must be one of z+`dist` must be a frozen distribution objectlocr   scaler   loc must be scalar.scale must be scalar.)r  r  zEach of the z( shape parameters must be a scalar, but z values are provided.rL   r   )r  r	  r{   )#r   r   distributions	rv_frozendistnamePINV_CONFIGkeysr   listkwdsgetr   r   isscalargetattr_frozendist	_distnamebroadcast_arrayssizenumargsr  support_domain_p_lower	_p_domaincdf_set_domain_adj_ignore_shape_range_domain_pinv_process_config_rvs_transform_inv_centerr	   _rng)r   r  r	  r
  r  distnamer  r  r   nargsnargs_expectedr$  d0d1s                 r   r   FastGeneratorInversion.__init__h  s    dE//99::yy~~H{//11 $XJ /))-k.>.>.@)A(BD  2 JKKiimmE1%		gq)yy{{3233{{5!!455"5(3

 "##D)!,11))..66"~. /$g%:< 
 )>++335DLDM DN!L ,,00aADM((,,T\\!_=MI&N#5 
 !LL ##H3"".((a@4@B((a@4@BwB !#D
 <<#||d//22#003 1 1! 44#003.**$$<<		r   c                     U R                   $ r   )_random_stater   s    r   r  #FastGeneratorInversion.random_state  s    !!!r   c                 $    [        U5      U l        g r   )check_random_state_qmcr4  )r   r  s     r   r  r6    s    3LAr   c                 N    U R                   R                  R                  SS5      $ )Nr  r   r  r  r  r5  s    r   r  FastGeneratorInversion.loc  s!    $$((22r   c                     [         R                  " U5      (       d  [        S5      eXR                  R                  S'   U R                  5         g )Nr  r  r   r  r   r  r  r&  )r   r  s     r   r  r;    s=    {{3233'*e$r   c                 N    U R                   R                  R                  SS5      $ )Nr  r   r:  r5  s    r   r  FastGeneratorInversion.scale  s!    $$((!44r   c                     [         R                  " U5      (       d  [        S5      eXR                  R                  S'   U R                  5         g )Nr  r  r=  )r   r  s     r   r  r?    s=    {{5!!455).g&r   c                     U R                   nU R                  nU R                  S   U-  U-   nU R                  S   U-  U-   nX44U l        g)z*Adjust the domain based on loc and scale. r   r   N)r  r  r"  _domain_adj)r   r  r  lbubs        r   r&  &FastGeneratorInversion._set_domain_adj  sL    hh

\\!_u$s*\\!_u$s*8r   c                    [         U   nSU;   a/  U R                  (       d  US   " U6 (       d  SU S3n[        U5      eSUR                  5       ;   a7  [        R
                  " US   5      (       d  US   " U6 U l        OUS   U l        OS U l        UR                  SS 5      U l        UR                  SS 5      U l	        UR                  SS 5      nUc  SU l
        O
U" U6 U l
        [        US	   U5      $ )
Nrz   z1No generator is defined for the shape parameters z=. Use ignore_shape_range to proceed with the selected values.r{   r   r   r   Fry   )r  r'  r   r  r   r  r+  r  _rvs_transformr*  _mirror_uniformr   )r   r-  r   cfgmsgrH  s         r   r)  &FastGeneratorInversion._process_config  s    (##%++./6N"V $77C %S/)sxxz!;;s8}--"8}d3"8}DL!ggot<"%''*=t"D''"2D9"#(D #2D#9D c%j$//r   c                 6   U R                   R                  US9nU R                  (       a  SU-
  nU R                  R	                  U5      nU R
                  b'  U R
                  " U/U R                  R                  Q76 nU R                  U R                  U-  -   $ )aQ  
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.
r  r   )
r  uniformrH  r,  ppfrG  r  r   r  r  )r   r  urs       r   rvsFastGeneratorInversion.rvs  s    4 %%4%0AAIIMM!*##A>(8(8(=(=>Axx$**q.((r   c                 d   [         R                  " U5      nU R                  (       a  U R                  R	                  SU-
  5      nOU R                  R	                  U5      nU R
                  b'  U R
                  " U/U R                  R                  Q76 nU R                  U-  U R                  -   $ )ac  
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   )
r   asarrayrH  r,  rO  rG  r  r   r  r  r   qr   s      r   rO  FastGeneratorInversion.ppf)  s    2 JJqM		a!e$A		a A*##A>(8(8(=(=>AzzA~((r   c                 J   [        X2U R                  5      u  p2 Uc  SnO[        U5      n Uc  SO[        R
                  " U5      nUR                  U5      nU R                  (       a  SU-
  nU R                  U5      nU R                  b'  U R                  " U/U R                  R                  Q76 nUc  UR                  5       S   nO,US:X  a  UR                  U5      nOUR                  XB4-   5      nU R                  U R                  U-  -   $ ! [         a    U4n Nf = f)ay  
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.

r   r   r    )r   r  tuple	TypeErrorr   prodrandomrH  _ppfrG  r  r   squeezereshaper  r  )r   r  r   r   
tuple_sizeNrP  qrvss           r   rd  FastGeneratorInversion.qrvsK  s   n ,J4;L;LM
	!|!
"4[

 A2774=a AAyy|*&&tDd.>.>.C.CDD<<<>"%DAv||J/||J$56xx$**t+++%  	!J	!s   D D D"!D"c                    [        U[        R                  [        R                  45      (       d  [        S5      e[        U5      nUR                  US9nU R                  (       a  SU-
  nU R                  U5      n[        R                  " [        R                  " U R                  U5      U-
  5      5      nU(       d  U[        R                  4$ U R                  U5      n[        R                  " U R                  U5      U-
  5      n	U	[        R                  " U5      -  n
[        R                  " X/5      R!                  SS9nU[        R                  " U5      4$ )uD  
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

zsize must be an integer.rM  r   r   )axis)r   numbersIntegralr   integerr   r8  rN  rH  rO  r2   r   _cdfnanr_  arrayr1   )r   r  r  x_errorurngrP  r   uerrppf_ux_error_absx_error_relx_error_combineds               r   evaluate_error%FastGeneratorInversion.evaluate_error  s   P $!1!12:: >??788
 &l3LLdL#AAHHQKvvbffTYYq\A-./<		!ffTXXa[./!BFF5M188[$>?CCCKRVV,---r   c                     U R                   $ )a  Support 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)

)rB  r5  s    r   r!  FastGeneratorInversion.support  s    B r   c                     U R                   R                  U5      nU R                  S:X  a  U$ [        R                  " X R
                  -
  U R                  -  SS5      $ )zCumulative distribution function (CDF)

Parameters
----------
x : array_like
    The values where the CDF is evaluated

Returns
-------
y : ndarray
    CDF evaluated at x

r   r   r   )r  r%  r$  r   clipr#  )r   r   r   s      r   rk  FastGeneratorInversion._cdf>  sN       #>>S HwwMM)T^^;QBBr   c                 L   U R                   S:X  a  U R                  R                  U5      $ U R                  R                  U R                   [        R                  " U5      -  U R
                  -   5      n[        R                  " X R                  S   U R                  S   5      $ )zPercent point function (inverse of `cdf`)

Parameters
----------
q : array_like
    lower tail probability

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

r   r   r   )r$  r  rO  r   rm  r#  rz  rB  rV  s      r   r_  FastGeneratorInversion._ppfQ  s~     >>S ##''**  "((1+!=!MNwwq**1-t/?/?/BCCr   )r+  r  r"  rB  r(  r  r'  rH  r$  r#  r4  r,  rG  r*  r  r   )NNN)i NF)r  r  r  r  __doc__r   propertyr  setterr  r  r&  r)  rR  rO  rd  ru  r!  rk  r_  r  r    r   r   r
   r
     s    ~H  Zx " " B B 3 3 	ZZ  5 5 \\ $06 )D )DR,hz.x! FC&Dr   c                   2    \ rS rSrSrSSS.S jrS	S jrSrg)
r   ie  a  
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

r   N)rQ   r  c                    X4:  a  [        S5      eUS::  a  [        S5      eXl        X l        X0l        X@l        XPl        [        U5      U l        g )Nzvmin must be smaller than vmax.r   zumax must be positive.)r   r   _umax_vmin_vmax_cr   r,  )r   ry   umaxvminvmaxrQ   r  s          r   r   RatioUniforms.__init__  sK    <>??19566	


&|4	r   c                    [        [        R                  " U5      5      n[        R                  " U5      n[        R                  " U5      nSu  pVXS:  a  X5-
  nU R
                  U R                  R                  US9-  nU R                  R                  U R                  U R                  US9n	X-  U R                  -   n
US-  U R                  U
5      :*  n[        R                  " U5      nUS:  a  X   XEX\-   & X\-  nUS:X  a  Xc-  S:  a  SXc-   S3n[        U5      eUS-  nXS:  a  M  [        R                  " XB5      $ )	a  Sampling 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.

)r   r   rM  r   r   iP  z2Not 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   )r[  r   
atleast_1dr]  zerosr  r,  rN  r  r  r  r   sumRuntimeErrorra  )r   r  size1drc  r   	simulatediku1v1rR  accept
num_acceptrJ  s                 r   rR  RatioUniforms.rvs  s2    r}}T*+GGFO HHQK	 mAdii//Q/77B""4::tzz"BB'DGG#C!etyy~-FJA~8;Y35'	QQSE\H N* *  #3''FA+ m. zz!$$r   )r  r   r,  r  r  r  rZ  )r  r  r  r  r~  r   rR  r  r    r   r   r   r   e  s    zx 454 52%r   )-r   rh  numpyr   scipyr   r   r&   _qmcr   r8  r   r   _unuran.unuran_wrapperr	   scipy._lib._util__all__r   r   r!   r-   r4   r9   r<   rA   rD   rF   rJ   rN   rR   rU   rX   rZ   r\   r`   rf   ri   rn   rp   rr   r  r   r   r
   r   r    r   r   <module>r     sr       & & > / $_
5
')%%5''	'	(U:>Bo;?o 2 	o 6:(0-o( :.5N)o6 :.7o@ 9AoJ =RKoT <RUo^ *_of 
;(gop 9qoz ({oB 	CoN %OoV 7Wo` 29aoj %"	kov 2wo~ 4oF ;GoN 7!OoX >Yob 7col *mot ?uo| 7}oD :EoL -MoT )9:Uo^ 9_oh B7
ior 5soz 1{oB CoL 7 7Uod, {
D {
D|}% }%r   