checks.py 18.5 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
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
import fugue
import fugue.api as fa
import numpy as np
import pandas as pd
import pytest
import time

from nixtla.nixtla_client import NixtlaClient
from typing import Callable

# setting used for distributed related tests
ATOL = 1e-3


# test num partitions
# we need to be sure that we can recover the same results
# using a for loop
# A: be aware that num partitons can produce different results
# when used finetune_steps
def check_num_partitions_same_results(method: Callable, num_partitions: int, **kwargs):
    res_partitioned = method(**kwargs, num_partitions=num_partitions)
    res_no_partitioned = method(**kwargs, num_partitions=1)
    sort_by = ["unique_id", "ds"]
    if "cutoff" in res_partitioned:
        sort_by.extend(["cutoff"])
    pd.testing.assert_frame_equal(
        res_partitioned.sort_values(sort_by).reset_index(drop=True),
        res_no_partitioned.sort_values(sort_by).reset_index(drop=True),
        rtol=1e-2,
        atol=1e-2,
    )


def check_retry_behavior(
    df,
    side_effect,
    side_effect_exception,
    max_retries=5,
    retry_interval=5,
    max_wait_time=40,
    should_retry=True,
    sleep_seconds=5,
):
    mock_nixtla_client = NixtlaClient(
        max_retries=max_retries,
        retry_interval=retry_interval,
        max_wait_time=max_wait_time,
    )
    mock_nixtla_client._make_request = side_effect
    init_time = time.time()
    with pytest.raises(side_effect_exception):
        mock_nixtla_client.forecast(
            df=df, h=12, time_col="timestamp", target_col="value"
        )
    total_mock_time = time.time() - init_time
    if should_retry:
        approx_expected_time = min((max_retries - 1) * retry_interval, max_wait_time)
        upper_expected_time = min(max_retries * retry_interval, max_wait_time)
        assert total_mock_time >= approx_expected_time, "It is not retrying as expected"
        # preprocessing time before the first api call should be less than 60 seconds
        assert (
            total_mock_time - upper_expected_time - (max_retries - 1) * sleep_seconds
            <= sleep_seconds
        )
    else:
        assert total_mock_time <= max_wait_time


# test we recover the same <mean> forecasts
# with and without restricting input
# (add_history)
def check_equal_fcsts_add_history(nixtla_client, **kwargs):
    fcst_no_rest_df = nixtla_client.forecast(**kwargs, add_history=True)
    fcst_no_rest_df = (
        fcst_no_rest_df.groupby("unique_id", observed=True)
        .tail(kwargs["h"])
        .reset_index(drop=True)
    )
    fcst_rest_df = nixtla_client.forecast(**kwargs)
    pd.testing.assert_frame_equal(
        fcst_no_rest_df,
        fcst_rest_df,
        atol=1e-4,
        rtol=1e-3,
    )
    return fcst_rest_df


def check_quantiles(
    nixtla_client: NixtlaClient,
    df: fugue.AnyDataFrame,
    id_col: str = "id_col",
    time_col: str = "time_col",
):
    test_qls = list(np.arange(0.1, 1, 0.1))
    exp_q_cols = [f"TimeGPT-q-{int(q * 100)}" for q in test_qls]

    def test_method_qls(method, **kwargs):
        df_qls = method(
            df=df, h=12, id_col=id_col, time_col=time_col, quantiles=test_qls, **kwargs
        )
        df_qls = fa.as_pandas(df_qls)
        assert all(col in df_qls.columns for col in exp_q_cols)
        # test monotonicity of quantiles
        df_qls.apply(lambda x: x.is_monotonic_increasing, axis=1).sum() == len(
            exp_q_cols
        )

    test_method_qls(nixtla_client.forecast)
    test_method_qls(nixtla_client.forecast, add_history=True)
    test_method_qls(nixtla_client.cross_validation)


def check_cv_same_results_num_partitions(
    nixtla_client: NixtlaClient,
    df: fugue.AnyDataFrame,
    horizon: int = 12,
    id_col: str = "unique_id",
    time_col: str = "ds",
    **fcst_kwargs,
):
    fcst_df = nixtla_client.cross_validation(
        df=df,
        h=horizon,
        num_partitions=1,
        id_col=id_col,
        time_col=time_col,
        **fcst_kwargs,
    )
    fcst_df = fa.as_pandas(fcst_df)
    fcst_df_2 = nixtla_client.cross_validation(
        df=df,
        h=horizon,
        num_partitions=2,
        id_col=id_col,
        time_col=time_col,
        **fcst_kwargs,
    )
    fcst_df_2 = fa.as_pandas(fcst_df_2)
    pd.testing.assert_frame_equal(
        fcst_df.sort_values([id_col, time_col]).reset_index(drop=True),
        fcst_df_2.sort_values([id_col, time_col]).reset_index(drop=True),
        atol=ATOL,
    )


def check_forecast_diff_results_diff_models(
    nixtla_client: NixtlaClient,
    df: fugue.AnyDataFrame,
    horizon: int = 12,
    id_col: str = "unique_id",
    time_col: str = "ds",
    **fcst_kwargs,
):
    fcst_df = nixtla_client.forecast(
        df=df,
        h=horizon,
        num_partitions=1,
        id_col=id_col,
        time_col=time_col,
        model="timegpt-1",
        **fcst_kwargs,
    )
    fcst_df = fa.as_pandas(fcst_df)
    fcst_df_2 = nixtla_client.forecast(
        df=df,
        h=horizon,
        num_partitions=1,
        id_col=id_col,
        time_col=time_col,
        model="timegpt-1-long-horizon",
        **fcst_kwargs,
    )
    fcst_df_2 = fa.as_pandas(fcst_df_2)

    with pytest.raises(
        AssertionError, match=r'\(column name="TimeGPT"\) are different'
    ):
        pd.testing.assert_frame_equal(
            fcst_df.sort_values([id_col, time_col]).reset_index(drop=True),
            fcst_df_2.sort_values([id_col, time_col]).reset_index(drop=True),
        )


def check_forecast(
    nixtla_client: NixtlaClient,
    df: fugue.AnyDataFrame,
    horizon: int = 12,
    id_col: str = "unique_id",
    time_col: str = "ds",
    n_series_to_check: int = 4,
    **fcst_kwargs,
):
    fcst_df = nixtla_client.forecast(
        df=df,
        h=horizon,
        id_col=id_col,
        time_col=time_col,
        **fcst_kwargs,
    )
    fcst_df = fa.as_pandas(fcst_df)
    assert n_series_to_check * 12 == len(fcst_df)
    cols = fcst_df.columns.to_list()
    exp_cols = [id_col, time_col, "TimeGPT"]
    if "level" in fcst_kwargs:
        level = sorted(fcst_kwargs["level"])
        exp_cols.extend([f"TimeGPT-lo-{lv}" for lv in reversed(level)])
        exp_cols.extend([f"TimeGPT-hi-{lv}" for lv in level])
    assert cols == exp_cols


def check_forecast_same_results_num_partitions(
    nixtla_client: NixtlaClient,
    df: fugue.AnyDataFrame,
    horizon: int = 12,
    id_col: str = "unique_id",
    time_col: str = "ds",
    **fcst_kwargs,
):
    fcst_df = nixtla_client.forecast(
        df=df,
        h=horizon,
        num_partitions=1,
        id_col=id_col,
        time_col=time_col,
        **fcst_kwargs,
    )
    fcst_df = fa.as_pandas(fcst_df)
    fcst_df_2 = nixtla_client.forecast(
        df=df,
        h=horizon,
        num_partitions=2,
        id_col=id_col,
        time_col=time_col,
        **fcst_kwargs,
    )
    fcst_df_2 = fa.as_pandas(fcst_df_2)
    pd.testing.assert_frame_equal(
        fcst_df.sort_values([id_col, time_col]).reset_index(drop=True),
        fcst_df_2.sort_values([id_col, time_col]).reset_index(drop=True),
        atol=ATOL,
    )


def check_forecast_dataframe(
    nixtla_client: NixtlaClient,
    df: fugue.AnyDataFrame,
    n_series_to_check: int = 4,
):
    check_cv_same_results_num_partitions(nixtla_client, df, n_windows=2, step_size=1)
    check_cv_same_results_num_partitions(
        nixtla_client, df, n_windows=3, step_size=None, horizon=1
    )
    check_cv_same_results_num_partitions(
        nixtla_client, df, model="timegpt-1-long-horizon", horizon=1
    )
    check_forecast_diff_results_diff_models(nixtla_client, df)
    check_forecast(nixtla_client, df, num_partitions=1)
    check_forecast(
        nixtla_client,
        df,
        level=[90, 80],
        num_partitions=1,
        n_series_to_check=n_series_to_check,
    )
    check_forecast_same_results_num_partitions(nixtla_client, df)


