Skip to content

Commit e848a21

Browse files
committed
fixes to distribution guide and add glossary skeleton
1 parent 188244a commit e848a21

File tree

3 files changed

+21
-16
lines changed

3 files changed

+21
-16
lines changed

docs/source/conf.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,8 @@
144144
# intersphinx configuration to ease linking arviz docs
145145
intersphinx_mapping = {
146146
"arviz": ("https://arviz-devs.github.io/arviz/", None),
147+
"aesara": ("https://aesara.readthedocs.io/en/latest/", None),
148+
"numpy": ("https://numpy.org/doc/stable/", None),
147149
}
148150

149151

docs/source/developer_guide_implementing_distribution.md

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ This guide provides an overview on how to implement a distribution for version 4
44
It is designed for developers who wish to add a new distribution to the library.
55
Users will not be aware of all this complexity and should instead make use of helper methods such as (TODO).
66

7-
PyMC3 {`class`}`~pymc3.distributions.Distribution` build on top of Aesara's {`class`}`~aesara.tensor.random.op.RandomVariable`, and implement `logp` and `logcdf` methods as well as other initialization and validation helpers, most notably `shape/dims`, alternative parametrizations, and default `transforms`.
7+
PyMC3 {class}`~pymc3.distributions.Distribution` build on top of Aesara's {class}`~aesara.tensor.random.op.RandomVariable`, and implement `logp` and `logcdf` methods as well as other initialization and validation helpers, most notably `shape/dims`, alternative parametrizations, and default `transforms`.
88

99
Here is a summary check-list of the steps needed to implement a new distribution.
1010
Each section will be expanded below:
@@ -19,7 +19,7 @@ This guide does not attempt to explain the rationale behind the `Distributions`
1919

2020
## 1. Creating a new `RandomVariable` `Op`
2121

22-
{`class`}`~aesara.tensor.random.op.RandomVariable` are responsible for implementing the random sampling methods, which in version 3 of PyMC3 used to be one of the standard `Distribution` methods, alongside `logp` and `logcdf`.
22+
{class}`~aesara.tensor.random.op.RandomVariable` are responsible for implementing the random sampling methods, which in version 3 of PyMC3 used to be one of the standard `Distribution` methods, alongside `logp` and `logcdf`.
2323
The `RandomVariable` is also responsible for parameter broadcasting and shape inference.
2424

