test_nixtla_client.py 17.7 KB
Newer Older
bailuo's avatar
readme  
bailuo committed
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
from contextlib import contextmanager
from copy import deepcopy

import httpx
import numpy as np
import pandas as pd
import pytest
import zstandard as zstd
from pydantic import ValidationError

from nixtla_tests.conftest import HYPER_PARAMS_TEST
from nixtla_tests.helpers.checks import (
    check_equal_fcsts_add_history,
    check_num_partitions_same_results,
)


CAPTURED_REQUEST = None


class CapturingClient(httpx.Client):
    def post(self, *args, **kwargs):
        request = self.build_request("POST", *args, **kwargs)
        global CAPTURED_REQUEST
        CAPTURED_REQUEST = {
            "headers": dict(request.headers),
            "content": request.content,
            "method": request.method,
            "url": str(request.url),
        }
        return super().post(*args, **kwargs)


@contextmanager
def capture_request():
    original_client = httpx.Client
    httpx.Client = CapturingClient
    try:
        yield
    finally:
        httpx.Client = original_client


@pytest.mark.parametrize(
    "df_converter, freq",
    [
        pytest.param(lambda series, with_gaps: with_gaps, "5min", id="gaps"),
        pytest.param(
            lambda series, with_gaps: pd.concat([series, series]),
            "5min",
            id="duplicates",
        ),
        pytest.param(lambda series, with_gaps: series, "1min", id="wrong_freq"),
    ],
)
def test_forecast_with_error(series_with_gaps, nixtla_test_client, df_converter, freq):
    series, with_gaps = series_with_gaps

    with pytest.raises(
        ValueError,
        match="missing or duplicate timestamps, or the timestamps do not match",
    ):
        nixtla_test_client.forecast(df=df_converter(series, with_gaps), h=1, freq=freq)

@pytest.mark.parametrize("test_params, expected_exception, expected_error_msg",
    [
       ({"model_parameters": None}, None, ""),
       ({"model_parameters": {"max_q": 1}}, None, ""),
       ({"model_parameters": {"max_p": None}}, None, ""),
       ({"model_parameters": {"horizon": [1, 2, 3]}}, None, ""),
       ({"model_parameters": {"horizon": (1, 2, 3)}}, None, ""),
       ({"model_parameters": {"horizon": {"nested": "dict"}}}, None, ""),
       ({"model_parameters": {"horizon": {"nested": None}}}, None, ""),
       ({"model_parameters": "not a dict"}, ValidationError, "Input should be a valid dictionary"),
       ({"model_parameters": 123}, ValidationError, "Input should be a valid dictionary"),
       ({"model_parameters": {"horizon": {"nested_key": [1, 2, 3]}}}, TypeError, "Invalid value type"),
       ({"model_parameters": {"horizon": {"nested_key": (1, 2, 3)}}}, TypeError, "Invalid value type"),
       ({"model_parameters": {"horizon": {"nested_key": {1, 2}}}}, TypeError, "Invalid value type"),
       ({"model_parameters": {"horizon": {"nested_key": {"inner_key": "val"}}}}, TypeError, "Invalid value type"),
       ({"model_parameters": {"horizon": pd.DataFrame()}}, TypeError, "Invalid value type"),
    ]
)
@pytest.mark.parametrize("endpoint", ["forecast", "cross_validation"])
def test_model_parameters(nixtla_test_client, air_passengers_df, test_params, expected_exception, expected_error_msg, endpoint):
    base_params = {
        "df": air_passengers_df,
        "h": 12,
        "time_col": "timestamp",
        "target_col": "value",
    }
    base_params.update(test_params)
    if expected_exception is None:
        if endpoint == "forecast":
            nixtla_test_client.forecast(**base_params)
        elif endpoint == "cross_validation":
            nixtla_test_client.cross_validation(**base_params)
    else:
        with pytest.raises(expected_exception) as exc_info:
            if endpoint == "forecast":
                nixtla_test_client.forecast(**base_params)
            elif endpoint == "cross_validation":
                nixtla_test_client.cross_validation(**base_params)

        assert expected_error_msg in str(exc_info.value)