def check_forecast_dataframe_diff_cols(
    nixtla_client: NixtlaClient,
    df: fugue.AnyDataFrame,
    id_col: str = "id_col",
    time_col: str = "time_col",
    target_col: str = "target_col",
):
    check_forecast(
        nixtla_client,
        df,
        id_col=id_col,
        time_col=time_col,
        target_col=target_col,
        num_partitions=1,
    )
    check_forecast(
        nixtla_client,
        df,
        id_col=id_col,
        time_col=time_col,
        target_col=target_col,
        level=[90, 80],
        num_partitions=1,
    )
    check_forecast_same_results_num_partitions(
        nixtla_client, df, id_col=id_col, time_col=time_col, target_col=target_col
    )


def check_anomalies(
    nixtla_client: NixtlaClient,
    df: fugue.AnyDataFrame,
    id_col: str = "unique_id",
    time_col: str = "ds",
    target_col: str = "y",
    **anomalies_kwargs,
):
    anomalies_df = nixtla_client.detect_anomalies(
        df=df,
        id_col=id_col,
        time_col=time_col,
        target_col=target_col,
        **anomalies_kwargs,
    )
    anomalies_df = fa.as_pandas(anomalies_df)
    assert (fa.as_pandas(df)[id_col].unique() == anomalies_df[id_col].unique()).all()
    cols = anomalies_df.columns.to_list()
    level = anomalies_kwargs.get("level", 99)
    exp_cols = [
        id_col,
        time_col,
        target_col,
        "TimeGPT",
        "anomaly",
        f"TimeGPT-lo-{level}",
        f"TimeGPT-hi-{level}",
    ]
    assert cols == exp_cols


def check_anomalies_same_results_num_partitions(
    nixtla_client: NixtlaClient,
    df: fugue.AnyDataFrame,
    id_col: str = "unique_id",
    time_col: str = "ds",
    target_col: str = "y",
    **anomalies_kwargs,
):
    anomalies_df = nixtla_client.detect_anomalies(
        df=df,
        num_partitions=1,
        id_col=id_col,
        time_col=time_col,
        target_col=target_col,
        **anomalies_kwargs,
    )
    anomalies_df = fa.as_pandas(anomalies_df)
    anomalies_df_2 = nixtla_client.detect_anomalies(
        df=df,
        num_partitions=2,
        id_col=id_col,
        time_col=time_col,
        target_col=target_col,
        **anomalies_kwargs,
    )
    anomalies_df_2 = fa.as_pandas(anomalies_df_2)
    pd.testing.assert_frame_equal(
        anomalies_df.sort_values([id_col, time_col]).reset_index(drop=True),
        anomalies_df_2.sort_values([id_col, time_col]).reset_index(drop=True),
        atol=ATOL,
    )


def check_anomalies_dataframe(nixtla_client: NixtlaClient, df: fugue.AnyDataFrame):
    check_anomalies(nixtla_client, df, num_partitions=1)
    check_anomalies(nixtla_client, df, level=90, num_partitions=1)
    check_anomalies_same_results_num_partitions(nixtla_client, df)


def check_online_anomalies(
    nixtla_client: NixtlaClient,
    df: fugue.AnyDataFrame,
    id_col: str = "unique_id",
    time_col: str = "ds",
    target_col: str = "y",
    level=99,
    **reatlime_anomalies_kwargs,
):
    anomalies_df = nixtla_client.detect_anomalies_online(
        df=df,
        id_col=id_col,
        time_col=time_col,
        target_col=target_col,
        **reatlime_anomalies_kwargs,
    )
    anomalies_df = fa.as_pandas(anomalies_df)
    assert (fa.as_pandas(df)[id_col].unique() == anomalies_df[id_col].unique()).all()
    cols = anomalies_df.columns.to_list()
    exp_cols = [
        id_col,
        time_col,
        target_col,
        "TimeGPT",
        "anomaly",
        "anomaly_score",
        f"TimeGPT-lo-{level}",
        f"TimeGPT-hi-{level}",
    ]
    assert cols == exp_cols


