
    `i                        d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
mZ d dlZd dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlZdZd	Z G d
 de          ZddZi ae j        d             Zd Zd Zd ZdS )    N)LinAlgError)_core)cuda)device)_kernels)_utill    l    c                      e Zd ZdZd[dZd Zd ZdefdZde	fdZ
defdZdefd	Zd
defdZdefdZd
defdZde	fdZde	fdZ ej        dddd          Zdd
defdZdd
defdZdd
defdZde	fdZddddefdZde	fdZdd
defdZdefdZdefd Zdefd!Zd
de	fd"Zdefd#Z d$ Z!d% Z" ej        d&d'd(d)          Z#d* Z$defd+Z%d
defd,Z& ej        d-d.d/d0          Z' ej        d-d1d2d3          Z(d4 Z)d5 Z*d6 Z+ ej        d7d8d9d:          Z,d\d;Z-defd<Z.defd=Z/defd>Z0defd?Z1defd@Z2d\dAZ3 ej        dBd'dCdD          Z4defdEZ5 ej        dFd'dGdH          Z6dd
defdIZ7defdJZ8 ej        dKdLdMdN          Z9defdOZ:defdPZ;de	fdQZ<d]dSZ=dT Z>dU Z?dV Z@ ej        dddWdX          ZAdd
defdYZBdde	fdZZCdS )^RandomStateaV  Portable container of a pseudo-random number generator.

    An instance of this class holds the state of a random number generator. The
    state is available only on the device which has been current at the
    initialization of the instance.

    Functions of :mod:`cupy.random` use global instances of this class.
    Different instances are used for different devices. The global state for
    the current device can be obtained by the
    :func:`cupy.random.get_random_state` function.

    Args:
        seed (None or int): Seed of the random number generator. See the
            :meth:`~cupy.random.RandomState.seed` method for detail.
        method (int): Method of the random number generator. Following values
            are available::

               cupy.cuda.curand.CURAND_RNG_PSEUDO_DEFAULT
               cupy.cuda.curand.CURAND_RNG_PSEUDO_XORWOW
               cupy.cuda.curand.CURAND_RNG_PSEUDO_MRG32K3A
               cupy.cuda.curand.CURAND_RNG_PSEUDO_MTGP32
               cupy.cuda.curand.CURAND_RNG_PSEUDO_MT19937
               cupy.cuda.curand.CURAND_RNG_PSEUDO_PHILOX4_32_10

    Nc                     ddl m} ||j        }|                    |          | _        t          j        | |j        | j                  | _        || _	        | 
                    |           d S )Nr   curand)cupy_backends.cuda.libsr   CURAND_RNG_PSEUDO_DEFAULTcreateGenerator
_generatorweakreffinalizedestroyGenerator
_finalizermethodseed)selfr   r   r   s       j/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/cupy/random/_generator.py__init__zRandomState.__init__8   sp    222222>5F 0088!*&)4?< <		$    c                 4    | j         |z   t          z  | _         d S N)_rk_seed_UINT64_MAX)r   sizes     r   _update_seedzRandomState._update_seedC   s    -<r   c                    t          j        |          }t           j                            |          }|dz  dk    r7t	          j        ||          } || j        |j        j        |j	        g|R   |S t	          j        |dz   f|          } || j        |j        j        |j	        g|R   |d |         
                    |          S )N   r   dtype   )r   get_sizeinternalprodcupyemptyr   dataptrr    reshape)r   funcr    r%   argselement_sizeouts          r   _generate_normalzRandomState._generate_normalF   s     ~d##~**400!q  *T///CD#(,@4@@@@J*lQ.0>>>CD#(,@4@@@@}}%--d333r   c                 &   t          j        |          t          j        |          }}|t          j        ||          j        }t          j        ||          }t          j        ||| j        |           |                     |j	                   |S )zReturns an array of samples drawn from the beta distribution.

        .. seealso::
            - :func:`cupy.random.beta` for full documentation
            - :meth:`numpy.random.RandomState.beta`
        Nshaper%   )
r*   asarray	broadcastr6   r+   r   beta_kernelr   r!   r    )r   abr    r%   ys         r   betazRandomState.betaY   s~     |AQ1<>!Q''-DJT///Q4=!444!&!!!r   c                 &   t          j        |          t          j        |          }}|t          j        ||          j        }t          j        ||          }t          j        ||| j        |           |                     |j	                   |S )zReturns an array of samples drawn from the binomial distribution.

        .. seealso::
            - :func:`cupy.random.binomial` for full documentation
            - :meth:`numpy.random.RandomState.binomial`
        Nr5   )
r*   r7   r8   r6   r+   r   binomial_kernelr   r!   r    r   npr    r%   r<   s         r   binomialzRandomState.binomialh   s~     |AQ1<>!Q''-DJT/// At}a888!&!!!r   c                     t          j        |          }||j        }t          j        ||          }t	          j        || j        |           |                     |j                   |S )zReturns an array of samples drawn from the chi-square distribution.

        .. seealso::
            - :func:`cupy.random.chisquare` for full documentation
            - :meth:`numpy.random.RandomState.chisquare`
        Nr5   )	r*   r7   r6   r+   r   chisquare_kernelr   r!   r    r   dfr    r%   r<   s        r   	chisquarezRandomState.chisquarew   se     \"<8DJT///!"dmQ777!&!!!r   c                 z   t          j        |          }||j        }n7t          |t          t           j        f          r|f|j        z   }n
||j        z  }t          j        ||          }t          j        || j	        |           ||
                    dd          z  }|                     |j                   |S )zReturns an array of samples drawn from the dirichlet distribution.

        .. seealso::
            - :func:`cupy.random.dirichlet` for full documentation
            - :meth:`numpy.random.RandomState.dirichlet`
        Nr5   T)axiskeepdims)r*   r7   r6   
isinstanceintintegerr+   r   standard_gamma_kernelr   sumr!   r    )r   alphar    r%   r<   s        r   	dirichletzRandomState.dirichlet   s     U##<;DDsDL122 	 7U[(DDEKDJT///&udmQ???	QUUTU***!&!!!r         ?c                     t          j        ||          }|dk                                     rt          d          ||j        }|                     ||          }||z  }|S )a.  Returns an array of samples drawn from a exponential distribution.

        .. warning::

            This function may synchronize the device.

        .. seealso::
            - :func:`cupy.random.exponential` for full documentation
            - :meth:`numpy.random.RandomState.exponential`
        r   	scale < 0)r*   r7   any
ValueErrorr6   standard_exponentialr   scaler    r%   xs        r   exponentialzRandomState.exponential   sh     UE**AI?? 	*[)))<;D%%dE22	U
r   c                 &   t          j        |          t          j        |          }}|t          j        ||          j        }t          j        ||          }t          j        ||| j        |           |                     |j	                   |S )zReturns an array of samples drawn from the f distribution.

        .. seealso::
            - :func:`cupy.random.f` for full documentation
            - :meth:`numpy.random.RandomState.f`
        Nr5   )
r*   r7   r8   r6   r+   r   f_kernelr   r!   r    )r   dfnumdfdenr    r%   r<   s         r   fzRandomState.f   s     |E**DL,?,?u<>%//5DJT///%q999!&!!!r   c                 .   t          j        |          t          j        |          }}|t          j        ||          j        }t          j        ||          }t          j        || j        |           ||z  }|                     |j	                   |S )zReturns an array of samples drawn from a gamma distribution.

        .. seealso::
            - :func:`cupy.random.gamma` for full documentation
            - :meth:`numpy.random.RandomState.gamma`
        Nr5   )
r*   r7   r8   r6   r+   r   rP   r   r!   r    )r   r6   r[   r    r%   r<   s         r   gammazRandomState.gamma   s     |E**DL,?,?u<>%//5DJT///&udmQ???	U
!&!!!r   c                     t          j        |          }||j        }t          j        ||          }t	          j        || j        |           |                     |j                   |S )zReturns an array of samples drawn from the geometric distribution.

        .. seealso::
            - :func:`cupy.random.geometric` for full documentation
            - :meth:`numpy.random.RandomState.geometric`
        Nr5   )	r*   r7   r6   r+   r   geometric_kernelr   r!   r    r   rB   r    r%   r<   s        r   	geometriczRandomState.geometric   sc     LOO<7DJT///!!T]A666!&!!!r   c                 R   t          j        |          t          j        |          t          j        |          }}}|t          j        |||          j        }t          j        ||          }t          j        |||| j        |           |                     |j	                   |S )zReturns an array of samples drawn from the hypergeometric distribution.

        .. seealso::
            - :func:`cupy.random.hypergeometric` for full documentation
            - :meth:`numpy.random.RandomState.hypergeometric`
        Nr5   )
r*   r7   r8   r6   r+   r   hypergeometric_kernelr   r!   r    )r   ngoodnbadnsampler    r%   r<   s          r   hypergeometriczRandomState.hypergeometric   s     Ld!3!3T\'5J5J t<>%w77=DJT///&udGT]ANNN!&!!!r   zT x, T loc, T scalezT yz>y = loc + scale * ((x <= 0.5) ? log(x + x): -log(x + x - 1.0))cupy_laplace_kernel        c                     t          j        ||          }t          j        ||          }|t          j        ||          j        }|                     ||          }t
                              ||||           |S )zReturns an array of samples drawn from the laplace distribution.

        .. seealso::
            - :func:`cupy.random.laplace` for full documentation
            - :meth:`numpy.random.RandomState.laplace`
        )r*   r7   r8   r6   _random_sample_rawr
   _laplace_kernelr   locr[   r    r%   r\   s         r   laplacezRandomState.laplace   ss     l3&&UE**<>#u--3D##D%00##AsE1555r   c                    t          j        |          t          j        |          }}|t          j        ||          j        }t          j        ||          }t          j        | j        |           |                     |j	                   d|z
  |z  }t          j
        ||           t          j        |||           t          j        |||           |S )zReturns an array of samples drawn from the logistic distribution.

        .. seealso::
            - :func:`cupy.random.logistic` for full documentation
            - :meth:`numpy.random.RandomState.logistic`
        Nr5   rT   r2   )r*   r7   r8   r6   r+   r   open_uniform_kernelr   r!   r    logmultiplyaddrt   s         r   logisticzRandomState.logistic   s     \#&&U(;(;U<>#u--3DJT///$T]A666!&!!!1WMaA&&&&CQr   c                 0   ddl m} t          d ||fD                       r0|                     ||||          }t	          j        ||           |S |d}t          |          }|j        dk    r|j        }n|j	        }| 
                    |||||          S )zReturns an array of samples drawn from a log normal distribution.

        .. seealso::
            - :func:`cupy.random.lognormal` for full documentation
            - :meth:`numpy.random.RandomState.lognormal`

        r   r   c              3   J   K   | ]}t          |t          j                  V  d S r   )rM   r*   ndarray).0args     r   	<genexpr>z(RandomState.lognormal.<locals>.<genexpr>  s.      FFz#t|,,FFFFFFr   rx   N rb   )r   r   rW   normalr*   exp_check_and_get_dtypechargenerateLogNormalgenerateLogNormalDoubler3   )r   meansigmar    r%   r   r\   r/   s           r   	lognormalzRandomState.lognormal  s     	322222FFuFFFFF 	D%u55AHQAH<D$U++:+DD1D$$T4eDDDr   c                 r   t          j        |          }t          j        |dk              rt          d          t          j        |dk              rt          d          ||j        }t          j        ||          }t          j        || j        |           | 	                    |j
                   |S )a*  Returns an array of samples drawn from a log series distribution.

        .. warning::

            This function may synchronize the device.

        .. seealso::
            - :func:`cupy.random.logseries` for full documentation
            - :meth:`numpy.random.RandomState.logseries`

        r   zp <= 0.0r&   zp >= 1.0Nr5   )r*   r7   rW   rX   r6   r+   r   logseries_kernelr   r!   r    rg   s        r   	logserieszRandomState.logseries*  s     LOO8AF 	)Z(((8AF 	)Z(((<7DJT///!!T]A666!&!!!r   ignoreg:0yE>choleskyc           	      \	   t          j        d           t          j        ||          }t          j        ||          }|g }n't	          |t
          t          j        f          r|g}n|}t          |j                  dk    rt          d          t          |j                  dk    s|j        d         |j        d         k    rt          d          |j        d         |j        d         k    rt          d	          t          |dd                   }	|	                    |j        d                    |d
vrt          d          |dk    r|dk    r|dk    rt          d          |dk    rt          j        d          5  	 t          j                            |          }
na# t           $ rS t          j        d          5  |dk    r|dk    r<t          j                            |          \  }}t          j        || k                }|dk    rVt          j                            |          \  }}}t          j        t          j        |j        |z  |          |||          }|t          j        t          j        |                    z  }
|st3          j        dt6                     n9t3          j        dt6                     t          j                            |          }
ddd           n# 1 swxY w Y   Y nw xY wddd           n# 1 swxY w Y   nt          j        |          5  	 |dk    r t          j                            |          }
n|dk    rLt          j                            |          \  }}|t          j        t          j        |                    z  }
nR|dk    rLt          j                            |          \  }}}|t          j        t          j        |                    z  }
n# t           $ r t!          d          w xY wddd           n# 1 swxY w Y   |                     |	|                              d|j        d                   }t          j        |
|j                  }|j        }||z  }t=          |	          |_        |S )ae  Returns an array of samples drawn from the multivariate normal
        distribution.

        .. warning::
            This function calls one or more cuSOLVER routine(s) which may yield
            invalid results if input conditions are not met.
            To detect these invalid results, you can set the `linalg`
            configuration to a value that is not `ignore` in
            :func:`cupyx.errstate` or :func:`cupyx.seterr`.

        .. seealso::
            - :func:`cupy.random.multivariate_normal` for full documentation
            - :meth:`numpy.random.RandomState.multivariate_normal`
        z+cupy.random.RandomState.multivariate_normalr$   Nr&   zmean must be 1 dimensionalr#   r   z$cov must be 2 dimensional and squarez"mean and cov must have same length>   svdeighr   z1method must be one of {'eigh', 'svd', 'cholesky'}r   warnraisez3check_valid must equal 'warn', 'raise', or 'ignore')linalgr   r   r   )rtolatolz?covariance is not positive-semidefinite, output may be invalid.z=covariance is not positive-semidefinite, output *is* invalid.z_Matrix is not positive definite; if matrix is positive-semidefinite, set'check_valid' to 'warn'rJ   )r   experimentalr*   r7   rM   rN   rO   lenr6   rX   listappendcupyxerrstater   r   r   r   rW   r   allclosedotTsqrtabswarningsr   RuntimeWarningstandard_normalr.   tuple)r   r   covr    check_validtolr   r%   r6   final_shapedecompsupsdvhr\   s                   r   multivariate_normalzRandomState.multivariate_normalB  s{     	HIII|D...l3e,,,<EEsDL122 	FEEEtz??a9:::	NNaSYq\SYq\%A%ACDDD:a=CIaL((ABBB58nn4:a=)))444CE E E (""f$$)?)? IK K K &  w/// ? ??![11#66FF" ? ? ?x888 ? ?!Z//%//)-)9)9#)>)>A*.(1t8*<*<&<%-1[__S-A-A
Ar&*mDHRTAXr4J4J47c'M 'M 'M%&48A;;)?)?%?F#& J ( /9:H!J !J !J
 %M +56DF F F &*[%9%9#%>%>F'? ? ? ? ? ? ? ? ? ? ? ? ? ? ??? ? ? ? ? ? ? ? ? ? ? ? ? ? ?4 {333 A AA++!%!5!5c!:!:6))!%!1!1#!6!6A!"TYtx{{%;%;!;5%)[__S%9%9
Ar!"TYtx{{%;%;!;" A A A% '@ A A AAA A A A A A A A A A A A A A A    ', ! . ..5gb$*Q-.H.H 	
HVQS!!C	T	$$s   	LF,*L, L
D$K<0L
<L  L
L L
L	L

LL L;P1=C
PP1P""P11P58P5c                    t          j        |          }t          j        |          }t          j        |dk              rt          d          t          j        |dk               rt          d          t          j        |dk              rt          d          |                     |d|z
  |z  |          }|                     ||          S )aB  Returns an array of samples drawn from the negative binomial distribution.

        .. warning::

            This function may synchronize the device.

        .. seealso::
            - :func:`cupy.random.negative_binomial` for full documentation
            - :meth:`numpy.random.RandomState.negative_binomial`
        r   zn <= 0zp < 0r&   zp > 1r$   )r*   r7   rW   rX   rd   poissonr@   s         r   negative_binomialzRandomState.negative_binomial  s     LOOLOO8AF 	'X&&&8AE?? 	&W%%%8AE?? 	&W%%%JJq1Q3'4((||AU|+++r   c                 (   ddl m} t          |          }|t          j        ||          j        }|j        dk    r|j        }n|j        }t          |t          j
                  rH|                     |||dd          }t          j        |||           t          j        |||           ndt          |t          j
                  r1|                     |||d|          }t          j        |||           n|                     |||||          }|S )zReturns an array of normally distributed samples.

        .. seealso::
            - :func:`cupy.random.normal` for full documentation
            - :meth:`numpy.random.RandomState.normal`

        r   r   Nrb   rp   rT   rx   )r   r   r   r*   r8   r6   r   generateNormalgenerateNormalDoublerM   r   r3   r{   r|   )r   ru   r[   r    r%   r   r/   r\   s           r   r   zRandomState.normal  s&    	322222$U++<>#u--3D:(DD.DeT\** 	E%%dD%cBBAM!U****HQ#####T\** 	E%%dD%eDDAHQ#####%%dD%eDDAr   c                     t          j        |          }||j        }|                     ||          }t          j        ||           t          j        | |z  |           |dz
  S )zReturns an array of samples drawn from the pareto II distribution.

        .. seealso::
            - :func:`cupy.random.pareto` for full documentation
            - :meth:`numpy.random.RandomState.pareto`
        Nrx   r&   )r*   r7   r6   rr   rz   r   r   r:   r    r%   r\   s        r   paretozRandomState.pareto  sk     LOO<7D##D%00!A11ur   c                    t          j        |          t          j        |          }}t          j        |dk              rt          d          t          j        |dk               rt          d          |t          j        ||          j        }t          j        ||          }t          j        ||| j	        |           | 
                    |j                   |S )aT  Returns an array of samples drawn from the noncentral chi-square
        distribution.

        .. warning::

            This function may synchronize the device.

        .. seealso::
            - :func:`cupy.random.noncentral_chisquare` for full documentation
            - :meth:`numpy.random.RandomState.noncentral_chisquare`
        r   zdf <= 0nonc < 0Nr5   )r*   r7   rW   rX   r8   r6   r+   r   noncentral_chisquare_kernelr   r!   r    )r   rG   noncr    r%   r<   s         r   noncentral_chisquarez RandomState.noncentral_chisquare  s     <##T\$%7%7D8B!G 	(Y'''8D1H 	)Z(((<>"d++1DJT///,Rt}aHHH!&!!!r   c                 <   t          j        |          t          j        |          t          j        |          }}}t          j        |dk              rt          d          t          j        |dk              rt          d          t          j        |dk               rt          d          |t          j        |||          j        }t          j        ||          }t          j        |||| j	        |           | 
                    |j                   |S )a3  Returns an array of samples drawn from the noncentral F distribution.

        .. warning::

            This function may synchronize the device.

        .. seealso::
            - :func:`cupy.random.noncentral_f` for full documentation
            - :meth:`numpy.random.RandomState.noncentral_f`
        r   z
dfnum <= 0z
dfden <= 0r   Nr5   )r*   r7   rW   rX   r8   r6   r+   r   noncentral_f_kernelr   r!   r    )r   r`   ra   r   r    r%   r<   s          r   noncentral_fzRandomState.noncentral_f  s    Le!4!4dl46H6H u8EQJ 	+\***8EQJ 	+\***8D1H 	)Z(((<>%55;DJT///$UE4JJJ!&!!!r   c                     t          j        |          }||j        }t          j        ||          }t	          j        || j        |           |                     |j                   |S )zReturns an array of samples drawn from the poisson distribution.

        .. seealso::
            - :func:`cupy.random.poisson` for full documentation
            - :meth:`numpy.random.RandomState.poisson`
        Nr5   )	r*   r7   r6   r+   r   poisson_kernelr   r!   r    )r   lamr    r%   r<   s        r   r   zRandomState.poisson  se     l3<9DJT///T]A666!&!!!r   c                 N   t          j        |          }t          j        |dk               rt          d          ||j        }|                     ||          }t          j        | |           t          j        d| |           t          j        |d|z  |           |S )a  Returns an array of samples drawn from the power distribution.

        .. warning::

            This function may synchronize the device.

        .. seealso::
            - :func:`cupy.random.power` for full documentation
            - :meth:`numpy.random.RandomState.power`
        r   a < 0Nr    r%   rx   r&   rT   )	r*   r7   rW   rX   r6   rY   r   r|   powerr   s        r   r   zRandomState.power$  s     LOO8AE?? 	&W%%%<7D%%4u%==!QBA
