-
Notifications
You must be signed in to change notification settings - Fork 2
/
Opschaler.py
294 lines (211 loc) · 8.35 KB
/
Opschaler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# coding: utf-8
# In[1]:
import numpy as np
import glob
import pandas as pd
from tqdm import tqdm
import matplotlib.pyplot as plt
import seaborn as sns
import time
# In[2]:
def test1(x):
return x
def test2(x):
y = test1(x)+test1(x)
return y
# def datetime_layout(dwelling_id, y, y2=None, y3=None, y4=None):
# def layout():
# plt.xticks(rotation=45)
# plt.grid()
# plt.tight_layout()
# x = df[datetime]
# plt.subplot(3,2,1)
# plt.plot(x, df[y], '-', color='r', linewidth=0.3)
# #plt.xlabel('Date [-]')
# plt.ylabel('Global Radiation [J/m$^2$]')
# datetime_layout()
# plt.subplot(3,2,2)
# plt.plot(x, data['T'], '-', color='r', linewidth=0.3)
# #plt.xlabel('Date [-]')
# plt.ylabel('Temperature [°C]')
# datetime_layout()
# plt.subplot(3,2,3)
# plt.plot(x, data['ePower'], '-', color='r', linewidth=0.3)
# #plt.xlabel('Date [-]')
# plt.ylabel('ePower [kWh]')
# datetime_layout()
# plt.subplot(3,2,4)
# plt.plot(x, data['gasPower'], '-', color='r', linewidth=0.3)
# #plt.xlabel('Date [-]')
# plt.ylabel('gasPower [m$^3$]')
# datetime_layout()
def dummies(df):
df['T-1'] = df['T'].shift(1)
#Creating hour of the day and day of the week variables
df['hour'] = df.index.hour #creating a column that takes the hour of the day from the DateTime index
df['dayofweek'] = df.index.dayofweek #same but with the day of the week, obviously
#Creating dummyvariables out of the columns above (meaning making a ones-matrix from the columns)
add_columns = ['hour', 'dayofweek'] #making variable for the columns
df[add_columns] = df[add_columns].astype('category') #in order to make dummy variables, they need to be of the type category
df = pd.get_dummies(df, columns=add_columns)
return df
def read_(select, sample_rate='_hour',processed=True):
path = '//datc//opschaler//combined_gas_smart_weather_dfs//'
folder_ = 'processed//'
if processed == False:
folder_ = 'unprocessed//'
if sample_rate == '10s':
sample_rate = '_10s'
complete_path = path+folder_+select+sample_rate+".csv"
df = pd.read_csv(complete_path,sep='\t',index_col=None)
return df, select, complete_path, sample_rate, processed
def reduce_memory(df):
"""
Reduces memory footprint of the input dataframe.
Changes float64 columns to float32 dtype.
"""
columns = df.columns
memory_before = df.memory_usage(deep=False).sum() / 2**30 # convert bytes to GB
for column in tqdm(columns):
if df[column].dtype == 'float64':
df[column] = df[column].astype('float32')
memory_after = df.memory_usage(deep=False).sum() / 2**30 # convert bytes to GB
print('Memory uasge reduced from %.3f GB to %.3f GB' % (memory_before, memory_after))
return df
def dwel_path_id(sample_rate, folder, combined):
"""
Reads in the file paths and dwelling id's of the combined smartmeter data.
:return: file_paths, dwelling_ids, both as lists.
"""
path = '//datc//opschaler//combined_gas_smart_weather_dfs//'
map_ = 'processed//'
subscript = '_hour'
combined_ = 'P*'
if sample_rate == '10s':
subscript = '_10s'
if folder == 'unprocessed':
map_ = 'unprocessed//'
if combined == 'yes':
combined_ = 'all_dwellings_combined'
complete_path = path+map_+combined_+subscript+".csv"
file_paths = np.array(glob.glob(complete_path))
print('complete_path: '+complete_path)
print('Detected %s smartmeter_data files.' % len(file_paths))
dwelling_ids = np.array(list((map(lambda x: x[-20:-9], file_paths))))
if sample_rate == '10s':
dwelling_ids = np.array(list((map(lambda x: x[-19:-8], file_paths)))) # 10s ids slicing
if combined == 'yes':
dwelling_ids = 'Used all dwellings to make this df'
return file_paths, dwelling_ids
def clean_datetime(df):
"""
Input should be a df with a column called 'datetime'.
This function checks wether a row in the df.datetime column can be parsed to a pandas datetime object,
by trying pd.to_datetime() on it.
If it fails it will replace that row with np.nan().
Finally this function will return the df with the NaN rows dropped.
It only drops the row if the datetime column contains a NaN.
"""
for i in range(len(df)):
try:
pd.to_datetime(df.datetime[i])
except ValueError:
print('-----')
print('ValueError at index = %s' % i)
print(df.datetime[i])
df.datetime = df.datetime.replace(df.datetime[i], np.nan)
df = df.dropna(subset = ['datetime'])
return df
def clean_prepare_smart_gas(file_path):
"""
Input is a dwelling_id.csv file.
Output are cleaned & prepared dataframes (smart, gas).
Return: smart, gas
"""
df = pd.read_csv(file_path, delimiter=';', header=0)
smart = df.iloc[:,:7]
gas = df.iloc[:,7:]
smart = smart.rename(index=str,columns={"Timestamp":"datetime"})
gas = gas.rename(index=str,columns={"gasTimestamp":"datetime"})
smart = clean_datetime(smart)
gas = clean_datetime(gas)
smart['datetime'] = pd.to_datetime(smart['datetime'])
gas['datetime'] = pd.to_datetime(gas['datetime'])
smart = smart.set_index(['datetime'])
gas = gas.set_index(['datetime'])
return smart, gas
def resample_smart_gas(smart, gas):
"""
Resamples the (smart, gas) dfs to 10s.
Also calculates gasPower.
Returns (smart_resampled, gas_resampled)
"""
smart_resampled = smart.resample('10s').mean()
gas_resampled = gas.resample('H').mean()
# replace 0s with NaNs
gas_resampled = gas_resampled.resample('10s').interpolate(method='time')
gas_resampled['gasPower'] = gas_resampled['gasMeter'].diff()
return smart_resampled, gas_resampled
def merge_smart_gas_weather(smart_resampled, gas_resampled, weather):
"""
Merges the dataframes, outputs one df.
"""
df = pd.merge(smart_resampled, gas_resampled, left_index=True, right_index=True)
df = pd.merge(df, weather, left_index=True, right_index=True)
return df
def save_df(df, dwelling_id):
dir = '//datc//opschaler//combined_dfs_gas_smart_weather//'
df.to_csv(dir+dwelling_id+'.csv', sep='\t', index=True)
print('Saved %s' % dwelling_id)
# def nan_table(sample_rate):
# file_paths, dwelling_ids = dwelling_data_paths(sample_rate)
# dfs_nan_table = []
# for i, path in enumerate(paths):
# dwelling_id = dwelling_ids[i]
# df = read_combined_df(path, dwelling_id)
# dfs_nan_table.append(df)
# final_df = pd.concat(dfs_nan_table)
# return final_df
def corr_df(dwelling_id, corr_dim):
plt.style.use('default')
df = pd.read_csv("/datc/opschaler/combined_gas_smart_weather_dfs/processed/"+dwelling_id+"_hour.csv",header=0,delimiter="\t",parse_dates = ['datetime'])
df = df.set_index(['datetime'])
if corr_dim == '1h':
df = df
if corr_dim == '3h':
df = df.resample('3H').mean()
if corr_dim == '6h':
df = df.resample('6H').mean()
if corr_dim == '12h':
df = df.resample('12H').mean()
if corr_dim == '1d':
df = df.resample('1D').mean()
if corr_dim == '1w':
df = df.resample('1W').mean()
rdf = df[df['T'] < 16]
corr = rdf.corr()
mask = np.zeros_like(corr)
mask[np.triu_indices_from(mask)] = True
fig, ax = plt.subplots(figsize=(25,25))
sns.heatmap(corr, mask=mask, square=False, cmap='RdYlGn', annot=True, ax=ax,
cbar_kws={'label':'Pearson correlation coefficient [-]'})
plt.title('Correlation Matrix')
plt.xticks(rotation=90)
plt.yticks(rotation=0)
return plt.show()
def dwel_len(dwelling_id):
"""
Get the total amount of days of an unprocessed dwelling_id.
"""
dir = '//datc//opschaler//combined_gas_smart_weather_dfs//unprocessed//'
df = pd.read_csv(dir+dwelling_id+'_10s.csv', delimiter='\t', parse_dates=['datetime'])
df = df['datetime'] # only keep the datetime column
start_date = df.iloc[0]
stop_date = df.iloc[-1]
del df # Free up memory
recorded_days = (stop_date - start_date).days # total amount of recorded days
return recorded_days, start_date, stop_date
#def read_in
#def read_in_10s
#def read_in_h
# In[ ]: