-
Notifications
You must be signed in to change notification settings - Fork 262
/
Copy pathtest_mmm.py
1714 lines (1497 loc) · 54.9 KB
/
test_mmm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2022 - 2025 The PyMC Labs Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import arviz as az
import numpy as np
import pandas as pd
import pymc as pm
import pytest
import xarray as xr
from matplotlib import pyplot as plt
from pymc_marketing.mmm.budget_optimizer import optimizer_xarray_builder
from pymc_marketing.mmm.components.adstock import DelayedAdstock, GeometricAdstock
from pymc_marketing.mmm.components.saturation import (
LogisticSaturation,
MichaelisMentenSaturation,
SaturationTransformation,
)
from pymc_marketing.mmm.mmm import MMM, BaseMMM
from pymc_marketing.model_builder import DifferentModelError
from pymc_marketing.prior import Prior
seed: int = sum(map(ord, "pymc_marketing"))
rng: np.random.Generator = np.random.default_rng(seed=seed)
@pytest.fixture(scope="module")
def generate_data():
def _generate_data(date_data: pd.DatetimeIndex) -> pd.DataFrame:
n: int = date_data.size
return pd.DataFrame(
data={
"date": date_data,
"channel_1": rng.integers(low=0, high=400, size=n),
"channel_2": rng.integers(low=0, high=50, size=n),
"control_1": rng.gamma(shape=1000, scale=500, size=n),
"control_2": rng.gamma(shape=100, scale=5, size=n),
"other_column_1": rng.integers(low=0, high=100, size=n),
"other_column_2": rng.normal(loc=0, scale=1, size=n),
}
)
return _generate_data
@pytest.fixture(scope="module")
def toy_X(generate_data) -> pd.DataFrame:
date_data: pd.DatetimeIndex = pd.date_range(
start="2019-06-01", end="2021-12-31", freq="W-MON"
)
return generate_data(date_data)
@pytest.fixture(scope="module")
def toy_X_with_bad_dates() -> pd.DataFrame:
bad_date_data = ["a", "b", "c", "d", "e"]
n: int = len(bad_date_data)
return pd.DataFrame(
data={
"date": bad_date_data,
"channel_1": rng.integers(low=0, high=400, size=n),
"channel_2": rng.integers(low=0, high=50, size=n),
"control_1": rng.gamma(shape=1000, scale=500, size=n),
"control_2": rng.gamma(shape=100, scale=5, size=n),
"other_column_1": rng.integers(low=0, high=100, size=n),
"other_column_2": rng.normal(loc=0, scale=1, size=n),
}
)
@pytest.fixture(scope="class")
def model_config_requiring_serialization() -> dict:
model_config = {
"intercept": Prior("Normal", mu=0, sigma=2),
"saturation_beta": Prior("HalfNormal", sigma=np.array([0.4533017, 0.25488063])),
"adstock_alpha": Prior(
"Beta", alpha=np.array([3, 3]), beta=np.array([3.55001301, 2.87092431])
),
"saturation_lam": Prior(
"Gamma", alpha=np.array([3, 3]), beta=np.array([4.12231653, 5.02896872])
),
"likelihood": Prior("Normal", sigma=Prior("HalfNormal", sigma=2)),
"gamma_control": Prior("HalfNormal", sigma=2),
"gamma_fourier": Prior("HalfNormal"),
}
return model_config
@pytest.fixture(scope="module")
def toy_y(toy_X: pd.DataFrame) -> pd.Series:
return pd.Series(data=rng.integers(low=0, high=100, size=toy_X.shape[0]))
@pytest.fixture(scope="module")
def mmm() -> MMM:
return MMM(
date_column="date",
channel_columns=["channel_1", "channel_2"],
control_columns=["control_1", "control_2"],
adstock=GeometricAdstock(l_max=4),
saturation=LogisticSaturation(),
)
@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(
date_column="date",
channel_columns=["channel_1", "channel_2"],
control_columns=["control_1", "control_2"],
adstock=GeometricAdstock(l_max=4),
saturation=LogisticSaturation(),
yearly_seasonality=2,
)
@pytest.fixture(scope="module")
def mmm_fitted(
mmm: MMM,
toy_X: pd.DataFrame,
toy_y: pd.Series,
mock_pymc_sample,
) -> MMM:
mmm.fit(X=toy_X, y=toy_y)
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,
toy_X: pd.DataFrame,
) -> MMM:
_ = mmm_fitted.sample_posterior_predictive(toy_X, extend_idata=True, combined=True)
return mmm_fitted
@pytest.fixture(scope="module")
def mmm_fitted_with_prior_and_posterior_predictive(
mmm_fitted_with_posterior_predictive,
toy_X,
):
_ = mmm_fitted_with_posterior_predictive.sample_prior_predictive(toy_X)
return mmm_fitted_with_posterior_predictive
@pytest.fixture(scope="module")
def mmm_fitted_with_fourier_features(
mmm_with_fourier_features: MMM,
toy_X: pd.DataFrame,
toy_y: pd.Series,
mock_pymc_sample,
) -> MMM:
mmm_with_fourier_features.fit(X=toy_X, y=toy_y)
return mmm_with_fourier_features
@pytest.mark.parametrize("media_transform", ["adstock", "saturation"])
def test_plotting_media_transform_workflow(mmm_fitted, media_transform) -> None:
transform = getattr(mmm_fitted, media_transform)
curve = transform.sample_curve(mmm_fitted.fit_result)
fig, axes = transform.plot_curve(curve)
assert isinstance(fig, plt.Figure)
assert len(axes) == mmm_fitted.fit_result["channel"].size
plt.close()
class TestMMM:
def test_save_load_with_not_serializable_model_config(
self,
model_config_requiring_serialization,
toy_X,
toy_y,
mock_pymc_sample,
):
def deep_equal(dict1, dict2):
for key, value in dict1.items():
if key not in dict2:
return False
if isinstance(value, dict):
if not deep_equal(value, dict2[key]):
return False
elif isinstance(value, np.ndarray):
if not np.array_equal(value, dict2[key]):
return False
else:
if value != dict2[key]:
return False
return True
l_max = 4
adstock = GeometricAdstock(l_max=l_max)
saturation = LogisticSaturation()
model = MMM(
date_column="date",
channel_columns=["channel_1", "channel_2"],
model_config=model_config_requiring_serialization,
adstock=adstock,
saturation=saturation,
)
model.fit(toy_X, toy_y)
model.save("test_save_load")
model2 = MMM.load("test_save_load")
assert model.date_column == model2.date_column
assert model.control_columns == model2.control_columns
assert model.channel_columns == model2.channel_columns
assert model.adstock.l_max == model2.adstock.l_max
assert model.validate_data == model2.validate_data
assert model.yearly_seasonality == model2.yearly_seasonality
assert deep_equal(model.model_config, model2.model_config)
assert model.sampler_config == model2.sampler_config
os.remove("test_save_load")
def test_bad_date_column(self, toy_X_with_bad_dates) -> None:
with pytest.raises(
ValueError,
match="Could not convert bad_date_column to datetime. Please check the date format.",
):
my_mmm = MMM(
date_column="bad_date_column",
channel_columns=["channel_1", "channel_2"],
adstock=GeometricAdstock(l_max=4),
saturation=LogisticSaturation(),
control_columns=["control_1", "control_2"],
)
y = np.ones(toy_X_with_bad_dates.shape[0])
my_mmm.build_model(X=toy_X_with_bad_dates, y=y)
@pytest.mark.parametrize(
argnames="adstock_max_lag",
argvalues=[1, 4],
ids=["adstock_max_lag=1", "adstock_max_lag=4"],
)
@pytest.mark.parametrize(
argnames="control_columns",
argvalues=[None, ["control_1"], ["control_1", "control_2"]],
ids=["no_control", "one_control", "two_controls"],
)
@pytest.mark.parametrize(
argnames="channel_columns",
argvalues=[
(["channel_1"]),
(["channel_1", "channel_2"]),
],
ids=[
"single_channel",
"multiple_channel",
],
)
@pytest.mark.parametrize(
argnames="yearly_seasonality",
argvalues=[None, 2],
ids=["no_yearly_seasonality", "yearly_seasonality"],
)
@pytest.mark.parametrize(
argnames="time_varying_intercept",
argvalues=[False, True],
ids=["no_time_varying_intercept", "time_varying_intercept"],
)
@pytest.mark.parametrize(
argnames="time_varying_media",
argvalues=[False, True],
ids=["no_time_varying_media", "time_varying_media"],
)
def test_init(
self,
toy_X: pd.DataFrame,
toy_y: pd.Series,
yearly_seasonality: int | None,
channel_columns: list[str],
control_columns: list[str],
adstock_max_lag: int,
time_varying_intercept: bool,
time_varying_media: bool,
) -> None:
mmm = BaseMMM(
date_column="date",
channel_columns=channel_columns,
control_columns=control_columns,
yearly_seasonality=yearly_seasonality,
time_varying_intercept=time_varying_intercept,
time_varying_media=time_varying_media,
adstock=GeometricAdstock(l_max=adstock_max_lag),
saturation=LogisticSaturation(),
)
mmm.build_model(X=toy_X, y=toy_y)
n_channel: int = len(mmm.channel_columns)
samples: int = 3
with mmm.model:
prior_predictive: az.InferenceData = pm.sample_prior_predictive(
draws=samples, random_seed=rng
)
assert az.extract(
prior_predictive, group="prior", var_names=["intercept"], combined=True
).to_numpy().shape == (
(samples,) if not time_varying_intercept else (toy_X.shape[0], samples)
)
assert az.extract(
data=prior_predictive,
group="prior",
var_names=["saturation_beta"],
combined=True,
).to_numpy().shape == (
n_channel,
samples,
)
assert az.extract(
data=prior_predictive,
group="prior",
var_names=["adstock_alpha"],
combined=True,
).to_numpy().shape == (
n_channel,
samples,
)
assert az.extract(
data=prior_predictive,
group="prior",
var_names=["saturation_lam"],
combined=True,
).to_numpy().shape == (
n_channel,
samples,
)
if control_columns is not None:
n_control = len(control_columns)
assert az.extract(
data=prior_predictive,
group="prior",
var_names=["gamma_control"],
combined=True,
).to_numpy().shape == (
n_control,
samples,
)
if yearly_seasonality is not None:
assert az.extract(
data=prior_predictive,
group="prior",
var_names=["gamma_fourier"],
combined=True,
).to_numpy().shape == (
2 * yearly_seasonality,
samples,
)
def test_fit(self, toy_X: pd.DataFrame, toy_y: pd.Series, mock_pymc_sample) -> None:
mmm = BaseMMM(
date_column="date",
channel_columns=["channel_1", "channel_2"],
control_columns=["control_1", "control_2"],
yearly_seasonality=2,
adstock=GeometricAdstock(l_max=2),
saturation=LogisticSaturation(),
)
assert mmm.version == "0.0.3"
assert mmm._model_type == "BaseValidateMMM"
assert mmm._model_name == "BaseMMM"
assert mmm.model_config is not None
n_channel: int = len(mmm.channel_columns)
n_control: int = len(mmm.control_columns)
mmm.fit(X=toy_X, y=toy_y)
posterior: az.InferenceData = mmm.fit_result
chains = posterior.sizes["chain"]
draws = posterior.sizes["draw"]
assert (
az.extract(data=posterior, var_names=["intercept"], combined=True)
.to_numpy()
.size
== draws * chains
)
assert az.extract(
data=posterior, var_names=["saturation_beta"], combined=True
).to_numpy().shape == (n_channel, draws * chains)
assert az.extract(
data=posterior, var_names=["adstock_alpha"], combined=True
).to_numpy().shape == (n_channel, draws * chains)
assert az.extract(
data=posterior, var_names=["saturation_lam"], combined=True
).to_numpy().shape == (n_channel, draws * chains)
assert az.extract(
data=posterior, var_names=["gamma_control"], combined=True
).to_numpy().shape == (
n_channel,
draws * chains,
)
mean_model_contributions_ts = mmm.compute_mean_contributions_over_time(
original_scale=True
)
assert mean_model_contributions_ts.shape == (
toy_X.shape[0],
n_channel
+ n_control
+ 2, # 2 for yearly seasonality (+1) and intercept (+)
)
processed_df = mmm._process_decomposition_components(
data=mean_model_contributions_ts
)
assert processed_df.shape == (n_channel + n_control + 2, 3)
assert mean_model_contributions_ts.columns.tolist() == [
"channel_1",
"channel_2",
"control_1",
"control_2",
"yearly_seasonality",
"intercept",
]
def test_mmm_serializes_and_deserializes_dag_and_nodes(
self,
toy_X: pd.DataFrame,
toy_y: pd.Series,
mock_pymc_sample,
) -> None:
dag = """
digraph {
channel_1 -> y;
control_1 -> channel_1;
control_1 -> y;
}
"""
treatment_nodes = ["channel_1"]
outcome_node = "y"
mmm = MMM(
date_column="date",
channel_columns=["channel_1", "channel_2"],
control_columns=["control_1", "control_2"],
adstock=GeometricAdstock(l_max=4),
saturation=LogisticSaturation(),
dag=dag,
treatment_nodes=treatment_nodes,
outcome_node=outcome_node,
)
mmm.fit(X=toy_X, y=toy_y)
# Save and reload the model
mmm.save("test_model")
loaded_mmm = MMM.load("test_model")
# Assert that the attributes persist
assert loaded_mmm.dag == dag, "DAG did not persist correctly."
assert loaded_mmm.treatment_nodes == treatment_nodes, (
"Treatment nodes did not persist correctly."
)
assert loaded_mmm.outcome_node == outcome_node, (
"Outcome node did not persist correctly."
)
# Clean up
os.remove("test_model")
def test_channel_contributions_forward_pass_recovers_contribution(
self,
mmm_fitted: MMM,
) -> None:
channel_data = mmm_fitted.preprocessed_data["X"][
mmm_fitted.channel_columns
].to_numpy()
channel_contributions_forward_pass = (
mmm_fitted.channel_contributions_forward_pass(channel_data=channel_data)
)
channel_contributions_forward_pass_mean = (
channel_contributions_forward_pass.mean(axis=(0, 1))
)
channel_contributions_mean = mmm_fitted.fit_result[
"channel_contributions"
].mean(dim=["draw", "chain"])
assert (
channel_contributions_forward_pass_mean.shape
== channel_contributions_mean.shape
)
# The forward pass results should be in the original scale of the target variable.
# The trace fits the model with scaled data, so when scaling back, they should match.
# Since we are using a `MaxAbsScaler`, the scaling factor is the maximum absolute, i.e y.max()
np.testing.assert_array_almost_equal(
x=channel_contributions_forward_pass_mean / channel_contributions_mean,
y=mmm_fitted.y.max(),
)
def test_allocate_budget_to_maximize_response(self, mmm_fitted: MMM) -> None:
budget = 2.0
num_periods = 8
time_granularity = "weekly"
budget_bounds = optimizer_xarray_builder(
value=[[0.5, 1.2], [0.5, 1.5]],
channel=["channel_1", "channel_2"],
bound=["lower", "upper"],
)
noise_level = 0.1
# Call the method
inference_data = mmm_fitted.allocate_budget_to_maximize_response(
budget=budget,
time_granularity=time_granularity,
num_periods=num_periods,
budget_bounds=budget_bounds,
noise_level=noise_level,
custom_constraints=(),
)
inference_periods = len(inference_data.coords["date"])
# a) Total budget consistency check
allocated_budget = mmm_fitted.optimal_allocation.sum()
assert np.isclose(allocated_budget, budget, rtol=1e-5), (
f"Total allocated budget {allocated_budget} does not match expected budget {budget}"
)
# b) Budget boundaries check
allocation = mmm_fitted.optimal_allocation
lower_bounds = budget_bounds.sel(bound="lower")
upper_bounds = budget_bounds.sel(bound="upper")
assert (allocation >= lower_bounds).all() and (
allocation <= upper_bounds
).all(), (
f"Allocations {allocation.values} are out of bounds ({lower_bounds.values}, {upper_bounds.values})"
)
# c) num_periods consistency check
assert inference_periods == num_periods, (
f"Number of periods in the data {inference_periods} does not match the expected {num_periods}"
)
def test_allocate_budget_to_maximize_response_bad_noise_level(
self, mmm_fitted: MMM
) -> None:
budget = 2.0
num_periods = 8
budget_bounds = optimizer_xarray_builder(
value=[[0.5, 1.2], [0.5, 1.5]],
channel=["channel_1", "channel_2"],
bound=["lower", "upper"],
)
with pytest.raises(ValueError, match="noise_level must be a float"):
mmm_fitted.optimize_budget(
budget=budget,
num_periods=num_periods,
budget_bounds=budget_bounds,
)
@pytest.mark.parametrize(
argnames="original_scale",
argvalues=[False, True],
ids=["scaled", "original-scale"],
)
@pytest.mark.parametrize(
argnames="var_contribution",
argvalues=["channel_contributions", "control_contributions"],
ids=["channel_contribution", "control_contribution"],
)
def test_get_ts_contribution_posterior(
self,
mmm_fitted_with_posterior_predictive: MMM,
var_contribution: str,
original_scale: bool,
):
ts_posterior = (
mmm_fitted_with_posterior_predictive.get_ts_contribution_posterior(
var_contribution=var_contribution, original_scale=original_scale
)
)
chains = ts_posterior.sizes["chain"]
draws = ts_posterior.sizes["draw"]
assert ts_posterior.dims == ("chain", "draw", "date")
assert ts_posterior.chain.size == chains
assert ts_posterior.draw.size == draws
@pytest.mark.parametrize(
argnames="original_scale",
argvalues=[False, True],
ids=["scaled", "original-scale"],
)
def test_get_errors(
self,
mmm_fitted_with_posterior_predictive: MMM,
original_scale: bool,
) -> None:
errors = mmm_fitted_with_posterior_predictive.get_errors(
original_scale=original_scale
)
n_chains = errors.sizes["chain"]
n_draws = errors.sizes["draw"]
assert isinstance(errors, xr.DataArray)
assert errors.name == "errors"
assert errors.shape == (
n_chains,
n_draws,
mmm_fitted_with_posterior_predictive.y.shape[0],
)
def test_get_errors_raises_not_fitted(self) -> None:
my_mmm = MMM(
date_column="date",
channel_columns=["channel_1", "channel_2"],
control_columns=["control_1", "control_2"],
adstock=GeometricAdstock(l_max=4),
saturation=LogisticSaturation(),
)
with pytest.raises(
RuntimeError,
match="Make sure the model has been fitted and the posterior_predictive has been sampled!",
):
my_mmm.get_errors()
def test_posterior_predictive_raises_not_fitted(self) -> None:
my_mmm = MMM(
date_column="date",
channel_columns=["channel_1", "channel_2"],
control_columns=["control_1", "control_2"],
adstock=GeometricAdstock(l_max=4),
saturation=LogisticSaturation(),
)
with pytest.raises(
RuntimeError,
match="Make sure the model has been fitted and the posterior_predictive has been sampled!",
):
my_mmm.plot_posterior_predictive()
def test_get_errors_bad_y_length(
self,
mmm_fitted_with_posterior_predictive: MMM,
):
mmm_fitted_with_posterior_predictive.y = np.array([1, 2])
with pytest.raises(ValueError):
mmm_fitted_with_posterior_predictive.get_errors()
def test_plot_posterior_predictive_bad_y_length(
self,
mmm_fitted_with_posterior_predictive: MMM,
):
mmm_fitted_with_posterior_predictive.y = np.array([1, 2])
with pytest.raises(ValueError):
mmm_fitted_with_posterior_predictive.plot_posterior_predictive()
def test_channel_contributions_forward_pass_is_consistent(
self, mmm_fitted: MMM
) -> None:
channel_data = mmm_fitted.preprocessed_data["X"][
mmm_fitted.channel_columns
].to_numpy()
channel_contributions_forward_pass = (
mmm_fitted.channel_contributions_forward_pass(channel_data=channel_data)
)
# use a grid [0, 1, 2] which corresponds to
# - no-spend -> forward pass should be zero
# - spend input for the model -> should match the forward pass
# - doubling the spend -> should be higher than the forward pass with the original spend
channel_contributions_forward_pass_grid = (
mmm_fitted.get_channel_contributions_forward_pass_grid(
start=0, stop=2, num=3
)
)
assert channel_contributions_forward_pass_grid[0].sum().item() == 0
np.testing.assert_equal(
actual=channel_contributions_forward_pass,
desired=channel_contributions_forward_pass_grid[1].to_numpy(),
)
assert (
channel_contributions_forward_pass_grid[2].to_numpy()
>= channel_contributions_forward_pass
).all()
def test_get_channel_contributions_forward_pass_grid_shapes(
self, mmm_fitted: MMM
) -> None:
n_channels = len(mmm_fitted.channel_columns)
data_range = mmm_fitted.X.shape[0]
grid_size = 2
contributions = mmm_fitted.get_channel_contributions_forward_pass_grid(
start=0, stop=1.5, num=grid_size
)
draws = contributions.sizes["draw"]
chains = contributions.sizes["chain"]
assert contributions.shape == (
grid_size,
chains,
draws,
data_range,
n_channels,
)
def test_bad_start_get_channel_contributions_forward_pass_grid(
self,
mmm_fitted: MMM,
) -> None:
with pytest.raises(
expected_exception=ValueError,
match="start must be greater than or equal to 0.",
):
mmm_fitted.get_channel_contributions_forward_pass_grid(
start=-0.5, stop=1.5, num=2
)
@pytest.mark.parametrize(
argnames="absolute_xrange",
argvalues=[False, True],
ids=["relative_xrange", "absolute_xrange"],
)
def test_plot_channel_contributions_grid(
self, mmm_fitted: MMM, absolute_xrange: bool
) -> None:
fig = mmm_fitted.plot_channel_contributions_grid(
start=0, stop=1.5, num=2, absolute_xrange=absolute_xrange
)
assert isinstance(fig, plt.Figure)
@pytest.mark.parametrize(
argnames="group",
argvalues=["prior_predictive", "posterior_predictive"],
ids=["prior_predictive", "posterior_predictive"],
)
@pytest.mark.parametrize(
argnames="original_scale",
argvalues=[False, True],
ids=["scaled", "original-scale"],
)
def test_get_group_predictive_data(
self,
mmm_fitted_with_prior_and_posterior_predictive: MMM,
group: str,
original_scale: bool,
):
dataset = (
mmm_fitted_with_prior_and_posterior_predictive._get_group_predictive_data(
group=group,
original_scale=original_scale,
)
)
assert isinstance(dataset, xr.Dataset)
assert dataset.dims["date"] == 135
assert dataset["y"].dims == ("chain", "draw", "date")
def test_data_setter(self, toy_X, toy_y, mock_pymc_sample):
base_delayed_saturated_mmm = BaseMMM(
date_column="date",
channel_columns=["channel_1", "channel_2"],
adstock=GeometricAdstock(l_max=4),
saturation=LogisticSaturation(),
)
base_delayed_saturated_mmm.fit(X=toy_X, y=toy_y)
X_correct_ndarray = np.random.randint(low=0, high=100, size=(135, 2))
y_correct_ndarray = np.random.randint(low=0, high=100, size=135)
X_incorrect = "Incorrect data"
y_incorrect = "Incorrect data"
with pytest.raises(TypeError):
base_delayed_saturated_mmm._data_setter(X_incorrect, toy_y)
with pytest.raises(TypeError):
base_delayed_saturated_mmm._data_setter(toy_X, y_incorrect)
with pytest.raises(KeyError):
X_wrong_df = pd.DataFrame(
{"column1": np.random.rand(135), "column2": np.random.rand(135)}
)
base_delayed_saturated_mmm._data_setter(X_wrong_df, toy_y)
try:
base_delayed_saturated_mmm._data_setter(toy_X, toy_y)
except Exception as e:
pytest.fail(f"_data_setter failed with error {e}")
with pytest.raises(TypeError, match="X must be a pandas DataFrame"):
base_delayed_saturated_mmm._data_setter(
X_correct_ndarray, y_correct_ndarray
)
def test_save_load(self, mmm_fitted: MMM):
model = mmm_fitted
model.save("test_save_load")
model2 = MMM.load("test_save_load")
assert model.date_column == model2.date_column
assert model.control_columns == model2.control_columns
assert model.channel_columns == model2.channel_columns
assert model.adstock.l_max == model2.adstock.l_max
assert model.validate_data == model2.validate_data
assert model.yearly_seasonality == model2.yearly_seasonality
assert model.model_config == model2.model_config
assert model.sampler_config == model2.sampler_config
os.remove("test_save_load")
def test_fail_id_after_load(self, monkeypatch, toy_X, toy_y):
# This is the new behavior for the property
def mock_property(self):
return "for sure not correct id"
# Now create an instance of MyClass
DSMMM = MMM(
date_column="date",
channel_columns=["channel_1", "channel_2"],
adstock=GeometricAdstock(l_max=4),
saturation=LogisticSaturation(),
)
# Check that the property returns the new value
DSMMM.fit(toy_X, toy_y)
DSMMM.save("test_model")
# Apply the monkeypatch for the property
monkeypatch.setattr(MMM, "id", property(mock_property))
error_msg = (
"The file 'test_model' does not "
"contain an InferenceData of the "
"same model or configuration as 'MMM'"
)
with pytest.raises(DifferentModelError, match=error_msg):
MMM.load("test_model")
os.remove("test_model")
@pytest.mark.parametrize(
argnames="model_config",
argvalues=[
None,
{
"intercept": Prior("Normal", mu=0, sigma=2),
"saturation_beta": Prior(
"HalfNormal", sigma=np.array([0.4533017, 0.25488063])
),
"adstock_alpha": Prior(
"Beta",
alpha=np.array([3, 3]),
beta=np.array([3.55001301, 2.87092431]),
),
"saturation_lam": Prior(
"Gamma",
alpha=np.array([3, 3]),
beta=np.array([4.12231653, 5.02896872]),
),
"likelihood": Prior("StudentT", nu=3, sigma=2),
"gamma_control": Prior("Normal", sigma=2),
"gamma_fourier": Prior("Laplace", mu=0, b=1),
},
],
ids=["default_config", "custom_config"],
)
def test_model_config(
self, model_config: dict, toy_X: pd.DataFrame, toy_y: pd.Series
):
# Create model instance with specified config
model = MMM(
date_column="date",
channel_columns=["channel_1", "channel_2"],
yearly_seasonality=2,
model_config=model_config,
adstock=GeometricAdstock(l_max=2),
saturation=LogisticSaturation(),
)
model.build_model(X=toy_X, y=toy_y.to_numpy())
# Check for default configuration
if model_config is None:
# assert observed RV type, and priors of some/all free_RVs.
assert isinstance(
model.model.observed_RVs[0].owner.op, pm.Normal
) # likelihood
# Add more asserts as needed for default configuration
# Check for custom configuration
else:
# assert custom configuration is applied correctly
assert isinstance(
model.model.observed_RVs[0].owner.op, pm.StudentT
) # likelihood
assert isinstance(
model.model["saturation_beta"].owner.op, pm.HalfNormal
) # saturation_beta
def test_mmm_causal_attributes_initialization(self):
dag = """
digraph {
channel_1 -> y;
control_1 -> channel_1;
control_1 -> y;
}
"""
treatment_nodes = ["channel_1"]
outcome_node = "y"
mmm = MMM(
date_column="date",
channel_columns=["channel_1", "channel_2"],
control_columns=["control_1", "control_2"],
adstock=GeometricAdstock(l_max=2),
saturation=LogisticSaturation(),
dag=dag,
treatment_nodes=treatment_nodes,
outcome_node=outcome_node,
)
assert mmm.dag == dag, "DAG was not set correctly."
assert mmm.treatment_nodes == treatment_nodes, (
"Treatment nodes not set correctly."
)
assert mmm.outcome_node == outcome_node, "Outcome node not set correctly."
def test_mmm_causal_attributes_default_treatment_nodes(self):
dag = """
digraph {
channel_1 -> y;
channel_2 -> y;
control_1 -> channel_1;
control_1 -> channel_2;
control_1 -> y;
}
"""
outcome_node = "y"
with pytest.warns(
UserWarning,
match="No treatment nodes provided, using channel columns as treatment nodes.",
):
mmm = MMM(
date_column="date",
channel_columns=["channel_1", "channel_2"],
control_columns=["control_1", "control_2"],
adstock=GeometricAdstock(l_max=2),
saturation=LogisticSaturation(),
dag=dag,
outcome_node=outcome_node,
)
assert mmm.treatment_nodes == [
"channel_1",
"channel_2",
], "Default treatment nodes are incorrect."
assert mmm.outcome_node == "y", "Outcome node was not set correctly."
def test_mmm_adjustment_set_updates_control_columns(self):
dag = """
digraph {
channel_1 -> y;
control_1 -> channel_1;
control_1 -> y;
}
"""
treatment_nodes = ["channel_1"]
outcome_node = "y"
mmm = MMM(
date_column="date",
channel_columns=["channel_1", "channel_2"],
control_columns=["control_1", "control_2"],
adstock=GeometricAdstock(l_max=2),
saturation=LogisticSaturation(),
dag=dag,
treatment_nodes=treatment_nodes,
outcome_node=outcome_node,
)
assert mmm.control_columns == ["control_1"], (
"Control columns were not updated based on the DAG."