Skip to content

Metaclass

pyrenew helper classes

Model

Model(**kwargs: object)

Abstract base class for models

Source code in pyrenew/metaclass.py
81
82
83
@abstractmethod
def __init__(self, **kwargs: object) -> None:  # numpydoc ignore=GL08
    pass

model

model(**kwargs: object) -> tuple

Alias for the sample method.

Parameters:

Name Type Description Default
**kwargs object

Additional keyword arguments passed through to internal sample calls, should there be any.

{}

Returns:

Type Description
tuple
Source code in pyrenew/metaclass.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def model(self, **kwargs: object) -> tuple:
    """
    Alias for the sample method.

    Parameters
    ----------
    **kwargs
        Additional keyword arguments passed through to
        internal `sample` calls, should there be any.

    Returns
    -------
    tuple
    """
    return self.sample(**kwargs)

posterior_predictive

posterior_predictive(
    rng_key: ArrayLike | None = None,
    numpyro_predictive_args: dict = {},
    **kwargs: object,
) -> dict

A wrapper of numpyro.infer.util.Predictive to generate posterior predictive samples.

Parameters:

Name Type Description Default
rng_key ArrayLike | None

Random key for the Predictive function call. Defaults to None.

None
numpyro_predictive_args dict

Dictionary of arguments to be passed to the numpyro.infer.util.Predictive constructor.

{}
**kwargs object

Additional named arguments passed to the __call__() method of numpyro.infer.util.Predictive.

{}

Returns:

Type Description
dict
Source code in pyrenew/metaclass.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
def posterior_predictive(
    self,
    rng_key: ArrayLike | None = None,
    numpyro_predictive_args: dict = {},
    **kwargs: object,
) -> dict:
    """
    A wrapper of [`numpyro.infer.util.Predictive`][] to generate
    posterior predictive samples.

    Parameters
    ----------
    rng_key
        Random key for the Predictive function call. Defaults to None.
    numpyro_predictive_args
        Dictionary of arguments to be passed to the
        [`numpyro.infer.util.Predictive`][] constructor.
    **kwargs
        Additional named arguments passed to the
        `__call__()` method of
        [`numpyro.infer.util.Predictive`][].

    Returns
    -------
    dict
    """
    if self.mcmc is None:
        raise ValueError(
            "No posterior samples available. Run model with model.run()."
        )

    if rng_key is None:
        rand_int = np.random.randint(np.iinfo(np.int64).min, np.iinfo(np.int64).max)
        rng_key = jr.key(rand_int)

    predictive = Predictive(
        model=self.model,
        posterior_samples=self.mcmc.get_samples(),
        **numpyro_predictive_args,
    )

    return predictive(rng_key, **kwargs)

print_summary

print_summary(prob: float = 0.9, exclude_deterministic: bool = True) -> None

A wrapper of numpyro.infer.mcmc.MCMC.print_summary.

Parameters:

Name Type Description Default
prob float

The width of the credible interval to show. Default 0.9

0.9
exclude_deterministic bool

Whether to print deterministic sites in the summary. Defaults to True.

True

Returns:

Type Description
None
Source code in pyrenew/metaclass.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def print_summary(
    self,
    prob: float = 0.9,
    exclude_deterministic: bool = True,
) -> None:
    """
    A wrapper of [`numpyro.infer.mcmc.MCMC.print_summary`][].

    Parameters
    ----------
    prob
        The width of the credible interval to show. Default 0.9
    exclude_deterministic
        Whether to print deterministic sites in the summary.
        Defaults to True.

    Returns
    -------
    None
    """
    return self.mcmc.print_summary(prob, exclude_deterministic)

prior_predictive

prior_predictive(
    rng_key: ArrayLike | None = None,
    numpyro_predictive_args: dict = {},
    **kwargs: object,
) -> dict

A wrapper for numpyro.infer.util.Predictive to generate prior predictive samples.

Parameters:

Name Type Description Default
rng_key ArrayLike | None

Random key for the Predictive function call. Default None.

None
numpyro_predictive_args dict

Dictionary of arguments to be passed to the numpyro.infer.util.Predictive constructor. Default None.

{}
**kwargs object

Additional named arguments passed to the __call__() method of numpyro.infer.util.Predictive.

{}

Returns:

Type Description
dict
Source code in pyrenew/metaclass.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
def prior_predictive(
    self,
    rng_key: ArrayLike | None = None,
    numpyro_predictive_args: dict = {},
    **kwargs: object,
) -> dict:
    """
    A wrapper for [`numpyro.infer.util.Predictive`][]
    to generate prior predictive samples.

    Parameters
    ----------
    rng_key
        Random key for the Predictive function call.
        Default None.
    numpyro_predictive_args
        Dictionary of arguments to be passed to
        the [`numpyro.infer.util.Predictive`][]
        constructor. Default None.
    **kwargs
        Additional named arguments passed to the
        `__call__()` method of
        [`numpyro.infer.util.Predictive`][].

    Returns
    -------
    dict
    """

    if rng_key is None:
        rand_int = np.random.randint(np.iinfo(np.int64).min, np.iinfo(np.int64).max)
        rng_key = jr.key(rand_int)

    predictive = Predictive(
        model=self.model,
        posterior_samples=None,
        **numpyro_predictive_args,
    )

    return predictive(rng_key, **kwargs)