def test_cv_forecast_consistency(nixtla_test_client, cv_series_with_features):
    series_with_features, train, valid, x_cols, h, freq = cv_series_with_features
    for hist_exog_list in [None, [], [x_cols[2], x_cols[1]], x_cols]:
        cv_res = nixtla_test_client.cross_validation(
            series_with_features,
            n_windows=1,
            h=h,
            freq=freq,
            hist_exog_list=hist_exog_list,
        )
        fcst_res = nixtla_test_client.forecast(
            train,
            h=h,
            freq=freq,
            hist_exog_list=hist_exog_list,
            X_df=valid,
        )
        np.testing.assert_allclose(
            cv_res["TimeGPT"], fcst_res["TimeGPT"], atol=1e-4, rtol=1e-3
        )


def test_forecast_different_hist_exog_gives_different_results(
    nixtla_test_client, cv_series_with_features
):
    _, train, valid, x_cols, h, freq = cv_series_with_features
    for X_df in (None, valid):
        res1 = nixtla_test_client.forecast(
            train, h=h, X_df=X_df, freq=freq, hist_exog_list=x_cols[:2]
        )
        res2 = nixtla_test_client.forecast(
            train, h=h, X_df=X_df, freq=freq, hist_exog_list=x_cols[2:]
        )
        with pytest.raises(AssertionError):
            np.testing.assert_allclose(
                res1["TimeGPT"],
                res2["TimeGPT"],
                atol=1e-4,
                rtol=1e-3,
            )


def test_forecast_date_features_multiple_series_and_different_ends(
    nixtla_test_client, two_short_series
):
    h = 12
    fcst_test_series = nixtla_test_client.forecast(
        two_short_series, h=h, date_features=["dayofweek"]
    )
    uids = two_short_series["unique_id"]
    for uid in uids:
        expected = pd.date_range(
            periods=h + 1, start=two_short_series.query("unique_id == @uid")["ds"].max()
        )[1:].tolist()
        actual = fcst_test_series.query("unique_id == @uid")["ds"].tolist()
        assert actual == expected


def test_compression(nixtla_test_client, series_1MB_payload):
    with capture_request():
        nixtla_test_client.forecast(
            df=series_1MB_payload,
            freq="D",
            h=1,
            hist_exog_list=["static_0", "static_1"],
        )
        assert CAPTURED_REQUEST["headers"]["content-encoding"] == "zstd"
        content = CAPTURED_REQUEST["content"]
        assert len(content) < 2**20
        assert len(zstd.ZstdDecompressor().decompress(content)) > 2**20


def test_cv_refit_equivalence(nixtla_test_client, air_passengers_df):
    cv_kwargs = dict(
        df=air_passengers_df,
        n_windows=2,
        h=12,
        freq="MS",
        time_col="timestamp",
        target_col="value",
        finetune_steps=2,
    )
    res_refit = nixtla_test_client.cross_validation(refit=True, **cv_kwargs)
    res_no_refit = nixtla_test_client.cross_validation(refit=False, **cv_kwargs)
    np.testing.assert_allclose(res_refit["value"], res_no_refit["value"])
    with pytest.raises(AssertionError):
        np.testing.assert_allclose(
            res_refit["TimeGPT"],
            res_no_refit["TimeGPT"],
            atol=1e-4,
            rtol=1e-3,
        )


def test_forecast_quantiles_error(nixtla_test_client, air_passengers_df):
    with pytest.raises(Exception) as excinfo:
        nixtla_test_client.forecast(
            df=air_passengers_df,
            h=12,
            time_col="timestamp",
            target_col="value",
            level=[80],
            quantiles=[0.2, 0.3],
        )
    assert "not both" in str(excinfo.value)