1bd""""r   c                     |                     dt                    }|r7t          dd                    |                                          z            |                     ||          S )zReturns uniform random values over the interval ``[0, 1)``.

        .. seealso::
            - :func:`cupy.random.rand` for full documentation
            - :meth:`numpy.random.RandomState.rand`

        r%   z*rand() got unexpected keyword arguments %s, r   )popfloat	TypeErrorjoinkeysrandom_sampler   r    kwargr%   s       r   randzRandomState.rand:  si     		'5)) 	7H"ii

556 7 7 7!!t5!999r   c                     |                     dt                    }|r7t          dd                    |                                          z            |                     ||          S )zReturns an array of standard normal random values.

        .. seealso::
            - :func:`cupy.random.randn` for full documentation
            - :meth:`numpy.random.RandomState.randn`

        r%   z+randn() got unexpected keyword arguments %sr   r   )r   r   r   r   r   r   r   s       r   randnzRandomState.randnH  sf     		'5)) 	7I"ii

556 7 7 7{{E{222r    zT xzx = (x == (T)1) ? 0 : xcupy_random_x_mod_1c                     ddl m} t          |          }t          j        ||          }|j        dk    r|j        }n|j        } || j        |j	        j
        |j                   |S )Nr   r   r$   rb   )r   r   r   r*   r+   r   generateUniformgenerateUniformDoubler   r,   r-   r    )r   r    r%   r   r2   r/   s         r   rr   zRandomState._random_sample_rawY  su    222222$U++jU+++:)DD/DT_chlCH555
r   c                 n    |d}|                      ||          }t                              |           |S )zReturns an array of random values over the interval ``[0, 1)``.

        .. seealso::
            - :func:`cupy.random.random_sample` for full documentation
            - :meth:`numpy.random.RandomState.random_sample`

        Nr   )rr   r
   _mod1_kernel)r   r    r%   r2   s       r   r   zRandomState.random_samplee  s<     <D%%dE22  %%%
r   c                 n   t          j        |          }||j        }t          j        |dk               rt	          d          |                     ||          }t          j        ||          }t          j        |d|          }t          j        ||          }t          j        |||          }|S )a%  Returns an array of samples drawn from a rayleigh distribution.

        .. warning::

            This function may synchronize the device.

        .. seealso::
            - :func:`cupy.random.rayleigh` for full documentation
            - :meth:`numpy.random.RandomState.rayleigh`
        Nr   rV   rx   g       )	r*   r7   r6   rW   rX   rr   rz   r{   r   rZ   s        r   rayleighzRandomState.rayleighs  s     U##<;D8EAI 	*[)))##D%00HQAM!Sa(((IaQM!U***r   zT max, T mxzT outz3out = max - (mx != max ? (max - mx) % (mx + 1) : 0) cupy_random_interval_upper_limitzT samplez$if (mx != max) { sample %= mx + 1; }"cupy_random_interval_sample_moduloc                    |d}nt          |t                    r|f}t          j        |          }|r|dk    r t	          j        |t          j                  S |dk     r"t          d                    |                    |t          k    r't          j        } |t          d|dz   z  z
            }n;|t          k    r't          j        } |t          d|dz   z  z
            }n	t          d	                    |                    |j        }|t          j        k    s|t          j        k    r?t          j        }|                    |d
          }|                     t          |          }n|t          j        k    s|t          j        k    r?t          j        }|                    |d
          }|                     t          |          }n"t          d                    |                    t#          j        t&          j        |d          }|dk    rt	          j        ||          S |                     ||          }|rW|dz   }|d|                                dz
  z  k    r4d|                                z  dz
  }	||	z  }|                    |          S |                     ||d
          }
|
j        }|dk    rt          j        |          s||
         }|dk    r|rt7          |dz  d          n|j        }|                     ||          }|                     ||d          }|j        }||k    r||d|                  ||
<   d}n.||         ||
d|         <   |
|d         }
|s
||d         }||z  }|dk    |r||z  }nI|t          j        k    r|                     t          ||          }n|                     t          ||          }|                    |          S )a`  Generate multiple integers independently sampled uniformly from ``[0, mx]``.

        Args:
            mx (int): Upper bound of the interval
            size (None or int or tuple): Shape of the array or the scalar
                returned.
        Returns:
            int or cupy.ndarray: If ``None``, an :class:`cupy.ndarray` with
            shape ``()`` is returned.
            If ``int``, 1-D array of length size is returned.
            If ``tuple``, multi-dimensional array with shape
            ``size`` is returned.
            Currently, only 32 bit or 64 bit integers can be sampled.
        Nr   r   r$   z$mx must be non-negative (actual: {})        r&               z+mx must be within uint64 range (actual: {})Fcopyzdtype must be integer, got: {}r#   i   T)rM   rN   numpyisscalarr*   zerosuint32rX   format_UINT32_MAXr   uint64r%   int32astype_interval_upper_limitint64	functoolsreduceoperatormulr+   _curand_generate
bit_lengthr.   _get_indicesr    max_interval_sample_modulo)r   mxr    is_mx_scalarr%   upper_limitn_samplesamplemx1mask
ng_indicesn_ngn_supplement
supplement
ok_indicesn_oks                   r   	_intervalzRandomState._interval  s    <DDc"" 	5D~b)) 	DQwwz$el;;;;Avv :AA"EEG G G{""#eK7rAv2F$FGG{""#eK7rAv2F$FGG AHHLLN N N HE
""et{&:&:YYu5Y11"88bII$*$$(<(<YYu5Y11"88bII 4;;EBBD D D #HL$::q==:d%0000&&x77 	,q&CaCNN,,q0111R]]__,1$~~d+++ &&v{EBB
!88EN2..8%j1KQhh+BCq$///1<1A ..|UCCJ **:{DIIJ?D t||%/
5D50A%Bz",6z,Bz%4%()'.
# 5"-dee"4K% Qhh(  	KcMFFdk!!11+r6JJFF11+r6JJF~~d###r   c                     ddl m} t          j        |f|          }|                    t
          j                  j        }|                    | j	        |j
        j        |           |S )Nr   r   r$   )r   r   r*   r+   viewr   r   r    generater   r,   r-   )r   numr%   r   r  size32s         r   r   zRandomState._curand_generate  sc    222222SF%0005<005&AAAr   c                 $   |j         dk     rt          j        nt          j        }|r||k    n||k    }t	          j        ||          }~t	          j        t          |d                   f|          }|                     |||j                    |S )Nr   r$   rJ   r    )	r    r   r   r   r*   cumsumr+   rN   _kernel_get_indices)r   r  r   condr%   flagscsumindicess           r   r   zRandomState._get_indices   s     &e 3 3+/K;&&f{6J{5...*c$r(mm-U;;;  wTY ???r   z
raw U csumzraw U indiceszo
        int j = 0;
        if (i > 0) { j = csum[i-1]; }
        if (csum[i] > j) { indices[j] = i; }
        cupy_get_indicesc                    ddl m} |f	 t          j        t	          j        d                    }t          |d          }n# t          $ r! t          j                    dz  t          z  }Y nw xY wt          |t          j                  r?t          t          j        |d                                          dd         d          }n[t          j        |          }|j        j        d	vrt'          d
          t          |          }|dk     s|dk    rt)          d          |                    | j        |           | j        |j        |j        fvr|                    | j        d           || _        dS )zResets the state of the random number generator with a seed.

        .. seealso::
            - :func:`cupy.random.seed` for full documentation
            - :meth:`numpy.random.RandomState.seed`

        r   r   N      i@B F)usedforsecuritybiuzSeed must be an integer.r   z/Seed must be an integer between 0 and 2**64 - 1)r   r   binasciihexlifyosurandomrN   NotImplementedErrortimer   rM   r   r   hashlibmd5	hexdigestr7   r%   kindr   rX   setPseudoRandomGeneratorSeedr   r   CURAND_RNG_PSEUDO_MT19937CURAND_RNG_PSEUDO_MTGP32setGeneratorOffsetr   )r   r   r   seed_strseed_arrs        r   r   zRandomState.seed  s    	322222<=#+BJqMM::8R((& = = =	g-<= $.. K7;%1 1 11:SbSBCEG G !=..>&e33#$>???8}}!88tu}}$IK K K 	++DOTBBBK @ & ? A A A%%doq999s   6A (A,+A,c                 x    |                      ||          }t          j        t          j        |dz
  z            S )zReturns an array of samples drawn from the standard cauchy distribution.

        .. seealso::
            - :func:`cupy.random.standard_cauchy` for full documentation
            - :meth:`numpy.random.RandomState.standard_cauchy`
        r   g      ?)uniformr*   tanpir   r    r%   r\   s       r   standard_cauchyzRandomState.standard_cauchy7  s4     LLd%L00x1s7+,,,r   c                 d    |d}|                      ||          }t          j        ||           S )zReturns an array of samples drawn from the standard exp distribution.

         .. seealso::
            - :func:`cupy.random.standard_exponential` for full documentation
            - :meth:`numpy.random.RandomState.standard_exponential`
        Nr   rx   )rr   r*   rz   r2  s       r   rY   z RandomState.standard_exponentialA  s;     <D##D%00"""""r   c                     t          j        |          }||j        }t          j        ||          }t	          j        || j        |           |                     |j                   |S )zReturns an array of samples drawn from a standard gamma distribution.

        .. seealso::
            - :func:`cupy.random.standard_gamma` for full documentation
            - :meth:`numpy.random.RandomState.standard_gamma`
        Nr5   )	r*   r7   r6   r+   r   rP   r   r!   r    )r   r6   r    r%   r<   s        r   standard_gammazRandomState.standard_gammaM  se     U##<;DJT///&udmQ???!&!!!r   c                 0    |                      ||          S )zReturns samples drawn from the standard normal distribution.

        .. seealso::
            - :func:`cupy.random.standard_normal` for full documentation
            - :meth:`numpy.random.RandomState.standard_normal`

        r   )r   )r   r    r%   s      r   r   zRandomState.standard_normal\  s     {{E{222r   c                     t          j        |          }||j        }t          j        ||          }t	          j        || j        |           |                     |j                   |S )zReturns an array of samples drawn from the standard t distribution.

        .. seealso::
            - :func:`cupy.random.standard_t` for full documentation
            - :meth:`numpy.random.RandomState.standard_t`
        Nr5   )	r*   r7   r6   r+   r   standard_t_kernelr   r!   r    rF   s        r   
