abhijit2k01 commited on
Commit
a69e62e
·
verified ·
1 Parent(s): e3a571b

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. datasets/raw/azure_vm_traces_2017/analysis/AzureFunctionsBlobDataset2020-Trace_Analysis.ipynb +0 -0
  2. datasets/raw/azure_vm_traces_2017/vm-noise-data/test_suite=OSBench/test_name=Test:_Create_Threads/vm_lifespan=long/vm_region=eastus/vm_sku=D8s_v5/unit=us Per Event.csv +0 -0
  3. datasets/raw/darts_benchmark_datasets/darts/dataprocessing/dtw/__init__.py +28 -0
  4. datasets/raw/darts_benchmark_datasets/darts/dataprocessing/dtw/cost_matrix.py +162 -0
  5. datasets/raw/darts_benchmark_datasets/darts/dataprocessing/dtw/dtw.py +373 -0
  6. datasets/raw/darts_benchmark_datasets/darts/dataprocessing/encoders/encoders.py +1622 -0
  7. datasets/raw/darts_benchmark_datasets/darts/utils/__init__.py +20 -0
  8. datasets/raw/darts_benchmark_datasets/darts/utils/_lazy.py +87 -0
  9. datasets/raw/darts_benchmark_datasets/darts/utils/_statsmodels_utils.py +13 -0
  10. datasets/raw/darts_benchmark_datasets/darts/utils/callbacks.py +275 -0
  11. datasets/raw/darts_benchmark_datasets/darts/utils/historical_forecasts/__init__.py +39 -0
  12. datasets/raw/darts_benchmark_datasets/darts/utils/historical_forecasts/optimized_historical_forecasts_regression.py +353 -0
  13. datasets/raw/darts_benchmark_datasets/darts/utils/historical_forecasts/utils.py +1666 -0
  14. datasets/raw/darts_benchmark_datasets/darts/utils/missing_values.py +187 -0
  15. datasets/raw/darts_benchmark_datasets/darts/utils/mlflow.py +1994 -0
  16. datasets/raw/darts_benchmark_datasets/darts/utils/statistics.py +1233 -0
  17. datasets/raw/darts_benchmark_datasets/darts/utils/timeseries_generation.py +950 -0
  18. datasets/raw/darts_benchmark_datasets/darts/utils/torch.py +96 -0
  19. datasets/raw/darts_benchmark_datasets/darts/utils/ts_utils.py +260 -0
  20. datasets/raw/darts_benchmark_datasets/darts/utils/utils.py +825 -0
datasets/raw/azure_vm_traces_2017/analysis/AzureFunctionsBlobDataset2020-Trace_Analysis.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
datasets/raw/azure_vm_traces_2017/vm-noise-data/test_suite=OSBench/test_name=Test:_Create_Threads/vm_lifespan=long/vm_region=eastus/vm_sku=D8s_v5/unit=us Per Event.csv ADDED
The diff for this file is too large to render. See raw diff
 
datasets/raw/darts_benchmark_datasets/darts/dataprocessing/dtw/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dynamic Time Warping (DTW)
3
+ --------------------------
4
+
5
+ Tools for computing Dynamic Time Warping alignment between time series, including cost matrices,
6
+ alignment algorithms, and windowing constraints (Sakoe-Chiba, Itakura).
7
+ """
8
+
9
+ from darts.dataprocessing.dtw.cost_matrix import CostMatrix
10
+ from darts.dataprocessing.dtw.dtw import DTWAlignment, dtw
11
+ from darts.dataprocessing.dtw.window import (
12
+ CRWindow,
13
+ Itakura,
14
+ NoWindow,
15
+ SakoeChiba,
16
+ Window,
17
+ )
18
+
19
+ __all__ = [
20
+ "CostMatrix",
21
+ "DTWAlignment",
22
+ "dtw",
23
+ "CRWindow",
24
+ "Itakura",
25
+ "NoWindow",
26
+ "SakoeChiba",
27
+ "Window",
28
+ ]
datasets/raw/darts_benchmark_datasets/darts/dataprocessing/dtw/cost_matrix.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ DTW Cost Matrix
3
+ ---------------
4
+ """
5
+
6
+ import array
7
+ from abc import ABC, abstractmethod
8
+ from itertools import repeat
9
+
10
+ import numpy as np
11
+
12
+ from darts.dataprocessing.dtw.window import CRWindow, Window
13
+
14
+ Elem = tuple[int, int]
15
+
16
+
17
+ class CostMatrix(ABC):
18
+ """
19
+ (n+1) x (m+1) Matrix
20
+ Cell (i,j) corresponds to minimum total cost/distance of matching elements (i-1, j-1) in series1 and series2.
21
+
22
+ Row 0 and column 0, are typically set to infinity, to prevent matching before the first element
23
+ """
24
+
25
+ n: int
26
+ m: int
27
+
28
+ @abstractmethod
29
+ def fill(self, value: float):
30
+ pass
31
+
32
+ @abstractmethod
33
+ def __getitem__(self, item):
34
+ pass
35
+
36
+ @abstractmethod
37
+ def __setitem__(self, key, value):
38
+ pass
39
+
40
+ @abstractmethod
41
+ def __iter__(self):
42
+ pass
43
+
44
+ @abstractmethod
45
+ def to_dense(self) -> np.ndarray:
46
+ """
47
+ Returns
48
+ -------
49
+ Dense n x m numpy array, where empty cells are set to np.inf
50
+ """
51
+ pass
52
+
53
+ @staticmethod
54
+ def _from_window(window: Window):
55
+ """
56
+ Creates a cost matrix from a window.
57
+ Depending on the density of the active cells in the window,
58
+ will select either a dense or sparse storage representation.
59
+
60
+ Parameters
61
+ ----------
62
+ window
63
+ Takes a `Window` defining which cells are active and which are empty
64
+
65
+ Returns
66
+ -------
67
+ CostMatrix
68
+ """
69
+ density = len(window) / ((window.n + 1) * (window.m + 1))
70
+
71
+ # In the future it might be worth implementing
72
+ # a sparse cost matrix based on column_index/column_length
73
+ # that will work even for non-contiguous windows
74
+ if isinstance(window, CRWindow) and density < 0.5:
75
+ return SparseCostMatrix(window)
76
+ else:
77
+ return DenseCostMatrix(window.n, window.m)
78
+
79
+
80
+ class DenseCostMatrix(np.ndarray, CostMatrix):
81
+ def __new__(self, n, m):
82
+ self.n = n
83
+ self.m = m
84
+ return super().__new__(self, (n + 1, m + 1), float)
85
+
86
+ def to_dense(self) -> np.ndarray:
87
+ return self[1:, 1:]
88
+
89
+ def __iter__(self):
90
+ for n in range(1, self.n):
91
+ for m in range(1, self.m):
92
+ yield n, m
93
+
94
+
95
+ class SparseCostMatrix(CostMatrix):
96
+ def __init__(self, window: CRWindow):
97
+ self.n = window.n
98
+ self.m = window.m
99
+ self.window = window
100
+ self.offsets = np.empty(self.n + 2, dtype=int)
101
+ self.column_ranges = window.column_ranges
102
+ self.offsets[0] = 0
103
+ np.cumsum(window.column_lengths(), out=self.offsets[1:])
104
+
105
+ len = self.offsets[-1]
106
+
107
+ self.offsets = array.array("i", self.offsets)
108
+ self.dense = array.array("f", repeat(np.inf, len))
109
+
110
+ def fill(self, value):
111
+ if value != np.inf: # should already be cleared to np.inf
112
+ for i in range(len(self.dense)):
113
+ self.dense[i] = value
114
+
115
+ def to_dense(self) -> np.ndarray:
116
+ matrix = np.empty((self.n, self.m))
117
+ matrix.fill(np.inf)
118
+
119
+ if isinstance(self.window, CRWindow):
120
+ ranges = self.window.column_ranges
121
+ lengths = self.window.column_lengths()
122
+
123
+ # TODO express only in terms of numpy operations
124
+ for i in range(1, self.n + 1):
125
+ start = ranges[i * 2 + 0] - 1
126
+ end = ranges[i * 2 + 1] - 1
127
+ len = lengths[i]
128
+ offset = self.offsets[i]
129
+
130
+ matrix[i - 1][start:end] = self.dense[offset : offset + len]
131
+ else:
132
+ for i in range(1, self.n + 1):
133
+ column_start = self.offsets[i]
134
+
135
+ for j in range(1, self.m + 1):
136
+ column_idx = self.window.column_index(i)
137
+ if column_idx == -1:
138
+ continue
139
+
140
+ matrix[i - 1, j - 1] = self.dense[column_start + column_idx]
141
+
142
+ return matrix
143
+
144
+ # PERFORMANCE: hot functions, avoid calling functions/excessive checking
145
+ def __getitem__(self, elem: Elem):
146
+ i, j = elem
147
+
148
+ start = self.column_ranges[i * 2 + 0]
149
+ end = self.column_ranges[i * 2 + 1]
150
+ if start <= j < end:
151
+ return self.dense[self.offsets[i] + j - start]
152
+ return np.inf
153
+
154
+ def __setitem__(self, elem, value):
155
+ i, j = elem
156
+
157
+ start = self.column_ranges[i * 2 + 0]
158
+
159
+ self.dense[self.offsets[i] + j - start] = value
160
+
161
+ def __iter__(self):
162
+ return self.window.__iter__()
datasets/raw/darts_benchmark_datasets/darts/dataprocessing/dtw/dtw.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Dynamic Time Warping (DTW)
3
+ --------------------------
4
+ """
5
+
6
+ import copy
7
+ from collections.abc import Callable
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ from darts import TimeSeries
13
+ from darts.dataprocessing.dtw.cost_matrix import CostMatrix
14
+ from darts.dataprocessing.dtw.window import CRWindow, NoWindow, Window
15
+ from darts.logging import get_logger, raise_log
16
+
17
+ logger = get_logger(__name__)
18
+
19
+ SeriesValue = np.ndarray | np.floating
20
+ DistanceFunc = Callable[[SeriesValue, SeriesValue], float]
21
+
22
+
23
+ # CORE ALGORITHM
24
+ def _dtw_cost_matrix(
25
+ x: np.ndarray, y: np.ndarray, dist: DistanceFunc, window: Window
26
+ ) -> CostMatrix:
27
+ dtw = CostMatrix._from_window(window)
28
+
29
+ dtw.fill(np.inf)
30
+ dtw[0, 0] = 0
31
+
32
+ for i, j in window:
33
+ cost = dist(x[i - 1], y[j - 1])
34
+ min_cost_prev = min(dtw[i - 1, j], dtw[i, j - 1], dtw[i - 1, j - 1])
35
+ dtw[i, j] = cost + min_cost_prev
36
+
37
+ return dtw
38
+
39
+
40
+ def _dtw_path(dtw: CostMatrix) -> np.ndarray:
41
+ i = dtw.n
42
+ j = dtw.m
43
+
44
+ path = []
45
+
46
+ while i > 0 or j > 0:
47
+ path.append((i - 1, j - 1))
48
+
49
+ stencil = [
50
+ (i - 1, j - 1), # diagonal
51
+ (i - 1, j), # left
52
+ (i, j - 1), # down
53
+ ]
54
+
55
+ costs = [dtw[i, j] for i, j in stencil]
56
+ index_min = costs.index(min(costs))
57
+
58
+ i, j = stencil[index_min]
59
+
60
+ path.reverse()
61
+ return np.array(path)
62
+
63
+
64
+ # MULTI-SCALE
65
+ def _down_sample(high_res: np.ndarray):
66
+ needs_padding = len(high_res) & 1
67
+ if needs_padding:
68
+ high_res = np.append(high_res, high_res[-1])
69
+
70
+ low_res = np.reshape(high_res, (-1, 2))
71
+ low_res = np.mean(low_res, axis=1)
72
+
73
+ return low_res
74
+
75
+
76
+ def _expand_window(low_res_path: np.ndarray, n: int, m: int, radius: int) -> CRWindow:
77
+ high_res_grid = CRWindow(n, m)
78
+
79
+ def is_valid(cell):
80
+ valid_x = 1 <= cell[0] <= n
81
+ valid_y = 1 <= cell[1] <= m
82
+
83
+ return valid_x and valid_y
84
+
85
+ # up-sample path, 1 grid point computed at half-resolution becomes at least 4
86
+ # (1,2) and (2,1) allows for better DWT solution, as it isn't diagonally constrained
87
+ #
88
+ # 4-sample 6-sample
89
+ # X X X X
90
+ # X X vs. X X X
91
+ # X X X X X
92
+ # X X X X
93
+
94
+ pattern = [(0, 0, 2), (1, 0, 3), (2, 1, 2)]
95
+
96
+ for i, j in low_res_path:
97
+ for column, start, end in pattern:
98
+ # +1 offset since x[0], y[0] maps to DTW[1][1]
99
+
100
+ column += i * 2 + 1
101
+
102
+ # ensure no out of bounds
103
+ # enlarge vertically by radius is O(1), due to compressed row representation
104
+ start = max(1, min(m + 1, start + j * 2 - radius))
105
+ end = max(1, min(m + 1, end + j * 2 + 1 + radius))
106
+
107
+ # to create an nxn block, add (0-n) range n times
108
+ # ensure no out of bounds
109
+ # if column is too large m-column -> 0
110
+ # if column-k is too small, column < radius+1
111
+ for k in range(0, min(radius + 1, column, n - column + 1)):
112
+ high_res_grid.add_range(column - k, start, end)
113
+
114
+ return high_res_grid
115
+
116
+
117
+ def _fast_dtw(
118
+ x: np.ndarray, y: np.ndarray, dist: DistanceFunc, radius: int, depth: int = 0
119
+ ) -> CostMatrix:
120
+ n = len(x)
121
+ m = len(y)
122
+ min_size = radius + 2
123
+
124
+ if n < min_size or m < min_size or radius == -1:
125
+ window = NoWindow()
126
+ window.init_size(n, m)
127
+ cost = _dtw_cost_matrix(x, y, dist, window)
128
+
129
+ return cost
130
+
131
+ half_x = _down_sample(x)
132
+ half_y = _down_sample(y)
133
+
134
+ low_res_cost = _fast_dtw(half_x, half_y, dist, radius, depth + 1)
135
+ low_res_path = _dtw_path(low_res_cost)
136
+ window = _expand_window(low_res_path, len(x), len(y), radius)
137
+ cost = _dtw_cost_matrix(x, y, dist, window)
138
+
139
+ return cost
140
+
141
+
142
+ def _default_distance_multi(x_values: np.ndarray, y_values: np.ndarray):
143
+ return np.sum(np.abs(x_values - y_values))
144
+
145
+
146
+ def _default_distance_uni(x_value: float, y_value: float):
147
+ return abs(x_value - y_value)
148
+
149
+
150
+ # Public API Functions
151
+ class DTWAlignment:
152
+ """
153
+ Dynamic Time Warping (DTW) Alignment.
154
+
155
+ Attributes
156
+ ----------
157
+ n
158
+ The length of `series1`
159
+ m
160
+ The length of `series2`
161
+ series1
162
+ A `TimeSeries` to align with `series2`.
163
+ series2
164
+ A `TimeSeries` to align with `series1`.
165
+ cost
166
+ The `CostMatrix` for DTW.
167
+ """
168
+
169
+ def __init__(self, series1: TimeSeries, series2: TimeSeries, cost: CostMatrix):
170
+ self.n = len(series1)
171
+ self.m = len(series2)
172
+ self.series1 = series1
173
+ self.series2 = series2
174
+ self.cost = cost
175
+
176
+ from ._plot import plot, plot_alignment
177
+
178
+ def path(self) -> np.ndarray:
179
+ """Gives the index paths from `series1` to `series2`.
180
+
181
+ Returns
182
+ -------
183
+ np.ndarray of shape `(len(path), 2)`
184
+ An array of indices [[i0,j0], [i1,j1], [i2,j2], ...], where i indexes into series1
185
+ and j indexes into series2.
186
+ Indices are in monotonic order, path[n] >= path[n-1]
187
+ """
188
+
189
+ if hasattr(self, "_path"):
190
+ return self._path
191
+ self._path = _dtw_path(self.cost)
192
+ return self._path
193
+
194
+ def distance(self) -> float:
195
+ """Gives the total distance between pair-wise elements in the two series after warping.
196
+
197
+ Returns
198
+ -------
199
+ float
200
+ The total distance between pair-wise elements in the two series after warping.
201
+ """
202
+ return self.cost[(self.n, self.m)]
203
+
204
+ def mean_distance(self) -> float:
205
+ """Gives the mean distance between pair-wise elements in the two series after warping.
206
+
207
+ Returns
208
+ -------
209
+ float
210
+ The mean distance between pair-wise elements in the two series after warping.
211
+ """
212
+ if hasattr(self, "_mean_distance"):
213
+ return self._mean_distance
214
+
215
+ path = self.path()
216
+ self._mean_distance = self.distance() / len(path)
217
+ return self._mean_distance
218
+
219
+ def warped(self) -> (TimeSeries, TimeSeries):
220
+ """Warps the two time series according to the warp path returned by `DTWAlignment.path()`, which minimizes the
221
+ pair-wise distance.
222
+ This will bring two time series that are out-of-phase back into phase.
223
+
224
+ Returns
225
+ -------
226
+ (TimeSeries, TimeSeries)
227
+ Two new TimeSeries instances of the same length, indexed by pd.RangeIndex.
228
+ """
229
+ values1 = self.series1.all_values(copy=False)
230
+ values2 = self.series2.all_values(copy=False)
231
+ path = self.path()
232
+
233
+ values1, values2 = values1[path[:, 0]], values2[path[:, 1]]
234
+
235
+ idx1 = pd.RangeIndex(values1.shape[0], name=self.series1._time_index.name)
236
+ idx2 = pd.RangeIndex(values2.shape[0], name=self.series2._time_index.name)
237
+ warped_series1 = TimeSeries(
238
+ times=idx1,
239
+ values=values1,
240
+ components=self.series1.components,
241
+ **self.series1._attrs,
242
+ )
243
+
244
+ warped_series2 = TimeSeries(
245
+ times=idx2,
246
+ values=values2,
247
+ components=self.series2.components,
248
+ **self.series2._attrs,
249
+ )
250
+
251
+ # todo: prevent time information being lost after warping
252
+ # Applying time index from series1 to series2 (take_dates = True) is disabled for consistency reasons
253
+ # Applying the warp path to the dates directly will result in duplicate dates
254
+ # and hence values being lost when converting back to a TimeSeries.
255
+ # As a result series1 will not be warped, whereas series2 will be.
256
+ # It could also cause the two series to have different lengths, if len(series1) < len(series2)
257
+ # One could generate intermediate dates, but then the series would not have a consistent frequency
258
+ return warped_series1, warped_series2
259
+
260
+
261
+ def dtw(
262
+ series1: TimeSeries,
263
+ series2: TimeSeries,
264
+ window: Window | None = None,
265
+ distance: DistanceFunc | None = None,
266
+ multi_grid_radius: int = -1,
267
+ ) -> DTWAlignment:
268
+ """
269
+ Determines the optimal alignment between two time series `series1` and `series2`, according to the Dynamic Time
270
+ Warping algorithm.
271
+ The alignment minimizes the distance between pair-wise elements after warping.
272
+ All elements in the two series are matched and are in strictly monotonically increasing order.
273
+ Considers only the values in the series, ignoring the time axis.
274
+
275
+ Dynamic Time Warping can be applied to determine how closely two time series correspond,
276
+ irrespective of phase, length or speed differences.
277
+
278
+ Parameters
279
+ ----------
280
+ series1
281
+ A `TimeSeries` to align with `series2`.
282
+ series2
283
+ A `TimeSeries` to align with `series1`.
284
+ window
285
+ Optionally, a `Window` used to constrain the search for the optimal alignment: see `SakoeChiba` and `Itakura`.
286
+ Default considers all possible alignments (`NoWindow`).
287
+ distance
288
+ Function taking as input either two `floats` for univariate series or two `np.ndarray`,
289
+ and returning the distance between them.
290
+
291
+ Defaults to the abs difference for univariate-data and the
292
+ sum of the abs difference for multi-variate series.
293
+ multi_grid_radius
294
+ Default radius of `-1` results in an exact evaluation of the dynamic time warping algorithm.
295
+ Without constraints DTW runs in O(nxm) time where n,m are the size of the series.
296
+ Exact evaluation with no constraints, will result in a performance warning on large datasets.
297
+
298
+ Setting `multi_grid_radius` to a value other than `-1`, will enable the approximate multi-grid solver,
299
+ which executes in linear time, vs quadratic time for exact evaluation.
300
+ Increasing radius trades solution accuracy for performance.
301
+
302
+ Returns
303
+ -------
304
+ DTWAlignment
305
+ Helper object for getting warp path, mean_distance, distance and warped time series
306
+ """
307
+ if window is None:
308
+ window = NoWindow()
309
+
310
+ if (
311
+ multi_grid_radius == -1
312
+ and type(window) is NoWindow
313
+ and len(series1) * len(series2) > 10**6
314
+ ):
315
+ logger.warning(
316
+ "Exact evaluation will result in poor performance on large datasets."
317
+ " Consider enabling multi-grid or using a window."
318
+ )
319
+
320
+ both_univariate = series1.is_univariate and series2.is_univariate
321
+
322
+ if distance is None:
323
+ if series1.n_components != series2.n_components:
324
+ raise_log(
325
+ ValueError(
326
+ "Expected series to have same number of components, or to supply custom distance function."
327
+ ),
328
+ )
329
+
330
+ distance = _default_distance_uni if both_univariate else _default_distance_multi
331
+
332
+ if both_univariate:
333
+ values_x = series1.univariate_values(copy=False)
334
+ values_y = series2.univariate_values(copy=False)
335
+ else:
336
+ values_x = series1.values(copy=False)
337
+ values_y = series2.values(copy=False)
338
+
339
+ if np.any(np.isnan(values_x)):
340
+ raise_log(
341
+ ValueError(
342
+ "Dynamic Time Warping does not support nan values. "
343
+ "You can use the module darts.utils.missing_values to fill them, "
344
+ "before passing them to dtw."
345
+ ),
346
+ )
347
+ if np.any(np.isnan(values_y)):
348
+ raise_log(
349
+ ValueError(
350
+ "Dynamic Time Warping does not support nan values. "
351
+ "You can use the module darts.utils.missing_values to fill them,"
352
+ "before passing it into dtw."
353
+ ),
354
+ )
355
+
356
+ window = copy.deepcopy(window)
357
+ window.init_size(len(values_x), len(values_y))
358
+
359
+ if multi_grid_radius < -1:
360
+ raise_log(
361
+ ValueError("Expected multi-grid radius to be positive or -1."),
362
+ )
363
+
364
+ if multi_grid_radius >= 0:
365
+ if not isinstance(window, NoWindow):
366
+ raise_log(
367
+ ValueError("Multi-grid solver does not currently support windows."),
368
+ )
369
+ cost_matrix = _fast_dtw(values_x, values_y, distance, multi_grid_radius)
370
+ else:
371
+ cost_matrix = _dtw_cost_matrix(values_x, values_y, distance, window)
372
+
373
+ return DTWAlignment(series1, series2, cost_matrix)
datasets/raw/darts_benchmark_datasets/darts/dataprocessing/encoders/encoders.py ADDED
@@ -0,0 +1,1622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Time Axes Encoders
3
+ ------------------
4
+
5
+ Encoders can generate past and/or future covariates series by encoding the index of a TimeSeries `series`.
6
+ Each encoder class has methods `encode_train()`, `encode_inference()`, and `encode_train_inference()` to generate the
7
+ encodings for training and inference.
8
+
9
+ The encoders extract the index either from the target series or optional additional past/future covariates.
10
+ If additional covariates are supplied to `encode_train()`, `encode_inference()`, or `encode_train_inference()`,
11
+ the time index of those covariates are used for the encodings. This means that the input covariates must meet the same
12
+ model-specific requirements as without encoders.
13
+
14
+ There are two main types of encoder classes: `SingleEncoder` and `SequentialEncoder`.
15
+
16
+ * SingleEncoder
17
+ The SingleEncoder classes carry the encoder logic for past and future covariates, and training and
18
+ inference datasets. They can be used as stand-alone encoders.
19
+
20
+ Each SingleEncoder has a dedicated subclass for generating past or future covariates. The naming convention
21
+ is `{X}{SingleEncoder}` where {X} is one of (Past, Future) and {SingleEncoder} is one of the SingleEncoder
22
+ classes described in the next section. An example:
23
+
24
+ .. highlight:: python
25
+ .. code-block:: python
26
+
27
+ encoder = PastDatetimeAttributeEncoder(
28
+ input_chunk_length=24,
29
+ output_chunk_length=12,
30
+ attribute='month'
31
+ tz='CET'
32
+ )
33
+
34
+ past_covariates_train = encoder.encode_train(
35
+ target=target,
36
+ covariates=optional_past_covariates
37
+ )
38
+ past_covariates_inf = encoder.encode_inference(
39
+ n=12,
40
+ target=target,
41
+ covariates=optional_past_covariates
42
+ )
43
+ # or generate encodings for train and inference together
44
+ past_covariates_train_inf = encoder.encode_train_inference(
45
+ n=12,
46
+ target=target,
47
+ covariates=optional_past_covariates
48
+ )
49
+
50
+ * SequentialEncoder
51
+ Stores and controls multiple SingleEncoders for both past and/or future covariates all under one hood.
52
+ It provides the same functionality as SingleEncoders (`encode_train()`, `encode_inference()`, and
53
+ `encode_train_inference()`).
54
+ It can be used both as stand-alone or as an all-in-one solution with Darts' forecasting models that support
55
+ covariates through optional parameter `add_encoders`:
56
+
57
+ .. highlight:: python
58
+ .. code-block:: python
59
+
60
+ model = SomeForecastingModel(..., add_encoders={...})
61
+ ..
62
+
63
+ If used at model creation, the SequentialEncoder will handle all past and future encoders autonomously.
64
+ The requirements for model parameter `add_encoders` are described in the next section or in
65
+ :meth:`SequentialEncoder <darts.dataprocessing.encoders.SequentialEncoder>`.
66
+
67
+ SingleEncoder
68
+ -------------
69
+
70
+ The SingleEncoders from {X}{SingleEncoder} are:
71
+
72
+ * `DatetimeAttributeEncoder`
73
+ Adds scalar pd.DatatimeIndex attribute information derived from `series.time_index`.
74
+ Requires `series` to have a pd.DatetimeIndex.
75
+
76
+ attribute
77
+ An attribute of `pd.DatetimeIndex`: see all available attributes in
78
+ https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.html#pandas.DatetimeIndex.
79
+ tz
80
+ Optionally, convert the time zone naive index to a time zone `tz` before applying the encoder.
81
+ * `CyclicTemporalEncoder`
82
+ Adds cyclic pd.DatetimeIndex attribute information deriveed from `series.time_index`.
83
+ Adds 2 columns, corresponding to sin and cos encodings, to uniquely describe the underlying attribute.
84
+ Requires `series` to have a pd.DatetimeIndex.
85
+
86
+ attribute
87
+ An attribute of `pd.DatetimeIndex` that follows a cyclic pattern. One of ('month', 'day', 'weekday',
88
+ 'dayofweek', 'day_of_week', 'hour', 'minute', 'second', 'microsecond', 'nanosecond', 'quarter',
89
+ 'dayofyear', 'day_of_year', 'week', 'weekofyear', 'week_of_year').
90
+ tz
91
+ Optionally, convert the time zone naive index to a time zone `tz` before applying the encoder.
92
+ * `IntegerIndexEncoder`
93
+ Adds the relative index positions as integer values (positions) derived from `series` time index.
94
+ `series` can either have a pd.DatetimeIndex or an integer index.
95
+
96
+ attribute
97
+ Currently, only 'relative' is supported.
98
+ 'relative' will generate position values relative to the forecasting/prediction point. Values range
99
+ from -inf to inf where 0 is set at the forecasting point.
100
+ * `CallableIndexEncoder`
101
+ Applies a user-defined callable to encode `series`' index.
102
+ `series` can either have a pd.DatetimeIndex or an integer index.
103
+
104
+ attribute
105
+ a callable/function to encode the index.
106
+ For `series` with a pd.DatetimeIndex: ``lambda index: (index.year - 1950) / 50``.
107
+ For `series` with an integer index: ``lambda index: index / 50``
108
+
109
+ SequentialEncoder
110
+ -----------------
111
+
112
+ The SequentialEncoder combines the logic of all SingleEncoders from above and has additional benefits:
113
+
114
+ * use multiple encoders at once
115
+ * generate multiple attribute encodings at once
116
+ * generate both past and future at once
117
+ * supports transformers (Scaler)
118
+ * easy to use with any forecasting model that supports covariates.
119
+
120
+ The model parameter `add_encoders` must be a Dict following of this convention:
121
+
122
+ * outer keys: `SingleEncoder` and Transformer tags:
123
+
124
+ * 'datetime_attribute' for `DatetimeAttributeEncoder`
125
+ * 'cyclic' for `CyclicEncoder`
126
+ * 'position' for `IntegerIndexEncoder`
127
+ * 'custom' for `CallableIndexEncoder`
128
+ * 'transformer' for a transformer
129
+ * 'tz' for applying a time zone conversion
130
+ * inner keys: covariates type
131
+
132
+ * 'past' for past covariates
133
+ * 'future' for future covariates
134
+ * (do not specify for 'transformer')
135
+ * inner key values:
136
+
137
+ * list of attributes for `SingleEncoder`
138
+ * transformer object for 'transformer'
139
+
140
+ Below is an example that illustrates a valid `add_encoders` dict for hourly data and how it can be used with a
141
+ TorchForecastingModel (this is only meant to illustrate many features at once).
142
+
143
+ .. highlight:: python
144
+ .. code-block:: python
145
+
146
+ add_encoders = {
147
+ 'cyclic': {'future': ['month']},
148
+ 'datetime_attribute': {'future': ['hour', 'dayofweek']},
149
+ 'position': {'past': ['relative'], 'future': ['relative']},
150
+ 'custom': {'past': [lambda idx: (idx.year - 1950) / 50]},
151
+ 'transformer': Scaler(),
152
+ 'tz': 'CET',
153
+ }
154
+
155
+ model = SomeTorchForecastingModel(..., add_encoders=add_encoders)
156
+ ..
157
+ """
158
+
159
+ import contextlib
160
+ import copy
161
+ from collections.abc import Callable, Sequence
162
+
163
+ import numpy as np
164
+ import pandas as pd
165
+
166
+ from darts import TimeSeries, concatenate
167
+ from darts.dataprocessing.encoders.encoder_base import (
168
+ CovariatesIndexGenerator,
169
+ Encoder,
170
+ FutureCovariatesIndexGenerator,
171
+ PastCovariatesIndexGenerator,
172
+ SequentialEncoderTransformer,
173
+ SingleEncoder,
174
+ _EncoderMethod,
175
+ )
176
+ from darts.dataprocessing.transformers import FittableDataTransformer
177
+ from darts.logging import get_logger, raise_log
178
+ from darts.timeseries import DIMS
179
+ from darts.typing import TimeIndex, TimeSeriesLike, TimeZone
180
+ from darts.utils.timeseries_generation import datetime_attribute_timeseries
181
+ from darts.utils.ts_utils import seq2series, series2seq
182
+ from darts.utils.utils import generate_index
183
+
184
+ SupportedTimeSeries = TimeSeriesLike
185
+
186
+ logger = get_logger(__name__)
187
+
188
+ ENCODER_KEYS = ["cyclic", "datetime_attribute", "position", "custom"]
189
+ FUTURE = "future"
190
+ PAST = "past"
191
+ VALID_TIME_PARAMS = [FUTURE, PAST]
192
+ VALID_ENCODER_DTYPES = (str, Sequence)
193
+
194
+ TZ_KEYS = ["tz"]
195
+ TRANSFORMER_KEYS = ["transformer"]
196
+ VALID_TRANSFORMER_DTYPES = FittableDataTransformer
197
+ INTEGER_INDEX_ATTRIBUTES = ["relative"]
198
+
199
+
200
+ class CyclicTemporalEncoder(SingleEncoder):
201
+ """`CyclicTemporalEncoder`: Cyclic encoding of time series datetime attributes."""
202
+
203
+ def __init__(
204
+ self,
205
+ index_generator: CovariatesIndexGenerator,
206
+ attribute: str,
207
+ tz: TimeZone = None,
208
+ ):
209
+ """
210
+ Cyclic index encoding for `TimeSeries` that have a time index of type `pd.DatetimeIndex`.
211
+
212
+ Parameters
213
+ ----------
214
+ index_generator
215
+ An instance of `CovariatesIndexGenerator` with methods `generate_train_idx()` and
216
+ `generate_inference_idx()`. Used to generate the index for encoders.
217
+ attribute
218
+ The attribute of the underlying pd.DatetimeIndex from for which to apply cyclic encoding.
219
+ Must be an attribute of `pd.DatetimeIndex`, or `week` / `weekofyear` / `week_of_year` - e.g. "month",
220
+ "weekday", "day", "hour", "minute", "second". See all available attributes in
221
+ https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.html#pandas.DatetimeIndex.
222
+ For more information, check out :meth:`datetime_attribute_timeseries()
223
+ <darts.utils.timeseries_generation.datetime_attribute_timeseries>`
224
+ tz
225
+ Optionally, a time zone to convert the time index before computing attributes.
226
+ Supports any type handled by pandas
227
+ `tz_convert <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.tz_convert.html>`__.
228
+ """
229
+ super().__init__(index_generator)
230
+ self.attribute = attribute
231
+ self.tz = tz
232
+
233
+ def _encode(
234
+ self, index: TimeIndex, target_end: pd.Timestamp, dtype: np.dtype
235
+ ) -> TimeSeries:
236
+ """applies cyclic encoding from `datetime_attribute_timeseries()` to `self.attribute` of `index`."""
237
+ super()._encode(index, target_end, dtype)
238
+ return datetime_attribute_timeseries(
239
+ index,
240
+ attribute=self.attribute,
241
+ cyclic=True,
242
+ dtype=dtype,
243
+ with_columns=[
244
+ self.base_component_name + self.attribute + "_sin",
245
+ self.base_component_name + self.attribute + "_cos",
246
+ ],
247
+ tz=self.tz,
248
+ )
249
+
250
+ @property
251
+ def accept_transformer(self) -> list[bool]:
252
+ """`CyclicTemporalEncoder` should not be transformed. Returns two elements for sine and cosine waves."""
253
+ return [False, False]
254
+
255
+ @property
256
+ def requires_fit(self) -> bool:
257
+ return False
258
+
259
+ @property
260
+ def base_component_name(self) -> str:
261
+ return super().base_component_name + "_cyc_"
262
+
263
+ @property
264
+ def encoding_n_components(self) -> int:
265
+ return 2
266
+
267
+
268
+ class PastCyclicEncoder(CyclicTemporalEncoder):
269
+ """`CyclicEncoder`: Cyclic encoding of past covariates datetime attributes."""
270
+
271
+ def __init__(
272
+ self,
273
+ attribute: str,
274
+ input_chunk_length: int | None = None,
275
+ output_chunk_length: int | None = None,
276
+ lags_covariates: list[int] | None = None,
277
+ tz: TimeZone = None,
278
+ ):
279
+ """
280
+ Parameters
281
+ ----------
282
+ attribute
283
+ The attribute of the underlying pd.DatetimeIndex from for which to apply cyclic encoding.
284
+ Must be an attribute of `pd.DatetimeIndex`, or `week` / `weekofyear` / `week_of_year` - e.g. "month",
285
+ "weekday", "day", "hour", "minute", "second". See all available attributes in
286
+ https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.html#pandas.DatetimeIndex.
287
+ For more information, check out :meth:`datetime_attribute_timeseries()
288
+ <darts.utils.timeseries_generation.datetime_attribute_timeseries>`
289
+ input_chunk_length
290
+ Optionally, the number of input target time steps per chunk. Only required for
291
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
292
+ Corresponds to parameter `input_chunk_length` from :class:`TorchForecastingModel`, or to the absolute
293
+ minimum target lag value `abs(min(lags))` for :class:`SKLearnModel`.
294
+ output_chunk_length
295
+ Optionally, the number of output target time steps per chunk. Only required for
296
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
297
+ Corresponds to parameter `output_chunk_length` from both :class:`TorchForecastingModel`, and
298
+ :class:`SKLearnModel`.
299
+ lags_covariates
300
+ Optionally, a list of integers representing the past covariate lags. Accepts integer lag values <= -1.
301
+ Only required for :class:`SKLearnModel`.
302
+ Corresponds to the lag values from parameter `lags_past_covariates` of :class:`SKLearnModel`.
303
+ tz
304
+ Optionally, a time zone to convert the time index before computing attributes.
305
+ Supports any type handled by pandas
306
+ `tz_convert <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.tz_convert.html>`__.
307
+ """
308
+ super().__init__(
309
+ index_generator=PastCovariatesIndexGenerator(
310
+ input_chunk_length,
311
+ output_chunk_length,
312
+ lags_covariates=lags_covariates,
313
+ ),
314
+ attribute=attribute,
315
+ tz=tz,
316
+ )
317
+
318
+
319
+ class FutureCyclicEncoder(CyclicTemporalEncoder):
320
+ """`CyclicEncoder`: Cyclic encoding of future covariates datetime attributes."""
321
+
322
+ def __init__(
323
+ self,
324
+ attribute: str,
325
+ input_chunk_length: int | None = None,
326
+ output_chunk_length: int | None = None,
327
+ lags_covariates: list[int] | None = None,
328
+ tz: TimeZone = None,
329
+ ):
330
+ """
331
+ Parameters
332
+ ----------
333
+ attribute
334
+ The attribute of the underlying pd.DatetimeIndex from for which to apply cyclic encoding.
335
+ Must be an attribute of `pd.DatetimeIndex`, or `week` / `weekofyear` / `week_of_year` - e.g. "month",
336
+ "weekday", "day", "hour", "minute", "second". See all available attributes in
337
+ https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.html#pandas.DatetimeIndex.
338
+ For more information, check out :meth:`datetime_attribute_timeseries()
339
+ <darts.utils.timeseries_generation.datetime_attribute_timeseries>`
340
+ input_chunk_length
341
+ Optionally, the number of input target time steps per chunk. Only required for
342
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
343
+ Corresponds to parameter `input_chunk_length` from :class:`TorchForecastingModel`, or to the absolute
344
+ minimum target lag value `abs(min(lags))` for :class:`SKLearnModel`.
345
+ output_chunk_length
346
+ Optionally, the number of output target time steps per chunk. Only required for
347
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
348
+ Corresponds to parameter `output_chunk_length` from both :class:`TorchForecastingModel`, and
349
+ :class:`SKLearnModel`.
350
+ lags_covariates
351
+ Optionally, a list of integers representing the future covariate lags. Accepts all integer values.
352
+ Only required for :class:`SKLearnModel`.
353
+ Corresponds to the lag values from parameter `lags_future_covariates` from :class:`SKLearnModel`.
354
+ tz
355
+ Optionally, a time zone to convert the time index before computing attributes.
356
+ Supports any type handled by pandas
357
+ `tz_convert <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.tz_convert.html>`__.
358
+ """
359
+ super().__init__(
360
+ index_generator=FutureCovariatesIndexGenerator(
361
+ input_chunk_length,
362
+ output_chunk_length,
363
+ lags_covariates=lags_covariates,
364
+ ),
365
+ attribute=attribute,
366
+ tz=tz,
367
+ )
368
+
369
+
370
+ class DatetimeAttributeEncoder(SingleEncoder):
371
+ """`DatetimeAttributeEncoder`: Adds pd.DatatimeIndex attribute information derived from the index as scalars.
372
+ Requires the underlying TimeSeries to have a pd.DatetimeIndex
373
+ """
374
+
375
+ def __init__(
376
+ self,
377
+ index_generator: CovariatesIndexGenerator,
378
+ attribute: str,
379
+ tz: TimeZone = None,
380
+ ):
381
+ """
382
+ Parameters
383
+ ----------
384
+ index_generator
385
+ An instance of `CovariatesIndexGenerator` with methods `generate_train_idx()` and
386
+ `generate_inference_idx()`. Used to generate the index for encoders.
387
+ attribute
388
+ The attribute of the underlying pd.DatetimeIndex for which to add scalar information.
389
+ Must be an attribute of `pd.DatetimeIndex`, or `week` / `weekofyear` / `week_of_year` - e.g. "month",
390
+ "weekday", "day", "hour", "minute", "second". See all available attributes in
391
+ https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.html#pandas.DatetimeIndex.
392
+ For more information, check out :meth:`datetime_attribute_timeseries()
393
+ <darts.utils.timeseries_generation.datetime_attribute_timeseries>`
394
+ tz
395
+ Optionally, a time zone to convert the time index before computing attributes.
396
+ Supports any type handled by pandas
397
+ `tz_convert <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.tz_convert.html>`__.
398
+ """
399
+ super().__init__(index_generator)
400
+ self.attribute = attribute
401
+ self.tz = tz
402
+
403
+ def _encode(
404
+ self, index: TimeIndex, target_end: pd.Timestamp, dtype: np.dtype
405
+ ) -> TimeSeries:
406
+ """Encode `index` as a scalar."""
407
+ super()._encode(index, target_end, dtype)
408
+ return datetime_attribute_timeseries(
409
+ index,
410
+ attribute=self.attribute,
411
+ dtype=dtype,
412
+ with_columns=self.base_component_name + self.attribute,
413
+ tz=self.tz,
414
+ )
415
+
416
+ @property
417
+ def accept_transformer(self) -> list[bool]:
418
+ """`DatetimeAttributeEncoder` accepts transformations"""
419
+ return [True]
420
+
421
+ @property
422
+ def requires_fit(self) -> bool:
423
+ return False
424
+
425
+ @property
426
+ def base_component_name(self) -> str:
427
+ return super().base_component_name + "_dta_"
428
+
429
+ @property
430
+ def encoding_n_components(self) -> int:
431
+ return 1
432
+
433
+
434
+ class PastDatetimeAttributeEncoder(DatetimeAttributeEncoder):
435
+ """Datetime attribute encoder for past covariates."""
436
+
437
+ def __init__(
438
+ self,
439
+ attribute: str,
440
+ input_chunk_length: int | None = None,
441
+ output_chunk_length: int | None = None,
442
+ lags_covariates: list[int] | None = None,
443
+ tz: TimeZone = None,
444
+ ):
445
+ """
446
+ Parameters
447
+ ----------
448
+ attribute
449
+ The attribute of the underlying pd.DatetimeIndex for which to add scalar information.
450
+ Must be an attribute of `pd.DatetimeIndex`, or `week` / `weekofyear` / `week_of_year` - e.g. "month",
451
+ "weekday", "day", "hour", "minute", "second". See all available attributes in
452
+ https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.html#pandas.DatetimeIndex.
453
+ For more information, check out :meth:`datetime_attribute_timeseries()
454
+ <darts.utils.timeseries_generation.datetime_attribute_timeseries>`
455
+ input_chunk_length
456
+ Optionally, the number of input target time steps per chunk. Only required for
457
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
458
+ Corresponds to parameter `input_chunk_length` from :class:`TorchForecastingModel`, or to the absolute
459
+ minimum target lag value `abs(min(lags))` for :class:`SKLearnModel`.
460
+ output_chunk_length
461
+ Optionally, the number of output target time steps per chunk. Only required for
462
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
463
+ Corresponds to parameter `output_chunk_length` from both :class:`TorchForecastingModel`, and
464
+ :class:`SKLearnModel`.
465
+ lags_covariates
466
+ Optionally, a list of integers representing the past covariate lags. Accepts integer lag values <= -1.
467
+ Only required for :class:`SKLearnModel`.
468
+ Corresponds to the lag values from parameter `lags_past_covariates` of :class:`SKLearnModel`.
469
+ tz
470
+ Optionally, a time zone to convert the time index before computing attributes.
471
+ Supports any type handled by pandas
472
+ `tz_convert <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.tz_convert.html>`__.
473
+ """
474
+ super().__init__(
475
+ index_generator=PastCovariatesIndexGenerator(
476
+ input_chunk_length,
477
+ output_chunk_length,
478
+ lags_covariates=lags_covariates,
479
+ ),
480
+ attribute=attribute,
481
+ tz=tz,
482
+ )
483
+
484
+
485
+ class FutureDatetimeAttributeEncoder(DatetimeAttributeEncoder):
486
+ """Datetime attribute encoder for future covariates."""
487
+
488
+ def __init__(
489
+ self,
490
+ attribute: str,
491
+ input_chunk_length: int | None = None,
492
+ output_chunk_length: int | None = None,
493
+ lags_covariates: list[int] | None = None,
494
+ tz: TimeZone = None,
495
+ ):
496
+ """
497
+ Parameters
498
+ ----------
499
+ attribute
500
+ The attribute of the underlying pd.DatetimeIndex for which to add scalar information.
501
+ Must be an attribute of `pd.DatetimeIndex`, or `week` / `weekofyear` / `week_of_year` - e.g. "month",
502
+ "weekday", "day", "hour", "minute", "second". See all available attributes in
503
+ https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.html#pandas.DatetimeIndex.
504
+ For more information, check out :meth:`datetime_attribute_timeseries()
505
+ <darts.utils.timeseries_generation.datetime_attribute_timeseries>`
506
+ input_chunk_length
507
+ Optionally, the number of input target time steps per chunk. Only required for
508
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
509
+ Corresponds to parameter `input_chunk_length` from :class:`TorchForecastingModel`, or to the absolute
510
+ minimum target lag value `abs(min(lags))` for :class:`SKLearnModel`.
511
+ output_chunk_length
512
+ Optionally, the number of output target time steps per chunk. Only required for
513
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
514
+ Corresponds to parameter `output_chunk_length` from both :class:`TorchForecastingModel`, and
515
+ :class:`SKLearnModel`.
516
+ lags_covariates
517
+ Optionally, a list of integers representing the future covariate lags. Accepts all integer values.
518
+ Only required for :class:`SKLearnModel`.
519
+ Corresponds to the lag values from parameter `lags_future_covariates` from :class:`SKLearnModel`.
520
+ tz
521
+ Optionally, a time zone to convert the time index before computing attributes.
522
+ Supports any type handled by pandas
523
+ `tz_convert <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.tz_convert.html>`__.
524
+ """
525
+ super().__init__(
526
+ index_generator=FutureCovariatesIndexGenerator(
527
+ input_chunk_length,
528
+ output_chunk_length,
529
+ lags_covariates=lags_covariates,
530
+ ),
531
+ attribute=attribute,
532
+ tz=tz,
533
+ )
534
+
535
+
536
+ class IntegerIndexEncoder(SingleEncoder):
537
+ """IntegerIndexEncoder: Adds integer index value (position) derived from the underlying TimeSeries' time index
538
+ for past and future covariates.
539
+ """
540
+
541
+ def __init__(self, index_generator: CovariatesIndexGenerator, attribute: str):
542
+ """
543
+ Parameters
544
+ ----------
545
+ index_generator
546
+ An instance of `CovariatesIndexGenerator` with methods `generate_train_idx()` and
547
+ `generate_inference_idx()`. Used to generate the index for encoders.
548
+ attribute
549
+ Currently only 'relative' is supported. The generated encoded values will range from (-inf, inf) and the
550
+ target series end time will be used as a reference to evaluate the relative index positions.
551
+ """
552
+ if not (isinstance(attribute, str) and attribute in INTEGER_INDEX_ATTRIBUTES):
553
+ raise_log(
554
+ ValueError(
555
+ f"Encountered invalid encoder argument `{attribute}` for encoder `position`. "
556
+ f'Attribute must be `"relative"`.'
557
+ ),
558
+ )
559
+ super().__init__(index_generator)
560
+
561
+ self.attribute = attribute
562
+
563
+ def _encode(
564
+ self, index: TimeIndex, target_end: pd.Timestamp, dtype: np.dtype
565
+ ) -> TimeSeries:
566
+ """Adds integer index value (position) to the provided `index`.
567
+ For attribute=='relative', the reference point/index is the prediction/forecast index of the target series.
568
+ """
569
+ super()._encode(index, target_end, dtype)
570
+
571
+ idx_larger_end = (index <= target_end).sum()
572
+ freq = index.freq if isinstance(index, pd.DatetimeIndex) else index.step
573
+ if idx_larger_end:
574
+ idx_larger_end -= 1
575
+ if index[0] > target_end:
576
+ idx_diff = (
577
+ len(generate_index(start=target_end, end=index[0], freq=freq)) - 1
578
+ )
579
+ elif index[-1] < target_end:
580
+ idx_diff = (
581
+ -len(generate_index(start=index[-1], end=target_end, freq=freq)) + 1
582
+ )
583
+ else:
584
+ idx_diff = 0
585
+ return TimeSeries(
586
+ times=index,
587
+ values=np.arange(
588
+ start=idx_diff - idx_larger_end,
589
+ stop=idx_diff - idx_larger_end + len(index),
590
+ dtype=np.dtype(dtype),
591
+ ),
592
+ components=[self.base_component_name + self.attribute],
593
+ copy=False,
594
+ )
595
+
596
+ @property
597
+ def accept_transformer(self) -> list[bool]:
598
+ """`IntegerIndexEncoder` accepts transformations. Note that transforming 'relative' `IntegerIndexEncoder`
599
+ will return the absolute position (in the transformed space)."""
600
+ return [True]
601
+
602
+ @property
603
+ def requires_fit(self) -> bool:
604
+ # requires fitting to get the reference index from `IntegerIndexEncoder.index_generator` for inference
605
+ return True
606
+
607
+ @property
608
+ def base_component_name(self) -> str:
609
+ return super().base_component_name + "_pos_"
610
+
611
+ @property
612
+ def encoding_n_components(self) -> int:
613
+ return 1
614
+
615
+
616
+ class PastIntegerIndexEncoder(IntegerIndexEncoder):
617
+ """`IntegerIndexEncoder`: Adds integer index value (position) for past covariates derived from the underlying
618
+ TimeSeries' time index.
619
+ """
620
+
621
+ def __init__(
622
+ self,
623
+ attribute: str,
624
+ input_chunk_length: int | None = None,
625
+ output_chunk_length: int | None = None,
626
+ lags_covariates: list[int] | None = None,
627
+ **kwargs,
628
+ ):
629
+ """
630
+ Parameters
631
+ ----------
632
+ attribute
633
+ Currently only 'relative' is supported. The generated encoded values will range from (-inf, inf) and the
634
+ target series end time will be used as a reference to evaluate the relative index positions.
635
+ input_chunk_length
636
+ Optionally, the number of input target time steps per chunk. Only required for
637
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
638
+ Corresponds to parameter `input_chunk_length` from :class:`TorchForecastingModel`, or to the absolute
639
+ minimum target lag value `abs(min(lags))` for :class:`SKLearnModel`.
640
+ output_chunk_length
641
+ Optionally, the number of output target time steps per chunk. Only required for
642
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
643
+ Corresponds to parameter `output_chunk_length` from both :class:`TorchForecastingModel`, and
644
+ :class:`SKLearnModel`.
645
+ lags_covariates
646
+ Optionally, a list of integers representing the past covariate lags. Accepts integer lag values <= -1.
647
+ Only required for :class:`SKLearnModel`.
648
+ Corresponds to the lag values from parameter `lags_past_covariates` of :class:`SKLearnModel`.
649
+ """
650
+ super().__init__(
651
+ index_generator=PastCovariatesIndexGenerator(
652
+ input_chunk_length,
653
+ output_chunk_length,
654
+ lags_covariates=lags_covariates,
655
+ ),
656
+ attribute=attribute,
657
+ )
658
+
659
+
660
+ class FutureIntegerIndexEncoder(IntegerIndexEncoder):
661
+ """`IntegerIndexEncoder`: Adds integer index value (position) for future covariates derived from the underlying
662
+ TimeSeries' time index.
663
+ """
664
+
665
+ def __init__(
666
+ self,
667
+ attribute: str,
668
+ input_chunk_length: int | None = None,
669
+ output_chunk_length: int | None = None,
670
+ lags_covariates: list[int] | None = None,
671
+ **kwargs,
672
+ ):
673
+ """
674
+ Parameters
675
+ ----------
676
+ attribute
677
+ Currently only 'relative' is supported. The generated encoded values will range from (-inf, inf) and the
678
+ target series end time will be used as a reference to evaluate the relative index positions.
679
+ input_chunk_length
680
+ Optionally, the number of input target time steps per chunk. Only required for
681
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
682
+ Corresponds to parameter `input_chunk_length` from :class:`TorchForecastingModel`, or to the absolute
683
+ minimum target lag value `abs(min(lags))` for :class:`SKLearnModel`.
684
+ output_chunk_length
685
+ Optionally, the number of output target time steps per chunk. Only required for
686
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
687
+ Corresponds to parameter `output_chunk_length` from both :class:`TorchForecastingModel`, and
688
+ :class:`SKLearnModel`.
689
+ lags_covariates
690
+ Optionally, a list of integers representing the future covariate lags. Accepts all integer values.
691
+ Only required for :class:`SKLearnModel`.
692
+ Corresponds to the lag values from parameter `lags_future_covariates` from :class:`SKLearnModel`.
693
+ """
694
+ super().__init__(
695
+ index_generator=FutureCovariatesIndexGenerator(
696
+ input_chunk_length,
697
+ output_chunk_length,
698
+ lags_covariates=lags_covariates,
699
+ ),
700
+ attribute=attribute,
701
+ )
702
+
703
+
704
+ class CallableIndexEncoder(SingleEncoder):
705
+ """`CallableIndexEncoder`: Applies a user-defined callable to encode the underlying index for past and future
706
+ covariates.
707
+ """
708
+
709
+ def __init__(self, index_generator: CovariatesIndexGenerator, attribute: Callable):
710
+ """
711
+ Parameters
712
+ ----------
713
+ index_generator
714
+ An instance of `CovariatesIndexGenerator` with methods `generate_train_idx()` and
715
+ `generate_inference_idx()`. Used to generate the index for encoders.
716
+ attribute
717
+ A callable that takes an index `index` of type `(pd.DatetimeIndex, pd.RangeIndex)` as input
718
+ and returns a `np.ndarray` of shape `(len(index),)` or `(len(index), n_output_components)`.
719
+ Examples for a correct `attribute` for `index` of type `pd.DatetimeIndex`:
720
+ ``attribute = lambda index: (index.year - 1950) / 50``
721
+ ``attribute = lambda index: np.stack([index.year, index.month], axis=1)``
722
+ And for `pd.RangeIndex`:
723
+ ``attribute = lambda index: (index - 1950) / 50``
724
+ """
725
+ if not callable(attribute):
726
+ raise_log(
727
+ ValueError(
728
+ f"Encountered invalid encoder argument `{attribute}` for encoder `callable`. "
729
+ f"Attribute must be a callable that returns a `np.ndarray`."
730
+ ),
731
+ )
732
+
733
+ super().__init__(index_generator)
734
+
735
+ self.attribute = attribute
736
+ self._n_components = self._detect_n_components(attribute)
737
+
738
+ @staticmethod
739
+ def _detect_n_components(attribute: Callable) -> int:
740
+ """Test the callable with sample `pd.DatetimeIndex` and `pd.RangeIndex` to determine
741
+ the number of output components.
742
+ """
743
+ n_components = None
744
+
745
+ for idx in (
746
+ pd.date_range("2000-01-01", periods=2, freq="D"),
747
+ pd.RangeIndex(2),
748
+ ):
749
+ with contextlib.suppress(Exception):
750
+ encoded = np.asarray(attribute(idx))
751
+ n_components = 1 if encoded.ndim == 1 else encoded.shape[1]
752
+ break
753
+
754
+ if n_components is None:
755
+ raise_log(
756
+ ValueError(
757
+ "Encountered invalid encoder argument for encoder `callable`. "
758
+ "Attribute must be a callable that accepts a `pd.DatetimeIndex` "
759
+ "or `pd.RangeIndex` and returns an array-like of shape "
760
+ "`(len(index),)` or `(len(index), n_output_components)`."
761
+ ),
762
+ )
763
+ return n_components
764
+
765
+ def _encode(
766
+ self, index: TimeIndex, target_end: pd.Timestamp, dtype: np.dtype
767
+ ) -> TimeSeries:
768
+ """Apply the user-defined callable to encode the index."""
769
+ super()._encode(index, target_end, dtype)
770
+
771
+ values = np.array(self.attribute(index), dtype=dtype)
772
+ components = [
773
+ self.base_component_name + ("custom" if i == 0 else f"custom_{i}")
774
+ for i in range(self.encoding_n_components)
775
+ ]
776
+ return TimeSeries(
777
+ times=index,
778
+ values=values,
779
+ components=components,
780
+ copy=False,
781
+ )
782
+
783
+ @property
784
+ def accept_transformer(self) -> list[bool]:
785
+ """`CallableIndexEncoder` accepts transformations."""
786
+ return [True] * self.encoding_n_components
787
+
788
+ @property
789
+ def requires_fit(self) -> bool:
790
+ return False
791
+
792
+ @property
793
+ def base_component_name(self) -> str:
794
+ return super().base_component_name + "_cus_"
795
+
796
+ @property
797
+ def encoding_n_components(self) -> int:
798
+ return self._n_components
799
+
800
+
801
+ class PastCallableIndexEncoder(CallableIndexEncoder):
802
+ """`IntegerIndexEncoder`: Adds integer index value (position) for past covariates derived from the underlying
803
+ TimeSeries' time index.
804
+ """
805
+
806
+ def __init__(
807
+ self,
808
+ attribute: Callable,
809
+ input_chunk_length: int | None = None,
810
+ output_chunk_length: int | None = None,
811
+ lags_covariates: list[int] | None = None,
812
+ **kwargs,
813
+ ):
814
+ """
815
+ Parameters
816
+ ----------
817
+ attribute
818
+ A callable that takes an index `index` of type `(pd.DatetimeIndex, pd.RangeIndex)` as input
819
+ and returns a `np.ndarray` of shape `(len(index),)` or `(len(index), n_output_components)`.
820
+ An example for a correct `attribute` for `index` of type pd.DatetimeIndex:
821
+
822
+ - ``attribute = lambda index: (index.year - 1950) / 50`` or
823
+ - ``attribute = lambda index: np.stack([index.year, index.month], axis=1)``,
824
+
825
+ And for pd.RangeIndex:
826
+
827
+ - ``attribute = lambda index: (index - 1950) / 50``
828
+ input_chunk_length
829
+ Optionally, the number of input target time steps per chunk. Only required for
830
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
831
+ Corresponds to parameter `input_chunk_length` from :class:`TorchForecastingModel`, or to the absolute
832
+ minimum target lag value `abs(min(lags))` for :class:`SKLearnModel`.
833
+ output_chunk_length
834
+ Optionally, the number of output target time steps per chunk. Only required for
835
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
836
+ Corresponds to parameter `output_chunk_length` from both :class:`TorchForecastingModel`, and
837
+ :class:`SKLearnModel`.
838
+ lags_covariates
839
+ Optionally, a list of integers representing the past covariate lags. Accepts integer lag values <= -1.
840
+ Only required for :class:`SKLearnModel`.
841
+ Corresponds to the lag values from parameter `lags_past_covariates` of :class:`SKLearnModel`.
842
+ """
843
+ super().__init__(
844
+ index_generator=PastCovariatesIndexGenerator(
845
+ input_chunk_length,
846
+ output_chunk_length,
847
+ lags_covariates=lags_covariates,
848
+ ),
849
+ attribute=attribute,
850
+ )
851
+
852
+
853
+ class FutureCallableIndexEncoder(CallableIndexEncoder):
854
+ """`IntegerIndexEncoder`: Adds integer index value (position) for future covariates derived from the underlying
855
+ TimeSeries' time index.
856
+ """
857
+
858
+ def __init__(
859
+ self,
860
+ attribute: Callable,
861
+ input_chunk_length: int | None = None,
862
+ output_chunk_length: int | None = None,
863
+ lags_covariates: list[int] | None = None,
864
+ **kwargs,
865
+ ):
866
+ """
867
+ Parameters
868
+ ----------
869
+ attribute
870
+ A callable that takes an index `index` of type `(pd.DatetimeIndex, pd.RangeIndex)` as input
871
+ and returns a `np.ndarray` of shape `(len(index),)` or `(len(index), n_output_components)`.
872
+ An example for a correct `attribute` for `index` of type pd.DatetimeIndex:
873
+
874
+ - ``attribute = lambda index: (index.year - 1950) / 50`` or
875
+ - ``attribute = lambda index: np.stack([index.year, index.month], axis=1)``,
876
+
877
+ And for pd.RangeIndex:
878
+
879
+ - ``attribute = lambda index: (index - 1950) / 50``
880
+ input_chunk_length
881
+ Optionally, the number of input target time steps per chunk. Only required for
882
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
883
+ Corresponds to parameter `input_chunk_length` from :class:`TorchForecastingModel`, or to the absolute
884
+ minimum target lag value `abs(min(lags))` for :class:`SKLearnModel`.
885
+ output_chunk_length
886
+ Optionally, the number of output target time steps per chunk. Only required for
887
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
888
+ Corresponds to parameter `output_chunk_length` from both :class:`TorchForecastingModel`, and
889
+ :class:`SKLearnModel`.
890
+ lags_covariates
891
+ Optionally, a list of integers representing the future covariate lags. Accepts all integer values.
892
+ Only required for :class:`SKLearnModel`.
893
+ Corresponds to the lag values from parameter `lags_future_covariates` from :class:`SKLearnModel`.
894
+ """
895
+ super().__init__(
896
+ index_generator=FutureCovariatesIndexGenerator(
897
+ input_chunk_length,
898
+ output_chunk_length,
899
+ lags_covariates=lags_covariates,
900
+ ),
901
+ attribute=attribute,
902
+ )
903
+
904
+
905
+ class SequentialEncoder(Encoder):
906
+ """A `SequentialEncoder` object can store and control multiple past and future covariates encoders at once.
907
+ It provides the same functionality as single encoders (`encode_train()`, `encode_inference()`,
908
+ `encode_train_inference()`).
909
+ """
910
+
911
+ def __init__(
912
+ self,
913
+ add_encoders: dict,
914
+ input_chunk_length: int | None = None,
915
+ output_chunk_length: int | None = None,
916
+ lags_past_covariates: list[int] | None = None,
917
+ lags_future_covariates: list[int] | None = None,
918
+ takes_past_covariates: bool = False,
919
+ takes_future_covariates: bool = False,
920
+ ) -> None:
921
+ """
922
+ SequentialEncoder automatically creates encoder objects from parameter `add_encoders`. `add_encoders` can also
923
+ be set directly in all of Darts' `ForecastingModels`. This will automatically set up a
924
+ :class:`SequentialEncoder` tailored to the settings of the underlying forecasting model.
925
+
926
+ The `add_encoders` dict must follow this convention:
927
+ `{encoder keyword: {temporal keyword: List[attributes]}, ..., transformer keyword: transformer object}`
928
+ Supported encoder keywords:
929
+ `'cyclic'` for cyclic temporal encoder. See the docs
930
+ :meth:`CyclicTemporalEncoder <darts.dataprocessing.encoders.CyclicTemporalEncoder>`;
931
+ `'datetime_attribute'` for adding scalar information of pd.DatetimeIndex attribute. See the docs
932
+ :meth:`DatetimeAttributeEncoder <darts.dataprocessing.encoders.DatetimeAttributeEncoder>`
933
+ `'position'` for integer index position encoder. See the docs
934
+ :meth:`IntegerIndexEncoder <darts.dataprocessing.encoders.IntegerIndexEncoder>`;
935
+ `'custom'` for encoding index with custom callables (functions). See the docs
936
+ :meth:`CallableIndexEncoder <darts.dataprocessing.encoders.CallableIndexEncoder>`;
937
+ Supported temporal keywords:
938
+ 'past' for adding encoding as past covariates
939
+ 'future' for adding encoding as future covariates
940
+ Supported attributes:
941
+ for attributes read the referred docs for the corresponding encoder from above
942
+ Supported transformers:
943
+ a transformer can be added with transformer keyword 'transformer'. The transformer object must be an
944
+ instance of Darts' :meth:`FittableDataTransformer
945
+ <darts.dataprocessing.transformers.fittable_data_transformer.FittableDataTransformer>` such as Scaler() or
946
+ BoxCox(). The transformers will be fitted on the training dataset when calling calling `model.fit()`.
947
+ The training, validation and inference datasets are then transformed equally.
948
+ Supported time zone:
949
+ Optionally, apply a time zone conversion with keyword 'tz'. This converts the time zone-naive index to a
950
+ timezone `'tz'` before applying the `'cyclic'` or `'datetime_attribute'` temporal encoders.
951
+
952
+ An example of a valid `add_encoders` dict for hourly data:
953
+
954
+ .. highlight:: python
955
+ .. code-block:: python
956
+
957
+ from darts.dataprocessing.transformers import Scaler
958
+ add_encoders={
959
+ 'cyclic': {'future': ['month']},
960
+ 'datetime_attribute': {'past': ['hour'], 'future': ['year', 'dayofweek']},
961
+ 'position': {'past': ['relative'], 'future': ['relative']},
962
+ 'custom': {'past': [lambda idx: (idx.year - 1950) / 50]},
963
+ 'transformer': Scaler(),
964
+ 'tz': 'CET',
965
+ }
966
+
967
+ Tuples of `(encoder_id, attribute)` are extracted from `add_encoders` to instantiate the `SingleEncoder`
968
+ objects:
969
+
970
+ * The `encoder_id` is extracted as follows:
971
+ str(encoder_kw) + str(temporal_kw) -> 'cyclic' + 'past' -> `encoder_id` = 'cyclic_past'
972
+ The `encoder_id` is used to map the parameters with the corresponding `SingleEncoder` objects.
973
+ * The `attribute` is extracted from the values given by values under `temporal_kw`
974
+ `attribute` = 'month'
975
+ ...
976
+ The `attribute` tells the `SingleEncoder` which attribute of the index to encode
977
+
978
+ New encoders can be added by appending them to the mapping property `SequentialEncoder.encoder_map()`
979
+
980
+ Parameters
981
+ ----------
982
+ add_encoders
983
+ A dictionary with the encoder settings.
984
+ input_chunk_length
985
+ Optionally, the number of input target time steps per chunk. Only required for
986
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
987
+ Corresponds to parameter `input_chunk_length` from :class:`TorchForecastingModel`, or to the absolute
988
+ minimum target lag value `abs(min(lags))` for :class:`SKLearnModel`.
989
+ output_chunk_length
990
+ Optionally, the number of output target time steps per chunk. Only required for
991
+ :class:`TorchForecastingModel`, and :class:`SKLearnModel`.
992
+ Corresponds to parameter `output_chunk_length` from both :class:`TorchForecastingModel`, and
993
+ :class:`SKLearnModel`.
994
+ lags_past_covariates
995
+ Optionally, a list of integers representing the past covariate lags. Accepts integer lag values <= -1.
996
+ Only required for :class:`SKLearnModel`.
997
+ Corresponds to the lag values from parameter `lags_past_covariates` of :class:`SKLearnModel`.
998
+ lags_future_covariates
999
+ Optionally, a list of integers representing the future covariate lags. Accepts all integer values.
1000
+ Only required for :class:`SKLearnModel`.
1001
+ Corresponds to the lag values from parameter `lags_future_covariates` from :class:`SKLearnModel`.
1002
+ takes_past_covariates
1003
+ Whether to encode/generate past covariates.
1004
+ takes_future_covariates
1005
+ Whether to encode/generate future covariates.
1006
+ """
1007
+ super().__init__()
1008
+ self.params = add_encoders
1009
+ self.input_chunk_length = input_chunk_length
1010
+ self.output_chunk_length = output_chunk_length
1011
+ self.encoding_available = False
1012
+ self.takes_past_covariates = takes_past_covariates
1013
+ self.takes_future_covariates = takes_future_covariates
1014
+ self.lags_past_covariates = lags_past_covariates
1015
+ self.lags_future_covariates = lags_future_covariates
1016
+
1017
+ # encoders
1018
+ self._past_encoders: list[SingleEncoder] = []
1019
+ self._past_components: pd.Index = pd.Index([])
1020
+ self._future_encoders: list[SingleEncoder] = []
1021
+ self._future_components: pd.Index = pd.Index([])
1022
+
1023
+ # transformer
1024
+ self._past_transformer: SequentialEncoderTransformer | None = None
1025
+ self._future_transformer: SequentialEncoderTransformer | None = None
1026
+
1027
+ # setup encoders and transformer
1028
+ self._setup_encoders(self.params)
1029
+ self._setup_transformer(self.params)
1030
+
1031
+ def encode_train(
1032
+ self,
1033
+ target: SupportedTimeSeries,
1034
+ past_covariates: SupportedTimeSeries | None = None,
1035
+ future_covariates: SupportedTimeSeries | None = None,
1036
+ encode_past: bool = True,
1037
+ encode_future: bool = True,
1038
+ ) -> tuple[TimeSeriesLike, TimeSeriesLike]:
1039
+ """Returns encoded index for all past and/or future covariates for training.
1040
+ Which covariates are generated depends on the parameters used at model creation.
1041
+
1042
+ Parameters
1043
+ ----------
1044
+ target
1045
+ The target TimeSeries used during training or passed to prediction as `series`.
1046
+ past_covariates
1047
+ Optionally, the past covariates used for training.
1048
+ future_covariates
1049
+ Optionally, the future covariates used for training.
1050
+ encode_past
1051
+ Whether to apply encoders for past covariates.
1052
+ encode_future
1053
+ Whether to apply encoders for future covariates.
1054
+ Returns
1055
+ -------
1056
+ Tuple[past_covariates, future_covariates]
1057
+ The past_covariates and/or future_covariates for training including the encodings.
1058
+ If input {x}_covariates is None and no {x}_encoders are given, will return `None`
1059
+ for the {x}_covariates.
1060
+ Raises
1061
+ ------
1062
+ Warning
1063
+ If model was created with `add_encoders` and there is suspicion of lazy loading.
1064
+ The encodings/covariates are generated eagerly before starting training for all individual targets and
1065
+ loaded into memory. Depending on the size of target data, this can create memory
1066
+ issues. In case this applies, consider setting `add_encoders=None` at model
1067
+ creation and build your encodings covariates manually for lazy loading.
1068
+ """
1069
+ if not self.fit_called:
1070
+ if not isinstance(target, TimeSeries | list):
1071
+ logger.warning(
1072
+ "Fitting was called with `add_encoders` and suspicion of lazy loading. "
1073
+ "The encodings/covariates are generated pre-train for all individual targets and "
1074
+ "loaded into memory. Depending on the size of your data, this can create memory issues. "
1075
+ "In case this applies, consider setting `add_encoders=None` at model creation."
1076
+ )
1077
+
1078
+ self._fit_called = True
1079
+ past_covariates, future_covariates = self._launch_encoder(
1080
+ target=target,
1081
+ past_covariates=past_covariates,
1082
+ future_covariates=future_covariates,
1083
+ encoder_method=_EncoderMethod("train"),
1084
+ n=None,
1085
+ encode_past=encode_past,
1086
+ encode_future=encode_future,
1087
+ )
1088
+ self._fit_called = True
1089
+ return past_covariates, future_covariates
1090
+
1091
+ def encode_inference(
1092
+ self,
1093
+ n: int,
1094
+ target: SupportedTimeSeries,
1095
+ past_covariates: SupportedTimeSeries | None = None,
1096
+ future_covariates: SupportedTimeSeries | None = None,
1097
+ encode_past: bool = True,
1098
+ encode_future: bool = True,
1099
+ ) -> tuple[TimeSeriesLike, TimeSeriesLike]:
1100
+ """Returns encoded index for all past and/or future covariates for inference/prediction.
1101
+ Which covariates are generated depends on the parameters used at model creation.
1102
+
1103
+ Parameters
1104
+ ----------
1105
+ n
1106
+ The forecast horizon
1107
+ target
1108
+ The target TimeSeries used during training or passed to prediction as `series`.
1109
+ past_covariates
1110
+ Optionally, the past covariates used for training.
1111
+ future_covariates
1112
+ Optionally, the future covariates used for training.
1113
+ encode_past
1114
+ Whether to apply encoders for past covariates.
1115
+ encode_future
1116
+ Whether to apply encoders for future covariates.
1117
+
1118
+ Returns
1119
+ -------
1120
+ Tuple[past_covariates, future_covariates]
1121
+ The past_covariates and/or future_covariates for prediction/inference including the encodings.
1122
+ If input {x}_covariates is None and no {x}_encoders are given, will return `None`
1123
+ for the {x}_covariates.
1124
+ """
1125
+ if not self.fit_called and self.requires_fit:
1126
+ raise_log(
1127
+ ValueError(
1128
+ f"`{self.__class__.__name__}` contains encoders or transformers which must "
1129
+ f"be trained before inference. Call method `encode_train()` before "
1130
+ f"`encode_inference()`."
1131
+ ),
1132
+ )
1133
+ return self._launch_encoder(
1134
+ target=target,
1135
+ past_covariates=past_covariates,
1136
+ future_covariates=future_covariates,
1137
+ encoder_method=_EncoderMethod("inference"),
1138
+ n=n,
1139
+ encode_past=encode_past,
1140
+ encode_future=encode_future,
1141
+ )
1142
+
1143
+ def encode_train_inference(
1144
+ self,
1145
+ n: int,
1146
+ target: SupportedTimeSeries,
1147
+ past_covariates: SupportedTimeSeries | None = None,
1148
+ future_covariates: SupportedTimeSeries | None = None,
1149
+ encode_past: bool = True,
1150
+ encode_future: bool = True,
1151
+ ) -> tuple[TimeSeriesLike, TimeSeriesLike]:
1152
+ """Returns encoded index for all past and/or future covariates for training and inference/prediction.
1153
+ Which covariates are generated depends on the parameters used at model creation.
1154
+
1155
+ Parameters
1156
+ ----------
1157
+ n
1158
+ The forecast horizon
1159
+ target
1160
+ The target TimeSeries used for training and prediction.
1161
+ past_covariates
1162
+ Optionally, the past covariates used for training and prediction.
1163
+ future_covariates
1164
+ Optionally, the future covariates used for training and prediction.
1165
+ encode_past
1166
+ Whether to apply encoders for past covariates.
1167
+ encode_future
1168
+ Whether to apply encoders for future covariates.
1169
+
1170
+ Returns
1171
+ -------
1172
+ Tuple[past_covariates, future_covariates]
1173
+ The past_covariates and/or future_covariates for prediction/inference including the encodings.
1174
+ If input {x}_covariates is None and no {x}_encoders are given, will return `None`
1175
+ for the {x}_covariates.
1176
+ """
1177
+ if not self.fit_called:
1178
+ if not isinstance(target, TimeSeries | list):
1179
+ logger.warning(
1180
+ "Fitting was called with `add_encoders` and suspicion of lazy loading. "
1181
+ "The encodings/covariates are generated pre-train for all individual targets and "
1182
+ "loaded into memory. Depending on the size of your data, this can create memory issues. "
1183
+ "In case this applies, consider setting `add_encoders=None` at model creation."
1184
+ )
1185
+
1186
+ self._fit_called = True
1187
+ past_covariates, future_covariates = self._launch_encoder(
1188
+ target=target,
1189
+ past_covariates=past_covariates,
1190
+ future_covariates=future_covariates,
1191
+ encoder_method=_EncoderMethod("train_inference"),
1192
+ n=n,
1193
+ encode_past=encode_past,
1194
+ encode_future=encode_future,
1195
+ )
1196
+ self._fit_called = True
1197
+ return past_covariates, future_covariates
1198
+
1199
+ def _launch_encoder(
1200
+ self,
1201
+ target: Sequence[TimeSeries],
1202
+ past_covariates: SupportedTimeSeries,
1203
+ future_covariates: SupportedTimeSeries,
1204
+ encoder_method: _EncoderMethod,
1205
+ n: int | None = None,
1206
+ encode_past: bool = True,
1207
+ encode_future: bool = True,
1208
+ ) -> tuple[Sequence[TimeSeries], Sequence[TimeSeries]]:
1209
+ """Launches the encode sequence for past covariates and future covariates for either training,
1210
+ inference/prediction or training and inference/prediction depending on `encoder_method`.
1211
+ """
1212
+ if not self.encoding_available:
1213
+ return past_covariates, future_covariates
1214
+
1215
+ # guarantee that all inputs are either a sequence of TimeSeries or None
1216
+ single_series = isinstance(target, TimeSeries)
1217
+ target = series2seq(target)
1218
+ past_covariates = series2seq(past_covariates)
1219
+ future_covariates = series2seq(future_covariates)
1220
+
1221
+ # generate past covariates encodings
1222
+ if self.past_encoders and encode_past:
1223
+ past_covariates = self._encode_sequence(
1224
+ encoders=self.past_encoders,
1225
+ transformer=self.past_transformer,
1226
+ target=target,
1227
+ covariates=past_covariates,
1228
+ covariates_type=PAST,
1229
+ encoder_method=encoder_method,
1230
+ n=n,
1231
+ )
1232
+
1233
+ # generate future covariates encodings
1234
+ if self.future_encoders and encode_future:
1235
+ future_covariates = self._encode_sequence(
1236
+ encoders=self.future_encoders,
1237
+ transformer=self.future_transformer,
1238
+ target=target,
1239
+ covariates=future_covariates,
1240
+ covariates_type=FUTURE,
1241
+ encoder_method=encoder_method,
1242
+ n=n,
1243
+ )
1244
+
1245
+ # convert covariates back to single series if single target was used as input
1246
+ if single_series:
1247
+ past_covariates = seq2series(past_covariates)
1248
+ future_covariates = seq2series(future_covariates)
1249
+ return past_covariates, future_covariates
1250
+
1251
+ def _encode_sequence(
1252
+ self,
1253
+ encoders: Sequence[SingleEncoder],
1254
+ transformer: SequentialEncoderTransformer | None,
1255
+ target: Sequence[TimeSeries],
1256
+ covariates: SupportedTimeSeries | None,
1257
+ covariates_type: str,
1258
+ encoder_method: _EncoderMethod,
1259
+ n: int | None = None,
1260
+ ) -> list[TimeSeries]:
1261
+ """Sequentially encodes the index of all input target/covariates TimeSeries with the corresponding
1262
+ `encoder_method`.
1263
+ """
1264
+ encode_method = encoder_method.method
1265
+
1266
+ encoded_sequence = []
1267
+ if covariates is None:
1268
+ covariates = [None] * len(target)
1269
+ else:
1270
+ covariates = (
1271
+ [covariates] if isinstance(covariates, TimeSeries) else covariates
1272
+ )
1273
+
1274
+ for ts, covs in zip(target, covariates):
1275
+ # drop encoder components if they are in input covariates
1276
+ covs = self._drop_encoded_components(
1277
+ covariates=covs,
1278
+ components=getattr(self, f"{covariates_type}_components"),
1279
+ )
1280
+ encoded = concatenate(
1281
+ [
1282
+ getattr(enc, encode_method)(
1283
+ target=ts, covariates=covs, merge_covariates=False, n=n
1284
+ )
1285
+ for enc in encoders
1286
+ ],
1287
+ axis=DIMS[1],
1288
+ )
1289
+ encoded_sequence.append(
1290
+ self._merge_covariates(encoded=encoded, covariates=covs)
1291
+ )
1292
+
1293
+ if transformer is not None:
1294
+ encoded_sequence = transformer.transform(encoded_sequence)
1295
+
1296
+ # store encoded past/future component names if they were not saved before
1297
+ if getattr(self, f"{covariates_type}_components").empty:
1298
+ components = encoded_sequence[0].components
1299
+ if covariates is not None and covariates[0] is not None:
1300
+ components = components[~components.isin(covariates[0].components)]
1301
+ setattr(self, f"_{covariates_type}_components", components)
1302
+
1303
+ return encoded_sequence
1304
+
1305
+ @property
1306
+ def past_encoders(self) -> list[SingleEncoder]:
1307
+ """Returns the past covariates encoders"""
1308
+ return self._past_encoders
1309
+
1310
+ @property
1311
+ def future_encoders(self) -> list[SingleEncoder]:
1312
+ """Returns the future covariates encoders"""
1313
+ return self._future_encoders
1314
+
1315
+ @property
1316
+ def encoders(self) -> tuple[list[SingleEncoder], list[SingleEncoder]]:
1317
+ """Returns a tuple of (past covariates encoders, future covariates encoders)"""
1318
+ return self.past_encoders, self.future_encoders
1319
+
1320
+ @property
1321
+ def past_components(self) -> pd.Index:
1322
+ """Returns the past covariates component names generated by `SequentialEncoder.past_encoders`.
1323
+ Only available after calling `SequentialEncoder.encode_train()`
1324
+ """
1325
+ return self._past_components
1326
+
1327
+ @property
1328
+ def future_components(self) -> pd.Index:
1329
+ """Returns the future covariates component names generated by `SequentialEncoder.future_encoders`.
1330
+ Only available after calling `SequentialEncoder.encode_train()`
1331
+ """
1332
+ return self._future_components
1333
+
1334
+ @property
1335
+ def components(self) -> tuple[pd.Index, pd.Index]:
1336
+ """Returns the covariates component names generated by `SequentialEncoder.past_encoders` and
1337
+ `SequentialEncoder.future_encoders`. A tuple of (past encoded components, future encoded components).
1338
+ Only available after calling `SequentialEncoder.encode_train()`
1339
+ """
1340
+ return self.past_components, self.future_components
1341
+
1342
+ @property
1343
+ def encoding_n_components(self) -> tuple[int, int]:
1344
+ """Returns the number of components generated by `SequentialEncoder.past_encoders` and
1345
+ `SequentialEncoder.future_encoders`.
1346
+ """
1347
+ # by default, _[past/future]_encoders are empty lists
1348
+ past_enc_n_compoments = sum(
1349
+ past_enc.encoding_n_components for past_enc in self.past_encoders
1350
+ )
1351
+ future_enc_n_compoments = sum(
1352
+ future_enc.encoding_n_components for future_enc in self.future_encoders
1353
+ )
1354
+ return past_enc_n_compoments, future_enc_n_compoments
1355
+
1356
+ @property
1357
+ def past_transformer(self) -> SequentialEncoderTransformer:
1358
+ """Returns the past transformer object"""
1359
+ return self._past_transformer
1360
+
1361
+ @property
1362
+ def future_transformer(self) -> SequentialEncoderTransformer:
1363
+ """Returns the future transformer object"""
1364
+ return self._future_transformer
1365
+
1366
+ def transformers(
1367
+ self,
1368
+ ) -> tuple[SequentialEncoderTransformer, SequentialEncoderTransformer]:
1369
+ """Returns a tuple of (past transformer, future transformer)."""
1370
+ return self.past_transformer, self.future_transformer
1371
+
1372
+ @property
1373
+ def encoder_map(self) -> dict:
1374
+ """Mapping between encoder identifier string (from parameters at model creations) and the corresponding
1375
+ future or past covariates encoder"""
1376
+ mapper = {
1377
+ "cyclic_past": PastCyclicEncoder,
1378
+ "cyclic_future": FutureCyclicEncoder,
1379
+ "datetime_attribute_past": PastDatetimeAttributeEncoder,
1380
+ "datetime_attribute_future": FutureDatetimeAttributeEncoder,
1381
+ "position_past": PastIntegerIndexEncoder,
1382
+ "position_future": FutureIntegerIndexEncoder,
1383
+ "custom_past": PastCallableIndexEncoder,
1384
+ "custom_future": FutureCallableIndexEncoder,
1385
+ }
1386
+ return mapper
1387
+
1388
+ def _setup_encoders(self, params: dict) -> None:
1389
+ """Sets up/Initializes all past and future encoders and an optional transformer from `add_encoder` parameter
1390
+ used at model creation.
1391
+
1392
+
1393
+ Parameters
1394
+ ----------
1395
+ params
1396
+ Dict from parameter `add_encoders` (kwargs) used at model creation. Relevant parameters are:
1397
+ * params={'cyclic': {'past': ['month', 'dayofweek', ...], 'future': [same as for 'past']}}
1398
+ """
1399
+ past_encoders, future_encoders = self._process_input_encoders(params)
1400
+ tz = self._process_timezone(params)
1401
+
1402
+ if not past_encoders and not future_encoders:
1403
+ return
1404
+
1405
+ self._past_encoders = [
1406
+ self.encoder_map[enc_id](
1407
+ attribute=attr,
1408
+ input_chunk_length=self.input_chunk_length,
1409
+ output_chunk_length=self.output_chunk_length,
1410
+ lags_covariates=self.lags_past_covariates,
1411
+ tz=tz,
1412
+ )
1413
+ for enc_id, attr in past_encoders
1414
+ ]
1415
+ self._future_encoders = [
1416
+ self.encoder_map[enc_id](
1417
+ attribute=attr,
1418
+ input_chunk_length=self.input_chunk_length,
1419
+ output_chunk_length=self.output_chunk_length,
1420
+ lags_covariates=self.lags_future_covariates,
1421
+ tz=tz,
1422
+ )
1423
+ for enc_id, attr in future_encoders
1424
+ ]
1425
+ self.encoding_available = True
1426
+
1427
+ def _setup_transformer(self, params: dict) -> None:
1428
+ """Sets up/Initializes an optional transformer from `add_encoder` parameter used at model creation.
1429
+
1430
+ Parameters
1431
+ ----------
1432
+ params
1433
+ Dict from parameter `add_encoders` (kwargs) used at model creation. Relevant parameters are:
1434
+ * params={..., 'transformer': Scaler()}
1435
+ """
1436
+ (
1437
+ transformer,
1438
+ transform_past_mask,
1439
+ transform_future_mask,
1440
+ ) = self._process_input_transformer(params)
1441
+ if transform_past_mask:
1442
+ self._past_transformer = SequentialEncoderTransformer(
1443
+ copy.deepcopy(transformer), transform_past_mask
1444
+ )
1445
+ if transform_future_mask:
1446
+ self._future_transformer = SequentialEncoderTransformer(
1447
+ copy.deepcopy(transformer), transform_future_mask
1448
+ )
1449
+
1450
+ def _process_input_encoders(self, params: dict) -> tuple[list, list]:
1451
+ """Processes input and returns two lists of tuples `(encoder_id, attribute)` from relevant encoder
1452
+ parameters at model creation.
1453
+
1454
+ Parameters
1455
+ ----------
1456
+ params
1457
+ The `add_encoders` dict used at model creation. Must follow this convention:
1458
+ `{encoder keyword: {temporal keyword: List[attributes]}}`
1459
+
1460
+ Tuples of `(encoder_id, attribute)` are extracted from `add_encoders` to instantiate the `SingleEncoder`
1461
+ objects:
1462
+
1463
+ * The `encoder_id` is extracted as follows:
1464
+ str(encoder_kw) + str(temporal_kw) -> 'cyclic' + 'past' -> `encoder_id` = 'cyclic_past'
1465
+ The `encoder_id` is used to map the parameters with the corresponding `SingleEncoder` objects.
1466
+ * The `attribute` is extracted from the values given by values under `temporal_kw`
1467
+ `attribute` = 'month'
1468
+ ...
1469
+ The `attribute` tells the `SingleEncoder` which attribute of the index to encode
1470
+
1471
+ Raises
1472
+ ------
1473
+ ValueError
1474
+ 1) if the outermost key is other than (`past`, `future`)
1475
+ 2) if the innermost values are other than type `str` or `Sequence`
1476
+ 3) if any of entry in the innermost values is a lambda function
1477
+ """
1478
+ if not params:
1479
+ return [], []
1480
+
1481
+ # check input for invalid encoder types
1482
+ invalid_encoders = [
1483
+ enc
1484
+ for enc in params
1485
+ if enc not in ENCODER_KEYS + TZ_KEYS + TRANSFORMER_KEYS
1486
+ ]
1487
+ if len(invalid_encoders) > 0:
1488
+ raise_log(
1489
+ ValueError(
1490
+ f"Encountered invalid encoder types `{invalid_encoders}` in `add_encoders` parameter at model "
1491
+ f"creation. Supported encoder types are: `{ENCODER_KEYS + TRANSFORMER_KEYS}`."
1492
+ ),
1493
+ )
1494
+
1495
+ encoders = {enc: params[enc] for enc in ENCODER_KEYS if params.get(enc, None)}
1496
+
1497
+ # check input for invalid temporal types
1498
+ invalid_time_params = list()
1499
+ for encoder, t_types in encoders.items():
1500
+ invalid_time_params += [
1501
+ t_type for t_type in t_types.keys() if t_type not in VALID_TIME_PARAMS
1502
+ ]
1503
+
1504
+ if len(invalid_time_params) > 0:
1505
+ raise_log(
1506
+ ValueError(
1507
+ f"Encountered invalid temporal types `{invalid_time_params}` in `add_encoders` parameter at model "
1508
+ f"creation. Supported temporal types are: `{VALID_TIME_PARAMS}`."
1509
+ ),
1510
+ )
1511
+
1512
+ # check that encoders are not lambda functions (not pickable)
1513
+ lambda_func_encoders = set()
1514
+ # convert into tuples of (encoder string identifier, encoder attribute)
1515
+ past_encoders, future_encoders = list(), list()
1516
+ for enc, enc_params in encoders.items():
1517
+ for enc_time, enc_attr in enc_params.items():
1518
+ if not isinstance(enc_attr, VALID_ENCODER_DTYPES):
1519
+ raise_log(
1520
+ ValueError(
1521
+ f"Encountered value `{enc_attr}` of invalid type `{type(enc_attr)}` for encoder "
1522
+ f"`{enc}` in `add_encoders` at model creation. Supported data types are: "
1523
+ f"`{VALID_ENCODER_DTYPES}`."
1524
+ ),
1525
+ )
1526
+ attrs = [enc_attr] if isinstance(enc_attr, str) else enc_attr
1527
+ for attr in attrs:
1528
+ encoder_id = "_".join([enc, enc_time])
1529
+ if enc_time == PAST:
1530
+ past_encoders.append((encoder_id, attr))
1531
+ else:
1532
+ future_encoders.append((encoder_id, attr))
1533
+
1534
+ if isinstance(attr, Callable):
1535
+ name = getattr(attr, "__name__", "")
1536
+ if name == "<lambda>":
1537
+ lambda_func_encoders.add(enc)
1538
+
1539
+ if len(lambda_func_encoders) > 0:
1540
+ raise_log(
1541
+ ValueError(
1542
+ f"Encountered lambda function in the following `add_encoders` entries : {lambda_func_encoders} "
1543
+ f"at model creation. "
1544
+ f"In order to prevent issues when saving the model, these encoders must be converted to "
1545
+ f"named functions."
1546
+ ),
1547
+ )
1548
+
1549
+ for temp_enc, takes_temp, temp in [
1550
+ (past_encoders, self.takes_past_covariates, "past"),
1551
+ (future_encoders, self.takes_future_covariates, "future"),
1552
+ ]:
1553
+ if temp_enc and not takes_temp:
1554
+ logger.warning(
1555
+ f"Specified {temp} encoders in `add_encoders` at model creation but model does not "
1556
+ f"accept {temp} covariates. {temp} encoders will be ignored."
1557
+ )
1558
+
1559
+ past_encoders = past_encoders if self.takes_past_covariates else []
1560
+ future_encoders = future_encoders if self.takes_future_covariates else []
1561
+ return past_encoders, future_encoders
1562
+
1563
+ def _process_input_transformer(
1564
+ self, params: dict
1565
+ ) -> tuple[FittableDataTransformer | None, list, list]:
1566
+ """Processes input params used at model creation and returns tuple of one transformer object and two masks
1567
+ that specify which past / future encoders accept being transformed.
1568
+
1569
+ Parameters
1570
+ ----------
1571
+ params
1572
+ Dict from parameter `add_encoders` (kwargs) used at model creation. Relevant parameters are:
1573
+ * params={'transformer': Scaler()}
1574
+ """
1575
+ if not params:
1576
+ return None, [], []
1577
+
1578
+ transformer = params.get(TRANSFORMER_KEYS[0], None)
1579
+ if transformer is None:
1580
+ return None, [], []
1581
+
1582
+ if not isinstance(transformer, VALID_TRANSFORMER_DTYPES):
1583
+ raise_log(
1584
+ ValueError(
1585
+ f"Encountered `{TRANSFORMER_KEYS[0]}` of invalid type `{type(transformer)}` "
1586
+ f"in `add_encoders` at model creation. Transformer must be an instance of "
1587
+ f"`{VALID_TRANSFORMER_DTYPES}`."
1588
+ ),
1589
+ )
1590
+
1591
+ transform_past_mask = [
1592
+ transform
1593
+ for enc in self.past_encoders
1594
+ for transform in enc.accept_transformer
1595
+ ]
1596
+ transform_future_mask = [
1597
+ transform
1598
+ for enc in self.future_encoders
1599
+ for transform in enc.accept_transformer
1600
+ ]
1601
+ return transformer, transform_past_mask, transform_future_mask
1602
+
1603
+ @staticmethod
1604
+ def _process_timezone(params: dict) -> str | None:
1605
+ """Processes input params used at model creation for time zone specification, and returns the time zone.
1606
+
1607
+ Parameters
1608
+ ----------
1609
+ params
1610
+ Dict from parameter `add_encoders` (kwargs) used at model creation. Relevant parameters are:
1611
+ * params={'tz': 'CET'}
1612
+ """
1613
+ if not params:
1614
+ return None
1615
+
1616
+ return params.get(TZ_KEYS[0], None)
1617
+
1618
+ @property
1619
+ def requires_fit(self) -> bool:
1620
+ return any([
1621
+ enc.requires_fit for cov_enc in self.encoders for enc in cov_enc
1622
+ ]) or any([tf is not None for tf in self.transformers()])
datasets/raw/darts_benchmark_datasets/darts/utils/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utils
3
+ -----
4
+
5
+ Utility functions and helper classes for various operations in Darts.
6
+ """
7
+
8
+ from darts.utils.utils import (
9
+ _build_tqdm_iterator,
10
+ _parallel_apply,
11
+ _with_sanity_checks,
12
+ n_steps_between,
13
+ )
14
+
15
+ __all__ = [
16
+ "_build_tqdm_iterator",
17
+ "_parallel_apply",
18
+ "_with_sanity_checks",
19
+ "n_steps_between",
20
+ ]
datasets/raw/darts_benchmark_datasets/darts/utils/_lazy.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared helper for PEP 562 lazy module loading in ``__init__.py`` files."""
2
+
3
+ import importlib
4
+ from collections.abc import Callable
5
+ from typing import Any
6
+
7
+
8
+ def setup_lazy_imports(
9
+ lazy_imports: dict[str, str | tuple[str, str | None]],
10
+ module_name: str,
11
+ module_globals: dict[str, Any],
12
+ extra_attrs: dict[str, Callable[[], Any]] | None = None,
13
+ ) -> tuple[list[str], Callable[[str], Any], Callable[[], list[str]]]:
14
+ """Create ``__all__``, ``__getattr__``, and ``__dir__`` for a lazy package.
15
+
16
+ Parameters
17
+ ----------
18
+ lazy_imports
19
+ Mapping of public attribute name to either:
20
+
21
+ - a module path string (required dependency), or
22
+ - a 2-tuple ``(module_path, optional_dep_name)`` where
23
+ *optional_dep_name* is a human-readable dependency label
24
+ (e.g. ``"(Py)Torch"``). When the import fails and
25
+ *optional_dep_name* is not ``None``, a
26
+ :class:`~darts.utils.utils.NotImportedModule` sentinel is
27
+ returned instead of raising.
28
+ module_name
29
+ The ``__name__`` of the calling package (for error messages).
30
+ module_globals
31
+ The ``globals()`` dict of the calling package. Resolved
32
+ attributes are cached here so ``__getattr__`` is only invoked
33
+ once per name.
34
+ extra_attrs
35
+ Optional mapping of additional attribute names to zero-arg
36
+ callables that produce their values on first access. Useful
37
+ for derived attributes (e.g. ``TIME_DEPENDENT_METRICS``).
38
+
39
+ Returns
40
+ -------
41
+ tuple[list[str], Callable, Callable]
42
+ ``(__all__, __getattr__, __dir__)`` ready to be assigned at
43
+ module level.
44
+ """
45
+ # attrs are added to `__all__` of `__init__.py`
46
+ all_names = list(lazy_imports.keys())
47
+ if extra_attrs:
48
+ all_names.extend(extra_attrs.keys())
49
+
50
+ # `__getattr__` is called when accessing module / package attributes
51
+ # e.g., `from darts.models import XXX` for the `darts.models` package
52
+ def __getattr__(name: str) -> Any:
53
+ if name in lazy_imports:
54
+ # import attrs from darts package and cache it
55
+ entry = lazy_imports[name]
56
+ if isinstance(entry, str):
57
+ module_path, optional_dep = entry, None
58
+ else:
59
+ module_path, optional_dep = entry
60
+
61
+ try:
62
+ module = importlib.import_module(module_path)
63
+ value = getattr(module, name)
64
+ except (ModuleNotFoundError, ImportError):
65
+ # attr is not available; if it is an optional dependency, wrap it in
66
+ # the `NotImportedModule`. Otherwise, raise an exception
67
+ if optional_dep is not None:
68
+ from darts.utils.utils import NotImportedModule
69
+
70
+ value = NotImportedModule(module_name=optional_dep, warn=False)
71
+ else:
72
+ raise
73
+ elif extra_attrs is not None and name in extra_attrs:
74
+ # special attrs that are not imported but computed within `__init__.py`
75
+ value = extra_attrs[name]()
76
+ else:
77
+ raise AttributeError(f"module {module_name!r} has no attribute {name!r}")
78
+
79
+ # cache the attr under globals to only invoke `__getattr__` only once per name
80
+ module_globals[name] = value
81
+ return value
82
+
83
+ # attrs are added to `__dir__` of `__init__.py`
84
+ def __dir__() -> list[str]:
85
+ return all_names
86
+
87
+ return all_names, __getattr__, __dir__
datasets/raw/darts_benchmark_datasets/darts/utils/_statsmodels_utils.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Internal utilities for statsmodels compatibility across versions."""
2
+
3
+ import contextlib
4
+ from importlib.metadata import version
5
+
6
+ _sm_150_or_above = True
7
+ with contextlib.suppress(Exception):
8
+ _statsmodel_rng_min_version = (0, 15, 0)
9
+ _sm_version = version("statsmodels")
10
+ _sm_version = tuple(int(el) for el in _sm_version.split(".")[:3])
11
+ _sm_150_or_above = _sm_version >= _statsmodel_rng_min_version
12
+
13
+ SM_RNG_KWARG = "rng" if _sm_150_or_above else "random_state"
datasets/raw/darts_benchmark_datasets/darts/utils/callbacks.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Callbacks for TorchForecastingModel
3
+ -----------------------------------
4
+ """
5
+
6
+ import sys
7
+ import warnings
8
+
9
+ from pytorch_lightning.callbacks import Callback, TQDMProgressBar
10
+ from pytorch_lightning.callbacks.progress.tqdm_progress import Tqdm
11
+
12
+ from darts.logging import raise_log
13
+
14
+ # system attr keys used to coordinate DDP pruning across processes
15
+ _OPTUNA_EPOCH_KEY = "ddp_pl:epoch"
16
+ _OPTUNA_INTERMEDIATE_VALUE = "ddp_pl:intermediate_value"
17
+ _OPTUNA_PRUNED_KEY = "ddp_pl:pruned"
18
+
19
+
20
+ class TFMProgressBar(TQDMProgressBar):
21
+ def __init__(
22
+ self,
23
+ enable_sanity_check_bar: bool = True,
24
+ enable_train_bar: bool = True,
25
+ enable_validation_bar: bool = True,
26
+ enable_prediction_bar: bool = True,
27
+ enable_train_bar_only: bool = False,
28
+ **kwargs,
29
+ ):
30
+ """Darts' Progress Bar for `TorchForecastingModels`.
31
+
32
+ Allows to customize for which model stages (sanity checks, training, validation, prediction) to display a
33
+ progress bar.
34
+
35
+ This class is a PyTorch Lightning `Callback` and can be passed to the `TorchForecastingModel` constructor
36
+ through the `pl_trainer_kwargs` parameter.
37
+
38
+ Examples
39
+ --------
40
+ >>> from darts.models import NBEATSModel
41
+ >>> from darts.utils.callbacks import TFMProgressBar
42
+ >>> # only display the training bar and not the validation, prediction, and sanity check bars
43
+ >>> prog_bar = TFMProgressBar(enable_train_bar_only=True)
44
+ >>> model = NBEATSModel(1, 1, pl_trainer_kwargs={"callbacks": [prog_bar]})
45
+
46
+ Parameters
47
+ ----------
48
+ enable_sanity_check_bar
49
+ Whether to enable to progress bar for sanity checks.
50
+ enable_train_bar
51
+ Whether to enable to progress bar for training.
52
+ enable_validation_bar
53
+ Whether to enable to progress bar for validation.
54
+ enable_prediction_bar
55
+ Whether to enable to progress bar for prediction.
56
+ enable_train_bar_only
57
+ Whether to disable all progress bars except the bar for training.
58
+ **kwargs
59
+ Arguments passed to the PyTorch Lightning's `TQDMProgressBar
60
+ <https://scikit-learn.org/stable/glossary.html#term-random_state>`__.
61
+ """
62
+ super().__init__(**kwargs)
63
+ self.enable_sanity_check_bar = enable_sanity_check_bar
64
+ self.enable_train_bar = enable_train_bar
65
+ self.enable_validation_bar = enable_validation_bar
66
+ self.enable_prediction_bar = enable_prediction_bar
67
+ self.enable_train_bar_only = enable_train_bar_only
68
+
69
+ def init_sanity_tqdm(self) -> Tqdm:
70
+ """Override this to customize the tqdm bar for the validation sanity run."""
71
+ return Tqdm(
72
+ desc=self.sanity_check_description,
73
+ position=(2 * self.process_position),
74
+ disable=not self.enable_sanity_check_bar or self.enable_train_bar_only,
75
+ leave=False,
76
+ dynamic_ncols=True,
77
+ file=sys.stdout,
78
+ )
79
+
80
+ def init_predict_tqdm(self) -> Tqdm:
81
+ """Override this to customize the tqdm bar for predicting."""
82
+ return Tqdm(
83
+ desc=self.predict_description,
84
+ position=(2 * self.process_position),
85
+ disable=not self.enable_prediction_bar or self.enable_train_bar_only,
86
+ leave=True,
87
+ dynamic_ncols=True,
88
+ file=sys.stdout,
89
+ smoothing=0,
90
+ )
91
+
92
+ def init_train_tqdm(self) -> Tqdm:
93
+ """Override this to customize the tqdm bar for training."""
94
+ return Tqdm(
95
+ desc=self.train_description,
96
+ position=(2 * self.process_position),
97
+ disable=not self.enable_train_bar,
98
+ leave=True,
99
+ dynamic_ncols=True,
100
+ file=sys.stdout,
101
+ smoothing=0,
102
+ )
103
+
104
+ def init_validation_tqdm(self) -> Tqdm:
105
+ """Override this to customize the tqdm bar for validation."""
106
+ # The train progress bar doesn't exist in `trainer.validate()`
107
+ has_main_bar = self.trainer.state.fn != "validate"
108
+ return Tqdm(
109
+ desc=self.validation_description,
110
+ position=(2 * self.process_position + has_main_bar),
111
+ disable=not self.enable_validation_bar or self.enable_train_bar_only,
112
+ leave=not has_main_bar,
113
+ dynamic_ncols=True,
114
+ file=sys.stdout,
115
+ )
116
+
117
+
118
+ # Adapted from optuna-integration (MIT License, Copyright (c) 2018 Preferred Networks, Inc.)
119
+ # https://github.com/optuna/optuna-integration/blob/main/optuna_integration/pytorch_lightning/pytorch_lightning.py
120
+ class PyTorchLightningPruningCallback(Callback):
121
+ """PyTorch Lightning callback to prune unpromising Optuna trials.
122
+
123
+ Reports the monitored metric to the Optuna trial after each validation epoch
124
+ and raises :class:`optuna.TrialPruned` when ``trial.should_prune()`` returns ``True``.
125
+
126
+ For distributed (DDP) training, :class:`~optuna.study.Study` must use RDB storage, and
127
+ :meth:`check_pruned` must be called manually after ``Trainer.fit()`` completes.
128
+
129
+ Parameters
130
+ ----------
131
+ trial
132
+ A :class:`~optuna.trial.Trial` corresponding to the current evaluation of the
133
+ objective function.
134
+ monitor
135
+ An evaluation metric for pruning, e.g., ``val_loss`` or
136
+ ``val_acc``. The metrics are obtained from the returned dictionaries from e.g.
137
+ ``lightning.pytorch.LightningModule.training_step`` or
138
+ ``lightning.pytorch.LightningModule.validation_epoch_end`` and the names thus depend on
139
+ how this dictionary is formatted.
140
+
141
+ Examples
142
+ --------
143
+ >>> import optuna
144
+ >>> from darts.utils.callbacks import PyTorchLightningPruningCallback
145
+ >>> def objective(trial):
146
+ ... pruner = PyTorchLightningPruningCallback(trial, monitor="val_loss")
147
+ ... model = TCNModel(..., pl_trainer_kwargs={"callbacks": [pruner]})
148
+ ... model.fit(...)
149
+ """
150
+
151
+ def __init__(self, trial, monitor: str) -> None:
152
+ super().__init__()
153
+ self._trial = trial
154
+ self.monitor = monitor
155
+ self.is_ddp_backend = False
156
+
157
+ def on_fit_start(self, trainer, pl_module) -> None:
158
+ self.is_ddp_backend = trainer._accelerator_connector.is_distributed
159
+ if self.is_ddp_backend:
160
+ from optuna.storages._cached_storage import _CachedStorage
161
+ from optuna.storages._rdb.storage import RDBStorage
162
+
163
+ # If it were not for this block, fitting is started even if unsupported storage
164
+ # is used. Note that the ValueError is transformed into ProcessRaisedException inside
165
+ # torch.
166
+ if not (
167
+ isinstance(self._trial.study._storage, _CachedStorage)
168
+ and isinstance(self._trial.study._storage._backend, RDBStorage)
169
+ ):
170
+ raise_log(
171
+ ValueError(
172
+ "PyTorchLightningPruningCallback supports only "
173
+ "optuna.storages.RDBStorage in DDP."
174
+ ),
175
+ )
176
+ # It is necessary to store intermediate values directly in the backend storage because
177
+ # they are not properly propagated to main process due to cached storage.
178
+ if trainer.is_global_zero:
179
+ self._trial.storage.set_trial_system_attr(
180
+ self._trial._trial_id,
181
+ _OPTUNA_INTERMEDIATE_VALUE,
182
+ dict(),
183
+ )
184
+
185
+ def on_validation_end(self, trainer, pl_module) -> None:
186
+ import optuna
187
+
188
+ # Trainer calls on_validation_end for sanity check — skip to avoid double-reporting
189
+ # at epoch 0.
190
+ if trainer.sanity_checking:
191
+ return
192
+
193
+ current_score = trainer.callback_metrics.get(self.monitor)
194
+ if current_score is None:
195
+ warnings.warn(
196
+ f"The metric '{self.monitor}' is not in the evaluation logs for pruning. "
197
+ "Please make sure you set the correct metric name."
198
+ )
199
+ return
200
+
201
+ epoch = pl_module.current_epoch
202
+ should_stop = False
203
+
204
+ # Determine if the trial should be terminated in a single process.
205
+ if not self.is_ddp_backend:
206
+ self._trial.report(current_score.item(), step=epoch)
207
+ if not self._trial.should_prune():
208
+ return
209
+ raise_log(optuna.TrialPruned(f"Trial was pruned at epoch {epoch}."))
210
+
211
+ # Determine if the trial should be terminated in a DDP.
212
+ if trainer.is_global_zero:
213
+ self._trial.report(current_score.item(), step=epoch)
214
+ should_stop = self._trial.should_prune()
215
+
216
+ # Update intermediate value in the storage.
217
+ _trial_id = self._trial._trial_id
218
+ _study = self._trial.study
219
+ _trial_system_attrs = _study._storage.get_trial_system_attrs(_trial_id)
220
+ intermediate_values = _trial_system_attrs.get(_OPTUNA_INTERMEDIATE_VALUE)
221
+ if intermediate_values is None:
222
+ return
223
+
224
+ intermediate_values[epoch] = current_score.item()
225
+ self._trial.storage.set_trial_system_attr(
226
+ self._trial._trial_id, _OPTUNA_INTERMEDIATE_VALUE, intermediate_values
227
+ )
228
+
229
+ # Terminate every process if any world process decides to stop.
230
+ should_stop = trainer.strategy.broadcast(should_stop)
231
+ trainer.should_stop = trainer.should_stop or should_stop
232
+ if not should_stop:
233
+ return
234
+
235
+ if trainer.is_global_zero:
236
+ # Update system_attr from global zero process.
237
+ self._trial.storage.set_trial_system_attr(
238
+ self._trial._trial_id, _OPTUNA_PRUNED_KEY, True
239
+ )
240
+ self._trial.storage.set_trial_system_attr(
241
+ self._trial._trial_id, _OPTUNA_EPOCH_KEY, epoch
242
+ )
243
+
244
+ def check_pruned(self) -> None:
245
+ """Raise :class:`optuna.TrialPruned` manually if pruned.
246
+
247
+ Currently, ``intermediate_values`` are not properly propagated between processes due to
248
+ storage cache. Therefore, necessary information is kept in ``trial.system_attrs`` when the
249
+ trial runs in a distributed situation. Please call this method right after calling
250
+ ``lightning.pytorch.Trainer.fit()``.
251
+ If a callback doesn't have any backend storage for DDP, this method does nothing.
252
+ """
253
+ import optuna
254
+ from optuna.storages._cached_storage import _CachedStorage
255
+
256
+ _trial_id = self._trial._trial_id
257
+ _study = self._trial.study
258
+ # Confirm if storage is not InMemory in case this method is called in a non-distributed
259
+ # situation by mistake.
260
+ if not isinstance(_study._storage, _CachedStorage):
261
+ return
262
+
263
+ _trial_system_attrs = _study._storage._backend.get_trial_system_attrs(_trial_id)
264
+ is_pruned = _trial_system_attrs.get(_OPTUNA_PRUNED_KEY)
265
+ intermediate_values = _trial_system_attrs.get(_OPTUNA_INTERMEDIATE_VALUE)
266
+
267
+ # Confirm if DDP backend is used in case this method is called from a non-DDP situation by
268
+ # mistake.
269
+ if intermediate_values is None:
270
+ return
271
+ for epoch, score in intermediate_values.items():
272
+ self._trial.report(score, step=int(epoch))
273
+ if is_pruned:
274
+ epoch = _trial_system_attrs.get(_OPTUNA_EPOCH_KEY)
275
+ raise_log(optuna.TrialPruned(f"Trial was pruned at epoch {epoch}."))
datasets/raw/darts_benchmark_datasets/darts/utils/historical_forecasts/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utils for Historical Forecasting
3
+ --------------------------------
4
+
5
+ Utilities for generating and optimizing historical forecasts.
6
+ """
7
+
8
+ from typing import TYPE_CHECKING
9
+
10
+ from darts.utils._lazy import setup_lazy_imports
11
+
12
+ if TYPE_CHECKING:
13
+ from darts.utils.historical_forecasts.optimized_historical_forecasts_regression import (
14
+ _optimized_historical_forecasts_regression as _optimized_historical_forecasts_regression,
15
+ )
16
+ from darts.utils.historical_forecasts.utils import (
17
+ _check_optimizable_historical_forecasts_global_models as _check_optimizable_historical_forecasts_global_models,
18
+ )
19
+ from darts.utils.historical_forecasts.utils import (
20
+ _get_historical_forecast_boundaries as _get_historical_forecast_boundaries,
21
+ )
22
+ from darts.utils.historical_forecasts.utils import (
23
+ _historical_forecasts_general_checks as _historical_forecasts_general_checks,
24
+ )
25
+ from darts.utils.historical_forecasts.utils import (
26
+ _process_historical_forecast_input as _process_historical_forecast_input,
27
+ )
28
+
29
+ _LAZY_IMPORTS: dict[str, str] = {
30
+ "_optimized_historical_forecasts_regression": (
31
+ "darts.utils.historical_forecasts.optimized_historical_forecasts_regression"
32
+ ),
33
+ "_check_optimizable_historical_forecasts_global_models": "darts.utils.historical_forecasts.utils",
34
+ "_get_historical_forecast_boundaries": "darts.utils.historical_forecasts.utils",
35
+ "_historical_forecasts_general_checks": "darts.utils.historical_forecasts.utils",
36
+ "_process_historical_forecast_input": "darts.utils.historical_forecasts.utils",
37
+ }
38
+
39
+ __all__, __getattr__, __dir__ = setup_lazy_imports(_LAZY_IMPORTS, __name__, globals())
datasets/raw/darts_benchmark_datasets/darts/utils/historical_forecasts/optimized_historical_forecasts_regression.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Optimized Historical Forecasts for SKLearnModel
3
+ -----------------------------------------------
4
+ """
5
+
6
+ import inspect
7
+ from collections.abc import Sequence
8
+ from typing import Any, Literal
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+ from numpy.lib.stride_tricks import sliding_window_view
13
+
14
+ from darts import TimeSeries
15
+ from darts.typing import TimeSeriesLike
16
+ from darts.utils import _build_tqdm_iterator
17
+ from darts.utils.data.tabularization import create_lagged_prediction_data
18
+ from darts.utils.historical_forecasts.utils import _get_historical_forecast_boundaries
19
+ from darts.utils.ts_utils import get_single_series
20
+ from darts.utils.utils import generate_index
21
+
22
+
23
+ def _optimized_historical_forecasts_regression(
24
+ model,
25
+ series: Sequence[TimeSeries],
26
+ past_covariates: Sequence[TimeSeries] | None = None,
27
+ future_covariates: Sequence[TimeSeries] | None = None,
28
+ num_samples: int = 1,
29
+ start: pd.Timestamp | float | int | Literal["end"] | None = None,
30
+ start_format: Literal["position", "value"] = "value",
31
+ forecast_horizon: int = 1,
32
+ stride: int = 1,
33
+ overlap_end: bool = False,
34
+ show_warnings: bool = True,
35
+ verbose: bool = False,
36
+ predict_likelihood_parameters: bool = False,
37
+ random_state: int | None = None,
38
+ predict_kwargs: dict[str, Any] | None = None,
39
+ last_points_only: bool = False,
40
+ ) -> TimeSeriesLike | Sequence[Sequence[TimeSeries]]:
41
+ """
42
+ Optimized historical forecasts for SKLearnModel.
43
+
44
+ Rely on _check_optimizable_historical_forecasts() to check that the assumptions are verified.
45
+
46
+ The data_transformers are applied in historical_forecasts (input and predictions)
47
+ """
48
+ # invoke base model predict for sanity checks
49
+ predict_kwargs = predict_kwargs or {}
50
+ base_cls = [
51
+ cls for cls in model.__class__.__mro__ if cls.__name__ == "SKLearnModel"
52
+ ][0]
53
+ super_predict_params = inspect.signature(super(base_cls, model).predict).parameters
54
+ super(base_cls, model).predict(
55
+ n=forecast_horizon,
56
+ series=series,
57
+ past_covariates=past_covariates,
58
+ future_covariates=future_covariates,
59
+ num_samples=num_samples,
60
+ predict_likelihood_parameters=predict_likelihood_parameters,
61
+ show_warnings=show_warnings,
62
+ **{k: v for k, v in predict_kwargs.items() if k in super_predict_params},
63
+ )
64
+
65
+ multi_models = model.multi_models
66
+ output_chunk_length = model.output_chunk_length
67
+ output_chunk_shift = model.output_chunk_shift
68
+
69
+ # get target lags and X positions for auto-regression
70
+ if model._get_lags("target") is not None:
71
+ if "target" in model.component_lags:
72
+ target_lags = model.component_lags["target"].values()
73
+ else:
74
+ target_lags = [model.lags["target"]] * get_single_series(
75
+ series
76
+ ).n_components
77
+
78
+ # map which target component lag belongs to which position in X
79
+ counter = 0
80
+ target_lag_positions = [[] for _ in range(len(target_lags))]
81
+ for lag in range(min(model.lags["target"]), max(model.lags["target"]) + 1):
82
+ for comp_idx, comp_lags in enumerate(target_lags):
83
+ if lag in comp_lags:
84
+ target_lag_positions[comp_idx].append(counter)
85
+ counter += 1
86
+ else:
87
+ target_lags, target_lag_positions = [], []
88
+
89
+ # determine the forecast scenario
90
+ is_auto_regression = forecast_horizon > output_chunk_length + output_chunk_shift
91
+
92
+ if multi_models:
93
+ # how many steps the model predicts in a single forecast
94
+ n_output_steps = output_chunk_length
95
+ # how many steps to adjust the first forecasted step (from a lag perspective)
96
+ output_step_adjust = 0
97
+ # stride can be applied directly before `predict()`
98
+ stride_tabularization = stride
99
+ else:
100
+ # multi_models=False only predicts one step at a time
101
+ n_output_steps = 1
102
+ # the predicted step is `output_chunk_length - 1` ahead of the target end time
103
+ output_step_adjust = output_chunk_length - 1
104
+ # stride can only be applied directly with auto-regression since `forecast_horizon` is
105
+ # generated through multiple forecast iterations.
106
+ # without auto-regression, we apply a trick for efficiency: all rows will be kept since the
107
+ # final forecast is composed of forecasts from previous rows (single model must step back to
108
+ # produce all forecasts for `1 < horizon < output_chunk_length`)
109
+ stride_tabularization = stride if is_auto_regression else 1
110
+
111
+ predict_kwargs = predict_kwargs or {}
112
+ forecasts_list = []
113
+ iterator = _build_tqdm_iterator(
114
+ series, verbose, total=len(series), desc="historical forecasts"
115
+ )
116
+ for idx, series_ in enumerate(iterator):
117
+ past_covariates_ = past_covariates[idx] if past_covariates is not None else None
118
+ future_covariates_ = (
119
+ future_covariates[idx] if future_covariates is not None else None
120
+ )
121
+ freq = series_.freq
122
+ forecast_components = (
123
+ model.likelihood.component_names(series=series_)
124
+ if predict_likelihood_parameters
125
+ else series_.columns
126
+ )
127
+
128
+ # obtain forecastable indexes boundaries, adjust target & covariates boundaries accordingly
129
+ (
130
+ hist_fct_start,
131
+ hist_fct_end,
132
+ hist_fct_tgt_start,
133
+ hist_fct_tgt_end,
134
+ hist_fct_pc_start,
135
+ hist_fct_pc_end,
136
+ hist_fct_fc_start,
137
+ hist_fct_fc_end,
138
+ ) = _get_historical_forecast_boundaries(
139
+ model=model,
140
+ series=series_,
141
+ series_idx=idx,
142
+ past_covariates=past_covariates_,
143
+ future_covariates=future_covariates_,
144
+ start=start,
145
+ start_format=start_format,
146
+ forecast_horizon=forecast_horizon,
147
+ overlap_end=overlap_end,
148
+ stride=stride,
149
+ freq=freq,
150
+ show_warnings=show_warnings,
151
+ )
152
+
153
+ if target_lags or model.uses_static_covariates:
154
+ series_adjusted = series_[hist_fct_tgt_start:hist_fct_tgt_end]
155
+ if is_auto_regression:
156
+ # add values to end of target series, to get all examples for auto-regression
157
+ nan_values = np.array(
158
+ [[np.nan] * series_.shape[1]]
159
+ * (forecast_horizon - (output_chunk_length + output_chunk_shift))
160
+ )
161
+ series_adjusted = series_adjusted.append_values(nan_values)
162
+ else:
163
+ series_adjusted = None
164
+
165
+ # extract lagged features;
166
+ # X shape: (n_forecasts, n_lagged_features, n_samples = 1)
167
+ X, _ = create_lagged_prediction_data(
168
+ target_series=series_adjusted,
169
+ past_covariates=(
170
+ None
171
+ if past_covariates_ is None
172
+ else past_covariates_[hist_fct_pc_start:hist_fct_pc_end]
173
+ ),
174
+ future_covariates=(
175
+ None
176
+ if future_covariates_ is None
177
+ else future_covariates_[hist_fct_fc_start:hist_fct_fc_end]
178
+ ),
179
+ lags=model._get_lags("target"),
180
+ lags_past_covariates=model._get_lags("past"),
181
+ lags_future_covariates=model._get_lags("future"),
182
+ uses_static_covariates=model.uses_static_covariates,
183
+ last_static_covariates_shape=model._static_covariates_shape,
184
+ max_samples_per_ts=None,
185
+ check_inputs=True,
186
+ use_moving_windows=True,
187
+ concatenate=False,
188
+ show_warnings=False,
189
+ )
190
+
191
+ # -> (n_forecasts, n_lags)
192
+ X = X[0][:, :, 0]
193
+
194
+ # get forecast iterations and their forecast end times
195
+ if not is_auto_regression:
196
+ # all steps can be predicted in a single forecast iteration
197
+ forecast_iterator = [output_chunk_length + output_chunk_shift]
198
+ else:
199
+ # multiple autoregressive forecast iterations with a roll size of `n_output_steps`
200
+ forecast_iterator = range(
201
+ n_output_steps + output_chunk_shift,
202
+ forecast_horizon + n_output_steps,
203
+ n_output_steps,
204
+ )
205
+
206
+ # generate forecasts
207
+ predictions = None
208
+ for pred_idx, t_pred in enumerate(forecast_iterator):
209
+ if pred_idx == 0 or t_pred <= forecast_horizon:
210
+ # the main forecast iterations ending at a round multiple of output_chunk_length;
211
+ # take only forecast_horizon points in case forecast_horizon < output_chunk_length
212
+ roll_shift = 0
213
+ take_forecast_indices = slice(None, forecast_horizon)
214
+ else:
215
+ # the last autoregressive forecast iteration when forecast_horizon is not a round
216
+ # multiple of output_chunk_length; requires shifting back into the past
217
+ roll_shift = (
218
+ n_output_steps
219
+ - (forecast_horizon - output_chunk_shift) % output_chunk_length
220
+ )
221
+ take_forecast_indices = slice(roll_shift, None)
222
+
223
+ # get current iteration's lagged features
224
+ # -> (n_forecasts, n_lags)
225
+ start_idx = pred_idx * n_output_steps - roll_shift
226
+ end_idx = min(-(forecast_horizon - t_pred), 0) or None
227
+ current_X = X[start_idx:end_idx:stride_tabularization]
228
+
229
+ # generate `num_samples` examples for probabilistic predictions
230
+ # -> (n_forecasts * n_samples, n_lags)
231
+ current_X = np.repeat(current_X, num_samples, axis=0)
232
+
233
+ if pred_idx > 0:
234
+ # auto-regression requires updating current X with previous predictions;
235
+ # determine what lags the previous forecasts correspond for the current iteration
236
+ forecast_length = predictions.shape[1]
237
+ # lag = (
238
+ # step
239
+ # - forecast_length # shift back into past
240
+ # + output_step_adjust # adjust for multi_models
241
+ # + roll_shift # adjust for non-round-multiple auto-regression
242
+ # )
243
+ forecasted_lags = {
244
+ step - forecast_length + output_step_adjust + roll_shift: step
245
+ for step in range(forecast_length)
246
+ }
247
+
248
+ # find matches between forecasted components and component-specific lags of the
249
+ # future iteration
250
+ for comp_idx, comp_lags in enumerate(target_lags):
251
+ update_x_indices = []
252
+ take_y_indices = []
253
+ for lag_idx, lag in enumerate(comp_lags):
254
+ y_pos = forecasted_lags.get(lag, None)
255
+ if y_pos is not None:
256
+ update_x_indices.append(
257
+ target_lag_positions[comp_idx][lag_idx]
258
+ )
259
+ take_y_indices.append(y_pos)
260
+
261
+ # update X with matched predictions (move around axes for correct reshaping
262
+ # of samples)
263
+ current_X[:, update_x_indices] = np.moveaxis(
264
+ predictions[:, take_y_indices, comp_idx], 1, -1
265
+ ).reshape(len(current_X), -1)
266
+
267
+ # forecast shape: (n_forecasts * num_samples, n_output_steps, n_components),
268
+ forecast = model._predict(
269
+ x=current_X,
270
+ num_samples=num_samples,
271
+ predict_likelihood_parameters=predict_likelihood_parameters,
272
+ random_state=random_state,
273
+ **predict_kwargs,
274
+ )
275
+
276
+ # reshape to separate forecasts and samples
277
+ # -> (n_forecasts, n_output_steps, n_components, n_samples)
278
+ forecast = np.moveaxis(
279
+ forecast.reshape(
280
+ len(current_X) // num_samples,
281
+ num_samples,
282
+ n_output_steps,
283
+ -1,
284
+ ),
285
+ 1,
286
+ -1,
287
+ )
288
+
289
+ if not multi_models and not is_auto_regression:
290
+ # forecast horizon can include multiple forecasts (of consecutive rows) -> apply
291
+ # sliding window -> (n_forecasts, 1, 1, forecast_horizon, n_components, n_samples)
292
+ forecast = sliding_window_view(
293
+ forecast[:, 0],
294
+ (forecast_horizon, len(forecast_components), num_samples),
295
+ )
296
+
297
+ # remove the last windows, apply stride and extract horizon
298
+ # -> (n_forecasts, forecast_horizon, n_components, n_samples)
299
+ last_window = min(forecast_horizon - output_chunk_length, 0) or None
300
+ forecast = forecast[:last_window:stride, 0, 0, :forecast_horizon, :, :]
301
+
302
+ # -> (n_forecasts, forecast_horizon, n_components, n_samples)
303
+ forecast = forecast[:, take_forecast_indices]
304
+ if predictions is None:
305
+ predictions = forecast
306
+ else:
307
+ predictions = np.concatenate([predictions, forecast], axis=1)
308
+
309
+ if last_points_only:
310
+ # a single TimeSeries with only the last points of each forecast
311
+ # -> TimeSeries with shape: (n_forecasts, n_components, n_samples)
312
+ new_times = generate_index(
313
+ start=hist_fct_start
314
+ + (forecast_horizon + output_chunk_shift - 1) * freq,
315
+ length=predictions.shape[0],
316
+ freq=freq * stride,
317
+ name=series_._time_index.name,
318
+ )
319
+ forecasts = TimeSeries(
320
+ times=new_times,
321
+ values=predictions[:, -1],
322
+ components=forecast_components,
323
+ static_covariates=series_.static_covariates,
324
+ hierarchy=series_.hierarchy,
325
+ metadata=series_.metadata,
326
+ copy=False,
327
+ )
328
+ else:
329
+ # a list of TimeSeries with the complete forecasts
330
+ # -> list[TimeSeries] each with shape: (forecast_horizon, n_components, n_samples)
331
+ forecasts = []
332
+ new_times = generate_index(
333
+ start=hist_fct_start + output_chunk_shift * series_.freq,
334
+ length=forecast_horizon + (predictions.shape[0] - 1) * stride,
335
+ freq=freq,
336
+ name=series_._time_index.name,
337
+ )
338
+ for idx_ftc, step_fct in enumerate(
339
+ range(0, forecast.shape[0] * stride, stride)
340
+ ):
341
+ ts = TimeSeries(
342
+ times=new_times[step_fct : step_fct + forecast_horizon],
343
+ values=predictions[idx_ftc],
344
+ components=forecast_components,
345
+ static_covariates=series_.static_covariates,
346
+ hierarchy=series_.hierarchy,
347
+ metadata=series_.metadata,
348
+ copy=False,
349
+ )
350
+ forecasts.append(ts)
351
+
352
+ forecasts_list.append(forecasts)
353
+ return forecasts_list
datasets/raw/darts_benchmark_datasets/darts/utils/historical_forecasts/utils.py ADDED
@@ -0,0 +1,1666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Optimized Historical Forecasts Utils
3
+ ------------------------------------
4
+ """
5
+
6
+ import inspect
7
+ from collections.abc import Callable, Sequence
8
+ from types import SimpleNamespace
9
+ from typing import Any, Literal, TypeAlias, TypeVar
10
+
11
+ import numpy as np
12
+ import pandas as pd
13
+ from numpy.typing import ArrayLike
14
+
15
+ from darts.dataprocessing.pipeline import Pipeline
16
+ from darts.dataprocessing.transformers import (
17
+ BaseDataTransformer,
18
+ FittableDataTransformer,
19
+ )
20
+ from darts.logging import get_logger, raise_log
21
+ from darts.timeseries import TimeSeries, slice_intersect
22
+ from darts.typing import TimeIndex, TimeSeriesLike
23
+ from darts.utils.ts_utils import (
24
+ SeriesType,
25
+ get_series_seq_type,
26
+ get_single_series,
27
+ series2seq,
28
+ )
29
+ from darts.utils.utils import n_steps_between
30
+
31
+ logger = get_logger(__name__)
32
+
33
+ T = TypeVar("T")
34
+
35
+ ExtendedTimeIndex: TypeAlias = (
36
+ TimeIndex | tuple[int, int] | tuple[pd.Timestamp, pd.Timestamp]
37
+ )
38
+
39
+
40
+ def _historical_forecasts_general_checks(
41
+ model, series, kwargs, is_conformal: bool = False
42
+ ):
43
+ """
44
+ Performs checks common to ForecastingModel and SKLearnModel backtest() methods
45
+
46
+ Parameters
47
+ ----------
48
+ model
49
+ The forecasting model.
50
+ series
51
+ Either series when called from ForecastingModel, or target_series if called from SKLearnModel
52
+ kwargs
53
+ Params specified by the caller of backtest(), they take precedence over the arguments' default values
54
+ """
55
+ # parse kwargs
56
+ n = SimpleNamespace(**kwargs)
57
+ series = series2seq(series)
58
+
59
+ # check forecast horizon
60
+ if n.forecast_horizon <= 0:
61
+ raise_log(
62
+ ValueError("`forecast_horizon` must be a positive integer."),
63
+ )
64
+
65
+ # check stride
66
+ if n.stride <= 0:
67
+ raise_log(
68
+ ValueError("`stride` must be a positive integer."),
69
+ )
70
+
71
+ # check stride for ConformalModel
72
+ if is_conformal and (
73
+ n.stride < model.cal_stride or n.stride % model.cal_stride > 0
74
+ ):
75
+ raise_log(
76
+ ValueError(
77
+ f"`stride` must be a round-multiple of `cal_stride={model.cal_stride}` "
78
+ f"and `>=cal_stride`. Received `stride={n.stride}`"
79
+ ),
80
+ )
81
+
82
+ _general_checks_start(model=model, series=series, n=n, is_conformal=is_conformal)
83
+ _general_checks_probabilistic(model=model, n=n)
84
+ _general_checks_data_transformers(series=series, n=n)
85
+ _general_checks_training(model=model, series=series, n=n)
86
+
87
+ # check fit and predict kwargs
88
+ _ = _historical_forecasts_sanitize_kwargs(
89
+ model=model,
90
+ fit_kwargs=n.fit_kwargs,
91
+ predict_kwargs=n.predict_kwargs,
92
+ retrain=n.retrain is not False and n.retrain != 0,
93
+ val_length=n.val_length,
94
+ show_warnings=n.show_warnings,
95
+ )
96
+
97
+
98
+ def _general_checks_start(
99
+ model,
100
+ series: Sequence[TimeSeries],
101
+ n: SimpleNamespace,
102
+ is_conformal: bool,
103
+ ):
104
+ start = n.start
105
+ start_format = n.start_format
106
+ stride = n.stride
107
+
108
+ if start is None:
109
+ return
110
+
111
+ # check start parameter in general (non series dependent)
112
+ if isinstance(start, str):
113
+ if start != "end":
114
+ raise_log(
115
+ ValueError(f"`start` string value must be 'end', received '{start}'.")
116
+ )
117
+ # start="end" skips all position/timestamp/overlap_end checks;
118
+ # validation happens in _get_historical_forecasts_setup per series
119
+ return
120
+
121
+ if not isinstance(start, float | int | np.int64 | pd.Timestamp):
122
+ raise_log(
123
+ TypeError(
124
+ "`start` must be either `float`, `int`, `pd.Timestamp`, `'end'` or `None`."
125
+ )
126
+ )
127
+
128
+ if start_format not in ["position", "value"]:
129
+ raise_log(
130
+ ValueError(
131
+ f"`start_format` must be one of ['position', 'value']. Received '{start_format}'."
132
+ )
133
+ )
134
+ if start_format == "position" and not isinstance(start, int | np.int64):
135
+ raise_log(
136
+ ValueError(
137
+ f"Since `start_format='position'`, `start` must be an integer, received {type(start)}."
138
+ ),
139
+ )
140
+ if isinstance(start, float):
141
+ if is_conformal:
142
+ raise_log(
143
+ ValueError(
144
+ "`start` of type float is not supported for `ConformalModel`."
145
+ ),
146
+ )
147
+ if not 0.0 <= start <= 1.0:
148
+ raise_log(ValueError("if `start` is a float, must be between 0.0 and 1.0."))
149
+
150
+ series_freq = None
151
+ for idx, series_ in enumerate(series):
152
+ start_is_value = False
153
+ # check specifically for int and Timestamp as error by `get_timestamp_at_point` is too generic
154
+ if isinstance(start, pd.Timestamp):
155
+ if not series_._has_datetime_index:
156
+ raise_log(
157
+ ValueError(
158
+ "if `start` is a `pd.Timestamp`, all series must be indexed with a `pd.DatetimeIndex`"
159
+ ),
160
+ )
161
+ if start > series_.end_time():
162
+ raise_log(
163
+ ValueError(
164
+ f"`start` time `{start}` is after the last timestamp `{series_.end_time()}` of the "
165
+ f"series at index: {idx}."
166
+ ),
167
+ )
168
+ start_is_value = True
169
+ elif isinstance(start, int | np.int64):
170
+ if start_format == "position" or series_.has_datetime_index:
171
+ if start >= len(series_):
172
+ raise_log(
173
+ ValueError(
174
+ f"`start` position `{start}` is out of bounds for series of length {len(series_)} "
175
+ f"at index: {idx}."
176
+ ),
177
+ )
178
+ else:
179
+ if start > series_.end_time(): # format "value" and range index
180
+ raise_log(
181
+ ValueError(
182
+ f"`start` time `{start}` is larger than the last index `{series_.end_time()}` "
183
+ f"for series at index: {idx}."
184
+ ),
185
+ )
186
+ start_is_value = True
187
+
188
+ # `ConformalModel` with `start_format='value'` requires all series to have the same frequency
189
+ if is_conformal and start_is_value:
190
+ if series_freq is None:
191
+ series_freq = series_.freq
192
+
193
+ if series_freq != series_.freq:
194
+ raise_log(
195
+ ValueError(
196
+ f"Found mismatching `series` time index frequencies `{series_freq}` and `{series_.freq}`. "
197
+ f"`start_format='value'` with `ConformalModel` is only supported if all series in "
198
+ f"`series` have the same frequency."
199
+ ),
200
+ )
201
+
202
+ # find valid start position relative to the series start time, otherwise raise an error
203
+ start_idx, _ = _get_start_index(series_, idx, start, start_format, stride)
204
+
205
+ # check that `overlap_end` and `start` are a valid combination
206
+ overlap_end = n.overlap_end
207
+ if (
208
+ not overlap_end
209
+ and start_idx + n.forecast_horizon + model.output_chunk_shift > len(series_)
210
+ ):
211
+ # verbose error messages
212
+ if start_format == "position" or (
213
+ not isinstance(start, pd.Timestamp) and series_._has_datetime_index
214
+ ):
215
+ start_value_msg = f"`start` position `{start}` corresponding to time"
216
+ else:
217
+ start_value_msg = "`start` time"
218
+ start_ = series_._time_index[start_idx]
219
+ raise_log(
220
+ ValueError(
221
+ f"{start_value_msg} `{start_}` is too late in the series {idx} to make any "
222
+ f"predictions with `overlap_end` set to `False`."
223
+ ),
224
+ )
225
+
226
+
227
+ def _general_checks_probabilistic(model, n: SimpleNamespace):
228
+ # duplication of ForecastingModel.predict() check for the optimized historical forecasts implementations
229
+ if not model.supports_probabilistic_prediction and n.num_samples > 1:
230
+ raise_log(
231
+ ValueError("`num_samples > 1` is only supported for probabilistic models."),
232
+ )
233
+
234
+ # check direct likelihood parameter prediction before fitting a model
235
+ if not n.predict_likelihood_parameters:
236
+ return
237
+
238
+ if not model.supports_likelihood_parameter_prediction:
239
+ raise_log(
240
+ ValueError(
241
+ f"Model `{model.__class__.__name__}` does not support `predict_likelihood_parameters=True`. "
242
+ f"Either the model does not support likelihoods, or no `likelihood` was used at model "
243
+ f"creation."
244
+ )
245
+ )
246
+ if n.num_samples != 1:
247
+ raise_log(
248
+ ValueError(
249
+ f"`predict_likelihood_parameters=True` is only supported for `num_samples=1`, "
250
+ f"received {n.num_samples}."
251
+ ),
252
+ )
253
+
254
+ if (
255
+ model.output_chunk_length is not None
256
+ and n.forecast_horizon > model.output_chunk_length
257
+ ):
258
+ raise_log(
259
+ ValueError(
260
+ "`predict_likelihood_parameters=True` is only supported for `forecast_horizon` smaller than or "
261
+ "equal to model's `output_chunk_length`."
262
+ ),
263
+ )
264
+
265
+
266
+ def _general_checks_data_transformers(series: Sequence[TimeSeries], n: SimpleNamespace):
267
+ data_transformers = n.data_transformers
268
+ if data_transformers is None:
269
+ return
270
+
271
+ # check the type
272
+ if not isinstance(data_transformers, dict):
273
+ raise_log(
274
+ ValueError("`data_transformers` must be either `None` or a dictionary.")
275
+ )
276
+ # check the keys
277
+ supported_keys = {"series", "past_covariates", "future_covariates"}
278
+ incorrect_keys = set(data_transformers.keys()) - supported_keys
279
+ if len(incorrect_keys) > 0:
280
+ raise_log(
281
+ ValueError(
282
+ f"The keys supported by `data_transformers` are {supported_keys}, received the following "
283
+ f"incorrect keys: {incorrect_keys}."
284
+ ),
285
+ )
286
+
287
+ # convert to Pipelines
288
+ data_pipelines = _convert_data_transformers(
289
+ data_transformers=data_transformers, copy=False
290
+ )
291
+ # extract pipelines containing at least one fittable element
292
+ fittable_pipelines = [
293
+ transf_ for transf_ in data_pipelines.values() if transf_.fittable
294
+ ]
295
+ # extract pipelines where all the fittable transformer are fitted globally
296
+ global_fit_pipelines = [
297
+ transf_ for transf_ in fittable_pipelines if transf_._global_fit
298
+ ]
299
+
300
+ if n.retrain:
301
+ # if more than one series is passed and the pipelines are retrained, they cannot be global
302
+ if (
303
+ n.show_warnings
304
+ and len(series) > 1
305
+ and len(global_fit_pipelines) > 0
306
+ and not n.apply_globally
307
+ ):
308
+ logger.warning(
309
+ "When `retrain=True` and multiple series are provided, the fittable `data_transformers` "
310
+ "are trained on each series independently (`global_fit=True` will be ignored)."
311
+ )
312
+ return
313
+
314
+ # must already be fitted without retraining
315
+ not_fitted_pipelines = [
316
+ name_
317
+ for name_, transf_ in data_pipelines.items()
318
+ if transf_.fittable and not transf_._fit_called
319
+ ]
320
+ if len(not_fitted_pipelines) > 0:
321
+ raise_log(
322
+ ValueError(
323
+ "All the fittable entries in `data_transformers` must already be fitted when "
324
+ f"`retrain=False`, the following entries were not fitted: {', '.join(not_fitted_pipelines)}."
325
+ ),
326
+ )
327
+ # extract the number of fitted params in each pipeline (already fitted)
328
+ fitted_params_pipelines = [
329
+ max(
330
+ len(t._fitted_params)
331
+ for t in pipeline
332
+ if isinstance(t, FittableDataTransformer)
333
+ )
334
+ for pipeline in data_pipelines.values()
335
+ ]
336
+
337
+ if len(series) > 1:
338
+ # if multiple series are passed and the pipelines are not all globally fitted, the number of series must
339
+ # match the number of fitted params in the pipelines
340
+ if len(global_fit_pipelines) != len(fittable_pipelines) and len(series) != max(
341
+ fitted_params_pipelines
342
+ ):
343
+ raise_log(
344
+ ValueError(
345
+ f"When multiple series are provided, their number should match the number of "
346
+ f"`TimeSeries` used to fit the data transformers `n={max(fitted_params_pipelines)}` "
347
+ f"(only relevant for fittable transformers that use `global_fit=False`)."
348
+ ),
349
+ )
350
+ else:
351
+ # at least one pipeline was fitted on several series with `global_fit=False` but only
352
+ # one series was passed
353
+ if n.show_warnings and max(fitted_params_pipelines) > 1:
354
+ logger.warning(
355
+ "Provided only a single series, but at least one of the `data_transformers` "
356
+ "that use `global_fit=False` was fitted on multiple `TimeSeries`."
357
+ )
358
+
359
+
360
+ def _general_checks_training(model, series: Sequence[TimeSeries], n: SimpleNamespace):
361
+ retrain = n.retrain
362
+ val_length = n.val_length
363
+
364
+ # check retrain value
365
+ if not (
366
+ isinstance(retrain, bool)
367
+ or (isinstance(retrain, int) and retrain >= 0)
368
+ or (isinstance(retrain, Callable))
369
+ ):
370
+ raise_log(
371
+ ValueError(
372
+ "`retrain` must be either `bool`, positive `int` or a "
373
+ "`Callable` returning a `bool`."
374
+ ),
375
+ )
376
+ elif isinstance(retrain, Callable):
377
+ retrain_func = retrain
378
+
379
+ # check that the signature matches the documentation
380
+ expected_arguments = [
381
+ "counter",
382
+ "pred_time",
383
+ "train_series",
384
+ "past_covariates",
385
+ "future_covariates",
386
+ ]
387
+ passed_arguments = list(inspect.signature(retrain_func).parameters.keys())
388
+ if expected_arguments != passed_arguments:
389
+ raise_log(
390
+ ValueError(
391
+ f"the Callable `retrain` must have a signature/arguments matching "
392
+ f"the following positional arguments: `{expected_arguments}`."
393
+ ),
394
+ )
395
+
396
+ # passing dummy values to check the type of the output
397
+ result = retrain_func(
398
+ counter=0,
399
+ pred_time=get_single_series(series).end_time(),
400
+ train_series=get_single_series(series),
401
+ past_covariates=get_single_series(n.past_covariates),
402
+ future_covariates=get_single_series(n.future_covariates),
403
+ )
404
+ if not isinstance(result, bool):
405
+ raise_log(
406
+ ValueError(
407
+ f"Return value of `retrain` must be bool, received {type(result)}"
408
+ ),
409
+ )
410
+
411
+ # model must have been fitted if not retraining
412
+ if not model._fit_called and retrain is False:
413
+ raise_log(
414
+ ValueError(
415
+ "The model has not been fitted yet, and `retrain` is ``False``. "
416
+ "Either call `fit()` before `historical_forecasts()`, or set `retrain` "
417
+ "to something different than ``False``."
418
+ ),
419
+ )
420
+ # only certain trained models support non-retrainable historical forecasts
421
+ if (isinstance(retrain, Callable) or int(retrain) != 1) and (
422
+ not model._supports_non_retrainable_historical_forecasts
423
+ ):
424
+ raise_log(
425
+ ValueError(
426
+ f"{model.__class__.__base__.__name__} does not support historical forecasting "
427
+ f"with `retrain` set to `False`. For now, this is only supported with "
428
+ f"GlobalForecastingModels such as TorchForecastingModels. For more information, "
429
+ f"read the documentation for `retrain` in `historical_forecasts()`"
430
+ ),
431
+ )
432
+
433
+ # check training length
434
+ if n.train_length is not None and n.train_length <= 0:
435
+ raise_log(
436
+ ValueError("`train_length` must be `None` or a positive integer."),
437
+ )
438
+ elif n.train_length is not None:
439
+ if retrain is False:
440
+ raise_log(
441
+ ValueError("Cannot use `train_length` with `retrain=False`."),
442
+ )
443
+ elif n.train_length < model.min_train_series_length:
444
+ raise_log(
445
+ ValueError(
446
+ "`train_length` is too small for the training requirements of this model. "
447
+ f"Must be `>={model.min_train_series_length}`."
448
+ ),
449
+ )
450
+
451
+ # check val length
452
+ if val_length < 0:
453
+ raise_log(
454
+ ValueError("`val_length` must be a non-negative integer."),
455
+ )
456
+ elif val_length >= 1:
457
+ if retrain is False:
458
+ raise_log(
459
+ ValueError("Cannot use `val_length` with `retrain=False`."),
460
+ )
461
+ elif val_length < model._target_window_lengths[1]:
462
+ # val length must cover at least one full prediction output (e.g. output window)
463
+ # the first input window is taken from the end of training series to use all available data
464
+ raise_log(
465
+ ValueError(
466
+ f"`val_length` is too small for the validation requirements of this model. "
467
+ f"Must be `>={model._target_window_lengths[1]}`."
468
+ )
469
+ )
470
+
471
+ if (
472
+ n.sample_weight is not None
473
+ and not isinstance(n.sample_weight, str)
474
+ and model.supports_sample_weight
475
+ ):
476
+ sample_weight = series2seq(n.sample_weight)
477
+ for idx, (series_, sample_weight_) in enumerate(zip(series, sample_weight)):
478
+ is_valid = (
479
+ sample_weight_.freq == series_.freq
480
+ and sample_weight_.start_time() <= series_.start_time()
481
+ and len(sample_weight_) >= len(series_)
482
+ )
483
+ if not is_valid:
484
+ raise_log(
485
+ ValueError(
486
+ f"`sample_weight` at series index {idx} must contain at least all times "
487
+ f"of the corresponding target `series`."
488
+ ),
489
+ )
490
+
491
+
492
+ def _historical_forecasts_sanitize_kwargs(
493
+ model,
494
+ fit_kwargs: dict[str, Any] | None,
495
+ predict_kwargs: dict[str, Any] | None,
496
+ retrain: bool,
497
+ val_length: int,
498
+ show_warnings: bool,
499
+ ) -> tuple[dict[str, Any], dict[str, Any]]:
500
+ """Convert kwargs to dictionary, check that their content is compatible with called methods."""
501
+ hfc_args = set(inspect.signature(model.historical_forecasts).parameters)
502
+ # replace `forecast_horizon` with `n` and allow some duplicate parameters
503
+ hfc_args = hfc_args - {"forecast_horizon", "verbose"}
504
+ hfc_args = hfc_args.union({"n"})
505
+
506
+ if fit_kwargs is None:
507
+ fit_kwargs = dict()
508
+ elif retrain:
509
+ fit_kwargs = _historical_forecasts_check_kwargs(
510
+ hfc_args=hfc_args,
511
+ name_kwargs="fit_kwargs",
512
+ dict_kwargs=fit_kwargs,
513
+ )
514
+ if val_length > 0 and fit_kwargs.get("val_series") is not None:
515
+ raise_log(
516
+ ValueError(
517
+ "`val_length` must be `0` when `val_series` is provided in `fit_kwargs`."
518
+ ),
519
+ )
520
+ elif show_warnings:
521
+ logger.warning(
522
+ "`fit_kwargs` was provided with `retrain=False`, the argument will be ignored."
523
+ )
524
+
525
+ if predict_kwargs is None:
526
+ predict_kwargs = dict()
527
+ else:
528
+ predict_kwargs = _historical_forecasts_check_kwargs(
529
+ hfc_args=hfc_args,
530
+ name_kwargs="predict_kwargs",
531
+ dict_kwargs=predict_kwargs,
532
+ )
533
+ return fit_kwargs, predict_kwargs
534
+
535
+
536
+ def _historical_forecasts_check_kwargs(
537
+ hfc_args: set[str],
538
+ name_kwargs: str,
539
+ dict_kwargs: dict[str, Any],
540
+ ) -> dict[str, Any]:
541
+ """
542
+ Return the kwargs dict without the arguments unsupported by the model method.
543
+
544
+ Raise a warning if some argument are not supported and an exception if some arguments interfere with
545
+ historical_forecasts logic.
546
+ """
547
+ invalid_args = set(dict_kwargs).intersection(hfc_args)
548
+ if len(invalid_args) > 0:
549
+ raise_log(
550
+ ValueError(
551
+ f"The following parameters cannot be passed in `{name_kwargs}`: {invalid_args}. "
552
+ f"Make sure to pass them explicitly to the function/method."
553
+ ),
554
+ )
555
+ return dict_kwargs
556
+
557
+
558
+ def _get_start_index(
559
+ series: TimeSeries,
560
+ series_idx: int,
561
+ start: pd.Timestamp | int | float | Literal["end"],
562
+ start_format: Literal["value", "position"],
563
+ stride: int,
564
+ historical_forecasts_time_index: ExtendedTimeIndex | None = None,
565
+ ):
566
+ """Finds a valid historical forecast start point within either `series` or `historical_forecasts_time_index`
567
+ (depending on whether `historical_forecasts_time_index` is passed, denoted as `ref`).
568
+
569
+ - If `start` is larger or equal to the first index of `ref`, uses `start` directly.
570
+ - If `start` is before the first index of `ref`, tries to find a start point within `ref` that lies a
571
+ round-multiple `stride` time steps ahead of `start`.
572
+
573
+ Raises an error if the new start index from above is larger than the last index in `ref`.
574
+
575
+ Parameters
576
+ ----------
577
+ series
578
+ A time series. If `historical_forecasts_time_index` is `None`, will use this series' time index as a reference
579
+ index.
580
+ series_idx
581
+ The sequence index of the `series`.
582
+ start
583
+ The start point for historical forecasts.
584
+ start_format
585
+ The start format for historical forecasts.
586
+ stride
587
+ The stride for historical forecasts.
588
+ historical_forecasts_time_index
589
+ Optionally, the historical forecast index (or the boundaries only) to use as the reference index.
590
+ """
591
+ series_start, series_end = series.start_time(), series.end_time()
592
+ has_dti = series._has_datetime_index
593
+ # find start position relative to the series start time
594
+ if isinstance(start, float):
595
+ # fraction of series
596
+ rel_start = series.get_index_at_point(start)
597
+ elif start_format == "value" and not (isinstance(start, int) and has_dti):
598
+ # start is a time stamp for DatetimeIndex, and integer for RangeIndex
599
+ rel_start = n_steps_between(start, series_start, freq=series.freq)
600
+ else:
601
+ # start is a positional index
602
+ start: int
603
+ rel_start = start if start >= 0 else len(series) - abs(start)
604
+
605
+ # find actual start time
606
+ start_idx = _adjust_start(rel_start, stride)
607
+ _check_start(
608
+ series=series,
609
+ start_idx=start_idx,
610
+ start=start,
611
+ start_format=start_format,
612
+ series_start=series_start,
613
+ ref_start=series_start,
614
+ ref_end=series_end,
615
+ stride=stride,
616
+ series_idx=series_idx,
617
+ is_historical_forecast=False,
618
+ )
619
+ if historical_forecasts_time_index is not None:
620
+ hfc_start, hfc_end = (
621
+ historical_forecasts_time_index[0],
622
+ historical_forecasts_time_index[-1],
623
+ )
624
+ # at this point, we know that `start_idx` is within `series`. Now, find the position of that time step
625
+ # relative to the first forecastable point
626
+ rel_start_hfc = n_steps_between(
627
+ series._time_index[start_idx], hfc_start, freq=series.freq
628
+ )
629
+ # get the positional index of `hfc_start` in `series`
630
+ hfc_start_idx = start_idx - rel_start_hfc
631
+ # potentially, adjust the position to be inside the forecastable points
632
+ hfc_start_idx += _adjust_start(rel_start_hfc, stride)
633
+ _check_start(
634
+ series=series,
635
+ start_idx=hfc_start_idx,
636
+ start=start,
637
+ start_format=start_format,
638
+ series_start=series_start,
639
+ ref_start=hfc_start,
640
+ ref_end=hfc_end,
641
+ stride=stride,
642
+ series_idx=series_idx,
643
+ is_historical_forecast=True,
644
+ )
645
+ start_idx = hfc_start_idx
646
+ return start_idx, rel_start
647
+
648
+
649
+ def _adjust_start(rel_start, stride):
650
+ """If relative start position `rel_start` is negative, then adjust it to the first non-negative index that lies a
651
+ round-multiple of `stride` ahead of `rel_start`
652
+ """
653
+ if rel_start >= 0:
654
+ start_idx = rel_start
655
+ else:
656
+ # if `start` lies before the start time of `series` -> check if there is a valid start point in
657
+ # `series` that is a round-multiple of `stride` ahead of `start`
658
+ start_idx = (
659
+ rel_start
660
+ + (abs(rel_start) // stride + int(abs(rel_start) % stride > 0)) * stride
661
+ )
662
+ return start_idx
663
+
664
+
665
+ def _check_start(
666
+ series: TimeSeries,
667
+ start_idx: int,
668
+ start: pd.Timestamp | int | float,
669
+ start_format: Literal["value", "position"],
670
+ series_start: pd.Timestamp | int,
671
+ ref_start: pd.Timestamp | int,
672
+ ref_end: pd.Timestamp | int,
673
+ stride: int,
674
+ series_idx: int,
675
+ is_historical_forecast: bool,
676
+ ):
677
+ """Raises an error if the start index (position) is not within the series."""
678
+ if start_idx < len(series):
679
+ return
680
+
681
+ if start_format == "position" or (
682
+ not isinstance(start, pd.Timestamp) and series._has_datetime_index
683
+ ):
684
+ start_format_msg = f"position `{start}` corresponding to time "
685
+ if isinstance(start, float):
686
+ # fraction of series
687
+ start = series.get_index_at_point(start)
688
+ elif start >= 0:
689
+ # start >= 0 is relative to the start
690
+ start = series.start_time() + start * series.freq
691
+ else:
692
+ # start < 0 is relative to the end
693
+ start = series.end_time() + (start + 1) * series.freq
694
+ else:
695
+ start_format_msg = "time "
696
+ ref_msg = "" if not is_historical_forecast else "historical forecastable "
697
+ start_new = series_start + start_idx * series.freq
698
+ raise_log(
699
+ ValueError(
700
+ f"`start` {start_format_msg}`{start}` is smaller than the first {ref_msg}time index "
701
+ f"`{ref_start}` for series at index: {series_idx}, and could not find a valid start "
702
+ f"point within the {ref_msg}time index that lies a round-multiple of `stride={stride}` "
703
+ f"ahead of `start` (first inferred start is `{start_new}`, but last {ref_msg}time index "
704
+ f"is `{ref_end}`."
705
+ ),
706
+ )
707
+
708
+
709
+ def _get_historical_forecasts_setup(
710
+ model,
711
+ series: TimeSeries,
712
+ past_covariates: TimeSeries | None,
713
+ future_covariates: TimeSeries | None,
714
+ series_idx: int,
715
+ forecast_horizon: int,
716
+ start: pd.Timestamp | int | float | Literal["end"] | None,
717
+ start_format: Literal["value", "position"],
718
+ stride: int,
719
+ overlap_end: bool,
720
+ retrain: bool | int | Callable[..., bool],
721
+ train_length: int | None,
722
+ val_length: int,
723
+ show_warnings: bool,
724
+ ) -> tuple[
725
+ tuple[int, int] | tuple[pd.Timestamp, pd.Timestamp] | None,
726
+ TimeSeries,
727
+ int | None,
728
+ int,
729
+ ]:
730
+ # get the first and last historical forecast start points for either (re)training or (zero shot) prediction
731
+ # mode; models that don't require training (e.g. global naive models, foundation models without fine-tuning)
732
+ # use prediction-mode extreme lags even when retrain is set
733
+ is_training = bool(retrain) and model._requires_training
734
+ overlap_end = True if start == "end" else overlap_end
735
+ historical_forecasts_time_index = _get_maximum_historical_forecastable_time_index(
736
+ model=model,
737
+ series=series,
738
+ forecast_horizon=forecast_horizon,
739
+ overlap_end=overlap_end,
740
+ past_covariates=past_covariates,
741
+ future_covariates=future_covariates,
742
+ is_training=is_training,
743
+ )
744
+
745
+ if historical_forecasts_time_index is None:
746
+ raise_log(
747
+ ValueError(
748
+ f"Cannot build any dataset {'to train the model' if is_training else 'for prediction'} "
749
+ f"with the provided `series` and `*_covariates` at series index: {series_idx}. "
750
+ f"The minimum {'training' if is_training else 'prediction'} input time index requirements "
751
+ f"were not met. Please check the time index of `series` and `*_covariates`."
752
+ ),
753
+ )
754
+
755
+ if is_training:
756
+ # trainable time indexes (considering lags and available covariates)
757
+ # We need the first value timestamp to be used in order to properly shift the series
758
+ # Look at both past and future, since the target lags must be taken in consideration
759
+ min_timestamp_series = (
760
+ historical_forecasts_time_index[0]
761
+ - model.min_train_series_length * series.freq
762
+ )
763
+ else:
764
+ # predictable time indexes (assuming model is already trained)
765
+ # we are only predicting: start of the series does not have to change
766
+ min_timestamp_series = series.start_time()
767
+
768
+ # based on `is_training`, historical_forecasts_time_index is based either on train or predict
769
+ (
770
+ historical_forecasts_time_index,
771
+ train_length,
772
+ val_length,
773
+ ) = _adjust_historical_forecasts_time_index_training(
774
+ model=model,
775
+ historical_forecasts_time_index=historical_forecasts_time_index,
776
+ series=series,
777
+ series_idx=series_idx,
778
+ is_training=is_training,
779
+ train_length=train_length,
780
+ val_length=val_length,
781
+ show_warnings=show_warnings,
782
+ )
783
+
784
+ # based on `start`, historical_forecasts_time_index is shortened
785
+ historical_forecasts_time_index = _adjust_historical_forecasts_time_index(
786
+ series=series,
787
+ series_idx=series_idx,
788
+ historical_forecasts_time_index=historical_forecasts_time_index,
789
+ start=start,
790
+ start_format=start_format,
791
+ stride=stride,
792
+ show_warnings=show_warnings,
793
+ )
794
+
795
+ # adjust the start of the series depending on whether we train (at some point), or predict only
796
+ # must be performed after the operation on historical_forecasts_time_index
797
+ if min_timestamp_series > series.start_time():
798
+ series = series.drop_before(min_timestamp_series, keep_point=True)
799
+
800
+ return historical_forecasts_time_index, series, train_length, val_length
801
+
802
+
803
+ def _get_maximum_historical_forecastable_time_index(
804
+ model,
805
+ series: TimeSeries,
806
+ forecast_horizon: int,
807
+ overlap_end: bool,
808
+ past_covariates: TimeSeries | None = None,
809
+ future_covariates: TimeSeries | None = None,
810
+ is_training: bool | None = False,
811
+ ) -> ExtendedTimeIndex | None:
812
+ """Computes the maximum historical forecastable time index for training or prediction mode.
813
+
814
+ Only accounts for `is_training`, `forecast_horizon`, `overlap_end`.
815
+
816
+ Returns the largest time_index representing the subset of each timestamps for which historical forecasts can be
817
+ made, given the model's properties, the training series
818
+ and the covariates.
819
+ - If ``None`` is returned, there is no point where a forecast can be made.
820
+
821
+ - If ``is_training=False``, it returns the time_index subset of predictable timestamps.
822
+
823
+ - If ``is_training=True``, it returns the time_index subset of trainable timestamps. A trainable
824
+ timestamp is a timestamp that has a training sample of length at least ``self.training_sample_length``
825
+ preceding it.
826
+
827
+ Additionally, it accounts for auto-regression (forecast_horizon > model.output_chunk_length , and overlap_end.
828
+ - In case of auto-regression, we have to step back the last possible predictable/trainable time step if the
829
+ covariates are too short
830
+ - In case overlap_end=False, the latest possible predictable/trainable time step is shifted back if a
831
+ prediction starting from that point would go beyond the end of `series`.
832
+
833
+
834
+ Parameters
835
+ ----------
836
+ series
837
+ A target series.
838
+ forecast_horizon
839
+ The forecast horizon for the predictions.
840
+ overlap_end
841
+ Whether the returned forecasts can go beyond the series' end or not.
842
+ past_covariates
843
+ Optionally, a past covariates.
844
+ future_covariates
845
+ Optionally, a future covariates.
846
+ is_training
847
+ Whether the returned time_index should be taking into account the training.
848
+ Returns
849
+ -------
850
+ pd.DatetimeIndex | pd.RangeIndex | tuple[int, int] | tuple[pd.Timestamp, pd.Timestamp] | None
851
+ The longest time_index that can be used for historical forecasting, either as a range or a tuple.
852
+
853
+ Examples
854
+ --------
855
+ >>> model = LinearRegressionModel(lags=3, output_chunk_length=2)
856
+ >>> model.fit(train_series)
857
+ >>> series = TimeSeries.from_times_and_values(pd.date_range('2000-01-01', '2000-01-10'), np.arange(10))
858
+ >>> model._get_maximum_historical_forecastable_time_index(series=series, is_training=False, forecast_horizon=1)
859
+ DatetimeIndex(
860
+ ['2000-01-04', '2000-01-05', '2000-01-06', '2000-01-07', '2000-01-08', '2000-01-09', '2000-01-10'],
861
+ dtype='datetime64[ns]', freq='D'
862
+ )
863
+ >>> model._get_maximum_historical_forecastable_time_index(series=series, is_training=True)
864
+ DatetimeIndex(['2000-01-06', '2000-01-08', '2000-01-09', '2000-01-10'], dtype='datetime64[ns]', freq='D')
865
+ >>> model = NBEATSModel(input_chunk_length=3, output_chunk_length=3)
866
+ >>> model.fit(train_series, train_past_covariates)
867
+ >>> series = TimeSeries.from_times_and_values(pd.date_range('2000-10-01', '2000-10-09'), np.arange(8))
868
+ >>> past_covariates = TimeSeries.from_times_and_values(
869
+ >>> pd.date_range('2000-10-03', '2000-10-20'),
870
+ >>> np.arange(18)
871
+ >>> )
872
+ >>> model._get_maximum_historical_forecastable_time_index(
873
+ >>> series=series,
874
+ >>> past_covariates=past_covariates,
875
+ >>> is_training=False,
876
+ >>> forecast_horizon=1,
877
+ >>> )
878
+ DatetimeIndex(['2000-10-06', '2000-10-07', '2000-10-08', '2000-10-09'], dtype='datetime64[ns]', freq='D')
879
+ >>> # Only one point is trainable; it corresponds to the first point after we reach a common subset of
880
+ >>> # timestamps of training_sample_length length.
881
+ >>> model._get_maximum_historical_forecastable_time_index(
882
+ >>> series=series,
883
+ >>> past_covariates=past_covariates,
884
+ >>> is_training=True,
885
+ >>> )
886
+ DatetimeIndex(['2000-10-09'], dtype='datetime64[ns]', freq='D')
887
+ """
888
+
889
+ (
890
+ min_target_lag,
891
+ max_target_lag,
892
+ min_past_cov_lag,
893
+ max_past_cov_lag,
894
+ min_future_cov_lag,
895
+ max_future_cov_lag,
896
+ output_chunk_shift,
897
+ ) = model.extreme_lags
898
+
899
+ # max_target_lag < 0 are local models which can predict for n (horizon) -> infinity (no auto-regression)
900
+ is_autoregression = (
901
+ max_target_lag >= 0
902
+ and forecast_horizon > max_target_lag - output_chunk_shift + 1
903
+ )
904
+
905
+ if min_target_lag is None:
906
+ min_target_lag = 0
907
+
908
+ # if SKLearnModel is not multi_models, prediction steps < output_chunk_length must look further into the past
909
+ is_single_sklearn_model = getattr(model, "multi_models", None) is False
910
+ if is_single_sklearn_model:
911
+ extra_lookback = model.output_chunk_length - 1
912
+ else:
913
+ extra_lookback = 0
914
+
915
+ # longest possible time index for target
916
+ if is_training:
917
+ start = (
918
+ series.start_time() + (max_target_lag - min_target_lag + 1) * series.freq
919
+ )
920
+ else:
921
+ start = series.start_time() + (extra_lookback - min_target_lag) * series.freq
922
+ end = series.end_time() + 1 * series.freq
923
+
924
+ intersect_ = (start, end)
925
+
926
+ # longest possible time index for past covariates
927
+ if (min_past_cov_lag is not None) and (past_covariates is not None):
928
+ if is_training:
929
+ start_pc = (
930
+ past_covariates.start_time()
931
+ + (max_target_lag - min_past_cov_lag + 1) * past_covariates.freq
932
+ )
933
+ else:
934
+ start_pc = (
935
+ past_covariates.start_time()
936
+ + (extra_lookback - min_past_cov_lag) * past_covariates.freq
937
+ )
938
+
939
+ shift_pc_end = max_past_cov_lag
940
+ if is_autoregression:
941
+ # we step back in case of auto-regression
942
+ shift_pc_end += forecast_horizon - (max_target_lag - output_chunk_shift + 1)
943
+ end_pc = past_covariates.end_time() - shift_pc_end * past_covariates.freq
944
+
945
+ intersect_ = (
946
+ max([intersect_[0], start_pc]),
947
+ min([intersect_[1], end_pc]),
948
+ )
949
+
950
+ # longest possible time index for future covariates
951
+ if (min_future_cov_lag is not None) and (future_covariates is not None):
952
+ if is_training:
953
+ start_fc = (
954
+ future_covariates.start_time()
955
+ + (max_target_lag - min_future_cov_lag + 1) * future_covariates.freq
956
+ )
957
+ else:
958
+ start_fc = (
959
+ future_covariates.start_time()
960
+ + (extra_lookback - min_future_cov_lag) * future_covariates.freq
961
+ )
962
+
963
+ shift_fc_end = max_future_cov_lag
964
+ if is_autoregression:
965
+ # we step back in case of auto-regression
966
+ shift_fc_end += forecast_horizon - (max_target_lag - output_chunk_shift + 1)
967
+ elif max_target_lag < 0:
968
+ # local models have no fixed output window but still need future
969
+ # covariates for the full forecast horizon
970
+ shift_fc_end += forecast_horizon - 1
971
+ end_fc = future_covariates.end_time() - shift_fc_end * future_covariates.freq
972
+
973
+ intersect_ = (
974
+ max([intersect_[0], start_fc]),
975
+ min([intersect_[1], end_fc]),
976
+ )
977
+
978
+ # overlap_end = False -> predictions must not go beyond end of target series
979
+ if (
980
+ not overlap_end
981
+ and intersect_[1] + (forecast_horizon + output_chunk_shift - 1) * series.freq
982
+ > series.end_time()
983
+ ):
984
+ intersect_ = (
985
+ intersect_[0],
986
+ end - (forecast_horizon + output_chunk_shift) * series.freq,
987
+ )
988
+
989
+ # more than one training sample is required; start later
990
+ if is_training and model.min_train_samples > 1:
991
+ intersect_ = (
992
+ intersect_[0] + (model.min_train_samples - 1) * series.freq,
993
+ intersect_[1],
994
+ )
995
+
996
+ # end comes before the start
997
+ if intersect_[1] < intersect_[0]:
998
+ return None
999
+
1000
+ return intersect_
1001
+
1002
+
1003
+ def _adjust_historical_forecasts_time_index(
1004
+ series: TimeSeries,
1005
+ series_idx: int,
1006
+ historical_forecasts_time_index: ExtendedTimeIndex,
1007
+ start: pd.Timestamp | float | int | Literal["end"] | None,
1008
+ start_format: Literal["position", "value"],
1009
+ stride: int,
1010
+ show_warnings: bool,
1011
+ ) -> ExtendedTimeIndex:
1012
+ """
1013
+ Shrink the beginning and end of the historical forecasts time index based on the value of `start`.
1014
+ """
1015
+ if start is None:
1016
+ return historical_forecasts_time_index
1017
+
1018
+ if start == "end":
1019
+ desired_pred_time = series.end_time() + series.freq
1020
+ if (
1021
+ desired_pred_time < historical_forecasts_time_index[0]
1022
+ or desired_pred_time > historical_forecasts_time_index[1]
1023
+ ):
1024
+ raise_log(
1025
+ ValueError(
1026
+ f"Cannot generate a forecast with `start='end'` for series at index: {series_idx}. "
1027
+ f"The prediction start point one step after the series end "
1028
+ f"(`{desired_pred_time}`) is outside the forecastable time range "
1029
+ f"`({historical_forecasts_time_index[0]}, {historical_forecasts_time_index[1]})`. "
1030
+ f"Please check that the `series` and `*_covariates` are long enough."
1031
+ ),
1032
+ )
1033
+ return desired_pred_time, desired_pred_time
1034
+
1035
+ # retrieve actual start
1036
+ # find valid start position relative to the hfc start time, otherwise raise an error
1037
+ start_idx, start_idx_orig = _get_start_index(
1038
+ series=series,
1039
+ series_idx=series_idx,
1040
+ start=start,
1041
+ start_format=start_format,
1042
+ stride=stride,
1043
+ historical_forecasts_time_index=historical_forecasts_time_index,
1044
+ )
1045
+ start_time = series._time_index[start_idx]
1046
+
1047
+ if start_time > historical_forecasts_time_index[1]:
1048
+ start_value_msg = _get_start_value_msg(
1049
+ series=series,
1050
+ start=start,
1051
+ start_format=start_format,
1052
+ start_idx_orig=start_idx_orig,
1053
+ )
1054
+ raise_log(
1055
+ ValueError(
1056
+ f"`start` {start_value_msg} is after the last historical forecastable time index "
1057
+ f"`{historical_forecasts_time_index[1]}` for series at index: {series_idx}. "
1058
+ f"Please check the time index of `series` and `*_covariates`."
1059
+ ),
1060
+ )
1061
+
1062
+ if start_idx != start_idx_orig and show_warnings:
1063
+ start_value_msg = _get_start_value_msg(
1064
+ series=series,
1065
+ start=start,
1066
+ start_format=start_format,
1067
+ start_idx_orig=start_idx_orig,
1068
+ )
1069
+ logger.warning(
1070
+ f"`start` {start_value_msg} is before the first predictable/trainable historical "
1071
+ f"forecasting point for series at index: {series_idx}. Using the first historical forecasting "
1072
+ f"point `{start_time}` that lies a round-multiple of `stride={stride}` "
1073
+ f"ahead of `start`. To hide these warnings, set `show_warnings=False`."
1074
+ )
1075
+ historical_forecasts_time_index = (
1076
+ max(historical_forecasts_time_index[0], start_time),
1077
+ historical_forecasts_time_index[1],
1078
+ )
1079
+ return historical_forecasts_time_index
1080
+
1081
+
1082
+ def _get_start_value_msg(
1083
+ series: TimeSeries,
1084
+ start: pd.Timestamp | float | int | Literal["end"] | None,
1085
+ start_format: Literal["position", "value"],
1086
+ start_idx_orig: int,
1087
+ ) -> str:
1088
+ """Get a resolved start value message for warnings and exceptions."""
1089
+ if start_idx_orig >= 0:
1090
+ start_time_orig = series._time_index[start_idx_orig]
1091
+ else:
1092
+ start_time_orig = series.start_time() + start_idx_orig * series.freq
1093
+
1094
+ if start_format == "position" or (
1095
+ not isinstance(start, pd.Timestamp) and series._has_datetime_index
1096
+ ):
1097
+ start_value_msg = (
1098
+ f"position `{start}` corresponding to time `{start_time_orig}`"
1099
+ )
1100
+ else:
1101
+ start_value_msg = f"time `{start_time_orig}`"
1102
+ return start_value_msg
1103
+
1104
+
1105
+ def _adjust_historical_forecasts_time_index_training(
1106
+ model,
1107
+ historical_forecasts_time_index: ExtendedTimeIndex,
1108
+ series: TimeSeries,
1109
+ series_idx: int,
1110
+ is_training: bool,
1111
+ train_length: int | None,
1112
+ val_length: int,
1113
+ show_warnings: bool,
1114
+ ) -> tuple[ExtendedTimeIndex, int | None, int]:
1115
+ """
1116
+ Shrink the beginning of the historical forecasts time index based on the value of `is_training`, `train_length`
1117
+ and `val_length`.
1118
+ """
1119
+ # if not training and model is already fitted, ignore train_length and val_length
1120
+ effective_train_length = None
1121
+ effective_val_length = 0
1122
+
1123
+ if not (is_training or (not model._fit_called)):
1124
+ return (
1125
+ historical_forecasts_time_index,
1126
+ effective_train_length,
1127
+ effective_val_length,
1128
+ )
1129
+
1130
+ # adjust start time based on train_length
1131
+ warn_train_length = False
1132
+ start_time = historical_forecasts_time_index[0]
1133
+ if train_length is not None:
1134
+ # hfc start might already be shifted from target-only start due to shorter covariates;
1135
+ # we want `train_length` to start from the first target step that is used for training
1136
+ start_shifted = n_steps_between(
1137
+ end=historical_forecasts_time_index[0],
1138
+ start=series.start_time() + model.min_train_series_length * series.freq,
1139
+ freq=series.freq,
1140
+ )
1141
+ train_length_adjusted = train_length + start_shifted
1142
+ if train_length_adjusted < len(series):
1143
+ train_length_start = series._time_index[train_length_adjusted]
1144
+ else:
1145
+ train_length_start = (
1146
+ series.start_time() + train_length_adjusted * series.freq
1147
+ )
1148
+
1149
+ if train_length_start > historical_forecasts_time_index[-1]:
1150
+ # train_length extends beyond available data
1151
+ warn_train_length = True
1152
+ else:
1153
+ # train_length is valid
1154
+ effective_train_length = train_length
1155
+ if train_length_start > historical_forecasts_time_index[0]:
1156
+ start_time = train_length_start
1157
+
1158
+ historical_forecasts_time_index = (start_time, historical_forecasts_time_index[1])
1159
+
1160
+ # adjust start time based on val_length
1161
+ warn_val_length = False
1162
+ start_time = historical_forecasts_time_index[0]
1163
+ if val_length:
1164
+ # adjust for val_length
1165
+ val_length_start = historical_forecasts_time_index[0] + val_length * series.freq
1166
+ if val_length_start > historical_forecasts_time_index[-1]:
1167
+ # val_length extends beyond available data
1168
+ warn_val_length = True
1169
+ else:
1170
+ # val_length is valid
1171
+ effective_val_length = val_length
1172
+ start_time = val_length_start
1173
+
1174
+ if not model.supports_transferable_series_prediction:
1175
+ # if the model cannot be trained on partial history, ignore val_length but still
1176
+ if show_warnings:
1177
+ logger.warning(
1178
+ "`val_length` is ignored (no validation set will be created) since "
1179
+ "the model must be trained on the entire series history ending just "
1180
+ "before the prediction start time. To hide these warnings, set "
1181
+ "`show_warnings=False`."
1182
+ )
1183
+ effective_val_length = 0
1184
+
1185
+ historical_forecasts_time_index = (start_time, historical_forecasts_time_index[1])
1186
+
1187
+ if warn_train_length and show_warnings:
1188
+ logger.warning(
1189
+ f"`train_length` is too large for the historical forecasts of the series at index: {series_idx}. "
1190
+ f"Ignoring `train_length` and using default behavior where all available time steps up "
1191
+ f"until the end of the expanding training set. To hide these warnings, set `show_warnings=False`."
1192
+ )
1193
+ if warn_val_length and show_warnings:
1194
+ logger.warning(
1195
+ f"`val_length` is too large for the historical forecasts of the series at index: {series_idx}. "
1196
+ f"Ignoring `val_length` and will not pass an evaluation set to fit the model. To hide these "
1197
+ f"warnings, set `show_warnings=False`."
1198
+ )
1199
+
1200
+ return historical_forecasts_time_index, effective_train_length, effective_val_length
1201
+
1202
+
1203
+ def _get_historical_forecast_boundaries(
1204
+ model,
1205
+ series: TimeSeries,
1206
+ series_idx: int,
1207
+ past_covariates: TimeSeries | None,
1208
+ future_covariates: TimeSeries | None,
1209
+ start: pd.Timestamp | float | int | Literal["end"] | None,
1210
+ start_format: Literal["position", "value"],
1211
+ forecast_horizon: int,
1212
+ overlap_end: bool,
1213
+ stride: int,
1214
+ freq: pd.DateOffset,
1215
+ show_warnings: bool = True,
1216
+ ) -> tuple[Any, ...]:
1217
+ """
1218
+ Based on the boundaries of the forecastable time index, generates the boundaries of each covariates using the lags.
1219
+
1220
+ For TimeSeries with a RangeIndex, the boundaries are converted to positional indexes to slice the array
1221
+ appropriately when start > 0.
1222
+
1223
+ When applicable, move the start boundaries to the value provided by the user.
1224
+ """
1225
+ # obtain forecastable indexes boundaries, as values from the time index
1226
+ historical_forecasts_time_index, _, _, _ = _get_historical_forecasts_setup(
1227
+ model=model,
1228
+ series=series,
1229
+ past_covariates=past_covariates,
1230
+ future_covariates=future_covariates,
1231
+ series_idx=series_idx,
1232
+ forecast_horizon=forecast_horizon,
1233
+ start=start,
1234
+ start_format=start_format,
1235
+ stride=stride,
1236
+ overlap_end=overlap_end,
1237
+ retrain=False,
1238
+ train_length=None,
1239
+ val_length=0,
1240
+ show_warnings=show_warnings,
1241
+ )
1242
+
1243
+ # re-adjust the slicing indexes to account for the lags
1244
+ (
1245
+ min_target_lag,
1246
+ max_target_lag,
1247
+ min_past_cov_lag,
1248
+ max_past_cov_lag,
1249
+ min_future_cov_lag,
1250
+ max_future_cov_lag,
1251
+ output_chunk_shift,
1252
+ ) = model.extreme_lags
1253
+
1254
+ # SKLearn models with `multi_models=False` require additional lookback
1255
+ if not getattr(model, "multi_models", True) and model.output_chunk_length > 1:
1256
+ shift_start = model.output_chunk_length - 1
1257
+ else:
1258
+ shift_start = 0
1259
+
1260
+ # check for auto-regression, to extract additional covariates;
1261
+ # max_target_lag < 0 are local models which can predict for n (horizon) -> infinity (no auto-regression)
1262
+ if (
1263
+ max_target_lag >= 0
1264
+ and forecast_horizon > max_target_lag - output_chunk_shift + 1
1265
+ ):
1266
+ auto_reg_steps = max(
1267
+ forecast_horizon - (max_target_lag - output_chunk_shift + 1), 0
1268
+ )
1269
+ else:
1270
+ auto_reg_steps = 0
1271
+
1272
+ # target lags are < 0
1273
+ hist_fct_tgt_start, hist_fct_tgt_end = historical_forecasts_time_index
1274
+ if min_target_lag is not None:
1275
+ hist_fct_tgt_start += (min_target_lag - shift_start) * freq
1276
+
1277
+ # target lag has a gap between the max lag and the present;
1278
+ if hasattr(model, "lags") and model.lags.get("target"):
1279
+ # for SKLearnModel we use the 'lags' and ignore component lags since we are only
1280
+ # interested in the maximum lags
1281
+ hist_fct_tgt_end += 1 * freq * model.lags.get("target")[-1]
1282
+ else:
1283
+ hist_fct_tgt_end -= 1 * freq
1284
+
1285
+ # past covariate lags are < 0
1286
+ hist_fct_pc_start, hist_fct_pc_end = historical_forecasts_time_index
1287
+ if min_past_cov_lag is not None:
1288
+ hist_fct_pc_start += (min_past_cov_lag - shift_start) * freq
1289
+ if max_past_cov_lag is not None:
1290
+ hist_fct_pc_end += (max_past_cov_lag + auto_reg_steps) * freq
1291
+
1292
+ # future lags can be anything
1293
+ hist_fct_fc_start, hist_fct_fc_end = historical_forecasts_time_index
1294
+ if min_future_cov_lag is not None:
1295
+ hist_fct_fc_start += (min_future_cov_lag - shift_start) * freq
1296
+ if max_future_cov_lag is not None:
1297
+ hist_fct_fc_end += (max_future_cov_lag + auto_reg_steps) * freq
1298
+
1299
+ # convert actual integer index values (points) to positional index, make end bound inclusive
1300
+ if series.has_range_index:
1301
+ hist_fct_tgt_start = series.get_index_at_point(hist_fct_tgt_start)
1302
+ hist_fct_tgt_end = series.get_index_at_point(hist_fct_tgt_end) + 1
1303
+ if past_covariates is not None:
1304
+ hist_fct_pc_start = past_covariates.get_index_at_point(hist_fct_pc_start)
1305
+ hist_fct_pc_end = past_covariates.get_index_at_point(hist_fct_pc_end) + 1
1306
+ else:
1307
+ hist_fct_pc_start, hist_fct_pc_end = None, None
1308
+ if future_covariates is not None:
1309
+ hist_fct_fc_start = future_covariates.get_index_at_point(hist_fct_fc_start)
1310
+ hist_fct_fc_end = future_covariates.get_index_at_point(hist_fct_fc_end) + 1
1311
+ else:
1312
+ hist_fct_fc_start, hist_fct_fc_end = None, None
1313
+
1314
+ return (
1315
+ historical_forecasts_time_index[0],
1316
+ historical_forecasts_time_index[1],
1317
+ hist_fct_tgt_start,
1318
+ hist_fct_tgt_end,
1319
+ hist_fct_pc_start,
1320
+ hist_fct_pc_end,
1321
+ hist_fct_fc_start,
1322
+ hist_fct_fc_end,
1323
+ )
1324
+
1325
+
1326
+ def _check_optimizable_historical_forecasts_global_models(
1327
+ retrain: bool | int | Callable[..., bool],
1328
+ ) -> bool:
1329
+ """
1330
+ Historical forecast can be optimized only if `retrain=False`.
1331
+ """
1332
+ return (retrain is False) or (retrain == 0)
1333
+
1334
+
1335
+ def _process_historical_forecast_input(
1336
+ model,
1337
+ series: Sequence[TimeSeries],
1338
+ past_covariates: Sequence[TimeSeries] | None = None,
1339
+ future_covariates: Sequence[TimeSeries] | None = None,
1340
+ forecast_horizon: int = 1,
1341
+ ) -> Sequence[TimeSeries] | Sequence[TimeSeries] | None | Sequence[TimeSeries] | None:
1342
+ if not model._fit_called:
1343
+ raise_log(
1344
+ ValueError("Model has not been fit yet."),
1345
+ )
1346
+
1347
+ # manage covariates, usually handled by SKLearnModel.predict()
1348
+ if past_covariates is None and model.past_covariate_series is not None:
1349
+ past_covariates = [model.past_covariate_series] * len(series)
1350
+ if future_covariates is None and model.future_covariate_series is not None:
1351
+ future_covariates = [model.future_covariate_series] * len(series)
1352
+
1353
+ if model.uses_static_covariates:
1354
+ model._verify_static_covariates(series[0].static_covariates)
1355
+
1356
+ if model.encoders.encoding_available:
1357
+ past_covariates, future_covariates = model.generate_fit_predict_encodings(
1358
+ n=forecast_horizon,
1359
+ series=series,
1360
+ past_covariates=past_covariates,
1361
+ future_covariates=future_covariates,
1362
+ )
1363
+ return series, past_covariates, future_covariates
1364
+
1365
+
1366
+ def _process_predict_start_points_bounds(
1367
+ series: Sequence[TimeSeries], bounds: ArrayLike, stride: int
1368
+ ) -> tuple[np.ndarray, np.ndarray]:
1369
+ """Processes the historical forecastable time index bounds (earliest, and latest possible prediction
1370
+ start points).
1371
+
1372
+ Parameters
1373
+ ----------
1374
+ bounds
1375
+ An array of shape (n series, 2), with the left and right prediction start point bounds per series.
1376
+ stride
1377
+ The number of time steps between two consecutive predictions.
1378
+
1379
+ Returns
1380
+ -------
1381
+ (np.ndarray, np.ndarray)
1382
+ The adjusted bounds: the right bounds are adjusted to be a multiple of 'stride' ahead of the left bounds.
1383
+ The number of resulting predicted series per input series respecting stride and bounds.
1384
+ """
1385
+ bounds = bounds if isinstance(bounds, np.ndarray) else np.array(bounds)
1386
+ if not bounds.shape == (len(series), 2):
1387
+ raise_log(
1388
+ ValueError(
1389
+ "`bounds` must be an array like with shape `(n target series, 2)`, "
1390
+ "with the start and end bounds of each series"
1391
+ ),
1392
+ )
1393
+ # we might have some steps that are too long considering stride
1394
+ steps_too_long = (bounds[:, 1] - bounds[:, 0]) % stride
1395
+ bounds[:, 1] -= steps_too_long
1396
+ cum_lengths = np.cumsum(np.diff(bounds) // stride + 1)
1397
+ return bounds, cum_lengths
1398
+
1399
+
1400
+ def _convert_data_transformers(
1401
+ data_transformers: dict[str, BaseDataTransformer | Pipeline] | None,
1402
+ copy: bool,
1403
+ ) -> dict[str, Pipeline]:
1404
+ if data_transformers is None:
1405
+ return dict()
1406
+ else:
1407
+ return {
1408
+ key_: val_
1409
+ if isinstance(val_, Pipeline)
1410
+ else Pipeline(transformers=[val_], copy=copy)
1411
+ for key_, val_ in data_transformers.items()
1412
+ }
1413
+
1414
+
1415
+ def _apply_data_transformers(
1416
+ series: Sequence[TimeSeries],
1417
+ pred_series: Sequence[TimeSeries] | None,
1418
+ past_covariates: Sequence[TimeSeries] | None,
1419
+ future_covariates: Sequence[TimeSeries] | None,
1420
+ data_transformers: dict[str, Pipeline],
1421
+ max_future_cov_lag: int,
1422
+ fit_transformers: bool,
1423
+ ) -> tuple[
1424
+ Sequence[TimeSeries],
1425
+ Sequence[TimeSeries] | None,
1426
+ Sequence[TimeSeries] | None,
1427
+ Sequence[TimeSeries] | None,
1428
+ ]:
1429
+ """Transform each series using the corresponding Pipeline.
1430
+
1431
+ If the Pipeline is fittable and `fit_transformers=True`, the series are sliced to correspond to the information
1432
+ available at model training time.
1433
+
1434
+ If the sequences contain more than one series, the series are expected to have the same time index (e.g. when
1435
+ running global historical forecasts with `apply_globally=True`). With this, we can avoid any look-ahead bias.
1436
+ """
1437
+ transformed_ts = []
1438
+
1439
+ series_0 = get_single_series(series)
1440
+ freq = series_0.freq
1441
+ series_end = series_0.end_time()
1442
+ for ts_type, apply_fit, ts in zip(
1443
+ ["series", "series", "past_covariates", "future_covariates"],
1444
+ [True, False, True, True],
1445
+ [
1446
+ series,
1447
+ pred_series,
1448
+ past_covariates,
1449
+ future_covariates,
1450
+ ], # mind the order, `pred_series` after `series`
1451
+ ):
1452
+ if ts is None or data_transformers.get(ts_type) is None:
1453
+ transformed_ts.append(ts)
1454
+ else:
1455
+ if fit_transformers and data_transformers[ts_type].fittable:
1456
+ # must slice the ts to distinguish accessible information from future information
1457
+ if ts_type == "past_covariates":
1458
+ # information is known until the end of the target series
1459
+ tmp_ts = [ts_.drop_after(series_end, keep_point=True) for ts_ in ts]
1460
+ elif ts_type == "future_covariates":
1461
+ # information is known until `max_future_cov_lag` steps after the end of the target series
1462
+ tmp_ts = [
1463
+ ts_.drop_after(
1464
+ series_end + max(0, max_future_cov_lag + 1) * freq,
1465
+ keep_point=True,
1466
+ )
1467
+ for ts_ in ts
1468
+ ]
1469
+ else: # "series" and "pred_series"
1470
+ # nothing to do, the target series is already sliced appropriately
1471
+ tmp_ts = ts
1472
+
1473
+ if apply_fit:
1474
+ data_transformers[ts_type].fit(tmp_ts)
1475
+ # transforming the series
1476
+ transformed_ts.append(data_transformers[ts_type].transform(ts))
1477
+ return tuple(transformed_ts)
1478
+
1479
+
1480
+ def _apply_inverse_data_transformers(
1481
+ series: TimeSeriesLike,
1482
+ forecasts: TimeSeriesLike | Sequence[Sequence[TimeSeries]],
1483
+ data_transformers: dict[str, Pipeline],
1484
+ series_idx: int | None = None,
1485
+ pass_insample: bool = True,
1486
+ ) -> TimeSeriesLike | Sequence[Sequence[TimeSeries]]:
1487
+ """
1488
+ If a preprocessing pipeline is registered under ``"series"`` and can be reversed, convert ``forecasts`` from
1489
+ preprocessed form back to the original one; if not, leave ``forecasts`` as they are.
1490
+
1491
+ ``pass_insample`` (default ``True``): also hand the (already transformed) training target ``series`` to that
1492
+ reverse step, so a **short** forecast can be turned back correctly when the method needs recent history (as with
1493
+ :class:`~darts.dataprocessing.transformers.diff.Diff`). Set it to ``False`` when ``forecasts`` is a **full-length**
1494
+ series that already contains everything needed to invert (for example in-sample fitted values). Only the
1495
+ ``"series"`` pipeline is inverted; other keys in ``data_transformers`` are unchanged. Arguments line up with
1496
+ :meth:`~darts.dataprocessing.pipeline.Pipeline.inverse_transform`.
1497
+ """
1498
+ if "series" in data_transformers and data_transformers["series"].invertible:
1499
+ called_with_single_series = get_series_seq_type(series) == SeriesType.SINGLE
1500
+ if called_with_single_series:
1501
+ forecasts = [forecasts]
1502
+ forecasts = data_transformers["series"].inverse_transform(
1503
+ data=forecasts,
1504
+ series_idx=series_idx,
1505
+ insample=series if pass_insample else None,
1506
+ )
1507
+ return forecasts[0] if called_with_single_series else forecasts
1508
+ else:
1509
+ return forecasts
1510
+
1511
+
1512
+ def _slice_intersect_series(
1513
+ series: Sequence[TimeSeries],
1514
+ past_covariates: Sequence[TimeSeries] | None,
1515
+ future_covariates: Sequence[TimeSeries] | None,
1516
+ sample_weight: str | Sequence[TimeSeries] | None,
1517
+ ) -> tuple[
1518
+ Sequence[TimeSeries],
1519
+ Sequence[TimeSeries] | None,
1520
+ Sequence[TimeSeries] | None,
1521
+ str | Sequence[TimeSeries] | None,
1522
+ ]:
1523
+ """Computes the slice intersection of all series sequences.
1524
+
1525
+ Raises an error if the intersection is empty for any of the sequences.
1526
+ """
1527
+ series = slice_intersect(series)
1528
+ past_covariates = (
1529
+ slice_intersect(past_covariates) if past_covariates is not None else None
1530
+ )
1531
+ future_covariates = (
1532
+ slice_intersect(future_covariates) if future_covariates is not None else None
1533
+ )
1534
+ if not isinstance(sample_weight, str):
1535
+ sample_weight = (
1536
+ slice_intersect(sample_weight) if sample_weight is not None else None
1537
+ )
1538
+
1539
+ for s_, name in zip(
1540
+ [series, past_covariates, future_covariates, sample_weight],
1541
+ ["series", "past_covariates", "future_covariates", "sample_weight"],
1542
+ ):
1543
+ if s_ is not None and not isinstance(s_, str) and len(s_[0]) == 0:
1544
+ raise_log(
1545
+ ValueError(
1546
+ f"The slice intersection of the `{name}` is empty. "
1547
+ f"Cannot apply historical forecasts globally."
1548
+ ),
1549
+ )
1550
+ return series, past_covariates, future_covariates, sample_weight
1551
+
1552
+
1553
+ def _pack_series_in_list(
1554
+ series: T, past_covariates: T, future_covariates: T, sample_weight: T
1555
+ ) -> tuple[
1556
+ T | list[T],
1557
+ T | list[T],
1558
+ T | list[T],
1559
+ T | list[T],
1560
+ ]:
1561
+ """Packs each provided input into a list (or str in case of sample weight)."""
1562
+ series = [series]
1563
+ past_covariates = [past_covariates] if past_covariates else None
1564
+ future_covariates = [future_covariates] if future_covariates else None
1565
+ if isinstance(sample_weight, str):
1566
+ sample_weight = sample_weight
1567
+ else:
1568
+ sample_weight = [sample_weight] if sample_weight else None
1569
+ return series, past_covariates, future_covariates, sample_weight
1570
+
1571
+
1572
+ def _process_historical_forecast_for_backtest(
1573
+ series: TimeSeriesLike,
1574
+ historical_forecasts: TimeSeries
1575
+ | Sequence[TimeSeries]
1576
+ | Sequence[Sequence[TimeSeries]],
1577
+ last_points_only: bool,
1578
+ ) -> tuple[Sequence[TimeSeries], Sequence[Sequence[TimeSeries]]]:
1579
+ """Checks that the `historical_forecasts` have the correct format based on the input `series` and
1580
+ `last_points_only`. If all checks have passed, it converts `series` and `historical_forecasts` format into a
1581
+ multiple series case with `last_points_only=False`.
1582
+ """
1583
+ # remember input series type
1584
+ series_seq_type = get_series_seq_type(series)
1585
+ series = series2seq(series)
1586
+
1587
+ # check that `historical_forecasts` have correct type
1588
+ expected_seq_type = None
1589
+ forecast_seq_type = get_series_seq_type(historical_forecasts)
1590
+ if last_points_only and not series_seq_type == forecast_seq_type:
1591
+ # lpo=True -> fc sequence type must be the same
1592
+ expected_seq_type = series_seq_type
1593
+ elif not last_points_only and forecast_seq_type != series_seq_type + 1:
1594
+ # lpo=False -> fc sequence type must be one order higher
1595
+ expected_seq_type = series_seq_type + 1
1596
+
1597
+ if expected_seq_type is not None:
1598
+ raise_log(
1599
+ ValueError(
1600
+ f"Expected `historical_forecasts` of type {expected_seq_type} "
1601
+ f"with `last_points_only={last_points_only}` and `series` of type "
1602
+ f"{series_seq_type}. However, received `historical_forecasts` of type "
1603
+ f"{forecast_seq_type}. Make sure to pass the same `last_points_only` "
1604
+ f"value that was used to generate the historical forecasts."
1605
+ ),
1606
+ )
1607
+
1608
+ # we must wrap each fc in a list if `last_points_only=True`
1609
+ nested = last_points_only and forecast_seq_type == SeriesType.SEQ
1610
+ historical_forecasts = series2seq(
1611
+ historical_forecasts, seq_type_out=SeriesType.SEQ_SEQ, nested=nested
1612
+ )
1613
+
1614
+ # check that the number of series-specific forecasts corresponds to the
1615
+ # number of series in `series`
1616
+ if len(series) != len(historical_forecasts):
1617
+ error_msg = (
1618
+ f"Mismatch between the number of series-specific `historical_forecasts` "
1619
+ f"(n={len(historical_forecasts)}) and the number of `TimeSeries` in `series` "
1620
+ f"(n={len(series)}). For `last_points_only={last_points_only}`, expected "
1621
+ )
1622
+ expected_seq_type = series_seq_type if last_points_only else series_seq_type + 1
1623
+ if expected_seq_type == SeriesType.SINGLE:
1624
+ error_msg += f"a single `historical_forecasts` of type {expected_seq_type}."
1625
+ else:
1626
+ error_msg += f"`historical_forecasts` of type {expected_seq_type} with length n={len(series)}."
1627
+ raise_log(
1628
+ ValueError(error_msg),
1629
+ )
1630
+ return series, historical_forecasts
1631
+
1632
+
1633
+ def _extend_series_for_overlap_end(
1634
+ series: Sequence[TimeSeries],
1635
+ historical_forecasts: Sequence[Sequence[TimeSeries]],
1636
+ ):
1637
+ """Extends each target `series` to the end of the last historical forecast for that series.
1638
+ Fills the values all missing dates with `np.nan`.
1639
+
1640
+ Assumes the input meets the multiple `series` case with `last_points_only=False` (e.g. the output of
1641
+ `darts.utils.historical_forecasts.utils_process_historical_forecast_for_backtest()`).
1642
+
1643
+ Notes
1644
+ -----
1645
+ Most forecasts do not end after their target series. We therefore compare end times first and only call the
1646
+ more expensive `n_steps_between()` / `append_values()` when an extension is needed. If nothing needs extending,
1647
+ the original `series` sequence is returned as-is.
1648
+ """
1649
+ series_extended = None
1650
+ for i, (series_, hfcs_) in enumerate(zip(series, historical_forecasts)):
1651
+ fc_end = hfcs_[-1].end_time()
1652
+ series_end = series_.end_time()
1653
+ # cheap rejection of the common case before n_steps_between()
1654
+ if fc_end <= series_end:
1655
+ if series_extended is not None:
1656
+ series_extended.append(series_)
1657
+ continue
1658
+
1659
+ missing_steps = n_steps_between(fc_end, series_end, freq=series_.freq)
1660
+ if series_extended is None:
1661
+ # defer list allocation until at least one series must be extended
1662
+ series_extended = list(series[:i])
1663
+ series_extended.append(
1664
+ series_.append_values(np.full((missing_steps,) + series_.shape[1:], np.nan))
1665
+ )
1666
+ return series if series_extended is None else series_extended
datasets/raw/darts_benchmark_datasets/darts/utils/missing_values.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utils for filling missing values
3
+ --------------------------------
4
+ """
5
+
6
+ from darts import TimeSeries
7
+ from darts.logging import raise_log
8
+
9
+
10
+ def missing_values_ratio(series: TimeSeries) -> float:
11
+ """
12
+ Computes the ratio of missing values
13
+
14
+ Parameters
15
+ ----------
16
+ series
17
+ The time series to compute ratio on
18
+
19
+ Returns
20
+ -------
21
+ float
22
+ The ratio of missing values
23
+ """
24
+
25
+ return series.to_dataframe().isnull().sum().mean() / len(series)
26
+
27
+
28
+ def fill_missing_values(
29
+ series: TimeSeries, fill: str | float = "auto", **interpolate_kwargs
30
+ ) -> TimeSeries:
31
+ """
32
+ Fills missing values in the provided time series
33
+
34
+ Parameters
35
+ ----------
36
+ series
37
+ The time series for which to fill missing values
38
+ fill
39
+ The value used to replace the missing values.
40
+ If set to 'auto', will auto-fill missing values using the `pandas.Dataframe.interpolate()` method.
41
+ interpolate_kwargs
42
+ Keyword arguments for `pandas.Dataframe.interpolate()`, only used when fit is set to 'auto'.
43
+ See `the documentation
44
+ <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.interpolate.html>`__
45
+ for the list of supported parameters.
46
+
47
+ Returns
48
+ -------
49
+ TimeSeries
50
+ A new TimeSeries with all missing values filled according to the rules above.
51
+ """
52
+ if not (isinstance(fill, str) or isinstance(fill, float)):
53
+ raise_log(ValueError("`fill` should either be a string or a float."))
54
+ if isinstance(fill, str) and fill != "auto":
55
+ raise_log(
56
+ ValueError("invalid string for `fill`: can only be set to 'auto'."),
57
+ )
58
+
59
+ if fill == "auto":
60
+ return _auto_fill(series, **interpolate_kwargs)
61
+ return _const_fill(series, fill)
62
+
63
+
64
+ def extract_subseries(
65
+ series: TimeSeries, min_gap_size: int | None = 1, mode: str = "all"
66
+ ) -> list[TimeSeries]:
67
+ """
68
+ Partitions the series into a sequence of sub-series by using significant gaps of missing values
69
+
70
+ Parameters
71
+ ----------
72
+ series
73
+ The TimeSeries to partition into sub-series
74
+
75
+ min_gap_size
76
+ The minimum number of contiguous missing values to consider a gap as significant. Defaults to 1.
77
+
78
+ mode
79
+ Only for multivariate TimeSeries. The definition of a gap; presence of a NaN in any column ("any")
80
+ or NaNs in all the columns ("all") for a given timestamp. Defaults to "all".
81
+
82
+ Returns
83
+ -------
84
+ subseries
85
+ A list of TimeSeries, sub-series without significant gaps of missing values
86
+
87
+ See Also
88
+ --------
89
+ TimeSeries.gaps : return the gaps in the TimeSeries
90
+ """
91
+
92
+ # Remove null values from the series extremes
93
+ series = series.strip()
94
+ freq = series.freq
95
+
96
+ if series.to_dataframe().isna().sum().sum() == 0:
97
+ return [series]
98
+
99
+ # Get start/end times of sub-series without gaps of missing values
100
+ gaps_df = series.gaps(mode=mode)
101
+ if gaps_df.empty:
102
+ return [series]
103
+ else:
104
+ gaps_df = gaps_df.query(f"gap_size>={min_gap_size}")
105
+ start_times = [series.start_time()] + (gaps_df["gap_end"] + freq).to_list()
106
+ end_times = (gaps_df["gap_start"] - freq).to_list() + [series.end_time()]
107
+
108
+ # slice by position (inclusive end), as integer slices of integer-indexed
109
+ # series are positional rather than label-based
110
+ subseries = []
111
+ for start, end in zip(start_times, end_times):
112
+ subseries.append(
113
+ series[
114
+ series.get_index_at_point(start) : series.get_index_at_point(end)
115
+ + 1
116
+ ]
117
+ )
118
+
119
+ return subseries
120
+
121
+
122
+ def _const_fill(series: TimeSeries, fill: float = 0) -> TimeSeries:
123
+ """
124
+ Fills the missing values of `series` with only the value provided (default zeroes).
125
+
126
+ Parameters
127
+ ----------
128
+ series
129
+ The TimeSeries to check for missing values.
130
+ fill
131
+ The value used to replace the missing values.
132
+
133
+ Returns
134
+ -------
135
+ TimeSeries
136
+ A TimeSeries, `series` with all missing values set to `fill`.
137
+ """
138
+
139
+ return TimeSeries(
140
+ series.time_index,
141
+ series.to_dataframe().fillna(value=fill),
142
+ freq=series.freq,
143
+ components=series.columns,
144
+ static_covariates=series.static_covariates,
145
+ hierarchy=series.hierarchy,
146
+ metadata=series.metadata,
147
+ copy=False,
148
+ )
149
+
150
+
151
+ def _auto_fill(series: TimeSeries, **interpolate_kwargs) -> TimeSeries:
152
+ """
153
+ This function fills the missing values in the TimeSeries `series`,
154
+ using the `pandas.Dataframe.interpolate()` method.
155
+
156
+ Parameters
157
+ ----------
158
+ series
159
+ The time series
160
+ interpolate_kwargs
161
+ Keyword arguments for `pandas.Dataframe.interpolate()`.
162
+ See `the documentation
163
+ <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.interpolate.html>`__
164
+ for the list of supported parameters.
165
+ Returns
166
+ -------
167
+ TimeSeries
168
+ A new TimeSeries with all missing values filled according to the rules above.
169
+ """
170
+
171
+ series_temp = series.to_dataframe()
172
+
173
+ # pandas interpolate wrapper, with chosen `method`
174
+ if "limit_direction" not in interpolate_kwargs:
175
+ interpolate_kwargs["limit_direction"] = "both"
176
+ interpolate_kwargs["inplace"] = True
177
+ series_temp.interpolate(**interpolate_kwargs)
178
+ return TimeSeries(
179
+ times=series_temp.index,
180
+ values=series_temp.values,
181
+ components=series_temp.columns,
182
+ freq=series.freq,
183
+ static_covariates=series.static_covariates,
184
+ hierarchy=series.hierarchy,
185
+ metadata=series.metadata,
186
+ copy=False,
187
+ )
datasets/raw/darts_benchmark_datasets/darts/utils/mlflow.py ADDED
@@ -0,0 +1,1994 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MLflow Integration
3
+ ------------------
4
+
5
+ .. _darts-mlflow-autolog-logging:
6
+
7
+ Custom MLflow model flavor for Darts forecasting models. Supports saving, loading,
8
+ and logging any Darts ``ForecastingModel`` (statistical, ML-based, and PyTorch-based)
9
+ to MLflow, as well as automatic logging via ``autolog()``.
10
+
11
+ See the `MLflow quickstart <https://github.com/unit8co/darts/blob/master/examples/29-MLflow-examples.ipynb>`_
12
+ for an end-to-end walkthrough.
13
+
14
+ .. dropdown:: Here's a quick start example
15
+
16
+ .. highlight:: python
17
+ .. code-block:: python
18
+
19
+ import os
20
+ import tempfile
21
+
22
+ import mlflow
23
+
24
+ import darts.metrics as metrics
25
+ from darts.datasets import AirPassengersDataset
26
+ from darts.models import LinearRegressionModel
27
+ from darts.utils.mlflow import autolog
28
+
29
+ # dummy temporary directory for local MLflow tracking;
30
+ # use a permanent location for real use cases
31
+ tmpdir = tempfile.mkdtemp()
32
+ mlflow_db = os.path.join(tmpdir, "mlflow.db")
33
+ artifact_root = os.path.join(tmpdir, "mlruns")
34
+
35
+ mlflow.set_tracking_uri(f"sqlite:///{mlflow_db}")
36
+ # SQLite stores run metadata; artifacts default to ./mlruns unless we set a location
37
+ mlflow.set_experiment(
38
+ experiment_id=mlflow.create_experiment(
39
+ "darts-quickstart",
40
+ artifact_location=artifact_root,
41
+ )
42
+ )
43
+
44
+ # load series and create train and val splits
45
+ series = AirPassengersDataset().load()
46
+ train, val = series[:-36], series[-36:]
47
+
48
+ # two models to compare with different lookback windows
49
+ model_lags, names = [12, 24], ["one-year", "two-years"]
50
+ horizon = 12
51
+
52
+ # activate autologging and try out the models
53
+ autolog()
54
+ for lags, name in zip(model_lags, names):
55
+ with mlflow.start_run(run_name=name) as run:
56
+ model = LinearRegressionModel(lags=lags)
57
+ model.fit(train) # autolog logs params and covariate metadata
58
+
59
+ # log standalone metrics from manual predictions
60
+ pred = model.predict(n=horizon)
61
+ metrics.mae(val, pred) # time-aggregated logged as scaler metric
62
+ metrics.ae(val, pred) # time-dependent logged as stepped metric
63
+
64
+ # log backtest metrics from historical forecasts over val set
65
+ bt = model.backtest(
66
+ series=series,
67
+ start=val.start_time(),
68
+ retrain=False,
69
+ forecast_horizon=horizon,
70
+ reduction=None, # `None` logs as stepped metric, scalar otherwise
71
+ metric=[metrics.mae, metrics.rmse],
72
+ )
73
+ autolog(disable=True)
74
+
75
+ # you can launch the MLflow UI with the command below from your terminal;
76
+ # then open the returned address for example in a browser (similar to http://localhost:5000)
77
+ print(f"mlflow ui --backend-store-uri {mlflow.get_tracking_uri()}")
78
+
79
+ When ``autolog()`` is enabled, the following functionalities emit detailed logs when inside
80
+ an active MLflow run (e.g. within ``with mlflow.start_run():``):
81
+
82
+ - Calling ``ForecastingModel.fit()``:
83
+
84
+ - Logs model creation parameters (``model.model_params``), both as MLflow
85
+ params and as a ``model_params.json`` artifact.
86
+ - Logs target series info and covariate usage information (past, future,
87
+ and static covariates) as a ``series_info.json`` artifact.
88
+ - Stores the trained model artifact when ``log_models=True`` (default:
89
+ ``False``), and sets ``darts.model_is_pretrained`` to ``True``.
90
+ - Logs per-epoch training and validation metrics for PyTorch-based models.
91
+ - Calling ``ForecastingModel.historical_forecasts(retrain=True)``:
92
+
93
+ - Logs the same model creation parameters and ``series_info.json`` as
94
+ ``fit()`` (overwriting any prior ``fit()`` artifacts in the same run).
95
+ - Stores an untrained model template (via ``untrained_model()``) when
96
+ ``log_models=True`` and no model was logged yet in the run. Sets the run
97
+ tag and model metadata ``darts.model_is_pretrained`` to ``False`` so
98
+ downstream code knows the artifact must be refit before inference.
99
+ If a model was already logged (e.g. via ``fit()`` or manual
100
+ ``log_model()``), the existing artifact is kept unchanged.
101
+ - Calling any Darts metric:
102
+
103
+ - Logs the result of that metric call as an MLflow metric. More information
104
+ in the notes below.
105
+ - Calling ``ForecastingModel.backtest()``:
106
+
107
+ - Logs all evaluation metrics under ``backtest_*`` keys. More information
108
+ in the notes below.
109
+
110
+ .. important::
111
+
112
+ **Cross-Model Run Comparability**: Metric values are only comparable
113
+ across runs when the evaluation settings match. Use the same evaluation
114
+ time frame, forecast horizon, and evaluation start date for every
115
+ ``backtest()`` / metric call you intend to compare.
116
+
117
+ .. note::
118
+
119
+ **Metric Naming Convention**: Logged metric keys follow the pattern
120
+ ``{metric_name}{component}{quantile_or_label}`` (e.g.,
121
+ ``"mae_target0_q0_500"``), where each part is included only when the
122
+ corresponding axis is present:
123
+
124
+ - ``metric_name`` - the metric function name, or the ``name`` metric
125
+ keyword argument when provided (e.g., ``"mae"``).
126
+ - ``component`` - the component name: e.g., ``"_target0"`` when
127
+ ``component_reduction=None``.
128
+ - ``quantile_or_label``:
129
+
130
+ - the quantile label: e.g., ``"_q0.500"`` for quantile metrics with
131
+ keyword argument ``q=[0.5]``
132
+ - the quantile interval label: e.g., ``"_qi0.800"`` for quantile
133
+ interval metrics with keyword argument ``q_interval=[(0.1, 0.9)]``
134
+ (80% interval between quantiles 0.1 and 0.9).
135
+ - the class label: e.g., ``"_label1"`` for classification metrics with
136
+ keyword argument ``labels`` when ``label_reduction=None``.
137
+
138
+ **Backtest metrics** are prefixed by ``"backtest_"``.
139
+
140
+ .. note::
141
+
142
+ **Metric Logging and Display**: Darts offers many ways of evaluating
143
+ forecasting models. To offer the highest value, we adapt what is logged
144
+ to MLflow based on the use case scenario.
145
+
146
+ - Metric type:
147
+
148
+ - Time-aggregated metrics (e.g. ``mae()``): Logged as
149
+ scaler values.
150
+ - Per-time step metrics (e.g. ``ae()`` where ``time_reduction=None``):
151
+ Logged as stepped metrics (one value per step in the forecast horizon).
152
+ - Single or Multi-series:
153
+
154
+ - Single series: Logged as explained above.
155
+ - Multiple (a list of) series: When the metric's
156
+ ``series_reduction=None``, the logged metric is aggregated over all
157
+ series using autolog's ``agg_func``. The detailed per-series metrics /
158
+ backtest metrics are logged under a single ``metrics_per_series.json``
159
+ table run artifact.
160
+
161
+ - Standalone or backtest metric:
162
+
163
+ - Standalone metric: Logged as explained above.
164
+ - Backtest metric: If backtest's ``reduction`` is other than ``None``,
165
+ the windowed forecast metrics are aggregated and logged as explained
166
+ above. If ``None``, metrics are logged as stepped MLflow metrics.
167
+
168
+ - Time-aggregated metrics: each step represents a specifc forecast
169
+ (window) metric. Steps represent the historical forecast windows
170
+ (0, 1, ..., n_windows - 1).
171
+ - Per-time step metrics: each step represents a step in the forecast
172
+ horizon aggregated over all windows. Steps represent the steps in
173
+ the forecast horizon (0, 1, ..., horizon - 1).
174
+
175
+ - Multi-series alignment (``series_align`` autolog option):
176
+
177
+ - ``"end"`` (default): shorter series skip early steps/windows so their
178
+ last points overlap the tail of longer series.
179
+ - ``"start"``: shorter series contribute at early steps/windows; longer
180
+ series have fewer contributing series at tail steps.
181
+
182
+ - Backtest aggregate (``log_backtest_aggregate`` autolog option):
183
+
184
+ - When enabled, logs an additional scalar per backtest metric key under
185
+ ``backtest_agg_{metric_key}`` (e.g. ``backtest_agg_mae``), computed
186
+ as ``agg_func`` over all logged steps for that key.
187
+
188
+ When components are preserved (``component_reduction=None``), all
189
+ series scored together must have the same number of components; names
190
+ are taken from the first series.
191
+ """
192
+
193
+ import inspect
194
+ import re
195
+ import sys
196
+ import threading
197
+ from collections.abc import Callable
198
+ from operator import itemgetter
199
+ from pathlib import Path
200
+ from typing import Any, Literal
201
+
202
+ from darts.logging import raise_log
203
+ from darts.typing import TimeSeriesLike
204
+
205
+ try:
206
+ import mlflow
207
+ except ImportError:
208
+ raise_log(
209
+ ImportError(
210
+ "The `mlflow` module could not be imported. To enable MLflow support "
211
+ "in Darts, follow the detailed instructions in the installation guide: "
212
+ "https://github.com/unit8co/darts/blob/master/INSTALL.md"
213
+ )
214
+ )
215
+
216
+ import numpy as np
217
+ import pandas as pd
218
+ import yaml
219
+ from mlflow.entities import LoggedModel
220
+ from mlflow.models import Model, ModelSignature
221
+ from mlflow.models.model import MLMODEL_FILE_NAME
222
+ from mlflow.models.utils import _save_example
223
+ from mlflow.tracking.artifact_utils import _download_artifact_from_uri
224
+ from mlflow.tracking.fluent import _initialize_logged_model
225
+ from mlflow.utils import _get_fully_qualified_class_name
226
+ from mlflow.utils.autologging_utils import (
227
+ autologging_integration,
228
+ get_autologging_config,
229
+ )
230
+ from mlflow.utils.autologging_utils.client import MlflowAutologgingQueueingClient
231
+ from mlflow.utils.autologging_utils.safety import safe_patch
232
+ from mlflow.utils.class_utils import _get_class_from_string
233
+ from mlflow.utils.environment import (
234
+ _CONDA_ENV_FILE_NAME,
235
+ _CONSTRAINTS_FILE_NAME,
236
+ _PYTHON_ENV_FILE_NAME,
237
+ _REQUIREMENTS_FILE_NAME,
238
+ _mlflow_conda_env,
239
+ _process_conda_env,
240
+ _process_pip_requirements,
241
+ _PythonEnv,
242
+ _validate_env_arguments,
243
+ )
244
+ from mlflow.utils.file_utils import write_to
245
+ from mlflow.utils.model_utils import (
246
+ _add_code_from_conf_to_system_path,
247
+ _get_flavor_configuration,
248
+ _validate_and_copy_code_paths,
249
+ _validate_and_prepare_target_save_path,
250
+ )
251
+ from mlflow.utils.requirements_utils import _get_pinned_requirement
252
+
253
+ import darts
254
+ from darts import TimeSeries
255
+ from darts.dataprocessing.encoders.encoders import SequentialEncoder
256
+ from darts.logging import get_logger, raise_log
257
+ from darts.metrics.utils import (
258
+ _LabelReduction,
259
+ register_metric_callback,
260
+ unregister_metric_callback,
261
+ )
262
+ from darts.models.forecasting.forecasting_model import ForecastingModel
263
+ from darts.utils.ts_utils import (
264
+ SeriesType,
265
+ get_series_seq_type,
266
+ get_single_series,
267
+ series2seq,
268
+ )
269
+ from darts.utils.utils import TORCH_AVAILABLE
270
+
271
+ if TORCH_AVAILABLE:
272
+ from darts.models.forecasting.torch_forecasting_model import (
273
+ TorchForecastingModel,
274
+ )
275
+
276
+ logger = get_logger(__name__)
277
+
278
+ FLAVOR_NAME = "darts"
279
+
280
+
281
+ _MODEL_FILE_STAT = "model.pkl"
282
+ _MODEL_FILE_TORCH = "model.pt"
283
+ _MODEL_IS_PRETRAINED_TAG = "darts.model_is_pretrained"
284
+
285
+ # Thread-local flags used by _patched_fit to suppress nested/re-entrant
286
+ # autologging: in_historical_forecasts covers historical_forecasts' internal
287
+ # fit() calls, in_fit covers nested fit() calls (e.g. ensembles, super()),
288
+ # so only the outermost call logs.
289
+ _autolog_state = threading.local()
290
+
291
+
292
+ def save_model(
293
+ model: ForecastingModel,
294
+ path: str,
295
+ conda_env: dict | str | None = None,
296
+ code_paths: list[str] | None = None,
297
+ mlflow_model: Model | None = None,
298
+ signature: ModelSignature | None = None,
299
+ input_example: Any | None = None,
300
+ pip_requirements: list[str] | None = None,
301
+ extra_pip_requirements: list[str] | None = None,
302
+ metadata: dict[str, Any] | None = None,
303
+ ) -> None:
304
+ """Save a Darts forecasting model in MLflow format.
305
+
306
+ Produces an MLflow model directory at ``path`` containing:
307
+
308
+ - The serialized Darts model (delegated to the model's own ``save()`` method).
309
+ - An ``MLmodel`` YAML file with flavor metadata.
310
+ - ``conda.yaml`` and ``requirements.txt`` environment files.
311
+
312
+ Parameters
313
+ ----------
314
+ model
315
+ A fitted Darts ``ForecastingModel`` instance.
316
+ path
317
+ Local filesystem path where the model directory will be created.
318
+ conda_env
319
+ A conda environment specification (dict or path to a ``conda.yaml``).
320
+ If ``None``, a default environment is generated.
321
+ code_paths
322
+ A list of local filesystem paths to Python file dependencies (or directories
323
+ containing file dependencies). These files are prepended to the system path
324
+ when the model is loaded.
325
+ mlflow_model
326
+ Optional MLflow Model object to use for saving. When provided (typically by
327
+ ``Model.log()``), this model instance is used instead of creating a new one.
328
+ signature
329
+ *Unsupported, see notes.* An ``mlflow.models.ModelSignature`` instance describing model input/output.
330
+ Use ``mlflow.models.infer_signature()`` to automatically generate from example inputs.
331
+ input_example
332
+ *Unsupported, see notes.* An example input for the model (used by MLflow UI).
333
+ pip_requirements
334
+ A list of pip requirement strings. Overrides ``conda_env`` pip section
335
+ when provided.
336
+ extra_pip_requirements
337
+ A list of additional pip requirement strings to add to the model's environment,
338
+ in addition to the default requirements.
339
+ metadata
340
+ Optional dictionary of custom metadata to store in the ``MLmodel`` file.
341
+
342
+ Notes
343
+ -----
344
+ ``signature`` and ``input_example`` params are currently not supported, as they
345
+ are used to support serving and input validation in the MLflow pyfunc flavor,
346
+ which is not implemented for Darts models. They are accepted as params for
347
+ simplifying potential future extensibility, and to keep in line with MLflow API
348
+ conventions.
349
+ """
350
+ if not isinstance(model, ForecastingModel):
351
+ raise_log(
352
+ ValueError(
353
+ "Model must be an instance of darts.models.forecasting.ForecastingModel."
354
+ )
355
+ )
356
+
357
+ _validate_env_arguments(conda_env, pip_requirements, extra_pip_requirements)
358
+
359
+ path = Path(path).resolve()
360
+ _validate_and_prepare_target_save_path(str(path))
361
+ code_dir_subpath = _validate_and_copy_code_paths(code_paths, str(path))
362
+
363
+ is_torch = _is_torch_model(model)
364
+
365
+ # clean=True excludes any timeseries or callbacks from the model file
366
+ model_file = _MODEL_FILE_TORCH if is_torch else _MODEL_FILE_STAT
367
+ model.save(str(path / model_file), clean=True)
368
+
369
+ model_class = _get_fully_qualified_class_name(model)
370
+
371
+ if mlflow_model is None:
372
+ mlflow_model = Model()
373
+
374
+ if signature is not None:
375
+ mlflow_model.signature = signature
376
+
377
+ if input_example is not None:
378
+ _save_example(mlflow_model, input_example, str(path))
379
+
380
+ if metadata is not None:
381
+ mlflow_model.metadata = metadata
382
+
383
+ mlflow_model.add_flavor(
384
+ FLAVOR_NAME,
385
+ darts_version=darts.__version__,
386
+ data=model_file,
387
+ model_class=model_class,
388
+ code=code_dir_subpath,
389
+ )
390
+ mlflow_model.save(str(path / MLMODEL_FILE_NAME))
391
+
392
+ if pip_requirements is None:
393
+ default_reqs = get_default_pip_requirements()
394
+ # TODO: `infer_pip_requirements` requires `pyfunc` flavor to be implemented.
395
+ # inferred_reqs = infer_pip_requirements(path, FLAVOR_NAME, fallback=default_reqs)
396
+ # default_reqs = sorted(set(inferred_reqs).union(default_reqs))
397
+ else:
398
+ default_reqs = None
399
+ conda_env, pip_requirements, pip_constraints = (
400
+ _process_pip_requirements(
401
+ default_reqs, pip_requirements, extra_pip_requirements
402
+ )
403
+ if conda_env is None
404
+ else _process_conda_env(conda_env)
405
+ )
406
+
407
+ with open(path / _CONDA_ENV_FILE_NAME, "w") as f:
408
+ yaml.safe_dump(conda_env, stream=f, default_flow_style=False)
409
+
410
+ if pip_constraints:
411
+ write_to(str(path / _CONSTRAINTS_FILE_NAME), "\n".join(pip_constraints))
412
+
413
+ write_to(str(path / _REQUIREMENTS_FILE_NAME), "\n".join(pip_requirements))
414
+ _PythonEnv.current().to_yaml(str(path / _PYTHON_ENV_FILE_NAME))
415
+
416
+
417
+ def load_model(
418
+ model_uri: str,
419
+ dst_path: str | None = None,
420
+ **kwargs,
421
+ ) -> ForecastingModel:
422
+ """Load a Darts model from an MLflow model URI.
423
+
424
+ Parameters
425
+ ----------
426
+ model_uri
427
+ An MLflow model URI, e.g. ``"runs:/<run_id>/model"``,
428
+ ``"models:/<name>/<version>"``, or a local ``file:///...`` path.
429
+ dst_path
430
+ Optional local path for downloading remote artifacts.
431
+ **kwargs
432
+ Additional keyword arguments forwarded to the model's ``load()`` method
433
+ (e.g. ``trusted=False`` for safe-loading , ``map_location`` for a
434
+ ``TorchForecastingModel``, etc.).
435
+
436
+ Returns
437
+ -------
438
+ ForecastingModel
439
+ The loaded Darts forecasting model.
440
+ """
441
+ local_path = _download_artifact_from_uri(
442
+ artifact_uri=model_uri, output_path=dst_path
443
+ )
444
+
445
+ flavor_conf = _get_flavor_configuration(
446
+ model_path=local_path, flavor_name=FLAVOR_NAME
447
+ )
448
+ _add_code_from_conf_to_system_path(local_path, flavor_conf)
449
+
450
+ model_cls_str = flavor_conf.get("model_class", None)
451
+ model_cls = _get_class_from_string(model_cls_str)
452
+
453
+ if not issubclass(model_cls, ForecastingModel):
454
+ raise_log(
455
+ ValueError(
456
+ f"Cannot load model: class `{model_cls_str}` is not a subclass of `ForecastingModel`."
457
+ )
458
+ )
459
+
460
+ model_path = Path(local_path) / flavor_conf["data"]
461
+
462
+ return model_cls.load(str(model_path), **kwargs)
463
+
464
+
465
+ def log_model(model: ForecastingModel, **kwargs):
466
+ """Log a Darts model to the current MLflow run, using the Darts MLflow flavor.
467
+
468
+ This is a thin wrapper around ``mlflow.models.Model.log()`` that supplies
469
+ the Darts flavor for saving/loading; every other argument is forwarded
470
+ as-is. See the `MLflow documentation
471
+ <https://mlflow.org/docs/latest/api_reference/python_api/mlflow.models.html#mlflow.models.Model.log>`_
472
+ for the full list of accepted parameters (e.g. ``name``,
473
+ ``registered_model_name``, ``conda_env``, ``pip_requirements``,
474
+ ``metadata``, ``tags``, ...).
475
+
476
+ Parameters
477
+ ----------
478
+ model
479
+ A fitted Darts ``ForecastingModel`` instance.
480
+ **kwargs
481
+ Forwarded to ``mlflow.models.Model.log()``. Use ``name`` to set the
482
+ run-relative artifact path. ``artifact_path`` parameter is deprecated
483
+ by MLflow and not exposed here.
484
+
485
+ Returns
486
+ -------
487
+ ModelInfo
488
+ MLflow ModelInfo object containing model_uri, run_id, artifact_path,
489
+ model_id, timestamps, and other metadata about the logged model.
490
+
491
+ Notes
492
+ -----
493
+ ``signature`` and ``input_example`` are currently not supported, as they
494
+ are used to support serving and input validation in the MLflow pyfunc
495
+ flavor, which is not implemented for Darts models.
496
+ """
497
+ # MLflow still requires "artifact_path" to be provided (it has no default),
498
+ # but it is deprecated in favour of "name". Accept it via kwargs for
499
+ # compatibility, defaulting to None so callers can use "name" alone.
500
+ artifact_path = kwargs.pop("artifact_path", None)
501
+ return Model.log(
502
+ artifact_path,
503
+ flavor=sys.modules[__name__],
504
+ model=model,
505
+ **kwargs,
506
+ )
507
+
508
+
509
+ def autolog(
510
+ log_models: bool = False,
511
+ log_params: bool = True,
512
+ log_metrics: bool = True,
513
+ log_torch_metrics: bool = True,
514
+ agg_func: Callable = np.nanmean,
515
+ series_align: Literal["start", "end"] = "end",
516
+ log_backtest_aggregate: bool = False,
517
+ disable: bool = False,
518
+ silent: bool = False,
519
+ ) -> None:
520
+ """Enable (or disable) automatic MLflow logging for Darts.
521
+
522
+ For a detailed overview of logged params, metrics, and artifacts, see
523
+ :ref:`the detailed documentation <darts-mlflow-autolog-logging>`.
524
+
525
+ Parameters
526
+ ----------
527
+ log_models
528
+ If ``True``, log a model artifact when calling ``fit()`` (trained
529
+ model) or ``historical_forecasts(retrain=True)`` (untrained template
530
+ via ``untrained_model()``). Defaults to ``False``. If a model was
531
+ already logged in the run (including via manual ``log_model()``),
532
+ autolog does not add another artifact.
533
+ log_params
534
+ If ``True`` (default), log model creation parameters when calling
535
+ ``fit()`` or ``historical_forecasts()``.
536
+ log_metrics
537
+ If ``True`` (default), log the result of any Darts metric call made
538
+ inside an active MLflow run, including standalone metric calls or via
539
+ backtest.
540
+ log_torch_metrics
541
+ If ``True`` (default), enable ``mlflow.pytorch.autolog(log_models=False)``
542
+ around PyTorch-based model training to automatically log per-epoch
543
+ training and validation metrics. Only effective for PyTorch-based models.
544
+ agg_func
545
+ Function used to aggregate a metric's per-series values into the
546
+ single value logged for a list of series (e.g. ``np.nanmean``, the
547
+ default, or ``np.median``). Called as ``agg_func(values)`` on a list
548
+ of floats. Also used when ``log_backtest_aggregate=True`` to collapse
549
+ all logged steps of a backtest metric into a single scalar.
550
+ series_align
551
+ How to align shorter series when multiple series differ in window or
552
+ time length. ``"end"`` (default) aligns from the end so shorter series
553
+ skip early steps/windows; ``"start"`` aligns from the start so shorter
554
+ series contribute at early steps/windows.
555
+ log_backtest_aggregate
556
+ If ``True``, log an additional scalar per backtest metric key under
557
+ ``backtest_agg_{metric_key}`` (e.g. ``backtest_agg_mae``), computed as
558
+ ``agg_func`` over all logged steps for that key. Defaults to ``False``.
559
+ disable
560
+ If ``True``, restore the original ``fit()`` methods and stop
561
+ autologging.
562
+ silent
563
+ If ``True`` (default ``False``), suppress all event logging and warnings from
564
+ MLflow during autologging.
565
+ """
566
+ if series_align not in ("start", "end"):
567
+ raise_log(
568
+ ValueError(
569
+ f"`series_align` must be 'start' or 'end', got {series_align!r}."
570
+ )
571
+ )
572
+
573
+ # Enable/disable mlflow.pytorch.autolog for per-epoch metrics on torch models.
574
+ # This must happen outside the @autologging_integration-decorated _autolog()
575
+ # because that decorator short-circuits _autolog()'s body entirely when
576
+ # disable=True, so a call placed inside it would never run. Unlike
577
+ # mlflow.sklearn, which exposes a private, undecorated _autolog(flavor_name=...)
578
+ # that other flavors (e.g. xgboost) call to tag its patches under their own
579
+ # integration name for cleanup, mlflow.pytorch has no such hook: its autolog()
580
+ # hardcodes its own patches under "pytorch", so Darts can't fold pytorch's
581
+ # patch lifecycle into its own and must call mlflow.pytorch.autolog() directly.
582
+ if log_torch_metrics and not disable:
583
+ try:
584
+ import mlflow.pytorch
585
+
586
+ mlflow.pytorch.autolog(
587
+ log_models=False,
588
+ log_datasets=False,
589
+ checkpoint=False,
590
+ silent=silent,
591
+ )
592
+ except ImportError:
593
+ pass
594
+ elif disable:
595
+ try:
596
+ import mlflow.pytorch
597
+
598
+ mlflow.pytorch.autolog(disable=True)
599
+ except (ImportError, Exception):
600
+ pass
601
+
602
+ # Register/unregister the metric-logging callback with darts.metrics.utils
603
+ # directly, rather than via mlflow's safe_patch on each darts.metrics
604
+ # attribute (which is import-order sensitive)
605
+ unregister_metric_callback(_mlflow_metric_callback)
606
+ if log_metrics and not disable:
607
+ register_metric_callback(_mlflow_metric_callback)
608
+
609
+ _autolog(
610
+ log_models=log_models,
611
+ log_params=log_params,
612
+ log_metrics=log_metrics,
613
+ agg_func=agg_func,
614
+ series_align=series_align,
615
+ log_backtest_aggregate=log_backtest_aggregate,
616
+ disable=disable,
617
+ silent=silent,
618
+ )
619
+
620
+
621
+ def _get_forecasting_models():
622
+ """Find all ``ForecastingModel`` subclasses currently loaded in memory.
623
+
624
+ Traverses ``__subclasses__()``, avoiding force-importing all of the forecasting
625
+ models.
626
+
627
+ Returns:
628
+ A list of (name, class) tuples for all matching classes.
629
+ """
630
+ seen: set[type] = set()
631
+ stack = [ForecastingModel]
632
+ while stack:
633
+ current = stack.pop()
634
+ for sub in current.__subclasses__():
635
+ if sub not in seen:
636
+ seen.add(sub)
637
+ stack.append(sub)
638
+
639
+ classes = [(cls.__name__, cls) for cls in seen]
640
+ return sorted(classes, key=itemgetter(0))
641
+
642
+
643
+ @autologging_integration(FLAVOR_NAME)
644
+ def _autolog(
645
+ log_models: bool = True,
646
+ log_params: bool = True,
647
+ log_metrics: bool = True,
648
+ agg_func: Callable = np.nanmean,
649
+ series_align: Literal["start", "end"] = "end",
650
+ log_backtest_aggregate: bool = False,
651
+ disable: bool = False,
652
+ silent: bool = False,
653
+ ) -> None:
654
+ """Internal autolog implementation decorated with ``@autologging_integration``.
655
+
656
+ Handles patching of Darts ``ForecastingModel.fit()`` and metric functions.
657
+ The ``mlflow.pytorch.autolog`` coordination is handled by the public
658
+ ``autolog()`` wrapper because the decorator short-circuits on
659
+ ``disable=True``.
660
+ """
661
+
662
+ def _patched_fit(original, self, *args, **kwargs):
663
+ """Patch function for ForecastingModel.fit() autologging.
664
+
665
+ Logs model parameters, class, and covariates; optionally logs the
666
+ model artifact when ``log_models=True``.
667
+
668
+ Parameters
669
+ ----------
670
+ original
671
+ The original fit method being patched.
672
+ self
673
+ The model instance (ForecastingModel or TorchForecastingModel).
674
+ args
675
+ Positional arguments passed to fit.
676
+ kwargs
677
+ Keyword arguments passed to fit.
678
+
679
+ Returns
680
+ -------
681
+ ForecastingModel
682
+ The result of calling the original fit method.
683
+ """
684
+ # Create a training session to track the training process and log information
685
+ autologging_client = MlflowAutologgingQueueingClient()
686
+
687
+ if getattr(_autolog_state, "in_historical_forecasts", False):
688
+ return original(self, *args, **kwargs)
689
+
690
+ # handle nested fit() calls
691
+ if getattr(_autolog_state, "in_fit", False):
692
+ return original(self, *args, **kwargs)
693
+
694
+ # Track which model is active so metric patches can prefix their keys
695
+ _autolog_state.current_model_name = type(self).__name__
696
+
697
+ _autolog_state.in_fit = True
698
+ try:
699
+ result = original(self, *args, **kwargs)
700
+ finally:
701
+ _autolog_state.in_fit = False
702
+
703
+ active_run = mlflow.active_run()
704
+ if active_run is None:
705
+ return result
706
+ run_id = active_run.info.run_id
707
+
708
+ fit_kwargs = inspect.signature(original).bind(self, *args, **kwargs).arguments
709
+ _log_model_setup(
710
+ model=self,
711
+ autologging_client=autologging_client,
712
+ run_id=run_id,
713
+ series=fit_kwargs["series"],
714
+ past_covariates=fit_kwargs.get("past_covariates"),
715
+ future_covariates=fit_kwargs.get("future_covariates"),
716
+ log_params=log_params,
717
+ )
718
+ _log_model_artifact(
719
+ model=result,
720
+ run_id=run_id,
721
+ is_pretrained=True,
722
+ log_models=log_models,
723
+ autologging_client=autologging_client,
724
+ )
725
+ autologging_client.flush(synchronous=False).await_completion()
726
+
727
+ return result
728
+
729
+ def _patched_historical_forecasts(original, self, *args, **kwargs):
730
+ """Suppress per-iteration fit() autologging; log model setup once when
731
+ ``retrain=True``.
732
+
733
+ Sets a thread-local flag so ``_patched_fit`` skips autologging for the
734
+ internal ``fit()`` calls. When retraining is enabled and an MLflow run is
735
+ active, logs model tags, creation parameters, and series info once after
736
+ the call (overwriting any prior ``fit()`` artifacts in the same run).
737
+ When ``log_models=True`` and no model exists yet in the run, also logs
738
+ an untrained model template with ``darts.model_is_pretrained=False``.
739
+ """
740
+ _autolog_state.in_historical_forecasts = True
741
+ try:
742
+ result = original(self, *args, **kwargs)
743
+ finally:
744
+ _autolog_state.in_historical_forecasts = False
745
+
746
+ active_run = mlflow.active_run()
747
+ if active_run is None:
748
+ return result
749
+
750
+ bound = inspect.signature(original).bind(self, *args, **kwargs)
751
+ bound.apply_defaults()
752
+
753
+ retrain = bound.arguments["retrain"]
754
+ if retrain is False or retrain == 0:
755
+ return result
756
+
757
+ run_id = active_run.info.run_id
758
+ autologging_client = MlflowAutologgingQueueingClient()
759
+ _log_model_setup(
760
+ model=self,
761
+ autologging_client=autologging_client,
762
+ run_id=run_id,
763
+ series=bound.arguments["series"],
764
+ past_covariates=bound.arguments.get("past_covariates"),
765
+ future_covariates=bound.arguments.get("future_covariates"),
766
+ log_params=log_params,
767
+ )
768
+ _log_model_artifact(
769
+ model=self.untrained_model(),
770
+ run_id=run_id,
771
+ is_pretrained=False,
772
+ log_models=log_models,
773
+ autologging_client=autologging_client,
774
+ )
775
+ autologging_client.flush(synchronous=False).await_completion()
776
+ return result
777
+
778
+ def _patched_backtest(original, self, *args, **kwargs):
779
+ """Wrap ``backtest`` to log metric result(s) to the active MLflow run.
780
+
781
+ Suppresses per-window metric logging. Delegates to ``_log_backtest_metrics``,
782
+ which infers result shape from the metric signature and logs every cell under
783
+ a descriptive key.
784
+ """
785
+ _autolog_state.in_backtest = True
786
+ try:
787
+ result = original(self, *args, **kwargs)
788
+ finally:
789
+ _autolog_state.in_backtest = False
790
+
791
+ active_run = mlflow.active_run()
792
+ if not log_metrics or active_run is None:
793
+ return result
794
+
795
+ bound = inspect.signature(original).bind(self, *args, **kwargs)
796
+ bound.apply_defaults()
797
+ backtest_kwargs = bound.arguments
798
+
799
+ autologging_client = MlflowAutologgingQueueingClient()
800
+ _log_backtest_metrics(
801
+ autologging_client=autologging_client,
802
+ run_id=active_run.info.run_id,
803
+ result=result,
804
+ backtest_kwargs=backtest_kwargs,
805
+ agg_func=agg_func,
806
+ series_align=series_align,
807
+ log_backtest_aggregate=log_backtest_aggregate,
808
+ )
809
+ autologging_client.flush(synchronous=False).await_completion()
810
+ return result
811
+
812
+ # patch `fit()` to log model setup and model artifact
813
+ for _, cls in _get_forecasting_models():
814
+ safe_patch(
815
+ autologging_integration=FLAVOR_NAME,
816
+ destination=cls,
817
+ function_name="fit",
818
+ patch_function=_patched_fit,
819
+ )
820
+
821
+ # patch `historical_forecasts()` to log model setup only once (when retrain=True);
822
+ # suppresses internal fit() call logging
823
+ for _, cls in _get_forecasting_models():
824
+ safe_patch(
825
+ autologging_integration=FLAVOR_NAME,
826
+ destination=cls,
827
+ function_name="historical_forecasts",
828
+ patch_function=_patched_historical_forecasts,
829
+ )
830
+
831
+ # patch `backtest()` to log backtest metrics once while suppressing per-window
832
+ # metric logging
833
+ for _, cls in _get_forecasting_models():
834
+ safe_patch(
835
+ autologging_integration=FLAVOR_NAME,
836
+ destination=cls,
837
+ function_name="backtest",
838
+ patch_function=_patched_backtest,
839
+ )
840
+
841
+
842
+ def _mlflow_metric_callback(func, result, args, kwargs) -> None:
843
+ """Metric callback registered with ``darts.metrics.utils`` for autologging.
844
+
845
+ Invoked by ``multi_ts_support`` (the outermost decorator on every Darts
846
+ metric) after every top-level metric call, so it fires regardless of how
847
+ the metric was imported. It is not invoked for internal metric-to-metric
848
+ calls (e.g. ``rmse`` calling ``mse`` internally via ``_get_wrapped_metric``),
849
+ since those bypass ``multi_ts_support`` entirely.
850
+
851
+ When an active MLflow run exists, infers the output axes from the metric
852
+ signature and call kwargs (via ``_infer_metric_axes``) and delegates to
853
+ ``_log_standalone_metric``, which logs each cell under a key built as::
854
+
855
+ {metric_name}{component}{quantile_or_label}
856
+
857
+ where:
858
+
859
+ - ``metric_name`` - the metric function name, or the ``name`` keyword
860
+ argument when provided (it overrides only this token).
861
+ - ``component`` - ``_{component_name}`` when ``component_reduction=None``.
862
+ - ``quantile_or_label`` - quantile/interval/label suffix (e.g. ``_q0.500``,
863
+ ``_qi0.800``, ``_label1``) when applicable.
864
+
865
+ When the input is a ``Sequence[TimeSeries]`` with more than one series, the
866
+ logged value is ``autolog()``'s ``agg_func`` applied over series, and the
867
+ per-series breakdown is appended to the run's ``metrics_per_series.json``
868
+ table artifact instead of per-series keys.
869
+
870
+ The per-timestep axis (``time_reduction=None``) is mapped to the MLflow
871
+ ``step``.
872
+
873
+ Parameters
874
+ ----------
875
+ func
876
+ The Darts metric function that was called (used for its name and
877
+ signature).
878
+ result
879
+ The metric's return value.
880
+ args
881
+ Positional arguments the metric was called with.
882
+ kwargs
883
+ Keyword arguments the metric was called with.
884
+ """
885
+ active_run = mlflow.active_run()
886
+ if active_run is None:
887
+ return
888
+
889
+ # backtest() calls metric functions internally; _patched_backtest
890
+ # handles logging the aggregated result, so skip here to avoid
891
+ # generating one flat key per window (series_gen_mape_0, _1, …).
892
+ if getattr(_autolog_state, "in_backtest", False):
893
+ return
894
+
895
+ func_signature = inspect.signature(func)
896
+ bound = func_signature.bind(
897
+ *args, **{k: v for k, v in kwargs.items() if k in func_signature.parameters}
898
+ )
899
+ bound.apply_defaults()
900
+ metric_kwargs = bound.arguments
901
+
902
+ # _mlflow_metric_callback is a bare registered callback, not a closure over
903
+ # autolog()'s call kwargs, so agg_func is read back from the autologging
904
+ # config store that autolog() populated.
905
+ agg_func = get_autologging_config(
906
+ flavor_name=FLAVOR_NAME, config_key="agg_func", default_value=np.nanmean
907
+ )
908
+ series_align = get_autologging_config(
909
+ flavor_name=FLAVOR_NAME, config_key="series_align", default_value="end"
910
+ )
911
+
912
+ autologging_client = MlflowAutologgingQueueingClient()
913
+ _log_metric_results(
914
+ autologging_client=autologging_client,
915
+ run_id=active_run.info.run_id,
916
+ result=result,
917
+ metrics=func,
918
+ metric_kwargs=metric_kwargs,
919
+ agg_func=agg_func,
920
+ series_align=series_align,
921
+ )
922
+ autologging_client.flush(synchronous=False).await_completion()
923
+
924
+
925
+ def get_default_pip_requirements():
926
+ """Return the default pip requirements for logging a Darts model.
927
+
928
+ Returns
929
+ -------
930
+ list[str]
931
+ A list of pip requirement strings.
932
+ """
933
+ reqs = [_get_pinned_requirement("darts")]
934
+ return reqs
935
+
936
+
937
+ def get_default_conda_env():
938
+ """Return a default conda environment dict for a Darts model.
939
+
940
+ Returns
941
+ -------
942
+ dict
943
+ A conda environment specification dictionary.
944
+ """
945
+ return _mlflow_conda_env(
946
+ additional_pip_deps=get_default_pip_requirements(),
947
+ )
948
+
949
+
950
+ def _infer_covariate_usage(
951
+ model: ForecastingModel,
952
+ series: TimeSeriesLike,
953
+ past_covariates: TimeSeriesLike | None,
954
+ future_covariates: TimeSeriesLike | None,
955
+ ) -> tuple[bool, bool, bool]:
956
+ """Infer past/future/static covariate usage from model state and call args.
957
+
958
+ After ``historical_forecasts(retrain=True)`` the outer model is still
959
+ unfitted (training happens on internal copies), so ``model.uses_*`` stays
960
+ ``False``. Fall back to call args / ``add_encoders`` / static covariates on
961
+ ``series``, gated by ``supports_*`` / ``considers_static_covariates``.
962
+ """
963
+ # encoders can add past and future covariates
964
+ encoders = _get_model_encoders(model)
965
+
966
+ first_series = get_single_series(series)
967
+ uses_past = model.uses_past_covariates or (
968
+ model.supports_past_covariates
969
+ and (past_covariates is not None or len(encoders.past_encoders) > 0)
970
+ )
971
+ uses_future = model.uses_future_covariates or (
972
+ model.supports_future_covariates
973
+ and (future_covariates is not None or len(encoders.future_encoders) > 0)
974
+ )
975
+ uses_static = model.uses_static_covariates or (
976
+ first_series is not None
977
+ and first_series.static_covariates is not None
978
+ and model.supports_static_covariates
979
+ and model.considers_static_covariates
980
+ )
981
+ return uses_past, uses_future, uses_static
982
+
983
+
984
+ def _get_model_info_tags(
985
+ model: ForecastingModel,
986
+ series: TimeSeriesLike,
987
+ past_covariates: TimeSeriesLike | None = None,
988
+ future_covariates: TimeSeriesLike | None = None,
989
+ ) -> dict[str, Any]:
990
+ """
991
+ Returns:
992
+ A dictionary of MLflow run tag keys and values describing the specified model.
993
+ """
994
+ uses_past, uses_future, uses_static = _infer_covariate_usage(
995
+ model, series, past_covariates, future_covariates
996
+ )
997
+ return {
998
+ "model_class": model.__class__.__name__,
999
+ "model_reference": (
1000
+ model.__class__.__module__ + "." + model.__class__.__name__
1001
+ ),
1002
+ "model_likelihood": (
1003
+ model.likelihood.__class__.__name__
1004
+ if model.likelihood is not None
1005
+ else None
1006
+ ),
1007
+ "model_uses_past_covariates": uses_past,
1008
+ "model_uses_future_covariates": uses_future,
1009
+ "model_uses_static_covariates": uses_static,
1010
+ }
1011
+
1012
+
1013
+ def _run_has_logged_model(run_id: str) -> bool:
1014
+ """Return whether the given run already has a logged model artifact."""
1015
+ if getattr(_autolog_state, "model_logged_run_id", None) == run_id:
1016
+ return True
1017
+ try:
1018
+ run = mlflow.get_run(run_id)
1019
+ return bool(run.outputs and run.outputs.model_outputs)
1020
+ except Exception:
1021
+ return False
1022
+
1023
+
1024
+ def _log_model_artifact(
1025
+ *,
1026
+ model: ForecastingModel,
1027
+ run_id: str,
1028
+ is_pretrained: bool,
1029
+ log_models: bool,
1030
+ autologging_client: MlflowAutologgingQueueingClient,
1031
+ ) -> None:
1032
+ """Log a Darts model artifact to the active run unless one already exists.
1033
+
1034
+ When autolog skips because the user already logged a model manually, the
1035
+ existing artifact and any user-provided metadata/tags are left unchanged.
1036
+ """
1037
+ if not log_models or _run_has_logged_model(run_id):
1038
+ return
1039
+
1040
+ model_name = type(model).__name__
1041
+ logged_model: LoggedModel = _initialize_logged_model(
1042
+ name=model_name, flavor=FLAVOR_NAME
1043
+ )
1044
+ metadata = {_MODEL_IS_PRETRAINED_TAG: str(is_pretrained)}
1045
+ registered_model_name = get_autologging_config(
1046
+ flavor_name=FLAVOR_NAME,
1047
+ config_key="registered_model_name",
1048
+ default_value=None,
1049
+ )
1050
+ log_model(
1051
+ model,
1052
+ name=model_name,
1053
+ registered_model_name=registered_model_name,
1054
+ model_id=logged_model.model_id,
1055
+ metadata=metadata,
1056
+ )
1057
+
1058
+ autologging_client.set_tags(
1059
+ run_id=run_id,
1060
+ tags={_MODEL_IS_PRETRAINED_TAG: str(is_pretrained)},
1061
+ )
1062
+ _autolog_state.model_logged_run_id = run_id
1063
+
1064
+
1065
+ def _log_model_setup(
1066
+ model: ForecastingModel,
1067
+ autologging_client: MlflowAutologgingQueueingClient,
1068
+ run_id: str,
1069
+ series: TimeSeriesLike,
1070
+ past_covariates: TimeSeriesLike | None = None,
1071
+ future_covariates: TimeSeriesLike | None = None,
1072
+ *,
1073
+ log_params: bool = True,
1074
+ ) -> None:
1075
+ """Log model tags, creation parameters, and series info to an active run.
1076
+
1077
+ Shared by ``fit()`` and ``historical_forecasts(retrain=True)`` autologging.
1078
+ Does not log the trained model artifact.
1079
+ """
1080
+ autologging_client.set_tags(
1081
+ run_id=run_id,
1082
+ tags=_get_model_info_tags(
1083
+ model=model,
1084
+ series=series,
1085
+ past_covariates=past_covariates,
1086
+ future_covariates=future_covariates,
1087
+ ),
1088
+ )
1089
+ if log_params:
1090
+ autologging_client.log_params(run_id=run_id, params=model.model_params)
1091
+ mlflow.log_dict(model.model_params, "model_params.json")
1092
+ _log_series_info(
1093
+ model=model,
1094
+ series=series,
1095
+ past_covariates=past_covariates,
1096
+ future_covariates=future_covariates,
1097
+ )
1098
+
1099
+
1100
+ def _log_series_info(
1101
+ model: ForecastingModel,
1102
+ series: TimeSeriesLike,
1103
+ past_covariates: TimeSeriesLike | None,
1104
+ future_covariates: TimeSeriesLike | None,
1105
+ ) -> None:
1106
+ """Log target series and covariate usage information to MLflow.
1107
+
1108
+ Extracts information about the target series, past, future, and
1109
+ static covariates used during training and logs them as a JSON
1110
+ artifact for easy filtering, comparison, and documentation.
1111
+
1112
+ Logs:
1113
+ - Target series: component count and names
1114
+ - Past / future covariates: usage, count, and names, including both
1115
+ explicitly-passed covariates and any generated by ``add_encoders``
1116
+ - Static covariates: usage, count, names, and whether they are global
1117
+ - Artifact: complete metadata as ``series_info.json``
1118
+
1119
+ Parameters
1120
+ ----------
1121
+ model
1122
+ A fitted Darts forecasting model instance.
1123
+ series
1124
+ The ``series`` argument passed to ``fit()``: a single ``TimeSeries``
1125
+ or a ``Sequence[TimeSeries]``.
1126
+ past_covariates
1127
+ The past covariate argument passed to ``fit()``, or
1128
+ ``None``.
1129
+ future_covariates
1130
+ The future covariate covariate argument passed to ``fit()``, or
1131
+ ``None``.
1132
+ """
1133
+ first_series = get_single_series(series)
1134
+ first_past_covariates = get_single_series(past_covariates)
1135
+ first_future_covariates = get_single_series(future_covariates)
1136
+ first_static_covariates = (
1137
+ first_series.static_covariates if first_series is not None else None
1138
+ )
1139
+ uses_past, uses_future, uses_static = _infer_covariate_usage(
1140
+ model=model,
1141
+ series=series,
1142
+ past_covariates=past_covariates,
1143
+ future_covariates=future_covariates,
1144
+ )
1145
+
1146
+ # if available, train encoders to get past and future encodings
1147
+ encoders = _get_model_encoders(model)
1148
+ if encoders.encoding_available:
1149
+ _ = encoders.encode_train(
1150
+ target=first_series,
1151
+ past_covariates=first_past_covariates,
1152
+ future_covariates=first_future_covariates,
1153
+ )
1154
+
1155
+ series_info = {
1156
+ "series": _extract_data_metadata(
1157
+ uses=True,
1158
+ data=first_series,
1159
+ names_attr="components",
1160
+ ),
1161
+ "past_covariates": _extract_data_metadata(
1162
+ uses=uses_past,
1163
+ data=first_past_covariates,
1164
+ names_attr="components",
1165
+ encodings=encoders.past_components,
1166
+ ),
1167
+ "future_covariates": _extract_data_metadata(
1168
+ uses=uses_future,
1169
+ data=first_future_covariates,
1170
+ names_attr="components",
1171
+ encodings=encoders.future_components,
1172
+ ),
1173
+ "static_covariates": _extract_data_metadata(
1174
+ uses=uses_static,
1175
+ data=first_static_covariates,
1176
+ names_attr="columns",
1177
+ ),
1178
+ }
1179
+
1180
+ # log complete information as JSON artifact
1181
+ mlflow.log_dict(series_info, "series_info.json")
1182
+
1183
+
1184
+ def _is_torch_model(model) -> bool:
1185
+ """Check if a model is a ``TorchForecastingModel``.
1186
+
1187
+ Parameters
1188
+ ----------
1189
+ model
1190
+ A Darts forecasting model instance.
1191
+
1192
+ Returns
1193
+ -------
1194
+ bool
1195
+ True if the model is a `TorchForecastingModel`, False otherwise.
1196
+ """
1197
+ return TORCH_AVAILABLE and isinstance(model, TorchForecastingModel)
1198
+
1199
+
1200
+ def _extract_data_metadata(
1201
+ uses: bool,
1202
+ data: TimeSeries | pd.DataFrame | None,
1203
+ names_attr: str,
1204
+ encodings: pd.Index | None = None,
1205
+ ) -> dict:
1206
+ """Extract data metadata.
1207
+
1208
+ Encodings are logged under the "encodings" key since they are not part
1209
+ of the input series.
1210
+
1211
+ Parameters
1212
+ ----------
1213
+ uses
1214
+ Whether the model uses this data type.
1215
+ data
1216
+ The data from a single series: a ``TimeSeries`` (target or past/future covariates)
1217
+ or a static-covariates ``DataFrame``, or ``None``.
1218
+ names_attr
1219
+ Attribute holding the feature names ("components" for a
1220
+ ``TimeSeries``, "columns" for a static-covariates ``DataFrame``).
1221
+ encodings
1222
+ The encodings for the data: a ``pd.Index`` of encoding names, or ``None``.
1223
+
1224
+ Returns
1225
+ -------
1226
+ dict
1227
+ Dictionary with keys: "used" (bool), "count" (int), "names" (list).
1228
+ """
1229
+ info = {"used": False, "count": 0, "names": [], "encodings": []}
1230
+
1231
+ if uses:
1232
+ info["used"] = True
1233
+ names = list(getattr(data, names_attr)) if data is not None else []
1234
+ info["names"] = names
1235
+ info["count"] = len(names)
1236
+ if encodings is not None:
1237
+ info["encodings"] = list(encodings)
1238
+
1239
+ return info
1240
+
1241
+
1242
+ def _sanitize_mlflow_key(name: str) -> str:
1243
+ """Sanitize a string for use as an MLflow metric key.
1244
+
1245
+ Replaces any invalid character from the metric key. Valid keys may
1246
+ only contain slashes, alphanumerics, underscores, periods, dashes,
1247
+ and spaces.
1248
+
1249
+ Parameters
1250
+ ----------
1251
+ name
1252
+ The raw name to sanitize.
1253
+
1254
+ Returns
1255
+ -------
1256
+ str
1257
+ A string safe for use as an MLflow metric key.
1258
+ """
1259
+ return re.sub(r"[^/\w.\- ]", "_", name)
1260
+
1261
+
1262
+ def _get_model_encoders(model: ForecastingModel) -> SequentialEncoder:
1263
+ """Get the encoders for a model.
1264
+
1265
+ Gets either the trained encoder of a fitted model or the
1266
+ fresh encoders of a model that has not been fitted yet.
1267
+
1268
+ Parameters
1269
+ ----------
1270
+ model
1271
+ A Darts forecasting model instance.
1272
+
1273
+ Returns
1274
+ -------
1275
+ SequentialEncoder
1276
+ The encoders for the model.
1277
+ """
1278
+ if model.add_encoders and not model.encoders.encoding_available:
1279
+ # model has encoders but it was not fitted yet
1280
+ return model.initialize_encoders()
1281
+ # model has been fitted, or does not have encodings available
1282
+ return model.encoders
1283
+
1284
+
1285
+ def _log_backtest_metrics(
1286
+ autologging_client: MlflowAutologgingQueueingClient,
1287
+ run_id: str,
1288
+ result,
1289
+ backtest_kwargs: dict,
1290
+ agg_func: Callable = np.nanmean,
1291
+ series_align: Literal["start", "end"] = "end",
1292
+ log_backtest_aggregate: bool = False,
1293
+ ) -> None:
1294
+ """Log backtest metric result(s) to MLflow.
1295
+
1296
+ Helper function for ``autolog()`` to log backtest metric results to MLflow.
1297
+ Details are documented in ``_log_metric_results()``.
1298
+ """
1299
+ _log_metric_results(
1300
+ autologging_client=autologging_client,
1301
+ run_id=run_id,
1302
+ result=result,
1303
+ metrics=backtest_kwargs["metric"],
1304
+ metric_kwargs=backtest_kwargs["metric_kwargs"] or dict(),
1305
+ agg_func=agg_func,
1306
+ series_align=series_align,
1307
+ log_backtest_aggregate=log_backtest_aggregate,
1308
+ backtest_kwargs=backtest_kwargs,
1309
+ )
1310
+
1311
+
1312
+ def _log_metric_results(
1313
+ autologging_client: MlflowAutologgingQueueingClient,
1314
+ run_id: str,
1315
+ result,
1316
+ metrics: Callable | list[Callable],
1317
+ metric_kwargs: dict[str, Any] | list[dict[str, Any]],
1318
+ backtest_kwargs: dict[str, Any] | None = None,
1319
+ agg_func: Callable = np.nanmean,
1320
+ series_align: Literal["start", "end"] = "end",
1321
+ log_backtest_aggregate: bool = False,
1322
+ ) -> None:
1323
+ """Log backtest or standalone metric result(s) to MLflow.
1324
+
1325
+ Shared implementation used by ``_log_backtest_metrics`` and
1326
+ ``_log_standalone_metric``. The two entry points differ only in how they
1327
+ populate the arguments below; all reshaping, key construction, step
1328
+ assignment, multi-series aggregation, and artifact writing happen here.
1329
+
1330
+ Entry modes
1331
+ -----------
1332
+ **Backtest** (``backtest_kwargs`` is not ``None``):
1333
+
1334
+ - ``metrics`` / ``metric_kwargs`` come from backtesting.
1335
+ - MLflow keys are prefixed with ``backtest_``.
1336
+ - A window axis ``W`` may be present (see *MLflow keys and steps*).
1337
+
1338
+ **Standalone** (``backtest_kwargs`` is ``None``):
1339
+
1340
+ - ``metrics`` / ``metric_kwargs`` describe a direct ``metric()`` call.
1341
+ - MLflow keys have no prefix.
1342
+ - There is never a backtest window axis (``W=1``); only the metric's own
1343
+ time / component / quantile / label axes apply.
1344
+
1345
+ Canonical layout
1346
+ ----------------
1347
+ Each per-series result is reshaped to ``(W, T, C, M)``:
1348
+
1349
+ - ``W`` - backtest windows (``1`` for standalone, or when windows were
1350
+ aggregated before scoring).
1351
+ - ``T`` - timesteps (``1`` when ``time_reduction`` is set).
1352
+ - ``C`` - sub-metrics per component (components * quantiles / intervals /
1353
+ labels; ``1`` when ``component_reduction`` is set).
1354
+ - ``M`` - number of metrics when several are logged at once.
1355
+
1356
+ Axis sizes are inferred from each metric's signature and the corresponding
1357
+ ``metric_kwargs``.
1358
+
1359
+ Kwargs that affect output dimensions (both modes unless noted):
1360
+
1361
+ - ``time_reduction`` - collapses the time axis (``T=1``).
1362
+ - ``component_reduction`` - collapses the component axis (``C=1``).
1363
+ - ``q`` / ``q_interval`` - one sub-metric per quantile / interval.
1364
+ - ``labels`` - when ``label_reduction=None``, one sub-metric per label;
1365
+ otherwise ``labels`` only restricts which classes are scored.
1366
+ - ``label_reduction`` - collapses label outputs to a scalar per component.
1367
+ - ``series_reduction`` - collapses the series axis inside the metric, so
1368
+ the caller's ``result`` is already aggregated and treated as a single
1369
+ series (``W=1`` for backtest regardless of ``reduction``).
1370
+
1371
+ Backtest-only kwargs:
1372
+
1373
+ - ``reduction=None`` - no aggregation across windows → one value per
1374
+ window (``W > 1``).
1375
+ - ``last_points_only`` - concatenates all windows into one ``TimeSeries``
1376
+ before scoring, so there is effectively one window regardless of
1377
+ ``reduction``.
1378
+ - ``forecast_horizon`` / ``historical_forecasts`` - set the time-axis
1379
+ length for time-dependent metrics when windows are preserved.
1380
+
1381
+ MLflow keys and steps
1382
+ ---------------------
1383
+ Every scalar cell is logged under a descriptive key built from the metric
1384
+ name, optional component suffix, and optional quantile / interval / label
1385
+ suffix (see ``_build_metric_keys``). A metric's ``name`` entry in
1386
+ ``metric_kwargs`` overrides the function-name token; the ``backtest_``
1387
+ prefix (when present) and axis suffixes are preserved.
1388
+
1389
+ The MLflow ``step`` is the axis the UI should chart:
1390
+
1391
+ - **Time-dependent metrics** (``time_reduction=None``): steps index the
1392
+ forecast horizon (``0 .. T-1``). When both time and window axes are
1393
+ present (backtest, no reduction, not ``last_points_only``), each step
1394
+ holds the ``agg_func`` aggregation over windows at that horizon index.
1395
+ - **Time-aggregated metrics**: steps index backtest windows aligned across
1396
+ series (``0 .. max_W-1``; shorter series skip early or late steps depending
1397
+ on ``series_align``). Standalone calls with a time axis but no window axis
1398
+ align timesteps the same way across series of different lengths.
1399
+
1400
+ Series can differ in length and overlap in time. By default
1401
+ (``series_align="end"``), we align from the end: a shorter series contributes
1402
+ at the last steps/windows, not the first. With ``series_align="start"``,
1403
+ shorter series contribute at the first steps/windows instead. This matches
1404
+ the usual backtest layout but is an assumption — series may also end at
1405
+ different calendar times.
1406
+
1407
+ Multi-series aggregation and artifacts
1408
+ ----------------------------------------
1409
+ When more than one series is scored (and ``series_reduction`` did not
1410
+ already collapse them), the logged value at each ``(key, step)`` is
1411
+ ``agg_func`` applied over series. The per-series breakdown is appended to
1412
+ the run's ``metrics_per_series.json`` table artifact when:
1413
+
1414
+ - several series were scored together, or
1415
+ - (backtest only) a time-dependent metric retains both time and window axes,
1416
+ so the aggregate steps average over windows but the table keeps every
1417
+ ``(window, horizon)`` cell.
1418
+
1419
+ For a single series, the aggregate is the value itself and no table is
1420
+ written unless the backtest time+window case above applies. When components
1421
+ are preserved (``component_reduction=None``), all series in a batch must
1422
+ have the same number of components; component names are taken from the first
1423
+ series.
1424
+
1425
+ When ``log_backtest_aggregate`` is enabled (backtest only), an additional
1426
+ scalar per metric key is logged under ``backtest_agg_{metric_key}`` (e.g.
1427
+ ``backtest_agg_mae``), computed as ``agg_func`` over all logged steps for
1428
+ that key.
1429
+
1430
+ Raises
1431
+ ------
1432
+ ValueError
1433
+ On a shape/size mismatch between the metric result and the inferred
1434
+ axes, when ``component_reduction=None`` and series in a sequence have
1435
+ different numbers of components, or when ``label_reduction=None`` is
1436
+ requested without explicit ``labels``.
1437
+
1438
+ Parameters
1439
+ ----------
1440
+ autologging_client
1441
+ MLflow autologging client used to queue metric writes.
1442
+ run_id
1443
+ ID of the active MLflow run.
1444
+ result
1445
+ Return value of ``backtest()`` or ``metric()``. Either a scalar/array
1446
+ for one series, a list of per-series results, or a single aggregate when
1447
+ ``series_reduction`` is set.
1448
+ metrics
1449
+ One metric callable or a list of callables logged together.
1450
+ metric_kwargs
1451
+ Keyword arguments forwarded to ``metrics``, either one dict shared by
1452
+ all metrics or one dict per metric. For standalone logging this is the
1453
+ bound ``metric()`` arguments; for backtest logging this is
1454
+ ``backtest_kwargs["metric_kwargs"]``.
1455
+ backtest_kwargs
1456
+ Bound arguments of the ``backtest()`` call (from
1457
+ ``inspect.BoundArguments.arguments`` after ``apply_defaults``). When
1458
+ ``None``, the call is treated as standalone metric logging.
1459
+ agg_func
1460
+ Function used to aggregate per-series values at each ``(key, step)``.
1461
+ Called as ``agg_func(values)`` on a list of floats. Also used to
1462
+ collapse all logged steps into a single scalar when
1463
+ ``log_backtest_aggregate`` is enabled.
1464
+ series_align
1465
+ How to align shorter series when multiple series differ in window or
1466
+ time length. ``"end"`` (default) or ``"start"``.
1467
+ log_backtest_aggregate
1468
+ If ``True`` (backtest only), log an additional scalar per metric key
1469
+ under ``backtest_agg_{metric_key}``.
1470
+ """
1471
+ metrics, metric_kwargs, metric_names = _normalize_metrics(
1472
+ metrics=metrics,
1473
+ metric_kwargs=metric_kwargs,
1474
+ )
1475
+ metric_axes = [_infer_metric_axes(m, kw) for m, kw in zip(metrics, metric_kwargs)]
1476
+ has_time_axis, has_comp_axis, _ = metric_axes[0]
1477
+
1478
+ series: TimeSeriesLike = (
1479
+ metric_kwargs[0]["actual_series"]
1480
+ if backtest_kwargs is None
1481
+ else backtest_kwargs["series"]
1482
+ )
1483
+ is_single_series = get_series_seq_type(series) == SeriesType.SINGLE
1484
+ series = series2seq(series)
1485
+
1486
+ if backtest_kwargs is None:
1487
+ # standalone metric
1488
+ is_backtest = False
1489
+ prefix = ""
1490
+ # `series_reduction` collapses the series axis inside the metric, so the
1491
+ # result has no leading series axis even for list input.
1492
+ series_reduced = metric_kwargs[0]["series_reduction"] is not None
1493
+ last_points_only = False
1494
+ has_windows = False
1495
+ forecast_horizon = 0
1496
+ else:
1497
+ # backtest metric
1498
+ is_backtest = True
1499
+ prefix = "backtest_"
1500
+ series_reduced = False
1501
+ last_points_only = backtest_kwargs["last_points_only"]
1502
+ has_windows, forecast_horizon = _resolve_backtest_layout(
1503
+ backtest_kwargs=backtest_kwargs,
1504
+ metric=metrics[0],
1505
+ metric_kwargs=metric_kwargs[0],
1506
+ is_single_series=is_single_series,
1507
+ )
1508
+
1509
+ if series_reduced:
1510
+ results = [result]
1511
+ else:
1512
+ results = [result] if is_single_series else result
1513
+
1514
+ if has_comp_axis and not series_reduced:
1515
+ n_components = {s.n_components for s in series}
1516
+ if len(n_components) > 1:
1517
+ raise_log(
1518
+ ValueError(
1519
+ "Backtest metric logging failed: all series must have the same "
1520
+ f"number of components, got {sorted(n_components)}. Consider "
1521
+ f"setting a metric `component_reduction`, or make sure all series "
1522
+ f"have the same number of components."
1523
+ )
1524
+ )
1525
+
1526
+ metric_keys = _build_metric_keys(
1527
+ metric_names=metric_names,
1528
+ components=series[0].components.tolist(),
1529
+ has_comp_axis=has_comp_axis,
1530
+ metric_axes=metric_axes,
1531
+ prefix=prefix,
1532
+ )
1533
+ series_metrics = [
1534
+ _reshape_metric_result(
1535
+ series=series_,
1536
+ result=r,
1537
+ metric_keys=metric_keys,
1538
+ has_time_axis=has_time_axis,
1539
+ has_windows=has_windows,
1540
+ forecast_horizon=forecast_horizon,
1541
+ is_backtest=is_backtest,
1542
+ )
1543
+ for r, series_ in zip(results, series)
1544
+ ]
1545
+ stepped_metrics, detailed_metrics = _collect_stepped_and_detailed_metrics(
1546
+ series_metrics=series_metrics,
1547
+ metric_keys=metric_keys,
1548
+ has_time_axis=has_time_axis,
1549
+ has_windows=has_windows,
1550
+ last_points_only=last_points_only,
1551
+ series_align=series_align,
1552
+ )
1553
+
1554
+ write_table = (not series_reduced and not is_single_series) or (
1555
+ has_time_axis and has_windows
1556
+ )
1557
+ _flush_logged_metrics(
1558
+ autologging_client,
1559
+ run_id,
1560
+ stepped_metrics,
1561
+ agg_func=agg_func,
1562
+ log_backtest_aggregate=log_backtest_aggregate and is_backtest,
1563
+ table_rows=detailed_metrics if write_table else None,
1564
+ )
1565
+
1566
+
1567
+ def _normalize_metrics(
1568
+ metrics: Callable | list[Callable],
1569
+ metric_kwargs: dict[str, Any] | list[dict[str, Any]],
1570
+ ) -> tuple[list, list[dict], list[str]]:
1571
+ """Normalize ``metric`` / ``metric_kwargs`` to parallel lists and key names.
1572
+
1573
+ ``backtest()`` accepts a single metric or a list, and a single kwargs
1574
+ dict (broadcast to all metrics) or a list of dicts. A ``name`` entry in
1575
+ ``metric_kwargs`` overrides the metric-name token in the MLflow key.
1576
+ """
1577
+ metrics = metrics if isinstance(metrics, list) else [metrics]
1578
+ metric_kwargs = (
1579
+ metric_kwargs if isinstance(metric_kwargs, list) else [metric_kwargs]
1580
+ )
1581
+ if len(metric_kwargs) != len(metrics):
1582
+ metric_kwargs = [metric_kwargs[0]] * len(metrics)
1583
+
1584
+ metric_names = [
1585
+ _sanitize_mlflow_key(
1586
+ metric_kwargs[i].get("name") or getattr(m, "__name__", f"metric_{i}")
1587
+ )
1588
+ for i, m in enumerate(metrics)
1589
+ ]
1590
+ return metrics, metric_kwargs, metric_names
1591
+
1592
+
1593
+ def _resolve_backtest_layout(
1594
+ backtest_kwargs: dict,
1595
+ metric: Callable,
1596
+ metric_kwargs: dict,
1597
+ is_single_series: bool,
1598
+ ) -> tuple[bool, int | None]:
1599
+ """Infer whether a window axis is present and the forecast horizon.
1600
+
1601
+ A window axis is present only when backtest did not aggregate windows
1602
+ (``reduction is None``), forecasts were not concatenated first
1603
+ (``last_points_only`` is false), and the metric's own
1604
+ ``series_reduction`` did not already collapse windows.
1605
+
1606
+ When the caller passed ``historical_forecasts``, ``backtest()`` ignores
1607
+ ``forecast_horizon``, so the horizon is read from the first forecast.
1608
+
1609
+ Returns
1610
+ -------
1611
+ tuple
1612
+ ``(has_windows, forecast_horizon)``.
1613
+ """
1614
+ last_points_only = backtest_kwargs["last_points_only"]
1615
+ has_windows = backtest_kwargs["reduction"] is None and not last_points_only
1616
+
1617
+ params = inspect.signature(metric).parameters
1618
+ if has_windows and "series_reduction" in params:
1619
+ series_reduction = metric_kwargs.get(
1620
+ "series_reduction", params["series_reduction"].default
1621
+ )
1622
+ if series_reduction is not None:
1623
+ has_windows = False
1624
+
1625
+ forecast_horizon = backtest_kwargs["forecast_horizon"]
1626
+ historical_forecasts = backtest_kwargs["historical_forecasts"]
1627
+ if historical_forecasts is not None and not last_points_only:
1628
+ first_forecast = (
1629
+ historical_forecasts[0] if is_single_series else historical_forecasts[0][0]
1630
+ )
1631
+ forecast_horizon = len(first_forecast)
1632
+
1633
+ return has_windows, forecast_horizon
1634
+
1635
+
1636
+ def _infer_metric_axes(
1637
+ metric: Callable, metric_kwargs: dict
1638
+ ) -> tuple[bool, bool, list[str]]:
1639
+ """Infer a metric's output axes from its signature and ``metric_kwargs``.
1640
+
1641
+ Covers ``time_reduction``, ``component_reduction``, ``q``, ``q_interval``,
1642
+ and ``label_reduction`` / ``labels`` for classification metrics.
1643
+ ``series_reduction`` is handled at the ``_log_metric_results`` level.
1644
+
1645
+ Parameters
1646
+ ----------
1647
+ metric
1648
+ A Darts metric callable.
1649
+ metric_kwargs
1650
+ Keyword arguments that will be forwarded to ``metric``.
1651
+
1652
+ Returns
1653
+ -------
1654
+ tuple
1655
+ ``(has_time_axis, has_comp_axis, axis_labels)`` where
1656
+
1657
+ - ``has_time_axis`` - ``True`` when ``time_reduction`` is ``None`` (i.e. a
1658
+ per-timestep axis is present in the output).
1659
+ - ``has_comp_axis`` - ``True`` when components are expanded (not collapsed to a scalar).
1660
+ - ``axis_labels`` - one key suffix per quantile/interval/label entry.
1661
+
1662
+ Raises
1663
+ ------
1664
+ ValueError
1665
+ If ``label_reduction=None`` is requested without explicit ``labels``.
1666
+ """
1667
+ params = inspect.signature(metric).parameters
1668
+
1669
+ def effective(param_name: str) -> Any:
1670
+ """Return metric_kwargs value if present, else the signature default."""
1671
+ if param_name in metric_kwargs:
1672
+ return metric_kwargs[param_name]
1673
+ return params[param_name].default if param_name in params else None
1674
+
1675
+ has_time_axis = "time_reduction" in params and effective("time_reduction") is None
1676
+ has_comp_axis = (
1677
+ "component_reduction" in params and effective("component_reduction") is None
1678
+ )
1679
+
1680
+ q_interval, q = metric_kwargs.get("q_interval"), metric_kwargs.get("q")
1681
+ if "q_interval" in params and q_interval is not None:
1682
+ intervals = np.atleast_2d(np.array(q_interval, dtype=float))
1683
+ axis_labels = [f"_qi{(hi - lo):.3f}" for lo, hi in intervals]
1684
+ elif "q" in params and q is not None:
1685
+ axis_labels = [f"_q{v:.3f}" for v in np.atleast_1d(np.array(q, dtype=float))]
1686
+ elif "label_reduction" in params:
1687
+ label_reduction = effective("label_reduction")
1688
+ if isinstance(label_reduction, _LabelReduction):
1689
+ label_reduction = label_reduction.value
1690
+ labels = metric_kwargs.get("labels")
1691
+ # label_reduction=None means one output per label, but without explicit
1692
+ # labels we can't know how many ahead of time
1693
+ if label_reduction is None and labels is None:
1694
+ raise_log(
1695
+ ValueError(
1696
+ "`label_reduction=None` requires explicit `labels` to be "
1697
+ "passed for MLflow autologging (the number of output "
1698
+ "labels cannot be determined ahead of time otherwise)."
1699
+ )
1700
+ )
1701
+ axis_labels = (
1702
+ [f"_label{x}" for x in np.atleast_1d(labels)]
1703
+ if label_reduction is None
1704
+ else [""]
1705
+ )
1706
+ else:
1707
+ axis_labels = [""]
1708
+
1709
+ return has_time_axis, has_comp_axis, axis_labels
1710
+
1711
+
1712
+ def _build_metric_keys(
1713
+ metric_names: list[str],
1714
+ components: list[str],
1715
+ has_comp_axis: bool,
1716
+ metric_axes: list[tuple[bool, bool, list[str]]],
1717
+ *,
1718
+ prefix: str = "",
1719
+ ) -> list[list[str]]:
1720
+ """Build sanitized MLflow metric keys for each metric x component x axis label.
1721
+
1722
+ Parameters
1723
+ ----------
1724
+ metric_names
1725
+ One sanitized metric-name token per metric.
1726
+ components
1727
+ Component names from the first series (used only when ``has_comp_axis``).
1728
+ has_comp_axis
1729
+ Whether components are preserved in the metric output.
1730
+ metric_axes
1731
+ Per-metric ``(has_time_axis, has_comp_axis, axis_labels)`` tuples from
1732
+ ``_infer_metric_axes``. Axis size is taken from the first entry.
1733
+ prefix
1734
+ Optional key prefix (e.g. ``"backtest_"``).
1735
+
1736
+ Returns
1737
+ -------
1738
+ list[list[str]]
1739
+ A list of lists of metric keys, where each inner list contains the sub-metric
1740
+ keys for a single metric. ``keys[m][i]`` is the sanitized key for metric index
1741
+ ``m`` and sub-metric index ``i``. Sub-metric index ``i`` is the component-label
1742
+ index walking axis labels innermost, then components (e.g. ``[_q0.100_comp1,
1743
+ _q0.900_comp1, _q0.100_comp2, _q0.900_comp2]``).
1744
+ """
1745
+ component_names = components if has_comp_axis else [None]
1746
+
1747
+ metric_keys: list[list[str]] = []
1748
+ for metric_idx, metric_name in enumerate(metric_names):
1749
+ labels = metric_axes[metric_idx][2]
1750
+ sub_metric_keys: list[str] = []
1751
+ for component in component_names:
1752
+ component_suffix = (
1753
+ f"_{_sanitize_mlflow_key(component)}" if component is not None else ""
1754
+ )
1755
+ for label in labels:
1756
+ sub_metric_keys.append(
1757
+ _sanitize_mlflow_key(
1758
+ f"{prefix}{metric_name}{component_suffix}{label}"
1759
+ )
1760
+ )
1761
+ metric_keys.append(sub_metric_keys)
1762
+ return metric_keys
1763
+
1764
+
1765
+ def _reshape_metric_result(
1766
+ series: TimeSeries,
1767
+ result,
1768
+ *,
1769
+ metric_keys: list[list[str]],
1770
+ has_time_axis: bool,
1771
+ has_windows: bool,
1772
+ forecast_horizon: int | None,
1773
+ is_backtest: bool,
1774
+ ) -> np.ndarray:
1775
+ """Reshape one series' backtest result to canonical ``(W, T, C, M)``.
1776
+
1777
+ - ``C`` is ``n_sub_metrics`` (n_components * n_quantiles/n_labels)
1778
+ - ``M`` is ``n_metrics``
1779
+ - ``T`` is ``1`` if not present, and otherwise the ``forecast_horizon`` or
1780
+ the length of the series (with ``last_points_only=True``).
1781
+ - ``W`` is ``1`` if not present, and otherwise the number of windows
1782
+
1783
+ After stripping the ``C`` and ``M`` axes, the leftover element count is split into
1784
+ ``(t_size, w_size)``:
1785
+
1786
+ - time axis and windows: ``T = forecast_horizon``, ``W = rest / T``
1787
+ - time axis only: ``T = rest``, ``W = 1``
1788
+ - windows only: ``T = 1``, ``W = rest``
1789
+ - neither: ``T = W = 1`` (``rest`` must be 1)
1790
+
1791
+ Returns
1792
+ -------
1793
+ np.ndarray
1794
+ Series metric values with shape ``(W, T, C, M)``.
1795
+ """
1796
+ arr = np.asarray(result, dtype=series.dtype)
1797
+ n_metrics = len(metric_keys)
1798
+ n_sub_metrics = len(metric_keys[0])
1799
+ n_round_multiples, remainder = divmod(arr.size, n_sub_metrics * n_metrics)
1800
+ if remainder:
1801
+ raise_log(
1802
+ ValueError(
1803
+ f"{'Backtest metric' if is_backtest else 'Metric'} logging failed: "
1804
+ f"result size ({arr.size}) is not divisible by n_sub_metrics * "
1805
+ f"n_metrics ({n_sub_metrics} * {n_metrics} = {n_sub_metrics * n_metrics}). "
1806
+ f"The metric output shape does not match the inferred axes."
1807
+ )
1808
+ )
1809
+
1810
+ if has_time_axis and has_windows:
1811
+ # T is the forecast horizon; W is recovered from the leftover length;
1812
+ # time-dependent metrics + last_points_only=False + no reduction
1813
+ assert forecast_horizon is not None
1814
+ t_size, w_size = forecast_horizon, n_round_multiples // forecast_horizon
1815
+ elif has_time_axis:
1816
+ # time-dependent metrics + last_points_only=False + reduction
1817
+ t_size, w_size = n_round_multiples, 1
1818
+ elif has_windows:
1819
+ # time-aggregated metrics + last_points_only=False + no reduction
1820
+ t_size, w_size = 1, n_round_multiples
1821
+ elif n_round_multiples == 1:
1822
+ # time-aggregated metrics + reduction
1823
+ t_size, w_size = 1, 1
1824
+ else:
1825
+ raise_log(
1826
+ ValueError(
1827
+ f"{'Backtest metric' if is_backtest else 'Metric'} logging failed: "
1828
+ f"expected a single scalar per component/metric after reduction, but got "
1829
+ f"{n_round_multiples} elements. Check time_reduction and "
1830
+ "component_reduction defaults."
1831
+ )
1832
+ )
1833
+
1834
+ return arr.reshape(w_size, t_size, n_sub_metrics, n_metrics)
1835
+
1836
+
1837
+ def _collect_stepped_and_detailed_metrics(
1838
+ series_metrics: list[np.ndarray],
1839
+ metric_keys: list[list[str]],
1840
+ *,
1841
+ has_time_axis: bool,
1842
+ has_windows: bool,
1843
+ last_points_only: bool,
1844
+ series_align: Literal["start", "end"] = "end",
1845
+ ) -> tuple[dict[tuple[str, int], list[float]], list[dict]]:
1846
+ """Parse series metrics and build inputs for MLflow stepped metrics and detailed metric table.
1847
+
1848
+ Each ``series_metrics`` array has shape ``(w_size, t_size, n_metrics * n_sub_metrics)``.
1849
+ Shorter series are aligned from the start or end of the longest remaining axis
1850
+ (windows, or time when there is no window axis), controlled by ``series_align``.
1851
+
1852
+ The MLflow ``step`` is the axis the UI should chart, always ``0 .. n-1``:
1853
+
1854
+ - forecast-horizon index when a time axis is present (time-dependent metrics)
1855
+ - if windows are present: each horizon step is aggregated over the windows
1856
+ - if multi-series: each horizon step is aggregated over the series
1857
+ - window index otherwise (time-aggregated metrics), aligned across series
1858
+ via ``series_align``
1859
+ - if multi-series: each window is aggregated over the series
1860
+ """
1861
+ stepped_metrics: dict[tuple[str, int], list[float]] = {}
1862
+ detailed_metrics: list[dict] = []
1863
+
1864
+ w_axis, t_axis = 0, 1
1865
+ max_w_size = max((values.shape[w_axis] for values in series_metrics), default=0)
1866
+ max_t_size = max((values.shape[t_axis] for values in series_metrics), default=0)
1867
+
1868
+ for series_index, values in enumerate(series_metrics):
1869
+ w_size = values.shape[w_axis]
1870
+ t_size = values.shape[t_axis]
1871
+
1872
+ # pad shorter series so their last (end) or first (start) point lines up
1873
+ if series_align == "end":
1874
+ w_offset = max_w_size - w_size if has_windows else 0
1875
+ t_offset = max_t_size - t_size if has_time_axis and not has_windows else 0
1876
+ else:
1877
+ w_offset = 0
1878
+ t_offset = 0
1879
+
1880
+ for metric_idx, sub_metric_keys in enumerate(metric_keys):
1881
+ for sub_metric_idx, key in enumerate(sub_metric_keys):
1882
+ for w in range(w_size):
1883
+ window_index = w + w_offset if has_windows else None
1884
+ for t in range(t_size):
1885
+ if has_time_axis and (has_windows or not last_points_only):
1886
+ # bt: backtest, sm: standalone metric
1887
+ # (bt) time-dependent metrics + last_points_only=False + no reduction
1888
+ # (bt) time-dependent metrics + last_points_only=False + reduction
1889
+ # (sm) time-dependent metrics
1890
+ step = t
1891
+ elif has_time_axis:
1892
+ # (bt) time-dependent metrics + last_points_only=True + no reduction
1893
+ step = t + t_offset
1894
+ else:
1895
+ # (bt) last_points_only=False + reduction (window index is None)
1896
+ # (bt) last_points_only=False + no reduction (window index is not None)
1897
+ # (sm) time-aggregated metrics (window index is None)
1898
+ step = window_index
1899
+
1900
+ value = float(values[w, t, sub_metric_idx, metric_idx])
1901
+ # table: one value per window and horizon
1902
+ detailed_metrics.append({
1903
+ "key": key,
1904
+ "series_index": series_index,
1905
+ "step": step,
1906
+ "window_index": window_index,
1907
+ "value": value,
1908
+ })
1909
+ # stepped metric chart: one value per window or horizon
1910
+ stepped_metrics.setdefault((key, step), []).append(value)
1911
+
1912
+ return stepped_metrics, detailed_metrics
1913
+
1914
+
1915
+ def _flush_logged_metrics(
1916
+ autologging_client: MlflowAutologgingQueueingClient,
1917
+ run_id: str,
1918
+ agg: dict[tuple[str, int], list[float]],
1919
+ agg_func: Callable,
1920
+ log_backtest_aggregate: bool = False,
1921
+ table_rows: list[dict] | None = None,
1922
+ ) -> None:
1923
+ """Aggregate per-series cells, log MLflow metrics, and optionally write the
1924
+ per-series table artifact.
1925
+
1926
+ Parameters
1927
+ ----------
1928
+ autologging_client
1929
+ MLflow autologging client used to queue metric writes.
1930
+ run_id
1931
+ ID of the active MLflow run.
1932
+ agg
1933
+ Map of ``(key, step) -> list of per-series float values``.
1934
+ agg_func
1935
+ Aggregation over the per-series values for each ``(key, step)``.
1936
+ log_backtest_aggregate
1937
+ If ``True``, log an additional scalar per backtest key under
1938
+ ``backtest_agg_{metric_key}`` as ``agg_func`` over all logged steps.
1939
+ table_rows
1940
+ Granular cells for ``metrics_per_series.json``. ``None`` skips writing
1941
+ the table artifact.
1942
+ """
1943
+ metrics_by_step: dict[int, dict[str, float]] = {}
1944
+ backtest_agg: dict[str, list[float]] = {}
1945
+ for (key, step), values in agg.items():
1946
+ step_agg = float(agg_func(values))
1947
+ metrics_by_step.setdefault(step, {})[key] = step_agg
1948
+
1949
+ if log_backtest_aggregate and key.startswith("backtest_"):
1950
+ agg_key = key.replace("backtest_", "backtest_agg_", 1)
1951
+ backtest_agg.setdefault(agg_key, []).append(step_agg)
1952
+
1953
+ for step, metrics in metrics_by_step.items():
1954
+ autologging_client.log_metrics(run_id=run_id, metrics=metrics, step=step)
1955
+
1956
+ if backtest_agg:
1957
+ aggregate_metrics = {
1958
+ agg_key: float(agg_func(step_values))
1959
+ for agg_key, step_values in backtest_agg.items()
1960
+ }
1961
+ autologging_client.log_metrics(run_id=run_id, metrics=aggregate_metrics, step=0)
1962
+
1963
+ if table_rows is not None:
1964
+ _log_per_series_table(table_rows)
1965
+
1966
+
1967
+ def _log_per_series_table(rows: list[dict]) -> None:
1968
+ """Append the granular per-series metric breakdown to a single, run-wide
1969
+ table artifact.
1970
+
1971
+ Each row is a single metric cell for one series, with columns ``key`` (the
1972
+ aggregate MLflow key, without any series suffix), ``series_index``, ``step``
1973
+ (the time or window index charted by MLflow), ``window_index`` (the
1974
+ source backtest window ``0 .. max_w - 1`` aligned per ``series_align``, or
1975
+ ``None`` when there is no window axis), and ``value``. All calls within a run
1976
+ append to the same ``metrics_per_series.json`` artifact.
1977
+ Used when more than one series is scored, since the logged metric keys
1978
+ only carry the aggregate over series.
1979
+
1980
+ Parameters
1981
+ ----------
1982
+ rows
1983
+ One dict per metric cell with keys ``key``, ``series_index``, ``step``,
1984
+ ``window_index``, and ``value``.
1985
+ """
1986
+ if not rows:
1987
+ return
1988
+
1989
+ df = pd.DataFrame(rows)
1990
+ sort_by = ["key", "series_index", "step"]
1991
+ if "window_index" in df.columns:
1992
+ sort_by.append("window_index")
1993
+ df = df.sort_values(sort_by)
1994
+ mlflow.log_table(data=df, artifact_file="metrics_per_series.json")
datasets/raw/darts_benchmark_datasets/darts/utils/statistics.py ADDED
@@ -0,0 +1,1233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ TimeSeries Statistics
3
+ ---------------------
4
+ """
5
+
6
+ import math
7
+ from collections.abc import Sequence
8
+
9
+ import matplotlib.axes
10
+ import matplotlib.pyplot as plt
11
+ import numpy as np
12
+ from scipy.signal import argrelmax
13
+ from scipy.stats import norm
14
+ from statsmodels.compat.python import lzip
15
+ from statsmodels.tsa.seasonal import MSTL, STL, seasonal_decompose
16
+ from statsmodels.tsa.stattools import (
17
+ acf,
18
+ adfuller,
19
+ ccovf,
20
+ grangercausalitytests,
21
+ kpss,
22
+ pacf,
23
+ )
24
+
25
+ from darts import TimeSeries
26
+ from darts.logging import get_logger, raise_log
27
+ from darts.metrics.metrics import _tolerance_coverages
28
+ from darts.metrics.utils import _get_tolerance_levels
29
+ from darts.typing import TimeSeriesLike
30
+ from darts.utils.likelihood_models.sklearn import QuantileRegression
31
+ from darts.utils.missing_values import fill_missing_values
32
+ from darts.utils.ts_utils import get_single_series
33
+ from darts.utils.utils import ModelMode, SeasonalityMode
34
+
35
+ _NP_2_OR_ABOVE = int(np.__version__.split(".")[0]) >= 2
36
+ _NP_TRAPEZOID_FN = np.trapezoid if _NP_2_OR_ABOVE else np.trapz
37
+
38
+ logger = get_logger(__name__)
39
+
40
+
41
+ def check_seasonality(
42
+ ts: TimeSeries, m: int | None = None, max_lag: int = 24, alpha: float = 0.05
43
+ ):
44
+ """
45
+ Checks whether the TimeSeries `ts` is seasonal with period `m` or not.
46
+
47
+ If `m` is None, we work under the assumption that there is a unique seasonality period, which is inferred
48
+ from the Auto-correlation Function (ACF).
49
+
50
+ Parameters
51
+ ----------
52
+ ts
53
+ The time series to check for seasonality.
54
+ m
55
+ The seasonality period to check.
56
+ max_lag
57
+ The maximal lag allowed in the ACF.
58
+ alpha
59
+ The desired confidence level (default 5%).
60
+
61
+ Returns
62
+ -------
63
+ Tuple[bool, int]
64
+ A tuple `(season, m)`, where season is a boolean indicating whether the series has seasonality or not
65
+ and `m` is the seasonality period.
66
+ """
67
+
68
+ ts._assert_univariate()
69
+
70
+ if m is not None and (m < 2 or not isinstance(m, int)):
71
+ raise_log(ValueError("m must be an integer greater than 1."))
72
+
73
+ if m is not None and m > max_lag:
74
+ raise_log(ValueError("max_lag must be greater than or equal to m."))
75
+
76
+ n_unique = np.unique(ts.values()).shape[0]
77
+
78
+ if n_unique == 1: # Check for non-constant TimeSeries
79
+ return False, 0
80
+
81
+ r = acf(
82
+ ts.univariate_values(), nlags=max_lag, fft=False
83
+ ) # In case user wants to check for seasonality higher than 24 steps.
84
+
85
+ # Finds local maxima of Auto-Correlation Function
86
+ candidates = argrelmax(r)[0]
87
+
88
+ if len(candidates) == 0:
89
+ return False, 0
90
+
91
+ if m is not None:
92
+ # Check for local maximum when m is user defined.
93
+ test = m not in candidates
94
+
95
+ if test:
96
+ return False, m
97
+
98
+ candidates = [m]
99
+
100
+ # Remove r[0], the auto-correlation at lag order 0, that introduces bias.
101
+ r = r[1:]
102
+
103
+ # The non-adjusted upper limit of the significance interval.
104
+ band_upper = r.mean() + norm.ppf(1 - alpha / 2) * r.var()
105
+
106
+ # Significance test, stops at first admissible value. The two '-1' below
107
+ # compensate for the index change due to the restriction of the original r to r[1:].
108
+ for candidate in candidates:
109
+ stat = _bartlett_formula(r, candidate - 1, len(ts))
110
+ if r[candidate - 1] > stat * band_upper:
111
+ return True, candidate
112
+ return False, 0
113
+
114
+
115
+ def _bartlett_formula(r: np.ndarray, m: int, length: int) -> float:
116
+ """
117
+ Computes the standard error of `r` at order `m` with respect to `length` according to Bartlett's formula.
118
+
119
+ Parameters
120
+ ----------
121
+ r
122
+ The array whose standard error is to be computed.
123
+ m
124
+ The order of the standard error.
125
+ length
126
+ The size of the underlying sample to be used.
127
+
128
+ Returns
129
+ -------
130
+ float
131
+ The standard error of `r` with order `m`.
132
+ """
133
+
134
+ if m == 1:
135
+ return math.sqrt(1 / length)
136
+ else:
137
+ return math.sqrt((1 + 2 * sum(map(lambda x: x**2, r[: m - 1]))) / length)
138
+
139
+
140
+ def extract_trend_and_seasonality(
141
+ ts: TimeSeries,
142
+ freq: int | Sequence[int] | None = None,
143
+ model: SeasonalityMode | ModelMode = ModelMode.MULTIPLICATIVE,
144
+ method: str = "naive",
145
+ **kwargs,
146
+ ) -> tuple[TimeSeries, TimeSeries]:
147
+ """
148
+ Extracts trend and seasonality from a TimeSeries instance using `statsmodels.tsa`.
149
+
150
+ Parameters
151
+ ----------
152
+ ts
153
+ The series to decompose
154
+ freq
155
+ The seasonality period to use.
156
+ model
157
+ The type of decomposition to use.
158
+ Must be ``from darts.utils.utils import ModelMode, SeasonalityMode`` Enum member.
159
+ Either ``MULTIPLICATIVE`` or ``ADDITIVE``.
160
+ Defaults ``ModelMode.MULTIPLICATIVE``.
161
+ method
162
+ The method to be used to decompose the series.
163
+ - "naive" : Seasonal decomposition using moving averages [1]_.
164
+ - "STL" : Season-Trend decomposition using LOESS [2]_. Only compatible with ``ADDITIVE`` model type.
165
+ - "MSTL" : Season-Trend decomposition using LOESS with multiple seasonalities [3]_.
166
+ Only compatible with ``ADDITIVE`` model type.
167
+ kwargs
168
+ Other keyword arguments are passed down to the decomposition method.
169
+
170
+ Returns
171
+ -------
172
+ Tuple[TimeSeries, TimeSeries]
173
+ A tuple of (trend, seasonal) time series.
174
+
175
+ References
176
+ ----------
177
+ .. [1] https://www.statsmodels.org/devel/generated/statsmodels.tsa.seasonal.seasonal_decompose.html
178
+ .. [2] https://www.statsmodels.org/devel/generated/statsmodels.tsa.seasonal.STL.html
179
+ .. [3] https://www.statsmodels.org/devel/generated/statsmodels.tsa.seasonal.MSTL.html
180
+ """
181
+
182
+ ts._assert_univariate()
183
+ if not (model in ModelMode or model in SeasonalityMode): # pragma: no cover
184
+ raise_log(ValueError(f"Unknown value for model_mode: {model}."))
185
+
186
+ if model is SeasonalityMode.NONE:
187
+ raise_log(
188
+ ValueError("The model must be either MULTIPLICATIVE or ADDITIVE."),
189
+ )
190
+
191
+ if isinstance(freq, Sequence) and method != "MSTL":
192
+ raise_log(
193
+ ValueError(
194
+ f"{method} decomposition cannot be performed with more than one seasonality, received {freq}."
195
+ ),
196
+ )
197
+
198
+ if method == "naive":
199
+ decomp = seasonal_decompose(
200
+ ts.to_series(), period=freq, model=model.value, extrapolate_trend="freq"
201
+ )
202
+
203
+ elif method == "STL":
204
+ if model not in [SeasonalityMode.ADDITIVE, ModelMode.ADDITIVE]:
205
+ raise_log(
206
+ ValueError(
207
+ f"Only ADDITIVE model is compatible with the STL method. Current model is {model}."
208
+ ),
209
+ )
210
+
211
+ decomp = STL(
212
+ endog=ts.to_series(),
213
+ period=freq,
214
+ **kwargs,
215
+ ).fit()
216
+
217
+ elif method == "MSTL":
218
+ if model not in [SeasonalityMode.ADDITIVE, ModelMode.ADDITIVE]:
219
+ raise_log(
220
+ ValueError(
221
+ f"Only ADDITIVE model is compatible with the MSTL method. Current model is {model}."
222
+ ),
223
+ )
224
+
225
+ decomp = MSTL(
226
+ endog=ts.to_series(),
227
+ periods=freq,
228
+ **kwargs,
229
+ ).fit()
230
+
231
+ else:
232
+ raise_log(ValueError(f"Unknown value for method: {method}."))
233
+
234
+ # keep components, ... only if the number of components matches
235
+ season_shape = decomp.seasonal.shape
236
+ if len(season_shape) == 1:
237
+ season_shape = (season_shape[0], 1)
238
+ if season_shape[1] == ts.n_components:
239
+ components = ts.components
240
+ static_covariates = ts.static_covariates
241
+ hierarchy = ts.hierarchy
242
+ else:
243
+ components = None
244
+ static_covariates = None
245
+ hierarchy = None
246
+
247
+ season = TimeSeries(
248
+ times=ts.time_index,
249
+ values=decomp.seasonal,
250
+ components=components,
251
+ static_covariates=static_covariates,
252
+ hierarchy=hierarchy,
253
+ metadata=ts.metadata,
254
+ copy=False,
255
+ )
256
+ trend = TimeSeries(
257
+ times=ts.time_index,
258
+ values=decomp.trend,
259
+ components=ts.components,
260
+ copy=False,
261
+ **ts._attrs,
262
+ )
263
+ return trend, season
264
+
265
+
266
+ def remove_from_series(
267
+ ts: TimeSeries, other: TimeSeries, model: SeasonalityMode | ModelMode
268
+ ) -> TimeSeries:
269
+ """
270
+ Removes the TimeSeries `other` from the TimeSeries `ts` as specified by `model`.
271
+ Use e.g. to remove an additive or multiplicative trend from a series.
272
+
273
+ Parameters
274
+ ----------
275
+ ts
276
+ The TimeSeries to be modified.
277
+ other
278
+ The TimeSeries to remove.
279
+ model
280
+ The type of model considered.
281
+ Must be ``from darts.utils.utils import ModelMode, SeasonalityMode`` Enums member.
282
+ Either ``MULTIPLICATIVE`` or ``ADDITIVE``.
283
+ Defaults ``ModelMode.MULTIPLICATIVE``.
284
+
285
+ Returns
286
+ -------
287
+ TimeSeries
288
+ A TimeSeries defined by removing `other` from `ts`.
289
+ """
290
+
291
+ ts._assert_univariate()
292
+ if not (model in ModelMode or model in SeasonalityMode): # pragma: no cover
293
+ raise_log(ValueError(f"Unknown value for model_mode: {model}."))
294
+
295
+ if model.value == "multiplicative":
296
+ new_ts = ts / other
297
+ elif model.value == "additive":
298
+ new_ts = ts - other
299
+ else:
300
+ raise_log(
301
+ ValueError(
302
+ f"Invalid parameter; must be either ADDITIVE or MULTIPLICATIVE. Was: {model}."
303
+ )
304
+ )
305
+ return new_ts
306
+
307
+
308
+ def remove_seasonality(
309
+ ts: TimeSeries,
310
+ freq: int | None = None,
311
+ model: SeasonalityMode = SeasonalityMode.MULTIPLICATIVE,
312
+ method: str = "naive",
313
+ **kwargs,
314
+ ) -> TimeSeries:
315
+ """
316
+ Adjusts the TimeSeries `ts` for a seasonality of order `frequency` using the `model` decomposition.
317
+
318
+ Parameters
319
+ ----------
320
+ ts
321
+ The TimeSeries to adjust.
322
+ freq
323
+ The seasonality period to use.
324
+ model
325
+ The type of decomposition to use.
326
+ Must be a `from darts import SeasonalityMode` Enum member.
327
+ Either SeasonalityMode.MULTIPLICATIVE or SeasonalityMode.ADDITIVE.
328
+ Defaults SeasonalityMode.MULTIPLICATIVE.
329
+ method
330
+ The method to be used to decompose the series.
331
+ - "naive" : Seasonal decomposition using moving averages [1]_.
332
+ - "STL" : Season-Trend decomposition using LOESS [2]_. Only compatible with ``ADDITIVE`` model type.
333
+ Defaults to "naive"
334
+ kwargs
335
+ Other keyword arguments are passed down to the decomposition method.
336
+
337
+ Returns
338
+ -------
339
+ TimeSeries
340
+ A new TimeSeries instance that corresponds to the seasonality-adjusted 'ts'.
341
+
342
+ References
343
+ ----------
344
+ .. [1] https://www.statsmodels.org/devel/generated/statsmodels.tsa.seasonal.seasonal_decompose.html
345
+ .. [2] https://www.statsmodels.org/devel/generated/statsmodels.tsa.seasonal.STL.html
346
+ """
347
+ ts._assert_univariate()
348
+ if model is SeasonalityMode.NONE:
349
+ raise_log(
350
+ ValueError("The model must be either MULTIPLICATIVE or ADDITIVE."),
351
+ )
352
+ if model not in [SeasonalityMode.ADDITIVE, ModelMode.ADDITIVE] and method == "STL":
353
+ raise_log(
354
+ ValueError(
355
+ f"Only ADDITIVE seasonality is compatible with the STL method. Current model is {model}."
356
+ ),
357
+ )
358
+
359
+ _, seasonality = extract_trend_and_seasonality(ts, freq, model, method, **kwargs)
360
+ new_ts = remove_from_series(ts, seasonality, model)
361
+ return new_ts
362
+
363
+
364
+ def remove_trend(
365
+ ts: TimeSeries,
366
+ model: ModelMode = ModelMode.MULTIPLICATIVE,
367
+ method: str = "naive",
368
+ **kwargs,
369
+ ) -> TimeSeries:
370
+ """
371
+ Adjusts the TimeSeries `ts` for a trend using the `model` decomposition.
372
+
373
+ Parameters
374
+ ----------
375
+ ts
376
+ The TimeSeries to adjust.
377
+ model
378
+ The type of decomposition to use.
379
+ Must be a ``from darts.utils.utils import ModelMode`` Enum member.
380
+ Either ``MULTIPLICATIVE`` or ``ADDITIVE``.
381
+ Defaults ``ModelMode.MULTIPLICATIVE``.
382
+ method
383
+ The method to be used to decompose the series.
384
+ - "naive" : Seasonal decomposition using moving averages [1]_.
385
+ - "STL" : Season-Trend decomposition using LOESS [2]_. Only compatible with ``ADDITIVE`` model type.
386
+ Defaults to "naive"
387
+ kwargs
388
+ Other keyword arguments are passed down to the decomposition method.
389
+
390
+ Returns
391
+ -------
392
+ TimeSeries
393
+ A new TimeSeries instance that corresponds to the trend-adjusted 'ts'.
394
+
395
+ References
396
+ ----------
397
+ .. [1] https://www.statsmodels.org/devel/generated/statsmodels.tsa.seasonal.seasonal_decompose.html
398
+ .. [2] https://www.statsmodels.org/devel/generated/statsmodels.tsa.seasonal.STL.html
399
+ """
400
+
401
+ ts._assert_univariate()
402
+
403
+ if model not in [SeasonalityMode.ADDITIVE, ModelMode.ADDITIVE] and method == "STL":
404
+ raise_log(
405
+ ValueError(
406
+ f"Only ADDITIVE seasonality is compatible with the STL method. Current model is {model}."
407
+ ),
408
+ )
409
+ trend, _ = extract_trend_and_seasonality(ts, model=model, method=method, **kwargs)
410
+ new_ts = remove_from_series(ts, trend, model)
411
+ return new_ts
412
+
413
+
414
+ def stationarity_tests(
415
+ ts: TimeSeries,
416
+ p_value_threshold_adfuller: float = 0.05,
417
+ p_value_threshold_kpss: float = 0.05,
418
+ ) -> bool:
419
+ """
420
+ Double test on stationarity using both Kwiatkowski-Phillips-Schmidt-Shin and Augmented
421
+ Dickey-Fuller statistical tests.
422
+
423
+ WARNING
424
+ Because Augmented Dickey-Fuller is testing null hypothesis that ts IS NOT stationary and
425
+ Kwiatkowski-Phillips-Schmidt-Shin that
426
+ ts IS stationary, we can't really decide on the same p_value threshold for both tests in general.
427
+ It seems reasonable to keep them both at 0.05.
428
+ If other threshold has to be tested, they have to go in opposite direction (for example,
429
+ p_value_threshold_adfuller = 0.01 and p_value_threshold_kpss = 0.1).
430
+
431
+ Parameters
432
+ ----------
433
+ ts
434
+ The TimeSeries to test.
435
+ p_value_threshold_adfuller
436
+ p_value threshold to reject stationarity for Augmented Dickey-Fuller test.
437
+ p_value_threshold_kpss
438
+ p_value threshold to reject non-stationarity for Kwiatkowski-Phillips-Schmidt-Shin test.
439
+
440
+ Returns
441
+ -------
442
+ bool
443
+ If ts is stationary or not.
444
+ """
445
+ adf_res = stationarity_test_adf(ts)
446
+ kpss_res = stationarity_test_kpss(ts)
447
+
448
+ return (adf_res[1] < p_value_threshold_adfuller) and (
449
+ kpss_res[1] > p_value_threshold_kpss
450
+ )
451
+
452
+
453
+ def stationarity_test_kpss(
454
+ ts: TimeSeries, regression: str = "c", nlags: str | int = "auto"
455
+ ) -> tuple:
456
+ """
457
+ Provides Kwiatkowski-Phillips-Schmidt-Shin test for stationarity for a time series,
458
+ using :func:`statsmodels.tsa.stattools.kpss`. See [1]_.
459
+
460
+
461
+ Parameters
462
+ ----------
463
+ ts
464
+ The time series to test.
465
+ regression
466
+ The null hypothesis for the KPSS test.
467
+ 'c' : The data is stationary around a constant (default).
468
+ 'ct' : The data is stationary around a trend.
469
+ nlags
470
+ Indicates the number of lags to be used. If 'auto' (default), lags is calculated using the data-dependent method
471
+ of Hobijn et al. (1998). See also Andrews (1991), Newey & West (1994), and Schwert (1989). If set to 'legacy',
472
+ uses int(12 * (n / 100)**(1 / 4)) , as outlined in Schwert (1989).
473
+
474
+ Returns
475
+ -------
476
+ tuple
477
+ | kpss_stat: The test statistic.
478
+ | pvalue: The p-value of the test. The p-value is interpolated from Table 1 in [2]_,
479
+ | and a boundary point is returned if the test statistic is outside the table of critical values,
480
+ | that is, if the p-value is outside the interval (0.01, 0.1).
481
+ | lags: The truncation lag parameter.
482
+ | crit: The critical values at 10%, 5%, 2.5% and 1%. Based on [2]_.
483
+
484
+ References
485
+ ----------
486
+ .. [1] https://www.statsmodels.org/dev/generated/statsmodels.tsa.stattools.kpss.html
487
+ .. [2] Kwiatkowski et al. (1992)
488
+ """
489
+ ts._assert_univariate()
490
+ ts._assert_deterministic()
491
+
492
+ return kpss(ts.univariate_values(copy=False), regression, nlags)
493
+
494
+
495
+ def stationarity_test_adf(
496
+ ts: TimeSeries,
497
+ maxlag: None | int = None,
498
+ regression: str = "c",
499
+ autolag: None | str = "AIC",
500
+ ) -> tuple:
501
+ """
502
+ Provides Augmented Dickey-Fuller unit root test for a time series,
503
+ using :func:`statsmodels.tsa.stattools.adfuller`. See [1]_.
504
+
505
+
506
+ Parameters
507
+ ----------
508
+ ts
509
+ The time series to test.
510
+ maxlag
511
+ Maximum lag which is included in test, default value of 12*(nobs/100)^{1/4} is used when None.
512
+ regression
513
+ Constant and trend order to include in regression.
514
+ "c" : constant only (default).
515
+ "ct" : constant and trend.
516
+ "ctt" : constant, and linear and quadratic trend.
517
+ "n" : no constant, no trend.
518
+ autolag
519
+ Method to use when automatically determining the lag length among the values 0, 1, …, maxlag.
520
+ If "AIC" (default) or "BIC", then the number of lags is chosen to minimize the corresponding
521
+ information criterion. "t-stat" based choice of maxlag. Starts with maxlag and drops a lag
522
+ until the t-statistic on the last lag length is significant using a 5%-sized test.
523
+ If None, then the number of included lags is set to maxlag.
524
+
525
+ Returns
526
+ -------
527
+ tuple
528
+ | adf: The test statistic.
529
+ | pvalue: MacKinnon's approximate p-value based on [2]_.
530
+ | usedlag: The number of lags used.
531
+ | nobs: The number of observations used for the ADF regression and calculation of the critical values.
532
+ | critical: Critical values for the test statistic at the 1 %, 5 %, and 10 % levels. Based on [2]_.
533
+ | icbest: The maximized information criterion if autolag is not None.
534
+
535
+ References
536
+ ----------
537
+ .. [1] https://www.statsmodels.org/dev/generated/statsmodels.tsa.stattools.adfuller.html
538
+ .. [2] MacKinnon (1994, 2010)
539
+ """
540
+
541
+ ts._assert_univariate()
542
+ ts._assert_deterministic()
543
+
544
+ return adfuller(ts.univariate_values(copy=False), maxlag, regression, autolag)
545
+
546
+
547
+ def granger_causality_tests(
548
+ ts_cause: TimeSeries,
549
+ ts_effect: TimeSeries,
550
+ maxlag: int,
551
+ addconst: bool = True,
552
+ ) -> dict:
553
+ """
554
+ Provides four tests for granger non causality of 2 time series using
555
+ :func:`statsmodels.tsa.stattools.grangercausalitytests`.
556
+ See [1]_.
557
+
558
+
559
+ Parameters
560
+ ----------
561
+ ts_cause
562
+ A univariate deterministic time series. The statistical test determines if this time series
563
+ 'Granger causes' the time series ts_effect (second parameter). Missing values are not supported.
564
+ if H_0 (non causality) is rejected (p near 0), then there is a 'granger causality'.
565
+ ts_effect
566
+ Univariate time series 'Granger caused' by ts_cause.
567
+ maxlag
568
+ If an integer, computes the test for all lags up to maxlag.
569
+ If an iterable, computes the tests only for the lags in maxlag.
570
+ addconst
571
+ Include a constant in the model.
572
+
573
+ Returns
574
+ -------
575
+ Dict
576
+ All test results, dictionary keys are the number of lags. For each lag the values are a tuple,
577
+ with the first element a dictionary with test statistic, pvalues, degrees of freedom, the second element are
578
+ the OLS estimation results for the restricted model, the unrestricted model and the restriction (contrast)
579
+ matrix for the parameter f_test.
580
+
581
+ References
582
+ ----------
583
+ .. [1] https://www.statsmodels.org/dev/generated/statsmodels.tsa.stattools.grangercausalitytests.html
584
+ """
585
+
586
+ ts_cause._assert_univariate()
587
+ ts_effect._assert_univariate()
588
+
589
+ ts_cause._assert_deterministic()
590
+ ts_effect._assert_deterministic()
591
+
592
+ if ts_cause.freq != ts_effect.freq:
593
+ raise_log(
594
+ ValueError("ts_cause and ts_effect must have the same frequency."),
595
+ )
596
+
597
+ if not ts_cause.has_same_time_as(ts_effect):
598
+ logger.warning(
599
+ "ts_cause and ts_effect time series have different time index. "
600
+ "We will slice-intersect ts_cause with ts_effect."
601
+ )
602
+
603
+ ts_cause = ts_cause.slice_intersect(ts_effect)
604
+ ts_effect = ts_effect.slice_intersect(ts_cause)
605
+
606
+ if not stationarity_tests(ts_cause):
607
+ logger.warning(
608
+ "ts_cause doesn't seem to be stationary. Please review granger causality validity in your problem context."
609
+ )
610
+ if not stationarity_tests(ts_effect):
611
+ logger.warning(
612
+ "ts_effect doesn't seem to be stationary. Please review granger causality validity in your problem context."
613
+ )
614
+
615
+ return grangercausalitytests(
616
+ np.concatenate(
617
+ (ts_effect.values(copy=False), ts_cause.values(copy=False)), axis=1
618
+ ),
619
+ maxlag,
620
+ addconst,
621
+ )
622
+
623
+
624
+ def plot_acf(
625
+ ts: TimeSeries,
626
+ m: int | None = None,
627
+ max_lag: int = 24,
628
+ alpha: float = 0.05,
629
+ bartlett_confint: bool = True,
630
+ fig_size: tuple[int, int] = (10, 5),
631
+ axis: matplotlib.axes.Axes | None = None,
632
+ default_formatting: bool = True,
633
+ ) -> None:
634
+ """
635
+ Plots the Autocorrelation Function (ACF) of `ts`, highlighting it at lag `m`, with corresponding significance
636
+ interval. Uses :func:`statsmodels.tsa.stattools.acf` [1]_
637
+
638
+ Parameters
639
+ ----------
640
+ ts
641
+ The TimeSeries whose ACF should be plotted.
642
+ m
643
+ Optionally, a time lag to highlight on the plot.
644
+ max_lag
645
+ The maximal lag order to consider.
646
+ alpha
647
+ The confidence interval to display.
648
+ bartlett_confint
649
+ The boolean value indicating whether the confidence interval should be
650
+ calculated using Bartlett's formula. If set to `True`, the confidence interval
651
+ can be used in the model identification stage for fitting ARIMA models.
652
+ If set to `False`, the confidence interval can be used to test for randomness
653
+ (i.e. there is no time dependence in the data) of the data.
654
+ fig_size
655
+ The size of the figure to be displayed.
656
+ axis
657
+ Optionally, an axis object to plot the ACF on.
658
+ default_formatting
659
+ Whether to use the darts default scheme.
660
+
661
+ References
662
+ ----------
663
+ .. [1] https://www.statsmodels.org/dev/generated/statsmodels.tsa.stattools.acf.html
664
+ """
665
+
666
+ ts._assert_univariate()
667
+ if max_lag is None or not (1 <= max_lag < len(ts)):
668
+ raise_log(
669
+ ValueError(
670
+ "max_lag must be greater than or equal to 1 and less than len(ts)."
671
+ ),
672
+ )
673
+ if m is not None and not (0 <= m <= max_lag):
674
+ raise_log(
675
+ ValueError(
676
+ "m must be greater than or equal to 0 and less than or equal to max_lag."
677
+ ),
678
+ )
679
+ if alpha is None or not (0 < alpha < 1):
680
+ raise_log(ValueError("alpha must be greater than 0 and less than 1."))
681
+
682
+ r, confint = acf(
683
+ ts.univariate_values(),
684
+ nlags=max_lag,
685
+ fft=False,
686
+ alpha=alpha,
687
+ bartlett_confint=bartlett_confint,
688
+ )
689
+
690
+ if axis is None:
691
+ plt.figure(figsize=fig_size)
692
+ axis = plt
693
+
694
+ for i in range(len(r)):
695
+ axis.plot(
696
+ (i, i),
697
+ (0, r[i]),
698
+ color=(
699
+ ("#b512b8" if m is not None and i == m else "black")
700
+ if default_formatting
701
+ else None
702
+ ),
703
+ lw=(1 if m is not None and i == m else 0.5),
704
+ )
705
+
706
+ # Adjusts the upper band of the confidence interval to center it on the x axis.
707
+ upp_band = [confint[lag][1] - r[lag] for lag in range(1, max_lag + 1)]
708
+
709
+ # Setting color t0 None overrides custom settings
710
+ extra_arguments = {}
711
+ if default_formatting:
712
+ extra_arguments["color"] = "#003DFD"
713
+
714
+ axis.fill_between(
715
+ np.arange(1, max_lag + 1),
716
+ upp_band,
717
+ [-x for x in upp_band],
718
+ alpha=0.25 if default_formatting else None,
719
+ **extra_arguments,
720
+ )
721
+ axis.plot((0, max_lag + 1), (0, 0), color="black" if default_formatting else None)
722
+
723
+
724
+ def plot_pacf(
725
+ ts: TimeSeries,
726
+ m: int | None = None,
727
+ max_lag: int = 24,
728
+ method: str = "ywadjusted",
729
+ alpha: float = 0.05,
730
+ fig_size: tuple[int, int] = (10, 5),
731
+ axis: matplotlib.axes.Axes | None = None,
732
+ default_formatting: bool = True,
733
+ ) -> None:
734
+ """
735
+ Plots the Partial Autocorrelation Function (PACF) of `ts`, highlighting it at lag `m`, with corresponding
736
+ significance interval. Uses :func:`statsmodels.tsa.stattools.pacf` [1]_
737
+
738
+ Parameters
739
+ ----------
740
+ ts
741
+ The TimeSeries whose ACF should be plotted.
742
+ m
743
+ Optionally, a time lag to highlight on the plot.
744
+ max_lag
745
+ The maximal lag order to consider.
746
+ method
747
+ The method to be used for the PACF calculation.
748
+
749
+ - "yw" or "ywadjusted" : Yule-Walker with sample-size adjustment in denominator for acovf. Default.
750
+ - "ywm" or "ywmle" : Yule-Walker without adjustment.
751
+ - "ols" : regression of time series on lags of it and on constant.
752
+ - "ols-inefficient" : regression of time series on lags using a single common sample to estimate all pacf
753
+ coefficients.
754
+ - "ols-adjusted" : regression of time series on lags with a bias adjustment.
755
+ - "ld" or "ldadjusted" : Levinson-Durbin recursion with bias correction.
756
+ - "ldb" or "ldbiased" : Levinson-Durbin recursion without bias correction.
757
+ alpha
758
+ The confidence interval to display.
759
+ fig_size
760
+ The size of the figure to be displayed.
761
+ axis
762
+ Optionally, an axis object to plot the ACF on.
763
+ default_formatting
764
+ Whether to use the darts default scheme.
765
+
766
+ References
767
+ ----------
768
+ .. [1] https://www.statsmodels.org/dev/generated/statsmodels.tsa.stattools.pacf.html
769
+ """
770
+
771
+ ts._assert_univariate()
772
+ if max_lag is None or not (1 <= max_lag < len(ts) // 2):
773
+ raise_log(
774
+ ValueError(
775
+ "max_lag must be greater than or equal to 1 and less than len(ts)//2."
776
+ ),
777
+ )
778
+ if m is not None and not (0 <= m <= max_lag):
779
+ raise_log(
780
+ ValueError(
781
+ "m must be greater than or equal to 0 and less than or equal to max_lag."
782
+ ),
783
+ )
784
+ if alpha is None or not (0 < alpha < 1):
785
+ raise_log(ValueError("alpha must be greater than 0 and less than 1."))
786
+
787
+ r, confint = pacf(ts.univariate_values(), nlags=max_lag, method=method, alpha=alpha)
788
+
789
+ if axis is None:
790
+ plt.figure(figsize=fig_size)
791
+ axis = plt
792
+
793
+ for i in range(len(r)):
794
+ axis.plot(
795
+ (i, i),
796
+ (0, r[i]),
797
+ color=(
798
+ "#b512b8"
799
+ if m is not None and i == m
800
+ else "black"
801
+ if default_formatting
802
+ else None
803
+ ),
804
+ lw=(1 if m is not None and i == m else 0.5),
805
+ )
806
+
807
+ # Adjusts the upper band of the confidence interval to center it on the x axis.
808
+ upp_band = [confint[lag][1] - r[lag] for lag in range(1, max_lag + 1)]
809
+
810
+ extra_arguments = {}
811
+ if default_formatting:
812
+ extra_arguments["color"] = "#003DFD"
813
+
814
+ axis.fill_between(
815
+ np.arange(1, max_lag + 1),
816
+ upp_band,
817
+ [-x for x in upp_band],
818
+ alpha=0.25 if default_formatting else None,
819
+ **extra_arguments,
820
+ )
821
+ axis.plot((0, max_lag + 1), (0, 0), color="black" if default_formatting else None)
822
+
823
+
824
+ def plot_ccf(
825
+ ts: TimeSeries,
826
+ ts_other: TimeSeries,
827
+ m: int | None = None,
828
+ max_lag: int = 24,
829
+ alpha: float = 0.05,
830
+ bartlett_confint: bool = True,
831
+ fig_size: tuple[int, int] = (10, 5),
832
+ axis: matplotlib.axes.Axes | None = None,
833
+ default_formatting: bool = True,
834
+ ) -> None:
835
+ """
836
+ Plots the Cross Correlation Function (CCF) between `ts` and `ts_other`, highlighting it at lag `m`, with
837
+ corresponding significance interval. Uses :func:`statsmodels.tsa.stattools.ccf` [1]_
838
+
839
+ This can be used to find the cross correlation between the target and different covariates lags.
840
+ If `ts_other` is identical `ts`, it corresponds to `plot_acf()`.
841
+
842
+ Parameters
843
+ ----------
844
+ ts
845
+ The TimeSeries whose CCF with `ts_other` should be plotted.
846
+ ts_other
847
+ The TimeSeries which to compare against `ts` in the CCF. E.g. check the cross correlation of different
848
+ covariate lags with the target.
849
+ m
850
+ Optionally, a time lag to highlight on the plot.
851
+ max_lag
852
+ The maximal lag order to consider.
853
+ alpha
854
+ The confidence interval to display.
855
+ bartlett_confint
856
+ The boolean value indicating whether the confidence interval should be
857
+ calculated using Bartlett's formula.
858
+ fig_size
859
+ The size of the figure to be displayed.
860
+ axis
861
+ Optionally, an axis object to plot the CCF on.
862
+ default_formatting
863
+ Whether to use the darts default scheme.
864
+
865
+ References
866
+ ----------
867
+ .. [1] https://www.statsmodels.org/dev/generated/statsmodels.tsa.stattools.ccf.html
868
+ """
869
+
870
+ ts._assert_univariate()
871
+ ts_other._assert_univariate()
872
+ if max_lag is None or not (1 <= max_lag < len(ts)):
873
+ raise_log(
874
+ ValueError(
875
+ "max_lag must be greater than or equal to 1 and less than len(ts)."
876
+ ),
877
+ )
878
+ if m is not None and not (0 <= m <= max_lag):
879
+ raise_log(
880
+ ValueError(
881
+ "m must be greater than or equal to 0 and less than or equal to max_lag."
882
+ ),
883
+ )
884
+ if alpha is None or not (0 < alpha < 1):
885
+ raise_log(ValueError("alpha must be greater than 0 and less than 1."))
886
+ ts_other = ts_other.slice_intersect(ts)
887
+ if len(ts_other) != len(ts):
888
+ raise_log(
889
+ ValueError("`ts_other` must contain at least the full time index of `ts`."),
890
+ )
891
+
892
+ x = ts.univariate_values()
893
+ y = ts_other.univariate_values()
894
+ cvf = ccovf(x=x, y=y, adjusted=True, demean=True, fft=False)
895
+
896
+ ccf = cvf / (np.std(x) * np.std(y))
897
+ ccf = ccf[: max_lag + 1]
898
+
899
+ n_obs = len(x)
900
+ if bartlett_confint:
901
+ varccf = np.ones_like(ccf) / n_obs
902
+ varccf[0] = 0
903
+ varccf[1] = 1.0 / n_obs
904
+ varccf[2:] *= 1 + 2 * np.cumsum(ccf[1:-1] ** 2)
905
+ else:
906
+ varccf = 1.0 / n_obs
907
+
908
+ interval = norm.ppf(1.0 - alpha / 2.0) * np.sqrt(varccf)
909
+ confint = np.array(lzip(ccf - interval, ccf + interval))
910
+
911
+ if axis is None:
912
+ plt.figure(figsize=fig_size)
913
+ axis = plt
914
+
915
+ for i in range(len(ccf)):
916
+ axis.plot(
917
+ (i, i),
918
+ (0, ccf[i]),
919
+ color=(
920
+ ("#b512b8" if m is not None and i == m else "black")
921
+ if default_formatting
922
+ else None
923
+ ),
924
+ lw=(1 if m is not None and i == m else 0.5),
925
+ )
926
+
927
+ # Adjusts the upper band of the confidence interval to center it on the x axis.
928
+ upp_band = [confint[lag][1] - ccf[lag] for lag in range(1, max_lag + 1)]
929
+
930
+ # Setting color t0 None overrides custom settings
931
+ extra_arguments = {}
932
+ if default_formatting:
933
+ extra_arguments["color"] = "#003DFD"
934
+
935
+ axis.fill_between(
936
+ np.arange(1, max_lag + 1),
937
+ upp_band,
938
+ [-x for x in upp_band],
939
+ alpha=0.25 if default_formatting else None,
940
+ **extra_arguments,
941
+ )
942
+ axis.plot((0, max_lag + 1), (0, 0), color="black" if default_formatting else None)
943
+
944
+
945
+ def plot_hist(
946
+ data: TimeSeries | list[float] | np.ndarray,
947
+ bins: int | np.ndarray | list[float] | None = None,
948
+ density: bool = False,
949
+ title: str | None = None,
950
+ fig_size: tuple[int, int] | None = None,
951
+ ax: matplotlib.axes.Axes | None = None,
952
+ ) -> None:
953
+ """This function plots the histogram of values in a TimeSeries instance or an array-like.
954
+
955
+ All types of TimeSeries are supported (uni-, multivariate, deterministic, stochastic).
956
+ Depending on the number of components in `data`, up to four histograms can be plotted on one figure.
957
+ All stochastic samples will be displayed with the corresponding component.
958
+
959
+ If `data` is an array-like, ALL values will be displayed in the same histogram.
960
+
961
+ Parameters
962
+ ----------
963
+ data
964
+ TimeSeries instance or an array-like from which to plot the histogram.
965
+ bins
966
+ Optionally, either an integer value for the number of bins to be displayed
967
+ or an array-like of floats determining the position of bins.
968
+ density
969
+ bool, if `density` is set to `True`, the bin counts will be converted to probability density
970
+ title
971
+ The title of the figure to be displayed
972
+ fig_size
973
+ The size of the figure to be displayed.
974
+ ax
975
+ Optionally, an axis object to plot the histogram on.
976
+ """
977
+
978
+ n_plots_max = 4
979
+
980
+ if isinstance(data, TimeSeries):
981
+ if len(data.components) > n_plots_max:
982
+ logger.warning(
983
+ "TimeSeries contains more than 4 components. Only the first 4 components will be displayed."
984
+ )
985
+
986
+ components = list(data.components[:n_plots_max])
987
+ values = data[components].all_values(copy=False).flatten(order="F")
988
+ else:
989
+ values = data if isinstance(data, np.ndarray) else np.array(data)
990
+ if len(values.shape) > 1:
991
+ logger.warning(
992
+ "Input array-like data with `dim>1d` will be flattened and displayed in one histogram."
993
+ )
994
+
995
+ components = ["Data"]
996
+ values = values.flatten(order="F")
997
+
998
+ # compute the number of columns and rows for subplots depending on shape of input data
999
+ n_components = len(components)
1000
+ n_cols = 1 if n_components == 1 else 2
1001
+ n_rows = math.ceil(n_components / n_cols)
1002
+
1003
+ title = "Histogram" if title is None else title
1004
+ if ax is None:
1005
+ fig = plt.figure(constrained_layout=True, figsize=fig_size)
1006
+ gs = fig.add_gridspec(n_rows, n_cols)
1007
+ fig.suptitle(title)
1008
+ ax_all = [fig.add_subplot(gs[i]) for i in range(n_components)]
1009
+ else:
1010
+ if n_components > 1:
1011
+ logger.warning(
1012
+ "Only the first component is plotted when calling plot_hist() with a given `ax`"
1013
+ )
1014
+ ax.set_title(title)
1015
+ ax_all = [ax]
1016
+
1017
+ n_entries = len(values) // n_components
1018
+ for i, label, ax_i in zip(range(n_components), components, ax_all):
1019
+ ax_i.hist(
1020
+ values[i * n_entries : (i + 1) * n_entries],
1021
+ bins=bins,
1022
+ density=density,
1023
+ label=label,
1024
+ )
1025
+ ax_i.set_xlabel("value")
1026
+ ax_i.set_ylabel("count" if not density else "probability density")
1027
+ ax_i.legend()
1028
+
1029
+
1030
+ def plot_residuals_analysis(
1031
+ residuals: TimeSeries,
1032
+ num_bins: int = 20,
1033
+ fill_nan: bool = True,
1034
+ default_formatting: bool = True,
1035
+ acf_max_lag: int = 24,
1036
+ ) -> None:
1037
+ """Plots data relevant to residuals.
1038
+
1039
+ This function takes a univariate TimeSeries instance of residuals and plots their values,
1040
+ their distribution and their ACF.
1041
+ Please note that if the residual TimeSeries instance contains NaN values, the plots
1042
+ might be displayed incorrectly. If `fill_nan` is set to `True`, the missing values will
1043
+ be interpolated.
1044
+
1045
+ Parameters
1046
+ ----------
1047
+ residuals
1048
+ Univariate TimeSeries instance representing residuals.
1049
+ num_bins
1050
+ Optionally, an integer value determining the number of bins in the histogram.
1051
+ fill_nan
1052
+ A boolean value indicating whether NaN values should be filled in the residuals.
1053
+ default_formatting
1054
+ Whether to use the darts default scheme.
1055
+ acf_max_lag
1056
+ The maximum lag to be displayed in the ACF plot. Must be less than residuals length.
1057
+ """
1058
+
1059
+ residuals._assert_univariate()
1060
+
1061
+ fig = plt.figure(constrained_layout=True, figsize=(8, 6))
1062
+ gs = fig.add_gridspec(2, 2)
1063
+
1064
+ if fill_nan:
1065
+ residuals = fill_missing_values(residuals)
1066
+
1067
+ # plot values
1068
+ ax1 = fig.add_subplot(gs[:1, :])
1069
+ residuals.plot(ax=ax1)
1070
+ ax1.set_ylabel("value")
1071
+ ax1.set_title("Residual values")
1072
+
1073
+ # plot histogram and distribution
1074
+ res_values = residuals.univariate_values(copy=False)
1075
+ res_mean, res_std = (
1076
+ np.mean(res_values),
1077
+ np.std(res_values),
1078
+ )
1079
+ res_min, res_max = (
1080
+ min(res_values),
1081
+ max(res_values),
1082
+ )
1083
+ x = np.linspace(res_min, res_max, 100)
1084
+ ax2 = fig.add_subplot(gs[1:, 1:])
1085
+ plot_hist(residuals, bins=num_bins, ax=ax2)
1086
+ ax2.plot(
1087
+ x,
1088
+ norm(res_mean, res_std).pdf(x)
1089
+ * len(residuals)
1090
+ * (res_max - res_min)
1091
+ / num_bins,
1092
+ )
1093
+ ax2.yaxis.set_major_locator(plt.MaxNLocator(integer=True))
1094
+ ax2.set_title("Distribution")
1095
+ ax2.set_ylabel("count")
1096
+ ax2.set_xlabel("value")
1097
+
1098
+ # plot ACF
1099
+ acf_max_lag = min(acf_max_lag, len(residuals) - 1)
1100
+ ax3 = fig.add_subplot(gs[1:, :1])
1101
+ plot_acf(
1102
+ residuals, axis=ax3, default_formatting=default_formatting, max_lag=acf_max_lag
1103
+ )
1104
+ ax3.set_ylabel("ACF value")
1105
+ ax3.set_xlabel("lag")
1106
+ ax3.set_title("ACF")
1107
+
1108
+
1109
+ def plot_tolerance_curve(
1110
+ actual_series: TimeSeriesLike,
1111
+ pred_series: TimeSeriesLike,
1112
+ intersect: bool = True,
1113
+ min_tolerance: float = 0.0,
1114
+ max_tolerance: float = 1.0,
1115
+ step: float = 0.01,
1116
+ q: float | list[float] | None = None,
1117
+ n_jobs: int = 1,
1118
+ verbose: bool = False,
1119
+ fig_size: tuple[int, int] | None = None,
1120
+ axis: matplotlib.axes.Axes | None = None,
1121
+ ) -> None:
1122
+ """
1123
+ Plots the Tolerance Curve for evaluating forecast alignment.
1124
+
1125
+ The tolerance curve shows, for each tolerance level (as a percentage of the actual series range),
1126
+ what fraction of prediction points fall within that tolerance.
1127
+
1128
+ For multivariate series, one curve is plotted per component.
1129
+
1130
+ The Area Under Tolerance Curve (AUTC) can be computed using :func:`~darts.metrics.metrics.autc`.
1131
+
1132
+ Parameters
1133
+ ----------
1134
+ actual_series
1135
+ The (sequence of) actual series.
1136
+ pred_series
1137
+ The (sequence of) predicted series.
1138
+ intersect
1139
+ For time series that are overlapping in time without having the same time index, setting `True`
1140
+ will consider the values only over their common time interval (intersection in time).
1141
+ min_tolerance
1142
+ The minimum tolerance level as a fraction of the series half-range. Default is 0.0 (0%).
1143
+ max_tolerance
1144
+ The maximum tolerance level as a fraction of the series half-range. Default is 1.0 (100%).
1145
+ step
1146
+ The step size between tolerance levels. Default is 0.01 (1%).
1147
+ For example, with defaults, tolerances are [0.0, 0.01, 0.02, ..., 1.0].
1148
+ q
1149
+ Optionally, the quantile (float [0, 1]) or list of quantiles of interest to compute the metric on.
1150
+ n_jobs
1151
+ The number of jobs to run in parallel. Parallel jobs are created only when a ``Sequence[TimeSeries]`` is
1152
+ passed as input, parallelising operations regarding different ``TimeSeries``. Defaults to `1`
1153
+ (sequential). Setting the parameter to `-1` means using all the available processors.
1154
+ verbose
1155
+ Optionally, whether to print operations progress.
1156
+ fig_size
1157
+ The size of the figure to be displayed.
1158
+ axis
1159
+ Optionally, an axis object to plot on.
1160
+
1161
+ See Also
1162
+ --------
1163
+ :func:`~darts.metrics.metrics.autc` : Compute the Area Under Tolerance Curve as a single score.
1164
+ """
1165
+ # get coverage for different tolerance levels
1166
+ coverages = _tolerance_coverages(
1167
+ actual_series=actual_series,
1168
+ pred_series=pred_series,
1169
+ intersect=intersect,
1170
+ min_tolerance=min_tolerance,
1171
+ max_tolerance=max_tolerance,
1172
+ step=step,
1173
+ q=q,
1174
+ component_reduction=None,
1175
+ series_reduction=np.nanmean,
1176
+ n_jobs=n_jobs,
1177
+ verbose=verbose,
1178
+ )
1179
+
1180
+ tolerances = _get_tolerance_levels(
1181
+ min_tolerance=min_tolerance,
1182
+ max_tolerance=max_tolerance,
1183
+ step=step,
1184
+ )
1185
+
1186
+ # -> (n coverages, n components * n quantiles)
1187
+ if len(coverages.shape) == 1:
1188
+ coverages = coverages.reshape(-1, 1)
1189
+
1190
+ series_ = get_single_series(actual_series)
1191
+ if q is None or isinstance(q, float):
1192
+ coverage_labels = series_.components.tolist()
1193
+ else:
1194
+ coverage_labels = QuantileRegression(n_outputs=1, quantiles=q).component_names(
1195
+ series_
1196
+ )
1197
+
1198
+ if axis is None:
1199
+ _, axis = plt.subplots(figsize=fig_size)
1200
+
1201
+ tolerances_perc = tolerances * 100.0
1202
+ for i, comp_name in enumerate(coverage_labels):
1203
+ coverages_comp = coverages[:, i]
1204
+ coverages_perc = coverages_comp * 100.0
1205
+
1206
+ auc = _NP_TRAPEZOID_FN(coverages_comp, tolerances)
1207
+ label = f"{comp_name} (AUTC = {auc:.3f})"
1208
+ axis.step(
1209
+ tolerances_perc,
1210
+ coverages_perc,
1211
+ where="post",
1212
+ linewidth=2,
1213
+ label=label,
1214
+ )
1215
+ if len(coverage_labels) == 1:
1216
+ axis.fill_between(
1217
+ tolerances_perc,
1218
+ coverages_perc,
1219
+ alpha=0.25,
1220
+ color=axis.get_lines()[-1].get_color(),
1221
+ step="post",
1222
+ )
1223
+
1224
+ # add reference line for perfect predictions
1225
+ axis.axhline(y=100, color="gray", linestyle="--", alpha=0.5, linewidth=1)
1226
+
1227
+ axis.set_xlim(0, 100)
1228
+ axis.set_ylim(0, 105)
1229
+ axis.set_xlabel("Tolerance (% of range)")
1230
+ axis.set_ylabel("Coverage (%)")
1231
+ axis.set_title("Tolerance Curve")
1232
+ axis.grid(True, alpha=0.3)
1233
+ axis.legend()
datasets/raw/darts_benchmark_datasets/darts/utils/timeseries_generation.py ADDED
@@ -0,0 +1,950 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utils for TimeSeries generation
3
+ -------------------------------
4
+ """
5
+
6
+ from collections.abc import Callable, Sequence
7
+ from typing import Any
8
+
9
+ import holidays
10
+ import numpy as np
11
+ import pandas as pd
12
+
13
+ from darts.logging import raise_log
14
+ from darts.timeseries import (
15
+ DIMS,
16
+ HIERARCHY_TAG,
17
+ METADATA_TAG,
18
+ STATIC_COV_TAG,
19
+ TIME_AX,
20
+ TimeSeries,
21
+ )
22
+ from darts.typing import TimeIndex, TimeZone
23
+ from darts.utils.utils import _maybe_cast_array_dtype, generate_index
24
+
25
+ ONE_INDEXED_FREQS = {
26
+ "day",
27
+ "month",
28
+ "quarter",
29
+ "dayofyear",
30
+ "day_of_year",
31
+ "week",
32
+ "weekofyear",
33
+ "week_of_year",
34
+ }
35
+ TIMES_NAME = DIMS[TIME_AX]
36
+
37
+
38
+ def constant_timeseries(
39
+ value: float = 1,
40
+ start: pd.Timestamp | int | None = pd.Timestamp("2000-01-01"),
41
+ end: pd.Timestamp | int | None = None,
42
+ length: int | None = None,
43
+ freq: str | int | None = None,
44
+ column_name: str | None = "constant",
45
+ dtype: np.typing.DTypeLike = np.float64,
46
+ ) -> TimeSeries:
47
+ """
48
+ Creates a constant univariate TimeSeries with the given value, length (or end date), start date and frequency.
49
+
50
+ Parameters
51
+ ----------
52
+ value
53
+ The constant value that the TimeSeries object will assume at every index.
54
+ start
55
+ The start of the returned TimeSeries' index. If a pandas Timestamp is passed, the TimeSeries will have a pandas
56
+ DatetimeIndex. If an integer is passed, the TimeSeries will have a pandas RangeIndex index. Works only with
57
+ either `length` or `end`.
58
+ end
59
+ Optionally, the end of the returned index. Works only with either `start` or `length`. If `start` is
60
+ set, `end` must be of same type as `start`. Else, it can be either a pandas Timestamp or an integer.
61
+ length
62
+ Optionally, the length of the returned index. Works only with either `start` or `end`.
63
+ freq
64
+ The time difference between two adjacent entries in the returned index. In case `start` is a timestamp,
65
+ a DateOffset alias is expected; see
66
+ `docs <https://pandas.pydata.org/pandas-docs/stable/user_guide/TimeSeries.html#dateoffset-objects>`__.
67
+ By default, "D" (daily) is used.
68
+ If `start` is an integer, `freq` will be interpreted as the step size in the underlying RangeIndex.
69
+ The freq is optional for generating an integer index (if not specified, 1 is used).
70
+ column_name
71
+ Optionally, the name of the value column for the returned TimeSeries
72
+ dtype
73
+ The desired NumPy dtype (np.float32 or np.float64) for the resulting series
74
+
75
+ Returns
76
+ -------
77
+ TimeSeries
78
+ A constant TimeSeries with value 'value'.
79
+ """
80
+
81
+ index = generate_index(
82
+ start=start, end=end, freq=freq, length=length, name=TIMES_NAME
83
+ )
84
+ values = np.full(len(index), value, dtype=dtype)
85
+ return TimeSeries(
86
+ times=index,
87
+ values=values,
88
+ components=pd.Index([column_name]),
89
+ copy=False,
90
+ )
91
+
92
+
93
+ def linear_timeseries(
94
+ start_value: float = 0,
95
+ end_value: float = 1,
96
+ start: pd.Timestamp | int | None = pd.Timestamp("2000-01-01"),
97
+ end: pd.Timestamp | int | None = None,
98
+ length: int | None = None,
99
+ freq: str | int | None = None,
100
+ column_name: str | None = "linear",
101
+ dtype: np.typing.DTypeLike = np.float64,
102
+ ) -> TimeSeries:
103
+ """
104
+ Creates a univariate TimeSeries with a starting value of `start_value` that increases linearly such that
105
+ it takes on the value `end_value` at the last entry of the TimeSeries. This means that
106
+ the difference between two adjacent entries will be equal to
107
+ (`end_value` - `start_value`) / (`length` - 1).
108
+
109
+ Parameters
110
+ ----------
111
+ start_value
112
+ The value of the first entry in the TimeSeries.
113
+ end_value
114
+ The value of the last entry in the TimeSeries.
115
+ start
116
+ The start of the returned TimeSeries' index. If a pandas Timestamp is passed, the TimeSeries will have a pandas
117
+ DatetimeIndex. If an integer is passed, the TimeSeries will have a pandas RangeIndex index. Works only with
118
+ either `length` or `end`.
119
+ end
120
+ Optionally, the end of the returned index. Works only with either `start` or `length`. If `start` is
121
+ set, `end` must be of same type as `start`. Else, it can be either a pandas Timestamp or an integer.
122
+ length
123
+ Optionally, the length of the returned index. Works only with either `start` or `end`.
124
+ freq
125
+ The time difference between two adjacent entries in the returned index. In case `start` is a timestamp,
126
+ a DateOffset alias is expected; see
127
+ `docs <https://pandas.pydata.org/pandas-docs/stable/user_guide/TimeSeries.html#dateoffset-objects>`__.
128
+ By default, "D" (daily) is used.
129
+ If `start` is an integer, `freq` will be interpreted as the step size in the underlying RangeIndex.
130
+ The freq is optional for generating an integer index (if not specified, 1 is used).
131
+ column_name
132
+ Optionally, the name of the value column for the returned TimeSeries
133
+ dtype
134
+ The desired NumPy dtype (np.float32 or np.float64) for the resulting series
135
+
136
+ Returns
137
+ -------
138
+ TimeSeries
139
+ A linear TimeSeries created as indicated above.
140
+ """
141
+
142
+ index = generate_index(
143
+ start=start, end=end, freq=freq, length=length, name=TIMES_NAME
144
+ )
145
+ values = np.linspace(start_value, end_value, len(index), dtype=dtype)
146
+ return TimeSeries(
147
+ times=index,
148
+ values=values,
149
+ components=pd.Index([column_name]),
150
+ copy=False,
151
+ )
152
+
153
+
154
+ def sine_timeseries(
155
+ value_frequency: float = 0.1,
156
+ value_amplitude: float = 1.0,
157
+ value_phase: float = 0.0,
158
+ value_y_offset: float = 0.0,
159
+ start: pd.Timestamp | int | None = pd.Timestamp("2000-01-01"),
160
+ end: pd.Timestamp | int | None = None,
161
+ length: int | None = None,
162
+ freq: str | int | None = None,
163
+ column_name: str | None = "sine",
164
+ dtype: np.typing.DTypeLike = np.float64,
165
+ ) -> TimeSeries:
166
+ """
167
+ Creates a univariate TimeSeries with a sinusoidal value progression with a given frequency, amplitude,
168
+ phase and y offset.
169
+
170
+ Parameters
171
+ ----------
172
+ value_frequency
173
+ The number of periods that take place within one time unit given in `freq`.
174
+ value_amplitude
175
+ The maximum difference between any value of the returned TimeSeries and `y_offset`.
176
+ value_phase
177
+ The relative position within one period of the first value of the returned TimeSeries (in radians).
178
+ value_y_offset
179
+ The shift of the sine function along the y axis.
180
+ start
181
+ The start of the returned TimeSeries' index. If a pandas Timestamp is passed, the TimeSeries will have a pandas
182
+ DatetimeIndex. If an integer is passed, the TimeSeries will have a pandas RangeIndex index. Works only with
183
+ either `length` or `end`.
184
+ end
185
+ Optionally, the end of the returned index. Works only with either `start` or `length`. If `start` is
186
+ set, `end` must be of same type as `start`. Else, it can be either a pandas Timestamp or an integer.
187
+ length
188
+ Optionally, the length of the returned index. Works only with either `start` or `end`.
189
+ freq
190
+ The time difference between two adjacent entries in the returned index. In case `start` is a timestamp,
191
+ a DateOffset alias is expected; see
192
+ `docs <https://pandas.pydata.org/pandas-docs/stable/user_guide/TimeSeries.html#dateoffset-objects>`__.
193
+ By default, "D" (daily) is used.
194
+ If `start` is an integer, `freq` will be interpreted as the step size in the underlying RangeIndex.
195
+ The freq is optional for generating an integer index (if not specified, 1 is used).
196
+ column_name
197
+ Optionally, the name of the value column for the returned TimeSeries
198
+ dtype
199
+ The desired NumPy dtype (np.float32 or np.float64) for the resulting series
200
+
201
+ Returns
202
+ -------
203
+ TimeSeries
204
+ A sinusoidal TimeSeries parametrized as indicated above.
205
+ """
206
+
207
+ index = generate_index(
208
+ start=start, end=end, freq=freq, length=length, name=TIMES_NAME
209
+ )
210
+ values = np.array(range(len(index)), dtype=dtype)
211
+ values = (
212
+ value_amplitude * np.sin(2 * np.pi * value_frequency * values + value_phase)
213
+ + value_y_offset
214
+ )
215
+ return TimeSeries(
216
+ times=index,
217
+ values=values,
218
+ components=pd.Index([column_name]),
219
+ copy=False,
220
+ )
221
+
222
+
223
+ def gaussian_timeseries(
224
+ mean: float | np.ndarray = 0.0,
225
+ std: float | np.ndarray = 1.0,
226
+ start: pd.Timestamp | int | None = pd.Timestamp("2000-01-01"),
227
+ end: pd.Timestamp | int | None = None,
228
+ length: int | None = None,
229
+ freq: str | int | None = None,
230
+ column_name: str | None = "gaussian",
231
+ dtype: np.typing.DTypeLike = np.float64,
232
+ ) -> TimeSeries:
233
+ """
234
+ Creates a gaussian univariate TimeSeries by sampling all the series values independently,
235
+ from a gaussian distribution with mean `mean` and standard deviation `std`.
236
+
237
+ Parameters
238
+ ----------
239
+ mean
240
+ The mean of the gaussian distribution that is sampled at each step.
241
+ If a float value is given, the same mean is used at every step.
242
+ If a numpy.ndarray of floats with the same length as `length` is
243
+ given, a different mean is used at each time step.
244
+ std
245
+ The standard deviation of the gaussian distribution that is sampled at each step.
246
+ If a float value is given, the same standard deviation is used at every step.
247
+ If an array of dimension `(length, length)` is given, it will
248
+ be used as covariance matrix for a multivariate gaussian distribution.
249
+ start
250
+ The start of the returned TimeSeries' index. If a pandas Timestamp is passed, the TimeSeries will have a pandas
251
+ DatetimeIndex. If an integer is passed, the TimeSeries will have a pandas RangeIndex index. Works only with
252
+ either `length` or `end`.
253
+ end
254
+ Optionally, the end of the returned index. Works only with either `start` or `length`. If `start` is
255
+ set, `end` must be of same type as `start`. Else, it can be either a pandas Timestamp or an integer.
256
+ length
257
+ Optionally, the length of the returned index. Works only with either `start` or `end`.
258
+ freq
259
+ The time difference between two adjacent entries in the returned index. In case `start` is a timestamp,
260
+ a DateOffset alias is expected; see
261
+ `docs <https://pandas.pydata.org/pandas-docs/stable/user_guide/TimeSeries.html#dateoffset-objects>`__.
262
+ By default, "D" (daily) is used.
263
+ If `start` is an integer, `freq` will be interpreted as the step size in the underlying RangeIndex.
264
+ The freq is optional for generating an integer index (if not specified, 1 is used).
265
+ column_name
266
+ Optionally, the name of the value column for the returned TimeSeries
267
+ dtype
268
+ The desired NumPy dtype (np.float32 or np.float64) for the resulting series
269
+
270
+ Returns
271
+ -------
272
+ TimeSeries
273
+ A white noise TimeSeries created as indicated above.
274
+ """
275
+
276
+ if isinstance(mean, np.ndarray):
277
+ if mean.shape != (length,):
278
+ raise_log(
279
+ ValueError(
280
+ "If a vector of means is provided, "
281
+ "it requires the same length as the TimeSeries."
282
+ ),
283
+ )
284
+ if isinstance(std, np.ndarray):
285
+ if std.shape != (length, length):
286
+ raise_log(
287
+ ValueError(
288
+ "If a matrix of standard deviations is provided, "
289
+ "its shape has to match the length of the TimeSeries."
290
+ ),
291
+ )
292
+
293
+ index = generate_index(
294
+ start=start, end=end, freq=freq, length=length, name=TIMES_NAME
295
+ )
296
+ values = np.random.normal(mean, std, size=len(index)).astype(dtype)
297
+ return TimeSeries(
298
+ times=index,
299
+ values=values,
300
+ components=pd.Index([column_name]),
301
+ copy=False,
302
+ )
303
+
304
+
305
+ def random_walk_timeseries(
306
+ mean: float = 0.0,
307
+ std: float = 1.0,
308
+ start: pd.Timestamp | int | None = pd.Timestamp("2000-01-01"),
309
+ end: pd.Timestamp | int | None = None,
310
+ length: int | None = None,
311
+ freq: str | int | None = None,
312
+ column_name: str | None = "random_walk",
313
+ dtype: np.typing.DTypeLike = np.float64,
314
+ ) -> TimeSeries:
315
+ """
316
+ Creates a random walk univariate TimeSeries, where each step is obtained by sampling a gaussian distribution
317
+ with mean `mean` and standard deviation `std`.
318
+
319
+ Parameters
320
+ ----------
321
+ mean
322
+ The mean of the gaussian distribution that is sampled at each step.
323
+ std
324
+ The standard deviation of the gaussian distribution that is sampled at each step.
325
+ start
326
+ The start of the returned TimeSeries' index. If a pandas Timestamp is passed, the TimeSeries will have a pandas
327
+ DatetimeIndex. If an integer is passed, the TimeSeries will have a pandas RangeIndex index. Works only with
328
+ either `length` or `end`.
329
+ end
330
+ Optionally, the end of the returned index. Works only with either `start` or `length`. If `start` is
331
+ set, `end` must be of same type as `start`. Else, it can be either a pandas Timestamp or an integer.
332
+ length
333
+ Optionally, the length of the returned index. Works only with either `start` or `end`.
334
+ freq
335
+ The time difference between two adjacent entries in the returned index. In case `start` is a timestamp,
336
+ a DateOffset alias is expected; see
337
+ `docs <https://pandas.pydata.org/pandas-docs/stable/user_guide/TimeSeries.html#dateoffset-objects>`__.
338
+ By default, "D" (daily) is used.
339
+ If `start` is an integer, `freq` will be interpreted as the step size in the underlying RangeIndex.
340
+ The freq is optional for generating an integer index (if not specified, 1 is used).
341
+ column_name
342
+ Optionally, the name of the value column for the returned TimeSeries
343
+ dtype
344
+ The desired NumPy dtype (np.float32 or np.float64) for the resulting series
345
+
346
+ Returns
347
+ -------
348
+ TimeSeries
349
+ A random walk TimeSeries created as indicated above.
350
+ """
351
+
352
+ index = generate_index(
353
+ start=start, end=end, freq=freq, length=length, name=TIMES_NAME
354
+ )
355
+ values = np.cumsum(np.random.normal(mean, std, size=len(index)), dtype=dtype)
356
+ return TimeSeries(
357
+ times=index,
358
+ values=values,
359
+ components=pd.Index([column_name]),
360
+ copy=False,
361
+ )
362
+
363
+
364
+ def autoregressive_timeseries(
365
+ coef: Sequence[float],
366
+ start_values: Sequence[float] | None = None,
367
+ start: pd.Timestamp | int | None = pd.Timestamp("2000-01-01"),
368
+ end: pd.Timestamp | int | None = None,
369
+ length: int | None = None,
370
+ freq: str | int | None = None,
371
+ column_name: str | None = "autoregressive",
372
+ dtype: np.typing.DTypeLike = np.float64,
373
+ ) -> TimeSeries:
374
+ """
375
+ Creates a univariate, autoregressive TimeSeries whose values are calculated using specified coefficients `coef` and
376
+ starting values `start_values`.
377
+
378
+ Parameters
379
+ ----------
380
+ coef
381
+ The autoregressive coefficients used for calculating the next time step.
382
+ series[t] = coef[-1] * series[t-1] + coef[-2] * series[t-2] + ... + coef[0] * series[t-len(coef)]
383
+ start_values
384
+ The starting values used for calculating the first few values for which no lags exist yet.
385
+ series[0] = coef[-1] * starting_values[-1] + coef[-2] * starting_values[-2] + ... + coef[0] * starting_values[0]
386
+ start
387
+ The start of the returned TimeSeries' index. If a pandas Timestamp is passed, the TimeSeries will have a pandas
388
+ DatetimeIndex. If an integer is passed, the TimeSeries will have a pandas RangeIndex index. Works only with
389
+ either `length` or `end`.
390
+ end
391
+ Optionally, the end of the returned index. Works only with either `start` or `length`. If `start` is
392
+ set, `end` must be of same type as `start`. Else, it can be either a pandas Timestamp or an integer.
393
+ length
394
+ Optionally, the length of the returned index. Works only with either `start` or `end`.
395
+ freq
396
+ The time difference between two adjacent entries in the returned index. In case `start` is a timestamp,
397
+ a DateOffset alias is expected; see
398
+ `docs <https://pandas.pydata.org/pandas-docs/stable/user_guide/TimeSeries.html#dateoffset-objects>`__.
399
+ By default, "D" (daily) is used.
400
+ If `start` is an integer, `freq` will be interpreted as the step size in the underlying RangeIndex.
401
+ The freq is optional for generating an integer index (if not specified, 1 is used).
402
+ column_name
403
+ Optionally, the name of the value column for the returned TimeSeries
404
+ dtype
405
+ The desired NumPy dtype (np.float32 or np.float64) for the resulting series
406
+
407
+ Returns
408
+ -------
409
+ TimeSeries
410
+ An autoregressive TimeSeries created as indicated above.
411
+ """
412
+
413
+ # if no start values specified default to a list of 1s
414
+ if start_values is None:
415
+ start_values = np.ones(len(coef), dtype=dtype)
416
+ else:
417
+ if len(start_values) != len(coef):
418
+ raise_log(ValueError("start_values must have same length as coef."))
419
+
420
+ index = generate_index(
421
+ start=start, end=end, freq=freq, length=length, name=TIMES_NAME
422
+ )
423
+
424
+ values = np.empty(len(coef) + len(index), dtype=dtype)
425
+ values[: len(coef)] = start_values
426
+
427
+ for i in range(len(coef), len(coef) + len(index)):
428
+ # calculate next time step as dot product of coefs with previous len(coef) time steps
429
+ values[i] = np.dot(values[i - len(coef) : i], coef)
430
+ return TimeSeries(
431
+ times=index,
432
+ values=values[len(coef) :],
433
+ components=pd.Index([column_name]),
434
+ copy=False,
435
+ )
436
+
437
+
438
+ def _extend_time_index_until(
439
+ time_index: TimeIndex,
440
+ until: int | str | pd.Timestamp | None,
441
+ add_length: int,
442
+ name,
443
+ ) -> pd.DatetimeIndex:
444
+ if not add_length and not until:
445
+ return time_index
446
+
447
+ if bool(add_length) and bool(until):
448
+ raise_log(ValueError("set only one of `add_length` and `until`."))
449
+
450
+ datetime_index = isinstance(time_index, pd.DatetimeIndex)
451
+
452
+ if add_length:
453
+ length = len(time_index) + add_length
454
+ end = None
455
+ else:
456
+ length = None
457
+ end = pd.Timestamp(until) if isinstance(until, str) else until
458
+
459
+ new_time_index = generate_index(
460
+ start=time_index[0],
461
+ freq=time_index.freq if datetime_index else time_index.freq,
462
+ length=length,
463
+ end=end,
464
+ name=name,
465
+ )
466
+
467
+ if new_time_index[-1] < time_index[-1]:
468
+ raise_log(
469
+ ValueError(
470
+ f"`until={end}` must lie further ahead in the future than the end of time index {time_index[-1]}"
471
+ ),
472
+ )
473
+ return new_time_index
474
+
475
+
476
+ def holidays_timeseries(
477
+ time_index: TimeSeries | pd.DatetimeIndex,
478
+ country_code: str,
479
+ prov: str | None = None,
480
+ state: str | None = None,
481
+ column_name: str | None = "holidays",
482
+ until: int | str | pd.Timestamp | None = None,
483
+ add_length: int = 0,
484
+ dtype: np.typing.DTypeLike = np.float64,
485
+ tz: TimeZone = None,
486
+ ) -> TimeSeries:
487
+ """
488
+ Creates a binary univariate TimeSeries with index `time_index` that equals 1 at every index that lies within
489
+ (or equals) a selected country's holiday, and 0 otherwise.
490
+
491
+ Available countries can be found `here <https://holidays.readthedocs.io/en/latest/#available-countries>`__.
492
+
493
+ Parameters
494
+ ----------
495
+ time_index
496
+ Either a `pd.DatetimeIndex` or a `TimeSeries` for which to generate the holidays.
497
+ country_code
498
+ The country ISO code.
499
+ prov
500
+ The province.
501
+ state
502
+ The state.
503
+ until
504
+ Extend the time_index up until timestamp for datetime indexed series
505
+ and int for range indexed series, should match or exceed forecasting window.
506
+ add_length
507
+ Extend the time_index by add_length, should match or exceed forecasting window.
508
+ Set only one of until and add_length.
509
+ column_name
510
+ Optionally, the name of the value column for the returned TimeSeries.
511
+ dtype
512
+ The desired NumPy dtype (np.float32 or np.float64) for the resulting series.
513
+ tz
514
+ Optionally, a time zone to convert the time index before computing attributes.
515
+ Supports any type handled by pandas
516
+ `tz_convert <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.tz_convert.html>`__.
517
+
518
+ Returns
519
+ -------
520
+ TimeSeries
521
+ A new binary holiday TimeSeries instance.
522
+ """
523
+ time_index_ts, time_index = _process_time_index(
524
+ time_index=time_index,
525
+ tz=tz,
526
+ until=until,
527
+ add_length=add_length,
528
+ )
529
+
530
+ scope = range(time_index[0].year, (time_index[-1] + pd.Timedelta(days=1)).year)
531
+ country_holidays = holidays.country_holidays(
532
+ country_code, prov=prov, state=state, years=scope
533
+ )
534
+ index_series = pd.Series(time_index, index=time_index)
535
+ values = index_series.apply(lambda x: x in country_holidays).astype(dtype)
536
+ return TimeSeries(
537
+ times=time_index_ts,
538
+ values=values,
539
+ components=pd.Index([column_name]),
540
+ copy=False,
541
+ )
542
+
543
+
544
+ def datetime_attribute_timeseries(
545
+ time_index: pd.DatetimeIndex | TimeSeries,
546
+ attribute: str,
547
+ one_hot: bool = False,
548
+ cyclic: bool = False,
549
+ until: int | str | pd.Timestamp | None = None,
550
+ add_length: int = 0,
551
+ dtype=np.float64,
552
+ with_columns: list[str] | str | None = None,
553
+ tz: TimeZone = None,
554
+ ) -> TimeSeries:
555
+ """
556
+ Returns a new TimeSeries with index `time_index` and one or more dimensions containing
557
+ (optionally one-hot encoded or cyclic encoded) pd.DatatimeIndex attribute information derived from the index.
558
+
559
+ 1-indexed attributes are shifted to enforce 0-indexing across all the encodings.
560
+
561
+ Parameters
562
+ ----------
563
+ time_index
564
+ Either a `pd.DatetimeIndex` attribute which will serve as the basis of the new column(s), or
565
+ a `TimeSeries` whose time axis will serve this purpose.
566
+ attribute
567
+ An attribute of `pd.DatetimeIndex`, or `week` / `weekofyear` / `week_of_year` - e.g. "month", "weekday", "day",
568
+ "hour", "minute", "second". See all available attributes `here
569
+ <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.html#pandas.DatetimeIndex>`__.
570
+ one_hot
571
+ Boolean value indicating whether to add the specified attribute as a one hot encoding
572
+ (results in more columns).
573
+ cyclic
574
+ Boolean value indicating whether to add the specified attribute as a cyclic encoding.
575
+ Alternative to one_hot encoding, enable only one of the two.
576
+ (adds 2 columns, corresponding to sin and cos transformation)
577
+ until
578
+ Extend the time_index up until timestamp for datetime indexed series
579
+ and int for range indexed series, should match or exceed forecasting window.
580
+ add_length
581
+ Extend the time_index by add_length, should match or exceed forecasting window.
582
+ Set only one of until and add_length.
583
+ dtype
584
+ The desired NumPy dtype (np.float32 or np.float64) for the resulting series
585
+ with_columns
586
+ Optionally, specify the output component names.
587
+
588
+ - If `one_hot` and `cyclic` are ``False``, must be a string
589
+ - If `cyclic` is ``True``, must be a list of two strings. The first string for the sine, the second for the
590
+ cosine component name.
591
+ - If `one_hot` is ``True``, must be a list of strings of the same length as the generated one hot encoded
592
+ features.
593
+ tz
594
+ Optionally, a time zone to convert the time index before computing attributes.
595
+ Supports any type handled by pandas
596
+ `tz_convert <https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.tz_convert.html>`__.
597
+
598
+ Returns
599
+ -------
600
+ TimeSeries
601
+ New datetime attribute TimeSeries instance.
602
+ """
603
+
604
+ time_index_ts, time_index = _process_time_index(
605
+ time_index=time_index,
606
+ tz=tz,
607
+ until=until,
608
+ add_length=add_length,
609
+ )
610
+
611
+ if not (
612
+ hasattr(pd.DatetimeIndex, attribute)
613
+ or (attribute in ["week", "weekofyear", "week_of_year"])
614
+ ):
615
+ raise_log(
616
+ ValueError(
617
+ f"attribute `{attribute}` needs to be an attribute of pd.DatetimeIndex. "
618
+ "See all available attributes in "
619
+ "https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.html#pandas.DatetimeIndex"
620
+ ),
621
+ )
622
+
623
+ if one_hot and cyclic:
624
+ raise_log(ValueError("set only one of one_hot or cyclic to true"))
625
+
626
+ num_values_dict = {
627
+ "month": 12,
628
+ "day": 31,
629
+ "weekday": 7,
630
+ "dayofweek": 7,
631
+ "day_of_week": 7,
632
+ "hour": 24,
633
+ "minute": 60,
634
+ "second": 60,
635
+ "microsecond": 1000000,
636
+ "nanosecond": 1000,
637
+ "quarter": 4,
638
+ "dayofyear": 365,
639
+ "day_of_year": 365,
640
+ "week": 52,
641
+ "weekofyear": 52,
642
+ "week_of_year": 52,
643
+ }
644
+
645
+ if attribute not in ["week", "weekofyear", "week_of_year"]:
646
+ values = getattr(time_index, attribute)
647
+ else:
648
+ values = (
649
+ time_index.isocalendar()
650
+ .set_index("week")
651
+ .index.astype("int64")
652
+ .rename("time")
653
+ )
654
+
655
+ # shift 1-indexed datetime attributes
656
+ if attribute in ONE_INDEXED_FREQS:
657
+ values -= 1
658
+
659
+ # leap years insert an additional day on the 29th of February
660
+ if attribute in {"dayofyear", "day_of_year"} and any(time_index.is_leap_year):
661
+ num_values_dict[attribute] += 1
662
+
663
+ # years contain an additional week if they are :
664
+ # - a regular year starting on a thursday
665
+ # - a leap year starting on a wednesday
666
+ if attribute in {"week", "weekofyear", "week_of_year"}:
667
+ years = time_index.year.unique()
668
+ # check if year respect properties
669
+ additional_week_year = any(
670
+ ((not first_day.is_leap_year) and first_day.day_name() == "Thursday")
671
+ or (first_day.is_leap_year and first_day.day_name() == "Wednesday")
672
+ for first_day in [pd.Timestamp(f"{year}-01-01") for year in years]
673
+ )
674
+ # check if time index actually include the additional week
675
+ additional_week_in_index = time_index[-1] - time_index[0] + pd.Timedelta(
676
+ days=1
677
+ ) >= pd.Timedelta(days=365)
678
+
679
+ if additional_week_year and additional_week_in_index:
680
+ num_values_dict[attribute] += 1
681
+
682
+ if one_hot or cyclic:
683
+ if attribute not in num_values_dict:
684
+ raise_log(
685
+ ValueError(
686
+ f"Given datetime attribute `{attribute}` not supported with one-hot or cyclical encoding. "
687
+ f"Supported datetime attribute: {list(num_values_dict.keys())}."
688
+ ),
689
+ )
690
+
691
+ if one_hot:
692
+ values_df = pd.get_dummies(values)
693
+ # fill missing columns (in case not all values appear in time_index)
694
+ attribute_range = np.arange(num_values_dict[attribute])
695
+ is_missing = np.isin(attribute_range, values_df.columns.values, invert=True)
696
+ # if there are attribute_range columns that are
697
+ # not in values_df.columns.values
698
+ if is_missing.any():
699
+ dict_0 = {i: False for i in attribute_range[is_missing]}
700
+ # Make a dataframe from the dictionary and concatenate it
701
+ # to the values values_df in which the existing columns
702
+ values_df = pd.concat(
703
+ [values_df, pd.DataFrame(dict_0, index=values_df.index)], axis=1
704
+ ).sort_index(axis=1)
705
+ else:
706
+ values_df = values_df[attribute_range]
707
+
708
+ if with_columns is None:
709
+ with_columns = [
710
+ attribute + "_" + str(column_name) for column_name in values_df.columns
711
+ ]
712
+
713
+ if len(with_columns) != len(values_df.columns):
714
+ raise_log(
715
+ ValueError(
716
+ "For the given case with `one_hot=True`,`with_columns` must be a list of strings of length "
717
+ f"{values_df.columns}."
718
+ ),
719
+ )
720
+
721
+ values_df.columns = with_columns
722
+ else:
723
+ if cyclic:
724
+ if attribute == "day":
725
+ periods = time_index.days_in_month.values
726
+ freq = 2 * np.pi * np.reciprocal(periods.astype(dtype))
727
+ else:
728
+ period = num_values_dict[attribute]
729
+ freq = 2 * np.pi / period
730
+
731
+ if with_columns is None:
732
+ with_columns = [attribute + "_sin", attribute + "_cos"]
733
+
734
+ if len(with_columns) != 2:
735
+ raise_log(
736
+ ValueError(
737
+ "`with_columns` must be a list of two strings when `cyclic=True`. "
738
+ "The first string for the sine component name, the second for the cosine component name."
739
+ ),
740
+ )
741
+ values_df = pd.DataFrame({
742
+ with_columns[0]: np.sin(freq * values),
743
+ with_columns[1]: np.cos(freq * values),
744
+ })
745
+ else:
746
+ if with_columns is None:
747
+ with_columns = attribute
748
+ if not isinstance(with_columns, str):
749
+ raise_log(
750
+ ValueError(
751
+ "`with_columns` must be a string specifying the output component name."
752
+ ),
753
+ )
754
+ values_df = pd.DataFrame({with_columns: values})
755
+ return TimeSeries(
756
+ times=time_index_ts,
757
+ values=values_df.values.astype(dtype),
758
+ components=values_df.columns,
759
+ copy=False,
760
+ )
761
+
762
+
763
+ def _build_forecast_series(
764
+ points_preds: np.ndarray | Sequence[np.ndarray],
765
+ input_series: TimeSeries,
766
+ custom_columns: list[str] | None = None,
767
+ with_static_covs: bool = True,
768
+ with_hierarchy: bool = True,
769
+ pred_start: pd.Timestamp | int | None = None,
770
+ time_index: TimeIndex | None = None,
771
+ copy: bool = False,
772
+ ) -> TimeSeries:
773
+ """
774
+ Builds a forecast time series starting after the end of an input time series, with the
775
+ correct time index (or after the end of the input series, if specified).
776
+
777
+ Parameters
778
+ ----------
779
+ points_preds
780
+ Forecasted values, can be either the target(s) or parameters of the likelihood model
781
+ input_series
782
+ TimeSeries used as input for the prediction
783
+ custom_columns
784
+ New names for the forecast TimeSeries, used when the number of components changes
785
+ with_static_covs
786
+ If set to `False`, do not copy the input_series `static_covariates` attribute
787
+ with_hierarchy
788
+ If set to `False`, do not copy the input_series `hierarchy` attribute
789
+ pred_start
790
+ Optionally, give a custom prediction start point. Only effective if `time_index` is `None`.
791
+ time_index
792
+ Optionally, the index to use for the forecast time series.
793
+ copy
794
+ If set to `True`, a copy of the input series is made. Otherwise, the input series is used as a view.
795
+
796
+ Returns
797
+ -------
798
+ TimeSeries
799
+ New TimeSeries instance starting after the input series
800
+ """
801
+ if time_index is None:
802
+ time_index_length = (
803
+ len(points_preds)
804
+ if isinstance(points_preds, np.ndarray)
805
+ else len(points_preds[0])
806
+ )
807
+ time_index = _generate_new_dates(
808
+ time_index_length,
809
+ input_series=input_series,
810
+ start=pred_start,
811
+ )
812
+ values = (
813
+ points_preds
814
+ if isinstance(points_preds, np.ndarray)
815
+ else np.stack(points_preds, axis=2)
816
+ )
817
+ values = _maybe_cast_array_dtype(values, input_series.dtype)
818
+ return TimeSeries(
819
+ times=time_index,
820
+ values=values,
821
+ freq=input_series.freq_str,
822
+ components=input_series.columns if custom_columns is None else custom_columns,
823
+ static_covariates=input_series.static_covariates if with_static_covs else None,
824
+ hierarchy=input_series.hierarchy if with_hierarchy else None,
825
+ metadata=input_series.metadata,
826
+ copy=copy,
827
+ )
828
+
829
+
830
+ def _build_forecast_series_from_schema(
831
+ values: np.ndarray,
832
+ schema: dict[str, Any],
833
+ pred_start: pd.Timestamp | int,
834
+ predict_likelihood_parameters: bool,
835
+ likelihood_component_names_fn: Callable | None = None,
836
+ copy: bool = False,
837
+ ) -> TimeSeries:
838
+ """
839
+ Builds a forecast time series from predicted values and `TimeSeries` schema starting at `pred_start`.
840
+
841
+ Parameters
842
+ ----------
843
+ values
844
+ Forecasted values, can be either the target(s) or parameters of the likelihood model
845
+ schema
846
+ Schema of the predicted target `TimeSeries`.
847
+ pred_start
848
+ The prediction start time.
849
+ predict_likelihood_parameters
850
+ Whether the values represent predicted likelihood parameters.
851
+ likelihood_component_names_fn
852
+ A function to compute the likelihood parameter component names. Only effective when
853
+ `predict_likelihood_parameters=True`.
854
+ copy
855
+ If set to `True`, a copy of the input series is made. Otherwise, the input series is used as a view.
856
+
857
+ Returns
858
+ -------
859
+ TimeSeries
860
+ A new TimeSeries instance.
861
+ """
862
+ time_index = generate_index(
863
+ start=pred_start,
864
+ freq=schema["time_freq"],
865
+ length=len(values),
866
+ name=schema["time_name"],
867
+ )
868
+ if predict_likelihood_parameters:
869
+ if likelihood_component_names_fn is None:
870
+ raise_log(
871
+ ValueError(
872
+ "Must pass `likelihood_component_names_fn` with "
873
+ "`predict_likelihood_parameters=True`"
874
+ ),
875
+ )
876
+ columns = likelihood_component_names_fn(components=schema["columns"])
877
+ static_covariates = None
878
+ hierarchy = None
879
+ else:
880
+ columns = schema["columns"]
881
+ static_covariates = schema[STATIC_COV_TAG]
882
+ hierarchy = schema[HIERARCHY_TAG]
883
+
884
+ # only torch models use this helper, we do not cast the data type to the input series' type
885
+ # since we support custom model precision
886
+ return TimeSeries(
887
+ times=time_index,
888
+ values=values,
889
+ components=columns,
890
+ static_covariates=static_covariates,
891
+ hierarchy=hierarchy,
892
+ metadata=schema[METADATA_TAG],
893
+ copy=copy,
894
+ )
895
+
896
+
897
+ def _generate_new_dates(
898
+ n: int, input_series: TimeSeries, start: pd.Timestamp | int | None = None
899
+ ) -> TimeIndex:
900
+ """
901
+ Generates `n` new dates after the end of the specified series
902
+ """
903
+ if start is None:
904
+ last = input_series.end_time()
905
+ start = last + input_series.freq
906
+ return generate_index(
907
+ start=start,
908
+ freq=input_series.freq,
909
+ length=n,
910
+ name=input_series._time_index.name,
911
+ )
912
+
913
+
914
+ def _process_time_index(
915
+ time_index: TimeSeries | pd.DatetimeIndex,
916
+ tz: TimeZone = None,
917
+ until: int | str | pd.Timestamp | None = None,
918
+ add_length: int = 0,
919
+ ) -> tuple[pd.DatetimeIndex, pd.DatetimeIndex]:
920
+ """
921
+ Extracts the time index, and optionally adds some time steps after the end of the index, and/or converts the
922
+ index to another time zone.
923
+
924
+ Returns a tuple of pd.DatetimeIndex with the first being the naive time index for generating a new TimeSeries,
925
+ and the second being the one used for generating datetime attributes and holidays in a potentially different
926
+ time zone.
927
+ """
928
+ if isinstance(time_index, TimeSeries):
929
+ time_index = time_index.time_index
930
+
931
+ if not isinstance(time_index, pd.DatetimeIndex):
932
+ raise_log(
933
+ ValueError(
934
+ "`time_index` must be a pandas `DatetimeIndex` or a `TimeSeries` indexed with a `DatetimeIndex`."
935
+ ),
936
+ )
937
+ if time_index.tz is not None:
938
+ raise_log(
939
+ ValueError("`time_index` must be time zone naive."),
940
+ )
941
+ time_index = _extend_time_index_until(
942
+ time_index, until, add_length, time_index.name
943
+ )
944
+
945
+ # convert to another time zone
946
+ if tz is not None:
947
+ time_index_ = time_index.tz_localize("UTC").tz_convert(tz)
948
+ else:
949
+ time_index_ = time_index
950
+ return time_index, time_index_
datasets/raw/darts_benchmark_datasets/darts/utils/torch.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utils for Pytorch and its usage
3
+ -------------------------------
4
+ """
5
+
6
+ from collections.abc import Callable
7
+ from functools import wraps
8
+ from typing import TypeVar
9
+
10
+ import numpy as np
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ from sklearn.utils import check_random_state
14
+ from torch import Tensor
15
+ from torch.random import fork_rng, manual_seed
16
+
17
+ from darts.logging import raise_log
18
+ from darts.utils.utils import MAX_NUMPY_SEED_VALUE, MAX_TORCH_SEED_VALUE, _is_method
19
+
20
+ T = TypeVar("T")
21
+
22
+
23
+ class MonteCarloDropout(nn.Dropout):
24
+ """
25
+ Defines Monte Carlo dropout Module as defined
26
+ in the paper https://arxiv.org/pdf/1506.02142.pdf.
27
+ In summary, This technique uses the regular dropout
28
+ which can be interpreted as a Bayesian approximation of
29
+ a well-known probabilistic model: the Gaussian process.
30
+ We can treat the many different networks
31
+ (with different neurons dropped out) as Monte Carlo samples
32
+ from the space of all available models. This provides mathematical
33
+ grounds to reason about the model’s uncertainty and, as it turns out,
34
+ often improves its performance.
35
+ """
36
+
37
+ # mc dropout is deactivated at init; see `MonteCarloDropout.mc_dropout_enabled` for more info
38
+ _mc_dropout_enabled = False
39
+
40
+ def forward(self, input: Tensor) -> Tensor:
41
+ # NOTE: we could use the following line in case a different rate
42
+ # is used for inference:
43
+ # return F.dropout(input, self.applied_rate, True, self.inplace)
44
+ return F.dropout(input, self.p, self.mc_dropout_enabled, self.inplace)
45
+
46
+ @property
47
+ def mc_dropout_enabled(self) -> bool:
48
+ # mc dropout is only activated on `PLForecastingModule.on_predict_start()`
49
+ # otherwise, it is activated based on the `model.training` flag.
50
+ return self._mc_dropout_enabled or self.training
51
+
52
+
53
+ def random_method(decorated: Callable[..., T]) -> Callable[..., T]:
54
+ """Decorator usable on any method within a class that will provide an isolated torch random context.
55
+
56
+ The decorator will store a `_random_instance` property on the object in order to persist successive calls to the RNG
57
+
58
+ Parameters
59
+ ----------
60
+ decorated
61
+ A method to be run in an isolated torch random context.
62
+ """
63
+ # check that @random_method has been applied to a method.
64
+ if not _is_method(decorated):
65
+ raise_log(ValueError("@random_method can only be used on methods."))
66
+
67
+ @wraps(decorated)
68
+ def decorator(self, *args, **kwargs) -> T:
69
+ store_instance = False
70
+ random_instance = None
71
+ if "random_state" in kwargs.keys() and kwargs["random_state"] is not None:
72
+ # get random state from model constructor or `predict()`
73
+ random_instance = check_random_state(kwargs["random_state"])
74
+ if not hasattr(self, "_random_instance"):
75
+ # store random instance when called from model constructor
76
+ store_instance = True
77
+ elif not hasattr(self, "_random_instance"):
78
+ # get random state for first time from other method
79
+ store_instance = True
80
+ random_instance = check_random_state(
81
+ np.random.randint(0, high=MAX_NUMPY_SEED_VALUE)
82
+ )
83
+
84
+ # if no random instance is provided, use the one stored in the class
85
+ if random_instance is None:
86
+ random_instance = self._random_instance
87
+
88
+ if store_instance:
89
+ self._random_instance = random_instance
90
+
91
+ # handle the randomness
92
+ with fork_rng():
93
+ manual_seed(random_instance.randint(0, high=MAX_TORCH_SEED_VALUE))
94
+ return decorated(self, *args, **kwargs)
95
+
96
+ return decorator
datasets/raw/darts_benchmark_datasets/darts/utils/ts_utils.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Additional TimeSeries related util functions
3
+ --------------------------------------------
4
+ """
5
+
6
+ from collections.abc import Sequence
7
+ from enum import Enum
8
+ from functools import total_ordering
9
+
10
+ from darts import TimeSeries
11
+ from darts.logging import raise_log
12
+ from darts.typing import TimeSeriesLike
13
+
14
+ _SEQ_TYPE_NAMES = {
15
+ 0: "`TimeSeries`",
16
+ 1: "`Sequence[TimeSeries]`",
17
+ 2: "`Sequence[Sequence[TimeSeries]]`",
18
+ }
19
+
20
+
21
+ @total_ordering
22
+ class SeriesType(Enum):
23
+ """An Enum for different `TimeSeries` sequence types."""
24
+
25
+ NONE = -1 # `None`
26
+ SINGLE = 0 # `TimeSeries`
27
+ SEQ = 1 # `Sequence[TimeSeries]`
28
+ SEQ_SEQ = 2 # `Sequence[Sequence[TimeSeries]]`
29
+
30
+ def _check_member(self, other):
31
+ if self.__class__ is not other.__class__:
32
+ raise_log(ValueError("`other` must be a `SeriesType` enum."))
33
+
34
+ def __eq__(self, other):
35
+ self._check_member(other)
36
+ return super().__eq__(other)
37
+
38
+ def __lt__(self, other):
39
+ self._check_member(other)
40
+ return self.value < other.value
41
+
42
+ def __add__(self, other: int):
43
+ if not isinstance(other, int):
44
+ raise_log(ValueError("`other` must be of type `int`."))
45
+ new_val = self.value + other
46
+ if new_val > 2:
47
+ raise_log(
48
+ ValueError("Cannot go higher than `SeriesType.SEQ_SEQ`."),
49
+ )
50
+ return SeriesType(new_val)
51
+
52
+ def __str__(self):
53
+ return _SEQ_TYPE_NAMES[self.value]
54
+
55
+
56
+ def series2seq(
57
+ ts: TimeSeriesLike | Sequence[Sequence[TimeSeries]] | None,
58
+ seq_type_out: SeriesType = SeriesType.SEQ,
59
+ nested: bool = False,
60
+ ) -> TimeSeriesLike | Sequence[Sequence[TimeSeries]] | None:
61
+ """If possible, converts `ts` into the desired sequence type `seq_type_out`. Otherwise, returns the
62
+ original `ts`.
63
+
64
+ Parameters
65
+ ----------
66
+ ts
67
+ None, a single TimeSeries, a sequence of TimeSeries, or a sequence of sequences of TimeSeries.
68
+ seq_type_out
69
+ The output sequence type:
70
+
71
+ - SeriesType.SINGLE: `TimeSeries` (e.g. a single series)
72
+ - SeriesType.SEQ: sequence of `TimeSeries` (e.g. multiple series)
73
+ - SeriesType.SEQ_SEQ: sequence of sequences of `TimeSeries` (e.g. historical forecasts output)
74
+ nested
75
+ Only applies with `seq_type_out=SeriesType.SEQ_SEQ` and `ts` having a sequence type `SeriesType.SEQ`.
76
+ In this case, wrap each element in `ts` in a list ([ts1, ts2] -> [[ts1], [ts2]]).
77
+
78
+ Raises
79
+ ------
80
+ ValueError
81
+ If there is an invalid `seq_type_out` value.
82
+ """
83
+ if ts is None:
84
+ return ts
85
+
86
+ if not isinstance(seq_type_out, SeriesType):
87
+ raise_log(
88
+ ValueError(
89
+ f"Invalid parameter `seq_type_out={seq_type_out}`. Must be one of `(0, 1, 2)`"
90
+ ),
91
+ )
92
+
93
+ seq_type_in = get_series_seq_type(ts)
94
+
95
+ if seq_type_out == seq_type_in:
96
+ return ts
97
+
98
+ n_series = 1 if seq_type_in == SeriesType.SINGLE else len(ts)
99
+
100
+ if seq_type_in == SeriesType.SINGLE and seq_type_out == SeriesType.SEQ:
101
+ # ts -> [ts]
102
+ return [ts]
103
+ elif seq_type_in == SeriesType.SINGLE and seq_type_out == SeriesType.SEQ_SEQ:
104
+ # ts -> [[ts]]
105
+ return [[ts]]
106
+ elif (
107
+ seq_type_in == SeriesType.SEQ
108
+ and seq_type_out == SeriesType.SINGLE
109
+ and n_series == 1
110
+ ):
111
+ # [ts] -> ts
112
+ return ts[0]
113
+ elif seq_type_in == SeriesType.SEQ and seq_type_out == SeriesType.SEQ_SEQ:
114
+ if not nested:
115
+ # [ts1, ts2] -> [[ts1, ts2]]
116
+ return [ts]
117
+ else:
118
+ # [ts1, ts2] -> [[ts1], [ts2]]
119
+ return [[ts_] for ts_ in ts]
120
+ elif (
121
+ seq_type_in == SeriesType.SEQ_SEQ
122
+ and seq_type_out == SeriesType.SINGLE
123
+ and n_series == 1
124
+ ):
125
+ # [[ts]] -> [ts]
126
+ return ts[0]
127
+ elif (
128
+ seq_type_in == SeriesType.SEQ_SEQ
129
+ and seq_type_out == SeriesType.SEQ
130
+ and n_series == 1
131
+ ):
132
+ # [[ts1, ts2]] -> [[ts1, ts2]]
133
+ return ts
134
+ else:
135
+ # ts -> ts
136
+ return ts
137
+
138
+
139
+ def seq2series(
140
+ ts: TimeSeriesLike | None,
141
+ ) -> TimeSeries | None:
142
+ """If `ts` is a Sequence with only a single series, return the single series as TimeSeries.
143
+
144
+ Parameters
145
+ ----------
146
+ ts
147
+ None, a single TimeSeries, or a sequence of TimeSeries
148
+
149
+ Returns
150
+ -------
151
+ `ts` if `ts` if is not a single element TimeSeries sequence, else `ts[0]`
152
+
153
+ """
154
+ return series2seq(ts, seq_type_out=SeriesType.SINGLE)
155
+
156
+
157
+ def get_single_series(
158
+ ts: TimeSeriesLike | Sequence[Sequence[TimeSeries]] | None,
159
+ ) -> TimeSeries | None:
160
+ """Returns a single (first) TimeSeries or `None` from `ts`. Returns `ts` if `ts` is a TimeSeries, `ts[0]` if
161
+ `ts` is a `Sequence[TimeSeries]`, and `ts[0][0]` if `ts` is a `Sequence[Sequence[TimeSeries]]`.
162
+ Otherwise, returns `None`.
163
+
164
+ Parameters
165
+ ----------
166
+ ts
167
+ None, a single `TimeSeries`, a sequence of `TimeSeries`, or a sequence of sequences of `TimeSeries`.
168
+
169
+ Returns
170
+ -------
171
+ TimeSeries
172
+ `ts` if `ts` is a TimeSeries, `ts[0]` if `ts` is a Sequence of TimeSeries. Otherwise, returns `None`
173
+
174
+ """
175
+ seq_type = get_series_seq_type(ts)
176
+ if seq_type <= SeriesType.SINGLE:
177
+ # `None` and `TimeSeries`
178
+ return ts
179
+ elif seq_type == SeriesType.SEQ:
180
+ return ts[0]
181
+ else:
182
+ return ts[0][0]
183
+
184
+
185
+ def get_series_seq_type(
186
+ ts: TimeSeriesLike | Sequence[Sequence[TimeSeries]] | None,
187
+ ) -> SeriesType:
188
+ """Returns the sequence type of `ts`.
189
+
190
+ - SeriesType.SINGLE: `TimeSeries` (e.g. a single series)
191
+ - SeriesType.SEQ: sequence of `TimeSeries` (e.g. multiple series)
192
+ - SeriesType.SEQ_SEQ: sequence of sequences of `TimeSeries` (e.g. historical forecasts output)
193
+
194
+ Parameters
195
+ ----------
196
+ ts
197
+ The input series to get the sequence type from.
198
+
199
+ Raises
200
+ ------
201
+ ValueError
202
+ If `ts` does not have one of the expected sequence types.
203
+ """
204
+ if ts is None:
205
+ return SeriesType.NONE
206
+ elif isinstance(ts, TimeSeries):
207
+ return SeriesType.SINGLE
208
+ elif isinstance(ts[0], TimeSeries):
209
+ return SeriesType.SEQ
210
+ else:
211
+ try:
212
+ if isinstance(ts[0][0], TimeSeries):
213
+ return SeriesType.SEQ_SEQ
214
+ else:
215
+ raise_log(
216
+ ValueError(
217
+ "input series must be of type `TimeSeries`, `Sequence[TimeSeries]`, or "
218
+ "`Sequence[Sequence[TimeSeries]]`."
219
+ ),
220
+ )
221
+ except Exception as err:
222
+ raise_log(
223
+ ValueError(
224
+ "input series must be of type `TimeSeries`, `Sequence[TimeSeries]`, or "
225
+ f"`Sequence[Sequence[TimeSeries]]`. Raised: `{type(err).__name__}('{str(err)}')`"
226
+ ),
227
+ )
228
+
229
+
230
+ # TODO: we do not check the time index here
231
+ def retain_period_common_to_all(series: list[TimeSeries]) -> list[TimeSeries]:
232
+ """
233
+ Trims all series in the provided list, if necessary, so that the returned time series have
234
+ a common span (corresponding to largest time sub-interval common to all series).
235
+
236
+ Parameters
237
+ ----------
238
+ series
239
+ The list of series to consider.
240
+
241
+ Raises
242
+ ------
243
+ ValueError
244
+ If no common time sub-interval exists
245
+
246
+ Returns
247
+ -------
248
+ List[TimeSeries]
249
+ A list of series, where each series have the same span
250
+ """
251
+
252
+ last_first = max(map(lambda s: s.start_time(), series))
253
+ first_last = min(map(lambda s: s.end_time(), series))
254
+
255
+ if last_first >= first_last:
256
+ raise_log(
257
+ ValueError("The provided time series must have nonzero overlap"),
258
+ )
259
+
260
+ return list(map(lambda s: s.slice(last_first, first_last), series))
datasets/raw/darts_benchmark_datasets/darts/utils/utils.py ADDED
@@ -0,0 +1,825 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Additional util functions
3
+ -------------------------
4
+ """
5
+
6
+ import contextlib
7
+ import importlib.util
8
+ import math
9
+ from collections.abc import Callable, Iterator
10
+ from enum import Enum
11
+ from functools import wraps
12
+ from inspect import Parameter, getcallargs, signature
13
+ from typing import Any, TypeVar
14
+
15
+ import narwhals as nw
16
+ import numpy as np
17
+ import pandas as pd
18
+ from narwhals import DataFrame
19
+ from pandas._libs.tslibs.offsets import BusinessMixin
20
+
21
+ from darts.logging import get_logger, raise_log
22
+ from darts.typing import TimeIndex
23
+
24
+ TORCH_AVAILABLE = importlib.util.find_spec("torch") is not None
25
+
26
+ logger = get_logger(__name__)
27
+
28
+ MAX_TORCH_SEED_VALUE = (1 << 31) - 1 # to accommodate 32-bit architectures
29
+ MAX_NUMPY_SEED_VALUE = (1 << 31) - 1
30
+
31
+ SUPPORTED_RESAMPLE_METHODS = [
32
+ "all",
33
+ "any",
34
+ "asfreq",
35
+ "backfill",
36
+ "bfill",
37
+ "count",
38
+ "ffill",
39
+ "first",
40
+ "interpolate",
41
+ "last",
42
+ "max",
43
+ "mean",
44
+ "median",
45
+ "min",
46
+ "nearest",
47
+ "pad",
48
+ "prod",
49
+ "quantile",
50
+ "reduce",
51
+ "std",
52
+ "sum",
53
+ "var",
54
+ ]
55
+
56
+
57
+ class NotImportedModule:
58
+ """Helper class for handling import errors of optional dependencies."""
59
+
60
+ usable = False
61
+
62
+ def __init__(self, module_name: str, warn: bool = True):
63
+ self.error_message = (
64
+ f"The `{module_name}` module could not be imported. "
65
+ f"To enable {module_name} support in Darts, follow the detailed "
66
+ f"instructions in the installation guide: "
67
+ f"https://github.com/unit8co/darts/blob/master/INSTALL.md"
68
+ )
69
+ if warn:
70
+ logger.warning(self.error_message)
71
+
72
+ def __call__(self, *args, **kwargs):
73
+ raise_log(ImportError(self.error_message))
74
+
75
+
76
+ # Enums
77
+ class SeasonalityMode(Enum):
78
+ MULTIPLICATIVE = "multiplicative"
79
+ ADDITIVE = "additive"
80
+ NONE = None
81
+
82
+
83
+ class TrendMode(Enum):
84
+ LINEAR = "linear"
85
+ EXPONENTIAL = "exponential"
86
+
87
+
88
+ class ModelMode(Enum):
89
+ MULTIPLICATIVE = "multiplicative"
90
+ ADDITIVE = "additive"
91
+ NONE = None
92
+
93
+
94
+ def _build_tqdm_iterator(iterable, verbose, **kwargs):
95
+ """
96
+ Build an iterable, possibly using tqdm (either in notebook or regular mode)
97
+
98
+ Parameters
99
+ ----------
100
+ iterable
101
+ verbose
102
+ total
103
+ Length of the iterator, helps in cases where tqdm is not detecting the total length.
104
+
105
+ Returns
106
+ -------
107
+ """
108
+ from tqdm import tqdm
109
+ from tqdm.notebook import tqdm as tqdm_notebook
110
+
111
+ try:
112
+ from IPython import get_ipython
113
+ except ModuleNotFoundError:
114
+ get_ipython = None
115
+
116
+ def _isnotebook():
117
+ if get_ipython is None:
118
+ return False
119
+ try:
120
+ shell = get_ipython().__class__.__name__
121
+ if shell == "ZMQInteractiveShell":
122
+ return True # Jupyter notebook or qtconsole
123
+ elif shell == "TerminalInteractiveShell":
124
+ return False # Terminal running IPython
125
+ else:
126
+ return False # Other type (?)
127
+ except NameError:
128
+ return False # Probably standard Python interpreter
129
+
130
+ if verbose:
131
+ if _isnotebook():
132
+ iterator = tqdm_notebook(iterable, **kwargs)
133
+ else:
134
+ iterator = tqdm(iterable, **kwargs)
135
+
136
+ else:
137
+ iterator = iterable
138
+ return iterator
139
+
140
+
141
+ # Types for sanity checks decorator: T is the output of the method to sanitize
142
+ T = TypeVar("T")
143
+
144
+
145
+ def _with_sanity_checks(
146
+ *sanity_check_methods: str,
147
+ ) -> Callable[[Callable[..., T]], Callable[..., T]]:
148
+ """
149
+ Decorator allowing to specify some sanity check method(s) to be used on a class method.
150
+ The decorator guarantees that args and kwargs from the method to sanitize will be available in the
151
+ sanity check methods as specified in the sanitized method's signature, irrespective of how it was called.
152
+ TypeVar `T` corresponds to the output of the method that the sanity checks are performed for.
153
+
154
+ Parameters
155
+ ----------
156
+ *sanity_check_methods
157
+ one or more sanity check methods that will be called with all the parameter of the decorated method.
158
+
159
+ Returns
160
+ -------
161
+ A Callable corresponding to the decorated method.
162
+
163
+ Examples
164
+ --------
165
+ class Model:
166
+ def _a_sanity_check(self, *args, **kwargs):
167
+ if kwargs['b'] != kwargs['c']:
168
+ raise_log(ValueError('b must equal c'))
169
+ @_with_sanity_checks("_a_sanity_check")
170
+ def fit(self, a, b=0, c=0):
171
+ # at this point we can safely assume that 'b' and 'c' are equal...
172
+ ...
173
+ """
174
+
175
+ def decorator(method_to_sanitize: Callable[..., T]) -> Callable[..., T]:
176
+ @wraps(method_to_sanitize)
177
+ def sanitized_method(self, *args, **kwargs) -> T:
178
+ only_args, only_kwargs = {}, {}
179
+ for sanity_check_method in sanity_check_methods:
180
+ # Convert all arguments into keyword arguments
181
+ all_as_kwargs = getcallargs(method_to_sanitize, self, *args, **kwargs)
182
+
183
+ # Then separate args from kwargs according to the function's signature
184
+ only_args = all_as_kwargs.copy()
185
+ only_kwargs = all_as_kwargs.copy()
186
+
187
+ for param_name, param in signature(
188
+ method_to_sanitize
189
+ ).parameters.items():
190
+ if (
191
+ param.default == Parameter.empty
192
+ and param.kind != Parameter.VAR_POSITIONAL
193
+ ):
194
+ only_kwargs.pop(param_name)
195
+ else:
196
+ only_args.pop(param_name)
197
+
198
+ only_args.pop("self")
199
+
200
+ getattr(self, sanity_check_method)(*only_args.values(), **only_kwargs)
201
+ return method_to_sanitize(self, *only_args.values(), **only_kwargs)
202
+
203
+ return sanitized_method
204
+
205
+ return decorator
206
+
207
+
208
+ def _parallel_apply(
209
+ iterator: Iterator[tuple], fn: Callable, n_jobs: int, fn_args, fn_kwargs
210
+ ) -> list:
211
+ """
212
+ Utility function that parallelise the execution of a function over an Iterator
213
+
214
+ Parameters
215
+ ----------
216
+ iterator (Iterator[Tuple])
217
+ Iterator which returns tuples of input value to feed to fn. Constant `args` and `kwargs` should passed through
218
+ `fn_args` and `fn_kwargs` respectively.
219
+ fn (Callable)
220
+ The function to be parallelized.
221
+ n_jobs (int)
222
+ The number of jobs to run in parallel. Defaults to `1` (sequential). Setting the parameter to `-1` means using
223
+ all the available processors.
224
+ Note: for a small amount of data, the parallelisation overhead could end up increasing the total
225
+ required amount of time.
226
+ fn_args
227
+ Additional arguments for each `fn()` call
228
+ fn_kwargs
229
+ Additional keyword arguments for each `fn()` call
230
+
231
+ """
232
+
233
+ from joblib import Parallel, delayed
234
+
235
+ returned_data = Parallel(n_jobs=n_jobs)(
236
+ delayed(fn)(*sample, *fn_args, **fn_kwargs) for sample in iterator
237
+ )
238
+ return returned_data
239
+
240
+
241
+ def _is_method(func: Callable[..., Any]) -> bool:
242
+ """Check if the specified function is a method.
243
+
244
+ Parameters
245
+ ----------
246
+ func
247
+ the function to inspect.
248
+
249
+ Returns
250
+ -------
251
+ bool
252
+ true if `func` is a method, false otherwise.
253
+ """
254
+ spec = signature(func)
255
+ return len(spec.parameters) > 0 and list(spec.parameters.keys())[0] == "self"
256
+
257
+
258
+ def _check_quantiles(quantiles):
259
+ if not all([0 < q < 1 for q in quantiles]):
260
+ raise_log(ValueError("All provided quantiles must be between 0 and 1."))
261
+
262
+ # we require the median to be present and the quantiles to be symmetric around it,
263
+ # for correctness of sampling.
264
+ median_q = 0.5
265
+ if median_q not in quantiles:
266
+ raise_log(ValueError("median quantile `q=0.5` must be in `quantiles`."))
267
+ is_centered = [
268
+ -1e-6 < (median_q - left_q) + (median_q - right_q) < 1e-6
269
+ for left_q, right_q in zip(quantiles, quantiles[::-1])
270
+ ]
271
+ if not all(is_centered):
272
+ raise_log(
273
+ ValueError(
274
+ "quantiles lower than `q=0.5` need to share same difference to `0.5` as quantiles "
275
+ "higher than `q=0.5`."
276
+ ),
277
+ )
278
+
279
+
280
+ def slice_index(
281
+ index: TimeIndex,
282
+ start: int | pd.Timestamp,
283
+ end: int | pd.Timestamp,
284
+ ) -> TimeIndex:
285
+ """
286
+ Returns a new Index with the same type as the input `index`, containing the values between `start`
287
+ and `end` included. If start and end are not in the index, the closest values are used instead.
288
+ The start and end values can be either integers (in which case they are interpreted as indices),
289
+ or pd.Timestamps (in which case they are interpreted as actual timestamps).
290
+
291
+
292
+ Parameters
293
+ ----------
294
+ index
295
+ The index to slice.
296
+ start
297
+ The start of the returned index.
298
+ end
299
+ The end of the returned index.
300
+
301
+ Returns
302
+ -------
303
+ pd.RangeIndex | pd.DatetimeIndex
304
+ A new index with the same type as the input `index`, but with only the values between `start` and `end`
305
+ included.
306
+ """
307
+
308
+ if type(start) is not type(end):
309
+ raise_log(
310
+ ValueError(
311
+ "start and end values must be of the same type (either both integers or both pd.Timestamps)"
312
+ ),
313
+ )
314
+
315
+ if isinstance(start, pd.Timestamp) and isinstance(index, pd.RangeIndex):
316
+ raise_log(
317
+ ValueError(
318
+ "start and end values are a pd.Timestamp, but time_index is a RangeIndex. "
319
+ "Please provide an integer start value."
320
+ ),
321
+ )
322
+ if isinstance(start, int) and isinstance(index, pd.DatetimeIndex):
323
+ raise_log(
324
+ ValueError(
325
+ "start and end value are integer, but time_index is a RangeIndex. "
326
+ "Please provide an integer end value."
327
+ ),
328
+ )
329
+
330
+ start_idx = index.get_indexer(generate_index(start, length=1), method="nearest")[0]
331
+ end_idx = index.get_indexer(generate_index(end, length=1), method="nearest")[0]
332
+
333
+ return index[start_idx : end_idx + 1]
334
+
335
+
336
+ def drop_before_index(
337
+ index: TimeIndex,
338
+ split_point: int | pd.Timestamp,
339
+ ) -> TimeIndex:
340
+ """
341
+ Drops everything before the provided time `split_point` (excluded) from the index.
342
+
343
+ Parameters
344
+ ----------
345
+ index
346
+ The index to drop values from.
347
+ split_point
348
+ The timestamp that indicates cut-off time.
349
+
350
+ Returns
351
+ -------
352
+ TimeIndex
353
+ A new index with values before `split_point` dropped.
354
+ """
355
+ return slice_index(index, split_point, index[-1])
356
+
357
+
358
+ def drop_after_index(
359
+ index: TimeIndex,
360
+ split_point: int | pd.Timestamp,
361
+ ) -> TimeIndex:
362
+ """
363
+ Drops everything after the provided time `split_point` (excluded) from the index.
364
+
365
+ Parameters
366
+ ----------
367
+ index
368
+ The index to drop values from.
369
+ split_point
370
+ The timestamp that indicates cut-off time.
371
+
372
+ Returns
373
+ -------
374
+ TimeIndex
375
+ A new index with values after `split_point` dropped.
376
+ """
377
+
378
+ return slice_index(index, index[0], split_point)
379
+
380
+
381
+ def n_steps_between(
382
+ end: pd.Timestamp | int,
383
+ start: pd.Timestamp | int,
384
+ freq: pd.DateOffset | int | str,
385
+ ) -> int:
386
+ """Get the number of time steps with a given frequency `freq` between `end` and `start`.
387
+ Works for both integers and time stamps.
388
+
389
+ * if `end`, `start`, `freq` are all integers, we can simple divide the difference by the frequency.
390
+ * if `freq` is a pandas Dateoffset with non-ambiguous timedelate (e.g. "d", "h", ..., and not "ME", "YE", ...),
391
+ we can simply divide by the frequency
392
+ * otherwise, we take the period difference between the two time stamps.
393
+
394
+ Parameters
395
+ ----------
396
+ end
397
+ The end pandas Timestamp / integer.
398
+ start
399
+ The start pandas Timestamp / integer.
400
+ freq
401
+ The frequency / step size.
402
+
403
+ Returns
404
+ -------
405
+ int
406
+ The number of steps/periods between `end` and `start` with a given frequency `freq`.
407
+
408
+ Examples
409
+ --------
410
+ >>> n_steps_between(start=pd.Timestamp("2000-01-01"), end=pd.Timestamp("2000-03-01"), freq="ME")
411
+ 2
412
+ >>> n_steps_between(start=0, end=2, freq=1)
413
+ 2
414
+ >>> n_steps_between(start=0, end=2, freq=2)
415
+ 1
416
+ """
417
+ freq = pd.tseries.frequencies.to_offset(freq) if isinstance(freq, str) else freq
418
+ valid_freq = freq >= 0 if isinstance(freq, int) else freq.n >= 0
419
+ if not valid_freq:
420
+ raise_log(
421
+ ValueError(f"`freq` must be positive/increasing, received freq={freq}."),
422
+ )
423
+ valid_int = (
424
+ isinstance(start, int) and isinstance(end, int) and isinstance(freq, int)
425
+ )
426
+ valid_time = (
427
+ isinstance(start, pd.Timestamp)
428
+ and isinstance(end, pd.Timestamp)
429
+ and isinstance(freq, pd.DateOffset)
430
+ )
431
+ if not (valid_int or valid_time):
432
+ raise_log(
433
+ ValueError(
434
+ "Either `start` and `end` must be pandas Timestamps and `freq` a pandas Dateoffset, "
435
+ "or all `start`, `end`, `freq` must be integers."
436
+ ),
437
+ )
438
+
439
+ # frequency has a fixed period (e.g. non-ambiguous timedelta value (not ‘M’, ‘Y’ or ‘y’, 'W'), or integer step)
440
+ if isinstance(freq, int) or pd.to_timedelta(freq, errors="coerce") is not pd.NaT:
441
+ diff = end - start
442
+ if abs(diff) != diff:
443
+ # (A) when diff is negative, not perfectly divisible by freq, and freq is a multiple of a base frequency
444
+ # (e.g., "2D" or step=2), then computing `diff // freq` can be one off
445
+ # Example: `end=1, start=2, freq=2` -> then `diff // freq` gives `-1`, but should be `0`.
446
+ diff += diff % freq
447
+ n_steps = diff // freq
448
+ else:
449
+ period_alias = pd.tseries.frequencies.get_period_alias(freq.name)
450
+ if isinstance(freq, BusinessMixin) or period_alias is None:
451
+ # for lower pandas versions ~1.5.0, business frequencies wrongly have a period alias.
452
+ # taking the period difference as computed in `else` gives wrong results.
453
+ # in this (worst) case for special frequencies (e.g "C*"), we must generate the index
454
+ is_reversed = end < start
455
+ if is_reversed:
456
+ # always generate an increasing index, since pandas (v2.2.1) gives inconsistent result for
457
+ # negative/decreasing frequencies. Then reverse the index in case of negative/decreasing
458
+ # input frequency
459
+ start, end = end, start
460
+ n_steps = len(generate_index(start=start, end=end, freq=freq))
461
+ if n_steps:
462
+ # index includes end, take away for difference
463
+ n_steps -= 1
464
+ if is_reversed:
465
+ n_steps *= -1
466
+ else:
467
+ # get the number of base periods ("2MS" has base freq "MS") between the two time steps
468
+ diff = (end.to_period(period_alias) - start.to_period(period_alias)).n
469
+ if abs(diff) != diff:
470
+ # similar case as with (A)
471
+ diff += diff % freq.n
472
+ # floor division by the frequency multiplier ("2MS" has multiplier 2)
473
+ n_steps = diff // freq.n
474
+ return n_steps
475
+
476
+
477
+ def infer_freq_intersection(
478
+ freq: int | str | pd.tseries.offsets.DateOffset,
479
+ other: int | str | pd.tseries.offsets.DateOffset,
480
+ ) -> int | pd.tseries.offsets.DateOffset:
481
+ """Infers the frequency at which two frequencies `freq` and `other` intersect.
482
+
483
+ Parameters
484
+ ----------
485
+ freq
486
+ The first frequency.
487
+ other
488
+ The other frequency.
489
+
490
+ Raises
491
+ ------
492
+ ValueError
493
+ If the intersecting frequency cannot be inferred.
494
+ """
495
+ freq = pd.tseries.frequencies.to_offset(freq) if isinstance(freq, str) else freq
496
+ other = pd.tseries.frequencies.to_offset(other) if isinstance(other, str) else other
497
+
498
+ if freq == other:
499
+ return freq
500
+
501
+ if isinstance(freq, int):
502
+ # e.g. (4, 1), (24, 3)
503
+ n_freq, n_other = freq, other
504
+ elif freq.base == other.base:
505
+ # e.g. (4W-MON, W-MON), (24h, 3h); frequency with the same base frequency
506
+ n_freq, n_other = freq.n, other.n
507
+ else:
508
+ try:
509
+ # e.g. (4D, 2h), (24h, 3min); only frequency with constant / fixed period
510
+ n_freq, n_other = freq.nanos, other.nanos
511
+ except ValueError as exc:
512
+ # e.g. (W-MON, MS, ...); frequencies with non-fixed period
513
+ raise_log(
514
+ ValueError(
515
+ f"Cannot find intersecting frequency between ({freq}, {other}): {exc}"
516
+ ),
517
+ )
518
+ return freq * (math.lcm(n_freq, n_other) // n_freq)
519
+
520
+
521
+ def generate_index(
522
+ start: pd.Timestamp | str | int | None = None,
523
+ end: pd.Timestamp | str | int | None = None,
524
+ length: int | None = None,
525
+ freq: str | int | pd.DateOffset | None = None,
526
+ name: str | None = None,
527
+ ) -> TimeIndex:
528
+ """Returns an index with a given start point and length. Either a pandas DatetimeIndex with given frequency
529
+ or a pandas RangeIndex. The index starts at
530
+
531
+ Parameters
532
+ ----------
533
+ start
534
+ The start of the returned index. If a pandas Timestamp or a date string is passed, the index will be a pandas
535
+ DatetimeIndex. If an integer is passed, the index will be a pandas RangeIndex index. Works only with
536
+ either `length` or `end`.
537
+ end
538
+ Optionally, the end of the returned index. Works only with either `start` or `length`. If `start` is
539
+ set, `end` must be of same type as `start`. Else, it can be either a pandas Timestamp or an integer.
540
+ length
541
+ Optionally, the length of the returned index. Works only with either `start` or `end`.
542
+ freq
543
+ The time difference between two adjacent entries in the returned index. In case `start` is a timestamp,
544
+ a DateOffset alias is expected; see
545
+ `docs <https://pandas.pydata.org/pandas-docs/stable/user_guide/TimeSeries.html#dateoffset-objects>`__.
546
+ By default, "D" (daily) is used.
547
+ If `start` is an integer, `freq` will be interpreted as the step size in the underlying RangeIndex.
548
+ The freq is optional for generating an integer index (if not specified, 1 is used).
549
+ name
550
+ Optionally, an index name.
551
+ """
552
+ constructors = [
553
+ arg_name
554
+ for arg, arg_name in zip([start, end, length], ["start", "end", "length"])
555
+ if arg is not None
556
+ ]
557
+ if len(constructors) != 2:
558
+ raise_log(
559
+ ValueError(
560
+ "index can only be generated with exactly two of the following parameters: "
561
+ "[`start`, `end`, `length`]. Observed parameters: {constructors}. For generating "
562
+ "an index with `end` and `length` consider setting `start` to None."
563
+ ),
564
+ )
565
+
566
+ start = pd.Timestamp(start) if isinstance(start, str) else start
567
+ end = pd.Timestamp(end) if isinstance(end, str) else end
568
+
569
+ if end is not None and start is not None and type(start) is not type(end):
570
+ raise_log(
571
+ ValueError(
572
+ "index generation with `start` and `end` requires equal object types of `start` and `end`."
573
+ ),
574
+ )
575
+
576
+ if isinstance(start, pd.Timestamp) or isinstance(end, pd.Timestamp):
577
+ freq = "D" if freq is None else freq
578
+ freq = pd.tseries.frequencies.to_offset(freq) if isinstance(freq, str) else freq
579
+
580
+ # performance notes: rolling a timestamp is only costly if the timestamp does not intersect
581
+ # with the offset (frequency)
582
+ if start is not None:
583
+ # adjust `start` so that it intersects with `freq`
584
+ start = freq.rollforward(start) if freq.n >= 0 else freq.rollback(start)
585
+ if end is not None:
586
+ # adjust `end` so that it intersects with `freq`
587
+ end = freq.rollback(end) if freq.n >= 0 else freq.rollforward(end)
588
+
589
+ index = pd.date_range(
590
+ start=start,
591
+ end=end,
592
+ periods=length,
593
+ freq=freq,
594
+ name=name,
595
+ )
596
+ else: # int
597
+ step = 1 if freq is None else freq
598
+ if start is None:
599
+ start_ = end - step * length + step
600
+ else:
601
+ start_ = start
602
+
603
+ if end is None:
604
+ end_ = start + step * length
605
+ else:
606
+ # make end inclusive
607
+ end_ = end + 1 if step >= 0 else end - 1
608
+
609
+ index = pd.RangeIndex(
610
+ start=start_,
611
+ stop=end_,
612
+ step=step,
613
+ name=name,
614
+ )
615
+ return index
616
+
617
+
618
+ def expand_arr(arr: np.ndarray, ndim: int):
619
+ """Expands a np.ndarray to `ndim` dimensions (if not already satisfied)."""
620
+ shape = arr.shape
621
+ if len(shape) != ndim:
622
+ arr = arr.reshape(shape + tuple(1 for _ in range(ndim - len(shape))))
623
+ return arr
624
+
625
+
626
+ def sample_from_quantiles(
627
+ vals: np.ndarray,
628
+ quantiles: np.ndarray,
629
+ num_samples: int,
630
+ ):
631
+ """Generates `num_samples` samples from quantile predictions using linear interpolation. The generated samples
632
+ should have quantile values close to the quantile predictions. For the lowest and highest quantiles, the lowest
633
+ and highest quantile predictions are repeated.
634
+
635
+ Parameters
636
+ ----------
637
+ vals
638
+ A numpy array of quantile predictions/values. Either an array with two dimensions
639
+ (n times, n components * n quantiles), or with three dimensions (n times, n components, n quantiles).
640
+ In the two-dimensional case, the order is first by ascending column, then by ascending quantile value
641
+ `(comp_0_q_0, comp_0_q_1, ... comp_n_q_m)`
642
+ quantiles
643
+ A numpy array of quantiles.
644
+ num_samples
645
+ The number of samples to generate.
646
+ """
647
+ if not 2 <= vals.ndim <= 3:
648
+ raise_log(
649
+ ValueError(
650
+ "`vals` must have either two dimensions with `(n times, n components * n quantiles)` or three "
651
+ "dimensions with shape `(n times, n components, n quantiles)`"
652
+ )
653
+ )
654
+ n_time_steps = len(vals)
655
+ n_quantiles = len(quantiles)
656
+ if vals.ndim == 2:
657
+ if vals.shape[1] % n_quantiles > 0:
658
+ raise_log(
659
+ ValueError(
660
+ "`vals` with two dimension must have shape `(n times, n components * n quantiles)`."
661
+ )
662
+ )
663
+ vals = vals.reshape((n_time_steps, -1, n_quantiles))
664
+ elif vals.ndim == 3 and vals.shape[2] != n_quantiles:
665
+ raise_log(
666
+ ValueError(
667
+ "`vals` with three dimension must have shape `(n times, n components, n quantiles)`."
668
+ )
669
+ )
670
+ n_columns = vals.shape[1]
671
+
672
+ # Generate uniform random samples
673
+ random_samples = np.random.uniform(0, 1, (n_time_steps, n_columns, num_samples))
674
+ # Find the indices of the quantiles just below and above the random samples
675
+ lower_indices = np.searchsorted(quantiles, random_samples, side="right") - 1
676
+ upper_indices = lower_indices + 1
677
+
678
+ # Handle edge cases
679
+ lower_indices = np.clip(lower_indices, 0, n_quantiles - 1)
680
+ upper_indices = np.clip(upper_indices, 0, n_quantiles - 1)
681
+
682
+ # Gather the corresponding quantile values and vals values
683
+ q_lower = quantiles[lower_indices]
684
+ q_upper = quantiles[upper_indices]
685
+ z_lower = np.take_along_axis(vals, lower_indices, axis=2)
686
+ z_upper = np.take_along_axis(vals, upper_indices, axis=2)
687
+
688
+ y = z_lower
689
+ # Linear interpolation
690
+ mask = q_lower != q_upper
691
+ y[mask] = z_lower[mask] + (z_upper[mask] - z_lower[mask]) * (
692
+ random_samples[mask] - q_lower[mask]
693
+ ) / (q_upper[mask] - q_lower[mask])
694
+ return y
695
+
696
+
697
+ def random_method(decorated: Callable[..., T]) -> Callable[..., T]:
698
+ """Decorator usable on any method within a class that will provide a random context.
699
+
700
+ The decorator will store a `_random_instance` property on the object in order to persist successive calls to the
701
+ RNG.
702
+
703
+ This is the equivalent to `darts.utils.torch.random_method` but for non-torch models.
704
+
705
+ Parameters
706
+ ----------
707
+ decorated
708
+ A method to be run in an isolated torch random context.
709
+ """
710
+ from sklearn.utils import check_random_state
711
+
712
+ # check that @random_method has been applied to a method.
713
+ if not _is_method(decorated):
714
+ raise_log(ValueError("@random_method can only be used on methods."))
715
+
716
+ @wraps(decorated)
717
+ def decorator(self, *args, **kwargs):
718
+ store_instance = True
719
+ random_instance = None
720
+ if "random_state" in kwargs.keys() and kwargs["random_state"] is not None:
721
+ # get random state from model constructor or `predict()`
722
+ random_instance = check_random_state(kwargs["random_state"]).get_state()
723
+ if hasattr(self, "_random_instance"):
724
+ # do not store random instance when called from `predict()`
725
+ store_instance = False
726
+ elif not hasattr(self, "_random_instance"):
727
+ # get random state for first time from other method
728
+ random_instance = check_random_state(
729
+ np.random.randint(0, high=MAX_NUMPY_SEED_VALUE)
730
+ ).get_state()
731
+
732
+ # if no random instance is provided, use the one stored in the class
733
+ if random_instance is None:
734
+ random_instance = self._random_instance
735
+
736
+ if store_instance:
737
+ self._random_instance = random_instance
738
+
739
+ # handle the randomness
740
+ np.random.set_state(random_instance)
741
+ result = decorated(self, *args, **kwargs)
742
+
743
+ # update the random state after the function call
744
+ if store_instance:
745
+ self._random_instance = np.random.get_state()
746
+ return result
747
+
748
+ return decorator
749
+
750
+
751
+ class ModelType(Enum):
752
+ FORECASTING_REGRESSOR = 0
753
+ FORECASTING_CLASSIFIER = 1
754
+
755
+
756
+ def dataframe_col_to_time_index(
757
+ df: DataFrame,
758
+ time_col: str,
759
+ ) -> pd.Index | pd.DatetimeIndex:
760
+ """Convert a dataframe column to a pandas Index or DatetimeIndex.
761
+
762
+ Parameters
763
+ ----------
764
+ df
765
+ The dataframe containing the time column.
766
+ time_col
767
+ The name of the time column.
768
+ """
769
+ if time_col not in df.columns:
770
+ raise_log(AttributeError(f"time_col='{time_col}' is not present."))
771
+
772
+ time_col_vals = df.get_column(time_col)
773
+
774
+ if time_col_vals.dtype == nw.String:
775
+ # Try to convert to integers if needed
776
+ with contextlib.suppress(Exception):
777
+ time_col_vals = time_col_vals.cast(nw.Int64)
778
+
779
+ if time_col_vals.dtype.is_integer():
780
+ # Temporarily use an integer `pd.Index` to sort the values; later replaced with
781
+ # a `pd.RangeIndex` in `__init__()`
782
+ time_index = pd.Index(time_col_vals)
783
+
784
+ elif isinstance(time_col_vals.dtype, nw.String):
785
+ # The integer conversion failed; try datetimes
786
+ try:
787
+ time_index = pd.DatetimeIndex(time_col_vals)
788
+ except ValueError:
789
+ raise_log(
790
+ AttributeError(
791
+ "'time_col' is of 'String' dtype but doesn't contain valid timestamps"
792
+ )
793
+ )
794
+ elif isinstance(time_col_vals.dtype, nw.Datetime):
795
+ # force time index to be timezone naive, as polars converts to UTC
796
+ time_zone = time_col_vals.dtype.time_zone
797
+ if time_zone is not None:
798
+ logger.warning(
799
+ "The provided DatetimeIndex was associated with a timezone (tz), which is currently not "
800
+ "supported. To avoid unexpected behaviour, the tz information was removed. Consider calling "
801
+ f"`ts.time_index.tz_localize({time_zone})` when exporting the results."
802
+ "To plot the series with the right time steps, consider setting the matplotlib.pyplot "
803
+ "`rcParams['timezone']` parameter to automatically convert the time axis back to the "
804
+ "original timezone."
805
+ )
806
+ time_col_vals = time_col_vals.dt.replace_time_zone(None)
807
+ time_index = pd.DatetimeIndex(time_col_vals)
808
+ elif isinstance(time_col_vals.dtype, nw.Date):
809
+ time_index = pd.DatetimeIndex(time_col_vals)
810
+ else:
811
+ raise_log(
812
+ AttributeError(
813
+ "Invalid type of `time_col`: it needs to be of either 'String', 'Datetime' or 'Int' dtype."
814
+ )
815
+ )
816
+ if not time_index.name:
817
+ time_index.name = time_col
818
+ return time_index
819
+
820
+
821
+ def _maybe_cast_array_dtype(vals: np.ndarray, dtype):
822
+ """Cast an array to `dtype` if it does not yet have the correct data type."""
823
+ if vals.dtype != dtype:
824
+ vals = vals.astype(dtype)
825
+ return vals