forked from trynthink/scout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ecm_prep.py
6107 lines (5708 loc) · 324 KB
/
ecm_prep.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
import numpy
import re
import itertools
import json
from collections import OrderedDict
from os import listdir, getcwd, stat, path
from os.path import isfile, join
import copy
import warnings
from urllib.parse import urlparse
import gzip
import pickle
from functools import reduce # forward compatibility for Python 3
import operator
from optparse import OptionParser
class MyEncoder(json.JSONEncoder):
"""Convert numpy arrays to list for JSON serializing."""
def default(self, obj):
"""Modify 'default' method from JSONEncoder."""
# Case where object to be serialized is numpy array
if isinstance(obj, numpy.ndarray):
return obj.tolist()
# All other cases
else:
return super(MyEncoder, self).default(obj)
class UsefulInputFiles(object):
"""Class of input file paths to be used by this routine.
Attributes:
msegs_in (JSON): Database of baseline microsegment stock/energy.
msegs_cpl_in (JSON): Database of baseline technology characteristics.
metadata (JSON) = Baseline metadata inc. min/max for year range.
cost_convert_in (JSON): Database of measure cost unit conversions.
cbecs_sf_byvint (JSON): Commercial sq.ft. by vintage data.
indiv_ecms: Individual ECM JSON definitions folder.
ecm_packages (JSON): Measure package data.
ecm_prep (JSON): Prepared measure attributes data for use in the
analysis engine.
ecm_compete_data: Folder with contributing microsegment data needed
to run measure competition in the analysis engine.
run_setup (JSON): Names of active measures that should be run in
the analysis engine.
cpi_data (CSV) = Historical Consumer Price Index data.
ss_data (JSON) = Site-source conversion data.
tsv_data (JSON) = Time sensitive energy, price, and emissions data.
"""
def __init__(self):
self.msegs_in = ("supporting_data", "stock_energy_tech_data",
"mseg_res_com_cz.json")
# UNCOMMENT WITH ISSUE 188
# self.msegs_in = ("supporting_data", "stock_energy_tech_data",
# "mseg_res_com_cz_2017.json")
self.msegs_cpl_in = ("supporting_data", "stock_energy_tech_data",
"cpl_res_com_cz.json")
# UNCOMMENT WITH ISSUE 188
# self.msegs_cpl_in = ("supporting_data", "stock_energy_tech_data",
# "cpl_res_com_cz_2017.json")
self.metadata = "metadata.json"
# UNCOMMENT WITH ISSUE 188
# self.metadata = "metadata_2017.json"
self.cost_convert_in = ("supporting_data", "convert_data",
"ecm_cost_convert.json")
self.cbecs_sf_byvint = \
("supporting_data", "convert_data", "cbecs_sf_byvintage.json")
self.indiv_ecms = "ecm_definitions"
self.ecm_packages = ("ecm_definitions", "package_ecms.json")
self.ecm_prep = ("supporting_data", "ecm_prep.json")
self.ecm_compete_data = ("supporting_data", "ecm_competition_data")
self.run_setup = "run_setup.json"
self.cpi_data = ("supporting_data", "convert_data", "cpi.csv")
self.ss_data = ("supporting_data", "convert_data",
"site_source_co2_conversions.json")
self.tsv_data = ("supporting_data", "convert_data", "tsv.json")
class UsefulVars(object):
"""Class of variables that are used globally across functions.
Attributes:
adopt_schemes (list): Possible consumer adoption scenarios.
discount_rate (float): Rate to use in discounting costs/savings.
retro_rate (float): Rate at which existing stock is retrofitted.
nsamples (int): Number of samples to draw from probability distribution
on measure inputs.
aeo_years (list): Modeling time horizon.
demand_tech (list): All demand-side heating/cooling technologies.
zero_cost_tech (list): All baseline technologies with cost of zero.
inverted_relperf_list (list) = Performance units that require
an inverted relative performance calculation (e.g., an air change
rate where lower numbers indicate higher performance).
valid_submkt_urls (list) = Valid URLs for sub-market scaling fractions.
consumer_price_ind (numpy.ndarray) = Historical Consumer Price Index.
ss_conv (dict): Site-source conversion factors by fuel type.
fuel_switch_conv (dict): Performance unit conversions for expected
fuel switching cases.
carb_int (dict): Carbon intensities by fuel type (MMTon/quad).
ecosts (dict): Energy costs by building and fuel type ($/MMBtu).
ccosts (dict): Carbon costs ($/MTon).
com_timeprefs (dict): Commercial adoption time preference premiums.
in_all_map (dict): Maps any user-defined measure inputs marked 'all' to
list of climates, buildings, fuels, end uses, or technologies.
valid_mktnames (list): List of all valid applicable baseline market
input names for a measure.
out_break_czones (OrderedDict): Maps measure climate zone names to
the climate zone categories used in summarizing measure outputs.
out_break_bldgtypes (OrderedDict): Maps measure building type names to
the building sector categories used in summarizing measure outputs.
out_break_enduses (OrderedDict): Maps measure end use names to
the end use categories used in summarizing measure outputs.
out_break_in (OrderedDict): Breaks out key measure results by
climate zone, building sector, and end use.
cconv_topkeys_map (dict): Maps measure cost units to top-level keys in
an input cost conversion data dict.
cconv_whlbldgkeys_map (dict): Maps measure cost units to whole
building-level cost conversion dict keys.
cconv_htclkeys_map (dict): Maps measure cost units to cost conversion
dict keys for the heating and cooling end uses.
cconv_tech_htclsupply_map (dict): Maps measure cost units to cost
conversion dict keys for supply-side heating/cooling technologies.
cconv_tech_mltstage_map (dict): Maps measure cost units to cost
conversion dict keys for demand-side heating/cooling
technologies and controls technologies requiring multiple
conversion steps (e.g., $/ft^2 glazing -> $/ft^2 wall ->
$/ft^2 floor; $/node -> $/ft^2 floor -> $/unit).
cconv_bybldg_units (list): Flags cost unit conversions that must
be re-initiated for each new microsegment building type.
cconv_bytech_units_res (list): Flags cost unit conversions that must
be re-initiated for each new microsegment technology type (
applies only to the residential sector, where conversions from
$/ft^2 floor to $/unit depend on number of units per household,
which varies according to technology type).
res_typ_sf_household (dict): Typical household-level square footages,
used to translate ECM costs from $/ft^2 floor to $/household.
res_typ_units_household (dict): Typical number of technology units per
household, used to translate ECM costs from $/household to the
$/unit scale expected by the residential ECM competition approach
deflt_choice (list): Residential technology choice capital/operating
cost parameters to use when choice data are missing.
tsv_order (list): Order in which to implement time-sensitive
efficiency impacts.
"""
def __init__(self, base_dir, handyfiles):
self.adopt_schemes = ['Technical potential', 'Max adoption potential']
self.discount_rate = 0.07
self.retro_rate = 0.01
self.nsamples = 100
# Load metadata including AEO year range
with open(path.join(base_dir, handyfiles.metadata), 'r') as aeo_yrs:
try:
aeo_yrs = json.load(aeo_yrs)
except ValueError as e:
raise ValueError(
"Error reading in '" +
handyfiles.metadata + "': " + str(e)) from None
# Set minimum AEO modeling year
aeo_min = aeo_yrs["min year"]
# Set maximum AEO modeling year
aeo_max = aeo_yrs["max year"]
# Derive time horizon from min/max years
self.aeo_years = [
str(i) for i in range(aeo_min, aeo_max + 1)]
self.demand_tech = [
'roof', 'ground', 'lighting gain', 'windows conduction',
'equipment gain', 'floor', 'infiltration', 'people gain',
'windows solar', 'ventilation', 'other heat gain', 'wall']
self.zero_cost_tech = ['infiltration']
self.inverted_relperf_list = ["ACH", "CFM/ft^2 @ 0.3 in. w.c.",
"kWh/yr", "kWh/day", "SHGC", "HP/CFM"]
self.valid_submkt_urls = [
'.eia.gov', '.doe.gov', '.energy.gov', '.data.gov',
'.energystar.gov', '.epa.gov', '.census.gov', '.pnnl.gov',
'.lbl.gov', '.nrel.gov', 'www.sciencedirect.com', 'www.costar.com',
'www.navigantresearch.com']
try:
self.consumer_price_ind = numpy.genfromtxt(
path.join(base_dir, *handyfiles.cpi_data),
names=True, delimiter=',',
dtype=[('DATE', 'U10'), ('VALUE', '<f8')])
except ValueError as e:
raise ValueError(
"Error reading in '" +
handyfiles.cpi_data + "': " + str(e)) from None
# Read in JSON with site to source conversion, fuel CO2 intensity,
# and energy/carbon costs data
with open(path.join(base_dir, *handyfiles.ss_data), 'r') as ss:
try:
cost_ss_carb = json.load(ss)
except ValueError as e:
raise ValueError(
"Error reading in '" +
handyfiles.ss_data + "': " + str(e)) from None
# Set site to source conversions
self.ss_conv = {
"electricity": cost_ss_carb[
"electricity"]["site to source conversion"]["data"],
"natural gas": {yr: 1 for yr in self.aeo_years},
"distillate": {yr: 1 for yr in self.aeo_years},
"other fuel": {yr: 1 for yr in self.aeo_years}}
# Set CO2 intensity by fuel type
carb_int_init = {
"residential": {
"electricity": cost_ss_carb[
"electricity"]["CO2 intensity"]["data"]["residential"],
"natural gas": cost_ss_carb[
"natural gas"]["CO2 intensity"]["data"]["residential"],
"distillate": cost_ss_carb[
"other"]["CO2 intensity"]["data"]["residential"],
"other fuel": cost_ss_carb[
"other"]["CO2 intensity"]["data"]["residential"]},
"commercial": {
"electricity": cost_ss_carb[
"electricity"]["CO2 intensity"]["data"]["commercial"],
"natural gas": cost_ss_carb[
"natural gas"]["CO2 intensity"]["data"]["commercial"],
"distillate": cost_ss_carb[
"other"]["CO2 intensity"]["data"]["commercial"],
"other fuel": cost_ss_carb[
"other"]["CO2 intensity"]["data"]["commercial"]}}
# Divide CO2 intensity by fuel type data by 1000000000 to reflect
# conversion from import units of MMTon/quad to MMTon/MMBtu
self.carb_int = {bldg: {fuel: {
yr: (carb_int_init[bldg][fuel][yr] / 1000000000) for
yr in self.aeo_years} for fuel in carb_int_init[bldg].keys()} for
bldg in carb_int_init.keys()}
# Set energy costs
self.ecosts = {
"residential": {
"electricity": cost_ss_carb[
"electricity"]["price"]["data"]["residential"],
"natural gas": cost_ss_carb[
"natural gas"]["price"]["data"]["residential"],
"distillate": cost_ss_carb[
"other"]["price"]["data"]["residential"],
"other fuel": cost_ss_carb[
"other"]["price"]["data"]["residential"]},
"commercial": {
"electricity": cost_ss_carb[
"electricity"]["price"]["data"]["commercial"],
"natural gas": cost_ss_carb[
"natural gas"]["price"]["data"]["commercial"],
"distillate": cost_ss_carb[
"other"]["price"]["data"]["commercial"],
"other fuel": cost_ss_carb[
"other"]["price"]["data"]["commercial"]}}
# Set carbon costs
ccosts_init = cost_ss_carb["CO2 price"]["data"]
# Multiply carbon costs by 1000000 to reflect
# conversion from import units of $/MTon to $/MMTon
self.ccosts = {
yr_key: (ccosts_init[yr_key] * 1000000) for
yr_key in self.aeo_years}
self.com_timeprefs = {
"rates": [10.0, 1.0, 0.45, 0.25, 0.15, 0.065, 0.0],
"distributions": {
"heating": {
key: [0.265, 0.226, 0.196, 0.192, 0.105, 0.013, 0.003]
for key in self.aeo_years},
"cooling": {
key: [0.264, 0.225, 0.193, 0.192, 0.106, 0.016, 0.004]
for key in self.aeo_years},
"water heating": {
key: [0.263, 0.249, 0.212, 0.169, 0.097, 0.006, 0.004]
for key in self.aeo_years},
"ventilation": {
key: [0.265, 0.226, 0.196, 0.192, 0.105, 0.013, 0.003]
for key in self.aeo_years},
"cooking": {
key: [0.261, 0.248, 0.214, 0.171, 0.097, 0.005, 0.004]
for key in self.aeo_years},
"lighting": {
key: [0.264, 0.225, 0.193, 0.193, 0.085, 0.013, 0.027]
for key in self.aeo_years},
"refrigeration": {
key: [0.262, 0.248, 0.213, 0.170, 0.097, 0.006, 0.004]
for key in self.aeo_years}}}
self.in_all_map = {
"climate_zone": [
"AIA_CZ1", "AIA_CZ2", "AIA_CZ3", "AIA_CZ4", "AIA_CZ5"],
"bldg_type": {
"residential": [
"single family home", "multi family home", "mobile home"],
"commercial": [
"assembly", "education", "food sales", "food service",
"health care", "lodging", "large office", "small office",
"mercantile/service", "warehouse", "other"]},
"structure_type": ["new", "existing"],
"fuel_type": {
"residential": [
"electricity", "natural gas", "distillate", "other fuel"],
"commercial": [
"electricity", "natural gas", "distillate"]},
"end_use": {
"residential": {
"electricity": [
'drying', 'other', 'water heating',
'cooling', 'cooking', 'computers', 'lighting',
'secondary heating', 'TVs', 'heating', 'refrigeration',
'fans and pumps', 'ceiling fan'],
"natural gas": [
'drying', 'water heating', 'cooling', 'heating',
'cooking', 'secondary heating', 'other'],
"distillate": [
'water heating', 'heating', 'secondary heating',
'other'],
"other fuel": [
'water heating', 'cooking', 'heating',
'secondary heating', 'other']},
"commercial": {
"electricity": [
'ventilation', 'water heating', 'cooling',
'heating', 'refrigeration', 'MELs',
'non-PC office equipment', 'PCs', 'lighting',
'cooking'],
"natural gas": [
'cooling', 'water heating', 'cooking', 'heating'],
"distillate": ['water heating', 'heating']}},
"technology": {
"residential": {
"supply": {
"electricity": {
'other': [
'dishwasher', 'clothes washing', 'freezers',
'rechargeables', 'coffee maker',
'dehumidifier', 'electric other',
'microwave', 'pool heaters and pumps',
'security system', 'portable electric spas',
'wine coolers'],
'water heating': ['solar WH', 'electric WH'],
'cooling': [
'room AC', 'ASHP', 'GSHP', 'central AC'],
'computers': [
'desktop PC', 'laptop PC', 'network equipment',
'monitors'],
'lighting': [
'linear fluorescent (T-8)',
'linear fluorescent (T-12)',
'reflector (LED)', 'general service (CFL)',
'external (high pressure sodium)',
'general service (incandescent)',
'external (CFL)',
'external (LED)', 'reflector (CFL)',
'reflector (incandescent)',
'general service (LED)',
'external (incandescent)',
'linear fluorescent (LED)',
'reflector (halogen)'],
'secondary heating': ['secondary heater'],
'TVs': [
'home theater and audio', 'set top box',
'video game consoles', 'DVD', 'TV'],
'heating': ['GSHP', 'resistance heat', 'ASHP'],
'ceiling fan': [None],
'fans and pumps': [None],
'refrigeration': [None],
'drying': [None],
'cooking': [None]},
"natural gas": {
'cooling': ['NGHP'],
'heating': ['furnace (NG)', 'NGHP', 'boiler (NG)'],
'secondary heating': ['secondary heater'],
'drying': [None],
'water heating': [None],
'cooking': [None],
'other': ["other appliances"]},
"distillate": {
'heating': [
'boiler (distillate)', 'furnace (distillate)'],
'secondary heating': ['secondary heater'],
'water heating': [None],
'other': ["other appliances"]},
"other fuel": {
'heating': [
'resistance', 'furnace (kerosene)',
'stove (wood)', 'furnace (LPG)'],
'secondary heating': [
'secondary heater (wood)',
'secondary heater (coal)',
'secondary heater (kerosene)',
'secondary heater (LPG)'],
'cooking': [None],
'water heating': [None],
'other': ["other appliances"]}},
"demand": [
'roof', 'ground', 'windows solar',
'windows conduction', 'equipment gain',
'people gain', 'wall', 'infiltration']},
"commercial": {
"supply": {
"electricity": {
'ventilation': ['VAV_Vent', 'CAV_Vent'],
'water heating': [
'Solar water heater', 'HP water heater',
'elec_booster_water_heater',
'elec_water_heater'],
'cooling': [
'rooftop_AC', 'scroll_chiller',
'res_type_central_AC', 'reciprocating_chiller',
'comm_GSHP-cool', 'centrifugal_chiller',
'rooftop_ASHP-cool', 'wall-window_room_AC',
'screw_chiller'],
'heating': [
'electric_res-heat', 'comm_GSHP-heat',
'rooftop_ASHP-heat', 'elec_boiler'],
'refrigeration': [
'Commercial Beverage Merchandisers',
'Commercial Compressor Rack Systems',
'Commercial Condensers',
'Commercial Ice Machines',
'Commercial Reach-In Freezers',
'Commercial Reach-In Refrigerators',
'Commercial Refrigerated Vending Machines',
'Commercial Supermarket Display Cases',
'Commercial Walk-In Freezers',
'Commercial Walk-In Refrigerators'],
'MELs': [
'elevators', 'escalators', 'coffee brewers',
'kitchen ventilation', 'laundry',
'lab fridges and freezers', 'fume hoods',
'medical imaging', 'large video boards',
'shredders', 'private branch exchanges',
'voice-over-IP telecom', 'IT equipment',
'office UPS', 'data center UPS',
'security systems',
'distribution transformers',
'non-road electric vehicles'
],
'lighting': [
'100W A19 Incandescent',
'100W Equivalent A19 Halogen',
'100W Equivalent CFL Bare Spiral',
'100W Equivalent LED A Lamp',
'Halogen Infrared Reflector (HIR) PAR38',
'Halogen PAR38',
'LED Integrated Luminaire',
'LED PAR38',
'Mercury Vapor',
'Metal Halide',
'Sodium Vapor',
'T5 4xF54 HO High Bay',
'T5 F28',
'T8 F28',
'T8 F32',
'T8 F59',
'T8 F96'
],
'cooking': [
'Range, Electric, 4 burner, oven, 11-inch gr',
'Range, Electric-induction, 4 burner, oven'],
'PCs': [None],
'non-PC office equipment': [None]},
"natural gas": {
'cooling': [
'gas_eng-driven_RTAC', 'gas_chiller',
'res_type_gasHP-cool',
'gas_eng-driven_RTHP-cool'],
'water heating': [
'gas_water_heater', 'gas_instantaneous_WH',
'gas_booster_WH'],
'cooking': [
'Range, Gas, 4 burner, oven, 11-inch griddle',
'Range, Gas, 4 powered burners, convect. ove'],
'heating': [
'gas_eng-driven_RTHP-heat',
'res_type_gasHP-heat', 'gas_boiler',
'gas_furnace']},
"distillate": {
'water heating': ['oil_water_heater'],
'heating': ['oil_boiler', 'oil_furnace']}},
"demand": [
'roof', 'ground', 'lighting gain',
'windows conduction', 'equipment gain',
'floor', 'infiltration', 'people gain',
'windows solar', 'ventilation',
'other heat gain', 'wall']}}}
# Find the full set of valid names for describing a measure's
# applicable baseline that do not begin with 'all'
mktnames_non_all = self.append_keyvals(
self.in_all_map, keyval_list=[]) + ['supply', 'demand']
# Find the full set of valid names for describing a measure's
# applicable baseline that do begin with 'all'
mktnames_all_init = ["all", "all residential", "all commercial"] + \
self.append_keyvals(self.in_all_map["end_use"], keyval_list=[])
mktnames_all = ['all ' + x if 'all' not in x else x for
x in mktnames_all_init]
self.valid_mktnames = mktnames_non_all + mktnames_all
self.out_break_czones = OrderedDict([
('AIA CZ1', 'AIA_CZ1'), ('AIA CZ2', 'AIA_CZ2'),
('AIA CZ3', 'AIA_CZ3'), ('AIA CZ4', 'AIA_CZ4'),
('AIA CZ5', 'AIA_CZ5')])
self.out_break_bldgtypes = OrderedDict([
('Residential (New)', [
'new', 'single family home', 'multi family home',
'mobile home']),
('Residential (Existing)', [
'existing', 'single family home', 'multi family home',
'mobile home'],),
('Commercial (New)', [
'new', 'assembly', 'education', 'food sales',
'food service', 'health care', 'mercantile/service',
'lodging', 'large office', 'small office', 'warehouse',
'other']),
('Commercial (Existing)', [
'existing', 'assembly', 'education', 'food sales',
'food service', 'health care', 'mercantile/service',
'lodging', 'large office', 'small office', 'warehouse',
'other'])])
self.out_break_enduses = OrderedDict([
('Heating (Equip.)', ["heating", "secondary heating"]),
('Cooling (Equip.)', ["cooling"]),
('Envelope', ["heating", "secondary heating", "cooling"]),
('Ventilation', ["ventilation"]),
('Lighting', ["lighting"]),
('Water Heating', ["water heating"]),
('Refrigeration', ["refrigeration", "other"]),
('Computers and Electronics', [
"PCs", "non-PC office equipment", "TVs", "computers"]),
('Other', [
"cooking", "drying", "ceiling fan", "fans and pumps",
"MELs", "other"])])
# Use the above output categories to establish a dictionary with blank
# values at terminal leaf nodes; this dict will eventually store
# partitioning fractions needed to breakout the measure results
# Determine all possible outcome category combinations
out_levels = [
self.out_break_czones.keys(), self.out_break_bldgtypes.keys(),
self.out_break_enduses.keys()]
out_levels_keys = list(itertools.product(*out_levels))
# Create dictionary using outcome category combinations as key chains
self.out_break_in = OrderedDict()
for kc in out_levels_keys:
current_level = self.out_break_in
for ind, elem in enumerate(kc):
if elem not in current_level:
current_level[elem] = OrderedDict()
current_level = current_level[elem]
self.cconv_bybldg_units = [
"$/ft^2 glazing", "$/ft^2 roof", "$/ft^2 wall",
"$/ft^2 footprint", "$/ft^2 floor", "$/occupant", "$/node"]
self.cconv_bytech_units_res = ["$/ft^2 floor", "$/occupant", "$/node"]
self.cconv_topkeys_map = {
"whole building": ["$/ft^2 floor", "$/node", "$/occupant"],
"heating and cooling": [
"$/kBtu/h heating", "$/kBtu/h cooling", "$/ft^2 glazing",
"$/ft^2 roof", "$/ft^2 wall", "$/ft^2 footprint"],
"ventilation": ["$/1000 CFM"],
"lighting": ["$/1000 lm"],
"water heating": ["$/kBtu/h water heating"],
"refrigeration": ["$/kBtu/h refrigeration"]}
self.cconv_htclkeys_map = {
"supply": [
"$/kBtu/h heating", "$/kBtu/h cooling"],
"demand": [
"$/ft^2 glazing", "$/ft^2 roof",
"$/ft^2 wall", "$/ft^2 footprint"]}
self.cconv_tech_htclsupply_map = {
"heating equipment": ["$/kBtu/h heating"],
"cooling equipment": ["$/kBtu/h cooling"]}
self.cconv_tech_mltstage_map = {
"windows": {
"key": ["$/ft^2 glazing"],
"conversion stages": ["windows", "walls"]},
"roof": {
"key": ["$/ft^2 roof"],
"conversion stages": ["roof", "footprint"]},
"walls": {
"key": ["$/ft^2 wall"],
"conversion stages": ["walls"]},
"footprint": {
"key": ["$/ft^2 footprint"],
"conversion stages": ["footprint"]}}
self.cconv_whlbldgkeys_map = {
"wireless sensor network": ["$/node"],
"occupant-centered sensing and controls": ["$/occupant"]}
# Typical household square footages based on RECS 2015 Table HC 1.10,
# "Total square footage of U.S. homes, 2015"; divide total square
# footage for each housing type by total number of homes for each
# housing type (combine single family detached/attached into single
# family home, combine apartments with 2-4 and 5 or more units into
# multi family home)
self.res_typ_sf_household = {
"single family home": 2491, "mobile home": 1176,
"multi family home": 882}
# Typical number of lighting units per household based on RECS 2015
# Table HC 5.1, "Lighting in U.S. homes by housing unit type, 2015";
# take the median value for each bin in the table rows (e.g., for
# bin 0-20 lights, median is 10), and compute a housing unit-weighted
# sum across all the bins and housing types (combine single family
# detached/attached into single family home, combine apartments with
# 2-4 and 5 or more units into multi family home). Assume one unit
# per household for all other technologies; note that windows are
# included in this assumption (homeowners install/replace multiple
# windows at once as one 'unit').
self.res_typ_units_household = {
"lighting": {"single family home": 36, "mobile home": 18,
"multi family home": 15},
"all other technologies": 1}
# Assume that missing technology choice parameters come from the
# appliances/MELs areas; default is thus the EIA choice parameters
# for refrigerator technologies
self.deflt_choice = [-0.01, -0.12]
# Establish the assumed order in which time sensitive ECM
# adjustments are applied
self.tsv_order = ["conventional", "shave", "fill", "shift", "shape"]
def append_keyvals(self, dict1, keyval_list):
"""Append all terminal key values in a dict to a list.
Note:
Values already in the list should not be appended.
Args:
dict1 (dict): Dictionary with terminal key values
to append.
Returns:
List including all terminal key values from dict.
Raises:
ValueError: If terminal key values are not formatted as
either lists or strings.
"""
for (k, i) in dict1.items():
if isinstance(i, dict):
self.append_keyvals(i, keyval_list)
elif isinstance(i, list):
keyval_list.extend([
x for x in i if x not in keyval_list])
elif isinstance(i, str) and i not in keyval_list:
keyval_list.append(i)
else:
raise ValueError(
"Input dict terminal key values expected to be "
"lists or strings in the 'append_keyvals' function"
"for ECM '" + self.name + "'")
return keyval_list
class EPlusMapDicts(object):
"""Class of dicts used to map Scout measure definitions to EnergyPlus.
Attributes:
czone (dict): Scout-EnergyPlus climate zone mapping.
bldgtype (dict): Scout-EnergyPlus building type mapping. Shown are
the EnergyPlus commercial reference building names that correspond
to each AEO commercial building type, and the weights needed in
some cases to map multiple EnergyPlus reference building types to
a single AEO type. See 'convert_data' JSON for more details.
fuel (dict): Scout-EnergyPlus fuel type mapping.
enduse (dict): Scout-EnergyPlus end use mapping.
structure_type (dict): Scout-EnergyPlus structure type mapping.
"""
def __init__(self):
self.czone = {
"sub arctic": "BA-SubArctic",
"very cold": "BA-VeryCold",
"cold": "BA-Cold",
"marine": "BA-Marine",
"mixed humid": "BA-MixedHumid",
"mixed dry": "BA-MixedDry",
"hot dry": "BA-HotDry",
"hot humid": "BA-HotHumid"}
self.bldgtype = {
"assembly": {
"Hospital": 1},
"education": {
"PrimarySchool": 0.26,
"SecondarySchool": 0.74},
"food sales": {
"Supermarket": 1},
"food service": {
"QuickServiceRestaurant": 0.31,
"FullServiceRestaurant": 0.69},
"health care": None,
"lodging": {
"SmallHotel": 0.26,
"LargeHotel": 0.74},
"large office": {
"LargeOffice": 0.9,
"MediumOffice": 0.1},
"small office": {
"SmallOffice": 0.12,
"OutpatientHealthcare": 0.88},
"mercantile/service": {
"RetailStandalone": 0.53,
"RetailStripmall": 0.47},
"warehouse": {
"Warehouse": 1},
"other": None}
self.fuel = {
'electricity': 'electricity',
'natural gas': 'gas',
'distillate': 'other_fuel'}
self.enduse = {
'heating': [
'heating_electricity', 'heat_recovery_electricity',
'humidification_electricity', 'pump_electricity',
'heating_gas', 'heating_other_fuel'],
'cooling': [
'cooling_electricity', 'pump_electricity',
'heat_rejection_electricity'],
'water heating': [
'service_water_heating_electricity',
'service_water_heating_gas',
'service_water_heating_other_fuel'],
'ventilation': ['fan_electricity'],
'cooking': [
'interior_equipment_gas', 'interior_equipment_other_fuel'],
'lighting': ['interior_lighting_electricity'],
'refrigeration': ['refrigeration_electricity'],
'PCs': ['interior_equipment_electricity'],
'non-PC office equipment': ['interior_equipment_electricity'],
'MELs': ['interior_equipment_electricity']}
# Note: assumed year range for each structure vintage shown in lists
self.structure_type = {
"new": '90.1-2013',
"retrofit": {
'90.1-2004': [2004, 2009],
'90.1-2010': [2010, 2012],
'DOE Ref 1980-2004': [1980, 2003],
'DOE Ref Pre-1980': [0, 1979]}}
class EPlusGlobals(object):
"""Class of global variables used in parsing EnergyPlus results file.
Attributes:
cbecs_sh (xlrd sheet object): CBECs square footages Excel sheet.
vintage_sf (dict): Summary of CBECs square footages by vintage.
eplus_coltypes (list): Expected EnergyPlus variable data types.
eplus_basecols (list): Variable columns that should never be removed.
eplus_perf_files (list): EnergyPlus simulation output file names.
eplus_vintages (list): EnergyPlus building vintage types.
eplus_vintage_weights (dicts): Square-footage-based weighting factors
for EnergyPlus vintages.
"""
def __init__(self, eplus_dir, cbecs_sf_byvint):
# Set building vintage square footage data from CBECS
self.vintage_sf = cbecs_sf_byvint
self.eplus_coltypes = [
('building_type', '<U50'), ('climate_zone', '<U50'),
('template', '<U50'), ('measure', '<U50'), ('status', '<U50'),
('ep_version', '<U50'), ('os_version', '<U50'),
('timestamp', '<U50'), ('cooling_electricity', '<f8'),
('cooling_water', '<f8'), ('district_chilled_water', '<f8'),
('district_hot_water_heating', '<f8'),
('district_hot_water_service_hot_water', '<f8'),
('exterior_equipment_electricity', '<f8'),
('exterior_equipment_gas', '<f8'),
('exterior_equipment_other_fuel', '<f8'),
('exterior_equipment_water', '<f8'),
('exterior_lighting_electricity', '<f8'),
('fan_electricity', '<f8'),
('floor_area', '<f8'), ('generated_electricity', '<f8'),
('heat_recovery_electricity', '<f8'),
('heat_rejection_electricity', '<f8'),
('heating_electricity', '<f8'), ('heating_gas', '<f8'),
('heating_other_fuel', '<f8'), ('heating_water', '<f8'),
('humidification_electricity', '<f8'),
('humidification_water', '<f8'),
('interior_equipment_electricity', '<f8'),
('interior_equipment_gas', '<f8'),
('interior_equipment_other_fuel', '<f8'),
('interior_equipment_water', '<f8'),
('interior_lighting_electricity', '<f8'),
('net_site_electricity', '<f8'), ('net_water', '<f8'),
('pump_electricity', '<f8'),
('refrigeration_electricity', '<f8'),
('service_water', '<f8'),
('service_water_heating_electricity', '<f8'),
('service_water_heating_gas', '<f8'),
('service_water_heating_other_fuel', '<f8'), ('total_gas', '<f8'),
('total_other_fuel', '<f8'), ('total_site_electricity', '<f8'),
('total_water', '<f8')]
self.eplus_basecols = [
'building_type', 'climate_zone', 'template', 'measure']
# Set EnergyPlus data file name list, given local directory
self.eplus_perf_files = [
f for f in listdir(eplus_dir) if
isfile(join(eplus_dir, f)) and '_scout_' in f]
# Import the first of the EnergyPlus measure performance files and use
# it to establish EnergyPlus vintage categories
eplus_file = numpy.genfromtxt(
(eplus_dir + '/' + self.eplus_perf_files[0]), names=True,
dtype=self.eplus_coltypes, delimiter=",", missing_values='')
self.eplus_vintages = numpy.unique(eplus_file['template'])
# Determine appropriate weights for mapping EnergyPlus vintages to the
# 'new' and 'retrofit' building structure types of Scout
self.eplus_vintage_weights = self.find_vintage_weights()
def find_vintage_weights(self):
"""Find square-footage-based weighting factors for building vintages.
Note:
Use CBECs building vintage square footage data to derive weighting
factors that will map the EnergyPlus building vintages to the 'new'
and 'retrofit' building structure types of Scout.
Returns:
Weights needed to map each EnergyPlus vintage category to the 'new'
and 'retrofit' structure types defined in Scout.
Raises:
ValueError: If vintage weights do not sum to 1.
KeyError: If unexpected vintage names are discovered in the
EnergyPlus file.
"""
handydicts = EPlusMapDicts()
# Set the expected names of the EnergyPlus building vintages and the
# low and high year limits of each building vintage category
expected_eplus_vintage_yr_bins = [
handydicts.structure_type['new']] + \
list(handydicts.structure_type['retrofit'].keys())
# Initialize a variable meant to translate the summed square footages
# of multiple 'retrofit' building vintages into weights that sum to 1;
# also initialize a variable used to check that these weights indeed
# sum to 1
total_retro_sf, retro_weight_sum = (0 for n in range(2))
# Check for expected EnergyPlus vintage names
if sorted(self.eplus_vintages) == sorted(
expected_eplus_vintage_yr_bins):
# Initialize a dictionary with the EnergyPlus vintages as keys and
# associated square footage values starting at zero
eplus_vintage_weights = dict.fromkeys(self.eplus_vintages, 0)
# Loop through the EnergyPlus vintages and assign associated
# weights by mapping to cbecs square footage data
for k in eplus_vintage_weights.keys():
# If looping through the EnergyPlus vintage associated with the
# 'new' Scout structure type, set vintage weight to 1 (only one
# vintage category will be associated with this structure type)
if k == handydicts.structure_type['new']:
eplus_vintage_weights[k] = 1
# Otherwise, set EnergyPlus vintage weight initially to the
# square footage that corresponds to that vintage in cbecs
else:
# Loop through all cbecs vintage bins
for k2 in self.vintage_sf.keys():
# Find the limits of the cbecs vintage bin
cbecs_match = re.search(
r'(\D*)(\d*)(\s*)(\D*)(\s*)(\d*)', k2)
cbecs_t1 = cbecs_match.group(2)
cbecs_t2 = cbecs_match.group(6)
# Handle a 'Before Year X' case in cbecs (e.g., 'Before
# 1920'), setting the lower year limit to zero
if cbecs_t2 == '':
cbecs_t2 = 0
# Determine a single average year that represents the
# current cbecs vintage bin
cbecs_yr = (int(cbecs_t1) + int(cbecs_t2)) / 2
# If the cbecs bin year falls within the year limits of
# the current EnergyPlus vintage bin, add the
# associated cbecs ft^2 data to the EnergyPlus
# vintage weight value
if cbecs_yr >= handydicts.structure_type[
'retrofit'][k][0] and \
cbecs_yr < handydicts.structure_type[
'retrofit'][k][1]:
eplus_vintage_weights[k] += self.vintage_sf[k2]
total_retro_sf += self.vintage_sf[k2]
# Run through all EnergyPlus vintage weights, normalizing the
# square footage-based weights for each 'retrofit' vintage to the
# total square footage across all 'retrofit' vintage categories
for k in eplus_vintage_weights.keys():
# If running through the 'new' EnergyPlus vintage bin, register
# the value of its weight (should be 1)
if k == handydicts.structure_type['new']:
new_weight_sum = eplus_vintage_weights[k]
# If running through a 'retrofit' EnergyPlus vintage bin,
# normalize the square footage for that vintage by total
# square footages across 'retrofit' vintages to arrive at the
# final weight for that EnergyPlus vintage
else:
eplus_vintage_weights[k] /= total_retro_sf
retro_weight_sum += eplus_vintage_weights[k]
# Check that the 'new' EnergyPlus vintage weight equals 1 and that
# all 'retrofit' EnergyPlus vintage weights sum to 1
if new_weight_sum != 1:
raise ValueError("Incorrect new vintage weight total when "
"instantiating 'EPlusGlobals' object")
elif retro_weight_sum != 1:
raise ValueError("Incorrect retrofit vintage weight total when"
"instantiating 'EPlusGlobals' object")
else:
raise KeyError(
"Unexpected EnergyPlus vintage(s) when instantiating "
"'EPlusGlobals' object; "
"check EnergyPlus vintage assumptions in structure_type "
"attribute of 'EPlusMapDict' object")
return eplus_vintage_weights
class Measure(object):
"""Set up a class representing efficiency measures as objects.
Attributes:
**kwargs: Arbitrary keyword arguments used to fill measure attributes
from an input dictionary.
remove (boolean): Determines whether measure should be removed from
analysis engine due to insufficient market source data.
handyvars (object): Global variables useful across class methods.
retro_rate (float or list): Stock retrofit rate specific to the ECM.
technology_type (string): Flag for supply- or demand-side technology.
yrs_on_mkt (list): List of years that the measure is active on market.
markets (dict): Data grouped by adoption scheme on:
a) 'master_mseg': a measure's master market microsegments (stock,
energy, carbon, cost),
b) 'mseg_adjust': all microsegments that contribute to each master
microsegment (required later for measure competition).
c) 'mseg_out_break': master microsegment breakdowns by key
variables (climate zone, building class, end use)
out_break_norm (dict): Total energy use data to normalize
savings values summed by climate zone, building class, and end use.
"""
def __init__(self, handyvars, **kwargs):
# Read Measure object attributes from measures input JSON.
for key, value in kwargs.items():
setattr(self, key, value)
# Check to ensure that measure name is proper length for plotting
if len(self.name) > 45:
raise ValueError(
"ECM '" + self.name + "' name must be <= 45 characters")
self.remove = False
self.handyvars = handyvars
# Set the rate of baseline retrofitting for ECM stock-and-flow calcs
try:
# Check first to see whether pulling up retrofit rate errors
self.retro_rate
# Accommodate retrofit rate input as a probability distribution
if type(self.retro_rate) is list and isinstance(
self.retro_rate[0], str):
# Sample measure retrofit rate values
self.retro_rate = self.rand_list_gen(
self.retro_rate, self.handyvars.nsamples)
# Raise error in case where distribution is incorrectly specified
elif type(self.retro_rate) is list:
raise ValueError(
"ECM " + self.name + " 'retro_rate' distribution must " +
"be formatted as [<distribution name> (string), " +
"<distribution parameters> (floats)]")
# If retrofit rate is set to None, use default retrofit rate value
elif self.retro_rate is None:
self.retro_rate = self.handyvars.retro_rate
# Do nothing in case where retrofit rate is specified as float
else:
pass
except AttributeError:
# If no 'retro_rate' attribute was given for the ECM, use default
# retrofit rate value
self.retro_rate = self.handyvars.retro_rate
# Determine whether the measure replaces technologies pertaining to
# the supply or the demand of energy services
self.technology_type = None
# Measures replacing technologies in a pre-specified
# 'demand_tech' list are of the 'demand' side technology type
if (isinstance(self.technology, list) and all([
x in self.handyvars.demand_tech for x in self.technology])) or \
self.technology in self.handyvars.demand_tech:
self.technology_type = "demand"
# Measures replacing technologies not in a pre-specified
# 'demand_tech' list are of the 'supply' side technology type
else:
self.technology_type = "supply"
# Reset market entry year if None or earlier than min. year
if self.market_entry_year is None or (int(
self.market_entry_year) < int(self.handyvars.aeo_years[0])):
self.market_entry_year = int(self.handyvars.aeo_years[0])
# Reset measure market exit year if None or later than max. year
if self.market_exit_year is None or (int(
self.market_exit_year) > (int(
self.handyvars.aeo_years[-1]) + 1)):
self.market_exit_year = int(self.handyvars.aeo_years[-1]) + 1
self.yrs_on_mkt = [str(i) for i in range(
self.market_entry_year, self.market_exit_year)]
# If no "time_sensitive_valuation" parameter was specified for the
# ECM, set this parameter to None
try:
self.time_sensitive_valuation
except AttributeError:
self.time_sensitive_valuation = None
self.markets, self.out_break_norm = ({} for n in range(2))
for adopt_scheme in handyvars.adopt_schemes: