-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutilities.py
211 lines (139 loc) · 5.95 KB
/
utilities.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from sklearn.metrics import mean_absolute_error as MAE
def median_filter(df, varname = None, window=24, std=3):
"""
A simple median filter, removes (i.e. replace by np.nan) observations that exceed N (default = 3)
tandard deviation from the median over window of length P (default = 24) centered around
each observation.
Parameters
----------
df : pandas.DataFrame
The pandas.DataFrame containing the column to filter.
varname : string
Column to filter in the pandas.DataFrame. No default.
window : integer
Size of the window around each observation for the calculation
of the median and std. Default is 24 (time-steps).
std : integer
Threshold for the number of std around the median to replace
by `np.nan`. Default is 3 (greater / less or equal).
Returns
-------
dfc : pandas.Dataframe
A copy of the pandas.DataFrame `df` with the new, filtered column `varname`
"""
dfc = df.loc[:,[varname]]
dfc['median']= dfc[varname].rolling(window, center=True).median()
dfc['std'] = dfc[varname].rolling(window, center=True).std()
dfc.loc[dfc.loc[:,varname] >= dfc['median']+std*dfc['std'], varname] = np.nan
dfc.loc[dfc.loc[:,varname] <= dfc['median']-std*dfc['std'], varname] = np.nan
return dfc.loc[:, varname]
def prepare_data(data, test_time='2017-01-01'):
"""
prepare the data for ingestion by fbprophet:
see: https://facebook.github.io/prophet/docs/quick_start.html
1) divide in training and test set, using the `year` parameter (int)
2) reset the index and rename the `datetime` column to `ds`
returns the training and test dataframes
Parameters
----------
data : pandas.DataFrame
The dataframe to prepare, needs to have a datetime index
year: integer
The year separating the training set and the test set (includes the year)
Returns
-------
data_train : pandas.DataFrame
The training set, formatted for fbprophet.
data_test : pandas.Dataframe
The test set, formatted for fbprophet.
"""
data_train = data.loc[:test_time,:]
data_test = data.loc[test_time:,:]
data_train.reset_index(inplace=True)
data_test.reset_index(inplace=True)
data_train = data_train.rename({'datetime':'ds'}, axis=1)
data_test = data_test.rename({'datetime':'ds'}, axis=1)
return data_train, data_test
def make_verif(forecast, data_train, data_test):
"""
Put together the forecast (coming from fbprophet)
and the overved data, and set the index to be a proper datetime index,
for plotting
Parameters
----------
forecast : pandas.DataFrame
The pandas.DataFrame coming from the `forecast` method of a fbprophet
model.
data_train : pandas.DataFrame
The training set, pandas.DataFrame
data_test : pandas.DataFrame
The training set, pandas.DataFrame
Returns
-------
forecast :
The forecast DataFrane including the original observed data.
"""
forecast.index = pd.to_datetime(forecast.ds)
data_train.index = pd.to_datetime(data_train.ds)
data_test.index = pd.to_datetime(data_test.ds)
data = pd.concat([data_train, data_test], axis=0)
forecast['y'] = data['y'].to_list()
return forecast
def plot_verif(verif, test_time='2017-01-01'):
"""
plots the forecasts and observed data, the `year` argument is used to visualise
the division between the training and test sets.
Parameters
----------
verif : pandas.DataFrame
The `verif` DataFrame coming from the `make_verif` function in this package
year : integer
The year used to separate the training and test set. Default 2017
Returns
-------
f : matplotlib Figure object
"""
f, ax = plt.subplots(figsize=(14, 8))
train = verif.loc[:test_time,:]
ax.plot(train.index, train.y, 'ko', markersize=3)
ax.plot(train.index, train.yhat, color='steelblue', lw=0.5)
ax.fill_between(train.index, train.yhat_lower, train.yhat_upper, color='steelblue', alpha=0.3)
test = verif.loc[test_time:,:]
ax.plot(test.index, test.y, 'ro', markersize=3)
ax.plot(test.index, test.yhat, color='coral', lw=0.5)
ax.fill_between(test.index, test.yhat_lower, test.yhat_upper, color='coral', alpha=0.3)
#ax.axvline(str(year), color='0.8', alpha=0.7)
ax.grid(ls=':', lw=0.5)
ax.set_xlabel("Date", fontsize=15)
ax.set_ylabel("TRU", fontsize=15)
return f
def plot_verif_component(verif, component='rain', year=2017):
"""
plots a specific component of the `verif` DataFrame
Parameters
----------
verif : pandas.DataFrame
The `verif` DataFrame coming from the `make_verif` function in this package.
component : string
The name of the component (i.e. column name) to plot in the `verif` DataFrame.
year : integer
The year used to separate the training and test set. Default 2017
Returns
-------
f : matplotlib Figure object
"""
f, ax = plt.subplots(figsize=(14, 7))
train = verif.loc[:str(year - 1),:]
ax.plot(train.index, train.loc[:,component] * 100, color='0.8', lw=1, ls='-')
ax.fill_between(train.index, train.loc[:, component+'_lower'] * 100, train.loc[:, component+'_upper'] * 100, color='0.8', alpha=0.3)
test = verif.loc[str(year):,:]
ax.plot(test.index, test.loc[:,component] * 100, color='k', lw=1, ls='-')
ax.fill_between(test.index, test.loc[:, component+'_lower'] * 100, test.loc[:, component+'_upper'] * 100, color='0.8', alpha=0.3)
#ax.axvline(str(year), color='k', alpha=0.7)
ax.grid(ls=':', lw=0.5)
return f