def check_anomalies_online_same_results_num_partitions(
    nixtla_client: NixtlaClient,
    df: fugue.AnyDataFrame,
    id_col: str = "unique_id",
    time_col: str = "ds",
    target_col: str = "y",
    **reatlime_anomalies_kwargs,
):
    anomalies_df = nixtla_client.detect_anomalies_online(
        df=df,
        id_col=id_col,
        time_col=time_col,
        target_col=target_col,
        num_partitions=1,
        **reatlime_anomalies_kwargs,
    )
    anomalies_df = fa.as_pandas(anomalies_df)
    anomalies_df_2 = nixtla_client.detect_anomalies_online(
        df=df,
        id_col=id_col,
        time_col=time_col,
        target_col=target_col,
        num_partitions=2,
        **reatlime_anomalies_kwargs,
    )
    anomalies_df_2 = fa.as_pandas(anomalies_df_2)
    pd.testing.assert_frame_equal(
        anomalies_df.sort_values([id_col, time_col]).reset_index(drop=True),
        anomalies_df_2.sort_values([id_col, time_col]).reset_index(drop=True),
        atol=ATOL,
    )


def check_anomalies_online_dataframe(
    nixtla_client: NixtlaClient, df: fugue.AnyDataFrame
):
    check_online_anomalies(
        nixtla_client,
        df,
        h=20,
        detection_size=5,
        threshold_method="univariate",
        level=99,
        num_partitions=1,
    )
    check_anomalies_online_same_results_num_partitions(
        nixtla_client,
        df,
        h=20,
        detection_size=5,
        threshold_method="univariate",
        level=99,
    )


def check_anomalies_dataframe_diff_cols(
    nixtla_client: NixtlaClient,
    df: fugue.AnyDataFrame,
    id_col: str = "id_col",
    time_col: str = "time_col",
    target_col: str = "target_col",
):
    check_anomalies(
        nixtla_client,
        df,
        id_col=id_col,
        time_col=time_col,
        target_col=target_col,
        num_partitions=1,
    )
    check_anomalies(
        nixtla_client,
        df,
        id_col=id_col,
        time_col=time_col,
        target_col=target_col,
        level=90,
        num_partitions=1,
    )
    check_anomalies_same_results_num_partitions(
        nixtla_client, df, id_col=id_col, time_col=time_col, target_col=target_col
    )


def check_forecast_x(
    nixtla_client: NixtlaClient,
    df: fugue.AnyDataFrame,
    X_df: fugue.AnyDataFrame,
    horizon: int = 24,
    id_col: str = "unique_id",
    time_col: str = "ds",
    target_col: str = "y",
    **fcst_kwargs,
):
    fcst_df = nixtla_client.forecast(
        df=df,
        X_df=X_df,
        h=horizon,
        id_col=id_col,
        time_col=time_col,
        target_col=target_col,
        **fcst_kwargs,
    )
    fcst_df = fa.as_pandas(fcst_df)
    n_series = fa.as_pandas(X_df)[id_col].nunique()
    assert n_series * horizon == len(fcst_df)

    cols = fcst_df.columns.to_list()
    exp_cols = [id_col, time_col, "TimeGPT"]
    if "level" in fcst_kwargs:
        level = sorted(fcst_kwargs["level"])
        exp_cols.extend([f"TimeGPT-lo-{lv}" for lv in reversed(level)])
        exp_cols.extend([f"TimeGPT-hi-{lv}" for lv in level])
    assert cols == exp_cols

    fcst_df_2 = nixtla_client.forecast(
        df=df,
        h=horizon,
        id_col=id_col,
        time_col=time_col,
        target_col=target_col,
        **fcst_kwargs,
    )
    fcst_df_2 = fa.as_pandas(fcst_df_2)
    equal_arrays = np.array_equal(
        fcst_df.sort_values([id_col, time_col])["TimeGPT"].values,
        fcst_df_2.sort_values([id_col, time_col])["TimeGPT"].values,
    )
    assert not equal_arrays, "Forecasts with and without ex vars are equal"


