|
| 1 | +import numpy as np |
| 2 | +import pytest |
| 3 | +import pymc as pm |
| 4 | +from causalpy.pymc_models import ModelBuilder |
| 5 | +import arviz as az |
| 6 | +import pandas as pd |
| 7 | + |
| 8 | + |
| 9 | +class MyToyModel(ModelBuilder): |
| 10 | + def build_model(self, X, y, coords): |
| 11 | + with self: |
| 12 | + X_ = pm.MutableData(name="X", value=X) |
| 13 | + y_ = pm.MutableData(name="y", value=y) |
| 14 | + beta = pm.Normal("beta", mu=0, sigma=1, shape=X_.shape[1]) |
| 15 | + sigma = pm.HalfNormal("sigma", sigma=1) |
| 16 | + mu = pm.Deterministic("mu", pm.math.dot(X_, beta)) |
| 17 | + pm.Normal("y_hat", mu=mu, sigma=sigma, observed=y_) |
| 18 | + |
| 19 | + |
| 20 | +class TestModelBuilder: |
| 21 | + def test_init(self): |
| 22 | + mb = ModelBuilder() |
| 23 | + assert mb.idata is None |
| 24 | + assert mb.sample_kwargs == {} |
| 25 | + |
| 26 | + @pytest.mark.parametrize( |
| 27 | + argnames="coords", argvalues=[{"a": 1}, None], ids=["coords-dict", "coord-None"] |
| 28 | + ) |
| 29 | + @pytest.mark.parametrize( |
| 30 | + argnames="y", argvalues=[np.ones(3), None], ids=["y-array", "y-None"] |
| 31 | + ) |
| 32 | + @pytest.mark.parametrize( |
| 33 | + argnames="X", argvalues=[np.ones(2), None], ids=["X-array", "X-None"] |
| 34 | + ) |
| 35 | + def test_model_builder(self, X, y, coords) -> None: |
| 36 | + with pytest.raises( |
| 37 | + NotImplementedError, match="This method must be implemented by a subclass" |
| 38 | + ): |
| 39 | + ModelBuilder().build_model(X=X, y=y, coords=coords) |
| 40 | + |
| 41 | + def test_fit_build_not_implemented(self): |
| 42 | + with pytest.raises( |
| 43 | + NotImplementedError, match="This method must be implemented by a subclass" |
| 44 | + ): |
| 45 | + ModelBuilder().fit(X=np.ones(2), y=np.ones(3), coords={"a": 1}) |
| 46 | + |
| 47 | + @pytest.mark.parametrize( |
| 48 | + argnames="coords", |
| 49 | + argvalues=[None, {"a": 1}], |
| 50 | + ids=["None-coords", "dict-coords"], |
| 51 | + ) |
| 52 | + def test_fit_predict(self, coords, rng) -> None: |
| 53 | + X = rng.normal(loc=0, scale=1, size=(20, 2)) |
| 54 | + y = rng.normal(loc=0, scale=1, size=(20,)) |
| 55 | + model = MyToyModel(sample_kwargs={"chains": 2, "draws": 2}) |
| 56 | + model.fit(X, y, coords=coords) |
| 57 | + predictions = model.predict(X=X) |
| 58 | + score = model.score(X=X, y=y) |
| 59 | + assert isinstance(model.idata, az.InferenceData) |
| 60 | + assert az.extract(data=model.idata, var_names=["beta"]).shape == (2, 2 * 2) |
| 61 | + assert az.extract(data=model.idata, var_names=["sigma"]).shape == (2 * 2,) |
| 62 | + assert az.extract(data=model.idata, var_names=["mu"]).shape == (20, 2 * 2) |
| 63 | + assert az.extract( |
| 64 | + data=model.idata, group="posterior_predictive", var_names=["y_hat"] |
| 65 | + ).shape == (20, 2 * 2) |
| 66 | + assert isinstance(score, pd.Series) |
| 67 | + assert score.shape == (2,) |
| 68 | + assert isinstance(predictions, az.InferenceData) |
0 commit comments