-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbss_workflow.py
More file actions
2219 lines (1879 loc) · 87 KB
/
bss_workflow.py
File metadata and controls
2219 lines (1879 loc) · 87 KB
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
# bss_workflow.py (refactored)
import os
import sys
import time
import json
import math
import boto3
import pandas as pd
from io import StringIO
from os import getcwd
from argparse import ArgumentParser
# Optional R support (platform-specific setup)
import platform
import sys
from contextlib import redirect_stderr
# Try to import rpy2, but fail gracefully if R is not available
# First, try to set R_HOME if using conda environment
robjects = None
if "CONDA_PREFIX" in os.environ:
conda_env = os.environ["CONDA_PREFIX"]
potential_r = os.path.join(conda_env, "lib", "R")
if os.path.exists(potential_r):
os.environ["R_HOME"] = potential_r
try:
# Suppress stderr to hide rpy2 initialization errors
with redirect_stderr(open(os.devnull, 'w')):
import rpy2.robjects as robjects
except Exception:
# Silently fail - R support is optional
robjects = None
pd.set_option("display.max_columns", None)
# ----------------------------
# Configuration
# ----------------------------
class Config:
# data version identifiers
SCOUT_RUN_DATE = "2026-01-09" # identifier for the Scout result vintage
DISAG_ID = "20260305" # identifier for disaggregated energy data
# S3 locations
DATABASE_NAME = "euss_oedi" # S3 database in which all tables are located
BUCKET_NAME = "margaretbucket" # bucket in DATABASE_NAME where intermediate and long results will be stored
EXTERNAL_S3_DIR = "datasets" # folder in BUCKET_NAME where the files in MAP_EU_DIR, MAP_MEAS_DIR, CALIB_MULT_PATH will be uploaded
DEST_BUCKET = "bss-workflow" # bucket in DATABASE_NAME where publication ready results (e.g. wide tables) will be stored
# names of tables that contain disaggregation multipliers
MULTIPLIERS_TABLES = [
"com_annual_disaggregation_multipliers_20260304", # mult_com_annual
"res_annual_disaggregation_multipliers_20260206", # mult_res_annual
"com_hourly_disaggregation_multipliers_20260304", # mult_com_hourly
"res_hourly_disaggregation_multipliers_20260212" # mult_res_hourly
]
# names of tables that contain BuildStock data - required to calculate disaggregation multipliers
BLDSTOCK_TABLES = [
"comstock_2025.1_parquet", # meta_com Commercial metadata
"comstock_2025.1_by_state", # ts_com Commercial hourly data
"comstock_2025.1_upgrade_0", # gap_com Gap model
"resstock_amy2018_release_2024.2_metadata", # meta_res Residential metadata
"resstock_amy2018_release_2024.2_by_state" # ts_res Residential hourly data
]
# Scenarios to process
# TURNOVERS = ["breakthrough", "ineff", "mid", "high", "stated"]
# TURNOVERS = ['brk','aeo25_20to50_bytech_indiv','aeo25_20to50_bytech_gap_indiv']
# TURNOVERS = ["aeo", "ref", "brk", "accel", "fossil", "state","dual_switch", "high_switch", "min_switch"]
TURNOVERS = ["aeo_010926"]
# TURNOVERS = ['brk_010926']
# TURNOVERS = ['brk_010926','aeo_010926']
# scenarios that do NOT have envelope measures
no_env_meas = [
"aeo",
"test",
"fossil",
"aeo25_20to50_byeu_indiv",
"aeo25_20to50_bytech_gap_indiv",
"aeo25_20to50_bytech_indiv",
"min_switch",
"dual_switch",
"aeo_010926"
]
# years in Scout results to process
# YEARS = ['2026','2030','2035','2040','2045','2050']
# YEARS = ['2026','2030','2040','2050']
# YEARS = ['2026']
# YEARS = ['2022']
# YEARS = ['2050']
YEARS = ['2020','2021','2022','2023','2024']
# YEARS = ['2023','2024']
# YEARS = ['2026','2030','2040']
BASE_YEAR = '2026' # baseline year for calculating % differences
# states in Scout results to process
US_STATES = [
'AL', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA',
'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME',
'MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ',
'NM', 'NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD',
'TN', 'TX', 'UT', 'VA', 'VT', 'WA', 'WI', 'WV', 'WY',
]
# US_STATES = ['WY']
# US_STATES = ['OR']
# input file locations -- change only if you rearranged folders and files compared to the repo
JSON_PATH = "json/input.json"
SQL_DIR = "sql" # folder that contains the SQL files
MAP_EU_DIR = "map_eu" # folder that contains the mapping files to define the disaggregation multipliers
MAP_MEAS_DIR = "map_meas" # folder that contains the measure map, envelope map, and calibration multipliers
ENVELOPE_MAP_PATH = os.path.join(MAP_MEAS_DIR, "envelope_map.tsv")
MEAS_MAP_PATH = os.path.join(MAP_MEAS_DIR, "measure_map.tsv")
CALIB_MULT_PATH = os.path.join(MAP_MEAS_DIR, "calibration_multipliers.tsv")
EIA_GROSS_PATH = "map_meas/eia_gross_consumption_by_state_sector_year_month.csv" # file with monthly EIA electricity and gas consumption
SCOUT_OUT_TSV = "scout_tsv" # location where transformed Scout files will be saved as TSV
SCOUT_IN_JSON = "scout_results" # location of raw JSON files from Scout
# ----------------------------
# Utilities
# ----------------------------
def get_end_uses(sectorid: str):
if sectorid == "res":
return ['Computers and Electronics', 'Cooking', 'Cooling (Equip.)', 'Heating (Equip.)',
'Lighting', 'Other', 'Refrigeration', 'Water Heating'
]
return ['Computers and Electronics', 'Cooking', 'Cooling (Equip.)', 'Heating (Equip.)',
'Lighting', 'Other', 'Refrigeration', 'Ventilation', 'Water Heating'
]
def get_boto3_clients():
session = boto3.Session()
return session.client("s3"), session.client("athena")
def start_athena_query(athena_client, query: str, output_location: str, database: str):
return athena_client.start_query_execution(
QueryString=query,
QueryExecutionContext={"Database": database},
ResultConfiguration={"OutputLocation": output_location},
)["QueryExecutionId"]
def wait_for_query_completion(athena_client, query_execution_id: str):
while True:
resp = athena_client.get_query_execution(QueryExecutionId=query_execution_id)
status = resp["QueryExecution"]["Status"]["State"]
if status == "SUCCEEDED":
print("Query succeeded.")
return resp
if status in ["FAILED", "CANCELLED"]:
reason = resp["QueryExecution"]["Status"].get("StateChangeReason", "Unknown")
raise RuntimeError(f"Athena query {status.lower()}: {reason}")
time.sleep(2)
def fetch_athena_results_csv_to_df(s3_client, results_s3_uri: str) -> pd.DataFrame:
"""
Download CSV from s3://bucket/prefix/key into a DataFrame via boto3.
"""
if not results_s3_uri.startswith("s3://"):
raise ValueError(f"Unexpected results location: {results_s3_uri}")
_, rest = results_s3_uri.split("s3://", 1)
bucket, key = rest.split("/", 1)
obj = s3_client.get_object(Bucket=bucket, Key=key)
body = obj["Body"].read().decode("utf-8")
return pd.read_csv(StringIO(body))
def execute_athena_query(athena_client, query: str, cfg: Config, *, is_create: bool, wait=True):
"""
Generic runner. If wait=True, returns (results_s3_uri, df_or_None).
If is_create=True, df_or_None is None.
"""
output_location = f"s3://{cfg.BUCKET_NAME}/configs/"
qid = start_athena_query(athena_client, query, output_location, cfg.DATABASE_NAME)
if not wait:
return qid, None
qexec = wait_for_query_completion(athena_client, qid)
result_loc = qexec["QueryExecution"]["ResultConfiguration"]["OutputLocation"]
print(f"Results at: {result_loc}")
return result_loc, (None if is_create else result_loc)
def execute_athena_query_to_df(s3_client, athena_client, query: str, cfg: Config) -> pd.DataFrame:
"""
Execute a SELECT and return a DataFrame.
"""
output_location = f"s3://{cfg.BUCKET_NAME}/diagnosis_csv/"
qid = start_athena_query(athena_client, query, output_location, cfg.DATABASE_NAME)
qexec = wait_for_query_completion(athena_client, qid)
results_uri = qexec["QueryExecution"]["ResultConfiguration"]["OutputLocation"]
return fetch_athena_results_csv_to_df(s3_client, results_uri)
def execute_athena_query_to_df2(s3_client, athena_client, query: str, table_name, cfg: Config) -> pd.DataFrame:
"""
Execute a SELECT and return a DataFrame.
"""
s3_bucket_target = "bss-workflow"
s3_folder = "v2/annual/"
s3_output_prefix = "athena_results/"
output_location = f"s3://{cfg.BUCKET_NAME}/{s3_output_prefix}/"
qid = start_athena_query(athena_client, query, output_location, cfg.DATABASE_NAME)
qexec = wait_for_query_completion(athena_client, qid)
results_uri = qexec["QueryExecution"]["ResultConfiguration"]["OutputLocation"]
df = fetch_athena_results_csv_to_df(s3_client, results_uri)
local_parquet_file = f"{table_name}.parquet"
df.to_csv(f"{table_name}.csv", index=False)
df.to_parquet(local_parquet_file, engine="pyarrow")
print(f"Results saved as {local_parquet_file}")
s3_client.upload_file(local_parquet_file, s3_bucket_target, f"{s3_folder}{local_parquet_file}")
print(f"{local_parquet_file} is uploaded to {s3_bucket_target}/{s3_folder}")
def upload_file_to_s3(s3_client, local_path: str, bucket: str, s3_path: str):
s3_client.upload_file(local_path, bucket, s3_path)
print(f"UPLOADED {os.path.basename(local_path)} to s3://{bucket}/{s3_path}")
def list_all_objects(s3_client, bucket: str, prefix: str):
paginator = s3_client.get_paginator("list_objects_v2")
items = []
for page in paginator.paginate(Bucket=bucket, Prefix=prefix):
items.extend(page.get("Contents", []))
return items
def infer_column_types(df: pd.DataFrame):
dtypes_map = {
"object": "string",
"int64": "int",
"int32": "int",
"float64": "double",
"float32": "double",
"bool": "boolean",
"datetime64[ns]": "timestamp",
}
cols = []
for col in df.columns:
dtype = str(df[col].dtype)
athena_type = "string" if col == "upgrade" else dtypes_map.get(dtype, "string")
cols.append(f"`{col}` {athena_type}")
return ",\n ".join(cols)
def sql_create_table(df: pd.DataFrame, table_name: str, file_format: str, cfg: Config):
file_format = file_format.lower()
if file_format not in ("csv", "tsv"):
raise ValueError("Unsupported file format. Use 'csv' or 'tsv'.")
delimiter = "," if file_format == "csv" else "\t"
schema = infer_column_types(df)
return f"""
CREATE EXTERNAL TABLE IF NOT EXISTS {table_name} (
{schema}
)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY '{delimiter}'
LOCATION 's3://{cfg.BUCKET_NAME}/{cfg.EXTERNAL_S3_DIR}/{table_name}/'
TBLPROPERTIES ('skip.header.line.count'='1');
""".strip()
def read_sql_file(rel_path: str, cfg: Config):
abs_path = os.path.join(cfg.SQL_DIR, rel_path) if not os.path.isabs(rel_path) else rel_path
with open(abs_path, "r", encoding="utf-8") as f:
return f.read()
def file_to_df(file_path: str) -> pd.DataFrame:
if file_path.endswith(".tsv"):
return pd.read_csv(file_path, sep="\t")
if file_path.endswith(".csv"):
return pd.read_csv(file_path)
raise ValueError("Please provide a .tsv or .csv file.")
def reshape_json(data, path=None):
if path is None:
path = []
rows = []
if isinstance(data, dict):
for key, value in data.items():
rows.extend(reshape_json(value, path + [key]))
else:
rows.append(path + [data])
return rows
# ----------------------------
# Scout Generation # CORRECT
# ----------------------------
def add_sector(row: pd.Series):
meas = row.get("meas")
if pd.isna(meas):
return None
sec = str(meas).split(" ")[0]
if "(C)" in sec or "Gap" in sec:
return "com"
if "(R)" in sec:
return "res"
return None
def compute_no_package_energy(wide_df: pd.DataFrame) -> pd.DataFrame:
"""
From efficient_* columns (MMBtu), compute annual kWh columns.
"""
if "efficient_measure_env_mmbtu" not in wide_df.columns:
df = wide_df.copy()
else:
df = wide_df[wide_df["efficient_measure_env_mmbtu"].isna()].copy()
df["original_ann"] = (df["efficient_mmbtu"] - df["efficient_measure_mmbtu"]) / 3412 * 1e6
df["measure_ann"] = df["efficient_measure_mmbtu"] / 3412 * 1e6
return df
def compute_with_package_energy(wide_df: pd.DataFrame, include_bldg_type: bool, envelope_map: pd.DataFrame) -> pd.DataFrame:
"""
For envelope packages; requires efficient_measure_env_mmbtu column.
"""
if "efficient_measure_env_mmbtu" not in wide_df.columns:
return pd.DataFrame(columns=wide_df.columns)
df = wide_df[~pd.isna(wide_df["efficient_measure_env_mmbtu"])].copy()
df = df.merge(envelope_map, on="meas", how="left")
def calc_measure(row):
comp = row.get("component")
if comp == "equipment":
return (row["efficient_measure_mmbtu"] - row["efficient_measure_env_mmbtu"]) / 3412 * 1e6
if comp == "equipment + env":
return row["efficient_measure_env_mmbtu"] / 3412 * 1e6
return None
def calc_original(row):
comp = row.get("component")
if comp == "equipment":
return (row["efficient_mmbtu"] - row["efficient_measure_mmbtu"]) / 3412 * 1e6
if comp == "equipment + env":
return 0
return None
df["measure_ann"] = df.apply(calc_measure, axis=1)
df["original_ann"] = df.apply(calc_original, axis=1)
keep_cols = ["meas_separated", "reg", "end_use", "fuel", "year",
"efficient_mmbtu", "efficient_measure_mmbtu",
"efficient_measure_env_mmbtu", "original_ann", "measure_ann"]
if include_bldg_type and "bldg_type" in df.columns:
keep_cols.insert(2, "bldg_type")
keep_cols = [c for c in keep_cols if c in df.columns]
return df[keep_cols].rename(columns={"meas_separated": "meas"})
def _scout_json_to_df(filename: str, include_env: bool, cfg: Config) -> pd.DataFrame:
new_columns = [
"meas", "adoption_scn", "metric", "reg",
"bldg_type", "end_use", "fuel", "year", "value"
]
with open(filename, "r") as f:
json_df = json.load(f)
meas_keys = list(json_df.keys())[:-1]
all_df = pd.DataFrame()
weights_df_all = pd.DataFrame()
for mea in meas_keys:
json_data = json_df[mea]["Markets and Savings (by Category)"]
data_from_json = reshape_json(json_data)
df_from_json = pd.DataFrame(data_from_json)
df_from_json["meas"] = mea
all_df = df_from_json if all_df.empty else pd.concat([all_df, df_from_json], ignore_index=True)
cols = ["meas"] + [c for c in all_df.columns if c != "meas"]
all_df = all_df[cols]
# ---- ComStock Gap Weights ----
if "ComStock Gap Weights" in json_df[mea]:
w_data = reshape_json(json_df[mea]["ComStock Gap Weights"])
wdf = pd.DataFrame(w_data)
wdf["meas"] = mea
wdf = wdf[["meas",0,1,2]]
wdf.columns = ["meas", "bldg_type", "year", "gap_weight"]
weights_df_all = wdf if weights_df_all.empty else pd.concat([weights_df_all, wdf], ignore_index=True)
# Name Markets & Savings columns and keep only energy-use metrics there
all_df.columns = new_columns
metrics = [
"Efficient Energy Use (MMBtu)",
"Efficient Energy Use, Measure (MMBtu)",
"Baseline Energy Use (MMBtu)"
]
if include_env:
metrics.append("Efficient Energy Use, Measure-Envelope (MMBtu)")
all_df = all_df[all_df["metric"].isin(metrics)].copy()
# Fix measures without a fuel key
to_shift = all_df[pd.isna(all_df["value"])].copy()
if not to_shift.empty:
to_shift.loc[:, "value"] = to_shift["year"]
to_shift.loc[:, "year"] = to_shift["fuel"]
to_shift.loc[:, "fuel"] = "Electric"
df = pd.concat([all_df[pd.notna(all_df["value"])], to_shift])
else:
df = all_df
out_path = os.path.join(f"{cfg.SCOUT_OUT_TSV}",
f"scout_annual_state_{os.path.basename(filename).split('/')[0]}_df.tsv")
os.makedirs(cfg.SCOUT_OUT_TSV, exist_ok=True)
df.to_csv(out_path, sep="\t", index=False)
out_weight_path = os.path.join(f"{cfg.SCOUT_OUT_TSV}",
f"scout_annual_state_{os.path.basename(filename).split('/')[0]}_weights_df.tsv")
weights_df_all.to_csv(out_weight_path, sep="\t", index=False)
return df, weights_df_all
def scout_to_df(filename: str, cfg: Config) -> pd.DataFrame:
return _scout_json_to_df(filename, include_env=True, cfg=cfg)
def scout_to_df_noenv(filename: str, cfg: Config) -> pd.DataFrame:
return _scout_json_to_df(filename, include_env=False, cfg=cfg)
def _calc_annual_common(df: pd.DataFrame, gap_weights: pd.DataFrame, include_baseline: bool, turnover: str, include_bldg_type: bool, cfg: Config, include_env: bool):
envelope_map = file_to_df(cfg.ENVELOPE_MAP_PATH)
grouping_cols = ["meas", "metric", "reg", "end_use", "fuel", "year"]
pivot_index = ["meas", "reg", "end_use", "fuel", "year"]
if include_bldg_type:
if "bldg_type" in df.columns:
grouping_cols.insert(3, "bldg_type")
pivot_index.insert(2, "bldg_type")
efficient_metrics = [
"Efficient Energy Use (MMBtu)",
"Efficient Energy Use, Measure (MMBtu)",
]
if include_env:
efficient_metrics.append("Efficient Energy Use, Measure-Envelope (MMBtu)")
df = df.copy()
efficient = df[df["metric"].isin(efficient_metrics)].copy()
grouped = efficient.groupby(grouping_cols, dropna=False)["value"].sum().reset_index()
wide = grouped.pivot(index=pivot_index, columns="metric", values="value").reset_index()
rename_map = {
"Efficient Energy Use (MMBtu)": "efficient_mmbtu",
"Efficient Energy Use, Measure (MMBtu)": "efficient_measure_mmbtu",
"Efficient Energy Use, Measure-Envelope (MMBtu)": "efficient_measure_env_mmbtu",
}
wide = wide.rename(columns={k: v for k, v in rename_map.items() if k in wide.columns})
keep_cols = pivot_index + ["original_ann", "measure_ann"]
# No-package
no_pkg = compute_no_package_energy(wide)
no_pkg = no_pkg[keep_cols] if set(keep_cols).issubset(no_pkg.columns) else no_pkg
# With env-package (optional)
frames = [no_pkg]
if include_env:
with_pkg = compute_with_package_energy(wide, include_bldg_type, envelope_map)
with_pkg = with_pkg[keep_cols] if set(keep_cols).issubset(with_pkg.columns) else with_pkg
frames.append(with_pkg)
dflong = pd.concat(frames, ignore_index=True).melt(
id_vars=pivot_index,
value_vars=["original_ann", "measure_ann"],
var_name="tech_stage",
value_name="state_ann_kwh",
)
dflong["turnover"] = turnover
# Optional baseline
if include_baseline:
base = df[df["metric"] == "Baseline Energy Use (MMBtu)"].copy()
grouped_base = base.groupby(grouping_cols, dropna=False)["value"].sum().reset_index()
grouped_base["state_ann_kwh"] = grouped_base["value"] / 3412 * 1e6
grouped_base["tech_stage"] = "original_ann"
grouped_base["turnover"] = "baseline"
if include_env:
# Align with 'equipment' split only
grouped_base = grouped_base.merge(
envelope_map[envelope_map["component"] == "equipment"],
on="meas",
how="left",
)
grouped_base["meas"] = grouped_base.apply(
lambda r: r["meas_separated"] if pd.notnull(r.get("meas_separated")) and isinstance(r.get("meas_separated"), str) else r["meas"],
axis=1,
)
final_cols = pivot_index + ["tech_stage", "state_ann_kwh", "turnover"]
final_cols = [c for c in final_cols if c in grouped_base.columns]
dflong = pd.concat([dflong, grouped_base[final_cols]], ignore_index=True)
dflong["sector"] = dflong.apply(add_sector, axis=1)
dflong["scout_run"] = cfg.SCOUT_RUN_DATE
dflong_before_split = dflong.copy()
# --- GAP SPLIT: commercial-electric only, using mirrored gap_weights ---
if not gap_weights.empty:
subset_mask = (dflong.get("sector") == "com") & (dflong.get("fuel") == "Electric")
long_subset = dflong.loc[subset_mask].copy()
# Join keys mirror baseline key set (present in dflong)
join_keys = ["meas", "bldg_type", "year"]
if not long_subset.empty and all(k in long_subset.columns for k in join_keys):
merged = long_subset.merge(
gap_weights, on=join_keys, how="left", validate="m:1"
)
merged["gap_weight"] = merged["gap_weight"].fillna(0.0).astype(float)
cols = list(merged.columns)
# portion modeled in ComStock
part1 = merged.copy()
part1["state_ann_kwh"] = (1.0 - part1["gap_weight"]) * part1["state_ann_kwh"]
# gap portion
part2 = merged.copy()
part2["state_ann_kwh"] = part2["gap_weight"] * part2["state_ann_kwh"]
part2["meas"] = "Gap"
expanded = pd.concat([part1[cols], part2[cols]], ignore_index=True)
dflong = pd.concat([dflong.loc[~subset_mask], expanded], ignore_index=True)
# --- conservation check: state_ann_kwh before vs after applying gap split ---
os.makedirs("diagnostics", exist_ok=True)
# group-by keys that should remain identical across the split (exclude 'meas')
group_keys = [k for k in [
"reg", "bldg_type", "end_use", "fuel", "year",
"tech_stage", "turnover", "sector", "scout_run"
] if k in dflong.columns]
# OVERALL (all rows, excluding 'meas')
pre_all = (
dflong_before_split
.groupby(group_keys, dropna=False)["state_ann_kwh"].sum()
.reset_index()
.rename(columns={"state_ann_kwh": "kwh_before"})
)
post_all = (
dflong
.groupby(group_keys, dropna=False)["state_ann_kwh"].sum()
.reset_index()
.rename(columns={"state_ann_kwh": "kwh_after"})
)
cmp_all = pre_all.merge(post_all, on=group_keys, how="outer") \
.fillna({"kwh_before": 0.0, "kwh_after": 0.0})
cmp_all["delta"] = cmp_all["kwh_after"] - cmp_all["kwh_before"]
cmp_all["pct_delta"] = cmp_all.apply(
lambda r: (r["delta"] / r["kwh_before"]) if r["kwh_before"] else (0.0 if r["kwh_after"] == 0 else float("inf")),
axis=1
)
cmp_all["scope"] = "ALL_ROWS"
# COM + ELECTRIC subset (the only rows we modify)
mask_pre = (dflong_before_split.get("sector") == "com") & (dflong_before_split.get("fuel") == "Electric")
mask_post = (dflong.get("sector") == "com") & (dflong.get("fuel") == "Electric")
pre_sub = (
dflong_before_split.loc[mask_pre, group_keys + ["state_ann_kwh"]]
.groupby(group_keys, dropna=False)["state_ann_kwh"].sum()
.reset_index()
.rename(columns={"state_ann_kwh": "kwh_before"})
)
post_sub = (
dflong.loc[mask_post, group_keys + ["state_ann_kwh"]]
.groupby(group_keys, dropna=False)["state_ann_kwh"].sum()
.reset_index()
.rename(columns={"state_ann_kwh": "kwh_after"})
)
cmp_sub = pre_sub.merge(post_sub, on=group_keys, how="outer") \
.fillna({"kwh_before": 0.0, "kwh_after": 0.0})
cmp_sub["delta"] = cmp_sub["kwh_after"] - cmp_sub["kwh_before"]
cmp_sub["pct_delta"] = cmp_sub.apply(
lambda r: (r["delta"] / r["kwh_before"]) if r["kwh_before"] else (0.0 if r["kwh_after"] == 0 else float("inf")),
axis=1
)
cmp_sub["scope"] = "COM_ELECTRIC_ONLY"
# Totals rows at the top for quick glance
def _totals_row(scope, df):
tot_before = df["kwh_before"].sum()
tot_after = df["kwh_after"].sum()
row = {k: "ALL" for k in group_keys}
row.update({
"kwh_before": tot_before,
"kwh_after": tot_after,
"delta": tot_after - tot_before,
"pct_delta": ((tot_after - tot_before) / tot_before) if tot_before else (0.0 if tot_after == 0 else float("inf")),
"scope": scope + "_TOTAL"
})
return pd.DataFrame([row])
cmp_all = pd.concat([_totals_row("ALL_ROWS", cmp_all), cmp_all], ignore_index=True)
cmp_sub = pd.concat([_totals_row("COM_ELECTRIC_ONLY", cmp_sub), cmp_sub], ignore_index=True)
diagnostics_df = pd.concat([cmp_all, cmp_sub], ignore_index=True)
out_csv = os.path.join("diagnostics", f"gap_kwh_conservation_{turnover}.csv")
diagnostics_df.to_csv(out_csv, index=False)
print(f"[Gap conservation check] Wrote {out_csv}")
os.makedirs(cfg.SCOUT_OUT_TSV, exist_ok=True)
local_path = os.path.join(cfg.SCOUT_OUT_TSV, f"scout_annual_state_{turnover}.tsv")
dflong.to_csv(local_path, sep="\t", index=False)
return dflong, local_path
def calc_annual(df: pd.DataFrame, gap_weights: pd.DataFrame, include_baseline: bool, turnover: str, include_bldg_type: bool, cfg: Config):
return _calc_annual_common(df, gap_weights, include_baseline, turnover, include_bldg_type, cfg, include_env=True)
def calc_annual_noenv(df: pd.DataFrame, gap_weights: pd.DataFrame, include_baseline: bool, turnover: str, include_bldg_type: bool, cfg: Config):
return _calc_annual_common(df, gap_weights, include_baseline, turnover, include_bldg_type, cfg, include_env=False)
# ----------------------------
# CSV/JSON conversions for templates
# ----------------------------
def convert_json_to_csv_folder(json_path: str, out_dir: str):
os.makedirs(out_dir, exist_ok=True)
with open(json_path, "r") as jf:
data = json.load(jf)
for key, val in data.items():
df = pd.DataFrame(val)
out = os.path.join(out_dir, f"{key}.csv")
df.to_csv(out, index=False)
print(f"CSV saved: {out}")
def convert_csv_folder_to_json(folder_path: str, json_path: str):
json_dat = {}
for file_name in os.listdir(folder_path):
full = os.path.join(folder_path, file_name)
if os.path.isfile(full) and file_name.endswith(".csv"):
df = pd.read_csv(full).fillna("None")
json_dat[os.path.splitext(file_name)[0]] = {col: df[col].tolist() for col in df.columns}
with open(json_path, "w") as jf:
json.dump(json_dat, jf, indent=4)
print(f"Combined JSON saved to {json_path}")
# ----------------------------
# S3 table creators
# ----------------------------
def s3_create_tables_from_csvdir(s3_client, athena_client, cfg: Config):
for file_name in os.listdir(cfg.MAP_EU_DIR):
local_path = os.path.join(cfg.MAP_EU_DIR, file_name)
table_name = os.path.splitext(file_name)[0]
file_ext = os.path.splitext(file_name)[-1][1:].lower()
if not os.path.isfile(local_path) or file_ext not in ("csv", "tsv"):
continue
s3_path = f"{cfg.EXTERNAL_S3_DIR}/{table_name}/{file_name}"
upload_file_to_s3(s3_client, local_path, cfg.BUCKET_NAME, s3_path)
delimiter = "," if file_ext == "csv" else "\t"
df = pd.read_csv(local_path, delimiter=delimiter)
query = sql_create_table(df, table_name, file_ext, cfg)
execute_athena_query(athena_client, query, cfg, is_create=True, wait=True)
def s3_create_table_from_tsv(s3_client, athena_client, local_path: str, cfg: Config):
file_name = os.path.basename(local_path)
table_name = os.path.splitext(file_name)[0]
file_ext = os.path.splitext(file_name)[-1][1:].lower()
if file_ext not in ("csv", "tsv"):
raise ValueError("Provide a .csv or .tsv file.")
s3_path = f"{cfg.EXTERNAL_S3_DIR}/{table_name}/{file_name}"
upload_file_to_s3(s3_client, local_path, cfg.BUCKET_NAME, s3_path)
delimiter = "," if file_ext == "csv" else "\t"
df = pd.read_csv(local_path, delimiter=delimiter)
query = sql_create_table(df, table_name, file_ext, cfg)
execute_athena_query(athena_client, query, cfg, is_create=True, wait=True)
def s3_insert_to_table_from_tsv(s3_client, athena_client, local_path: str, dest_table_name: str, cfg: Config):
table_name = os.path.splitext(os.path.basename(local_path))[0]
s3_create_table_from_tsv(s3_client, athena_client, local_path, cfg)
sql = f"INSERT INTO {dest_table_name} SELECT * FROM {table_name};"
execute_athena_query(athena_client, sql, cfg, is_create=True, wait=True)
def sql_to_s3table(athena_client, cfg: Config, sql_file: str, sectorid: str, yearid: str, turnover: str):
sql_rel = f"{sectorid}/{sql_file}"
template_raw = read_sql_file(sql_rel, cfg)
sectorlong = "Commercial" if sectorid == "com" else "Residential"
base_kwargs = dict(
turnover=turnover,
# version=cfg.MULT_VERSION_ID,
sector=sectorid,
year=yearid,
dest_bucket=cfg.BUCKET_NAME,
scout_version=cfg.SCOUT_RUN_DATE,
sectorlong=sectorlong,
disag_id=cfg.DISAG_ID,
baseyear=cfg.BASE_YEAR,
mult_com_annual=cfg.MULTIPLIERS_TABLES[0],
mult_res_annual=cfg.MULTIPLIERS_TABLES[1],
mult_com_hourly=cfg.MULTIPLIERS_TABLES[2],
mult_res_hourly=cfg.MULTIPLIERS_TABLES[3],
meta_com=cfg.BLDSTOCK_TABLES[0],
ts_com=cfg.BLDSTOCK_TABLES[1],
gap_com=cfg.BLDSTOCK_TABLES[2],
meta_res=cfg.BLDSTOCK_TABLES[3],
ts_res=cfg.BLDSTOCK_TABLES[4]
)
contains_state = "{state}" in template_raw
contains_enduse = "{enduse}" in template_raw
def render(**kw):
return template_raw.format(**kw)
# Case 1: both {state} and {enduse}
if contains_state and contains_enduse:
for st in cfg.US_STATES:
for eu in get_end_uses(sectorid):
q = render(**base_kwargs, state=st, enduse=eu)
print(
f"RUN {sql_rel} | sector={sectorid} turnover={turnover} "
f"year={yearid} state={st} enduse={eu}"
)
execute_athena_query(athena_client, q, cfg, is_create=False, wait=True)
return
# Case 2: only {state}
if contains_state:
for st in cfg.US_STATES:
q = render(**base_kwargs, state=st)
print(
f"RUN {sql_rel} | sector={sectorid} turnover={turnover} "
f"year={yearid} state={st}"
)
execute_athena_query(athena_client, q, cfg, is_create=False, wait=True)
return
# Case 3: only {enduse}
if contains_enduse:
for eu in get_end_uses(sectorid):
q = render(**base_kwargs, enduse=eu)
print(f"RUN {sql_rel} | sector={sectorid} turnover={turnover} year={yearid} enduse={eu}")
execute_athena_query(athena_client, q, cfg, is_create=False, wait=True)
return
# Case 4: neither placeholder -> single render
q = render(**base_kwargs)
print(f"RUN {sql_rel} | sector={sectorid} turnover={turnover} year={yearid}")
execute_athena_query(athena_client, q, cfg, is_create=False, wait=True)
# ----------------------------
# Specific pipelines
# ----------------------------
def gen_multipliers(s3_client, athena_client, cfg: Config):
sectors = ["com", "res"]
tbl_res = [
"tbl_ann_mult.sql",
"res_ann_shares_cook.sql",
"res_ann_shares_cooling_delivered.sql",
"res_ann_shares_cw.sql",
"res_ann_shares_dry.sql",
"res_ann_shares_dw.sql",
"res_ann_shares_fanspumps.sql",
"res_ann_shares_heating_delivered.sql",
"res_ann_shares_hvac.sql",
"res_ann_shares_lighting.sql",
"res_ann_shares_misc.sql",
"res_ann_shares_poolpump.sql",
"res_ann_shares_refrig.sql",
"res_ann_shares_wh.sql",
"res_ann_shares_wh_delivered.sql",
"tbl_hr_mult.sql",
"res_hourly_shares_cook.sql",
"res_hourly_shares_cw.sql",
"res_hourly_shares_dry.sql",
"res_hourly_shares_dw.sql",
"res_hourly_shares_fanspumps.sql",
# "res_hourly_shares_gap.sql",
"res_hourly_shares_lighting.sql",
"res_hourly_shares_misc.sql",
"res_hourly_shares_poolpump.sql",
"res_hourly_shares_refrig.sql",
"res_hourly_shares_wh.sql",
"tbl_hr_mult_hvac_temp.sql",
"res_hourly_shares_cooling.sql",
"res_hourly_shares_heating.sql",
"res_hourly_hvac_norm.sql",
]
tbl_com = [
"tbl_ann_mult.sql",
"com_ann_shares_cook.sql",
"com_ann_shares_cool_delivered.sql",
"com_ann_shares_gap.sql",
"com_ann_shares_hvac.sql",
"com_ann_shares_heat_agnostic.sql",
"com_ann_shares_lighting.sql",
"com_ann_shares_misc.sql",
"com_ann_shares_refrig.sql",
"com_ann_shares_ventilation_ref.sql",
"com_ann_shares_wh.sql",
"com_ann_shares_wh_agnostic.sql",
"tbl_hr_mult.sql",
"com_hourly_shares_cooking.sql",
"com_hourly_shares_gap.sql",
"com_hourly_shares_lighting.sql",
"com_hourly_shares_misc.sql",
"com_hourly_shares_refrig.sql",
"com_hourly_shares_wh.sql",
"tbl_hr_mult_hvac_temp.sql",
"com_hourly_shares_cooling.sql",
"com_hourly_shares_heating.sql",
"com_hourly_shares_ventilation.sql",
"com_hourly_shares_ventilation_ref.sql",
"com_hourly_hvac_norm.sql",
]
for sectorid in sectors:
tbls = tbl_res if sectorid == "res" else tbl_com
for tbl_name in tbls:
# year/turnover are not used by these create-table templates -> pass placeholders anyway
sql_to_s3table(athena_client, cfg, tbl_name, sectorid, yearid="2024", turnover="brk")
def county_hourly_examples_60_days(s3_client, athena_client, cfg: Config, turnover: str):
# Step 1: find counties with largest annual increase and decrease
dynamic_sql = """
WITH ns AS (
SELECT "in.county"
FROM "{meta_res}"
WHERE upgrade = 0
GROUP BY "in.county"
HAVING COUNT("in.state") >= 50
),
county_totals AS (
SELECT lca."in.county", lca.turnover, lca."in.state", lca."year",
SUM(lca.county_ann_kwh) AS county_total_ann_kwh
FROM ns
LEFT JOIN long_county_annual_{turnover}_{disag_id} lca ON ns."in.county" = lca."in.county"
WHERE turnover != 'baseline'
AND lca.county_ann_kwh IS NOT NULL
AND "year" IN ({baseyear}, 2050)
AND fuel = 'Electric'
GROUP BY lca."in.county", turnover, "in.state", "year"
),
county_differences AS (
SELECT "in.county", turnover, "in.state",
(MAX(CASE WHEN year = 2050 THEN county_total_ann_kwh END) -
MAX(CASE WHEN year = {baseyear} THEN county_total_ann_kwh END))
/ NULLIF(MAX(CASE WHEN year = {baseyear} THEN county_total_ann_kwh END), 0) AS percent_difference
FROM county_totals
GROUP BY "in.county", turnover, "in.state"
)
SELECT "in.county", 'Large decrease' AS example_type FROM (
SELECT "in.county" FROM county_differences ORDER BY percent_difference ASC LIMIT 2
)
UNION ALL
SELECT "in.county", 'Large increase' AS example_type FROM (
SELECT "in.county" FROM county_differences ORDER BY percent_difference DESC LIMIT 2
)
""".format(
meta_res=cfg.BLDSTOCK_TABLES[3],
turnover=turnover,
disag_id=cfg.DISAG_ID,
baseyear=cfg.BASE_YEAR
)
dynamic_results = execute_athena_query_to_df(s3_client, athena_client, dynamic_sql, cfg)
# Step 2: combine with hardcoded counties
hardcoded = [
('G1200110', 'Hot'), # Boward County, FL
('G0400130', 'Hot'), # Maricopa County, AZ
('G3800170', 'Cold'), # Cass County, ND
('G2700530', 'Cold'), # Hennepin County, MN
('G3600810', 'High fossil heat'), # Queens, NY
('G1700310', 'High fossil heat'), # Cook County, IL
('G1200310', 'High electric heat'), # Duval County, FL
('G4500510', 'High electric heat'), # Horry County, SC
]
dynamic = [(row['in.county'], row['example_type']) for _, row in dynamic_results.iterrows()]
values_clause = ",\n ".join(f"('{c}', '{t}')" for c, t in hardcoded + dynamic)
# Step 3: find hourly consumption for example counties
main_sql = """
WITH example_counties AS (
SELECT "in.county", example_type FROM (VALUES
{values_clause}
) AS t("in.county", example_type)
),
hourly_data AS (
SELECT
lch."in.county",
ec.example_type,
lch.turnover,
lch.year,
lch.timestamp_hour,
SUM(lch.county_hourly_cal_kwh) AS county_hourly_kwh
FROM long_county_hourly_{turnover}_{disag_id} lch
INNER JOIN example_counties ec ON lch."in.county" = ec."in.county"
WHERE lch.year IN ({baseyear}, 2050)
AND lch.fuel = 'Electric'
GROUP BY lch."in.county", ec.example_type, lch.turnover, lch.year, lch.timestamp_hour
),
monthly_peak_min_days AS (
SELECT DISTINCT
h."in.county",
h.example_type,
h.year,
h.turnover AS peak_source_turnover,
month(h.timestamp_hour) AS month,
FIRST_VALUE(date_trunc('day', h.timestamp_hour))
OVER (PARTITION BY h."in.county", h.turnover, h.year, month(h.timestamp_hour)
ORDER BY h.county_hourly_kwh DESC) AS peak_day,
FIRST_VALUE(date_trunc('day', h.timestamp_hour))
OVER (PARTITION BY h."in.county", h.turnover, h.year, month(h.timestamp_hour)
ORDER BY h.county_hourly_kwh ASC) AS min_peak_day
FROM hourly_data h
),
monthly_peak_profiles AS (
SELECT
h."in.county",
h.example_type,
h."year",
h.turnover,
md.peak_source_turnover,
'monthly_peak_day' AS day_type,
month(h.timestamp_hour) AS month,
hour(h.timestamp_hour)+1 AS hour_of_day,
h.county_hourly_kwh,
md.peak_day AS "date"
FROM hourly_data h
INNER JOIN monthly_peak_min_days md
ON h."in.county" = md."in.county"
AND h.year = md.year
AND month(h.timestamp_hour) = md.month
AND date_trunc('day', h.timestamp_hour) = md.peak_day
),
monthly_min_profiles AS (
SELECT
h."in.county",
h.example_type,
h.year,
h.turnover,
md.peak_source_turnover,
'monthly_min_peak_day' AS day_type,
month(h.timestamp_hour) AS month,
hour(h.timestamp_hour)+1 AS hour_of_day,
h.county_hourly_kwh,
md.min_peak_day AS "date"
FROM hourly_data h
INNER JOIN monthly_peak_min_days md
ON h."in.county" = md."in.county"
AND h.year = md.year
AND month(h.timestamp_hour) = md.month
AND date_trunc('day', h.timestamp_hour) = md.min_peak_day
),
monthly_mean_profiles AS (
SELECT