standard_tzRandomState.standard_tf  se     \"<8DJT///"2t}a888!&!!!r   c                     ddl m} |d}t          j        |t          j                  }|j        j        dz  }|                    | j        |j	        j
        |j        |z             |t          j        t          j                  j        z  }|S )a  Draws integers between 0 and max integer inclusive.

        Return a sample of uniformly distributed random integers in the
        interval [0, ``np.iinfo(np.int_).max``]. The `np.int_` type translates
        to the C long integer type and its precision is platform dependent.

        Args:
            size (int or tuple of ints): Output shape.

        Returns:
            cupy.ndarray: Drawn samples.

        .. seealso::
            :meth:`numpy.random.RandomState.tomaxint`

        r   r   Nr   r$      )r   r   r*   r+   int_r%   itemsizer  r   r,   r-   r    iinfor   )r   r    r   r  size_in_ints        r   tomaxintzRandomState.tomaxintu  s    " 	322222<DD	222l+q0OV[_fkK.G	I 	I 	I 	$*TY''++r   zL left, M mode, R righta  
        T base, leftbase, ratio, leftprod, rightprod;

        base = right - left;
        leftbase = mode - left;
        ratio = leftbase / base;
        leftprod = leftbase*base;
        rightprod = (right - mode)*base;

        if (x <= ratio)
        {
            x = left + sqrt(x*leftprod);
        } else
        {
            x = right - sqrt((1.0 - x) * rightprod);
        }
        cupy_triangular_kernelc                    t          j        |          t          j        |          t          j        |          }}}t          j        ||k              rt          d          t          j        ||k              rt          d          t          j        ||k              rt          d          |t          j        |||          j        }|                     ||          }t                              ||||          S )a-  Returns an array of samples drawn from the triangular distribution.

        .. warning::

            This function may synchronize the device.

        .. seealso::
            - :func:`cupy.random.triangular` for full documentation
            - :meth:`numpy.random.RandomState.triangular`
        zleft > modezmode > rightzleft == rightNr   )	r*   r7   rW   rX   r8   r6   r   r
   _triangular_kernel)r   leftmoderightr    r%   r\   s          r   