run

run(
    num_warmup: int,
    num_samples: int,
    rng_key: ArrayLike | None = None,
    nuts_args: dict = None,
    mcmc_args: dict = None,
    **kwargs: object,
) -> None

Run the model after validating model-specific arguments.

Validation occurs before the NumPyro kernel and MCMC objects are initialized. Models without model-specific run validation proceed unchanged. If validation, initialization, or sampling fails, kernel and mcmc are reset to None.

Parameters:

Name Type Description Default
nuts_args dict

Dictionary of arguments passed to the kernel numpyro.infer.hmc.NUTS constructor. Defaults to None.

None
mcmc_args dict

Dictionary of arguments passed to the MCMC runner numpyro.infer.mcmc.MCMC constructor. Defaults to None.

None
**kwargs object

Model-specific arguments. These are validated before MCMC initialization and then forwarded to the model's sample() method by the MCMC runner.

{}

Returns:

Type Description
None
Source code in pyrenew/metaclass.py
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
def run(
    self,
    num_warmup: int,
    num_samples: int,
    rng_key: ArrayLike | None = None,
    nuts_args: dict = None,
    mcmc_args: dict = None,
    **kwargs: object,
) -> None:
    """
    Run the model after validating model-specific arguments.

    Validation occurs before the NumPyro kernel and MCMC objects are
    initialized. Models without model-specific run validation proceed
    unchanged. If validation, initialization, or sampling fails, ``kernel``
    and ``mcmc`` are reset to ``None``.

    Parameters
    ----------
    nuts_args
        Dictionary of arguments passed to the kernel
        [`numpyro.infer.hmc.NUTS`][] constructor.
        Defaults to None.
    mcmc_args
        Dictionary of arguments passed to the MCMC runner
        [`numpyro.infer.mcmc.MCMC`][] constructor.
        Defaults to None.
    **kwargs
        Model-specific arguments. These are validated before MCMC
        initialization and then forwarded to the model's ``sample()``
        method by the MCMC runner.

    Returns
    -------
    None
    """

    # A failed run must not leave samples from a previous run, or a
    # partially initialized runner, attached to the model.
    self.kernel = None
    self.mcmc = None

    try:
        self._validate_run_args(**kwargs)

        self._init_model(
            num_warmup=num_warmup,
            num_samples=num_samples,
            nuts_args=nuts_args,
            mcmc_args=mcmc_args,
        )
        if rng_key is None:
            rand_int = np.random.randint(
                np.iinfo(np.int64).min, np.iinfo(np.int64).max
            )
            rng_key = jr.key(rand_int)

        self.mcmc.run(rng_key=rng_key, **kwargs)
    except BaseException:
        self.kernel = None
        self.mcmc = None
        raise

    return None

sample abstractmethod

sample(**kwargs: object) -> tuple

Sample method of the model.

The method design in the class should have at least kwargs.

Parameters:

Name Type Description Default
**kwargs object

Additional keyword arguments passed through to internal sample calls, should there be any.

{}

Returns:

Type Description
tuple
Source code in pyrenew/metaclass.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
@abstractmethod
def sample(
    self,
    **kwargs: object,
) -> tuple:
    """
    Sample method of the model.

    The method design in the class should have at least kwargs.

    Parameters
    ----------
    **kwargs
        Additional keyword arguments passed through to internal
        `sample` calls, should there be any.

    Returns
    -------
    tuple
    """
    pass

RandomVariable

RandomVariable(name: str, **kwargs: object)

Abstract base class for latent and observed random variables.

Parameters:

Name Type Description Default
name str

A non-empty string identifying this random variable.

required

Default constructor.

Parameters:

Name Type Description Default
name str

A non-empty string identifying this random variable.

required
**kwargs object

Additional keyword arguments.

{}

Raises:

Type Description
ValueError

If name is not a non-empty string.

Source code in pyrenew/metaclass.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def __init__(self, name: str, **kwargs: object) -> None:
    """
    Default constructor.

    Parameters
    ----------
    name
        A non-empty string identifying this random variable.
    **kwargs
        Additional keyword arguments.

    Raises
    ------
    ValueError
        If ``name`` is not a non-empty string.
    """
    if not isinstance(name, str) or len(name) == 0:
        raise ValueError(
            f"name must be a non-empty string. Got {type(name).__name__}: {name!r}"
        )
    self.name = name

__call__

__call__(**kwargs: object) -> tuple

Alias for sample.

Source code in pyrenew/metaclass.py
67
68
69
70
71
def __call__(self, **kwargs: object) -> tuple:
    """
    Alias for `sample`.
    """
    return self.sample(**kwargs)

sample abstractmethod

sample(**kwargs: object) -> tuple

Sample method of the process

The method design in the class should have at least kwargs.

Parameters:

Name Type Description Default
**kwargs object

Additional keyword arguments passed through to internal sample calls, should there be any.

{}

Returns:

Type Description
tuple
Source code in pyrenew/metaclass.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
@abstractmethod
def sample(
    self,
    **kwargs: object,
) -> tuple:
    """
    Sample method of the process

    The method design in the class should have at least kwargs.

    Parameters
    ----------
    **kwargs
        Additional keyword arguments passed through to internal
        `sample` calls, should there be any.

    Returns
    -------
    tuple
    """
    pass