def check_forecast_x_same_results_num_partitions(
    nixtla_client: NixtlaClient,
    df: fugue.AnyDataFrame,
    X_df: fugue.AnyDataFrame,
    horizon: int = 24,
    id_col: str = "unique_id",
    time_col: str = "ds",
    target_col: str = "y",
    **fcst_kwargs,
):
    fcst_df = nixtla_client.forecast(
        df=df,
        X_df=X_df,
        h=horizon,
        num_partitions=1,
        id_col=id_col,
        time_col=time_col,
        target_col=target_col,
        **fcst_kwargs,
    )
    fcst_df = fa.as_pandas(fcst_df)
    fcst_df_2 = nixtla_client.forecast(
        df=df,
        h=horizon,
        num_partitions=2,
        id_col=id_col,
        time_col=time_col,
        target_col=target_col,
        **fcst_kwargs,
    )
    fcst_df_2 = fa.as_pandas(fcst_df_2)
    equal_arrays = np.array_equal(
        fcst_df.sort_values([id_col, time_col])["TimeGPT"].values,
        fcst_df_2.sort_values([id_col, time_col])["TimeGPT"].values,
    )
    assert not equal_arrays, "Forecasts with and without ex vars are equal"


def check_forecast_x_dataframe(
    nixtla_client: NixtlaClient, df: fugue.AnyDataFrame, X_df: fugue.AnyDataFrame
):
    check_forecast_x(nixtla_client, df, X_df, num_partitions=1)
    check_forecast_x(nixtla_client, df, X_df, level=[90, 80], num_partitions=1)
    check_forecast_x_same_results_num_partitions(nixtla_client, df, X_df)


def check_forecast_x_dataframe_diff_cols(
    nixtla_client: NixtlaClient,
    df: fugue.AnyDataFrame,
    X_df: fugue.AnyDataFrame,
    id_col: str = "id_col",
    time_col: str = "time_col",
    target_col: str = "target_col",
):
    check_forecast_x(
        nixtla_client,
        df,
        X_df,
        id_col=id_col,
        time_col=time_col,
        target_col=target_col,
        num_partitions=1,
    )
    check_forecast_x(
        nixtla_client,
        df,
        X_df,
        id_col=id_col,
        time_col=time_col,
        target_col=target_col,
        level=[90, 80],
        num_partitions=1,
    )
    check_forecast_x_same_results_num_partitions(
        nixtla_client, df, X_df, id_col=id_col, time_col=time_col, target_col=target_col
    )


def check_finetuned_model(
    nixtla_client: NixtlaClient,
    df: fugue.AnyDataFrame,
    model_id2: str,
):
    # fine-tuning on distributed fails
    with pytest.raises(
        ValueError, match="Can only fine-tune on pandas or polars dataframes."
    ):
        nixtla_client.finetune(df=df)

    # forecast
    local_fcst = nixtla_client.forecast(
        df=fa.as_pandas(df), h=5, finetuned_model_id=model_id2,
    )
    distr_fcst = (
        fa.as_pandas(nixtla_client.forecast(df=df, h=5, finetuned_model_id=model_id2))
        .sort_values(["unique_id", "ds"])
        .reset_index(drop=True)
    )
    pd.testing.assert_frame_equal(
        local_fcst,
        distr_fcst,
        check_dtype=False,
        atol=1e-4,
        rtol=1e-2,
    )

    # cross-validation
    local_cv = nixtla_client.cross_validation(
        df=fa.as_pandas(df), n_windows=2, h=5, finetuned_model_id=model_id2
    )
    distr_cv = (
        fa.as_pandas(
            nixtla_client.cross_validation(
                df=df, n_windows=2, h=5, finetuned_model_id=model_id2
            )
        )
        .sort_values(["unique_id", "ds"])
        .reset_index(drop=True)
    )
    pd.testing.assert_frame_equal(
        local_cv,
        distr_cv[local_cv.columns],
        check_dtype=False,
        atol=1e-4,
        rtol=1e-2,
    )

    # anomaly detection
    local_anomaly = nixtla_client.detect_anomalies(
        df=fa.as_pandas(df), finetuned_model_id=model_id2
    )
    distr_anomaly = (
        fa.as_pandas(
            nixtla_client.detect_anomalies(df=df, finetuned_model_id=model_id2)
        )
        .sort_values(["unique_id", "ds"])
        .reset_index(drop=True)
    )
    pd.testing.assert_frame_equal(
        local_anomaly,
        distr_anomaly[local_anomaly.columns],
        check_dtype=False,
        atol=1e-3,
        rtol=1e-2,
    )