@pytest.mark.parametrize(
    "method,kwargs",
    [
        ("forecast", {}),
        ("forecast", {"add_history": True}),
        ("cross_validation", {}),
    ],
)
def test_forecast_quantiles_output(
    nixtla_test_client, air_passengers_df, method, kwargs
):
    test_qls = list(np.arange(0.1, 1, 0.1))
    exp_q_cols = [f"TimeGPT-q-{int(100 * q)}" for q in test_qls]

    args = {
        "df": air_passengers_df,
        "h": 12,
        "time_col": "timestamp",
        "target_col": "value",
        "quantiles": test_qls,
        **kwargs,
    }
    if method == "cross_validation":
        func = nixtla_test_client.cross_validation
    elif method == "forecast":
        func = nixtla_test_client.forecast

    df_qls = func(**args)

    assert all(col in df_qls.columns for col in exp_q_cols)
    assert not any("-lo-" in col for col in df_qls.columns)
    # test monotonicity of quantiles
    for c1, c2 in zip(exp_q_cols[:-1], exp_q_cols[1:]):
        assert df_qls[c1].lt(df_qls[c2]).all()


@pytest.mark.parametrize("freq", ["D", "W-THU", "Q-DEC", "15T"])
@pytest.mark.parametrize(
    "method_name,method_kwargs,exog",
    [
        ("detect_anomalies", {"level": 98}, False),
        ("cross_validation", {"h": 7, "n_windows": 2}, False),
        ("forecast", {"h": 7, "add_history": True}, False),
        ("detect_anomalies", {"level": 98}, True),
        ("cross_validation", {"h": 7, "n_windows": 2}, False),
        ("forecast", {"h": 7, "add_history": True}, False),
    ],
)
def test_num_partitions_same_results_parametrized(
    nixtla_test_client, df_freq_generator, method_name, method_kwargs, freq, exog
):
    mathod_mapper = {
        "detect_anomalies": nixtla_test_client.detect_anomalies,
        "cross_validation": nixtla_test_client.cross_validation,
        "forecast": nixtla_test_client.forecast,
    }
    method = mathod_mapper[method_name]

    df_freq = df_freq_generator(n_series=10, min_length=500, max_length=550, freq=freq)
    df_freq["ds"] = df_freq.groupby("unique_id", observed=True)["ds"].transform(
        lambda x: pd.date_range(periods=len(x), freq=freq, end="2023-01-01")
    )
    if exog:
        df_freq["exog_1"] = 1

    kwargs = {
        "method": method,
        "num_partitions": 2,
        "df": df_freq,
        **method_kwargs,
    }

    check_num_partitions_same_results(**kwargs)


@pytest.mark.parametrize(
    "freq,h",
    [
        ("D", 7),
        ("W-THU", 52),
        ("Q-DEC", 8),
        ("15T", 4 * 24 * 7),
    ],
)
def test_forecast_models_different_results(
    nixtla_test_client, df_freq_generator, freq, h
):
    df_freq = df_freq_generator(n_series=10, min_length=500, max_length=550, freq=freq)
    df_freq["ds"] = df_freq.groupby("unique_id", observed=True)["ds"].transform(
        lambda x: pd.date_range(periods=len(x), freq=freq, end="2023-01-01")
    )
    kwargs = dict(df=df_freq, h=h)
    fcst_1_df = check_equal_fcsts_add_history(
        nixtla_test_client, **{**kwargs, "model": "timegpt-1"}
    )
    fcst_2_df = check_equal_fcsts_add_history(
        nixtla_test_client, **{**kwargs, "model": "timegpt-1-long-horizon"}
    )
    with pytest.raises(
        AssertionError, match=r'\(column name="TimeGPT"\) are different'
    ):
        pd.testing.assert_frame_equal(fcst_1_df, fcst_2_df)


