-
Notifications
You must be signed in to change notification settings - Fork 0
/
ComEd_DR_Aggregation.py
executable file
·2378 lines (1956 loc) · 106 KB
/
ComEd_DR_Aggregation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 11 12:07:39 2020
@author: lliu2
"""
### setting
import os
import re
import sys
import json
import pandas as pd
import functools
import itertools
import zipfile
import tempfile
import shutil
import pytz
import datetime as dt
from dask.distributed import Client, wait, LocalCluster
import dask.dataframe as dd
import dask
from dask import delayed
from dask import compute
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import matplotlib.patches as mpatches
from getpass import getuser
import numpy as np
from dateutil.tz import tzoffset
from dateutil.relativedelta import relativedelta
import traceback
from IPython.display import HTML
from operator import itemgetter
import pickle
import math
from scipy.stats import gaussian_kde, linregress, norm
from scipy.stats import t as tstats
from scipy import optimize
import statistics as stats
import lmfit
from calendar import monthrange
#import ruptures as rpt
#from ruptures.utils import pairwise
from statsmodels.tsa.statespace.sarimax import SARIMAX
from sklearn.metrics import mean_squared_error
import statsmodels.api as sm
from sklearn.linear_model import LinearRegression
from sklearn.metrics import explained_variance_score
import time
from multiprocessing import Pool
from sklearn.preprocessing import LabelBinarizer
import random
import scipy
from pandas.tseries.offsets import DateOffset
#get_ipython().run_line_magic('matplotlib', 'inline')
#sns.set_style('whitegrid')
#sns.set_context('talk')
plt.style.use('default')
username = getuser()
username
# specify paths
prefix = '/Users/lliu2/Documents/' #'/Users/lliu2/OneDrive - NREL/Documents/'
datadir = os.path.join(prefix,'Project 1 - Energy Analysis/Python/zip codes/ComEd_zipcode_avg_AWS/')
datadir2 = os.path.join(prefix, 'Project 1 - Energy Analysis/Python/zip codes/')
outdir = os.path.join(prefix, 'Project 1 - Energy Analysis/Python/zip codes/DR_heating_cooling/')
# use dir(modulename) to check available attributes for the module
# %%
def linear(x, a0, a1):
return a0 + a1*x
def linearc(x, a0, a1, x0):
return a0 + a1*(x-x0)
def cubic(x, a0, a1, a2, a3):
return a0 + a1*x + a2*(x**2) + a3*(x**3)
def quartic(x, a0, a1, a2, a3, a4):
return a0 + a1*x + a2*(x**2) + a3*(x**3) + a4*(x**4)
def quintic(x, a0, a1, a2, a3, a4, a5):
a1 *= 1e-1; a2 *= 1e-2; a3 *= 1e-3; a4 *= 1e-4; a5 *= 1e-5;
return a0 + a1*x + a2*(x**2) + a3*(x**3) + a4*(x**4) + a5*(x**5)
def logistic(x, L, k, x0, b0):
return L/(1+np.exp(-k*(x-x0)))+b0
def fourier1(t, p, c, a1, b1):
# 2pi/w = p or period or cycle length (e.g. 24-hr)
# if p, cycle = 24hr, then:
# a1, b1 = effects at 24-hr cycle (24/1), larger val = stronger effects
# a2, b2 = effects at 12-hr cycle, (24/2)...
w = 2*np.pi/p # in radian
return c + a1*np.cos(t*w) + b1*np.sin(t*w)
def fourier2(t, p, c, a1, b1, a2, b2):
# 2pi/w = p or period or cycle length (e.g. 24-hr)
# if p, cycle = 24hr, then:
# a1, b1 = effects at 24-hr cycle (24/1), larger val = stronger effects
# a2, b2 = effects at 12-hr cycle, (24/2)...
w = 2*np.pi/p # in radian
# w: 24 hr; 2w: 12 hr
return c + a1*np.cos(t*w) + b1*np.sin(t*w) + a2*np.cos(2*t*w) + b2*np.sin(2*t*w)
def fourier3(t, p, c, a1, b1, a2, b2, a3, b3, k2, k3):
w = 2*np.pi/p # in radian
return c + a1*np.cos(t*w) + b1*np.sin(t*w) + a2*np.cos(k2*t*w) + b2*np.sin(k2*t*w) +\
a3*np.cos(k3*t*w) + b3*np.sin(k3*t*w)
def fourier14(t, p, c, a1, b1, a7, b7, a14, b14):
w = 2*np.pi/p # in radian
# w: 1 week; 7w: 24 hr; 14w: 12 hr
return c + a1*np.cos(t*w) + b1*np.sin(t*w) + a7*np.cos(7*t*w) + b7*np.sin(7*t*w) +\
a14*np.cos(14*t*w) + b14*np.sin(14*t*w)
def fourier_top4(t, p, c, a1, b1, a2, b2, a3, b3, a4, b4, k2, k3, k4):
w = 2*np.pi/p # in radian
# w: 1 year; 2w: half year; 366w: 24hr; 732w: 12 hr
return c + a1*np.cos(t*w)+b1*np.sin(t*w) + a2*np.cos(k2*t*w)+b2*np.sin(k2*t*w) +\
a3*np.cos(k3*t*w)+b3*np.sin(k3*t*w) + a4*np.cos(k4*t*w)+b4*np.sin(k4*t*w)
def fourier_top8(t, p, c, a1, b1, a2, b2, a3, b3, a4, b4,
a5, b5, a6, b6, a7, b7, a8, b8,
k2, k3, k4, k5, k6, k7, k8):
w = 2*np.pi/p # in radian
# w: 1 year; 2w: half year; 366w: 24hr; 732w: 12 hr
return c + a1*np.cos(t*w)+b1*np.sin(t*w) + a2*np.cos(k2*t*w)+b2*np.sin(k2*t*w) +\
a3*np.cos(k3*t*w)+b3*np.sin(k3*t*w) + a4*np.cos(k4*t*w)+b4*np.sin(k4*t*w) +\
a5*np.cos(k5*t*w)+b5*np.sin(k5*t*w) + a6*np.cos(k6*t*w)+b6*np.sin(k6*t*w) +\
a7*np.cos(k7*t*w)+b7*np.sin(k7*t*w) + a8*np.cos(k8*t*w)+b8*np.sin(k8*t*w)
def piecewise_linear(x, x0, b0, mh, mc):
condlist = [x<=x0] # + else
funclist = [mh*(x-x0)+b0, mc*(x-x0)+b0]
return np.where(condlist[0], funclist[0], funclist[1])
def rsq(data,model):
return (np.corrcoef(data,model)[0,1])**2
##############################################################################
def load_pickle(name):
""" Function to load an object from a pickle """
with open(f'{name}.pkl', 'rb') as f:
temp = pickle.load(f)
return temp
def save_pickle(contents, name):
""" Function to save to an object as a pickle """
with open(f'{name}.pkl', 'wb') as output:
pickle.dump(contents, output, pickle.HIGHEST_PROTOCOL)
def load_dill(name):
""" Function to load an object from a dill """
with open(f'{name}.dll', 'rb') as f:
temp = dill.load(f)
return temp
def save_dill(contents, name):
""" Function to save to an object as a dill """
with open(f'{name}.dll', 'wb') as output:
dill.dump(contents, output, dill.HIGHEST_PROTOCOL)
print('Model math and pickle/dill functions ran.')
# %% [1] load data
data_type = 'half_hourly' #<------ hourly or half_hourly
# check if these files exist:
file_status = 1
for C in ['C23', 'C24', 'C25', 'C26']:
file_status = file_status*os.path.exists(os.path.join(datadir,
'ComEd_zipcode_{}_avg_w_temp_{}.parquet'.format(data_type,C)))
# if processed files exist, call directly, else create from AWS queries
if file_status:
# % option (1) - load directly, if file exists
print('DF exists, loading DF directly...')
DF = {}
for C in ['C23', 'C24', 'C25', 'C26']:
DF[C] = pd.read_parquet(os.path.join(datadir,'ComEd_zipcode_{}_avg_w_temp_{}.parquet'.format(data_type,C)),
engine='pyarrow')
else:
# option (2) - create from AWS queried dfs
print('Creating DF from scratch...')
df = pd.read_parquet(os.path.join(datadir,'comed_zipcode_{}_avg_201510-201703.parquet'.format(data_type)),engine='pyarrow')
# break out df into a dictionary
DF = {}
for C in ['C23', 'C24', 'C25', 'C26']:
dfi = df.query('type == @C').reset_index(drop=True)
### missing timestamp 2016-03-31 23:30, fill with 5th order polynomial
dfi = dfi.drop(['type'], axis=1) # remove type
dfi = dfi[dfi['mean']>0] # take only all positive values
dfi = dfi.set_index(['time','zip_code']).unstack(level='zip_code')
IDX = dfi.index.get_level_values(level='time')
IDX = pd.date_range(IDX[0], IDX[-1], freq='0.5H').rename('time')
dfi = dfi.reindex(IDX, fill_value=np.NAN)
dfi = dfi.interpolate(method='time', limit=2, limit_area='inside', axis=0) # fill missing val with 5th order
dfi = dfi.stack().reset_index().sort_values(
by=['zip_code','time']).reset_index(drop=True)
dfi['type'] = C # add type back in
DF[C] = dfi
display(DF['C23'])
df = pd.concat(DF.values(), axis=0).reset_index(drop=True)
# save new df
df.to_parquet(os.path.join(datadir,'comed_zipcode_{}_avg_201510-201703.parquet'.format(data_type)),engine='pyarrow', flavor='spark')
del df # save memory
pref = 'HalfHourly' if data_type == 'half_hourly' else 'Hourly'
HHTemp = pd.read_csv(os.path.join(datadir2,'W{}_temp_by_station_201510-201703.csv'.format(pref)),
parse_dates=['time']).set_index('time')
zip_stn = pd.read_csv(os.path.join(datadir2,'Wzipcode_station_lookup.csv'))
zip_stn = dict(zip(zip_stn['zip_code'],zip_stn['station'].astype(str)))
for C in DF.keys():
print('>>> mapping temp to {}...'.format(C))
### add temp
DF[C]['degC'] = DF[C].set_index([DF[C]['zip_code'].map(zip_stn),
'time']).index.map(HHTemp.unstack().to_dict())
### export as parquets
DF[C].to_parquet(os.path.join(datadir,'ComEd_zipcode_{}_avg_w_temp_{}.parquet'.format(data_type,C)),
engine='pyarrow', flavor='spark')
display(DF['C26'])
def data_set_up(service_type, in_W=True, log_transform=True):
global DF, data_type
ts1 = pd.Timestamp('2015-12-01')
ts2 = pd.Timestamp('2016-12-01')
# filter on timestamps
DF2 = DF[service_type].query('(time>=@ts1)&(time<@ts2)').set_index(
['time','zip_code'])[['mean','degC']].unstack(level='zip_code')
# assign df_temp, y, t
m = 1000 if in_W else 1
multiplier = 2*m if data_type == 'half_hourly' else m
df_temp,df_demand = DF2['degC'],DF2['mean']*multiplier # <--- degC, W
# log transformation
df_demand = np.log(df_demand) if log_transform else df_demand
### get FFT values
ext = '_log' if log_transform else ''
### FFT from shoulder
fft = pd.read_parquet(os.path.join(datadir,'df_zipcode_sorted_FFT_{}{}.parquet'.format(service_type, ext)),
engine='pyarrow').set_index(['type','index'])
fft.columns = fft.columns.astype('int')
fftn = pd.read_parquet(os.path.join(datadir,'df_zipcode_non_HVAC_sorted_FFT_{}{}.parquet'.format(service_type, ext)),
engine='pyarrow').set_index(['type','index'])
fftn.columns = fftn.columns.astype('int')
ffth = pd.read_parquet(os.path.join(datadir,'df_zipcode_heating_sorted_FFT_{}{}.parquet'.format(service_type, ext)),
engine='pyarrow').set_index(['type','index'])
ffth.columns = ffth.columns.astype('int')
fftc = pd.read_parquet(os.path.join(datadir,'df_zipcode_cooling_sorted_FFT_{}.parquet'.format(service_type, ext)),
engine='pyarrow').set_index(['type','index'])
fftc.columns = fftc.columns.astype('int')
print(' data is in [{}]'.format('W(h)' if in_W else 'kW(h)'))
return df_temp, df_demand, fft, fftn, ffth, fftc
def folder_set_up(service_type, fourier_type='42', log_transform=True):
global DF, data_type, outdir
log = 'log' if log_transform else ''
# sub folder for results
outdir_sub = os.path.join(outdir, 'Model{}_{}_{}_{}'.format(fourier_type,log,service_type,data_type))
if not os.path.exists(outdir_sub):
os.mkdir(outdir_sub)
# sub-sub folder for plots
outdir_fig = os.path.join(outdir_sub,'plots')
if not os.path.exists(outdir_fig):
os.mkdir(outdir_fig)
return outdir_sub
print('ran')
# %% model funcs (orig - no time constraint)
def linear_fourier_top4(x, y, t, # data
xh, yh, xc, yc, # domain bounds
mh, bh, mc, bc, # heat/cool lines
b0, b1c, b1s, b2c, b2s, b3c, b3s, b4c, b4s, # fourier 0 HVAC-off reg
bh0, bh1c, bh1s, bh2c, bh2s, bh3c, bh3s, bh4c, bh4s, # fourier heat
bc0, bc1c, bc1s, bc2c, bc2s, bc3c, bc3s, bc4c, bc4s, # fourier cool reg
p, ph, pc, k2, k3, k4, kh2, kh3, kh4, kc2, kc3, kc4, # fourier period and fourier term multiplers
modtype='B'):
# domain-wise regressions
l0 = fourier_top4(t, p, b0, b1c, b1s, b2c, b2s, b3c, b3s, b4c, b4s, k2, k3, k4) # HVAC-off domain
lh = linearc(x, bh, mh, xh)*fourier_top4(t, ph, bh0, bh1c, bh1s, bh2c, bh2s, bh3c, bh3s, bh4c, bh4s, kh2, kh3, kh4) # heat domain
lc = linearc(x, bc, mc, xc)*fourier_top4(t, pc, bc0, bc1c, bc1s, bc2c, bc2s, bc3c, bc3s, bc4c, bc4s, kc2, kc3, kc4) # cool domain
if modtype != 'A':
lh = lh + l0
lc = lc + l0
condlist = [(x<xh) & (y>yh), (x>xc) & (y>yc)] # + else
funclist = [lh, lc, l0]
return np.where(condlist[0], funclist[0],
np.where(condlist[1], funclist[1], funclist[2]))
def HVAC_demands_linear_fourier_top4(x, y, t, tidx, V, log_transform=True, modtype='B'):
Xh = x[(x<V['xh'])&(y>V['yh'])]; Th = t[(x<V['xh'])&(y>V['yh'])];
tidx = np.array(tidx); tidxh = tidx[(x<V['xh'])&(y>V['yh'])];
l0h = fourier_top4(Th, V['p'], V['b0'], V['b1c'], V['b1s'], V['b2c'], V['b2s'],
V['b3c'], V['b3s'],V['b4c'], V['b4s'],
V['k2'], V['k3'], V['k4']) # HVAC-off domain
lh = linearc(Xh, V['bh'], V['mh'], V['xh']) * fourier_top4(Th, V['ph'], V['bh0'],
V['bh1c'], V['bh1s'], V['bh2c'], V['bh2s'], V['bh3c'], V['bh3s'],
V['bh4c'], V['bh4s'], V['kh2'], V['kh3'], V['kh4']) # heat domain
Xc = x[(x>V['xc']) & (y>V['yc'])]; Tc = t[(x>V['xc']) & (y>V['yc'])];
tidxc = tidx[(x>V['xc']) & (y>V['yc'])]
l0c = fourier_top4(Tc, V['p'], V['b0'], V['b1c'], V['b1s'], V['b2c'], V['b2s'],
V['b3c'], V['b3s'], V['b4c'], V['b4s'],
V['k2'], V['k3'], V['k4']) # HVAC-off domain
lc = linearc(Xc, V['bc'], V['mc'], V['xc']) * fourier_top4(Tc, V['pc'], V['bc0'],
V['bc1c'], V['bc1s'], V['bc2c'], V['bc2s'], V['bc3c'], V['bc3s'],
V['bc4c'], V['bc4s'], V['kc2'], V['kc3'], V['kc4']) # cool domain
if log_transform:
# need to back-transform
if modtype == 'A':
lh = np.exp(lh) - np.exp(l0h)
lc = np.exp(lc) - np.exp(l0c)
else:
lh = np.exp(lh+l0h) - np.exp(l0h)
lc = np.exp(lc+l0c) - np.exp(l0c)
else:
if modtype == 'A':
lh -= l0h
lc -= l0c
return [tidxh, tidxc], [Xh, Xc], [lh, lc]
def linear_fourier_top4_24_12(x, y, t, # data
xh, yh, xc, yc, # domain bounds
mh, bh, mc, bc, # heat/cool lines
b0, b1c, b1s, b2c, b2s, b3c, b3s, b4c, b4s, # fourier 0 HVAC-off reg
bh0, bh1c, bh1s, bh2c, bh2s, # fourier heat
bc0, bc1c, bc1s, bc2c, bc2s, # fourier cool reg
p, ph, pc, k2, k3, k4, # fourier period and fourier term multiplers
modtype='B'):
# domain-wise regressions
l0 = fourier_top4(t, p, b0, b1c, b1s, b2c, b2s, b3c, b3s, b4c, b4s, k2, k3, k4) # HVAC-off domain
lh = linearc(x, bh, mh, xh)*fourier2(t, ph, bh0, bh1c, bh1s, bh2c, bh2s) # heat domain
lc = linearc(x, bc, mc, xc)*fourier2(t, pc, bc0, bc1c, bc1s, bc2c, bc2s) # cool domain
#if modtype != 'A':
lh = lh + l0
lc = lc + l0
condlist = [(x<xh) & (y>yh), (x>xc) & (y>yc)] # + else
funclist = [lh, lc, l0]
return np.where(condlist[0], funclist[0],
np.where(condlist[1], funclist[1], funclist[2]))
def HVAC_demands_linear_fourier_top4_24_12(x, y, t, tidx, V, log_transform=True, modtype='B'):
Xh = x[(x<V['xh'])&(y>V['yh'])]; Th = t[(x<V['xh'])&(y>V['yh'])];
tidx = np.array(tidx); tidxh = tidx[(x<V['xh'])&(y>V['yh'])];
l0h = fourier_top4(Th, V['p'], V['b0'], V['b1c'], V['b1s'], V['b2c'], V['b2s'],
V['b3c'], V['b3s'],V['b4c'], V['b4s'],
V['k2'], V['k3'], V['k4']) # HVAC-off domain
lh = linearc(Xh, V['bh'], V['mh'], V['xh']) * fourier2(Th, V['ph'], V['bh0'],
V['bh1c'], V['bh1s'], V['bh2c'], V['bh2s']) # heat domain
Xc = x[(x>V['xc']) & (y>V['yc'])]; Tc = t[(x>V['xc']) & (y>V['yc'])]; tidxc = tidx[(x>V['xc']) & (y>V['yc'])]
l0c = fourier_top4(Tc, V['p'], V['b0'], V['b1c'], V['b1s'], V['b2c'], V['b2s'],
V['b3c'], V['b3s'], V['b4c'], V['b4s'],
V['k2'], V['k3'], V['k4']) # HVAC-off domain
lc = linearc(Xc, V['bc'], V['mc'], V['xc']) * fourier2(Tc, V['pc'], V['bc0'],
V['bc1c'], V['bc1s'], V['bc2c'], V['bc2s']) # cool domain
if log_transform:
# need to back-transform
if modtype == 'A':
lh = np.exp(lh) - np.exp(l0h)
lc = np.exp(lc) - np.exp(l0c)
else:
lh = np.exp(lh+l0h) - np.exp(l0h)
lc = np.exp(lc+l0c) - np.exp(l0c)
else:
if modtype == 'A':
lh -= l0h
lc -= l0c
return [tidxh, tidxc], [Xh, Xc], [lh, lc]
print(' "linear_fourier models" and "get HVAC load models" (original) ran.')
# %% model func (with time constraints)
def linear_fourier_top4(x, y, t, # data
xh, yh, xc, yc, # domain bounds
mh, bh, mc, bc, # heat/cool lines
b0, b1c, b1s, b2c, b2s, b3c, b3s, b4c, b4s, # fourier 0 HVAC-off reg
bh0, bh1c, bh1s, bh2c, bh2s, bh3c, bh3s, bh4c, bh4s, # fourier heat
bc0, bc1c, bc1s, bc2c, bc2s, bc3c, bc3s, bc4c, bc4s, # fourier cool reg
p, ph, pc, k2, k3, k4, kh2, kh3, kh4, kc2, kc3, kc4, # fourier period and fourier term multiplers
modtype='B'):
global tseason
# domain-wise regressions
l0 = fourier_top4(t, p, b0, b1c, b1s, b2c, b2s, b3c, b3s, b4c, b4s, k2, k3, k4) # HVAC-off domain
lh = linearc(x, bh, mh, xh)*fourier_top4(t, ph, bh0, bh1c, bh1s, bh2c, bh2s, bh3c, bh3s, bh4c, bh4s, kh2, kh3, kh4) # heat domain
lc = linearc(x, bc, mc, xc)*fourier_top4(t, pc, bc0, bc1c, bc1s, bc2c, bc2s, bc3c, bc3s, bc4c, bc4s, kc2, kc3, kc4) # cool domain
if modtype != 'A':
lh = lh + l0
lc = lc + l0
condlist = [(x<xh) & (y>yh) & ((t<tseason[0])|(t>=tseason[3])),
(x>xc) & (y>yc) & (t>=tseason[1]) & (t<tseason[2])] # + else
funclist = [lh, lc, l0]
return np.where(condlist[0], funclist[0],
np.where(condlist[1], funclist[1], funclist[2]))
def HVAC_demands_linear_fourier_top4(x, y, t, tidx, V, log_transform=True, modtype='B'):
global tseason
Hfilt = (x<V['xh'])&(y>V['yh']) & ((t<tseason[0])|(t>=tseason[3]))
Xh = x[Hfilt]; Th = t[Hfilt]; tidxh = tidx[Hfilt];
l0h = fourier_top4(Th, V['p'], V['b0'], V['b1c'], V['b1s'], V['b2c'], V['b2s'],
V['b3c'], V['b3s'],V['b4c'], V['b4s'],
V['k2'], V['k3'], V['k4']) # HVAC-off domain
lh = linearc(Xh, V['bh'], V['mh'], V['xh']) * fourier_top4(Th, V['ph'], V['bh0'],
V['bh1c'], V['bh1s'], V['bh2c'], V['bh2s'], V['bh3c'], V['bh3s'],
V['bh4c'], V['bh4s'], V['kh2'], V['kh3'], V['kh4']) # heat domain
Cfilt = (x>V['xc']) & (y>V['yc']) & (t>=tseason[1]) & (t<tseason[2])
Xc = x[Cfilt]; Tc = t[Cfilt]; tidxc = tidx[Cfilt];
l0c = fourier_top4(Tc, V['p'], V['b0'], V['b1c'], V['b1s'], V['b2c'], V['b2s'],
V['b3c'], V['b3s'], V['b4c'], V['b4s'],
V['k2'], V['k3'], V['k4']) # HVAC-off domain
lc = linearc(Xc, V['bc'], V['mc'], V['xc']) * fourier_top4(Tc, V['pc'], V['bc0'],
V['bc1c'], V['bc1s'], V['bc2c'], V['bc2s'], V['bc3c'], V['bc3s'],
V['bc4c'], V['bc4s'], V['kc2'], V['kc3'], V['kc4']) # cool domain
if log_transform:
# need to back-transform
if modtype == 'A':
lh = np.exp(lh) - np.exp(l0h)
lc = np.exp(lc) - np.exp(l0c)
else:
lh = np.exp(lh+l0h) - np.exp(l0h)
lc = np.exp(lc+l0c) - np.exp(l0c)
else:
if modtype == 'A':
lh -= l0h
lc -= l0c
return [tidxh, tidxc], [Xh, Xc], [lh, lc]
def linear_fourier_top4_24_12(x, y, t, # data
xh, yh, xc, yc, # domain bounds
mh, bh, mc, bc, # heat/cool lines
b0, b1c, b1s, b2c, b2s, b3c, b3s, b4c, b4s, # fourier 0 HVAC-off reg
bh0, bh1c, bh1s, bh2c, bh2s, # fourier heat
bc0, bc1c, bc1s, bc2c, bc2s, # fourier cool reg
p, ph, pc, k2, k3, k4, # fourier period and fourier term multiplers
modtype='B'):
global tseason
# domain-wise regressions
l0 = fourier_top4(t, p, b0, b1c, b1s, b2c, b2s, b3c, b3s, b4c, b4s, k2, k3, k4) # HVAC-off domain
lh = linearc(x, bh, mh, xh)*fourier2(t, ph, bh0, bh1c, bh1s, bh2c, bh2s) # heat domain
lc = linearc(x, bc, mc, xc)*fourier2(t, pc, bc0, bc1c, bc1s, bc2c, bc2s) # cool domain
#if modtype != 'A':
lh = lh + l0
lc = lc + l0
condlist = [(x<xh) & (y>yh) & ((t<tseason[0])|(t>=tseason[3])),
(x>xc) & (y>yc) & (t>=tseason[1]) & (t<tseason[2])] # + else
funclist = [lh, lc, l0]
return np.where(condlist[0], funclist[0],
np.where(condlist[1], funclist[1], funclist[2]))
def HVAC_demands_linear_fourier_top4_24_12(x, y, t, tidx, V, log_transform=True, modtype='B'):
global tseason
Hfilt = (x<V['xh'])&(y>V['yh']) & ((t<tseason[0])|(t>=tseason[3]))
Xh = x[Hfilt]; Th = t[Hfilt]; tidxh = tidx[Hfilt];
l0h = fourier_top4(Th, V['p'], V['b0'], V['b1c'], V['b1s'], V['b2c'], V['b2s'],
V['b3c'], V['b3s'],V['b4c'], V['b4s'],
V['k2'], V['k3'], V['k4']) # HVAC-off domain
lh = linearc(Xh, V['bh'], V['mh'], V['xh']) * fourier2(Th, V['ph'], V['bh0'],
V['bh1c'], V['bh1s'], V['bh2c'], V['bh2s']) # heat domain
Cfilt = (x>V['xc']) & (y>V['yc']) & (t>=tseason[1]) & (t<tseason[2])
Xc = x[Cfilt]; Tc = t[Cfilt]; tidxc = tidx[Cfilt];
l0c = fourier_top4(Tc, V['p'], V['b0'], V['b1c'], V['b1s'], V['b2c'], V['b2s'],
V['b3c'], V['b3s'], V['b4c'], V['b4s'],
V['k2'], V['k3'], V['k4']) # HVAC-off domain
lc = linearc(Xc, V['bc'], V['mc'], V['xc']) * fourier2(Tc, V['pc'], V['bc0'],
V['bc1c'], V['bc1s'], V['bc2c'], V['bc2s']) # cool domain
if log_transform:
# need to back-transform
if modtype == 'A':
lh = np.exp(lh) - np.exp(l0h)
lc = np.exp(lc) - np.exp(l0c)
else:
lh = np.exp(lh+l0h) - np.exp(l0h)
lc = np.exp(lc+l0c) - np.exp(l0c)
else:
if modtype == 'A':
lh -= l0h
lc -= l0c
return [tidxh, tidxc], [Xh, Xc], [lh, lc]
def Baseload_linear_fourier_top4(x, y, t, tidx, V, log_transform):
l0 = fourier_top4(t, V['p'], V['b0'], V['b1c'], V['b1s'], V['b2c'], V['b2s'],
V['b3c'], V['b3s'],V['b4c'], V['b4s'],
V['k2'], V['k3'], V['k4']) # HVAC-off domain
if log_transform:
l0 = np.exp(l0)
return l0
def linear_fourier_top8_24_12(x, y, t, # data
xh, yh, xc, yc, # domain bounds
mh, bh, mc, bc, # heat/cool lines
b0, b1c, b1s, b2c, b2s, b3c, b3s, b4c, b4s, # fourier 0 HVAC-off reg
b5c, b5s, b6c, b6s, b7c, b7s, b8c, b8s,
bh0, bh1c, bh1s, bh2c, bh2s, # fourier heat
bc0, bc1c, bc1s, bc2c, bc2s, # fourier cool reg
p, ph, pc, k2, k3, k4, k5, k6, k7, k8, # fourier period and fourier term multiplers
modtype='B'):
global tseason
# domain-wise regressions
l0 = fourier_top8(t, p, b0, b1c, b1s, b2c, b2s, b3c, b3s, b4c, b4s,
b5c, b5s, b6c, b6s, b7c, b7s, b8c, b8s,
k2, k3, k4, k5, k6, k7, k8) # HVAC-off domain
lh = linearc(x, bh, mh, xh)*fourier2(t, ph, bh0, bh1c, bh1s, bh2c, bh2s) # heat domain
lc = linearc(x, bc, mc, xc)*fourier2(t, pc, bc0, bc1c, bc1s, bc2c, bc2s) # cool domain
if modtype != 'A':
lh = lh + l0
lc = lc + l0
condlist = [(x<xh) & (y>yh) & ((t<tseason[0])|(t>=tseason[3])),
(x>xc) & (y>yc) & (t>=tseason[1]) & (t<tseason[2])] # + else
funclist = [lh, lc, l0]
return np.where(condlist[0], funclist[0],
np.where(condlist[1], funclist[1], funclist[2]))
def HVAC_demands_linear_fourier_top8_24_12(x, y, t, tidx, V, log_transform, modtype='B'):
global tseason
Hfilt = (x<V['xh'])&(y>V['yh']) & ((t<tseason[0])|(t>=tseason[3]))
Xh = x[Hfilt]; Th = t[Hfilt]; tidxh = tidx[Hfilt];
l0h = fourier_top8(Th, V['p'], V['b0'], V['b1c'], V['b1s'], V['b2c'], V['b2s'],
V['b3c'], V['b3s'],V['b4c'], V['b4s'],
V['b5c'], V['b5s'], V['b6c'], V['b6s'],
V['b7c'], V['b7s'],V['b8c'], V['b8s'],
V['k2'], V['k3'], V['k4'],V['k5'], V['k6'], V['k7'], V['k8']) # HVAC-off domain
lh = linearc(Xh, V['bh'], V['mh'], V['xh']) * fourier2(Th, V['ph'], V['bh0'],
V['bh1c'], V['bh1s'], V['bh2c'], V['bh2s']) # heat domain
Cfilt = (x>V['xc']) & (y>V['yc']) & (t>=tseason[1]) & (t<tseason[2])
Xc = x[Cfilt]; Tc = t[Cfilt]; tidxc = tidx[Cfilt];
l0c = fourier_top8(Tc, V['p'], V['b0'], V['b1c'], V['b1s'], V['b2c'], V['b2s'],
V['b3c'], V['b3s'],V['b4c'], V['b4s'],
V['b5c'], V['b5s'], V['b6c'], V['b6s'],
V['b7c'], V['b7s'],V['b8c'], V['b8s'],
V['k2'], V['k3'], V['k4'],V['k5'], V['k6'], V['k7'], V['k8']) # HVAC-off domain
lc = linearc(Xc, V['bc'], V['mc'], V['xc']) * fourier2(Tc, V['pc'], V['bc0'],
V['bc1c'], V['bc1s'], V['bc2c'], V['bc2s']) # cool domain
if log_transform:
# need to back-transform
if modtype == 'A':
lh = np.exp(lh) - np.exp(l0h)
lc = np.exp(lc) - np.exp(l0c)
else:
lh = np.exp(lh+l0h) - np.exp(l0h)
lc = np.exp(lc+l0c) - np.exp(l0c)
else:
if modtype == 'A':
lh -= l0h
lc -= l0c
return [tidxh, tidxc], [Xh, Xc], [lh, lc]
def Baseload_linear_fourier_top8(x, y, t, tidx, V, log_transform):
l0 = fourier_top8(t, V['p'], V['b0'], V['b1c'], V['b1s'], V['b2c'], V['b2s'],
V['b3c'], V['b3s'],V['b4c'], V['b4s'],
V['b5c'], V['b5s'], V['b6c'], V['b6s'],
V['b7c'], V['b7s'],V['b8c'], V['b8s'],
V['k2'], V['k3'], V['k4'],V['k5'], V['k6'], V['k7'], V['k8']) # HVAC-off domain
if log_transform:
l0 = np.exp(l0)
return l0
print(' "linear_fourier models" and "get HVAC load models" (with time constraints) ran.')
# %% [2] get DR from results
def get_disagg_load_kW(zc, service_type, LB_pdata=None, LB_r2=None, fourier_type='42', log_transform=True):
global data_type
"""
LB_pdata: lower bound for zip codes to be included in aggregation based on their 'pdata', [0,1]
LB_r2: lower bound for zip codes to be included in aggregation based on their 'r2', [0,1]
"""
modtype = 'B'
log = 'log' if log_transform else ''
outdir_sub = os.path.join(outdir, 'Model{}_{}_{}_{}'.format(fourier_type,log,service_type,data_type))
Output = load_pickle(os.path.join(outdir_sub,'Model{}{}_{}_{}'.format(fourier_type, '_log' if log_transform else '',
service_type, zc)))
data = Output['data']
xx, yy, t, tidx, best_fit = data['temp'], data['demand'], data['time_index'], data['time'], data['best_fit']
tidx = np.array(tidx)
it = Output['opt']; V = Output['df_val'].iloc[it]
if fourier_type == '44':
Thc, Xhc, Yhc = HVAC_demands_linear_fourier_top4(xx, yy, t, tidx, V, log_transform, modtype) # [xh, xc], [yh, yc]
elif fourier_type == '42':
Thc, Xhc, Yhc = HVAC_demands_linear_fourier_top4_24_12(xx, yy, t, tidx, V, log_transform, modtype)
elif fourier_type == '82':
Thc, Xhc, Yhc = HVAC_demands_linear_fourier_top8_24_12(xx, yy, t, tidx, V, log_transform, modtype)
if fourier_type in ['44','42']:
BL = Baseload_linear_fourier_top4(xx, yy, t, tidx, V, log_transform)
elif fourier_type == '82':
BL = Baseload_linear_fourier_top8(xx, yy, t, tidx, V, log_transform)
for i in range(len(Yhc)):
### retain only positive DR
Thc[i] = Thc[i][Yhc[i]>0]; Xhc[i] = Xhc[i][Yhc[i]>0]; Yhc[i] = Yhc[i][Yhc[i]>0]
### apply filters
if LB_pdata is not None:
if V['pdata'] < LB_pdata:
Yhc[i] = np.zeros_like(Xhc[i])
if LB_r2 is not None:
if V['r2'] < LB_r2:
Yhc[i] = np.zeros_like(Xhc[i])
### put into df
ttheat = pd.DataFrame(Xhc[0], index=Thc[0], columns=[zc]); ttheat.index.name='time' # time temp
ttcool = pd.DataFrame(Xhc[1], index=Thc[1], columns=[zc]); ttcool.index.name='time'
tdheat = pd.DataFrame(Yhc[0], index=Thc[0], columns=[zc]).divide(1000); tdheat.index.name='time' # time DR kW
tdcool = pd.DataFrame(Yhc[1], index=Thc[1], columns=[zc]).divide(1000); tdcool.index.name='time'
baseload = pd.DataFrame(BL, index=tidx, columns=[zc]).divide(1000); baseload.index.name='time' # time baseload kW
return ttheat, ttcool, tdheat, tdcool, baseload
def get_results(zc, service_type, fourier_type='42', log_transform=True):
global data_type
"""
LB_pdata: lower bound for zip codes to be included in aggregation based on their 'pdata', [0,1]
LB_r2: lower bound for zip codes to be included in aggregation based on their 'r2', [0,1]
"""
modtype = 'B'
log = 'log' if log_transform else ''
outdir_sub = os.path.join(outdir, 'Model{}_{}_{}_{}'.format(fourier_type,log,service_type,data_type))
Output = load_pickle(os.path.join(outdir_sub,'Model{}{}_{}_{}'.format(fourier_type, '_log' if log_transform else '',
service_type, zc)))
#### Ouput structure #####
# Output = dict({'zipcode': zc, # single val
# 'data': {'temp': xx, 'demand': yy, 'time_index': t, 'time': tidx, 'best_fit': res.best_fit}, # list of data
# 'df_val': DFV, # df of best val and stats from all iterations
# #'res': Results, # list of lmfit res output
# 'opt': Opt, # single val, opt iter
# 'opt_DR': Opt_posDR # single val, opt iter out of all non neg DR
# })
it = Output['opt']; V = Output['df_val'].iloc[it] # optimal iter only
df_val = Output['df_val']
df_val['type'] = service_type
df_val['zip_code'] = zc
return df_val
print('"get DR kWh and results" func ran')
def diurnal(df):
"""
df : single col dataframe
"""
df = df.groupby(df.index.hour).agg(['mean','std'])
df.index.name = 'hour of day'
return df
def diurnal_box(df):
df.index = df.index.hour
df.index.name = 'hour of day'
df = df.reset_index().pivot(columns='hour of day', values=df.name)
return df
def get_weighted_mean_and_std(dfx, dfw):
N0w = len(dfw.dropna()) # no. non-zero weights
AD_mean = (dfx*dfw).sum()/dfw.sum() # weighted mean
AD_std = np.sqrt((dfw*((dfx-AD_mean)**2)).sum() / ((N0w-1)/N0w*dfw.sum())) # weighted std
return AD_mean, AD_std
def get_DR(DRC, DR_type):
global heat1e, cools, coole, heat2s
DR = DRC.copy()
# make heating available only in winter and cooling in summer
DR.loc[heat1e:cools-pd.Timedelta(0.5,'h'), :] = np.NAN # shoulder 1
DR.loc[coole:heat2s-pd.Timedelta(0.5,'h'), :] = np.NAN # shoulder 2
if DR_type == 'cooling':
DR.loc[:heat1e-pd.Timedelta(0.5,'h'), :] = np.NAN # winter 1 - no cool
DR.loc[heat2s:, :] = np.NAN # winter 2 - no cool
elif DR_type == 'heating':
DR.loc[cools:coole-pd.Timedelta(0.5,'h'), :] = np.NAN # summer - no heat
return DR
def get_annual_DR(DRC, DR_type):
DR = get_DR(DRC, DR_type)
annual_DR = DR.sum(axis=0)/2 # half hourly kW to kWh
return annual_DR
def get_annual_percent_DR(df_demand, DRC, DR_type):
# get annual qty
dfD = df_demand.mean(axis=0)*8784 # [kWh]
dfDR = get_annual_DR(DRC, DR_type)
percent_DR = dfDR/dfD # percent DR
return percent_DR
def weighted_quantile(values, quantiles, sample_weight=None,
values_sorted=False, old_style=False):
""" Very close to numpy.percentile, but supports weights.
NOTE: quantiles should be in [0, 1]!
:param values: numpy.array with data
:param quantiles: array-like with many quantiles needed
:param sample_weight: array-like of the same length as `array`
:param values_sorted: bool, if True, then will avoid sorting of
initial array
:param old_style: if True, will correct output to be consistent
with numpy.percentile.
:return: numpy.array with computed quantiles.
"""
values = np.array(values)
quantiles = np.array(quantiles)
if sample_weight is None:
sample_weight = np.ones(len(values))
sample_weight = np.array(sample_weight)
assert np.all(quantiles >= 0) and np.all(quantiles <= 1), \
'quantiles should be in [0, 1]'
if not values_sorted:
sorter = np.argsort(values)
values = values[sorter]
sample_weight = sample_weight[sorter]
weighted_quantiles = np.cumsum(sample_weight) - 0.5 * sample_weight
if old_style:
# To be convenient with numpy.percentile
weighted_quantiles -= weighted_quantiles[0]
weighted_quantiles /= weighted_quantiles[-1]
else:
weighted_quantiles /= np.sum(sample_weight)
return np.interp(quantiles, weighted_quantiles, values)
# %% [3] run panel for Average premise DR
###### agg DR by service type ######
fourier_type = '82' # <---------- # '44' or '42' or '82'
log_transform = False # <------- # if modeling data as log(data) in [W]
LB_pdata = 95 # <------ lower bound for pdata: 0~100
LB_r2 = None # <------- lower bound for r2: 0~100
fig_ext = 'png' # <-------
log_ext = '_log' if log_transform else ''
ylog_msg = 'log ' if log_transform else ''
pdata_ext = '_al{}pct'.format(LB_pdata) if LB_pdata is not None else ''
r2_ext = '_al{}ptR2'.format(LB_r2) if LB_r2 is not None else ''
LB_pdata = LB_pdata/100 if LB_pdata is not None else LB_pdata
LB_r2 = LB_r2/100 if LB_r2 is not None else LB_r2
type_descr = {'C23': 'SF-NE',
'C24': 'MF-NE',
'C25': 'SF-E',
'C26': 'MF-E'}
long_type_descr = {'C23': 'Single family non-electric',
'C24': 'Multi-family non-electric',
'C25': 'Single family electric',
'C26': 'Multi-family electric'}
outdir_dr = os.path.join(outdir, 'Model{}{}_DR'.format(fourier_type, '_log' if log_transform else ''))
if not os.path.exists(outdir_dr):
os.mkdir(outdir_dr)
### seasons by months
# heat1e = pd.Timestamp('2016-05-01') #
# cools = pd.Timestamp('2016-06-01') #
# coole = pd.Timestamp('2016-09-01') #
# heat2s = pd.Timestamp('2016-10-01') #
### seasons by rupture
heat1e = pd.Timestamp('2016-04-11')
cools = pd.Timestamp('2016-05-26')
coole = pd.Timestamp('2016-09-28')
heat2s = pd.Timestamp('2016-11-17')
# tseason
tseason = np.array([heat1e, cools, coole, heat2s]) - np.array([pd.Timestamp('2015-12-01')])
tseason = np.array([i.days*24 + i.seconds/3600 for i in tseason])
ComEd = pd.read_csv(os.path.join(outdir,'ComEd System Loads','hrl_load_estimated.csv'),
parse_dates=['datetime_beginning_utc']).rename({
'datetime_beginning_utc':'time',
'estimated_load_hourly':'system load'},
axis=1)[['time','system load']]
# system load
ComEd['time'] = ComEd['time']-DateOffset(hours=6); ComEd.index.freq = 'h'
ComEd.set_index(['time'], inplace=True)
ComEd = ComEd/1e3 # MW to GW
### system load duration by season
ComEd3H = get_DR(ComEd, 'heating').sort_values(by='system load', ascending=False)
ComEd3C = get_DR(ComEd, 'cooling').sort_values(by='system load', ascending=False)
print('>>> output directory: {}'.format(outdir_dr))
ADR = {}; # ADRC = {}, {}; # for storing zipcode DR timeseries
AnnDRH, AnnDRC = {}, {}; # for storing annual zipcode heat/cool load
PDRH, PDRC = {}, {}; # for storing annual zipcode heat/cool load percents
SPDRH, SPDRC = {}, {}; # for storing seasonal zipcode heat/cool percents
PeakDRH, PeakDRC = {}, {}; # for storing avg DR for top 5 seasonal peaks
SPeakDRH, SPeakDRC = {}, {}; # for storing % DR for top 5 seasonal peaks
NACC = {}; # for storing no. acct per zip code
for counter, typ in enumerate(['C23','C24','C25','C26'],1):
# need to break 'C23' into two partitions
service_type = typ
outdir_sub = folder_set_up(service_type, fourier_type, log_transform)
print('>>> {}. load data: {} in {} [{}W]...'.format(counter, service_type, data_type, ylog_msg))
############### (1) get zip code DR from results
## get completed list
zc_list = list(os.path.splitext(os.path.basename(y))[0][-5:] for y in
list(filter(lambda x: x.endswith('.pkl'), os.listdir(outdir_sub))))
zc_list = list(map(int, zc_list))
#zc_list = zc_list[:5] # <-----
TTH, TTC, TDH, TDC, BL = [], [], [], [], [] # in kWh (avg per acct)
for zc in zc_list:
DR = get_disagg_load_kW(zc=zc, service_type=service_type, LB_pdata=LB_pdata, LB_r2=LB_r2,
fourier_type=fourier_type, log_transform=log_transform)
# add to lists
TTH.append(DR[0]); TTC.append(DR[1]) # time temp
TDH.append(DR[2]); TDC.append(DR[3]) # time DR kW
BL.append(DR[4]) # time baseload kW
print(' >>> for-loop compute completed!\n')
# convert to df
TTH = pd.concat(TTH, axis=1); TTC = pd.concat(TTC, axis=1) # premise level zipcode [time, temp]
TDH = pd.concat(TDH, axis=1); TDC = pd.concat(TDC, axis=1) # premise level zipcode [time, demand(kW)]
BL = pd.concat(BL, axis=1);
##### (2) remove zip codes with total DR = 0 as they are filtered out by LBs
filtered_zc_list = TDH.columns[(TDH.sum(axis=0)>0) | (TDC.sum(axis=0)>0)]
TTH = TTH[filtered_zc_list]; TTC = TTC[filtered_zc_list]; # filtered
TDH = TDH[filtered_zc_list]; TDC = TDC[filtered_zc_list]; # filtered
BL = BL[filtered_zc_list];
##### (3) load demand data
df_temp, df_demand, fft, fftn, ffth, fftc = data_set_up(service_type, in_W=False, log_transform=False)
df_temp = df_temp[filtered_zc_list]; df_demand = df_demand[filtered_zc_list] # filtered
ts1 = pd.Timestamp('2015-12-01')
ts2 = pd.Timestamp('2016-12-01')
# get number of acct per zip code
df_count = DF[service_type].query('(time>=@ts1)&(time<@ts2)').set_index(
['time','zip_code'])[['count']].unstack(level='zip_code')
df_count_max = df_count.max().astype('int')
df_count = (df_count/df_count*df_count_max)['count'] # make all count time series the same within a zip code
df_count = df_count[filtered_zc_list] # filtered
Nacc = df_count.max(axis=0)
Nacc = Nacc.astype('int') # make into integers
atd = DF[service_type].query('(time>=@ts1)&(time<@ts2)&(zip_code in @filtered_zc_list)') # ['mean'] is in kWh
atd['mean'] = 2*atd['mean'] # convert from kWh for half hourly to kW
atd.loc[:,'count'] = atd['zip_code'].map(atd.groupby(['zip_code'])['count'].max().astype('int'))
atd = atd.set_index(['zip_code','time'])
print(' >>> demand data loaded!\n')
##### (4) consolidate DR, temp, and count and save
TTD = pd.concat([TDH,TDC,BL], keys=['heating_kW', 'cooling_kW','baseload_kW']) # time temp + time demand (kWh)
TTD = TTD.rename_axis(columns='zip_code')
TTD = TTD.unstack(level=0).stack(level='zip_code').reset_index(
).sort_values(by=['zip_code','time']).reset_index(drop=True)
TTD = TTD.set_index(['zip_code','time']).join(atd[['count', 'mean','degC']], how='right').fillna(0)
TTD = TTD.rename({'mean':'total_kW'}, axis=1)
TTD.to_parquet(os.path.join(outdir_dr, 'Disagg_load_{}_{}{}{}{}.parquet'.format(
service_type, fourier_type, log_ext, pdata_ext, r2_ext)))
ADR[service_type] = TTD;
print('filtered zip code list: ', len(filtered_zc_list))
print('len(TTDH): ', TTD.index.get_level_values(level='zip_code').nunique())
print('len(atd): ', atd.index.get_level_values(level='zip_code').nunique())
### turn avg DR into a single avg DR
# get total demand
TD = ((df_demand*df_count).sum(axis=1)/df_count.sum(axis=1)).rename('whole-home demand') #[kWh] - weighted per premise
TotalD = (df_demand*df_count).div(df_count.sum(axis=1), axis=0) #[kWh] - weighted per premise (disagg)
##### (5) get annual data
### whole-home demand and 95%CI
Ademand = df_demand.mean(axis=0)*len(df_demand)/2
AD_mean, AD_std = get_weighted_mean_and_std(Ademand, Nacc)
Percentiles = [0.05, 0.25, 0.5, 0.75, 0.95]
Ademand_Ptile = pd.DataFrame([weighted_quantile(np.array(Ademand), Percentiles, sample_weight=np.array(Nacc))],
columns=Percentiles)
print('---> Avg annual whole-home demand [kWh] for {}: {} +/- {} (95%CI)'.format(
service_type, round(AD_mean,0), round(AD_std*1.96,0)))
print(' In percentiles:')
display(Ademand_Ptile)
print('\n >>> SANITY CHECK...')
print(' SUM(AVG_TS): ', TD.sum()*Nacc.sum()/2)
print(' SUM(ANNUAL): ', (Ademand*Nacc).sum())
print(' % DIFF FROM TOP TO BOTTOM: {}%'.format(
round((TD.sum()*Nacc.sum()/2-(Ademand*Nacc).sum())/(Ademand*Nacc).sum()*100,2)
))
### annual DR by zip codes
Annual_DRH = get_annual_DR(TDH, 'heating')
Annual_DRC = get_annual_DR(TDC, 'cooling')
AnnDRH[service_type] = Annual_DRH; AnnDRC[service_type] = Annual_DRC
### annual baseload by zip codes
Annual_BL = BL.sum(axis=0)/2
# print(' % diff of DR+baseload from ground truth total: \n{}'.format(
# round((Annual_DRH + Annual_BL-Ademand)/Ademand*100, 2)))
### annual percent DR by zip codes
PctDRH = Annual_DRH/(Annual_DRH + Annual_BL) #Ademand
PctDRC = Annual_DRC/(Annual_DRC + Annual_BL) #Ademand
PDRH[service_type] = PctDRH; PDRC[service_type] = PctDRC
### print annual DR percents and 95%CI
PctDRH_mean, PctDRH_std = get_weighted_mean_and_std(PctDRH, Nacc)
HPct_Ptile = pd.DataFrame([weighted_quantile(np.array(PctDRH), Percentiles, sample_weight=np.array(Nacc))],
columns=Percentiles)
print('---> Avg % annual heating load for {}: {} +/- {} (95%CI)'.format(
service_type, round(PctDRH_mean*100,2), round(PctDRH_std*100*1.96,2)))