|
| 1 | +# Copyright 2024 The PyMC Developers |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +from collections.abc import Sequence |
| 15 | + |
| 16 | +import xarray |
| 17 | + |
| 18 | +from xarray import Dataset |
| 19 | + |
| 20 | +from pymc.backends.arviz import apply_function_over_dataset, coords_and_dims_for_inferencedata |
| 21 | +from pymc.model.core import Model, modelcontext |
| 22 | + |
| 23 | + |
| 24 | +def compute_deterministics( |
| 25 | + dataset: Dataset, |
| 26 | + *, |
| 27 | + var_names: Sequence[str] | None = None, |
| 28 | + model: Model | None = None, |
| 29 | + sample_dims: Sequence[str] = ("chain", "draw"), |
| 30 | + merge_dataset: bool = False, |
| 31 | + progressbar: bool = True, |
| 32 | + compile_kwargs: dict | None = None, |
| 33 | +) -> Dataset: |
| 34 | + """Compute model deterministics given a dataset with values for model variables. |
| 35 | +
|
| 36 | + Parameters |
| 37 | + ---------- |
| 38 | + dataset : Dataset |
| 39 | + Dataset with values for model variables. Commonly InferenceData["posterior"]. |
| 40 | + var_names : sequence of str, optional |
| 41 | + List of names of deterministic variable to compute. |
| 42 | + If None, compute all deterministics in the model. |
| 43 | + model : Model, optional |
| 44 | + Model to use. If None, use context model. |
| 45 | + sample_dims : sequence of str, default ("chain", "draw") |
| 46 | + Sample (batch) dimensions of the dataset over which to compute the deterministics. |
| 47 | + merge_dataset : bool, default False |
| 48 | + Whether to extend the original dataset or return a new one. |
| 49 | + progressbar : bool, default True |
| 50 | + Whether to display a progress bar in the command line. |
| 51 | + progressbar_theme : Theme, optional |
| 52 | + Custom theme for the progress bar. |
| 53 | + compile_kwargs: dict, optional |
| 54 | + Additional arguments passed to `model.compile_fn`. |
| 55 | +
|
| 56 | + Returns |
| 57 | + ------- |
| 58 | + Dataset |
| 59 | + Dataset with values for the deterministics. |
| 60 | +
|
| 61 | +
|
| 62 | + Examples |
| 63 | + -------- |
| 64 | + .. code:: python |
| 65 | +
|
| 66 | + import pymc as pm |
| 67 | +
|
| 68 | + with pm.Model(coords={"group": (0, 2, 4)}) as m: |
| 69 | + mu_raw = pm.Normal("mu_raw", 0, 1, dims="group") |
| 70 | + mu = pm.Deterministic("mu", mu_raw.cumsum(), dims="group") |
| 71 | +
|
| 72 | + trace = pm.sample(var_names=["mu_raw"], chains=2, tune=5 draws=5) |
| 73 | +
|
| 74 | + assert "mu" not in trace.posterior |
| 75 | +
|
| 76 | + with m: |
| 77 | + trace.posterior = pm.compute_deterministics(trace.posterior, merge_dataset=True) |
| 78 | +
|
| 79 | + assert "mu" in trace.posterior |
| 80 | +
|
| 81 | +
|
| 82 | + """ |
| 83 | + model = modelcontext(model) |
| 84 | + |
| 85 | + if var_names is None: |
| 86 | + deterministics = model.deterministics |
| 87 | + else: |
| 88 | + deterministics = [model[var_name] for var_name in var_names] |
| 89 | + if not set(deterministics).issubset(set(model.deterministics)): |
| 90 | + raise ValueError("Not all var_names corresponded to model deterministics") |
| 91 | + |
| 92 | + fn = model.compile_fn( |
| 93 | + inputs=model.free_RVs, |
| 94 | + outs=deterministics, |
| 95 | + on_unused_input="ignore", |
| 96 | + **(compile_kwargs or {}), |
| 97 | + ) |
| 98 | + |
| 99 | + coords, dims = coords_and_dims_for_inferencedata(model) |
| 100 | + |
| 101 | + new_dataset = apply_function_over_dataset( |
| 102 | + fn, |
| 103 | + dataset[[rv.name for rv in model.free_RVs]], |
| 104 | + output_var_names=[det.name for det in model.deterministics], |
| 105 | + dims=dims, |
| 106 | + coords=coords, |
| 107 | + sample_dims=sample_dims, |
| 108 | + progressbar=progressbar, |
| 109 | + ) |
| 110 | + |
| 111 | + if merge_dataset: |
| 112 | + new_dataset = xarray.merge([dataset, new_dataset], compat="override") |
| 113 | + |
| 114 | + return new_dataset |
0 commit comments