/
nixtla_client.py
1534 lines (1464 loc) 路 61.2 KB
/
nixtla_client.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
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/nixtla_client.ipynb.
# %% auto 0
__all__ = ['main_logger', 'httpx_logger']
# %% ../nbs/nixtla_client.ipynb 3
import functools
import inspect
import json
import logging
import os
import requests
import warnings
from typing import Dict, List, Optional, Union
import numpy as np
import pandas as pd
from tenacity import (
retry,
stop_after_attempt,
wait_fixed,
stop_after_delay,
RetryCallState,
retry_if_exception,
retry_if_not_exception_type,
)
from utilsforecast.processing import (
backtest_splits,
drop_index_if_pandas,
join,
maybe_compute_sort_indices,
take_rows,
vertical_concat,
)
from nixtlats.client import (
ApiError,
Nixtla,
SingleSeriesForecast,
MultiSeriesForecast,
MultiSeriesAnomaly,
MultiSeriesInsampleForecast,
)
logging.basicConfig(level=logging.INFO)
main_logger = logging.getLogger(__name__)
httpx_logger = logging.getLogger("httpx")
httpx_logger.setLevel(logging.ERROR)
# %% ../nbs/nixtla_client.ipynb 5
def deprecated_argument(old_name, new_name):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if old_name in kwargs:
warnings.warn(
f"`'{old_name}'` is deprecated; use `'{new_name}'` instead.",
FutureWarning,
)
if new_name in kwargs:
raise TypeError(f"{new_name} argument duplicated")
kwargs[new_name] = kwargs.pop(old_name)
return func(*args, **kwargs)
return wrapper
return decorator
# %% ../nbs/nixtla_client.ipynb 6
def deprecated_method(new_method):
def decorator(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
warnings.warn(
f"Method `{func.__name__}` is deprecated; "
f"use `{new_method}` instead.",
FutureWarning,
)
return getattr(self, new_method)(*args, **kwargs)
wrapper.__doc__ = func.__doc__
return wrapper
return decorator
# %% ../nbs/nixtla_client.ipynb 7
deprecated_fewshot_steps = deprecated_argument("fewshot_steps", "finetune_steps")
deprecated_fewshot_loss = deprecated_argument("fewshot_loss", "finetune_loss")
deprecated_token = deprecated_argument("token", "api_key")
deprecated_environment = deprecated_argument("environment", "base_url")
# %% ../nbs/nixtla_client.ipynb 8
use_validate_api_key = deprecated_method(new_method="validate_api_key")
# %% ../nbs/nixtla_client.ipynb 9
date_features_by_freq = {
# Daily frequencies
"B": ["year", "month", "day", "weekday"],
"C": ["year", "month", "day", "weekday"],
"D": ["year", "month", "day", "weekday"],
# Weekly
"W": ["year", "week", "weekday"],
# Monthly
"M": ["year", "month"],
"SM": ["year", "month", "day"],
"BM": ["year", "month"],
"CBM": ["year", "month"],
"MS": ["year", "month"],
"SMS": ["year", "month", "day"],
"BMS": ["year", "month"],
"CBMS": ["year", "month"],
# Quarterly
"Q": ["year", "quarter"],
"BQ": ["year", "quarter"],
"QS": ["year", "quarter"],
"BQS": ["year", "quarter"],
# Yearly
"A": ["year"],
"Y": ["year"],
"BA": ["year"],
"BY": ["year"],
"AS": ["year"],
"YS": ["year"],
"BAS": ["year"],
"BYS": ["year"],
# Hourly
"BH": ["year", "month", "day", "hour", "weekday"],
"H": ["year", "month", "day", "hour"],
# Minutely
"T": ["year", "month", "day", "hour", "minute"],
"min": ["year", "month", "day", "hour", "minute"],
# Secondly
"S": ["year", "month", "day", "hour", "minute", "second"],
# Milliseconds
"L": ["year", "month", "day", "hour", "minute", "second", "millisecond"],
"ms": ["year", "month", "day", "hour", "minute", "second", "millisecond"],
# Microseconds
"U": ["year", "month", "day", "hour", "minute", "second", "microsecond"],
"us": ["year", "month", "day", "hour", "minute", "second", "microsecond"],
# Nanoseconds
"N": [],
}
# %% ../nbs/nixtla_client.ipynb 10
class _NixtlaClientModel:
def __init__(
self,
client: Nixtla,
h: int,
id_col: str = "unique_id",
time_col: str = "ds",
target_col: str = "y",
freq: str = None,
level: Optional[List[Union[int, float]]] = None,
quantiles: Optional[List[float]] = None,
finetune_steps: int = 0,
finetune_loss: str = "default",
clean_ex_first: bool = True,
date_features: Union[bool, List[str]] = False,
date_features_to_one_hot: Union[bool, List[str]] = True,
model: str = "timegpt-1",
max_retries: int = 6,
retry_interval: int = 10,
max_wait_time: int = 6 * 60,
):
self.client = client
self.h = h
self.id_col = id_col
self.time_col = time_col
self.target_col = target_col
self.base_freq = freq
self.level, self.quantiles = self._prepare_level_and_quantiles(level, quantiles)
self.finetune_steps = finetune_steps
self.finetune_loss = finetune_loss
self.clean_ex_first = clean_ex_first
self.date_features = date_features
self.date_features_to_one_hot = date_features_to_one_hot
self.model = model
self.max_retries = max_retries
self.retry_interval = retry_interval
self.max_wait_time = max_wait_time
# variables defined by each flow
self.weights_x: pd.DataFrame = None
self.freq: str = self.base_freq
self.drop_uid: bool = False
self.x_cols: List[str]
self.input_size: int
self.model_horizon: int
@staticmethod
def _prepare_level_and_quantiles(
level: Optional[List[Union[int, float]]],
quantiles: Optional[List[float]],
):
if (level is not None) and (quantiles is not None):
raise Exception("you should include `level` or `quantiles` but not both.")
if quantiles is None:
return level, quantiles
# we recover level from quantiles
if not all(0 < q < 1 for q in quantiles):
raise Exception("`quantiles` should lie between 0 and 1")
level = [abs(int(100 - 200 * q)) for q in quantiles]
return level, quantiles
def _retry_strategy(self):
def after_retry(retry_state: RetryCallState):
"""Called after each retry attempt."""
main_logger.info(f"Attempt {retry_state.attempt_number} failed...")
# we want to retry when:
# there is no ApiError
# there is an ApiError with string body
def is_api_error_with_text_body(exception):
if isinstance(exception, ApiError):
if isinstance(exception.body, str):
return True
return False
return retry(
stop=(
stop_after_attempt(self.max_retries)
| stop_after_delay(self.max_wait_time)
),
wait=wait_fixed(self.retry_interval),
reraise=True,
after=after_retry,
retry=retry_if_exception(is_api_error_with_text_body)
| retry_if_not_exception_type(ApiError),
)
def _call_api(self, method, request):
response = self._retry_strategy()(method)(request=request)
if "data" in response:
response = response["data"]
return response
def transform_inputs(self, df: pd.DataFrame, X_df: pd.DataFrame):
df = df.copy()
main_logger.info("Validating inputs...")
if self.base_freq is None and hasattr(df.index, "freq"):
inferred_freq = df.index.freq
if inferred_freq is not None:
inferred_freq = inferred_freq.rule_code
main_logger.info(f"Inferred freq: {inferred_freq}")
self.freq = inferred_freq
time_col = df.index.name if df.index.name else "ds"
self.time_col = time_col
df.index.name = time_col
df = df.reset_index()
else:
self.freq = self.base_freq
renamer = {
self.id_col: "unique_id",
self.time_col: "ds",
self.target_col: "y",
}
df = df.rename(columns=renamer)
if df.dtypes.ds != "object":
df["ds"] = df["ds"].astype(str)
if "unique_id" not in df.columns:
# Insert unique_id column
df = df.assign(unique_id="ts_0")
self.drop_uid = True
if X_df is not None:
X_df = X_df.copy()
X_df = X_df.rename(columns=renamer)
if "unique_id" not in X_df.columns:
X_df = X_df.assign(unique_id="ts_0")
if X_df.dtypes.ds != "object":
X_df["ds"] = X_df["ds"].astype(str)
return df, X_df
def transform_outputs(
self, fcst_df: pd.DataFrame, level_to_quantiles: bool = False
):
renamer = {
"unique_id": self.id_col,
"ds": self.time_col,
"y": self.target_col,
}
if self.drop_uid:
fcst_df = fcst_df.drop(columns="unique_id")
fcst_df = fcst_df.rename(columns=renamer)
# transfom levels to quantiles if needed
if level_to_quantiles and self.quantiles is not None:
cols = [
col
for col in fcst_df.columns
if ("-lo-" not in col) and ("-hi-" not in col)
]
for q in sorted(self.quantiles):
if q == 0.5:
col = "TimeGPT"
else:
lv = int(100 - 200 * q)
hi_or_lo = "lo" if lv > 0 else "hi"
lv = abs(lv)
col = f"TimeGPT-{hi_or_lo}-{lv}"
q_col = f"TimeGPT-q-{int(q * 100)}"
fcst_df[q_col] = fcst_df[col].values
cols.append(q_col)
fcst_df = fcst_df[cols]
return fcst_df
def infer_freq(self, df: pd.DataFrame):
# special freqs that need to be checked
# for example to ensure 'W'-> 'W-MON'
special_freqs = ["W", "M", "Q", "Y", "A"]
if self.freq is None or self.freq in special_freqs:
unique_id = df.iloc[0]["unique_id"]
df_id = df.query("unique_id == @unique_id")
inferred_freq = pd.infer_freq(df_id["ds"].sort_values())
if inferred_freq is None:
raise Exception(
"Could not infer frequency of ds column. This could be due to "
"inconsistent intervals. Please check your data for missing, "
"duplicated or irregular timestamps"
)
if self.freq is not None:
# check we have the same base frequency
# except when we have yearly frequency (A, and Y means the same)
if (self.freq != inferred_freq[0] and self.freq != "Y") or (
self.freq == "Y" and inferred_freq[0] != "A"
):
raise Exception(
f"Failed to infer special date, inferred freq {inferred_freq}"
)
main_logger.info(f"Inferred freq: {inferred_freq}")
self.freq = inferred_freq
def resample_dataframe(self, df: pd.DataFrame):
df = df.copy()
df["ds"] = pd.to_datetime(df["ds"])
resampled_df = (
df.set_index("ds").groupby("unique_id").resample(self.freq).bfill()
)
resampled_df = resampled_df.drop(columns="unique_id").reset_index()
resampled_df["ds"] = resampled_df["ds"].astype(str)
return resampled_df
def make_future_dataframe(self, df: pd.DataFrame, reconvert: bool = True):
last_dates = df.groupby("unique_id")["ds"].max()
def _future_date_range(last_date):
future_dates = pd.date_range(last_date, freq=self.freq, periods=self.h + 1)
future_dates = future_dates[-self.h :]
return future_dates
future_df = last_dates.apply(_future_date_range).reset_index()
future_df = future_df.explode("ds").reset_index(drop=True)
if reconvert and df.dtypes["ds"] == "object":
# avoid date 000
future_df["ds"] = future_df["ds"].astype(str)
return future_df
def compute_date_feature(self, dates, feature):
if callable(feature):
feat_name = feature.__name__
feat_vals = feature(dates)
else:
feat_name = feature
if feature in ("week", "weekofyear"):
dates = dates.isocalendar()
feat_vals = getattr(dates, feature)
if not isinstance(feat_vals, pd.DataFrame):
vals = np.asarray(feat_vals)
feat_vals = pd.DataFrame({feat_name: vals})
feat_vals["ds"] = dates
return feat_vals
def add_date_features(
self,
df: pd.DataFrame,
X_df: Optional[pd.DataFrame],
):
# df contains exogenous variables
# X_df are the future values of the exogenous variables
# construct dates
train_dates = df["ds"].unique().tolist()
# if we dont have future exogenos variables
# we need to compute the future dates
if (self.h is not None) and X_df is None:
X_df = self.make_future_dataframe(df=df)
future_dates = X_df["ds"].unique().tolist()
elif X_df is not None:
future_dates = X_df["ds"].unique().tolist()
else:
future_dates = []
dates = pd.DatetimeIndex(np.unique(train_dates + future_dates).tolist())
date_features_df = pd.DataFrame({"ds": dates})
for feature in self.date_features:
feat_df = self.compute_date_feature(dates, feature)
date_features_df = date_features_df.merge(feat_df, on=["ds"], how="left")
if df.dtypes["ds"] == "object":
date_features_df["ds"] = date_features_df["ds"].astype(str)
if self.date_features_to_one_hot is not None:
date_features_df = pd.get_dummies(
date_features_df,
columns=self.date_features_to_one_hot,
dtype=int,
)
# remove duplicated columns if any
date_features_df = date_features_df.drop(
columns=[
col
for col in date_features_df.columns
if col in df.columns and col not in ["unique_id", "ds"]
]
)
# add date features to df
df = df.merge(date_features_df, on="ds", how="left")
# add date features to X_df
if X_df is not None:
X_df = X_df.merge(date_features_df, on="ds", how="left")
return df, X_df
def preprocess_X_df(self, X_df: pd.DataFrame):
if X_df.isna().any().any():
raise Exception("Some of your exogenous variables contain NA, please check")
X_df = X_df.sort_values(["unique_id", "ds"]).reset_index(drop=True)
X_df = self.resample_dataframe(X_df)
return X_df
def preprocess_dataframes(
self,
df: pd.DataFrame,
X_df: Optional[pd.DataFrame],
):
self.infer_freq(df=df)
"""Returns Y_df and X_df dataframes in the structure expected by the endpoints."""
# add date features logic
if isinstance(self.date_features, bool):
if self.date_features:
self.date_features = date_features_by_freq.get(self.freq)
if self.date_features is None:
warnings.warn(
f"Non default date features for {self.freq} "
"please pass a list of date features"
)
else:
self.date_features = None
if self.date_features is not None:
if isinstance(self.date_features_to_one_hot, bool):
if self.date_features_to_one_hot:
self.date_features_to_one_hot = [
feat for feat in self.date_features if not callable(feat)
]
self.date_features_to_one_hot = (
None
if not self.date_features_to_one_hot
else self.date_features_to_one_hot
)
else:
self.date_features_to_one_hot = None
df, X_df = self.add_date_features(df=df, X_df=X_df)
y_cols = ["unique_id", "ds", "y"]
Y_df = df[y_cols]
if Y_df["y"].isna().any():
raise Exception("Your target variable contains NA, please check")
# Azul: efficient this code
# and think about returning dates that are not in the training set
Y_df = self.resample_dataframe(Y_df)
x_cols = []
if X_df is not None:
x_cols = X_df.drop(columns=["unique_id", "ds"]).columns.to_list()
if not all(col in df.columns for col in x_cols):
raise Exception(
"You must include the exogenous variables in the `df` object, "
f'exogenous variables {",".join(x_cols)}'
)
if (self.h is not None) and (
len(X_df) != df["unique_id"].nunique() * self.h
):
raise Exception(
f"You have to pass the {self.h} future values of your "
"exogenous variables for each time series"
)
X_df_history = df[["unique_id", "ds"] + x_cols]
X_df = pd.concat([X_df_history, X_df])
X_df = self.preprocess_X_df(X_df)
elif (X_df is None) and (self.h is None) and (len(y_cols) < df.shape[1]):
# case for just insample,
# we dont need h
X_df = df.drop(columns="y")
x_cols = X_df.drop(columns=["unique_id", "ds"]).columns.to_list()
X_df = self.preprocess_X_df(X_df)
self.x_cols = x_cols
return Y_df, X_df
def dataframes_to_dict(self, Y_df: pd.DataFrame, X_df: pd.DataFrame):
to_dict_args = {"orient": "split"}
if "index" in inspect.signature(pd.DataFrame.to_dict).parameters:
to_dict_args["index"] = False
y = Y_df.to_dict(**to_dict_args)
x = X_df.to_dict(**to_dict_args) if X_df is not None else None
# A: I'm aware that sel.x_cols exists, but
# I want to be sure that we are logging the correct
# x cols :kiss:
if x:
x_cols = [col for col in x["columns"] if col not in ["unique_id", "ds"]]
main_logger.info(
f'Using the following exogenous variables: {", ".join(x_cols)}'
)
return y, x
def set_model_params(self):
model_params = self._call_api(
self.client.model_params,
SingleSeriesForecast(freq=self.freq, model=self.model),
)
model_params = model_params["detail"]
self.input_size, self.model_horizon = (
model_params["input_size"],
model_params["horizon"],
)
def validate_input_size(self, Y_df: pd.DataFrame):
min_history = Y_df.groupby("unique_id").size().min()
if min_history < self.input_size + self.model_horizon:
raise Exception(
"Your time series data is too short "
"Please be sure that your unique time series contain "
f"at least {self.input_size + self.model_horizon} observations"
)
def forecast(
self,
df: pd.DataFrame,
X_df: Optional[pd.DataFrame] = None,
add_history: bool = False,
):
df, X_df = self.transform_inputs(df=df, X_df=X_df)
main_logger.info("Preprocessing dataframes...")
Y_df, X_df = self.preprocess_dataframes(df=df, X_df=X_df)
self.set_model_params()
if self.h > self.model_horizon:
main_logger.warning(
'The specified horizon "h" exceeds the model horizon. '
"This may lead to less accurate forecasts. "
"Please consider using a smaller horizon."
)
# restrict input if
# - we dont want to finetune
# - we dont have exogenous regegressors
# - and we dont want to produce pred intervals
# - no add history
restrict_input = (
self.finetune_steps == 0
and X_df is None
and self.level is not None
and not add_history
)
if restrict_input:
# add sufficient info to compute
# conformal interval
main_logger.info("Restricting input...")
new_input_size = 3 * self.input_size + max(self.model_horizon, self.h)
Y_df = Y_df.groupby("unique_id").tail(new_input_size)
if X_df is not None:
X_df = X_df.groupby("unique_id").tail(
new_input_size + self.h
) # history plus exogenous
if self.finetune_steps > 0 or self.level is not None:
self.validate_input_size(Y_df=Y_df)
y, x = self.dataframes_to_dict(Y_df, X_df)
main_logger.info("Calling Forecast Endpoint...")
payload = MultiSeriesForecast(
y=y,
x=x,
fh=self.h,
freq=self.freq,
level=self.level,
finetune_steps=self.finetune_steps,
finetune_loss=self.finetune_loss,
clean_ex_first=self.clean_ex_first,
model=self.model,
)
response_timegpt = self._call_api(
self.client.forecast_multi_series,
payload,
)
if "weights_x" in response_timegpt:
self.weights_x = pd.DataFrame(
{
"features": self.x_cols,
"weights": response_timegpt["weights_x"],
}
)
fcst_df = pd.DataFrame(**response_timegpt["forecast"])
if add_history:
main_logger.info("Calling Historical Forecast Endpoint...")
self.validate_input_size(Y_df=Y_df)
response_timegpt = self._call_api(
self.client.historic_forecast_multi_series,
MultiSeriesInsampleForecast(
y=y,
x=x,
freq=self.freq,
level=self.level,
clean_ex_first=self.clean_ex_first,
model=self.model,
),
)
fitted_df = pd.DataFrame(**response_timegpt["forecast"])
fitted_df = fitted_df.drop(columns="y")
fcst_df = pd.concat([fitted_df, fcst_df]).sort_values(["unique_id", "ds"])
fcst_df = self.transform_outputs(fcst_df, level_to_quantiles=True)
return fcst_df
def detect_anomalies(self, df: pd.DataFrame):
# Azul
# Remember the input X_df is the FUTURE ex vars
# there is a misleading notation here
# because X_df inputs in the following methods
# returns X_df outputs that means something different
# ie X_df = [X_df_history, X_df]
# exogenous variables are passed after df
df, _ = self.transform_inputs(df=df, X_df=None)
main_logger.info("Preprocessing dataframes...")
Y_df, X_df = self.preprocess_dataframes(df=df, X_df=None)
main_logger.info("Calling Anomaly Detector Endpoint...")
y, x = self.dataframes_to_dict(Y_df, X_df)
response_timegpt = self._call_api(
self.client.anomaly_detection_multi_series,
MultiSeriesAnomaly(
y=y,
x=x,
freq=self.freq,
level=(
[self.level]
if (isinstance(self.level, int) or isinstance(self.level, float))
else [self.level[0]]
),
clean_ex_first=self.clean_ex_first,
model=self.model,
),
)
if "weights_x" in response_timegpt:
self.weights_x = pd.DataFrame(
{
"features": self.x_cols,
"weights": response_timegpt["weights_x"],
}
)
anomalies_df = pd.DataFrame(**response_timegpt["forecast"])
anomalies_df = anomalies_df.drop(columns="y")
anomalies_df = self.transform_outputs(anomalies_df)
return anomalies_df
def cross_validation(
self,
df: pd.DataFrame,
n_windows: int = 1,
step_size: Optional[int] = None,
):
# A: see `transform_inputs`
# the code always will return X_df=None
# if X_df=None
df, _ = self.transform_inputs(df=df, X_df=None)
self.infer_freq(df)
df["ds"] = pd.to_datetime(df["ds"])
# mlforecast cv code
results = []
sort_idxs = maybe_compute_sort_indices(df, "unique_id", "ds")
if sort_idxs is not None:
df = take_rows(df, sort_idxs)
splits = backtest_splits(
df,
n_windows=n_windows,
h=self.h,
id_col="unique_id",
time_col="ds",
freq=pd.tseries.frequencies.to_offset(self.freq),
step_size=self.h if step_size is None else step_size,
)
for i_window, (cutoffs, train, valid) in enumerate(splits):
if len(valid.columns) > 3:
# if we have uid, ds, y + exogenous vars
train_future = valid.drop(columns="y")
else:
train_future = None
y_pred = self.forecast(
df=train,
X_df=train_future,
)
y_pred, _ = self.transform_inputs(df=y_pred, X_df=None)
y_pred = join(y_pred, cutoffs, on="unique_id", how="left")
y_pred["ds"] = pd.to_datetime(y_pred["ds"])
result = join(
valid[["unique_id", "ds", "y"]],
y_pred,
on=["unique_id", "ds"],
)
if result.shape[0] < valid.shape[0]:
raise ValueError(
"Cross validation result produced less results than expected. "
"Please verify that the frequency parameter (freq) matches your series' "
"and that there aren't any missing periods."
)
results.append(result)
out = vertical_concat(results)
out = drop_index_if_pandas(out)
first_out_cols = ["unique_id", "ds", "cutoff", "y"]
remaining_cols = [c for c in out.columns if c not in first_out_cols]
fcst_cv_df = out[first_out_cols + remaining_cols]
fcst_cv_df["ds"] = fcst_cv_df["ds"].astype(str)
fcst_cv_df = self.transform_outputs(fcst_cv_df)
return fcst_cv_df
# %% ../nbs/nixtla_client.ipynb 11
def validate_model_parameter(func):
def wrapper(self, *args, **kwargs):
if "model" in kwargs:
model = kwargs["model"]
rename_models_dict = {
"short-horizon": "timegpt-1",
"long-horizon": "timegpt-1-long-horizon",
}
if model in rename_models_dict.keys():
new_model = rename_models_dict[model]
warnings.warn(
f"'{model}' is deprecated; use '{new_model}' instead.",
FutureWarning,
)
model = new_model
if model not in self.supported_models:
raise ValueError(
f'unsupported model: {kwargs["model"]} '
f'supported models: {", ".join(self.supported_models)}'
)
return func(self, *args, **kwargs)
return wrapper
# %% ../nbs/nixtla_client.ipynb 12
def remove_unused_categories(df: pd.DataFrame, col: str):
"""Check if col exists in df and if it is a category column.
In that case, it removes the unused levels."""
if df is not None and col in df:
if df[col].dtype == "category":
df = df.copy()
df[col] = df[col].cat.remove_unused_categories()
return df
# %% ../nbs/nixtla_client.ipynb 13
def partition_by_uid(func):
def wrapper(self, num_partitions, **kwargs):
if num_partitions is None or num_partitions == 1:
return func(self, **kwargs, num_partitions=1)
df = kwargs.pop("df")
X_df = kwargs.pop("X_df", None)
id_col = kwargs["id_col"]
uids = df["unique_id"].unique()
results_df = []
for uids_split in np.array_split(uids, num_partitions):
df_uids = df.query("unique_id in @uids_split")
if X_df is not None:
X_df_uids = X_df.query("unique_id in @uids_split")
else:
X_df_uids = None
df_uids = remove_unused_categories(df_uids, col=id_col)
X_df_uids = remove_unused_categories(X_df_uids, col=id_col)
kwargs_uids = {"df": df_uids, **kwargs}
if X_df_uids is not None:
kwargs_uids["X_df"] = X_df_uids
results_uids = func(self, **kwargs_uids, num_partitions=1)
results_df.append(results_uids)
results_df = pd.concat(results_df).reset_index(drop=True)
return results_df
return wrapper
# %% ../nbs/nixtla_client.ipynb 14
class _NixtlaClient:
"""
A class used to interact with Nixtla API.
"""
@deprecated_token
@deprecated_environment
def __init__(
self,
api_key: Optional[str] = None,
base_url: Optional[str] = None,
max_retries: int = 6,
retry_interval: int = 10,
max_wait_time: int = 6 * 60,
):
"""
Constructs all the necessary attributes for the NixtlaClient object.
Parameters
----------
api_key : str, (default=None)
The authorization api_key interacts with the Nixtla API.
If not provided, it will be inferred by the NIXTLA_API_KEY environment variable.
base_url : str, (default=None)
Custom base_url. Pass only if provided.
max_retries : int, (default=6)
The maximum number of attempts to make when calling the API before giving up.
It defines how many times the client will retry the API call if it fails.
Default value is 6, indicating the client will attempt the API call up to 6 times in total
retry_interval : int, (default=10)
The interval in seconds between consecutive retry attempts.
This is the waiting period before the client tries to call the API again after a failed attempt.
Default value is 10 seconds, meaning the client waits for 10 seconds between retries.
max_wait_time : int, (default=360)
The maximum total time in seconds that the client will spend on all retry attempts before giving up.
This sets an upper limit on the cumulative waiting time for all retry attempts.
If this time is exceeded, the client will stop retrying and raise an exception.
Default value is 360 seconds, meaning the client will cease retrying if the total time
spent on retries exceeds 360 seconds.
The client throws a ReadTimeout error after 60 seconds of inactivity. If you want to
catch these errors, use max_wait_time >> 60.
"""
if api_key is None:
timegpt_token = os.environ.get("TIMEGPT_TOKEN")
if timegpt_token is not None:
warnings.warn(
f"`TIMEGPT_TOKEN` environment variable is deprecated; "
"use `NIXTLA_API_KEY` instead.",
FutureWarning,
)
api_key = os.environ.get("NIXTLA_API_KEY", timegpt_token)
if api_key is None:
raise Exception(
"The api_key must be set either by passing `api_key` "
"or by setting the `NIXTLA_API_KEY` environment variable."
)
if base_url is None:
base_url = os.environ.get(
"NIXTLA_BASE_URL",
"https://dashboard.nixtla.io/api",
)
self.client = Nixtla(base_url=base_url, token=api_key)
self.max_retries = max_retries
self.retry_interval = retry_interval
self.max_wait_time = max_wait_time
self.supported_models = ["timegpt-1", "timegpt-1-long-horizon"]
# custom attr
self.weights_x: pd.DataFrame = None
@use_validate_api_key
def validate_token(self):
"""this is deprecated in favor of validate_api_key"""
pass
def validate_api_key(self, log: bool = True) -> bool:
"""Returns True if your api_key is valid."""
valid = False
try:
validation = self.client.validate_token()
except:
validation = dict()
if "message" in validation:
if validation["message"] == "success":
valid = True
elif "detail" in validation:
if "Forecasting! :)" in validation["detail"]:
valid = True
if "support" in validation and log:
main_logger.info(f'Happy Forecasting! :), {validation["support"]}')
return valid
@validate_model_parameter
@partition_by_uid
def _forecast(
self,
df: pd.DataFrame,
h: int,
freq: Optional[str] = None,
id_col: str = "unique_id",
time_col: str = "ds",
target_col: str = "y",
X_df: Optional[pd.DataFrame] = None,
level: Optional[List[Union[int, float]]] = None,
quantiles: Optional[List[float]] = None,
finetune_steps: int = 0,
finetune_loss: str = "default",
clean_ex_first: bool = True,
validate_api_key: bool = False,
add_history: bool = False,
date_features: Union[bool, List[str]] = False,
date_features_to_one_hot: Union[bool, List[str]] = True,
model: str = "timegpt-1",
num_partitions: int = 1,
):
if validate_api_key and not self.validate_api_key(log=False):
raise Exception("API Key not valid, please email ops@nixtla.io")
nixtla_client_model = _NixtlaClientModel(
client=self.client,
h=h,
id_col=id_col,
time_col=time_col,
target_col=target_col,
freq=freq,
level=level,
quantiles=quantiles,
finetune_steps=finetune_steps,
finetune_loss=finetune_loss,
clean_ex_first=clean_ex_first,
date_features=date_features,
date_features_to_one_hot=date_features_to_one_hot,
model=model,
max_retries=self.max_retries,
retry_interval=self.retry_interval,
max_wait_time=self.max_wait_time,
)
fcst_df = nixtla_client_model.forecast(
df=df, X_df=X_df, add_history=add_history
)
self.weights_x = nixtla_client_model.weights_x
return fcst_df
@validate_model_parameter
@partition_by_uid
def _detect_anomalies(
self,
df: pd.DataFrame,
freq: Optional[str] = None,
id_col: str = "unique_id",
time_col: str = "ds",
target_col: str = "y",
level: Union[int, float] = 99,
clean_ex_first: bool = True,
validate_api_key: bool = False,
date_features: Union[bool, List[str]] = False,
date_features_to_one_hot: Union[bool, List[str]] = True,
model: str = "timegpt-1",
num_partitions: int = 1,
):
if validate_api_key and not self.validate_api_key(log=False):
raise Exception("API Key not valid, please email ops@nixtla.io")
nixtla_client_model = _NixtlaClientModel(
client=self.client,
h=None,
id_col=id_col,
time_col=time_col,
target_col=target_col,
freq=freq,
level=level,
clean_ex_first=clean_ex_first,
date_features=date_features,
date_features_to_one_hot=date_features_to_one_hot,
model=model,
max_retries=self.max_retries,
retry_interval=self.retry_interval,
max_wait_time=self.max_wait_time,
)
anomalies_df = nixtla_client_model.detect_anomalies(df=df)
self.weights_x = nixtla_client_model.weights_x
return anomalies_df
@validate_model_parameter
@partition_by_uid
def _cross_validation(
self,
df: pd.DataFrame,
h: int,
freq: Optional[str] = None,
id_col: str = "unique_id",
time_col: str = "ds",
target_col: str = "y",
level: Optional[List[Union[int, float]]] = None,
quantiles: Optional[List[float]] = None,
validate_api_key: bool = False,
n_windows: int = 1,
step_size: Optional[int] = None,
finetune_steps: int = 0,
finetune_loss: str = "default",
clean_ex_first: bool = True,
date_features: Union[bool, List[str]] = False,
date_features_to_one_hot: Union[bool, List[str]] = True,
model: str = "timegpt-1",
num_partitions: int = 1,
):
if validate_api_key and not self.validate_api_key(log=False):
raise Exception("API Key not valid, please email ops@nixtla.io")
nixtla_client_model = _NixtlaClientModel(
client=self.client,
h=h,
id_col=id_col,
time_col=time_col,
target_col=target_col,
freq=freq,
level=level,
quantiles=quantiles,
finetune_steps=finetune_steps,
finetune_loss=finetune_loss,
clean_ex_first=clean_ex_first,
date_features=date_features,
date_features_to_one_hot=date_features_to_one_hot,
model=model,
max_retries=self.max_retries,
retry_interval=self.retry_interval,
max_wait_time=self.max_wait_time,
)
cv_df = nixtla_client_model.cross_validation(