Skip to content

Pass coords argument into as_model decorator #282

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion pymc_experimental/model/model_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ def as_model(*model_args, **model_kwargs):
R"""
Decorator to provide context to PyMC models declared in a function.
This removes all need to think about context managers and lets you separate creating a generative model from using the model.
Additionally, a coords argument is added to the function so coords can be changed during function invocation

Adapted from `Rob Zinkov's blog post <https://www.zinkov.com/posts/2023-alternative-frontends-pymc/>`_ and inspired by the `sampled <https://github.com/colcarroll/sampled>`_ decorator for PyMC3.

Expand All @@ -32,12 +33,21 @@ def basic_model():
m = basic_model()
pm.sample(model=m)

# alternative way to use functional API
@pmx.as_model()
def basic_model():
pm.Normal("x", 0., 1., dims="obs")

m = basic_model(coords={"obs": ["a", "b"]})
pm.sample(model=m)

"""

def decorator(f):
@wraps(f)
def make_model(*args, **kwargs):
with Model(*model_args, **model_kwargs) as m:
coords = model_kwargs.pop("coords", {}) | kwargs.pop("coords", {})
with Model(*model_args, coords=coords, **model_kwargs) as m:
f(*args, **kwargs)
return m

Expand Down
7 changes: 7 additions & 0 deletions pymc_experimental/tests/model/test_model_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,11 @@ def model_wrapped():

mw = model_wrapped()

@pmx.as_model()
def model_wrapped2():
pm.Normal("x", 0.0, 1.0, dims="obs")

mw2 = model_wrapped2(coords=coords)

np.testing.assert_equal(model.point_logps(), mw.point_logps())
np.testing.assert_equal(mw.point_logps(), mw2.point_logps())