@pytest.mark.parametrize(
    "method, method_kwargs",
    [
        (
            "forecast",
            dict(
                h=12,
                level=[90, 95],
                add_history=True,
                time_col="timestamp",
                target_col="value",
            ),
        ),
        (
            "cross_validation",
            dict(h=12, level=[90, 95], time_col="timestamp", target_col="value"),
        ),
        ("detect_anomalies", dict(level=99, time_col="timestamp", target_col="value")),
    ],
)
def test_different_models_give_different_results(
    air_passengers_df, nixtla_test_client, method, method_kwargs
):
    mathod_mapper = {
        "detect_anomalies": nixtla_test_client.detect_anomalies,
        "cross_validation": nixtla_test_client.cross_validation,
        "forecast": nixtla_test_client.forecast,
    }
    execute = mathod_mapper[method]

    # Run with first model
    out1 = execute(df=air_passengers_df, model="timegpt-1", **method_kwargs)
    # Run with second model
    out2 = execute(
        df=air_passengers_df, model="timegpt-1-long-horizon", **method_kwargs
    )
    # Compare only the TimeGPT column
    with pytest.raises(
        AssertionError, match=r'\(column name="TimeGPT"\) are different'
    ):
        pd.testing.assert_frame_equal(out1[["TimeGPT"]], out2[["TimeGPT"]])

    # test unsupported model
    method_kwargs["model"] = "my-awesome-model"
    with pytest.raises(ValueError, match="unsupported model"):
        execute(df=air_passengers_df, **method_kwargs)


def test_shap_features(nixtla_test_client, date_features_result):
    # Test shap values are returned and sum to predictions
    df_date_features, future_df, _ = date_features_result
    h = 12
    fcst_df = nixtla_test_client.forecast(
        df=df_date_features, h=h, X_df=future_df, feature_contributions=True
    )
    shap_values = nixtla_test_client.feature_contributions
    assert len(shap_values) == len(fcst_df)
    np.testing.assert_allclose(
        fcst_df["TimeGPT"].values, shap_values.iloc[:, 3:].sum(axis=1).values, rtol=1e-3
    )

    fcst_hist_df = nixtla_test_client.forecast(
        df=df_date_features,
        h=h,
        X_df=future_df,
        add_history=True,
        feature_contributions=True,
    )
    shap_values_hist = nixtla_test_client.feature_contributions
    assert len(shap_values_hist) == len(fcst_hist_df)
    np.testing.assert_allclose(
        fcst_hist_df["TimeGPT"].values,
        shap_values_hist.iloc[:, 3:].sum(axis=1).values,
        atol=1e-4,
    )

    # test num partitions
    _ = nixtla_test_client.feature_contributions
    pd.testing.assert_frame_equal(
        nixtla_test_client.feature_contributions, shap_values_hist, atol=1e-4, rtol=1e-3
    )


@pytest.mark.parametrize("hyp", HYPER_PARAMS_TEST)
def test_exogenous_variables_cv(nixtla_test_client, exog_data, hyp):
    df_ex_, df_train, df_test, x_df_test = exog_data
    fcst_test = nixtla_test_client.forecast(
        df_train.merge(df_ex_.drop(columns="y")), h=12, X_df=x_df_test, **hyp
    )
    fcst_test = df_test[["unique_id", "ds", "y"]].merge(fcst_test)
    fcst_test = fcst_test.sort_values(["unique_id", "ds"]).reset_index(drop=True)
    fcst_cv = nixtla_test_client.cross_validation(df_ex_, h=12, **hyp)
    fcst_cv = fcst_cv.sort_values(["unique_id", "ds"]).reset_index(drop=True)
    pd.testing.assert_frame_equal(
        fcst_test,
        fcst_cv.drop(columns="cutoff"),
        atol=1e-4,
        rtol=1e-3,
    )


@pytest.mark.parametrize("hyp", HYPER_PARAMS_TEST)
def test_forecast_vs_cv_no_exog(
    nixtla_test_client, train_test_split, air_passengers_renamed_df, hyp
):
    df_train, df_test = train_test_split
    fcst_test = nixtla_test_client.forecast(df_train, h=12, **hyp)
    fcst_test = df_test[["unique_id", "ds", "y"]].merge(fcst_test)
    fcst_test = fcst_test.sort_values(["unique_id", "ds"]).reset_index(drop=True)
    fcst_cv = nixtla_test_client.cross_validation(
        air_passengers_renamed_df, h=12, **hyp
    )
    fcst_cv = fcst_cv.sort_values(["unique_id", "ds"]).reset_index(drop=True)
    pd.testing.assert_frame_equal(
        fcst_test,
        fcst_cv.drop(columns="cutoff"),
        rtol=1e-2,
    )


