[SciPy-Dev] Integrating UNU.RAN in scipy.stats

Tirth Patel tirthasheshpatel at gmail.com
Fri Jul 16 15:48:24 EDT 2021


Hi all,

I, Christoph, and Nicholas have been working on gh-14215 [1] to integrate
UNU.RAN library in SciPy. We'd appreciate your thoughts on it!

We have designed an object-oriented API for sampling from any continuous or
discrete distributions using universal generators in UNU.RAN. For now, only
the `TransformedDensityRejection` (for continuous distributions) and
`DiscreteAliasUrn` (for discrete distributions) methods have been added.
These methods take a distribution object with required methods like PDF,
dPDF, CDF, etc as input and set-up a generator which can then be used to
sample from that distribution:

    >>> from scipy.stats import TransformedDensityRejection
    >>> import numpy as np
    >>>
    >>> class StdNorm:
    ...     def pdf(self, x: float) -> float:
    ...         # notice that normalization constant is not required
    ...         # and the pdf accepts and returns scalars.
    ...         return np.exp(-0.5 * x*x)
    ...     def dpdf(self, x: float) -> float:
    ...         return -x * self.pdf(x)
    ...
    >>> dist = StdNorm()
    >>> rng = TransformedDensityRejection(dist, seed=123)
    >>> rng.rvs()
    0.474548717355228

One of the tricky parts about this PR is handling errors occurring in
Python callbacks and UNU.RAN C library. We could use some reviews and ideas
to build a maintainable infrastructure. Use of non-local returns causes
memory leaks making the code for error handling a lot less trivial and
possibly much more complex. I would really appreciate it if someone could
take a look at the Cython and C code in the PR and help verify the approach
or suggest an alternative approach, if any. There are some discussions
about this in [2] and [3] and you can also look at the review comments on
the main PR. Although the API design is not final yet, please feel free to
comment on it as well. Thanks!

[1]: https://github.com/scipy/scipy/pull/14215
[2]: https://github.com/tirthasheshpatel/scipy/pull/9
[3]: https://github.com/tirthasheshpatel/unuran/pull/1


--
Kind Regards,
Tirth Patel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.python.org/pipermail/scipy-dev/attachments/20210717/65b4698c/attachment.html>


More information about the SciPy-Dev mailing list