Package: polyagamma
Polya-GammaEfficiently generate samples from the Polya-Gamma distribution using a NumPy/SciPy compatible interface.Why?If you are reading this, you probably have already used thepypolyagammapackage before. It is
a great package that I have also used in the past, however I encountered several issues:Generating an array of samples is awkward because it requires using a list comprehension
if parameter values are scalars or have pre-allocated arrays of a known size to pass for both
the parameters and the output array. Moreover, broadcasting of input is not supported and thus
requiring the user to write another layer to support it.It requires extra effort to be used in multiprocessing because pickling of the
sampler is not supported.There is no parameter validation supported meaning it is easy to get the wrong samples if
you do not check the inputs manually.The sampling API is very different from the ones used by popular packages like numpy/scipy,
making it harder to just "plug-n-play" in existing code bases.It does not allow passing in an instance of anp.random.RandomStateornp.random.Generatorfor seeding, requiring extra effort when changing the seed if used in a larger code base.The C++ code wrapped by the package is GPLv3 licensed, making it difficult to
use the source code in a project that prefers licenses like MIT/Apache/BSD.The above issues are the reason why this package exists. And the aim ofpolyagammais to "fix" them.FeaturesInput parameters can be scalars, arrays or both; allowing for easy generation
of multi-dimensional samples without specifying the size.Input validation is done internally with clear error messages upon failure.It is flexible and allows the user to sample using one of 4 available algorithms.Implements functions to compute the CDF and density of the distribution as well
as their logarithms.Random number generation is thread safe.The functional API resembles that of common numpy/scipy functions, therefore making it easy to plugin to
existing libraries.polyagammais optimized for performance and tests show that it is faster
than other implementations.Pre-built wheels are provided for easy installation on Linux, MacOS and Windows.ExamplesPythonimportarrayimportnumpyasnpfrompolyagammaimportrandom_polyagamma# generate a PG(1, 0) sampleo=random_polyagamma()# Get a 5 by 1 array of PG(1, 2) variates.o=random_polyagamma(z=2,size=5)# We can pass sequences as input. Numpy's broadcasting rules apply here.# Get a 10 by 2 array where column 1 is PG(2, -10) and column 2 is PG(1, 10)o=random_polyagamma([2,1],[-10,10],size=(10,2))z=[[1.5,2,-0.75,4,5],[9.5,-8,7,6,-0.9]]o=random_polyagamma(1,z)# We can pass an output array using the `out` parameter. It does not have to be# a numpy array. it can be any object that implements the array or buffer protocols.# As long as its type is 64bit float, contiguous in memory and aligned (e.g. Python's array object).numpy_out=np.empty(5)array_out=array.array('d',[0]*5)random_polyagamma(out=numpy_out)print(numpy_out)random_polyagamma(out=array_out)print(array_out)# one can choose a sampling method from {devroye, alternate, gamma, saddle}.# If not given, the default behaviour is a hybrid sampler that picks the most# efficient method based on the input values.o=random_polyagamma(method="saddle")# one can also use an existing instance of `numpy.random.Generator` as a parameter.# This is useful to reproduce samples generated via a given seed.rng=np.random.default_rng(12345)o=random_polyagamma(random_state=rng)# If one is using a `numpy.random.RandomState` instance instead of the `Generator`# class, the object's underlying bitgenerator can be passed as the value of random_statebit_gen=np.random.RandomState(12345)._bit_generatoro=random_polyagamma(random_state=bit_gen)# When passing a large input array for the shape parameter `h`, parameter value# validation checks can be disabled if the values are guaranteed to be positive# to avoid some overhead, which may boost performance.large_h=np.ones(1000000)o=random_polyagamma(large_h,disable_checks=True)Functions to compute the density and CDF are available. Broadcasting of input is supported.frompolyagammaimportpolyagamma_pdf,polyagamma_cdf>>>polyagamma_pdf(0.1)# 3.613955566329298>>>polyagamma_cdf([1,2],h=2,z=1)# array([0.95637847, 0.99963397])>>>polyagamma_pdf([2,0.1],h=[[1,2],[3,4]],return_log=True)# array([[   -8.03172733,  -489.17101125]#        [   -3.82023942, -1987.09156971]])>>>polyagamma_cdf(4,z=[-100,0,2],return_log=True)# array([ 3.72007598e-44, -3.40628215e-09, -1.25463528e-12])CythonThe package also provides low-level functions that can be imported in cython modules. They are:random_polyagammarandom_polyagamma_fillrandom_polyagamma_fill2Refer to thepgm_random.hheader file for more info about the
function signatures. Below is an example of how these functions can be used.fromcpython.pycapsulecimportPyCapsule_GetPointerfrompolyagammacimportrandom_polyagamma_fill,DEVROYEfromnumpy.randomcimportbitgen_timportnumpyasnp# assuming there exists an instance of the Generator class called `rng`.bitgenerator=rng._bit_generator# get pointer to the underlying bitgenerator structcdefbitgen_t*bitgen=<bitgen_t*>PyCapsule_GetPointer(bitgenerator.capsule,"BitGenerator")# set distribution parameterscdefdoubleh=1,z=0# get a memory view of the array to store samples incdefdouble[:]out=np.empty(300)withbitgenerator.lock,nogil:random_polyagamma_fill(bitgen,h,z,DEVROYE,<size_t>out.shape[0],&out[0])print(out.base)...PyMCAs ofpymc>=4.0.0b1, this distribution can be accessed as a PyMC distribution object. See the
pymc documentation for more details.CFor an example of how to usepolyagammain a C program, seehere.DependenciesNumpy >= 1.19.0InstallationTo get the latest version of the package, one can install it by downloading the wheel/source distribution
from thereleasespage, or usingpipwith the following shell command:$pipinstall--pre-Upolyagammaor usingcondawith the following command:$condainstall-cconda-forgepolyagammaAlternatively, once can install from source with the following shell commands:$gitclonehttps://github.com/zoj613/polyagamma.git
$cdpolyagamma/
$pipinstall.BenchmarksBelow are runtime plots of 20000 samples generated for various values ofhandz, using each method. We restricthto integer values to accomodate thedevroyemethod, which cannot be used for non-integerh. The version of the
package used to generate them isv1.3.1.Generally:Thegammamethod is slowest and should be avoided in cases where speed is paramount.Forh >= 8, thesaddlemethod is the fastest for any value ofz.For0 <= z <= 1and integerh <= 4, thedevroyemethod should be preferred.Forz > 1and1 < h < 8, thealternatemethod is the most efficient.Forh > 50(or any value large enough), the normal approximation to the distribution is
fastest (not reported in the above plot but it is around 10 times faster than thesaddlemethod and also equally accurate).Therefore, we devise a "hybrid/default" sampler that picks a sampler based on the above guidelines.We also benchmark the hybrid sampler runtime with the sampler found in thepypolyagammapackage (version1.2.3). The version of NumPy we use is1.19.0. We compare our
sampler to thepgdrawvfunctions provided by the package. Below are runtime plots of 20000
samples for each value ofhandz. Values ofhrange from 0.1 to 50, whilezis set
to 0, 2.5, 5, and 10.It can be seen that when generating many samples at once for any given combination of
parameters,polyagammaoutperforms thepypolyagammapackage by a large margin.
The exception is when the scale parameter is very small (e.gh < 1). It is also worth
noting that thepypolygammapackage is on average faster than ours at generating exactly 1
sample value from the distribution. This is mainly due to the overhead introduced by creating
the bitgenerator + acquiring/releasing the thread lock + doing parameter validation checks at
every call to the function. This overhead can somewhat be mitigated by passing in a random
generator instance at every call to thepolyagammafunction. To eliminate this overhead,
it is best to use the Cython functions directly. Below is a timing example to demonstrate
the benefit of passing a generator explicitly:In[3]:rng=np.random.SFC64(1)In[4]:%timeitrandom_polyagamma()90µs±1.65µsperloop(mean±std.dev.of7runs,10000loopseach)In[5]:%timeitrandom_polyagamma(random_state=rng)1.69µs±6.96nsperloop(mean±std.dev.of7runs,1000000loopseach)To generate the above plots locally, run$pipinstall-rscripts/requirements.txt
$pythonscripts/benchmark.py--size=<somesize>--z=<zvalue>Note that the runtimes may differ  than the ones reported here, depending on the machine this script
is ran on.Distribution PlotsBelow is a visualization of the Cumulative distribution and density functions for
various values of the parameters.We can compare these plots to the Kernel density estimate and empirical CDF plots
generated from 20000 random samples using each of the available methods.ContributingAll contributions, bug reports, bug fixes, documentation improvements, enhancements, and ideas are welcome.To submit a PR, follow the steps below:Fork the repo.Install and setup the dev environment withpip install -r requirements-dev.txtormake dev.Start writing your changes, including unittests.Run tests to make sure they all pass withmake test.Once finished, you can submit a PR for review.ReferencesLuc Devroye. "On exact simulation algorithms for some distributions related to Jacobi theta functions." Statistics & Probability Letters, Volume 79, Issue 21, (2009): 2251-2259.Polson, Nicholas G., James G. Scott, and Jesse Windle. "Bayesian inference for logistic models using Pólya–Gamma latent variables." Journal of the American statistical Association 108.504 (2013): 1339-1349.J. Windle, N. G. Polson, and J. G. Scott. "Improved Polya-gamma sampling". Technical Report, University of Texas at Austin, 2013b.Windle, Jesse, Nicholas G. Polson, and James G. Scott. "Sampling Polya-Gamma random variates: alternate and approximate techniques." arXiv preprint arXiv:1405.0506 (2014)Windle, J. (2013). Forecasting high-dimensional, time-varying variance-covariance matrices with high-frequency data and sampling Pólya-Gamma random variates for posterior distributions derived from logistic likelihoods.(PhD thesis). Retrieved fromhttp://hdl.handle.net/2152/21842.