@pytest.mark.parametrize("hyp", HYPER_PARAMS_TEST)
def test_forecast_vs_cv_insert_y(
    nixtla_test_client, train_test_split, air_passengers_renamed_df, hyp
):
    df_train, df_test = train_test_split
    fcst_test = nixtla_test_client.forecast(df_train, h=12, **hyp)
    fcst_test.insert(2, "y", df_test["y"].values)
    fcst_test = fcst_test.sort_values(["unique_id", "ds"]).reset_index(drop=True)
    fcst_cv = nixtla_test_client.cross_validation(
        air_passengers_renamed_df, h=12, **hyp
    )
    fcst_cv = fcst_cv.sort_values(["unique_id", "ds"]).reset_index(drop=True)
    pd.testing.assert_frame_equal(
        fcst_test,
        fcst_cv.drop(columns="cutoff"),
        rtol=1e-2,
    )


def test_forecast_and_anomalies_index_vs_columns(
    nixtla_test_client, air_passengers_renamed_df, air_passengers_renamed_df_with_index
):
    fcst_inferred_df_index = nixtla_test_client.forecast(
        air_passengers_renamed_df_with_index, h=10
    )
    anom_inferred_df_index = nixtla_test_client.detect_anomalies(
        air_passengers_renamed_df_with_index
    )
    fcst_inferred_df = nixtla_test_client.forecast(
        air_passengers_renamed_df[["ds", "unique_id", "y"]], h=10
    )
    anom_inferred_df = nixtla_test_client.detect_anomalies(
        air_passengers_renamed_df[["ds", "unique_id", "y"]]
    )
    pd.testing.assert_frame_equal(
        fcst_inferred_df_index, fcst_inferred_df, atol=1e-4, rtol=1e-3
    )
    pd.testing.assert_frame_equal(
        anom_inferred_df_index, anom_inferred_df, atol=1e-4, rtol=1e-3
    )


@pytest.mark.parametrize("freq", ["Y", "W-MON", "Q-DEC", "H"])
def test_forecast_index_vs_columns_various_freq(
    nixtla_test_client, air_passengers_renamed_df_with_index, freq
):
    df_ds_index = air_passengers_renamed_df_with_index.groupby("unique_id").tail(80)
    df_ds_index.index = np.concatenate(
        df_ds_index["unique_id"].nunique()
        * [pd.date_range(end="2023-01-01", periods=80, freq=freq)]
    )
    df_ds_index.index.name = "ds"
    fcst_inferred_df_index = nixtla_test_client.forecast(df_ds_index, h=10)
    df_test = df_ds_index.reset_index()
    fcst_inferred_df = nixtla_test_client.forecast(df_test, h=10)
    pd.testing.assert_frame_equal(
        fcst_inferred_df_index, fcst_inferred_df, atol=1e-4, rtol=1e-3
    )


def test_index_as_time_col(nixtla_test_client, air_passengers_df):
    df_test = deepcopy(air_passengers_df)
    df_test["timestamp"] = pd.to_datetime(df_test["timestamp"])
    df_test.set_index(df_test["timestamp"], inplace=True)
    df_test.drop(columns="timestamp", inplace=True)
    # Using user_provided time_col and freq
    timegpt_anomalies_df_1 = nixtla_test_client.detect_anomalies(
        air_passengers_df, time_col="timestamp", target_col="value", freq="M"
    )
    # Infer time_col and freq from index
    timegpt_anomalies_df_2 = nixtla_test_client.detect_anomalies(
        df_test, time_col="timestamp", target_col="value"
    )
    pd.testing.assert_frame_equal(
        timegpt_anomalies_df_1,
        timegpt_anomalies_df_2,
        atol=1e-4,
        rtol=1e-3,
    )