Skip to content
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

Fix _create_synth_dataset when MMM has no controls #1513

Merged
merged 3 commits into from
Feb 19, 2025
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
18 changes: 16 additions & 2 deletions pymc_marketing/mmm/mmm.py
Original file line number Diff line number Diff line change
Expand Up @@ -2162,10 +2162,24 @@
"Unsupported time granularity. Choose from 'daily', 'weekly', 'monthly', 'quarterly', 'yearly'."
)

if controls is not None:
mmm_has_controls = (
self.control_columns is not None
and len(self.control_columns) > 0
and all(
column in self.preprocessed_data["X"].columns
for column in self.control_columns
)
)

if controls is not None and mmm_has_controls:
_controls: list[str] = controls
elif controls is not None and not mmm_has_controls:
raise ValueError(

Check warning on line 2177 in pymc_marketing/mmm/mmm.py

View check run for this annotation

Codecov / codecov/patch

pymc_marketing/mmm/mmm.py#L2177

Added line #L2177 was not covered by tests
"""The model was built without controls and cannot translate the provided controls to contributions.
Remove the controls from the function call and try again."""
)
else:
controls = []
_controls = []

last_date = pd.to_datetime(df[date_column]).max()
new_dates = []
Expand Down
98 changes: 98 additions & 0 deletions tests/mmm/test_mmm.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,16 @@ def mmm() -> MMM:
)


@pytest.fixture(scope="module")
def mmm_no_controls() -> MMM:
return MMM(
date_column="date",
channel_columns=["channel_1", "channel_2"],
adstock=GeometricAdstock(l_max=4),
saturation=LogisticSaturation(),
)


@pytest.fixture(scope="module")
def mmm_with_fourier_features() -> MMM:
return MMM(
Expand All @@ -139,6 +149,17 @@ def mmm_fitted(
return mmm


@pytest.fixture(scope="module")
def mmm_fitted_no_controls(
mmm_no_controls: MMM,
toy_X: pd.DataFrame,
toy_y: pd.Series,
mock_pymc_sample,
) -> MMM:
mmm_no_controls.fit(X=toy_X, y=toy_y)
return mmm_no_controls


@pytest.fixture(scope="module")
def mmm_fitted_with_posterior_predictive(
mmm_fitted: MMM,
Expand Down Expand Up @@ -1601,3 +1622,80 @@ def test_create_synth_dataset(
# Check target variable exists and has reasonable values
assert "y" in synth_df.columns
assert not synth_df["y"].isna().any()


@pytest.mark.parametrize(
argnames="noise_level", argvalues=[0.01, 0.05], ids=["low_noise", "high_noise"]
)
@pytest.mark.parametrize(
argnames="granularity",
argvalues=["weekly", "monthly", "quarterly", "yearly"],
ids=["weekly", "monthly", "quarterly", "yearly"],
)
@pytest.mark.parametrize(
argnames="time_length",
argvalues=[8, 12, 16, 20],
ids=["time_length_8", "time_length_12", "time_length_16", "time_length_20"],
)
@pytest.mark.parametrize(
argnames="lag", argvalues=[2, 4, 6, 8], ids=["lag_2", "lag_4", "lag_6", "lag_8"]
)
def test_create_synth_dataset_no_controls(
mmm_fitted_no_controls: MMM,
toy_X: pd.DataFrame,
noise_level: float,
granularity: str,
time_length: int,
lag: int,
) -> None:
"""Test the _create_synth_dataset method of MMM class."""

# Create a simple allocation strategy
channels = mmm_fitted_no_controls.channel_columns
allocation_strategy = xr.DataArray(
data=np.ones(len(channels)),
dims=["channel"],
coords={"channel": channels},
)

# Generate synthetic dataset
synth_df = mmm_fitted_no_controls._create_synth_dataset(
df=toy_X,
date_column=mmm_fitted_no_controls.date_column,
channels=mmm_fitted_no_controls.channel_columns,
controls=mmm_fitted_no_controls.control_columns,
target_col="y",
allocation_strategy=allocation_strategy,
time_granularity=granularity,
time_length=time_length,
lag=lag,
noise_level=noise_level,
)

# Test output properties
assert isinstance(synth_df, pd.DataFrame)
assert len(synth_df) == time_length

# Check required columns exist
required_columns = {
mmm_fitted_no_controls.date_column,
*mmm_fitted_no_controls.channel_columns,
"y",
}
if mmm_fitted_no_controls.control_columns:
required_columns.update(mmm_fitted_no_controls.control_columns)
assert all(col in synth_df.columns for col in required_columns)

# Check date properties
assert pd.api.types.is_datetime64_any_dtype(
synth_df[mmm_fitted_no_controls.date_column]
)
assert len(synth_df[mmm_fitted_no_controls.date_column].unique()) == time_length

# Check channel values are non-negative (since they represent spend)
for channel in mmm_fitted_no_controls.channel_columns:
assert (synth_df[channel] >= 0).all()

# Check target variable exists and has reasonable values
assert "y" in synth_df.columns
assert not synth_df["y"].isna().any()