Universal Non-Uniform Random Number Sampling in SciPy
SciPy provides an interface to many universal non-uniform random number
generators to sample random variates from a wide variety of univariate
continuous and discrete distributions. Implementations of a fast C library
called UNU.RAN are used
for speed and performance. Please look at UNU.RAN’s
documentation
for an in-depth explanation of these methods. It is heavily referred to
for writing this tutorial and the documentation of all the generators.
Introduction
Random variate generation is the small field of research that deals with
algorithms to generate random variates from various distributions. It is
common to assume that a uniform random number generator is available.
This is a program that produces a sequence of independent and identically
distributed continuous U(0,1) random variates (i.e. uniform random variates
on the interval (0,1)). Of course, real-world computers can never generate
ideal random numbers and they cannot produce numbers of arbitrary precision
but state-of-the-art uniform random number generators come close to this
aim. Thus, random variate generation deals with the problem of transforming
such a sequence of random numbers into non-uniform random variates.
These methods are universal and work in a black-box fashion.
U(0,1)
Some methods to do that are:
The Inversion method: When the inverse F−1 of the cumulative
distribution function is known, then random variate generation is easy.
We just generate a uniformly U(0,1) distributed random number U and
return X=F−1(U). As closed form solutions for the inverse
are rarely available, one usually needs to rely on approximations of
the inverse (e.g. scipy.special.ndtri,
scipy.special.stdtrit). In general, the implementation of special
functions is quite slow compared to the inversion methods in UNU.RAN.
The Rejection Method: The rejection method, often called
acceptance-rejection method, has been suggested by John von Neumann in
1951[1]. It involves computing an upper bound to the PDF (also called the
hat function) and using the inversion method to generate a random
variate, say Y, from this bound. Then a uniform random number can be
drawn between 0 and the value of the upper bound at Y. If this number
is less than the PDF at Y, return the sample otherwise reject it. See
.
The Ratio-of-Uniforms Method: This is a type of acceptance-rejection
method which is uses minimal bounding rectangles to construct the hat
function. See scipy.stats.sampling.RatioUniforms.
Inversion for Discrete Distributions: The difference compared to the
continuous case is that F is now a step-function. To realize
this in a computer, a search algorithm is used, the simplest of which
is sequential search. A uniform random number is generated from
U(0,1) and probabilities are summed until the cumulative probability
exceeds the uniform random number. The index at which this happens is
the required random variate and is returned.
When generating random variates of a distribution, two factors are important
to determine the speed of a generator: the setup step and the actual sampling.
Depending on the situation, different generators can be optimal. For example,
if one repeatedly needs to draw large samples from a given distribution with
a fixed shape parameter, a slow setup is acceptable if the sampling is fast.
This is called the fixed parameter case. If one aims to generate samples of
a distribution for different shape parameters (the varying parameter case),
an expensive setup that needs to be repeated for each parameter would lead
to very poor performance. In such a situation, a fast setup is crucial to
achieve good performance. An overview of the setup and sampling speed of the
different methods is shown in the table below.
To apply the numerical inversion method NumericalInversePolynomial to a large
number of continuous distributions in SciPy with minimal effort, take a look
at scipy.stats.sampling.FastGeneratorInversion.
For more details on the generators implemented in UNU.RAN, please refer to [2] and [3].
Basic concepts of the Interface
Every generator needs to be set up before one can start sampling from it.
This can be done by instantiating an object of that class. Most of the
generators take a distribution object as input which contains the implementation
of required methods like PDF, CDF, etc. In addition to the distribution
object, one can also pass parameters used to set up the generator. It is also
possible to truncate the distributions using a domain parameter. All
generators need a stream of uniform random numbers that are transformed into
random variates of the given distribution. This is done by passing a random_state
parameter with a NumPy BitGenerator as the uniform random number generator.
random_state can either be an integer, numpy.random.Generator,
or numpy.random.RandomState.
All the generators have a common rvs method that can be used to draw
samples from the given distribution.
An example of this interface is shown below:
fromscipy.stats.samplingimportTransformedDensityRejectionfrommathimportexpimportnumpyasnpclassStandardNormal:defpdf(self,x:float)->float:# note that the normalization constant isn't required
As shown in the example, we first initialize a distribution object that
contains an implementation of the methods required by the generator. In
our case, we use the TransformedDensityRejection (TDR)
method which requires a PDF and its derivative w.r.t. x (i.e. the variate).
In the above example, we have set up an object of the
TransformedDensityRejection method to sample from a
standard normal distribution. Now, we can start sampling from our
distribution by calling the rvs method:
<objectid> is the ID of the object given by UNU.RAN
<errorcode> is an error code representing a type of error.
<reason> is the reason why the error occurred.
<typeoferror> is a short description of the type of error.
The <reason> shows what caused the error. This, by itself, should contain
enough information to help debug the error. In addition, <errorid> and
<typeoferror> can be used to investigate different classes of error in
UNU.RAN. A complete list of all the error codes and their descriptions can be
found in the Section 8.4 of the UNU.RAN user
manual.
An example of an error generated by UNU.RAN is shown below:
This shows that UNU.RAN failed to initialize an object with ID TDR.003
because the PDF was < 0. i.e. negative. This falls under the type
“possible invalid data for the generator” and has error code 50.
Warnings thrown by UNU.RAN also follow the same format.