2525
Before creating a new `RandomVariable` make sure that it is not offered in the [Numpy library](https://numpy.org/doc/stable/reference/random/generator.html#distributions).
@@ -85,12 +85,12 @@ blah = BlahRV()
8585

8686
Some important things to keep in mind:
8787

88-
1. Everything inside the `rng_fn` method is pure Python code (as are the inputs) and should not make use of other `Aesara` symbolic ops. The random method should make use of the `rng` which is a Numpy {`class`}`~numpy.random.RandomState`, so that samples are reproducible.
88+
1. Everything inside the `rng_fn` method is pure Python code (as are the inputs) and should not make use of other `Aesara` symbolic ops. The random method should make use of the `rng` which is a Numpy {class}`~numpy.random.RandomState`, so that samples are reproducible.
8989
1. The `size` argument (together with the inputs shape) are the only way for the user to specify non-default `RandomVariable` dimensions. The `rng_fn` will have to take this into consideration for correct output. `size` is the specification used by `Numpy` and `Scipy` and works like PyMC3 `shape` for univariate distributions, but is different for multivariate distributions. Unfortunately there is no general reference documenting how `size` ought to work for multivariate distributions. This [discussion](https://github.com/numpy/numpy/issues/17669) may be helpful to get more context.
9090
1. `Aesara` tries to infer the output shape of the `RandomVariable` (given a user-specified size) by introspection of the `ndim_supp` and `ndim_params` attributes. However, the default method may not work for more complex distributions. In that case, custom `_shape_from_params` (and less probably, `_infer_shape`) should also be implemented in the new `RandomVariable` class. One simple example is seen in the {class}`~pymc3.distributions.multivariate.DirichletMultinomialRV` where it was necessary to specify the `rep_param_idx` so that the `default_shape_from_params` helper method could do its job. In more complex cases, it may not be possible to make use of the default helper, but those have not been found yet!
9191
1. It's okay to use the `rng_fn` `classmethods` of other Aesara and PyMC3 `RandomVariables` inside the new `rng_fn`. For example if you are implementing a negative HalfNormal `RandomVariable`, your `rng_fn` can simply return `- halfnormal.rng_fn(rng, scale, size)`.
9292

93-
*Note: In addition to `size`, the `PyMC3` API also provides `shape` and `dims` as alternatives to define a distribution dimensionality, but this is taken care of by {`class`}`~pymc3.distributions.Distribution`, and should not require any extra changes.*
93+
*Note: In addition to `size`, the `PyMC3` API also provides `shape` and `dims` as alternatives to define a distribution dimensionality, but this is taken care of by {class}`~pymc3.distributions.Distribution`, and should not require any extra changes.*
9494

9595
For a quick test that your new `RandomVariable` `Op` is working, you can call the `Op` with the necessary parameters and then call `eval()` on the returned object:
9696

@@ -114,11 +114,11 @@ blah([0, 0], [1, 2], size=(10, 2)).eval()
114114

115115
## 2. Inheriting from a PyMC3 base `Distribution` class
116116

117-
After implementing the new `RandomVariable` `Op`, it's time to make use of it in a new PyMC3 {`Distribution`}`pymc3.distributions.Distribution`.
118-
PyMC3 works in a very {functional}`Functional_Programming` way, and the `distribution` classes are there mostly to facilitate porting the `v3` code to the new `v4` version, add PyMC3 API features and keep related methods organized together.
117+
After implementing the new `RandomVariable` `Op`, it's time to make use of it in a new PyMC3 {class}`pymc3.distributions.Distribution`.
118+
PyMC3 works in a very {term}`functional <Functional Programming>` way, and the `distribution` classes are there mostly to facilitate porting the `v3` code to the new `v4` version, add PyMC3 API features and keep related methods organized together.
119119
In practice, they take care of:
120120

121-
1. Linking ({dispatch}`Dispatching`) a rv_op class with the corresponding logp and logcdf methods.
121+
1. Linking ({term}`Dispatching`) a rv_op class with the corresponding logp and logcdf methods.
122122
1. Defining a standard transformation (for continuous distributions) that converts a bounded variable domain (e.g., positive line) to an unbounded domain (i.e., the real line), which many samplers prefer.
123123
1. Validating the parametrization of a distribution and converting non-symbolic inputs (i.e., numeric literals or numpy arrays) to symbolic variables.
124124
1. Converting multiple alternative parametrizations to the standard parametrization that the `RandomVariable` is defined in terms of.
@@ -183,10 +183,10 @@ class Blah(PositiveContinuous):
183183

184184
Some notes:
185185

186-
1. A distribution should at the very least inherit from `Discrete` or `Continuous`. For the latter, more specific subclasses exist:`PositiveContinuous`, `UnitContinuous`, `BoundedContinuous`, `CircularContinuous`, which specify default transformations for the variables. If you need to specify a one-time custom transform you can also override the `__new__` method, as is done for the {`class`}`~pymc3.distributions.multivariate.Dirichlet`.
187-
1. If a distribution does not have a corresponding `random` implementation, a `RandomVariable` should still be created that raises a `NotImplementedError`. This is the case for the {`class`}`~pymc3.distributions.continuous.FlatRV`. In this case it will be necessary to provide a standard `initval` by
186+
1. A distribution should at the very least inherit from {class}`~pymc3.distributions.Discrete` or {class}`~pymc3.distributions.Continuous`. For the latter, more specific subclasses exist: `PositiveContinuous`, `UnitContinuous`, `BoundedContinuous`, `CircularContinuous`, which specify default transformations for the variables. If you need to specify a one-time custom transform you can also override the `__new__` method, as is done for the {class}`~pymc3.distributions.multivariate.Dirichlet`.
187+
1. If a distribution does not have a corresponding `random` implementation, a `RandomVariable` should still be created that raises a `NotImplementedError`. This is the case for the {class}`~pymc3.distributions.continuous.Flat`. In this case it will be necessary to provide a standard `initval` by
188188
overriding `__new__`.
189-
1. As mentioned above, `v4` works in a very {functional}`Functional_Programming` way, and all the information that is needed in the `logp` and `logcdf` methods is expected to be "carried" via the `RandomVariable` inputs. You may pass numerical arguments that are not strictly needed for the `rng_fn` method but are used in the `logp` and `logcdf` methods. Just keep in mind whether this affects the correct shape inference behavior of the `RandomVariable`. If specialized non-numeric information is needed you might need to define your custom`_logp` and `_logcdf` {dispatch}`Dispatching` functions, but this should be done as a last resort.
189+
1. As mentioned above, `v4` works in a very {term}`functional <Functional Programming>` way, and all the information that is needed in the `logp` and `logcdf` methods is expected to be "carried" via the `RandomVariable` inputs. You may pass numerical arguments that are not strictly needed for the `rng_fn` method but are used in the `logp` and `logcdf` methods. Just keep in mind whether this affects the correct shape inference behavior of the `RandomVariable`. If specialized non-numeric information is needed you might need to define your custom`_logp` and `_logcdf` {term}`Dispatching` functions, but this should be done as a last resort.
190190
1. The `logcdf` method is not a requirement, but it's a nice plus!
191191

192192
For a quick check that things are working you can try the following:
@@ -214,7 +214,7 @@ pm.logcdf(blah, [1.5, 1.5]).eval()
214214
## 3. Adding tests for the new `RandomVariable`
215215

216216
Tests for new `RandomVariables` are mostly located in `pymc3/tests/test_distributions_random.py`.
217-
Most tests can be accomodated by the default `BaseTestDistribution` class, which provides default tests for checking:
217+
Most tests can be accommodated by the default `BaseTestDistribution` class, which provides default tests for checking:
218218
1. Expected inputs are passed to the `rv_op` by the `dist` `classmethod`, via `check_pymc_params_match_rv_op`
219219
1. Expected (exact) draws are being returned, via `check_pymc_draws_match_reference`
220220
1. Shape variable inference is correct, via `check_rv_size`
@@ -258,7 +258,7 @@ class TestBlahAltParam2(BaseTestDistribution):
258258

259259
```
260260

261-
Custom tests can also be added to the class as is done for the {`class`}`~pymc3.tests.test_random.TestFlat`.
261+
Custom tests can also be added to the class as is done for the {class}`~pymc3.tests.test_random.TestFlat`.
262262

263263
### Note on `check_rv_size` test:
264264

@@ -271,7 +271,7 @@ tests_to_run = ["check_rv_size"]
271271
```
272272

273273
This is usually needed for Multivariate distributions.
274-
You can see an example in {`class`}`~pymc3.test.test_random.TestDirichlet`.
274+
You can see an example in {class}`~pymc3.test.test_random.TestDirichlet`.
275275

276276
### Notes on `check_pymcs_draws_match_reference` test
277277

@@ -281,7 +281,7 @@ The latter kind of test (if warranted) can be performed with the aid of `pymc3_r
281281
This kind of test only makes sense if there is a good independent generator reference (i.e., not just the same composition of numpy / scipy python calls that is done inside `rng_fn`).
282282

283283
Finally, when your `rng_fn` is doing something more than just calling a `numpy` or `scipy` method, you will need to setup an equivalent seeded function with which to compare for the exact draws (instead of relying on `seeded_[scipy|numpy]_distribution_builder`).
284-
You can find an example in {`class`}`~pymc3.tests.test_distributions_random.TestWeibull`, whose `rng_fn` returns `beta * np.random.weibull(alpha, size=size)`.
284+
You can find an example in {class}`~pymc3.tests.test_distributions_random.TestWeibull`, whose `rng_fn` returns `beta * np.random.weibull(alpha, size=size)`.
285285

286286

287287
## 4. Adding tests for the `logp` / `logcdf` methods
@@ -357,8 +357,7 @@ New distributions should have a rich docstring, following the same format as tha
357357
It generally looks something like this:
358358

359359
```python
360-
r"""
361-
Univariate blah distribution.
360+
r"""Univariate blah distribution.
362361
363362
The pdf of this distribution is
364363

docs/source/glossary.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,8 @@ Second term
1212
Definitions can have as many lines as desired, and should be written in markdown. Definitions
1313
can contain any markdown formatting for MyST to parse, this includes basic markdown like **bold**
1414
as well as MyST directives and roles like {fa}`fort awesome,style=fab`
15+
Functional Programming
16+
Functional programming is writing pure functions
17+
Dispatching
18+
Choosing which implementation of an operation is used
1519
:::::

0 commit comments

Comments
 (0)