Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

test_main.py 31 KB

You have to be logged in to leave a comment. Sign In
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
  1. # MIT License
  2. #
  3. # Copyright (c) 2018 Dafiti OpenSource
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in all
  13. # copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. """
  23. Tests for module main.py. Fixtures comes from file conftest.py located at the same dir
  24. of this file.
  25. """
  26. import os
  27. import mock
  28. import numpy as np
  29. import pandas as pd
  30. import pytest
  31. from numpy.testing import assert_allclose, assert_array_equal
  32. from pandas.core.indexes.range import RangeIndex
  33. from pandas.util.testing import assert_frame_equal, assert_series_equal
  34. from statsmodels.tsa.statespace.structural import (UnobservedComponents,
  35. UnobservedComponentsResultsWrapper)
  36. from causalimpact import CausalImpact
  37. from causalimpact.misc import standardize
  38. def test_default_causal_cto(rand_data, pre_int_period, post_int_period):
  39. ci = CausalImpact(rand_data, pre_int_period, post_int_period)
  40. assert_frame_equal(ci.data, rand_data)
  41. assert ci.pre_period == pre_int_period
  42. assert ci.post_period == post_int_period
  43. pre_data = rand_data.loc[pre_int_period[0]: pre_int_period[1], :]
  44. assert_frame_equal(ci.pre_data, pre_data)
  45. post_data = rand_data.loc[post_int_period[0]: post_int_period[1], :]
  46. assert_frame_equal(ci.post_data, post_data)
  47. assert ci.alpha == 0.05
  48. normed_pre_data, (mu, sig) = standardize(pre_data)
  49. assert_frame_equal(ci.normed_pre_data, normed_pre_data)
  50. normed_post_data = (post_data - mu) / sig
  51. assert_frame_equal(ci.normed_post_data, normed_post_data)
  52. assert ci.mu_sig == (mu[0], sig[0])
  53. assert ci.model_args == {'standardize': True, 'nseasons': []}
  54. assert isinstance(ci.model, UnobservedComponents)
  55. assert_array_equal(ci.model.endog, normed_pre_data.iloc[:, 0].values.reshape(-1, 1))
  56. assert_array_equal(ci.model.exog, normed_pre_data.iloc[:, 1:].values.reshape(
  57. -1,
  58. rand_data.shape[1] - 1
  59. )
  60. )
  61. assert ci.model.endog_names == 'y'
  62. assert ci.model.exog_names == ['x1', 'x2']
  63. assert ci.model.k_endog == 1
  64. assert ci.model.level
  65. assert ci.model.trend_specification == 'local level'
  66. assert isinstance(ci.trained_model, UnobservedComponentsResultsWrapper)
  67. assert ci.trained_model.nobs == len(pre_data)
  68. assert ci.inferences is not None
  69. assert ci.p_value > 0 and ci.p_value < 1
  70. assert ci.n_sims == 1000
  71. def test_default_causal_cto_w_date(date_rand_data, pre_str_period, post_str_period):
  72. ci = CausalImpact(date_rand_data, pre_str_period, post_str_period)
  73. assert_frame_equal(ci.data, date_rand_data)
  74. assert ci.pre_period == pre_str_period
  75. assert ci.post_period == post_str_period
  76. pre_data = date_rand_data.loc[pre_str_period[0]: pre_str_period[1], :]
  77. assert_frame_equal(ci.pre_data, pre_data)
  78. post_data = date_rand_data.loc[post_str_period[0]: post_str_period[1], :]
  79. assert_frame_equal(ci.post_data, post_data)
  80. assert ci.alpha == 0.05
  81. normed_pre_data, (mu, sig) = standardize(pre_data)
  82. assert_frame_equal(ci.normed_pre_data, normed_pre_data)
  83. normed_post_data = (post_data - mu) / sig
  84. assert_frame_equal(ci.normed_post_data, normed_post_data)
  85. assert ci.mu_sig == (mu[0], sig[0])
  86. assert ci.model_args == {'standardize': True, 'nseasons': []}
  87. assert isinstance(ci.model, UnobservedComponents)
  88. assert_array_equal(ci.model.endog, normed_pre_data.iloc[:, 0].values.reshape(-1, 1))
  89. assert_array_equal(ci.model.exog, normed_pre_data.iloc[:, 1:].values.reshape(
  90. -1,
  91. date_rand_data.shape[1] - 1
  92. )
  93. )
  94. assert ci.model.endog_names == 'y'
  95. assert ci.model.exog_names == ['x1', 'x2']
  96. assert ci.model.k_endog == 1
  97. assert ci.model.level
  98. assert ci.model.trend_specification == 'local level'
  99. assert isinstance(ci.trained_model, UnobservedComponentsResultsWrapper)
  100. assert ci.trained_model.nobs == len(pre_data)
  101. assert ci.inferences is not None
  102. assert ci.p_value > 0 and ci.p_value < 1
  103. assert ci.n_sims == 1000
  104. def test_default_causal_cto_no_exog(rand_data, pre_int_period, post_int_period):
  105. rand_data = pd.DataFrame(rand_data.iloc[:, 0])
  106. ci = CausalImpact(rand_data, pre_int_period, post_int_period)
  107. assert_frame_equal(ci.data, rand_data)
  108. assert ci.pre_period == pre_int_period
  109. assert ci.post_period == post_int_period
  110. pre_data = rand_data.loc[pre_int_period[0]: pre_int_period[1], :]
  111. assert_frame_equal(ci.pre_data, pre_data)
  112. post_data = rand_data.loc[post_int_period[0]: post_int_period[1], :]
  113. assert_frame_equal(ci.post_data, post_data)
  114. assert ci.alpha == 0.05
  115. normed_pre_data, (mu, sig) = standardize(pre_data)
  116. assert_frame_equal(ci.normed_pre_data, normed_pre_data)
  117. normed_post_data = (post_data - mu) / sig
  118. assert_frame_equal(ci.normed_post_data, normed_post_data)
  119. assert ci.mu_sig == (mu[0], sig[0])
  120. assert ci.model_args == {'standardize': True, 'nseasons': []}
  121. assert isinstance(ci.model, UnobservedComponents)
  122. assert_array_equal(ci.model.endog, normed_pre_data.iloc[:, 0].values.reshape(-1, 1))
  123. assert ci.model.exog is None
  124. assert ci.model.endog_names == 'y'
  125. assert ci.model.exog_names is None
  126. assert ci.model.k_endog == 1
  127. assert ci.model.level
  128. assert ci.model.trend_specification == 'local level'
  129. assert isinstance(ci.trained_model, UnobservedComponentsResultsWrapper)
  130. assert ci.trained_model.nobs == len(pre_data)
  131. assert ci.inferences is not None
  132. assert ci.p_value > 0 and ci.p_value < 1
  133. assert ci.n_sims == 1000
  134. def test_default_causal_cto_w_np_array(rand_data, pre_int_period, post_int_period):
  135. data = rand_data.values
  136. ci = CausalImpact(data, pre_int_period, post_int_period)
  137. assert_array_equal(ci.data, data)
  138. assert ci.pre_period == pre_int_period
  139. assert ci.post_period == post_int_period
  140. pre_data = pd.DataFrame(data[pre_int_period[0]: pre_int_period[1] + 1, :])
  141. assert_frame_equal(ci.pre_data, pre_data)
  142. post_data = pd.DataFrame(data[post_int_period[0]: post_int_period[1] + 1, :])
  143. post_data.index = RangeIndex(start=len(pre_data), stop=len(rand_data))
  144. assert_frame_equal(ci.post_data, post_data)
  145. assert ci.alpha == 0.05
  146. normed_pre_data, (mu, sig) = standardize(pre_data)
  147. assert_frame_equal(ci.normed_pre_data, normed_pre_data)
  148. normed_post_data = (post_data - mu) / sig
  149. assert_frame_equal(ci.normed_post_data, normed_post_data)
  150. assert ci.mu_sig == (mu[0], sig[0])
  151. assert ci.model_args == {'standardize': True, 'nseasons': []}
  152. assert isinstance(ci.model, UnobservedComponents)
  153. assert_array_equal(ci.model.endog, normed_pre_data.iloc[:, 0].values.reshape(-1, 1))
  154. assert_array_equal(ci.model.exog, normed_pre_data.iloc[:, 1:].values.reshape(
  155. -1,
  156. data.shape[1] - 1
  157. )
  158. )
  159. assert ci.model.endog_names == 'y'
  160. assert ci.model.exog_names == [1, 2]
  161. assert ci.model.k_endog == 1
  162. assert ci.model.level
  163. assert ci.model.trend_specification == 'local level'
  164. assert isinstance(ci.trained_model, UnobservedComponentsResultsWrapper)
  165. assert ci.trained_model.nobs == len(pre_data)
  166. assert ci.inferences is not None
  167. assert ci.p_value > 0 and ci.p_value < 1
  168. assert ci.n_sims == 1000
  169. def test_causal_cto_w_no_standardization(rand_data, pre_int_period, post_int_period):
  170. ci = CausalImpact(rand_data, pre_int_period, post_int_period, standardize=False)
  171. pre_data = rand_data.loc[pre_int_period[0]: pre_int_period[1], :]
  172. post_data = rand_data.loc[post_int_period[0]: post_int_period[1], :]
  173. assert ci.normed_pre_data is None
  174. assert ci.normed_post_data is None
  175. assert ci.mu_sig is None
  176. assert_array_equal(ci.model.endog, pre_data.iloc[:, 0].values.reshape(-1, 1))
  177. assert_array_equal(ci.model.exog, pre_data.iloc[:, 1:].values.reshape(
  178. -1,
  179. rand_data.shape[1] - 1
  180. )
  181. )
  182. assert ci.p_value > 0 and ci.p_value < 1
  183. def test_causal_cto_w_seasons(date_rand_data, pre_str_period, post_str_period):
  184. ci = CausalImpact(date_rand_data, pre_str_period, post_str_period,
  185. nseasons=[{'period': 4}, {'period': 3}])
  186. assert ci.model.freq_seasonal_periods == [4, 3]
  187. assert ci.model.freq_seasonal_harmonics == [2, 1]
  188. ci = CausalImpact(date_rand_data, pre_str_period, post_str_period,
  189. nseasons=[{'period': 4, 'harmonics': 1},
  190. {'period': 3, 'harmonis': 1}])
  191. assert ci.model.freq_seasonal_periods == [4, 3]
  192. assert ci.model.freq_seasonal_harmonics == [1, 1]
  193. def test_causal_cto_w_custom_model_and_seasons(rand_data, pre_int_period,
  194. post_int_period):
  195. pre_data = rand_data.loc[pre_int_period[0]: pre_int_period[1], :]
  196. post_data = rand_data.loc[post_int_period[0]: post_int_period[1], :]
  197. model = UnobservedComponents(endog=pre_data.iloc[:, 0], level='llevel',
  198. exog=pre_data.iloc[:, 1:],
  199. freq_seasonal=[{'period': 4}, {'period': 3}])
  200. ci = CausalImpact(rand_data, pre_int_period, post_int_period, model=model)
  201. assert ci.model.freq_seasonal_periods == [4, 3]
  202. assert ci.model.freq_seasonal_harmonics == [2, 1]
  203. def test_causal_cto_w_custom_model(rand_data, pre_int_period, post_int_period):
  204. pre_data = rand_data.loc[pre_int_period[0]: pre_int_period[1], :]
  205. post_data = rand_data.loc[post_int_period[0]: post_int_period[1], :]
  206. model = UnobservedComponents(endog=pre_data.iloc[:, 0], level='llevel',
  207. exog=pre_data.iloc[:, 1:])
  208. ci = CausalImpact(rand_data, pre_int_period, post_int_period, model=model)
  209. assert ci.model.endog_names == 'y'
  210. assert ci.model.exog_names == ['x1', 'x2']
  211. assert ci.model.k_endog == 1
  212. assert ci.model.level
  213. assert ci.model.trend_specification == 'local level'
  214. assert isinstance(ci.trained_model, UnobservedComponentsResultsWrapper)
  215. assert ci.trained_model.nobs == len(pre_data)
  216. def test_causal_cto_raises_on_None_input(rand_data, pre_int_period, post_int_period):
  217. with pytest.raises(ValueError) as excinfo:
  218. ci = CausalImpact(None, pre_int_period, post_int_period)
  219. assert str(excinfo.value) == 'data input cannot be empty'
  220. with pytest.raises(ValueError) as excinfo:
  221. ci = CausalImpact(rand_data, None, post_int_period)
  222. assert str(excinfo.value) == 'pre_period input cannot be empty'
  223. with pytest.raises(ValueError) as excinfo:
  224. ci = CausalImpact(rand_data, pre_int_period, None)
  225. assert str(excinfo.value) == 'post_period input cannot be empty'
  226. def test_invalid_data_input_raises():
  227. with pytest.raises(ValueError) as excinfo:
  228. ci = CausalImpact('test', [0, 5], [5, 10])
  229. assert str(excinfo.value) == 'Could not transform input data to pandas DataFrame.'
  230. data = [1, 2, 3, 4, 5, 6, 2 + 1j]
  231. with pytest.raises(ValueError) as excinfo:
  232. ci = CausalImpact(data, [0, 3], [3, 6])
  233. assert str(excinfo.value) == 'Input data must contain only numeric values.'
  234. data = np.random.randn(10, 2)
  235. data[0, 1] = np.nan
  236. with pytest.raises(ValueError) as excinfo:
  237. ci = CausalImpact(data, [0, 3], [3, 6])
  238. assert str(excinfo.value) == 'Input data cannot have NAN values.'
  239. def test_invalid_response_raises():
  240. data = np.random.rand(100, 2)
  241. data[:, 0] = np.ones(len(data)) * np.nan
  242. with pytest.raises(ValueError) as excinfo:
  243. ci = CausalImpact(data, [0, 50], [50, 100])
  244. assert str(excinfo.value) == 'Input response cannot have just Null values.'
  245. data[0:2, 0] = 1
  246. with pytest.raises(ValueError) as excinfo:
  247. ci = CausalImpact(data, [0, 50], [50, 100])
  248. assert str(excinfo.value) == ('Input response must have more than 3 non-null points '
  249. 'at least.')
  250. data[0:3, 0] = 1
  251. with pytest.raises(ValueError) as excinfo:
  252. ci = CausalImpact(data, [0, 50], [50, 100])
  253. assert str(excinfo.value) == 'Input response cannot be constant.'
  254. def test_invalid_alpha_raises(rand_data, pre_int_period, post_int_period):
  255. with pytest.raises(ValueError) as excinfo:
  256. ci = CausalImpact(rand_data, pre_int_period, post_int_period, alpha=1)
  257. assert str(excinfo.value) == 'alpha must be of type float.'
  258. with pytest.raises(ValueError) as excinfo:
  259. ci = CausalImpact(rand_data, pre_int_period, post_int_period, alpha=2.)
  260. assert str(excinfo.value) == (
  261. 'alpha must range between 0 (zero) and 1 (one) inclusive.')
  262. def test_custom_model_input_validation(rand_data, pre_int_period, post_int_period):
  263. with pytest.raises(ValueError) as excinfo:
  264. ci = CausalImpact(rand_data, pre_int_period, post_int_period, model='test')
  265. assert str(excinfo.value) == 'Input model must be of type UnobservedComponents.'
  266. ucm = UnobservedComponents(rand_data.iloc[:101, 0], level='llevel',
  267. exog=rand_data.iloc[:101, 1:])
  268. ucm.level = False
  269. with pytest.raises(ValueError) as excinfo:
  270. ci = CausalImpact(rand_data, pre_int_period, post_int_period, model=ucm)
  271. assert str(excinfo.value) == 'Model must have level attribute set.'
  272. ucm = UnobservedComponents(rand_data.iloc[:101, 0], level='llevel',
  273. exog=rand_data.iloc[:101, 1:])
  274. ucm.exog = None
  275. with pytest.raises(ValueError) as excinfo:
  276. ci = CausalImpact(rand_data, pre_int_period, post_int_period, model=ucm)
  277. assert str(excinfo.value) == 'Model must have exog attribute set.'
  278. ucm = UnobservedComponents(rand_data.iloc[:101, 0], level='llevel',
  279. exog=rand_data.iloc[:101, 1:])
  280. ucm.data = None
  281. with pytest.raises(ValueError) as excinfo:
  282. ci = CausalImpact(rand_data, pre_int_period, post_int_period, model=ucm)
  283. assert str(excinfo.value) == 'Model must have data attribute set.'
  284. def test_kwargs_validation(rand_data, pre_int_period, post_int_period):
  285. with pytest.raises(ValueError) as excinfo:
  286. ci = CausalImpact(rand_data, pre_int_period, post_int_period,
  287. standardize='yes')
  288. assert str(excinfo.value) == 'Standardize argument must be of type bool.'
  289. with pytest.raises(ValueError) as excinfo:
  290. ci = CausalImpact(rand_data, pre_int_period, post_int_period,
  291. standardize=False, nseasons=[7])
  292. assert str(excinfo.value) == (
  293. 'nseasons must be a list of dicts with the required key "period" and the '
  294. 'optional key "harmonics".'
  295. )
  296. with pytest.raises(ValueError) as excinfo:
  297. ci = CausalImpact(rand_data, pre_int_period, post_int_period,
  298. standardize=False, nseasons=[{'test': 8}])
  299. assert str(excinfo.value) == 'nseasons dicts must contain the key "period" defined.'
  300. with pytest.raises(ValueError) as excinfo:
  301. ci = CausalImpact(rand_data, pre_int_period, post_int_period,
  302. standardize=False, nseasons=[{'period': 4, 'harmonics': 3}])
  303. assert str(excinfo.value) == (
  304. 'Total harmonics must be less or equal than periods divided by 2.')
  305. def test_periods_validation(rand_data, date_rand_data):
  306. with pytest.raises(ValueError) as excinfo:
  307. ci = CausalImpact(rand_data, [5, 10], [4, 7])
  308. assert str(excinfo.value) == ('Values in training data cannot be present in the '
  309. 'post-intervention data. Please fix your pre_period value to cover at most one '
  310. 'point less from when the intervention happened.')
  311. with pytest.raises(ValueError) as excinfo:
  312. ci = CausalImpact(date_rand_data, ['20180101', '20180201'],
  313. ['20180110', '20180210'])
  314. assert str(excinfo.value) == ('Values in training data cannot be present in the '
  315. 'post-intervention data. Please fix your pre_period value to cover at most one '
  316. 'point less from when the intervention happened.')
  317. with pytest.raises(ValueError) as excinfo:
  318. ci = CausalImpact(rand_data, [5, 10], [15, 11])
  319. assert str(excinfo.value) == 'post_period last number must be bigger than its first.'
  320. with pytest.raises(ValueError) as excinfo:
  321. ci = CausalImpact(date_rand_data, ['20180101', '20180110'],
  322. ['20180115', '20180111'])
  323. assert str(excinfo.value) == 'post_period last number must be bigger than its first.'
  324. with pytest.raises(ValueError) as excinfo:
  325. ci = CausalImpact(rand_data, [0, 2], [15, 11])
  326. assert str(excinfo.value) == 'pre_period must span at least 3 time points.'
  327. with pytest.raises(ValueError) as excinfo:
  328. ci = CausalImpact(date_rand_data, ['20180101', '20180102'],
  329. ['20180115', '20180111'])
  330. assert str(excinfo.value) == 'pre_period must span at least 3 time points.'
  331. with pytest.raises(ValueError) as excinfo:
  332. ci = CausalImpact(rand_data, [5, 0], [15, 11])
  333. assert str(excinfo.value) == 'pre_period last number must be bigger than its first.'
  334. with pytest.raises(ValueError) as excinfo:
  335. ci = CausalImpact(date_rand_data, ['20180105', '20180101'],
  336. ['20180115', '20180111'])
  337. assert str(excinfo.value) == 'pre_period last number must be bigger than its first.'
  338. with pytest.raises(ValueError) as excinfo:
  339. ci = CausalImpact(rand_data, 0, [15, 11])
  340. assert str(excinfo.value) == 'Input period must be of type list.'
  341. with pytest.raises(ValueError) as excinfo:
  342. ci = CausalImpact(date_rand_data, '20180101', ['20180115', '20180130'])
  343. assert str(excinfo.value) == 'Input period must be of type list.'
  344. with pytest.raises(ValueError) as excinfo:
  345. ci = CausalImpact(rand_data, [0, 10, 30], [15, 11])
  346. assert str(excinfo.value) == ('Period must have two values regarding the beginning '
  347. 'and end of the pre and post intervention data.')
  348. with pytest.raises(ValueError) as excinfo:
  349. ci = CausalImpact(rand_data, [0, None], [15, 11])
  350. assert str(excinfo.value) == 'Input period cannot have `None` values.'
  351. with pytest.raises(ValueError) as excinfo:
  352. ci = CausalImpact(rand_data, [0, 5.5], [15, 11])
  353. assert str(excinfo.value) == 'Input must contain either int or str.'
  354. with pytest.raises(ValueError) as excinfo:
  355. ci = CausalImpact(rand_data, [-2, 10], [11, 20])
  356. assert str(excinfo.value) == (
  357. '-2 not present in input data index.'
  358. )
  359. with pytest.raises(ValueError) as excinfo:
  360. ci = CausalImpact(rand_data, [0, 10], [11, 2000])
  361. assert str(excinfo.value) == (
  362. '2000 not present in input data index.'
  363. )
  364. with pytest.raises(ValueError) as excinfo:
  365. ci = CausalImpact(rand_data, ['20180101', '20180110'],
  366. ['20180111', '20180130'])
  367. assert str(excinfo.value) == (
  368. '20180101 not present in input data index.'
  369. )
  370. with pytest.raises(ValueError) as excinfo:
  371. ci = CausalImpact(date_rand_data, ['20180101', '20180110'],
  372. ['20180111', '20200130'])
  373. assert str(excinfo.value) == ('20200130 not present in input data index.')
  374. with pytest.raises(ValueError) as excinfo:
  375. ci = CausalImpact(date_rand_data, ['20170101', '20180110'],
  376. ['20180111', '20180120'])
  377. assert str(excinfo.value) == ('20170101 not present in input data index.')
  378. def test_default_causal_inferences(fix_path):
  379. np.random.seed(1)
  380. data = pd.read_csv(os.path.join(fix_path, 'google_data.csv'))
  381. del data['t']
  382. pre_period = [0, 60]
  383. post_period = [61, 90]
  384. ci = CausalImpact(data, pre_period, post_period)
  385. assert int(ci.summary_data['average']['actual']) == 156
  386. assert int(ci.summary_data['average']['predicted']) == 129
  387. assert int(ci.summary_data['average']['predicted_lower']) == 124
  388. assert int(ci.summary_data['average']['predicted_upper']) == 134
  389. assert int(ci.summary_data['average']['abs_effect']) == 27
  390. assert round(ci.summary_data['average']['abs_effect_lower'], 1) == 21.6
  391. assert int(ci.summary_data['average']['abs_effect_upper']) == 31
  392. assert round(ci.summary_data['average']['rel_effect'], 1) == 0.2
  393. assert round(ci.summary_data['average']['rel_effect_lower'], 2) == 0.17
  394. assert round(ci.summary_data['average']['rel_effect_upper'], 2) == 0.25
  395. assert int(ci.summary_data['cumulative']['actual']) == 4687
  396. assert int(ci.summary_data['cumulative']['predicted']) == 3876
  397. assert int(ci.summary_data['cumulative']['predicted_lower']) == 3729
  398. assert int(ci.summary_data['cumulative']['predicted_upper']) == 4040
  399. assert int(ci.summary_data['cumulative']['abs_effect']) == 810
  400. assert int(ci.summary_data['cumulative']['abs_effect_lower']) == 646
  401. assert int(ci.summary_data['cumulative']['abs_effect_upper']) == 957
  402. assert round(ci.summary_data['cumulative']['rel_effect'], 1) == 0.2
  403. assert round(ci.summary_data['cumulative']['rel_effect_lower'], 2) == 0.17
  404. assert round(ci.summary_data['cumulative']['rel_effect_upper'], 2) == 0.25
  405. assert round(ci.p_value, 1) == 0.0
  406. def test_default_causal_inferences_w_date(fix_path):
  407. np.random.seed(1)
  408. data = pd.read_csv(os.path.join(fix_path, 'google_data.csv'))
  409. data['date'] = pd.to_datetime(data['t'])
  410. data.index = data['date']
  411. del data['t']
  412. del data['date']
  413. pre_period = ['2016-02-20 22:41:20', '2016-02-20 22:51:20']
  414. post_period = ['2016-02-20 22:51:30', '2016-02-20 22:56:20']
  415. ci = CausalImpact(data, pre_period, post_period)
  416. assert int(ci.summary_data['average']['actual']) == 156
  417. assert int(ci.summary_data['average']['predicted']) == 129
  418. assert int(ci.summary_data['average']['predicted_lower']) == 124
  419. assert int(ci.summary_data['average']['predicted_upper']) == 134
  420. assert int(ci.summary_data['average']['abs_effect']) == 27
  421. assert round(ci.summary_data['average']['abs_effect_lower'], 1) == 21.6
  422. assert int(ci.summary_data['average']['abs_effect_upper']) == 31
  423. assert round(ci.summary_data['average']['rel_effect'], 1) == 0.2
  424. assert round(ci.summary_data['average']['rel_effect_lower'], 2) == 0.17
  425. assert round(ci.summary_data['average']['rel_effect_upper'], 2) == 0.25
  426. assert int(ci.summary_data['cumulative']['actual']) == 4687
  427. assert int(ci.summary_data['cumulative']['predicted']) == 3876
  428. assert int(ci.summary_data['cumulative']['predicted_lower']) == 3729
  429. assert int(ci.summary_data['cumulative']['predicted_upper']) == 4040
  430. assert int(ci.summary_data['cumulative']['abs_effect']) == 810
  431. assert int(ci.summary_data['cumulative']['abs_effect_lower']) == 646
  432. assert int(ci.summary_data['cumulative']['abs_effect_upper']) == 957
  433. assert round(ci.summary_data['cumulative']['rel_effect'], 1) == 0.2
  434. assert round(ci.summary_data['cumulative']['rel_effect_lower'], 2) == 0.17
  435. assert round(ci.summary_data['cumulative']['rel_effect_upper'], 2) == 0.25
  436. assert round(ci.p_value, 1) == 0.0
  437. def test_default_model_fit(rand_data, pre_int_period, post_int_period, monkeypatch):
  438. pre_data = rand_data.loc[pre_int_period[0]: pre_int_period[1], :]
  439. post_data = rand_data.loc[post_int_period[0]: post_int_period[1], :]
  440. fit_mock = mock.Mock()
  441. model = UnobservedComponents(endog=pre_data.iloc[:, 0], level='llevel',
  442. exog=pre_data.iloc[:, 1:])
  443. model.fit = fit_mock
  444. construct_mock = mock.Mock(return_value=model)
  445. monkeypatch.setattr('causalimpact.main.CausalImpact._get_default_model',
  446. construct_mock)
  447. monkeypatch.setattr('causalimpact.main.CausalImpact._process_posterior_inferences',
  448. mock.Mock())
  449. ci = CausalImpact(rand_data, pre_int_period, post_int_period)
  450. model.fit.assert_called_with(
  451. bounds=[(None, None), (0.01 / 1.2, 0.012), (None, None), (None, None)],
  452. disp=False,
  453. nseasons=[],
  454. standardize=True
  455. )
  456. ci = CausalImpact(rand_data, pre_int_period, post_int_period, disp=True)
  457. model.fit.assert_called_with(
  458. bounds=[(None, None), (0.01 / 1.2, 0.012), (None, None), (None, None)],
  459. disp=True,
  460. nseasons=[],
  461. standardize=True
  462. )
  463. ci = CausalImpact(rand_data, pre_int_period, post_int_period, disp=True,
  464. prior_level_sd=0.1)
  465. model.fit.assert_called_with(
  466. bounds=[(None, None), (0.1 / 1.2, 0.1 * 1.2), (None, None), (None, None)],
  467. disp=True,
  468. prior_level_sd=0.1,
  469. nseasons=[],
  470. standardize=True
  471. )
  472. ci = CausalImpact(rand_data, pre_int_period, post_int_period, disp=True,
  473. prior_level_sd=None)
  474. model.fit.assert_called_with(
  475. bounds=[(None, None), (None, None), (None, None), (None, None)],
  476. disp=True,
  477. prior_level_sd=None,
  478. nseasons=[],
  479. standardize=True
  480. )
  481. model = UnobservedComponents(endog=pre_data.iloc[:, 0], level='llevel',
  482. exog=pre_data.iloc[:, 1:],
  483. freq_seasonal=[{'period': 3}])
  484. model.fit = fit_mock
  485. construct_mock = mock.Mock(return_value=model)
  486. monkeypatch.setattr('causalimpact.main.CausalImpact._get_default_model',
  487. construct_mock)
  488. ci = CausalImpact(rand_data, pre_int_period, post_int_period, disp=True,
  489. prior_level_sd=0.001, nseasons=[{'period': 3}])
  490. model.fit.assert_called_with(
  491. bounds=[(None, None), (0.001 / 1.2, 0.001 * 1.2), (None, None), (None, None),
  492. (None, None)],
  493. disp=True,
  494. prior_level_sd=0.001,
  495. nseasons=[{'period': 3}],
  496. standardize=True
  497. )
  498. model = UnobservedComponents(endog=pre_data.iloc[:, 0], level='llevel')
  499. model.fit = fit_mock
  500. construct_mock = mock.Mock(return_value=model)
  501. monkeypatch.setattr('causalimpact.main.CausalImpact._get_default_model',
  502. construct_mock)
  503. new_data = pd.DataFrame(np.random.randn(200, 1), columns=['y'])
  504. ci = CausalImpact(new_data, pre_int_period, post_int_period, disp=False)
  505. model.fit.assert_called_with(
  506. bounds=[(None, None), (0.01 / 1.2, 0.01 * 1.2)],
  507. disp=False,
  508. nseasons=[],
  509. standardize=True
  510. )
  511. def test_custom_model_fit(rand_data, pre_int_period, post_int_period, monkeypatch):
  512. fit_mock = mock.Mock()
  513. monkeypatch.setattr('causalimpact.main.CausalImpact._process_posterior_inferences',
  514. mock.Mock())
  515. pre_data = rand_data.loc[pre_int_period[0]: pre_int_period[1], :]
  516. post_data = rand_data.loc[post_int_period[0]: post_int_period[1], :]
  517. model = UnobservedComponents(endog=pre_data.iloc[:, 0], level='llevel',
  518. exog=pre_data.iloc[:, 1:])
  519. model.fit = fit_mock
  520. ci = CausalImpact(rand_data, pre_int_period, post_int_period, model=model)
  521. fit_mock.assert_called_with(
  522. bounds=[(None, None), (0.01 / 1.2, 0.01 * 1.2), (None, None), (None, None)],
  523. disp=False,
  524. nseasons=[],
  525. standardize=True
  526. )
  527. ci = CausalImpact(rand_data, pre_int_period, post_int_period, model=model, disp=True)
  528. fit_mock.assert_called_with(
  529. bounds=[(None, None), (0.01 / 1.2, 0.01 * 1.2), (None, None), (None, None)],
  530. disp=True,
  531. nseasons=[],
  532. standardize=True
  533. )
  534. ci = CausalImpact(rand_data, pre_int_period, post_int_period, model=model, disp=True,
  535. prior_level_sd=0.01)
  536. fit_mock.assert_called_with(
  537. bounds=[(None, None), (0.01 / 1.2, 0.01 * 1.2), (None, None), (None, None)],
  538. disp=True,
  539. prior_level_sd=0.01,
  540. nseasons=[],
  541. standardize=True
  542. )
  543. ci = CausalImpact(rand_data, pre_int_period, post_int_period, model=model, disp=True,
  544. prior_level_sd=None)
  545. fit_mock.assert_called_with(
  546. bounds=[(None, None), (None, None), (None, None), (None, None)],
  547. disp=True,
  548. prior_level_sd=None,
  549. nseasons=[],
  550. standardize=True
  551. )
  552. model = UnobservedComponents(endog=pre_data.iloc[:, 0], level='llevel',
  553. exog=pre_data.iloc[:, 1:], freq_seasonal=[{'period': 3}])
  554. model.fit = fit_mock
  555. ci = CausalImpact(rand_data, pre_int_period, post_int_period, model=model, disp=True,
  556. prior_level_sd=0.001)
  557. fit_mock.assert_called_with(
  558. bounds=[(None, None), (0.001 / 1.2, 0.001 * 1.2), (None, None), (None, None),
  559. (None, None)],
  560. disp=True,
  561. prior_level_sd=0.001,
  562. nseasons=[],
  563. standardize=True
  564. )
  565. model = UnobservedComponents(
  566. endog=pre_data.iloc[:, 0],
  567. level=True,
  568. exog=pre_data.iloc[:, 1],
  569. trend=True,
  570. seasonal=3,
  571. stochastic_level=True
  572. )
  573. model.fit = fit_mock
  574. ci = CausalImpact(rand_data, pre_int_period, post_int_period, model=model, disp=True,
  575. prior_level_sd=0.001)
  576. fit_mock.assert_called_with(
  577. bounds=[(0.001 / 1.2, 0.001 * 1.2), (None, None), (None, None)],
  578. disp=True,
  579. prior_level_sd=0.001,
  580. nseasons=[],
  581. standardize=True
  582. )
  583. new_pre_data = rand_data.loc[pre_int_period[0]: pre_int_period[1], ['y', 'x1']]
  584. new_post_data = rand_data.loc[post_int_period[0]: post_int_period[1], ['y', 'x1']]
  585. model = UnobservedComponents(endog=new_pre_data.iloc[:, 0], level='llevel',
  586. exog=new_pre_data.iloc[:, 1:])
  587. model.fit = fit_mock
  588. ci = CausalImpact(rand_data, pre_int_period, post_int_period, model=model,
  589. disp=False)
  590. fit_mock.assert_called_with(
  591. bounds=[(None, None), (0.01 / 1.2, 0.01 * 1.2), (None, None)],
  592. disp=False,
  593. nseasons=[],
  594. standardize=True
  595. )
  596. model = UnobservedComponents(endog=new_pre_data.iloc[:, 0], level='dtrend',
  597. exog=new_pre_data.iloc[:, 1:])
  598. model.fit = fit_mock
  599. ci = CausalImpact(rand_data, pre_int_period, post_int_period, model=model,
  600. disp=False)
  601. fit_mock.assert_called_with(
  602. bounds=[(None, None), (None, None)],
  603. disp=False,
  604. nseasons=[],
  605. standardize=True
  606. )
  607. model = UnobservedComponents(endog=new_pre_data.iloc[:, 0], level='lltrend',
  608. exog=new_pre_data.iloc[:, 1:])
  609. model.fit = fit_mock
  610. ci = CausalImpact(rand_data, pre_int_period, post_int_period, model=model,
  611. disp=False)
  612. fit_mock.assert_called_with(
  613. bounds=[(None, None), (0.01 / 1.2, 0.01 * 1.2), (None, None), (None, None)],
  614. disp=False,
  615. nseasons=[],
  616. standardize=True
  617. )
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...