-
Notifications
You must be signed in to change notification settings - Fork 317
Pydantic MuEffect
#1922
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
Draft
PabloRoque
wants to merge
5
commits into
pymc-labs:main
Choose a base branch
from
PabloRoque:pydantic-mueffects
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Pydantic MuEffect
#1922
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
2d2c311
Enforce MuEffect as pydantic subclass to support serialization/deseri…
PabloRoque fe2eba1
Update test_fourier_multidimensional to comply with the new pydantic …
PabloRoque 520db58
Improve tests to comply with new interface
PabloRoque 0dd6ddc
Merge branch 'main' into pydantic-mueffects
cetagostini e5823da
Merge branch 'main' into pydantic-mueffects
TeemuSailynoja File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -104,12 +104,13 @@ def set_data(self, mmm, model, X): | |
- In `set_data`, update the data variables when dates/dims change. | ||
""" | ||
|
||
from typing import Any, Protocol | ||
from abc import ABC, abstractmethod | ||
from typing import Annotated, Any, Protocol | ||
|
||
import pandas as pd | ||
import pymc as pm | ||
import xarray as xr | ||
from pydantic import BaseModel, InstanceOf | ||
from pydantic import BaseModel, Field, InstanceOf, PlainValidator, WithJsonSchema | ||
from pymc_extras.prior import create_dim_handler | ||
from pytensor import tensor as pt | ||
|
||
|
@@ -131,35 +132,31 @@ def model(self) -> pm.Model: | |
"""The PyMC model.""" | ||
|
||
|
||
class MuEffect(Protocol): | ||
"""Protocol for arbitrary additive mu effect.""" | ||
class MuEffect(ABC, BaseModel): | ||
"""Abstract base class for arbitrary additive mu effects. | ||
|
||
All mu_effects must inherit from this Pydantic BaseModel to ensure proper | ||
serialization and deserialization when saving/loading MMM models. | ||
""" | ||
|
||
@abstractmethod | ||
def create_data(self, mmm: Model) -> None: | ||
"""Create the required data in the model.""" | ||
|
||
@abstractmethod | ||
def create_effect(self, mmm: Model) -> pt.TensorVariable: | ||
"""Create the additive effect in the model.""" | ||
|
||
@abstractmethod | ||
def set_data(self, mmm: Model, model: pm.Model, X: xr.Dataset) -> None: | ||
"""Set the data for new predictions.""" | ||
|
||
|
||
class FourierEffect: | ||
class FourierEffect(MuEffect): | ||
"""Fourier seasonality additive effect for MMM.""" | ||
|
||
def __init__(self, fourier: FourierBase, date_dim_name: str = "date"): | ||
"""Initialize the Fourier effect. | ||
|
||
Parameters | ||
---------- | ||
fourier : FourierBase | ||
The FourierBase instance to use for the effect. | ||
date_dim_name : str, optional | ||
The name of the date dimension in the model, by default "date". | ||
|
||
""" | ||
self.fourier = fourier | ||
self.date_dim_name: str = date_dim_name | ||
fourier: InstanceOf[FourierBase] | ||
date_dim_name: str = Field("date") | ||
|
||
def create_data(self, mmm: Model) -> None: | ||
"""Create the required data in the model. | ||
|
@@ -256,7 +253,14 @@ def set_data(self, mmm: Model, model: pm.Model, X: xr.Dataset) -> None: | |
pm.set_data(new_data=new_data, model=model) | ||
|
||
|
||
class LinearTrendEffect: | ||
_Timestamp = Annotated[ | ||
pd.Timestamp, | ||
PlainValidator(lambda x: pd.Timestamp(x)), | ||
WithJsonSchema({"type": "date-time"}), | ||
] | ||
|
||
|
||
class LinearTrendEffect(MuEffect): | ||
"""Wrapper for LinearTrend to use with MMM's MuEffect protocol. | ||
|
||
This class adapts the LinearTrend component to be used as an additive effect | ||
|
@@ -268,6 +272,8 @@ class LinearTrendEffect: | |
The LinearTrend instance to wrap. | ||
prefix : str | ||
The prefix to use for variables in the model. | ||
date_dim_name : str | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same |
||
The name of the date dimension in the model. | ||
|
||
Examples | ||
-------- | ||
|
@@ -357,11 +363,10 @@ class MockMMM: | |
|
||
""" | ||
|
||
def __init__(self, trend: LinearTrend, prefix: str, date_dim_name: str = "date"): | ||
self.trend = trend | ||
self.prefix = prefix | ||
self.linear_trend_first_date: pd.Timestamp | ||
self.date_dim_name: str = date_dim_name | ||
trend: InstanceOf[LinearTrend] | ||
prefix: str | ||
date_dim_name: str = Field("date") | ||
linear_trend_first_date: _Timestamp | None = Field(None, init=False) | ||
|
||
def create_data(self, mmm: Model) -> None: | ||
"""Create the required data in the model. | ||
|
@@ -439,7 +444,7 @@ def set_data(self, mmm: Model, model: pm.Model, X: xr.Dataset) -> None: | |
pm.set_data({f"{self.prefix}_t": t}, model=model) | ||
|
||
|
||
class EventAdditiveEffect(BaseModel): | ||
class EventAdditiveEffect(MuEffect): | ||
"""Event effect class for the MMM. | ||
|
||
Parameters | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we need to supply the
date_dim_name
here, as the mutltidimensional MMM has thedate_column
attribute?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yes, because
MuEffect
is just an interface that has nothing to do with an MMM class.So either we have this explicit
date_dim_name
or we need to introduce coupling with the MMM class.