-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtime_series_eda.py
More file actions
414 lines (376 loc) · 12.6 KB
/
Copy pathtime_series_eda.py
File metadata and controls
414 lines (376 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
from typing import List, Optional, Union
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from pandas.plotting import autocorrelation_plot
from statsmodels.graphics.tsaplots import plot_pacf
from statsmodels.tsa.seasonal import MSTL
from time_constants import (
DAYS_PER_MONTH,
DAYS_PER_WEEK,
FIFTEEN_MINUTES_PER_HOUR,
HOURS_PER_DAY,
)
# Define the settings for high-quality plots
plot_settings = {
"figure.figsize": (16, 8), # Figure size
"font.size": 15, # Font size
"font.family": "serif", # Font family
"lines.linewidth": 3, # Line width
"axes.labelsize": 16, # Label size
"axes.titlesize": 18, # Title size
"xtick.labelsize": 14, # X-tick label size
"ytick.labelsize": 14, # Y-tick label size
"legend.fontsize": 14, # Legend font size
"axes.grid": True, # Show grid
"savefig.dpi": 300, # DPI for saving figures
"savefig.format": "png", # Format for saving figures
"savefig.bbox": "tight", # Bounding box for saving figures
"savefig.pad_inches": 0.1, # Padding for saving figures
}
plt.style.use("dark_background")
# Apply the settings globally
plt.rcParams.update(plot_settings)
class TimeSeriesEDA:
"""
Class for performing Exploratory Data Analysis (EDA) on time series data.
"""
@staticmethod
def plot_time_series(
y: Union[pd.Series, list[pd.Series]],
title: str,
label: Union[str, list[str]] = "",
color: Union[str, list[str]] = "blue",
savefig_name: Optional[str] = None,
) -> None:
"""
Plots the time series data.
Parameters
----------
y : pd.Series
Time series data.
"""
# If y or label or color is list, ensure that they are all lists of the same length
if (
isinstance(y, list)
and isinstance(label, list)
and isinstance(color, list)
):
if len(y) != len(label) or len(y) != len(color):
raise ValueError(
"If y, label, and color are lists, they must all have the same length"
)
# If y or label or color is not a list, convert it to a list
elif (
not isinstance(y, list)
and not isinstance(label, list)
and not isinstance(color, list)
):
y = [y]
label = [label]
color = [color]
else:
raise TypeError(
"If y, label, and color are lists, they must all have the same length"
)
plt.close("all")
plt.figure()
for y_, label_, color_ in zip(y, label, color):
plt.plot(y_, label=label_, color=color_)
plt.legend(loc="best", fontsize=12)
plt.title(title)
plt.xlabel("Time")
plt.ylabel("Load")
if savefig_name is not None:
plt.savefig(savefig_name)
else:
plt.show()
@staticmethod
def plot_seasonal_decomposition(
y: pd.Series,
seasonalities: Optional[List[int]] = None,
savefig_name: Optional[str] = None,
) -> None:
"""
Plots the seasonal decomposition of the time series data using STL.
Parameters
----------
y : pd.Series
Time series data.
seasonalities : List[int], optional
Seasonalities to consider for decomposition. Default is [96, 96*7, 96*30].
"""
if seasonalities is None:
seasonalities = [
FIFTEEN_MINUTES_PER_HOUR * HOURS_PER_DAY, # 1 day
FIFTEEN_MINUTES_PER_HOUR
* HOURS_PER_DAY
* DAYS_PER_WEEK, # 1 week
FIFTEEN_MINUTES_PER_HOUR
* HOURS_PER_DAY
* DAYS_PER_MONTH, # 1 month
]
if isinstance(seasonalities, int):
seasonalities = [seasonalities]
mstl = MSTL(y, periods=seasonalities)
result = mstl.fit()
plt.close("all")
plt.figure(figsize=(16, 12))
result.plot()
if savefig_name is not None:
plt.savefig(savefig_name)
else:
plt.show()
@staticmethod
def plot_acf_pacf(
y: pd.Series, lags: int, savefig_name: Optional[str] = None
) -> None:
"""
Plots the Autocorrelation Function (ACF) and Partial Autocorrelation Function (PACF).
Parameters
----------
y : pd.Series
Time series data.
lags : int
Number of lags to consider.
"""
plt.close("all")
plt.figure()
plt.subplot(211)
autocorrelation_plot(y)
plt.title("Autocorrelation Function (ACF)")
plt.subplot(212)
plot_pacf(y, lags=lags)
plt.title("Partial Autocorrelation Function (PACF)")
if savefig_name is not None:
plt.savefig(savefig_name)
else:
plt.show()
@staticmethod
def plot_distribution(
y: pd.Series, savefig_name: Optional[str] = None
) -> None:
"""
Plots the distribution of the time series data.
Parameters
----------
y : pd.Series
Time series data.
"""
plt.close("all")
plt.figure()
sns.histplot(y, kde=True, edgecolor="black")
plt.title("Distribution Plot")
plt.xlabel("Value")
plt.ylabel("Frequency")
if savefig_name is not None:
plt.savefig(savefig_name)
else:
plt.show()
@staticmethod
def plot_patterns(
df: pd.DataFrame,
target_variable: str,
x_variable: str,
title: str,
savefig_name: Optional[str] = None,
) -> None:
"""
Plots the patterns of the time series data.
Parameters
----------
df : pd.DataFrame
DataFrame containing the time series data.
target_variable : str
The target variable to be plotted.
x_variable : str
The variable to be plotted on the x-axis.
title : str
The title of the plot.
"""
plt.close("all")
plt.figure()
sns.boxplot(data=df, x=x_variable, y=target_variable)
plt.title(title)
plt.xlabel(x_variable)
plt.ylabel(target_variable)
if savefig_name is not None:
plt.savefig(savefig_name)
else:
plt.show()
@staticmethod
def plot_heatmap(
df: pd.DataFrame,
target_variable: str,
groupby_vars: list,
title: str,
savefig_name: Optional[str] = None,
) -> None:
"""
Plots a heatmap of the time series data.
Parameters
----------
df : pd.DataFrame
DataFrame containing the time series data.
target_variable : str
The target variable to be plotted.
groupby_vars : list
List of variables to group by for the heatmap.
title : str
The title of the heatmap.
"""
load_data = df.groupby(groupby_vars)[target_variable].mean().unstack()
plt.close("all")
plt.figure()
sns.heatmap(
load_data,
cmap="coolwarm",
annot=True,
fmt=".0f",
linewidths=1,
linecolor="black",
)
plt.title(title)
plt.xlabel(groupby_vars[1])
plt.ylabel(groupby_vars[0])
if savefig_name is not None:
plt.savefig(savefig_name)
else:
plt.show()
@staticmethod
def plot_rolling_stats(y: pd.Series, window: Optional[int]) -> None:
if window is None:
window = FIFTEEN_MINUTES_PER_HOUR * HOURS_PER_DAY # 1 day
y_mean = y.rolling(window=window).mean()
y_median = y.rolling(window=window).median()
y_max = y.rolling(window=window).max()
y_min = y.rolling(window=window).min()
# Plot basic statistics
TimeSeriesEDA.plot_time_series(
[y_mean, y_median, y_max, y_min],
label=[
f"Rolling Mean ({window})",
f"Rolling Median ({window})",
f"Rolling Max ({window})",
f"Rolling Min ({window})",
],
color=["blue", "red", "green", "orange"],
title="Rolling Statistics",
savefig_name=f"figures/eda/rolling_statistics_{window}.png",
)
@staticmethod
def perform_eda(
df: pd.DataFrame,
target_variable: str,
seasonalities: Optional[list[int]] = None,
lags: int = FIFTEEN_MINUTES_PER_HOUR
* HOURS_PER_DAY
* DAYS_PER_WEEK, # 1 week
) -> None:
"""
Performs Exploratory Data Analysis (EDA) on the time series data.
Parameters
----------
df : pd.DataFrame
DataFrame containing the time series data.
target_variable : str
The target variable to be analyzed.
seasonalities : list[int], optional
Seasonalities for seasonal decomposition. Default is None, and is handled in the plot_seasonal_decomposition method.
lags : int, optional
Number of lags to consider for ACF and PACF plots. Default is equivalent of 1 week.
"""
# Ensure that we do not modify the original dataframe
df = df.copy()
# Ensure that the index is a datetime object
df.index = pd.to_datetime(df.index)
# Extract necessary information
df["hour"] = df.index.hour.values
df["day"] = df.index.dayofweek
df["month"] = df.index.month
# Call the plotting methods
y = df[target_variable]
TimeSeriesEDA.plot_time_series(
y,
title="Load Time Series",
savefig_name="figures/eda/load_time_series.png",
)
# Plot basic statistics
TimeSeriesEDA.plot_rolling_stats(
y, window=FIFTEEN_MINUTES_PER_HOUR * HOURS_PER_DAY
) # 1 day
TimeSeriesEDA.plot_rolling_stats(
y, window=FIFTEEN_MINUTES_PER_HOUR * HOURS_PER_DAY * DAYS_PER_WEEK
) # 1 week
TimeSeriesEDA.plot_rolling_stats(
y, window=FIFTEEN_MINUTES_PER_HOUR * HOURS_PER_DAY * DAYS_PER_MONTH
) # 1 month
# Plot seasonal decomposition, ACF, PACF
"""
TimeSeriesEDA.plot_seasonal_decomposition(
y,
seasonalities=seasonalities,
savefig_name="figures/eda/seasonal_decomposition.png",
)
TimeSeriesEDA.plot_acf_pacf(
y, lags, savefig_name="figures/eda/acf_pacf.png"
)
"""
TimeSeriesEDA.plot_distribution(
y, savefig_name="figures/eda/distribution.png"
)
# Plot load distributions conditional on hour, day, and month
for hour in df["hour"].unique():
subset = df[df["hour"] == hour]
TimeSeriesEDA.plot_distribution(
subset[target_variable],
savefig_name=f"figures/eda/distribution_hour_{hour}.png",
)
for day in df["day"].unique():
subset = df[df["day"] == day]
TimeSeriesEDA.plot_distribution(
subset[target_variable],
savefig_name=f"figures/eda/distribution_day_{day}.png",
)
for month in df["month"].unique():
subset = df[df["month"] == month]
TimeSeriesEDA.plot_distribution(
subset[target_variable],
savefig_name=f"figures/eda/distribution_month_{month}.png",
)
# Plot load patterns conditional on hour, day, and month
TimeSeriesEDA.plot_patterns(
df,
target_variable,
"hour",
"Hourly Load Patterns",
savefig_name="figures/eda/hourly_load_patterns.png",
)
TimeSeriesEDA.plot_patterns(
df,
target_variable,
"day",
"Daily Load Patterns",
savefig_name="figures/eda/daily_load_patterns.png",
)
TimeSeriesEDA.plot_patterns(
df,
target_variable,
"month",
"Monthly Load Patterns",
savefig_name="figures/eda/monthly_load_patterns.png",
)
TimeSeriesEDA.plot_heatmap(
df,
target_variable,
["day", "hour"],
"Weekly Load Heatmap",
savefig_name="figures/eda/weekly_load_heatmap.png",
)
TimeSeriesEDA.plot_heatmap(
df,
target_variable,
["month", "hour"],
"Annual Load Heatmap",
savefig_name="figures/eda/annual_load_heatmap.png",
)