-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_build.py
executable file
·1748 lines (1661 loc) · 73.9 KB
/
db_build.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
import sqlite3
import pandas as pd
import numpy as np
import os
import glob
import re
import ast
import time
import seaborn as sns
import matplotlib.pyplot as plt
import util
import util_io as uo
import lean_temperature_monthly as ltm
import get_building_set as gbs
homedir = os.getcwd() + '/csv_FY/'
tempdir = homedir + 'temp_data_view/'
master_dir = homedir + 'master_table/'
weatherdir = os.getcwd() + '/csv_FY/weather/'
pro_dir = '/media/yujiex/work/project/data/'
def to_sql(excel, sheet_ids, conn):
filename = excel[excel.find('FY1'):]
for i in sheet_ids:
df = pd.read_excel(excel, sheetname=i)
# filter out records with empty name
df = df[pd.notnull(df['Building Number'])]
outfile = '{0}_{1}'.format(filename[:4], i + 1)
print 'write to file: ' + outfile
df.to_sql(outfile, conn, if_exists='replace', index=False)
return
def excel2csv():
print 'excel2csv...'
conn = sqlite3.connect(homedir + 'db/energy_input.db')
c = conn.cursor()
filelist = glob.glob(os.getcwd() + '/input/FY/EUAS/' + '*.xlsx')
print filelist
for excel in filelist:
filename = excel[excel.find('FY1'):]
print 'processing {0}'.format(filename)
# check_sheetname(excel, False)
to_sql(excel, range(11), conn)
conn.close()
return
def check_small_area(cutoff):
conn = uo.connect('all')
df = pd.read_sql('SELECT DISTINCT Building_Number, [Gross_Sq.Ft] FROM EUAS_area WHERE [Gross_Sq.Ft] < {0} ORDER BY [Gross_Sq.Ft] DESC'.format(cutoff), conn)
# print df
return df
def check_change_area():
conn = uo.connect('all')
df = pd.read_sql('SELECT DISTINCT Building_Number, [Gross_Sq.Ft] FROM EUAS_area', conn)
print df.head(n=20)
print len(df)
df2 = df.groupby('Building_Number').filter(lambda x: len(x) > 1)
df2.to_csv(homedir + 'temp/change_area.csv', index=False)
return
def check_change_cat():
conn = uo.connect('all')
df = pd.read_sql('SELECT DISTINCT Building_Number, Cat FROM EUAS_monthly', conn)
print len(df)
df2 = df.groupby('Building_Number').filter(lambda x: len(x) > 1)
print len(df2)
df2.to_csv(homedir + 'temp/change_cat.csv', index=False)
return
def view_building(b, col):
conn = uo.connect('all')
df = pd.read_sql('SELECT DISTINCT Building_Number, Fiscal_Year, Fiscal_Month, year, month, [Gross_Sq.Ft], [Region_No.], Cat, [{1}] FROM EUAS_monthly WHERE Building_Number = \'{0}\''.format(b, col), conn)
return df
def dump_file(f, ext, conn):
filename = f[f.rfind('/') + 1:]
year_pattern = re.compile("20[0-9]{2}")
year = year_pattern.search(filename).group(0)
region_pattern = re.compile("[0-9]{1,2}")
region = region_pattern.search(filename).group(0)
if ext == 'excel':
df = pd.read_excel(f, sheetname=0)
elif ext == 'csv':
df = pd.read_csv(f)
df = df[df['Building Number'].notnull()]
outfile = 'FY{0}_{1}'.format(year[-2:], region)
print 'write to file: ' + outfile
df.to_sql(outfile, conn, if_exists='replace', index=False)
return
def excel2csv_singlesheet():
conn = sqlite3.connect(homedir + 'db/energy_input.db')
files = glob.glob(os.getcwd() + \
'/input/FY/EUAS/*/*.xlsx')
for i, f in enumerate(files):
# print i, f[f.rfind('/') + 1:]
dump_file(f, 'excel', conn)
# need to manually save .xls to .csv
files = glob.glob(os.getcwd() + '/input/FY/EUAS/*/*.csv')
for i, f in enumerate(files):
# print i, f[f.rfind('/') + 1:]
dump_file(f, 'csv', conn)
conn.close()
def copy_table_helper(conn, conn2, table):
with conn:
df = pd.read_sql('SELECT * FROM {0}'.format(table), conn)
with conn2:
df.to_sql(table, conn2, if_exists='replace')
def copy_table():
conn = uo.connect('all')
conn2 = uo.connect('all_back')
# copy_table_helper(conn, conn2, 'EUAS_monthly')
copy_table_helper(conn, conn2, 'eui_by_fy')
print 'end'
return
def copy_tables():
conn = uo.connect('backup/all')
cursor = conn.cursor()
tables = util.get_list_tables(cursor)
conn2 = uo.connect('all_back')
tables = [x for x in tables if '_test' not in x]
tables = [x for x in tables if x != 'Temperature_Hour_UTC']
for t in tables:
print 'copy table: {0}'.format(t)
copy_table_helper(conn, conn2, t)
print 'end'
return
def compare():
conn = uo.connect('all')
conn2 = uo.connect('all_back')
df1 = pd.read_sql('SELECT DISTINCT Building_Number, Fiscal_Year FROM EUAS_monthly', conn).groupby('Fiscal_Year').count()[['Building_Number']]
df2 = pd.read_sql('SELECT DISTINCT Building_Number, Fiscal_Year FROM EUAS_monthly', conn2).groupby('Fiscal_Year').count()[['Building_Number']]
df = pd.merge(df1, df2, left_index=True, right_index=True, suffixes=['_new', '_old'])
print
print df
# with conn:
# df1 = pd.read_sql('SELECT DISTINCT Building_Number, Fiscal_Year FROM EUAS_monthly', conn)
# with conn2:
# df2 = pd.read_sql('SELECT DISTINCT Building_Number, Fiscal_Year FROM EUAS_monthly', conn2)
# df1['status'] = 'new'
# df2['status'] = 'old'
# df_all = pd.concat([df1, f2], ignore_index=True)
# df_all.groupby('Building_Number').filter(lambda x: len(x) < 2)
# df_all.to_csv(homedir + 'temp/euas_building_cmp.csv')
# with conn:
# df1 = pd.read_sql('SELECT * FROM EUAS_category', conn)
# df2 = pd.read_sql('SELECT * FROM EUAS_category', conn2)
# df = pd.merge(df1, df2, on='Building_Number', how='outer', suffixes=['_new', '_old'])
# df['equal'] = df.apply(lambda r: r['Cat_new'] == r['Cat_old'], axis=1)
# print df.head()
# df = df[df['equal'] == False]
# print df.head()
# df.to_csv(homedir + 'temp/euas_cat_cmp.csv', index=False)
# return
# with conn:
# df1 = pd.read_sql('SELECT Fiscal_Year, eui FROM eui_by_fy', conn)
# df2 = pd.read_sql('SELECT Fiscal_Year, eui FROM eui_by_fy', conn2)
# df1 = df1[df1['eui'] != np.inf]
# df2 = df2[df2['eui'] != np.inf]
# print 'new'
# print df1.groupby('Fiscal_Year').count()
# print 'old'
# print df2.groupby('Fiscal_Year').count()
def clean_energy(df_all):
df_all['year'] = df_all.apply(lambda row:
util.fiscal2calyear(row['Fiscal' +
'_Year'], row['Fiscal_Month']),
axis=1)
df_all['month'] = df_all['Fiscal_Month'].map(util.fiscal2calmonth)
df_all['Electric_(kBtu)'] = df_all['Electricity_(KWH)'] * 3.412
df_all['Gas_(kBtu)'] = df_all['Gas_(Cubic_Ft)'] * 1.026
m_oil = (139 + 138 + 146 + 150)/4
df_all['Oil_(kBtu)'] = df_all['Oil_(Gallon)'] * m_oil
df_all['Steam_(kBtu)'] = df_all['Steam_(Thou._lbs)'] * 1194
df_all['Electric_(kBtu)'] = df_all['Electric_(kBtu)'].map(np.float64)
df_all['Gas_(kBtu)'] = df_all['Gas_(kBtu)'].map(np.float64)
df_all['Oil_(kBtu)'] = df_all['Oil_(kBtu)'].map(np.float64)
df_all['Steam_(kBtu)'] = df_all['Steam_(kBtu)'].map(np.float64)
df_all['Water_(Gallon)'] = df_all['Water_(Gallon)'].map(np.float64)
df_all['Gross_Sq.Ft'] = df_all['Gross_Sq.Ft'].map(np.float64)
df_all['eui_elec'] = \
df_all['Electric_(kBtu)']/df_all['Gross_Sq.Ft']
df_all['Total_(kBtu)'] = df_all[['Electric_(kBtu)', 'Gas_(kBtu)',
'Oil_(kBtu)', 'Steam_(kBtu)']].sum(axis=1)
df_all['eui_gas'] = df_all['Gas_(kBtu)']/df_all['Gross_Sq.Ft']
df_all['eui_oil'] = df_all['Oil_(kBtu)']/df_all['Gross_Sq.Ft']
df_all['eui_steam'] = df_all['Steam_(kBtu)']/df_all['Gross_Sq.Ft']
df_all['eui_water'] = df_all['Water_(Gallon)']/df_all['Gross_Sq.Ft']
df_all['eui'] = df_all['eui_elec'] + df_all['eui_gas']
df_all['eui_total'] = df_all['Total_(kBtu)']/df_all['Gross_Sq.Ft']
df_all.replace(util.get_state_abbr_dict(), inplace=True)
df_all.replace('******', np.nan, inplace=True) #take too long
print(list(df_all))
df_f = df_all.sort_values(by=['Building_Number', 'Fiscal_Year', 'Fiscal_Month'])
return df_f
def concat():
conn = sqlite3.connect(homedir + 'db/energy_input.db')
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
tables = [x[0] for x in cursor.fetchall()]
queries = ['SELECT * FROM {0}'.format(t) for t in tables]
with conn:
dfs = [pd.read_sql(q, conn) for q in queries]
conn.close()
df_all = pd.concat(dfs, join='outer', ignore_index=True)
df_all.dropna(axis=1, inplace=True, how='all')
clean_energy(df_all)
df_temp = df_f[df_f['Building_Number'] == 'PA0600ZZ']
print df_temp[['Fiscal_Year', 'Fiscal_Month', 'eui_gas']]
# conn = sqlite3.connect(homedir + 'db/all.db')
# with conn:
# df_f.to_sql('EUAS_monthly', conn, if_exists='replace')
# conn.close()
print 'end'
return
def get_eui_weather():
conn = sqlite3.connect(homedir + 'db/all.db')
with conn:
df1 = pd.read_sql('SELECT * FROM EUAS_monthly_weather', conn)
df2 = pd.read_sql('SELECT Building_Number, Cat FROM EUAS_category', conn)
df = pd.merge(df1, df2, on='Building_Number', how='left')
df = df[df['eui_total'] != np.inf]
df.info()
df_f = df.groupby(['Building_Number', 'Fiscal_Year']).agg({'Cat': 'first', 'eui_elec': 'sum', 'eui_gas': 'sum', 'eui': 'sum', 'eui_total': 'sum', 'hdd65':'sum', 'cdd65': 'sum'})
df_f.reset_index(inplace=True)
df_f = df_f[['Building_Number', 'Fiscal_Year', 'Cat', 'eui_elec', 'eui_gas', 'eui', 'eui_total', 'hdd65', 'cdd65']]
df_f['eui_gas_perdd'] = df_f['eui_gas']/df_f['hdd65']
df_f['eui_elec_perdd'] = df_f['eui_elec']/df_f['cdd65']
df_f['eui_perdd'] = df_f['eui_gas_perdd'] + df_f['eui_elec_perdd']
df_f.sort_values(['Building_Number', 'Fiscal_Year'], inplace=True)
df_f.info()
# def get_status(e, g):
# if e >= 12 and g >= 3:
# return 'Electric EUI >= 12 and Gas EUI >= 3'
# elif e >= 12 and g < 3:
# return 'Low Gas EUI'
# elif e < 12 and g >= 3:
# return 'Low Electric EUI'
# else:
# return 'Low Gas and Electric EUI'
# print df_f.groupby(['Fiscal_Year']).count()[['Building_Number']]
# df_f['status'] = df_f.apply(lambda r: get_status(r['eui_elec'],
# r['eui_gas']),
# axis=1)
# print df_f['status'].value_counts()
with conn:
df_f.to_sql('eui_by_fy_weather', conn, if_exists='replace')
print 'end'
return
# compute eui of each single building
# eui_total != np.inf removes records with zero square footage but
# non-zero gas/oil/steam/electric consumption
def get_eui():
conn = sqlite3.connect(homedir + 'db/all.db')
df = pd.read_sql('SELECT * FROM EUAS_monthly_weather', conn)
df = df[df['eui_total'] != np.inf]
df.info()
# df_f = df.groupby(['Building_Number', 'Fiscal_Year']).sum()
df_f = df.groupby(['Building_Number', 'Fiscal_Year']).agg({'Gross_Sq.Ft': 'mean', 'Cat': 'first', 'eui_elec': 'sum', 'eui_gas': 'sum', 'eui_oil': 'sum', 'eui_steam': 'sum', 'eui_water': 'sum', 'eui': 'sum', 'eui_total': 'sum', 'eui':'sum', 'hdd65':'sum', 'cdd65': 'sum'})
df_f.reset_index(inplace=True)
df_f = df_f[['Building_Number', 'Fiscal_Year', 'Cat', 'Gross_Sq.Ft', 'eui_elec', 'eui_gas', 'eui_oil', 'eui_steam', 'eui_water', 'eui', 'eui_total', 'hdd65', 'cdd65']]
df_f.sort_values(['Building_Number', 'Fiscal_Year'], inplace=True)
df_f.info()
def get_status(e, g):
if e >= 12 and g >= 3:
return 'Electric EUI >= 12 and Gas EUI >= 3'
elif e >= 12 and g < 3:
return 'Low Gas EUI'
elif e < 12 and g >= 3:
return 'Low Electric EUI'
else:
return 'Low Gas and Electric EUI'
print df_f.groupby(['Fiscal_Year']).count()[['Building_Number']]
df_f['status'] = df_f.apply(lambda r: get_status(r['eui_elec'],
r['eui_gas']),
axis=1)
print df_f['status'].value_counts()
# with conn:
# df_f.to_sql('eui_by_fy', conn, if_exists='replace')
print 'end'
return
def check_num():
conn = sqlite3.connect(homedir + 'db/all.db')
df = pd.read_sql('SELECT DISTINCT Building_Number, Fiscal_Year FROM EUAS_monthly', conn)
print df.groupby(['Fiscal_Year']).count()
return
def get_geo_input(d):
tokens = [d['Street_Address'], d['City'], d['State'],
d['Zip_Code']]
zipcode = tokens[-1]
# print zipcode, type(zipcode)
if (type (zipcode) != float) and (len(zipcode) == 9):
tokens[-1] = '{0}-{1}'.format(zipcode[:5], zipcode[-4:])
tokens = [x for x in tokens if (type(x) != float) and (x != None)]
return ','.join(tokens)
def join_static():
conn = sqlite3.connect(homedir + 'db/other_input.db')
df2 = pd.read_sql('SELECT DISTINCT Building_Number, Street_Address, City, Zip_Code FROM Entire_GSA_Building_Portfolio_input', conn)
df2['source'] = 'Entire_GSA_Building_Portfolio_input'
df_use = pd.read_sql('SELECT DISTINCT Building_Number, Street_Address, City, Zip_Code FROM PortfolioManager_sheet0_input', conn)
df3 = pd.read_sql('SELECT DISTINCT Building_Number, Street_Address, City FROM euas_database_of_buildings_cmu', conn)
conn.close()
df3['source'] = 'euas_database_of_buildings_cmu'
df_use['source'] = 'PortfolioManager_sheet0_input'
df_loc = pd.concat([df2, df_use, df3], ignore_index=True)
df_loc.sort_values(by=['Building_Number', 'source'], inplace=True)
conn = sqlite3.connect(homedir + 'db/all.db')
df1 = pd.read_sql('SELECT DISTINCT Building_Number, State FROM EUAS_monthly', conn)
df_loc.to_sql('building_address_source', conn, if_exists='replace')
df_loc.drop_duplicates(subset=['Building_Number', 'Street_Address', 'City',
'Zip_Code'], inplace=True)
df_loc.to_sql('building_address_source_unique', conn, if_exists='replace')
df_all = pd.merge(df1, df_loc, how='left', on='Building_Number')
df_all['geocoding_input'] = df_all.apply(get_geo_input, axis=1)
df_all.to_sql('EUAS_address', conn, if_exists='replace')
# df_all.to_csv(tempdir + 'EUAS_address.csv')
conn.close()
print 'end'
return
def gsalink_address_geocoding():
df = pd.read_csv(os.getcwd() + '/input/FY/GSAlink 81 Buildings Updated 9_22_15.csv')
df.rename(columns={'Building ID': 'Building_Number', 'Street': 'Street_Address', 'Zip Code': 'Zip_Code'}, inplace=True)
df = df[['Building_Number', 'Street_Address', 'City', 'State',
'Zip_Code']]
df['geocoding_input'] = df.apply(get_geo_input, axis=1)
keys = (df['geocoding_input'].unique())
d = geocoding_cache(keys)
df2 = pd.DataFrame({'geocoding_input': d.keys(), 'latlng':
d.values()})
df_all = pd.merge(df, df2, on='geocoding_input', how='left')
df_all.to_csv(homedir + 'temp/geocoding_gsalink.csv')
conn = uo.connect('all')
with conn:
df_all.to_sql('gsalink_address', conn, if_exists='replace')
conn.close()
return
def geocoding_cache(keys):
d = {}
for i, k in enumerate(keys):
print i
if not k in d:
d[k] = str(util.get_lat_long(k))
time.sleep(0.03)
return d
def geocoding():
conn = sqlite3connect(homedir + 'db/all.db')
df = pd.read_sql('SELECT DISTINCT Building_Number, geocoding_input FROM EUAS_address', conn)
keys = (df['geocoding_input'].unique())
d = geocoding_cache(keys)
df2 = pd.DataFrame({'geocoding_input': d.keys(), 'latlng':
d.values()})
df_all = pd.merge(df, df2, on='geocoding_input', how='left')
# print df_all.head()
df_all.to_sql('EUAS_latlng', conn, if_exists='replace')
conn.close()
print 'end'
return
def get_start_end():
conn = sqlite3.connect(homedir + 'db/all.db')
df = pd.read_sql('SELECT year, month, Building_Number FROM EUAS_monthly', conn)
df['year'] = df['year'].map(int)
df['month'] = df['month'].map(int)
df.sort_values(['Building_Number', 'year', 'month'], inplace=True)
df_min = df.groupby('Building_Number').first()
df_max = df.groupby('Building_Number').last()
df_min['Date_min'] = df_min.apply(lambda r: '{0}-{1}-1 00:00:00'.format(r['year'], r['month']), axis=1)
df_min = df_min[['Date_min']]
print df_min.head()
df_max['Date_max'] = df_max.apply(lambda r: '{0}-{1}-{2} 23:59:59'.format(r['year'], r['month'], util.get_month_lastday(r['year'], r['month'])), axis=1)
df_max = df_max[['Date_max']]
print df_max.head()
df_all = pd.merge(df_min, df_max, left_index=True, right_index=True, how='inner')
print df_all.head()
df_all.reset_index(inplace=True)
df_all.to_sql('EUAS_energy_daterange', conn, if_exists='replace')
return
# download hourly temperature station into a separate database file
# containing a table of downloaded stations
def download_weather_sep_db_gsa(test):
if test:
conn_w = sqlite3.connect(homedir + 'db/gsalink_utc_test.db')
c_w = conn_w.cursor()
else:
conn_w = sqlite3.connect(homedir + 'db/gsalink_utc.db')
c_w = conn_w.cursor()
conn = sqlite3.connect(homedir + 'db/all.db')
c = conn.cursor()
df = pd.read_csv(homedir + 'temp/geocoding_gsalink.csv')
df.info()
# with conn:
# df = pd.read_sql('SELECT Building_Number, Latlng FROM gsalink_address', conn)
buildings = df['Building_Number'].tolist()
latlngs = df['latlng'].tolist()
print len(buildings), len(latlngs)
length = 5
stations = []
dists = []
bs = []
ll = []
downloaded = set()
no_data = set()
bs_list = zip(buildings, latlngs)
if test:
bs_list = bs_list[:5]
for i, (b, loc) in enumerate(bs_list):
latlng = ast.literal_eval(loc)
print i, b, latlng
sd_list = util.get_station_dist(b, latlng, length)
print sd_list
mindate = '2010-9-1T00:00:00Z'
maxdate = '2016-6-27T00:00:00Z'
station = 'Not Found'
dist = -1
for s, d in sd_list:
if s in downloaded:
print '{0} exist'.format(s)
station = s
dist = d
break
elif s in no_data:
print '{0} has no data'.format(s)
continue
else:
ori = time.time()
df = ltm.get_weather_data(s, mindate, maxdate, 'H')
if df is None:
print '{0} has no data'.format(s)
no_data.add(s)
continue
df['ICAO'] = s
station = s
dist = d
df.rename(columns={s: 'Temperature_F', 'index':
'Timestamp'}, inplace=True)
df['Timestamp'] = df.index.map(lambda x: x.strftime('%Y-%m-%d %H:%M:%S'))
with conn_w:
df.to_sql(s, conn_w, if_exists='replace')
break
bs.append(b)
ll.append(loc)
stations.append(station)
dists.append(dist)
downloaded.add(station)
# print len(buildings), len(latlngs), len(stations), len(dists), '11111'
df_station = pd.DataFrame({'Building_Number': bs, 'latlng': ll, 'ICAO': stations, 'Distance_Mile': dists})
if test:
df_station.to_sql('gsalink_weather_station_test', conn, if_exists='replace')
else:
df_station.to_sql('gsalink_weather_station', conn, if_exists='replace')
df_downloaded = pd.DataFrame({'ICAO': list(downloaded)})
df_nodata = pd.DataFrame({'ICAO': list(no_data)})
with conn_w:
df_downloaded.to_sql('downloaded', conn_w, if_exists='replace')
df_nodata.to_sql('nodata', conn_w, if_exists='replace')
conn_w.close()
conn.close()
return
# download hourly temperature station into a separate database file
# containing a table of downloaded stations
def download_weather_sep_db(test, step, db_prefix, variable):
if test:
conn_w = sqlite3.connect(homedir + 'db/{}_test_17.db'.format(db_prefix))
c_w = conn_w.cursor()
else:
conn_w = sqlite3.connect(homedir + 'db/{}_17.db'.format(db_prefix))
c_w = conn_w.cursor()
conn = sqlite3.connect(homedir + 'db/all.db')
c = conn.cursor()
with conn:
df = pd.read_sql('SELECT Building_Number, Latlng FROM EUAS_latlng_2', conn)
buildings = df['Building_Number'].tolist()
latlngs = df['latlng'].tolist()
print len(buildings), len(latlngs)
length = 5
stations = []
dists = []
bs = []
ll = []
downloaded = set()
no_data = set()
bs_list = zip(buildings, latlngs)
col_rename_dict = {'temperature': 'Temperature_F', 'HDD': 'HDD', 'CDD': 'CDD'}
if test:
bs_list = bs_list[:5]
for i, (b, loc) in enumerate(bs_list):
try:
latlng = ast.literal_eval(loc)
except ValueError:
print 'malformed latlng'
continue
print i, b, latlng
sd_list = util.get_station_dist(b, latlng, length)
print sd_list
mindate = '2002-9-30T00:00:00Z'
maxdate = '2017-10-1T00:00:00Z'
station = 'Not Found'
dist = -1
for s, d in sd_list:
if s in downloaded:
print '{0} exist'.format(s)
station = s
dist = d
break
elif s in no_data:
print '{0} has no data'.format(s)
continue
else:
ori = time.time()
df = ltm.get_weather_data(s, mindate, maxdate, step, variable)
if df is None:
print '{0} has no data'.format(s)
no_data.add(s)
continue
df['ICAO'] = s
station = s
dist = d
df.rename(columns={s: col_rename_dict[variable], 'index':
'Timestamp'}, inplace=True)
df['Timestamp'] = df.index.map(lambda x: x.strftime('%Y-%m-%d %H:%M:%S'))
print df.head()
with conn_w:
df.to_sql(s, conn_w, if_exists='replace', index=False)
break
bs.append(b)
ll.append(loc)
stations.append(station)
dists.append(dist)
downloaded.add(station)
# print len(buildings), len(latlngs), len(stations), len(dists), '11111'
df_station = pd.DataFrame({'Building_Number': bs, 'latlng': ll, 'ICAO': stations, 'Distance_Mile': dists})
if test:
df_station.to_sql('building_weather_station_test', conn, if_exists='replace')
else:
df_station.to_sql('building_weather_station', conn, if_exists='replace')
df_downloaded = pd.DataFrame({'ICAO': list(downloaded)})
df_nodata = pd.DataFrame({'ICAO': list(no_data)})
with conn_w:
df_downloaded.to_sql('downloaded', conn_w, if_exists='replace')
df_nodata.to_sql('nodata', conn_w, if_exists='replace')
conn_w.close()
conn.close()
return
def download_weather(test):
conn = sqlite3.connect(homedir + 'db/all.db')
c = conn.cursor()
if test:
c.execute("DROP TABLE IF EXISTS Temperature_Hour_UTC_test")
c.execute('CREATE TABLE Temperature_Hour_UTC_test (ICAO text KEY, Timestamp text KEY, Temperature_F real);')
else:
c.execute("DROP TABLE IF EXISTS Temperature_Hour_UTC")
c.execute('CREATE TABLE Temperature_Hour_UTC (ICAO text KEY, Timestamp text KEY, Temperature_F real);')
df = pd.read_sql('SELECT Building_Number, Latlng FROM EUAS_latlng_', conn)
buildings = df['Building_Number'].tolist()
latlngs = df['latlng'].tolist()
print len(buildings), len(latlngs)
length = 5
stations = []
dists = []
bs = []
ll = []
downloaded = set()
no_data = set()
bs_list = zip(buildings, latlngs)
if test:
bs_list = bs_list[:5]
for i, (b, loc) in enumerate(bs_list):
latlng = ast.literal_eval(loc)
print i, b, latlng
sd_list = util.get_station_dist(b, latlng, length)
print sd_list
mindate = '2002-9-30T00:00:00Z'
maxdate = '2016-5-1T00:00:00Z'
station = 'Not Found'
dist = -1
for s, d in sd_list:
if s in downloaded:
print '{0} exist'.format(s)
station = s
dist = d
break
elif s in no_data:
print '{0} has no data'.format(s)
continue
else:
ori = time.time()
df = ltm.get_weather_data(s, mindate, maxdate, 'H')
if df is None:
print '{0} has no data'.format(s)
no_data.add(s)
continue
df['ICAO'] = s
station = s
dist = d
df.rename(columns={s: 'Temperature_F', 'index':
'Timestamp'}, inplace=True)
df['Timestamp'] = df.index.map(lambda x: x.strftime('%Y-%m-%d %H:%M:%S'))
if test:
df.to_sql('Temperature_Hour_UTC_test', conn,
if_exists='append')
else:
df.to_sql('Temperature_Hour_UTC', conn,
if_exists='append')
break
bs.append(b)
ll.append(loc)
stations.append(station)
dists.append(dist)
downloaded.add(station)
# print len(buildings), len(latlngs), len(stations), len(dists), '11111'
df_station = pd.DataFrame({'Building_Number': bs, 'latlng': ll, 'ICAO': stations, 'Distance_Mile': dists})
if test:
df_station.to_sql('building_weather_station_test', conn, if_exists='replace')
else:
df_station.to_sql('building_weather_station', conn, if_exists='replace')
conn.close()
return
def db_view_alltable(db):
conn = sqlite3.connect(homedir + 'db/{0}.db'.format(db))
c = conn.cursor()
tables = util.get_list_tables(c)
tables.remove('Temperature_Hour_UTC')
for t in tables:
print
print t
print
util.describe_table(conn, t, False)
conn.close()
return
def db_view(db, header, *args):
conn = sqlite3.connect(homedir + 'db/{0}.db'.format(db))
c = conn.cursor()
tables = util.get_list_tables(c)
for t in tables:
print t
if len(args) == 0:
t = tables[-1]
else:
t = args[0]
print
print t
print
util.describe_table(conn, t, header)
conn.close()
return
# 'AVG(Temperature_F)'
# print timezone and offset to stdout
def get_bd_timezone_output():
conn = uo.connect('all')
with conn:
df = pd.read_sql('SELECT DISTINCT Building_Number, ICAO, latlng FROM EUAS_monthly_weather', conn)
bl = zip(df['Building_Number'], df['latlng'])
print len(bl)
for i, (b, l) in enumerate(bl):
latlng = ast.literal_eval(l)
util.get_timezone(latlng[0], latlng[1], b, i)
time.sleep(0.1)
def timezone2db():
df = pd.read_csv(homedir + 'EUAS_timezone.csv')
conn = uo.connect('all')
with conn:
df.to_sql('EUAS_timezone', conn, if_exists='replace')
print 'end'
conn.close()
conn = uo.connect('interval_ion')
with conn:
df.to_sql('EUAS_timezone', conn, if_exists='replace')
print 'end'
conn.close()
def interval_availability():
conn = uo.connect('all')
conn2 = uo.connect('interval_ion')
with conn:
df = pd.read_sql('SELECT DISTINCT Building_Number, latlng FROM EUAS_monthly_weather', conn)
with conn2:
df2 = pd.read_sql('SELECT DISTINCT id FROM electric_id', conn2)
df3 = pd.read_sql('SELECT DISTINCT id FROM gas_id', conn2)
df4 = pd.concat([df2, df3], ignore_index=True)
print len(df4)
df4.drop_duplicates(inplace=True)
print len(df4)
df4.rename(columns={'id': 'Building_Number'}, inplace=True)
df_all = pd.merge(df4, df, on='Building_Number')
df_all.to_csv(pro_dir + 'interval_latlng.csv', index=False)
conn.close()
conn2.close()
def aggregate_sep_station(method):
conn = sqlite3.connect(homedir + 'db/weather_hourly_utc.db')
c = conn.cursor()
if method == 'ave':
agg_fun_str = 'AVG(Temperature_F) '
elif method == 'hdd65':
base = float(method[-2:])
agg_fun_str = 'SUM(MAX(65.0 - Temperature_F, 0.0))/24.0 '.format(base)
elif method == 'cdd65':
base = float(method[-2:])
agg_fun_str = 'SUM(MAX(Temperature_F - {0}, 0.0))/24.0 '.format(base)
print '11111111111111111'
c.execute('DROP TABLE IF EXISTS weather_{0}'.format(method))
c.execute('CREATE TABLE weather_{0} (month text KEY, year text KEY, ICAO text KEY, {0} real);'.format(method))
print '11111111111111111'
with conn:
downloaded = pd.read_sql('SELECT * FROM downloaded', conn)['ICAO'].tolist()
print len(downloaded)
for i, table in enumerate(downloaded):
print i, table
query = 'INSERT INTO weather_{0} '.format(method) + \
'SELECT strftime(\'%m\', Timestamp) as month,' + \
'strftime(\'%Y\', Timestamp) as year, ICAO,' + \
agg_fun_str + \
'FROM {0} GROUP BY ICAO, year, month'.format(table)
with conn:
c.execute(query)
conn.close()
print 'end'
return
def aggregate(table, method):
conn = sqlite3.connect(homedir + 'db/all.db')
c = conn.cursor()
if method == 'ave':
agg_fun_str = 'AVG(Temperature_F) '
elif method == 'hdd65':
base = float(method[-2:])
agg_fun_str = 'SUM(MAX(65.0 - Temperature_F, 0.0))/24.0 '.format(base)
elif method == 'cdd65':
base = float(method[-2:])
agg_fun_str = 'SUM(MAX(Temperature_F - {0}, 0.0))/24.0 '.format(base)
print '11111111111111111'
c.execute('DROP TABLE IF EXISTS weather_{0}'.format(method))
c.execute('CREATE TABLE weather_{0} (month text KEY, year text KEY, ICAO text KEY, {0} real);'.format(method))
print '11111111111111111'
query = 'INSERT INTO weather_{0} '.format(method) + \
'SELECT strftime(\'%m\', Timestamp) as month,' + \
'strftime(\'%Y\', Timestamp) as year, ICAO,' + \
agg_fun_str + \
'FROM {0} GROUP BY ICAO, year, month'.format(table)
print '11111111111111111'
c.execute(query)
conn.commit()
print '11111111111111111'
conn.close()
print 'end'
return
def get_cat():
conn = sqlite3.connect(homedir + 'db/all.db')
df = pd.read_sql('SELECT DISTINCT Building_Number, Fiscal_Year, Cat FROM EUAS_monthly ORDER BY Building_Number ASC, Fiscal_Year ASC;', conn)
df2 = df.groupby('Building_Number').last()
df2.reset_index(inplace=True)
df2.rename(columns={'Fiscal_Year': 'Record_Year'}, inplace=True)
df2.to_sql('EUAS_category', conn, if_exists='replace')
conn.close()
print 'end'
return
# excel serial date to actual time
# source: https://gist.github.com/oag335/9959241
def convert_excel_time(excel_time):
'''
converts excel float format to pandas datetime object
round to '1min' with
.dt.round('1min') to correct floating point conversion innaccuracy
'''
return pd.to_datetime('1899-12-30') + pd.to_timedelta(excel_time,'D')
def dump_static():
conn = sqlite3.connect(homedir + 'db/other_input.db')
# df2 = pd.read_csv(os.getcwd() + '/input/FY/static info/Entire GSA Building Portfolio.csv')
# df2.rename(columns={'Building ID': 'Building Number', 'Street':
# 'Street Address'}, inplace=True)
# df2.to_sql('Entire_GSA_Building_Portfolio_input', conn, if_exists='replace')
# filename = os.getcwd() + '/csv/all_column/sheet-0-all_col.csv'
# df_use = pd.read_csv(filename)
# df_use['Property Name'] = df_use['Property Name'].map(lambda x: x.partition(' ')[0][:8])
# df_use.rename(columns={'Property Name': 'Building Number',
# 'City/Municipality': 'City', 'Postal Code':
# 'Zip Code'}, inplace=True)
# df_use.to_sql('PortfolioManager_sheet0_input', conn,
# if_exists='replace')
# df3 = pd.read_csv(os.getcwd() + '/input/FY/static info/buildings_in_facility_fy15.csv', header=None, skiprows=6, names=['Region Number', 'Facility Number', 'Building Number', 'Facility total gsf', 'Building gsf'])
# with conn:
# df3.to_sql('buildings_in_facility_fy15', conn,
# if_exists='replace')
df4 = pd.read_csv(os.getcwd() + '/input/FY/static info/euas_database_of_buildings_cmu.csv')
df4.drop(['Building ID', 'Historical Status Desc'], axis=1, inplace=True)
df4['Building Date - Construction Completed'] = df4['Building Date - Construction Completed'].map(convert_excel_time)
df4['Building Date - Last Modernization'] = df4['Building Date - Last Modernization'].map(convert_excel_time)
df4.rename(index=str, columns={'Location Facility Code': 'Building_Number',
'Street Address': 'Street_Address', 'State Code': 'State'},
inplace=True)
print df4.head()
with conn:
df4.to_sql('euas_database_of_buildings_cmu', conn, if_exists='replace')
conn.close()
print 'end'
return
def get_use():
conn = sqlite3.connect(homedir + 'db/all.db')
print ' creating EUAS_type.csv master table ...'
with conn:
df1 = pd.read_sql('SELECT * FROM EUAS_category', conn)
conn_other = sqlite3.connect(homedir + 'db/other_input.db')
with conn_other:
df2 = pd.read_sql('SELECT Building_Number, [Self-Selected_Primary_Function] FROM PortfolioManager_sheet0_input', conn_other)
duplicated = df2[df2.duplicated(cols='Building_Number')]
print duplicated
print df2[df2['Building_Number'].isin(duplicated['Building_Number'].tolist())]
df2.drop_duplicates(cols='Building_Number', take_last=True, inplace=True)
print len(df1)
df = pd.merge(df1, df2, on='Building_Number', how='left')
print len(df)
df = df[['Building_Number', 'Self-Selected_Primary_Function']]
print df.head()
df.to_sql('EUAS_type', conn, if_exists='replace')
return
def check():
conn = sqlite3.connect(homedir + 'db/all.db')
with conn:
df = pd.read_sql('SELECT * FROM EUAS_monthly', conn)
# conn2 = sqlite3.connect(homedir + 'db/other_input.db')
with conn2:
df3 = pd.read_sql('SELECT * FROM buildings_in_facility_fy15', conn2)
# df4 = df.groupby(['Building_Number', 'Fiscal_Year']).mean()[['Gross_Sq.Ft']]
# df4.reset_index(inplace=True)
# zeros = set(df4[df4['Gross_Sq.Ft'] == 0]['Building_Number'].tolist())
# df_zero = df4[df4['Building_Number'].isin(zeros)][['Building_Number', 'Fiscal_Year', 'Gross_Sq.Ft']]
# df_zero.sort_values(['Building_Number', 'Fiscal_Year'], inplace=True)
# print df_zero.to_csv(homedir + '/check/zero_sqft.csv', index=False)
# col = 'Gas_(Cubic_Ft)'
# df_oil = df[['Building_Number', 'year', 'month', col]]
# df_oil.sort_values(['Building_Number', 'year', col], inplace=True)
# df_oil_nona = df_oil[df_oil[col] > 0]
# df_oil_max = df_oil_nona.drop_duplicates(cols=['Building_Number', 'year'], take_last=True)
# print df_oil_max['month'].value_counts()
# with conn:
# df_add = pd.read_sql('SELECT * FROM EUAS_latlng_', conn)
# df_add.info()
# df_add2 = df_add.groupby(['Building_Number', 'latlng']).first()
# df_add2.reset_index(inplace=True)
# df_add3 = df_add2.groupby('Building_Number').filter(lambda x: len(x) > 1)
# print df_add3.head(n=10)
# df_add.drop_duplicates(cols='Building_Number').info()
# with conn:
# df_add = pd.read_sql('SELECT * FROM EUAS_address', conn)
# print df_add.head()
# df_add2 = df_add.drop_duplicates(cols = 'Building_Number')
# print(len(df_add2[df_add2['Street_Address'].isnull()]))
# df_add2.info()
with conn:
df_dist = pd.read_sql('SELECT Building_Number, Distance_Mile, ICAO FROM building_weather_station', conn)
df_dist.drop_duplicates(cols=['Building_Number', 'Distance_Mile'], inplace=True)
df_dist.sort_values(['Building_Number', 'Distance_Mile'], inplace=True)
# print df_dist['Distance_Mile'].describe()
# print df_dist.sort_values('Distance_Mile', ascending=False).head(n=10)
# print df_dist.head(n=15)
df = df_dist.groupby('Building_Number').last()
print df.sort_values('Distance_Mile', ascending=False).head(n=10)
print df.describe()
# with conn:
# df = pd.read_sql('SELECT Building_Number, eui_gas, eui_elec FROM eui_by_fy', conn)
# print df[(df['eui_gas'] > 0) & (df['eui_gas'] != np.inf)]['eui_gas'].quantile(0.1)
# print df[(df['eui_gas'] > 0) & (df['eui_gas'] != np.inf)]['eui_gas'].describe()
# print df[(df['eui_elec'] > 0) & (df['eui_elec'] != np.inf)]['eui_elec'].quantile(0.1)
# print df[(df['eui_elec'] > 0) & (df['eui_elec'] != np.inf)]['eui_elec'].describe()
def get_latlng_from_datafile():
conn = sqlite3.connect(homedir + 'db/all.db')
df1 = pd.read_sql('SELECT * FROM EUAS_latlng_', conn)
print len(df1)
df2 = pd.read_sql('SELECT DISTINCT Building_Number FROM EUAS_monthly', conn)
print len(df2)
pd.read_sql('SELECT * FROM EUAS_latlng_2', conn).to_csv(homedir + \
'db_build_temp_csv/EUAS_latlng_2_old.csv')
df = pd.merge(df2, df1, on='Building_Number', how='left')
df['source'] = "geocoding"
print len(df)
conn = sqlite3.connect(homedir + 'db/other_input.db')
with conn:
df_latlng = pd.read_sql('SELECT Building_Number, Latitude, Longitude FROM euas_database_of_buildings_cmu', conn)
df_latlng['latlng'] = df_latlng.apply(lambda r: '[{}, {}]'.format(r['Latitude'], r['Longitude']), axis=1)
df_latlng.drop(['Latitude', 'Longitude'], axis=1, inplace=True)
conn.close()
df_latlng['source'] = 'euas_database_of_buildings_cmu'
df_final = pd.merge(df, df_latlng, how='left', on='Building_Number')
print df_final.head()
df_final['latlng_x'].update(df_final['latlng_y'])
df_final['source_x'].update(df_final['source_y'])
df_final.rename(index=str, columns={'latlng_x': 'latlng', 'source_x': 'source'}, inplace=True)
df_final.drop('latlng_y', axis=1, inplace=True)
df_final.drop('source_y', axis=1, inplace=True)
print df_final.head()
conn = uo.connect('all')
with conn:
df_final.to_sql('EUAS_latlng_2', conn, if_exists='replace')
conn.close()
print 'end'
def re_geocoding():
conn = sqlite3.connect(homedir + 'db/all.db')
df = pd.read_sql('SELECT * FROM EUAS_latlng', conn)
print df.head()
keys = df[df['latlng'] == 'None']['geocoding_input']
def modify_zipcode(string):
zipcode_idx = string.rfind(',') + 1
zipcode = string[zipcode_idx:]
if len(zipcode) == 9:
return '{0}{1}-{2}'.format(string[:zipcode_idx],
zipcode[:5], zipcode[-4:])
else:
return string
newkeys = [modify_zipcode(k) for k in keys]
def get_coarse(address):
return ','.join(address.split(',')[-1:])
newkeys = [get_coarse(x) for x in newkeys]
set_newkeys = set(newkeys)
d = geocoding_cache(set_newkeys)
for k in d:
print k, d[k]
d1 = dict(zip(keys, newkeys))
d2 = {k: d[d1[k]] for k in keys}
for k in d2:
print d2[k]
df['latlng'] = df.apply(lambda r: d2[r['geocoding_input']] if r['latlng'] == 'None' else r['latlng'], axis=1)
df.to_sql('EUAS_latlng_', conn, if_exists='replace')
conn.close()
return
def get_weather(test, step, db_prefix):
# get_start_end()
# download_weather(test)
variable = 'temperature'
download_weather_sep_db(test, step, db_prefix, variable)
return
def get_monthly_temperature_CDD_HDD(test):
if test:
conn_w = sqlite3.connect(homedir + 'db/weather_monthly_test_17.db')
c_w = conn_w.cursor()
else:
conn_w = sqlite3.connect(homedir + 'db/weather_monthly_17.db')
c_w = conn_w.cursor()
conn = sqlite3.connect(homedir + 'db/all.db')
c = conn.cursor()
with conn:
df = pd.read_sql('SELECT Building_Number, Latlng FROM EUAS_latlng_2', conn)
buildings = df['Building_Number'].tolist()
latlngs = df['latlng'].tolist()
print len(buildings), len(latlngs)
length = 5
stations = []
dists = []
bs = []
ll = []
downloaded = set()
no_data = set()
bs_list = zip(buildings, latlngs)
if test:
bs_list = bs_list[:5]
for i, (b, loc) in enumerate(bs_list):
try:
latlng = ast.literal_eval(loc)
except ValueError:
print 'malformed latlng'
continue
print i, b, latlng
sd_list = util.get_station_dist(b, latlng, length)
print sd_list
mindate = '2002-9-30T00:00:00Z'
maxdate = '2017-10-1T00:00:00Z'
station = 'Not Found'
dist = -1