triangularzRandomState.triangular  s     LT 2 2DL4G4G d8D4K   	,]+++8D5L!! 	-^,,,8DEM"" 	._---<>$e44:DD66--dD%CCCr   zT low, T highzx = T(low) + x * T(high - low)
cupy_scalec                 l   t          j        |          st          j        ||          }t          j        |          st          j        ||          }|t          j        ||          j        }t          j        |          }|                     ||          }t          	                    |||          S )zReturns an array of uniformly-distributed samples over an interval.

        .. seealso::
            - :func:`cupy.random.uniform` for full documentation
            - :meth:`numpy.random.RandomState.uniform`

        Nr   )
r   r   r*   r7   r8   r6   r%   r   r
   _scale_kernel)r   lowhighr    r%   r   s         r   r/  zRandomState.uniform  s     ~c"" 	+,sE**C~d## 	-<e,,D<>#t,,2DE""!!t5!99((dD999r   c                 &   t          j        |          t          j        |          }}|t          j        ||          j        }t          j        ||          }t          j        ||| j        |           |                     |j	                   |S )zReturns an array of samples drawn from the von Mises distribution.

        .. seealso::
            - :func:`cupy.random.vonmises` for full documentation
            - :meth:`numpy.random.RandomState.vonmises`
        Nr5   )
