示例#1
0
    def test_summary_w_report_output(self, monkeypatch, inference_input,
                                     summary_report_filename):
        inferences_df = pd.DataFrame(inference_input)
        causal = CausalImpact()

        params = {'alpha': 0.05, 'post_period': [2, 4]}

        causal.params = params
        causal.inferences = inferences_df

        dedent_mock = mock.Mock()

        expected = open(summary_report_filename).read()
        expected = re.sub(r'\s+', ' ', expected)
        expected = expected.strip()

        tmpdir = mkdtemp()
        tmp_file = os.path.join(tmpdir, 'summary_test')

        def dedent_side_effect(msg):
            with open(tmp_file, 'a') as file_obj:
                msg = re.sub(r'\s+', ' ', msg)
                msg = msg.strip()
                file_obj.write(msg)
            return msg

        dedent_mock.side_effect = dedent_side_effect
        monkeypatch.setattr('textwrap.dedent', dedent_mock)

        causal.summary(output='report')
        result_str = open(tmp_file, 'r').read()
        assert result_str == expected
示例#2
0
    def test_summary_wrong_argument_raises(self, inference_input):
        inferences_df = pd.DataFrame(inference_input)
        causal = CausalImpact()

        params = {'alpha': 0.05, 'post_period': [2, 4]}

        causal.params = params
        causal.inferences = inferences_df

        with pytest.raises(ValueError):
            causal.summary(output='wrong_argument')
示例#3
0
    def test_summary(self, inference_input):
        inferences_df = pd.DataFrame(inference_input)
        causal = CausalImpact()

        params = {'alpha': 0.05, 'post_period': [2, 4]}

        causal.params = params
        causal.inferences = inferences_df

        expected = [
            [3, 7],
            [3, 7],
            [[3, 3], [7, 7]],
            [' ', ' '],
            [0, 0],
            [[0, 0], [0, 0]],
            [' ', ' '],
            ['-2.8%', '-2.8%'],
            [['0.0%', '-11.1%'], ['0.0%', '-11.1%']],
            [' ', ' '],
            ['0.0%', ' '],
            ['100.0%', ' '],
        ]

        expected = pd.DataFrame(expected,
                                columns=['Average', 'Cumulative'],
                                index=[
                                    'Actual', 'Predicted', '95% CI', ' ',
                                    'Absolute Effect', '95% CI', ' ',
                                    'Relative Effect', '95% CI', " ",
                                    "P-value", "Prob. of Causal Effect"
                                ])

        tmpdir = mkdtemp()
        tmp_expected = 'tmp_expected'
        tmp_result = 'tmp_test_summary'

        result_file = os.path.join(tmpdir, tmp_result)
        expected_file = os.path.join(tmpdir, tmp_expected)

        expected.to_csv(expected_file)
        expected_str = open(expected_file).read()

        causal.summary(path=result_file)

        result = open(result_file).read()
        assert result == expected_str
示例#4
0
    def test_plot(self, monkeypatch):
        causal = CausalImpact()

        params = {'alpha': 0.05, 'post_period': [2, 4], 'pre_period': [0, 1]}

        inferences_mock = {
            'point_pred': 'points predicted',
            'response': 'y obs',
            'point_pred_lower': 'lower predictions',
            'point_pred_upper': 'upper predictions'
        }

        class Inferences(object):
            @property
            def iloc(self):
                class Iloc(object):
                    def __getitem__(*args, **kwargs):
                        class EnhancedDict(dict):
                            @property
                            def index(self):
                                return [0, 1]

                            @property
                            def point_effect(self):
                                return 'lift'

                            @property
                            def point_effect_lower(self):
                                return 'point effect lower'

                            @property
                            def point_effect_upper(self):
                                return 'point effect upper'

                            @property
                            def cum_effect(self):
                                return 'cum effect'

                            @property
                            def cum_effect_upper(self):
                                return 'cum effect upper'

                            @property
                            def cum_effect_lower(self):
                                return 'cum effect lower'

                        return EnhancedDict(inferences_mock)

                return Iloc()

        class Data(object):
            @property
            def index(self):
                return 'index'

            @property
            def shape(self):
                return [(1, 2)]

        plot_mock = mock.Mock()
        fill_mock = mock.Mock()
        show_mock = mock.Mock()
        np_zeros_mock = mock.Mock()
        np_zeros_mock.side_effect = lambda x: [0, 0]

        get_lib_mock = mock.Mock(return_value=plot_mock)
        monkeypatch.setattr('causalimpact.analysis.get_matplotlib',
                            get_lib_mock)

        monkeypatch.setattr('numpy.zeros', np_zeros_mock)

        causal.params = params
        causal.inferences = Inferences()
        causal.data = Data()

        causal.plot(panels=['original', 'pointwise', 'cumulative'])
        causal.plot(panels=['pointwise', 'cumulative'])

        causal.plot(panels=['original'])

        plot_mock.plot.assert_any_call('y obs',
                                       'k',
                                       label='endog',
                                       linewidth=2)
        plot_mock.plot.assert_any_call('points predicted',
                                       'r--',
                                       label='model',
                                       linewidth=2)

        plot_mock.fill_between.assert_any_call([0, 1],
                                               'lower predictions',
                                               'upper predictions',
                                               facecolor='gray',
                                               interpolate=True,
                                               alpha=0.25)

        causal.plot(panels=['pointwise'])

        plot_mock.plot.assert_any_call('lift', 'r--', linewidth=2)
        plot_mock.plot.assert_any_call('index', [0, 0], 'g-', linewidth=2)

        causal.plot(panels=['cumulative'])

        plot_mock.plot.assert_any_call([0, 1],
                                       'cum effect',
                                       'r--',
                                       linewidth=2)
        plot_mock.plot.assert_any_call('index', [0, 0], 'g-', linewidth=2)