-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquantitative_report.py
executable file
·1933 lines (1854 loc) · 96.1 KB
/
quantitative_report.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
# How to interpret scatter plot
import os
import glob
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import pylab as P
import textwrap as tw
from scipy import stats
import time
import datetime
import get_building_set as gbs
import sqlite3
import calendar
import shutil
import util_io as uo
import label as lb
import util
homedir = os.getcwd() + '/csv_FY/'
master_dir = homedir + 'master_table/'
weatherdir = os.getcwd() + '/csv_FY/weather/'
r_input = os.getcwd() + '/input_R/'
my_dpi = 70
plot_set_label = {'AI': 'A + I', 'All': 'All', 'ACI': 'A + C + I'}
def eui_distribution():
conn = uo.connect('all')
df = pd.read_sql('SELECT Building_Number, Fiscal_Year, eui_elec, eui_gas FROM eui_by_fy', conn)
# print df.groupby('Fiscal_Year').count()
df['Fiscal_Year'] = df['Fiscal_Year'].map(int)
df2 = df[df['eui_elec'] > 200000]
print df2
print len(df2)
sns.set_style("whitegrid")
sns.set_context("talk", font_scale=1.0)
sns.set_palette(sns.color_palette('Set3'))
sns.factorplot(x='Fiscal_Year', y='eui_elec', data=df[df['eui_elec'] < 100000],
kind='violin', size=6, aspect=2)
print my_dpi
# P.savefig(os.getcwd() + '/plot_FY_annual/quant/cat_count.png', dpi = my_dpi, figsize = (2000/my_dpi, 500/my_dpi), bbox_inches='tight')
plt.show()
plt.close()
def area_distribution():
conn = uo.connect('all')
df = pd.read_sql('SELECT * FROM EUAS_area', conn)
# print df.groupby('Fiscal_Year').count()
df['Fiscal_Year'] = df['Fiscal_Year'].map(int)
sns.set_style("whitegrid")
sns.set_context("talk", font_scale=1.0)
sns.set_palette(sns.color_palette('Set3'))
sns.barplot(x='Fiscal_Year', y='Gross_Sq.Ft', data=df)
plt.title('Average Gross_Sq.Ft by Fiscal Year')
plt.xlabel('Fiscal Year')
print my_dpi
P.savefig(os.getcwd() + '/plot_FY_annual/quant/area_dist.png', dpi = my_dpi, figsize = (2000/my_dpi, 500/my_dpi), bbox_inches='tight')
# plt.show()
plt.close()
def cat_distribution():
conn = uo.connect('all')
df = pd.read_sql('SELECT DISTINCT Building_Number, Fiscal_Year, Cat FROM EUAS_monthly', conn)
df['Fiscal_Year'] = df['Fiscal_Year'].map(int)
sns.set_style("whitegrid")
sns.set_context("talk", font_scale=1.0)
sns.set_palette(sns.color_palette('Set3'))
sns.factorplot(x='Fiscal_Year', hue='Cat', hue_order=['A', 'I',
'C', 'B',
'D', 'E'],
data=df,
kind='count',
size=6,
aspect=2)
plt.ylabel('Building Count')
print my_dpi
P.savefig(os.getcwd() + '/plot_FY_annual/quant/cat_count.png', dpi = my_dpi, figsize = (2000/my_dpi, 500/my_dpi), bbox_inches='tight')
# plt.show()
plt.close()
def temp():
df = pd.read_csv(master_dir + 'eui_by_fy_wcat.csv')
df = df[df['Cat'].isin(['A', 'C', 'I'])]
df = df[df['Fiscal Year'] > 2006]
df = df[df['Fiscal Year'] < 2016]
print df.groupby(['Fiscal Year']).count()[['Building Number']]
df2 = df.groupby(['Building Number']).filter(lambda x: len(x) > 5)
print '> 5 year records', len(df2['Building Number'].unique())
return
def building_count_plot(plot_set):
conn = sqlite3.connect(homedir + 'db/all.db')
with conn:
df = pd.read_sql('SELECT DISTINCT Building_Number FROM EUAS_category', conn)
# df = pd.read_csv(master_dir + 'EUAS_static_tidy.csv')
conn = sqlite3.connect(homedir + 'db/all.db')
with conn:
# df2 = pd.read_csv(master_dir + 'eui_by_fy_wcat.csv')
df2 = pd.read_sql('SELECT Building_Number, Fiscal_Year, eui_elec, eui_gas, eui FROM eui_by_fy', conn)
print df2.groupby('Fiscal_Year').count().head(n=15)
if 'AI' in plot_set:
study_set = gbs.get_cat_set(['A', 'I'])
if 'ACI' in plot_set:
study_set = gbs.get_cat_set(['A', 'C', 'I'])
if 'ECM' in plot_set:
study_set = gbs.get_ecm_set()
if 'Invest' in plot_set:
study_set = gbs.get_invest_set()[-1]
else:
study_set = gbs.get_all_building_set()
df = df[df['Building_Number'].isin(study_set)]
df2 = df2[df2['Building_Number'].isin(study_set)]
df2['good_elec'] = df2['eui_elec'].map(lambda x: 'Electric EUI >='+
' 12' if x >= 12 else np.nan)
df2['good_gas'] = df2['eui_gas'].map(lambda x: 'Gas EUI >= 3' if x
>= 3 else np.nan)
good_both_str = '\n'.join(tw.wrap('Electric EUI >= 12 and Gas EUI'+
' >= 3', 20))
df2['good_both'] = df2.apply(lambda r: good_both_str if
(r['eui_elec'] >= 12 and r['eui_gas']
>= 3) else np.nan, axis=1)
df3 = pd.melt(df2, id_vars=['Building_Number', 'Fiscal_Year'], value_vars=['good_elec', 'good_gas', 'good_both'])
df2 = df2[['Building_Number', 'Fiscal_Year']]
df2['value'] = 'All Building'
df3.drop('variable', axis=1, inplace=True)
df4 = pd.concat([df2, df3], ignore_index=True)
df4['Fiscal_Year'] = df4['Fiscal_Year'].map(lambda x: str(int(x)))
print 'Plot set: {0}'.format(plot_set)
df_gr = (df4.groupby(['Fiscal_Year', 'value']).size()).to_frame('count')
df_gr.replace('\n', ' ', inplace=True)
print df_gr.head(n=15)
df_gr.to_csv(os.getcwd() + '/plot_FY_annual/quant_data/count_{0}.csv'.format(plot_set))
sns.set_style("whitegrid")
sns.set_context("talk", font_scale=1.5)
sns.set_palette(sns.color_palette('Set3'))
# sns.countplot(hue='value', x='Fiscal Year', data=df4)
sns.factorplot(hue='value', x='Fiscal_Year', data=df4,
kind='count', size=6, aspect=2)
if plot_set == 'ECM':
plt.title('Count of Building in EUAS data set with ECM')
elif plot_set == 'AIECM':
plt.title('Count of A + I Building in EUAS data set with ECM')
elif plot_set == 'AllInvest':
plt.title('Count of All Building in EUAS data set with Investment')
elif plot_set == 'AIInvest':
plt.title('Count of A + I Building in EUAS data set with Investment')
else:
plt.title('Count of {0} Building in EUAS data set'.format(plot_set_label[plot_set]))
# plt.legend(loc = 2, bbox_to_anchor=(1, 1))
plt.ylabel('Building Count')
plt.xlabel('Fiscal Year')
print my_dpi
P.savefig(os.getcwd() + '/plot_FY_annual/quant/count_{0}.png'.format(plot_set), dpi = my_dpi, figsize = (2000/my_dpi, 500/my_dpi), bbox_inches='tight')
# plt.show()
plt.close()
def good_elec_gas():
conn = uo.connect('all')
with conn:
df = pd.read_sql('SELECT * FROM eui_by_fy', conn)
df3 = pd.read_sql('SELECT Building_Number, Cat FROM EUAS_category', conn)
df = df[df['Fiscal_Year'] > 2006]
df = df[df['Fiscal_Year'] < 2016]
df['good_both'] = df.apply(lambda r: 1 if (r['eui_elec'] >= 12 and
r['eui_gas'] >= 3) else
0, axis=1)
df = df[['Building_Number', 'good_both']]
df2 = df.groupby('Building_Number').sum()
df2 = df2[df2['good_both'] > 5]
df2.reset_index(inplace=True)
df_long = pd.merge(df3, df2, on='Building_Number', how='left')
df_short = pd.merge(df3, df2, on='Building_Number', how='right')
df_long['Status'] = "All building in EUAS data set"
df_short['Status'] = "Electric EUI >= 12 and\nGas EUI >= 3\nfor at least 6 years\nfrom FY2007 to FY2015"
df_c = pd.concat([df_long, df_short], ignore_index=True)
print len(df_long), len(df_short), len(df_c)
rename_dict = {\
'A': 'A\n{0}'.format('\n'.join(tw.wrap('Government Goal', 10))),
'I': 'I\n{0}'.format('\n'.join(tw.wrap('Energy Intensive', 10))),
'B': 'B\n{0}'.format('\n'.join(tw.wrap('Government Exempt', 10))),
'C': 'C\n{0}'.format('\n'.join(tw.wrap('Lease', 10))),
'D': 'D\n{0}'.format('\n'.join(tw.wrap('Lease Exempt', 10))),
'E': 'E\n{0}'.format('\n'.join(tw.wrap('Reimbursable non reportable', 12)))}
df_c.replace(rename_dict, inplace=True)
order = [rename_dict[k] for k in ['A', 'I', 'B', 'C', 'D', 'E']]
sns.set_palette(sns.color_palette('Set2'))
sns.set_context("talk", font_scale=1.2)
sns.countplot(x='Cat', order=order, hue='Status', data=df_c)
plt.title('Building Category Count Plot')
plt.ylabel('Building Count')
plt.legend(loc = 2, bbox_to_anchor=(1, 1))
print 'write to cat_count_all_building_quality.png ...'
P.savefig(os.getcwd() + '/plot_FY_annual/quant/cat_count_all_building_quality.png', dpi = my_dpi, figsize = (2000/my_dpi, 500/my_dpi), bbox_inches='tight')
# plt.show()
plt.close()
def fuel_type_plot(years=None, catfilter=None):
print 'plot fuel type {0} to {1}, {2}'.format(years[0], years[-1], catfilter)
# year_labels = [str(y)[2:] for y in years]
# filelist = ['{0}fuel_type/FY{1}.csv'.format(homedir, yr) for yr in year_labels]
# dfs = []
# for f in filelist:
# df = pd.read_csv(f)
# year = f[-6: -4]
# df['year'] = '20{0}'.format(year)
# dfs.append(df)
# df_all = pd.concat(dfs, ignore_index=False)
conn = uo.connect('all')
with conn:
df_all = pd.read_sql('SELECT * FROM fuel_type', conn)
df_all['Fiscal_Year'] = df_all['Fiscal_Year'].map(int)
if not years is None:
df_all = df_all[df_all['Fiscal_Year'].isin(years)]
fuel_type_cols = ['No Data', 'Gas Only', 'Oil Only',
'Steam Only', 'Gas + Oil', 'Gas + Steam',
'Oil + Steam', 'Gas + Oil + Steam']
df_all = df_all[['Building_Number', 'heating_fuel_type', 'Fiscal_Year']]
with conn:
df_cat = pd.read_sql('SELECT Building_Number, Cat FROM EUAS_category', conn)
df_all2 = pd.merge(df_all, df_cat, on='Building_Number',
how='left')
if catfilter == 'AI':
df_all2 = df_all2[df_all2['Cat'].isin(['A', 'I'])]
sns.set_style("whitegrid")
sns.set_palette(sns.color_palette('Set2'))
sns.set_context("talk", font_scale=1.5)
# sns.mpl.rc("figure", figsize=(10, 5))
sns.factorplot(x='Fiscal_Year',
hue='heating_fuel_type', palette='Set3',
hue_order=fuel_type_cols, data=df_all2,
kind='count', size=6, aspect=2)
# sns.countplot(x='year', order= [str(x) for x in years],
# hue='Heating Fuel Type', palette='Set3',
# hue_order=fuel_type_cols, data=df_all2)
# plt.legend(loc = 2, bbox_to_anchor=(1, 1))
plt.title('Count of {2} Building by Heating Fuel Type (FY{0} - FY{1})'.format(years[0], years[-1], plot_set_label[catfilter]))
plt.ylabel('Number of Buildings')
plt.xlabel('Fiscal Year')
P.savefig(os.getcwd() + '/plot_FY_annual/quant/fuel_type_{0}.png'.format(catfilter), dpi = my_dpi, figsize = (2000/my_dpi, 500/my_dpi), bbox_inches='tight')
plt.close()
def plot_type(plot_set):
ecm_set = gbs.get_ecm_set()
energy_set = gbs.get_energy_set('eui')
# df = pd.read_csv(master_dir + 'EUAS_type.csv')
conn = uo.connect('all')
with conn:
df = pd.read_sql('SELECT * FROM EUAS_type', conn)
if plot_set == 'AI':
ai_set = gbs.get_cat_set(['A', 'I'], conn)
df = df[df['Building_Number'].isin(ai_set)]
df.fillna({'Self-Selected_Primary_Function': 'No Data'},
inplace=True)
eng_ecm_str = '\n'.join(tw.wrap('with ECM Action and at least 6 years of Electric EUI >= 12 and Gas EUI >= 3 from FY2007 to FY2015', 20))
df['ECM'] = df['Building_Number'].map(lambda x: 'with ECM action'
if x in ecm_set else
'without ECM Action')
df2 = df.copy()
df2 = df2[df2['Building_Number'].isin(ecm_set)]
df2 = df2[df2['Building_Number'].isin(energy_set)]
# df['good_energy'] = df['Building Number'].map(lambda x: 'at least 6 years of Electric EUI >= 12 and Gas EUI >= 3' if x in energy_set else np.nan]
df2['ECM'] = eng_ecm_str
df3 = pd.concat([df, df2], ignore_index=True)
sns.set_style("whitegrid")
sns.set_palette(sns.color_palette('Set2'))
sns.set_context("talk", font_scale=1.2)
sns.countplot(y='Self-Selected_Primary_Function', hue='ECM',
data=df3, orient='v')
plt.title('Building Type Count Plot')
plt.suptitle('plot set: {0}'.format(plot_set_label[plot_set]) +
' building')
plt.ylabel('Self-Selected Primary Function')
plt.xlabel('Building Count')
plt.legend(loc = 2, bbox_to_anchor=(1, 1))
print 'write to use_count_{0}.png'.format(plot_set)
# plt.show()
P.savefig(os.getcwd() + '/plot_FY_annual/quant/use_count_{0}.png'.format(plot_set), dpi = my_dpi, figsize = (2000/my_dpi, 500/my_dpi), bbox_inches='tight')
plt.close()
return
def plot_co_count(plot_set, **kwargs):
sns.set_style("whitegrid")
sns.set_palette(sns.color_palette('Set3'))
if 'energy_set' in kwargs:
df = pd.read_csv(master_dir + 'EUAS_static_tidy.csv')
df = df[df['Building Number'].isin(kwargs['energy_set'])]
sns.set_context("talk", font_scale=1)
else:
df = pd.read_csv(master_dir + 'eui_by_fy_wcat.csv')
sns.set_context("talk", font_scale=1.5)
if plot_set == 'AI':
df = df[df['Cat'].isin(['A', 'I'])]
s1 = get_co_set('Capital')
s2 = get_co_set('Operational')
sc = s1.difference(s2)
so = s2.difference(s1)
sco = s1.intersection(s2)
sn = s1.union(s2)
def classify(x):
if x in sc:
return 'C Only'
elif x in so:
return 'O Only'
elif x in sco:
return 'C&O'
elif x not in sn:
return 'No'
order=['C&O', 'C Only' ,'O Only' , 'No']
df['Capital or Operational'] = df['Building Number'].map(classify)
df['Fiscal Year'] = df['Fiscal Year'].map(lambda x: str(int(x)))
if 'energy_set' in kwargs:
eng_ecm_str = '\n'.join(tw.wrap('with ECM Action and at least 6 years of Electric EUI >= 12 and Gas EUI >= 3 from FY2007 to FY2015', 50))
sns.factorplot(x='Capital or Operational', order=order,
data=df, kind='count', size=6, aspect=1)
# sns.countplot(x='Capital or Operational', order=order, data=df)
plt.subplots_adjust(top=0.85)
plt.suptitle('plot set: building {0}'.format(eng_ecm_str))
else:
sns.factorplot(hue='Capital or Operational', x='Fiscal Year',
hue_order=order, data=df, kind='count', size=6,
aspect=2)
# sns.countplot(hue='Capital or Operational', x='Fiscal Year',
# hue_order=order, data=df)
plt.subplots_adjust(top=0.9)
plt.title('{0} Building Count of Capital vs Operational Investment'.format(plot_set_label[plot_set]))
plt.ylabel('Building Count')
if 'energy_set' in kwargs:
P.savefig(os.getcwd() + '/plot_FY_annual/quant/co_count_good_energy_{0}.png'.format(plot_set), dpi = my_dpi, figsize = (2000/my_dpi, 500/my_dpi), bbox_inches='tight')
else:
P.savefig(os.getcwd() + '/plot_FY_annual/quant/co_count_{0}.png'.format(plot_set), dpi = my_dpi, figsize = (2000/my_dpi, 500/my_dpi), bbox_inches='tight')
# plt.show()
plt.close()
return
def get_stat(plot_set, energy_set):
ai_set = gbs.get_ai_set()
if energy_set == None:
study = ai_set
else:
study = ai_set.intersection(energy_set)
df_ecm = pd.read_csv(master_dir + 'ECM/EUAS_ecm.csv')
df_ecm = df_ecm[df_ecm['Building Number'].isin(study)]
df_ecm = df_ecm[df_ecm['high_level_ECM'].notnull()]
gr = df_ecm.groupby(['high_level_ECM', 'detail_level_ECM']).count()
solo = df_ecm.groupby(['Building Number']).filter(lambda x: len(x) == 1)
print solo.head()
if energy_set == None:
gr.to_csv(os.getcwd() + '/plot_FY_annual/quant_data/ecmAction_{0}.csv'.format(plot_set))
solo.groupby(['high_level_ECM', 'detail_level_ECM']).count().to_csv(os.getcwd() + '/plot_FY_annual/quant_data/ecmAction_solo_{0}.csv'.format(plot_set))
else:
gr.to_csv(os.getcwd() + '/plot_FY_annual/quant_data/ecmAction_{0}_energy.csv'.format(plot_set))
solo.groupby(['high_level_ECM', 'detail_level_ECM']).count().to_csv(os.getcwd() + '/plot_FY_annual/quant_data/ecmAction_solo_{0}_energy.csv'.format(plot_set))
df_pro = pd.read_csv(master_dir + 'ecm_program_tidy.csv')
df_pro = df_pro[df_pro['ECM program'] != 'Energy Star']
df_pro = df_pro[df_pro['Building Number'].isin(study)]
gr = df_pro.groupby('ECM program').count()
solo = df_pro.groupby(['Building Number']).filter(lambda x: len(x) == 1)
if energy_set == None:
gr.to_csv(os.getcwd() + '/plot_FY_annual/quant_data/ecmProgram_{0}.csv'.format(plot_set))
solo.groupby(['ECM program']).count().to_csv(os.getcwd() + '/plot_FY_annual/quant_data/ecmProgram_solo_{0}.csv'.format(plot_set))
else:
gr.to_csv(os.getcwd() + '/plot_FY_annual/quant_data/ecmProgram_{0}_energy.csv'.format(plot_set))
solo.groupby(['ECM program']).count().to_csv(os.getcwd() + '/plot_FY_annual/quant_data/ecmProgram_solo_{0}_energy.csv'.format(plot_set))
return
def plot_c_or_o(plot_set, co, energy_set):
df = pd.read_csv(master_dir + 'EUAS_static_tidy.csv')
if plot_set == 'AI':
df = df[df['Cat'].isin(['A', 'I'])]
study_set = set(df['Building Number'].tolist())
df = df[df['Building Number'].isin(energy_set)]
dfs = []
def cap_df(buildings, invest):
df = pd.DataFrame({'Building Number': list(buildings)})
df['Investment'] = invest
return df
if co == 'Capital':
dfs.append(cap_df(gbs.get_ecm_nogsalink(), 'ECM Action'))
dfs.append(cap_df(gbs.get_program_set('LEED'), 'LEED'))
dfs.append(cap_df(gbs.get_program_set('GP'), 'GSA Guiding' +
' Principles'))
elif co == 'Operational':
dfs.append(cap_df(gbs.get_program_set('first fuel'), 'First Fuel'))
dfs.append(cap_df(gbs.get_program_set('Shave Energy'), 'Shave Energy'))
dfs.append(cap_df(gbs.get_program_set('E4'), 'E4'))
dfs.append(cap_df(gbs.get_action_set('high_level_ECM', 'GSALink'),
'GSALink'))
df_all = pd.concat(dfs, ignore_index=True)
df_all = df_all[df_all['Building Number'].isin(study_set)]
print df_all.groupby('Investment').count()
sns.set_style("whitegrid")
sns.set_context("talk", font_scale=1)
sns.set_palette(sns.color_palette('Set3'))
# sns.countplot(x='Investment', data=df_all)
sns.factorplot(x='Investment', data=df_all, kind='count', size=6,
aspect=1)
plt.subplots_adjust(top=0.85)
if co == 'Capital':
plt.ylim((0, 350))
plt.ylabel('Building Count')
plt.title('Count of Building with {0} Investment'.format(co))
eng_ecm_str = '\n'.join(tw.wrap('with at least 6 years of Electric EUI >= 12 and Gas EUI >= 3 from FY2007 to FY2015', 50))
plt.suptitle('plot set: {0} building {1}'.format(plot_set_label[plot_set], eng_ecm_str))
P.savefig(os.getcwd() + '/plot_FY_annual/quant/{1}_count_good_energy_{0}.png'.format(plot_set, co), dpi = my_dpi, figsize = (2000/my_dpi, 500/my_dpi), bbox_inches='tight')
# plt.show()
plt.close()
return
def get_size(df, col, label_dict):
df_size = df.groupby(['Fiscal_Year', col]).size().to_frame('count')
df_size.reset_index(inplace=True)
keys = label_dict.keys()
df_size['order'] = df_size[col].map(lambda x: keys.index(x))
df_size.sort('order', inplace=True)
df_size['label'] = df_size.apply(lambda r: '{0} = {1}'.format(r[col], r['count']), axis=1)
df_size.replace({'label': label_dict}, inplace=True)
df_size = df_size[['Fiscal_Year', 'label']]
d = df_size.groupby('Fiscal_Year')['label'].apply(lambda x: '\n'.join(x)).to_dict()
return {k: '{0}\n{1}'.format(k, d[k]) for k in d}
def classify_fullname(x, cap_only, op_only, cap_and_op, cap_or_op):
if x in cap_only:
return 'Capital Only'
elif x in op_only:
return 'Operational Only'
elif x in cap_and_op:
return 'Capital and Operational'
else:
return 'No Known Investment'
def plot_pnnl(x1, y1, y2 ,y3, plot_set, energy_filter, total_type, method, cat_current):
sns.set_style("whitegrid")
sns.set_palette("Set2")
sns.set_context("talk", font_scale=1)
f, (ax1, ax2, ax3) = plt.subplots(3, sharex=True)
ax1.plot(x1, y1, color='blue', marker='o')
for x,y in zip(x1, y1):
ax1.annotate('{:,.0f}'.format(int(round(y, 0))), xy = (x - 0.5, y-0.7e4), fontsize=12, weight='semibold', color='black')
ax1.set_ylabel('EUI Btu/SF ({0})'.format(lb.total_type_dict[total_type]))
for x,y in zip(x1, y2):
ax2.annotate('{:,.0f}'.format(int(round(y, 0))), xy = (x - 0.5, y-0.7e3), fontsize=12, weight='semibold', color='black')
ax2.plot(x1, y2, color='red', marker='o')
ax2.set_ylabel('Energy Use (BBtu)')
ax3.plot(x1, y3, color='green', marker='o')
plt.sca(ax1)
plt.yticks(range(40000, 90000, 20000), ['40k', '60k', '80k'])
ax1.set_ylim((40000, 95000))
plt.sca(ax2)
plt.yticks(range(5000, 19000, 5000), ['5k', '10k', '15k'])
ax2.set_ylim((5000, 19000))
plt.sca(ax3)
plt.yticks(range(100000, 210000, 50000), ['100k', '150k', '200k'])
for x,y in zip(x1, y3):
ax3.annotate('{:,.0f}'.format(int(round(y, 0))), xy = (x - 0.5, y-0.1e4), fontsize=12, weight='semibold', color='black')
ax3.set_ylabel('Floor Space/kSF')
plt.xlim((2002, 2015))
plt.xlabel('Fiscal Year')
# plt.show()
if cat_current:
P.savefig(os.getcwd() + '/plot_FY_annual/quant/eui_trend_{0}_{1}_{2}_{3}_currentCat.png'.format(plot_set, total_type, method, energy_filter), dpi = my_dpi)
else:
P.savefig(os.getcwd() + '/plot_FY_annual/quant/eui_trend_{0}_{1}_{2}_{3}_latestCat.png'.format(plot_set, total_type, method, energy_filter), dpi = my_dpi)
plt.close()
# cat_current: if true, using current year category, else use latest record
def prepare(plot_set, cat_current, energy_filter):
conn = sqlite3.connect(homedir + 'db/all.db')
df_exc = pd.read_csv(os.getcwd() + \
'/input/FY/excluded_buildings.csv')
exc_set = set(df_exc['Building_Number'].tolist())
# exc_set = set(['AL0011ZZ','FL0033ZZ','FL0039ZZ','MO0039ZZ','TX0000TG','TX0000BM','TX0000CB','TX0000CR','TX0000CV','TX0000EP','TX0000JL','TX0000LI','TX0000LT','TX0000NW','TX0000PH','TX0000RM'])
with conn:
df = pd.read_sql('SELECT Building_Number, Fiscal_Year, [Electric_(kBtu)], [Gas_(kBtu)], [Total_(kBtu)], Cat FROM EUAS_monthly', conn)
df_eui = pd.read_sql('SELECT Building_Number, Fiscal_Year, Cat, eui, eui_total FROM eui_by_fy', conn)
if energy_filter != None:
energy_set = gbs.get_energy_set(energy_filter)
if not cat_current:
study_set = None
if plot_set == 'AI':
ai_set = gbs.get_cat_set(['A', 'I'], conn)
if energy_filter != None:
study_set = ai_set.intersection(energy_set)
else:
study_set = ai_set
elif plot_set == 'ACI':
aci_set = gbs.get_cat_set(['A', 'C', 'I'], conn)
if energy_filter != None:
study_set = aci_set.intersection(energy_set)
else:
study_set = aci_set
elif plot_set == 'select':
study_set = gbs.get_all_building_set().difference(exc_set)
else:
if energy_filter != None:
study_set = energy_set
study_set = study_set.difference(exc_set)
if study_set != None:
df = df[df['Building_Number'].isin(study_set)]
df_eui = df_eui[df_eui['Building_Number'].isin(study_set)]
elif cat_current:
if plot_set == 'AI':
df = df[df['Cat'].isin(['A', 'I'])]
df_eui = df_eui[df_eui['Cat'].isin(['A', 'I'])]
elif plot_set == 'ACI':
df = df[df['Cat'].isin(['A', 'C', 'I'])]
df_eui = df_eui[df_eui['Cat'].isin(['A', 'C', 'I'])]
if energy_filter != None:
df = df[df['Building_Number'].isin(energy_set)]
df_eui = df_eui[df_eui['Building_Number'].isin(energy_set)]
# total consumption
df2 = df.groupby('Fiscal_Year').sum()
df2.reset_index(inplace=True)
with conn:
df3 = pd.read_sql('SELECT * FROM EUAS_area_cat', conn)
if plot_set != 'All' or energy_filter != None:
if not cat_current:
df3 = df3[df3['Building_Number'].isin(study_set)]
else:
if plot_set == 'AI':
df3 = df3[df3['Cat'].isin(['A', 'I'])]
elif plot_set == 'ACI':
df3 = df3[df3['Cat'].isin(['A', 'C', 'I'])]
if energy_filter != None:
df3 = df3[df3['Building_Number'].isin(energy_set)]
# total area
df_area = df3.groupby('Fiscal_Year').sum()
# df_area.reset_index(inplace=True)
df_all = pd.merge(df2, df_area, left_on='Fiscal_Year', right_index=True, how='left')
df_all['Total Electric + Gas'] = df_all['Gas_(kBtu)'] + df_all['Electric_(kBtu)']
df_merge = pd.merge(df_eui, df3, on=['Building_Number', 'Fiscal_Year'], how='left')
return df_all, df_eui, df_merge, df_area
# weight needs re calculate based on selection set
def plot_eui_trend_weighted_mean(plot_set, total_type, energy_filter, cat_current):
df_all, _, df_merge, df_area = prepare(plot_set, cat_current, energy_filter)
df_merge['weight'] = df_merge.apply(lambda r: r['Gross_Sq.Ft']/df_area.ix[int(r['Fiscal_Year']),'Gross_Sq.Ft'], axis=1)
df_merge['weighted'] = df_merge['eui'] * df_merge['weight']
df_merge['weighted_total'] = \
df_merge['eui_total'] * df_merge['weight']
df_result = df_merge.groupby('Fiscal_Year').sum()
x1 = df_all['Fiscal_Year']
if total_type == 'elec_gas':
y1 = df_result['weighted']*1e3
y2 = df_all['Total Electric + Gas']*1e-6
elif total_type == 'all_type':
y1 = df_result['weighted_total']*1e3
y2 = df_all['Total_(kBtu)']*1e-6
y3 = df_all['Gross_Sq.Ft']*1e-3
plot_pnnl(x1, y1, y2, y3, plot_set, energy_filter, total_type, 'weighted', cat_current)
def plot_eui_trend_simple_mean(plot_set, total_type, energy_filter, cat_current):
df_all, df_eui, _, _ = prepare(plot_set, cat_current, energy_filter)
df_result = df_eui.groupby('Fiscal_Year').mean()
x1 = df_all['Fiscal_Year']
if total_type == 'elec_gas':
y1 = df_result['eui']*1e3
y2 = df_all['Total Electric + Gas']*1e-6
elif total_type == 'all_type':
y1 = df_result['eui_total']*1e3
y2 = df_all['Total_(kBtu)']*1e-6
y3 = df_all['Gross_Sq.Ft']*1e-3
# print
# print df_all[['Fiscal_Year', 'EUI']]
plot_pnnl(x1, y1, y2, y3, plot_set, energy_filter, total_type, 'simpleMean', cat_current)
def plot_eui_trend_total_total(plot_set, total_type, energy_filter, cat_current):
df_all, _, _, _ = prepare(plot_set, cat_current, energy_filter)
x1 = df_all['Fiscal_Year']
if total_type == 'elec_gas':
y1 = df_all['Total Electric + Gas']/df_all['Gross_Sq.Ft']*1e3
y2 = df_all['Total Electric + Gas']*1e-6
elif total_type == 'all_type':
y1 = df_all['Total_(kBtu)']/df_all['Gross_Sq.Ft']*1e3
y2 = df_all['Total_(kBtu)']*1e-6
y3 = df_all['Gross_Sq.Ft']*1e-3
# print
# print df_all[['Fiscal_Year', 'EUI']]
plot_pnnl(x1, y1, y2, y3, plot_set, energy_filter, total_type, 'totalOverTotal', cat_current)
def plot_co_type_boxtrend(plot_set, theme, ylimit, agg):
order=['Capital and Operational', 'Capital Only', 'Operational'+
' Only' ,'No Known Investment']
df = pd.read_csv(master_dir + 'eui_by_fy_wcat.csv')
if plot_set == 'AI':
df = df[df['Cat'].isin(['A', 'I'])]
energy_set = gbs.get_energy_set(theme)
df = df[df['Building Number'].isin(energy_set)]
(cap_only, op_only, cap_and_op, cap_or_op) = gbs.get_invest_set()
if agg == 'ave':
df = get_agg(df)
df['Investment Type'] = df['Building Number'].map(lambda x: classify_fullname(x, cap_only, op_only, cap_and_op, cap_or_op))
if agg != 'ave':
df['in_range'] = df['Fiscal Year'].map(lambda x: 2006 < x and x <
2016)
df = df[df['in_range']]
df.sort('Fiscal Year', inplace=True)
df['Fiscal Year'] = df['Fiscal Year'].map(lambda x: str(int(x)))
label_dict = {'Capital Only': 'C',
'Operational Only': 'O',
'Capital and Operational': 'C&O',
'No Known Investment': 'No'}
size_dict = get_size(df, 'Investment Type', label_dict)
df.replace({'Fiscal Year': size_dict}, inplace=True)
sns.set_style("whitegrid")
sns.set_context("talk", font_scale=1.2)
sns.set_palette(sns.color_palette('Set2'))
if agg == 'ave':
aspect = 1.5
else:
aspect = 2
g = sns.FacetGrid(df, aspect=aspect, size=6, legend_out=True)
g = g.map(sns.boxplot, x='Fiscal Year', y='eui', hue='Investment Type', hue_order=order, data=df, palette='Set2')
if agg == 'ori':
pointsize = 1
else:
pointsize = 2
g.map(sns.stripplot, x='Fiscal Year', y='eui', hue='Investment Type', hue_order=order, data=df, jitter=0.3, size=pointsize, color='dimgray', edgecolor='dimgray', label='_nolegend_')
df.groupby(['Fiscal Year', 'Investment Type']).mean().to_csv(os.getcwd() + '/plot_FY_annual/quant_data/mean_type_{0}_{1}.csv'.format(plot_set, agg))
# sns.boxplot(x='Fiscal Year', y='eui', hue='Investment Type',
# hue_order=order, data=df)
# sns.stripplot(x='Fiscal Year', y='eui', hue='Investment Type',
# hue_order=order, data=df, jitter=0.3, size=1,
# color='dimgray', edgecolor='dimgray',
# label='_nolegend_')
plt.subplots_adjust(top=0.87)
plt.legend(loc = 2, bbox_to_anchor=(1, 1))
if agg == 'ori':
plt.title('{0} Distribution Trend'.format(lb.title_dict[theme]))
elif agg == 'ave':
plt.title('Average {0} Distribution Trend'.format(lb.title_dict[theme]))
eng_ecm_str = '\n'.join(tw.wrap('with at least 6 years of Electric EUI >= 12 and Gas EUI >= 3 from FY2007 to FY2015', 50))
plt.suptitle('plot set: {0} building {1}'.format(plot_set_label[plot_set], eng_ecm_str))
plt.ylabel(lb.ylabel_dict[theme])
plt.ylim((0, 140))
P.savefig(os.getcwd() + '/plot_FY_annual/quant/invest_type_{0}_{1}_{2}.png'.format(plot_set, theme, agg), dpi = my_dpi, figsize = (2000/my_dpi, 500/my_dpi), bbox_inches='tight')
# plt.show()
plt.close()
def get_agg(df):
df1 = df[df['Fiscal_Year'] < 2009]
df1 = df1.drop('Fiscal_Year', axis=1)
df2 = df[df['Fiscal_Year'] > 2013]
df2 = df2.drop('Fiscal_Year', axis=1)
df1_mean = df1.groupby('Building_Number').mean()
df1_mean.reset_index(inplace=True)
df1_mean['Fiscal_Year'] = 'FY2007 and FY2008'
df2_mean = df2.groupby('Building_Number').mean()
df2_mean.reset_index(inplace=True)
df2_mean['Fiscal_Year'] = 'FY2014 and FY2015'
df = pd.concat([df1_mean, df2_mean], ignore_index=True)
df.reset_index(inplace=True)
return df
def plot_co_boxtrend(plot_set, theme, ylimit, agg):
# df = pd.read_csv(master_dir + 'eui_by_fy_wcat.csv')
conn = uo.connect('all')
with conn:
df = pd.read_sql('SELECT * FROM eui_by_fy', conn)
if plot_set == 'AI':
ai_set = gbs.get_cat_set(['A', 'I'], conn)
# df = df[df['Cat'].isin(['A', 'I'])]
energy_set = gbs.get_energy_set(theme)
study_set = ai_set.intersection(energy_set)
df = df[df['Building_Number'].isin(energy_set)]
(cap_only, op_only, cap_and_op, cap_or_op) = gbs.get_invest_set()
df['Have any investment'] = df['Building_Number'].map(lambda x: 'With Investment' if x in cap_or_op else 'No Known Investment')
def classify(x):
if x in cap_only:
return 'Capital Only'
elif x in op_only:
return 'Operational Only'
elif x in cap_and_op:
return 'Capital and Operational'
elif x not in cap_or_op:
return 'No Capital or Operational'
if agg == 'ave':
df = get_agg(df)
df['Have any investment'] = df['Building_Number'].map(lambda x: 'With Investment' if x in cap_or_op else 'No Known Investment')
if agg != 'ave':
df['in_range'] = df['Fiscal_Year'].map(lambda x: 2006 < x and x <
2016)
df = df[df['in_range']]
df.sort('Fiscal_Year', inplace=True)
df['Fiscal_Year'] = df['Fiscal_Year'].map(lambda x: str(int(x)))
label_dict = {'With Investment': 'Yes', 'No Known Investment': 'No'}
size_dict = get_size(df, 'Have any investment', label_dict)
df.replace({'Fiscal_Year': size_dict}, inplace=True)
sns.set_style("whitegrid")
sns.set_context("talk", font_scale=1.2)
sns.set_palette(sns.color_palette('Set2'))
if agg == 'ave':
aspect = 1.5
else:
aspect = 2
g = sns.FacetGrid(df, aspect=aspect, size=6, legend_out=True)
g = g.map(sns.boxplot, x='Fiscal_Year', y='eui', hue='Have any investment', data=df, palette='Set2', fliersize=0)
df.groupby(['Fiscal_Year', 'Have any investment']).median().to_csv(homedir + 'temp/co_saving.csv')
# g.map(sns.stripplot, x='Fiscal_Year', y='eui', hue='Have any investment', data=df, jitter=0.3, size=1, color='dimgray', edgecolor='dimgray')
# sns.boxplot(x='Fiscal Year', y='eui', hue='Have any investment', data=df)
# sns.stripplot(x='Fiscal Year', y='eui', hue='Have any investment',
# data=df, jitter=0.3, size=1, color='dimgray',
# edgecolor='dimgray', label='_nolegend_')
df.groupby(['Fiscal_Year', 'Have any investment']).mean().to_csv(os.getcwd() + '/plot_FY_annual/quant_data/mean_with_{0}_{1}.csv'.format(plot_set, agg))
plt.subplots_adjust(top=0.87)
plt.legend(loc = 2, bbox_to_anchor=(1, 1))
if agg == 'ori':
plt.title('{1} Building {0} Distribution Trend'.format(lb.title_dict[theme], plot_set_label[plot_set]))
elif agg == 'ave':
plt.title('{1} Building Average {0} Distribution Trend'.format(lb.title_dict[theme], plot_set_label[plot_set]))
eng_ecm_str = '\n'.join(tw.wrap('with at least 6 years of Electric EUI >= 12 and Gas EUI >= 3 from FY2007 to FY2015', 50))
plt.suptitle('plot set: Building {0}'.format(eng_ecm_str))
plt.ylabel(lb.ylabel_dict[theme])
plt.ylim((0, 140))
P.savefig(os.getcwd() + '/plot_FY_annual/quant/invest_{0}_{1}_{2}.png'.format(plot_set, theme, agg), dpi = my_dpi, figsize = (2000/my_dpi, 500/my_dpi), bbox_inches='tight')
# plt.show()
plt.close()
def ecm_time_dist(plot_set):
df = pd.read_csv(master_dir + 'ECM/EUAS_ecm.csv')
df = df[df['high_level_ECM'].notnull()]
df = df[df['Substantial Completion Date'].notnull()]
if plot_set == 'AI':
ai_set = gbs.get_ai_set()
df = df[df['Building Number'].isin(ai_set)]
df['Calendar Year'] = df['Substantial Completion Date'].map(lambda x: x[:4])
years = set(df['Calendar Year'].tolist())
sns.set_context("talk", font_scale=1.5)
sns.set_palette(sns.color_palette('Set3'))
df.rename(columns={'high_level_ECM': 'High Level ECM Action'},
inplace=True)
sns.factorplot(x='Calendar Year', order=sorted(years),
hue='High Level ECM Action', data=df, kind='count', size=6, aspect=2)
plt.title('{0} Building ECM Action Completion Year Distribution'.format(plot_set_label[plot_set]))
plt.xlabel('Calendar Year')
plt.ylabel('Building Count')
P.savefig(os.getcwd() + '/plot_FY_annual/quant/ecm_time_{0}.png'.format(plot_set), dpi = my_dpi, figsize = (2000/my_dpi, 500/my_dpi), bbox_inches='tight')
# plt.show()
plt.close()
return
def get_time_label(status, yearlist):
if len(yearlist) > 1:
return '{0} (FY{1}--FY{2})'.format(status, *yearlist)
elif len(yearlist) == 1:
return '{0} (FY{1})'.format(status, *yearlist)
def compute_saving(theme, study_set, shape, pre_years, post_years):
conn = uo.connect('all')
with conn:
df = pd.read_sql('SELECT Building_Number, Fiscal_Year, eui_elec, eui_gas, eui FROM eui_by_fy', conn)
conn.close()
if study_set != None:
df = df[df['Building_Number'].isin(study_set)]
energy_set = gbs.get_energy_set(theme)
def agg(df, years):
df = df[df['Fiscal_Year'].isin(years)]
df = df.groupby(['Building_Number']).filter(lambda x: len(x)
== len(years))
df = df[df['Building_Number'].isin(energy_set)]
df = df[['Building_Number', theme]]
df_g = df.groupby('Building_Number').mean()
return df_g
df_pre = agg(df, pre_years)
df_post = agg(df, post_years)
print len(df_pre), len(df_post)
if shape == 'long':
df_pre['status'] = get_time_label('pre', pre_years)
df_post['status'] = get_time_label('post', post_years)
df_all = pd.concat([df_pre, df_post])
else:
df_all = pd.merge(df_pre, df_post, left_index=True,
right_index=True, suffixes=['_pre', '_post'])
df_all['saving amount'] = df_all[theme + '_pre'] - df_all[theme +
'_post']
df_all['saving percent'] = \
df_all['saving amount']/df_all[theme + '_pre'] * 100
print df_all.head()
return df_all
def timing(ori, current, funname):
print '{0} takes {1}s...'.format(funname, current - ori)
return current
def process_stat(df, col, label_yes, label_no, var, name, lines, dfs):
df_all = df.reset_index()
df_yes = df_all[df_all[col] == label_yes]
df_no = df_all[df_all[col] == label_no]
a = np.array(df_yes[var])
b = np.array(df_no[var])
ave_yes = np.average(a)
ave_no = np.average(b)
median_yes = np.median(a)
median_no = np.median(b)
print ave_yes, ave_no
result = stats.ttest_ind(a, b, equal_var=False)
t = result[0]
p = result[-1]
line = '{7},{0},{1},{2},{3},{4},{5},{6},{8},{9},{10},{11}'.format(var,label_yes, label_no, ave_yes, ave_no, t, p/2, name, len(a), len(b), median_yes, median_no)
print line
lines.append(line)
dfs.append(df_yes)
dfs.append(df_no)
if name == 'Capital Only':
print label_yes, len(label_yes)
# print df_yes['Building_Number'].unique()
print label_no, len(label_no)
# print df_no['Building_Number'].unique()
print set(df_yes['Building_Number'].tolist()).union(set(df_no['Building_Number'].tolist()))
return
def process_stat_no(df, col, label_yes, label_no, var, df_no, name, lines):
df_all = df.reset_index()
df_yes = df_all[df_all[col] == label_yes]
df_no = df_no[df_no[col] == label_no]
a = np.array(df_yes[var])
b = np.array(df_no[var])
ave_yes = np.average(a)
ave_no = np.average(b)
median_yes = np.median(a)
median_no = np.medianr(b)
print ave_yes, ave_no
result = stats.ttest_ind(a, b, equal_var=False)
t = result[0]
p = result[-1]
line = '{7},{0},{1},{2},{3},{4},{5},{6},{8},{9},{10},{11}'.format(var,label_yes, label_no, ave_yes, ave_no, t, p, name, len(a), len(b), median_yes, median_no)
print line
lines.append(line)
def test_hypo_covered(theme, plot_set, shape, pre_years, post_years):
ori = time.time()
energy_set = gbs.get_energy_set('eui')
if plot_set == 'AI':
cat_set = gbs.get_cat_set(['A', 'I'])
study_set = energy_set.intersection(cat_set)
else:
study_set = energy_set
df_all = compute_saving(theme, study_set, shape, pre_years, post_years)
conn = uo.connect('all')
with conn:
df_cover = pd.read_sql('SELECT DISTINCT Building_Number FROM covered_facility', conn)
covered_buildings = df_cover['Building_Number'].tolist()
df_all['Is Covered'] = df_all.index.map(lambda x: 'Covered' if x in covered_buildings else 'Not Covered')
lines = []
lines.append('name,variable,group A,group B,mean A,mean B,t,p,n_a,n_b,median A, median B')
dfs = []
gr = df_all.groupby('Is Covered')
pre_label = get_time_label('pre', pre_years)
post_label = get_time_label('post', post_years)
for name, group in gr:
print name
process_stat(group, 'status', pre_label, post_label, 'eui',
name, lines, dfs)
with open(os.getcwd() + '/plot_FY_annual/quant_data/hypotest_covered_{0}.csv'.format(plot_set), 'w+') as wt:
wt.write('\n'.join(lines))
df_all = pd.concat(dfs, ignore_index=True)
sns.barplot(x='Is Covered', order=['Covered', 'Not Covered'], hue='status', y='eui', hue_order = [pre_label, post_label], data=df_all)
plt.title('Average EUI reduction: pre (FY2007 and FY2008) vs. post (FY2014 and FY2015)')
eng_str = '\n'.join(tw.wrap('with at least 6 years of Electric EUI >= 12 and Gas EUI >= 3 from FY2007 to FY2015', 50))
plt.suptitle('plot set: building {0}'.format(eng_str))
# plt.show()
P.savefig(os.getcwd() + '/plot_FY_annual/quant/covered.png', dpi = my_dpi, figsize = (2000/my_dpi, 500/my_dpi), bbox_inches='tight')
plt.close()
def box_cap_op(theme, plot_set, shape, pre_years, post_years):
ori = time.time()
energy_set = gbs.get_energy_set('eui')
conn = uo.connect('all')
if plot_set == 'AI':
cat_set = gbs.get_cat_set(['A', 'I'], conn)
study_set = energy_set.intersection(cat_set)
elif plot_set == 'AIcovered':
cat_set = gbs.get_cat_set(['A', 'I'], conn)
covered_set = gbs.get_covered_set()
study_set = energy_set.intersection(cat_set.intersection(covered_set))
else:
study_set = energy_set
df_all = compute_saving(theme, study_set, shape, pre_years, post_years)
ori = timing(ori, time.time(), 'compute_saving')
(cap_only, op_only, cap_and_op, cap_or_op) = gbs.get_invest_set()
ori = timing(ori, time.time(), 'get_invest_set')
df_all['Investment'] = df_all.index.map(lambda x: 'With Investment' if x in cap_or_op else 'No Known Investment')
df_all['Investment Type'] = df_all.index.map(lambda x: classify_fullname(x, cap_only, op_only, cap_and_op, cap_or_op))
df_all.to_csv(homedir + 'temp/cap_op_eui.csv')
# print df_all['Investment Type'].value_counts()
# ori = timing(ori, time.time(), 'classify')
# eng_str = '\n'.join(tw.wrap('with at least 6 years of Electric EUI >= 12 and Gas EUI >= 3 from FY2007 to FY2015', 50))
# sns.set_style("whitegrid")
# sns.set_context("talk", font_scale=1)
# sns.set_palette(sns.color_palette('Set2'))
# # gr = df_all.groupby('Investment Type')
# gr = df_all.groupby('Investment')
# lines = []
# lines.append('name,variable,group A,group B,mean A,mean B,t,p,n_a,n_b,median A, median B')
# dfs = []
# pre_label = get_time_label('pre', pre_years)
# post_label = get_time_label('post', post_years)
# print pre_label, post_label
# with open(os.getcwd() + '/plot_FY_annual/quant_data/hypotest_abs_w_wout{0}.csv'.format(plot_set), 'w+') as wt:
# wt.write('\n'.join(lines))
# if plot_set == 'AIcovered':
# pointsize = 2
# sns.boxplot(x='Investment Type', order=['Capital and Operational', 'Operational Only'], hue='status', y='eui', hue_order = [pre_label, post_label], data=df_all, fliersize=0)
# # sns.stripplot(x='Investment Type', order=['Capital and Operational', 'Operational Only'], hue='status', y='eui', hue_order = [pre_label, post_label], data=df_all, jitter=0.3, size=pointsize, color='dimgray', edgecolor='dimgray', label='_nolegend_')
# else:
# pointsize = 1
# sns.boxplot(x='Investment Type', order=['Capital and Operational', 'Operational Only', 'Capital Only', 'No Known Investment'], hue='status', y='eui', hue_order = [pre_label, post_label], data=df_all, fliersize=0)
# # sns.stripplot(x='Investment Type', order=['Capital and Operational', 'Operational Only', 'Capital Only', 'No Known Investment'], hue='status', y='eui', hue_order = [pre_label, post_label], data=df_all, jitter=0.3, size=pointsize, color='dimgray', edgecolor='dimgray', label='_nolegend_')
# plt.title('Median EUI reduction: {0} vs. {1}'.format(pre_label, post_label))
# plt.ylim((0, 200))
# eng_str = '\n'.join(tw.wrap('with at least 6 years of Electric EUI >= 12 and Gas EUI >= 3 from FY2007 to FY2015', 50))
# plt.suptitle('plot set: building {0}'.format(eng_str))
# plt.show()
# # P.savefig(os.getcwd() + '/plot_FY_annual/quant/invest_box_{0}.png'.format(plot_set), dpi = my_dpi, figsize = (2000/my_dpi, 500/my_dpi), bbox_inches='tight')
# plt.close()
return
def test_hypo_absolute(theme, plot_set, shape, pre_years, post_years):
ori = time.time()
energy_set = gbs.get_energy_set('eui')
conn = uo.connect('all')
if plot_set == 'AI':
cat_set = gbs.get_cat_set(['A', 'I'], conn)
study_set = energy_set.intersection(cat_set)
elif plot_set == 'AIcovered':
cat_set = gbs.get_cat_set(['A', 'I'], conn)
covered_set = gbs.get_covered_set()
study_set = energy_set.intersection(cat_set.intersection(covered_set))
else:
study_set = energy_set
df_all = compute_saving(theme, study_set, shape, pre_years, post_years)
ori = timing(ori, time.time(), 'compute_saving')
(cap_only, op_only, cap_and_op, cap_or_op) = gbs.get_invest_set()
ori = timing(ori, time.time(), 'get_invest_set')
df_all['Investment'] = df_all.index.map(lambda x: 'With Investment' if x in cap_or_op else 'No Known Investment')
df_all['Investment Type'] = df_all.index.map(lambda x: classify_fullname(x, cap_only, op_only, cap_and_op, cap_or_op))
print df_all['Investment Type'].value_counts()
ori = timing(ori, time.time(), 'classify')
eng_str = '\n'.join(tw.wrap('with at least 6 years of Electric EUI >= 12 and Gas EUI >= 3 from FY2007 to FY2015', 50))
sns.set_style("whitegrid")
sns.set_context("talk", font_scale=1)
# bookmark
# sns.set_palette(sns.color_palette('Set2'))
sns.set_palette(sns.color_palette(["#FC8D62", "#66C2A5"]))
# gr = df_all.groupby('Investment Type')
gr = df_all.groupby('Investment')
lines = []
lines.append('name,variable,group A,group B,mean A,mean B,t,p,n_a,n_b,median A, median B')
dfs = []
pre_label = get_time_label('pre', pre_years)
post_label = get_time_label('post', post_years)
print pre_label, post_label
# if plot_set == 'AIcovered':
# names = ['Capital and Operational', 'Operational Only']
# else:
# names = gr.groups.keys()
# print names
# for name, group in gr:
# print name
# for name in names:
# print name, '1111111111111'
# group = gr.get_group(name)
# process_stat(group, 'status', post_label, pre_label, 'eui',
# name, lines, dfs)
# process_stat(df_all, 'status', post_label, pre_label, 'eui', 'all',
# lines, dfs)
# df_all = pd.concat(dfs, ignore_index=True)
# print df_all['status'].value_counts()
with open(os.getcwd() + '/plot_FY_annual/quant_data/hypotest_abs_w_wout{0}.csv'.format(plot_set), 'w+') as wt:
wt.write('\n'.join(lines))
# sns.barplot(x='Investment Type', order=['Capital and Operational', 'Operational Only', 'Capital Only', 'No Known Investment'], hue='status', y='eui', hue_order = [pre_label, post_label], data=df_all)
# sns.boxplot(x='Investment Type', order=['Capital and Operational', 'Operational Only', 'Capital Only', 'No Known Investment'], hue='status', y='eui', hue_order = [pre_label, post_label], data=df_all)
if plot_set == 'AIcovered':
pointsize = 2
sns.boxplot(x='Investment Type', order=['Capital and Operational', 'Operational Only'], hue='status', y='eui', hue_order = [pre_label, post_label], data=df_all, fliersize=0)
# sns.stripplot(x='Investment Type', order=['Capital and Operational', 'Operational Only'], hue='status', y='eui', hue_order = [pre_label, post_label], data=df_all, jitter=0.3, size=pointsize, color='dimgray', edgecolor='dimgray', label='_nolegend_')
else:
pointsize = 1
sns.boxplot(x='Investment Type', order=['Capital and Operational', 'Operational Only', 'Capital Only', 'No Known Investment'], hue='status', y='eui', hue_order = [pre_label, post_label], data=df_all, fliersize=0)
# sns.stripplot(x='Investment Type', order=['Capital and Operational', 'Operational Only', 'Capital Only', 'No Known Investment'], hue='status', y='eui', hue_order = [pre_label, post_label], data=df_all, jitter=0.3, size=pointsize, color='dimgray', edgecolor='dimgray', label='_nolegend_')
plt.title('Median EUI reduction: {0} vs. {1}'.format(pre_label, post_label))
plt.ylim((0, 200))
eng_str = '\n'.join(tw.wrap('with at least 6 years of Electric EUI >= 12 and Gas EUI >= 3 from FY2007 to FY2015', 50))
plt.suptitle('plot set: building {0}'.format(eng_str))
# plt.show()
P.savefig(os.getcwd() + '/plot_FY_annual/quant/invest_box_{0}.png'.format(plot_set), dpi = my_dpi, figsize = (2000/my_dpi, 500/my_dpi), bbox_inches='tight')
plt.close()
# no use now
# no_invest = gr.get_group('No Known Investment')
# lines = []