r*   r7   r8   r6   r+   r   vonmises_kernelr   r!   r    )r   mukappar    r%   r<   s         r   vonmiseszRandomState.vonmises  s     L$$dl5&9&9E<>"e,,2DJT/// UDM1===!&!!!r   zT mean, T scale, T UzT Xa	  
            T mu_2l;
            T Y;
            mu_2l = mean / (2*scale);
            Y = mean*X*X;
            X = mean + mu_2l*(Y - sqrt(4*scale*Y + Y*Y));
            if (U > mean/(mean+X))
            {
                X = mean*mean/X;
            }
        cupy_wald_scalec                 (   t          j        ||          t          j        ||          }}|t          j        ||          j        }|                     ||          }|                     ||          }t                              ||||          S )zReturns an array of samples drawn from the Wald distribution.

         .. seealso::
            - :func:`cupy.random.wald` for full documentation
            - :meth:`numpy.random.RandomState.wald`
        r$   Nr   )r*   r7   r8   r6   r   r   r
   _wald_kernel)r   r   r[   r    r%   r\   r   s          r   waldzRandomState.wald  s     LU+++T\%u-M-M-M <>$..4DKKTK//D66''eQ:::r   c                     t          j        |          }t          j        |dk               rt          d          ||j        }|                     ||          }t          j        |d|z  |           |S )a$  Returns an array of samples drawn from the weibull distribution.

        .. warning::

            This function may synchronize the device.

        .. seealso::
            - :func:`cupy.random.weibull` for full documentation
            - :meth:`numpy.random.RandomState.weibull`
        r   r   NrT   rx   )r*   r7   rW   rX   r6   rY   r   r   s        r   weibullzRandomState.weibull  st     LOO8AE?? 	&W%%%<7D%%dE22
1bd""""r   c                 $   t          j        |          }t          j        |dk              rt          d          ||j        }t          j        ||          }t          j        || j        |           | 	                    |j
                   |S )a  Returns an array of samples drawn from the Zipf distribution.

        .. warning::

            This function may synchronize the device.

        .. seealso::
            - :func:`cupy.random.zipf` for full documentation
            - :meth:`numpy.random.RandomState.zipf`
        rT   z'a' must be a valid float > 1.0Nr5   )r*   r7   rW   rX   r6   r+   r   zipf_kernelr   r!   r    )r   r:   r    r%   r<   s        r   zipfzRandomState.zipf  s     LOO8AH 	B@AAA<7DJT///Qq111!&!!!r   Tc                    |t          d          t          |t          j                  r|j        dk    rt
          t          |t                    r|}|dk     rt          d          n?t          j        |d          }|j        dk    rt          d          t          |          }|t          j        |          }|j        dk    rt          d          t          |          |k    rt          d	          |dk    	                                st          d
          t          j
        |                                          }t          j        |d          st          d          |t          d          |}t          j        |          }|dk    r|dk    rt          d          |s|||k     rt          d          t          |t                    rt          j        |d          }n|                                }|                     |           |d|                             |          S |st
          |t          j        |||f          }t          j        t          j        |          |                     ||f          z   d          }	t          |t                    st          j        |	|          }	nA|dk    rd}|                     d||          }	|	                    t          j        d          }	t          |t                    r|	S |	j        dk    r!t          j        ||	         |j                  S ||	         S )zReturns an array of random values from a given 1-D array.

        .. seealso::
            - :func:`cupy.random.choice` for full documentation
            - :meth:`numpy.random.choice`

        Nz%a must be 1-dimensional or an integerr   z$a must be greater than or equal to 0Fr   r&   zp must be 1-dimensionalza and p must have same sizez"probabilities are not non-negativezprobabilities do not sum to 1z5choice() without specifying size is not supported yetz-a cannot be empty unless no samples are takenz@Cannot take a larger sample than population when 'replace=False'lr$   r  )rK   )rX   rM   r*   r   ndimr"  rN   arrayr   allrQ   getr   r   r)   aranger   shuffler.   broadcast_toargmaxrz   gumbelrandintr   r   r%   )
r   r:   r    replacerB   a_sizep_sumr6   r  indexs
             r   choicezRandomState.choice3  sG    9DEEEa&& 	&16Q;;%%a 	Fzz !GHHH  
15)))Av{{ !HIIIVVF=
1Av{{ !:;;;1vv !>???F<<>> G !EFFFHQKKOO%%E>%++ B !@AAA<%GI I Iz%  Q;;4!88LMMM 
	119}} () ) ) !S!! #+as333&&((LL!!!5D5>))%000 	&%%=!!dF^44AK $$ @ @!A%&( ( (E eS)) 3UE22{{LLFL77ELL%L88Ea 	L:??:ahag6666xr   c                     t          |t          j                  st          d          |j        dk    rt          d          ||                     t          |                             |dd<   dS )zReturns a shuffled array.

        .. seealso::
            - :func:`cupy.random.shuffle` for full documentation
            - :meth:`numpy.random.shuffle`

        zThe array must be cupy.ndarrayr   z)An array whose ndim is 0 is not supportedN)rM   r*   r   r   r^  _permutationr   r   r:   s     r   rc  zRandomState.shuffle  sk     !T\** 	><===6Q;;GHHH""3q66**+!!!r   c                     t          |t                    r|                     |          S ||                     t          |                             S )z6Returns a permuted range or a permutation of an array.)rM   rN   rn  r   ro  s     r   permutationzRandomState.permutation  sG    a 	0$$Q'''T&&s1vv..//r   c                     ddl m} t          j        |ft          j                  }|                    | j        |j        j	        |           t          j
        |          }|S )zReturns a permuted range.r   r   r$   )r   r   r*   r+   r   r   r  r   r,   r-   argsort)r   r  r   r  r_  s        r   rn  zRandomState._permutation  s\    222222SF%+666#>>>V$$r   z$y = T(loc) - log(-log(x)) * T(scale)cupy_gumbel_kernelc                 J   t          j        |          st          j        ||          }t          j        |          st          j        ||          }|t          j        ||          j        }|                     ||          }t                              ||||           |S )zReturns an array of samples drawn from a Gumbel distribution.

        .. seealso::
            - :func:`cupy.random.gumbel` for full documentation
            - :meth:`numpy.random.RandomState.gumbel`
        Nr   )	r   r   r*   r7   r8   r6   rr   r
   _gumbel_kernelrt   s         r   rf  zRandomState.gumbel  s     ~c"" 	+,sE**C~e$$ 	/L..E<>#u--3D##U#;;""1c5!444r   c                    t          j        |          st          j        |          }|t          j        |          }|dz
  }n|}t          j        |          dz
  }|t          j        ||          j        }||z
  }t          j        t          j
        |d          }|                     |                                |          }	|	                    |          }	t          j        |	|          }	|                    |d          }t          j        |	||	           |	S |d}t!          |          dz
  }
n!t!          |          }t!          |          dz
  }
||
k    rt#          d          |t          j        |          j        k     r9t#          d                    t          j        |          j                            |
t          j        |          j        k    r9t#          d	                    t          j        |          j                            |
|z
  }|                     ||                              |d          }t          j        |||           |S )
zReturns a scalar or an array of integer values over ``[low, high)``.

        .. seealso::
            - :func:`cupy.random.randint` for full documentation
            - :meth:`numpy.random.RandomState.randint`
        Nr&   Fr   rx   r   zlow >= highzlow is out of bounds for {}zhigh is out of bounds for {})r   r   r*   r7   
zeros_liker8   r6   r   r   r   r   r
  flattenr   r.   r|   rN   rX   r?  minr   r%   namer   )r   rL  rM  r    r%   lohidifftotal_elemsr2   hi1r\   s               r   rg  zRandomState.randint  s8    ~c"" *	,s##C|_S))1W\$''!+|~b"--37D#*8<qAAK..==C**U##C,sD))C5u--BHS"#&&&&J|#hhlXX$ii!mCxx ///DJu%%))) 188
5)).0 01 1 1 TZ&&*** 299
5)).0 01 1 1 8DtT**11%e1DDAHQ""""Hr   )NNr   )NTN)D__name__
__module____qualname____doc__r   r!   r3   r   r=   rN   rC   rH   rS   r]   rb   rd   rh   rn   r   ElementwiseKernelrs   rv   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   rr   r   r   r   r   r
  r   r   r  r   r3  rY   r6  r   r:  rA  rD  rH  rK  r/  rR  rU  rV  rX  r[  rl  rc  rq  rn  rv  rf  rg  r   r   r   r
   r
      sZ        4	 	 	 	= = =4 4 4& #%     #'c     "&U     %)    ( !$$e    ( $(u     "%4u      !%C     9=C      .e-uH O
 St5     cE    & !$e E E E E. !%C    0 37H %j^ ^ ^ ^@ ,0s , , , ,, Cd%    8 "     37e    0 59    4 D     !    ,: : :3 3 3 +5*
E,.CE EL
 
 
 "&U     !t5    . 4E3w=*, ,
 6e5z.,. .
a$ a$ a$F     2%1o	
 	 # # # #J $(u - - - - )-E 
# 
# 
# 
# *.U     $(u 3 3 3 3 #'e       > 10!5	" 	!' , 26U D D D D0 ,E+( M
 Cd% : : : :( (,5     +5*
	 	 L &* ; ; ; ; #%    ,  s    *N N N N`, , , 0 0 0   -U,u. N
 Cd%    " !%4s 1 1 1 1 1 1r   r
   c                 H    t                                          |            dS )a  Resets the state of the random number generator with a seed.

    This function resets the state of the global random number generator for
    the current device. Be careful that generators for other devices are not
    affected.

    Args:
        seed (None or int): Seed for the random number generator. If ``None``,
            it uses :func:`os.urandom` if available or :func:`time.time`
            otherwise. Note that this function does not support seeding by
            an integer array.

    N)get_random_stater   )r   s    r   r   r     s$     D!!!!!r   c                  
    i a d S r   )_random_statesr   r   r   reset_statesr    s     NNNr   c                  <   t          j                    } t                              | j        d          }|ft          j        d          }|!t          j        t          |                    }t          |          }t                              | j        |          }|S )aX  Gets the state of the random number generator for the current device.

    If the state for the current device is not created yet, this function
    creates a new one, initializes it, and stores it as the state for the
    current device.

    Returns:
        RandomState: The state of the random number generator for the
        device.

    N	CUPY_SEED)r   Devicer  ra  idr   getenvr   r   rN   r
   
setdefault)devrsr   s      r   r  r  	  s~     +--C			CFD	)	)B	zy%%<D		**D&&svr22Ir   c                     t          | t                    s/t          d                    t	          |                               | t
          t          j                    <   dS )zSets the state of the random number generator for the current device.

    Args:
        state(RandomState): Random state to set for the current device.
    z;Random state must be an instance of RandomState. Actual: {}N)rM   r
   r   r   typer  r   get_device_id)r  s    r   set_random_stater     s[     b+&& +R))+ + 	+ .0N6'))***r   c                 ^    t          j        |           } | j        dvrt          d          | S )N)rb   dz-cupy.random only supports float32 and float64)r   r%   r   r   r$   s    r   r   r   -  s2    KEz##GHHHLr   r   ) atexitr  r   r$  r   r   r#  r   r   r   numpy.linalgr   r*   r   r   	cupy.cudar   cupy.randomr   r   r   r   r   objectr
   r   r  registerr  r  r  r   r   r   r   <module>r     s           				     $ $ $ $ $ $                                        N N N N N& N N Nb&" " " "&    
  .
0 
0 
0    r   