-
Notifications
You must be signed in to change notification settings - Fork 21
/
retail_rate_calculations.py
2436 lines (2159 loc) · 114 KB
/
retail_rate_calculations.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
#%% ===========================================================================================
### --- IMPORTS ---
### ===========================================================================================
import argparse
import copy
import itertools
import pandas as pd
import numpy as np
import gdxpds
import os
### Local imports
import ferc_distadmin
import plots
#########################
### Shared properties ###
# Assign tracelabels here instead of inside the plotting function so
# that it can be easily imported in postprocess_for_tableau.py
tracelabels = {
'bias_correction': 'State bias correction',
'load_flow': 'Flow: Load',
'oper_res_flow': 'Flow: Operating reserves',
'res_marg_ann_flow': 'Flow: Planning reserves',
'rps_flow': 'Flow: RPS',
'op_emissions_taxes': 'Operation: Emissions taxes',
'op_acp_compliance_costs': 'Operation: Alternative compliance payments',
'op_vom_costs': 'Operation: Variable O&M',
'op_operating_reserve_costs': 'Operation: Operating reserves',
'op_fuelcosts_objfn': 'Operation: Fuel',
'op_h2ct_fuel_costs': 'Operation: H2-CT - Hydrogen',
'op_h2_storage': 'Operation: Storage - Hydrogen',
'op_h2_transport': 'Operation: Transport - Hydrogen',
'op_h2_transport_intrareg': 'Operation: Intraregional transport - Hydrogen',
'op_h2_fuel_costs': 'Operation: Fuel - Hydrogen',
'op_h2_vom': 'Operation: Variable O&M - Hydrogen',
'op_co2_transport_storage': 'Operation: CO2 Transport Storage',
'op_co2_storage': 'Operation: CO2 Storage',
'op_co2_network_fom_pipe': 'Operation: Fixed O&M - CO2 Pipe',
'op_co2_network_fom_spur': 'Operation: Fixed O&M - CO2 Spur',
'op_fom_costs': 'Operation: Fixed O&M',
'op_spurline_fom': 'Operation: Fixed O&M - Spur line',
'op_transmission_intrazone_fom': 'Operation: Fixed O&M - Intrazone Transmission',
'op_co2_incentive_negative': 'Operation: Incentives - CO2 tax credits',
'op_h2_ptc_payments_negative': 'Operation: Incentives - H2 PTC payments',
'op_ptc_payments_negative': 'Operation: Incentives - PTC payments',
'op_startcost': 'Operation: Startup/ramping',
'op_wc_debt_interest': 'Capital: Working capital debt interest',
'op_wc_equity_return': 'Capital: Working capital equity return',
'op_wc_income_tax': 'Capital: Working capital income tax',
'op_dist': 'Operation: Distribution',
'op_admin': 'Operation: Administration',
'op_trans': 'Operation: Transmission',
'op_transmission_fom': 'Operation: Transmission (ReEDS)',
'cap_admin_dep_expense': 'Capital: Administration depreciation',
'cap_admin_debt_interest': 'Capital: Administration debt interest',
'cap_admin_equity_return': 'Capital: Administration equity return',
'cap_admin_income_tax': 'Capital: Administration income tax',
'cap_dist_dep_expense': 'Capital: Distribution depreciation',
'cap_dist_debt_interest': 'Capital: Distribution debt interest',
'cap_dist_equity_return': 'Capital: Distribution equity return',
'cap_dist_income_tax': 'Capital: Distribution income tax',
'cap_fom_dep_expense': 'Capital: Fixed O&M depreciation',
'cap_fom_debt_interest': 'Capital: Fixed O&M debt interest',
'cap_fom_equity_return': 'Capital: Fixed O&M equity return',
'cap_fom_income_tax': 'Capital: Fixed O&M income tax',
'cap_gen_dep_expense': 'Capital: Generator depreciation',
'cap_gen_debt_interest': 'Capital: Generator debt interest',
'cap_gen_equity_return': 'Capital: Generator equity return',
'cap_gen_income_tax': 'Capital: Generator income tax',
'cap_trans_FERC_dep_expense': 'Capital: Transmission (intra-region) depreciation',
'cap_trans_FERC_debt_interest': 'Capital: Transmission (intra-region) debt interest',
'cap_trans_FERC_equity_return': 'Capital: Transmission (intra-region) equity return',
'cap_trans_FERC_income_tax': 'Capital: Transmission (intra-region) income tax',
'cap_transmission_dep_expense': 'Capital: Transmission (inter-region) depreciation',
'cap_transmission_debt_interest': 'Capital: Transmission (inter-region) debt interest',
'cap_transmission_equity_return': 'Capital: Transmission (inter-region) equity return',
'cap_transmission_income_tax': 'Capital: Transmission (inter-region) income tax',
'cap_spurline_dep_expense': 'Capital: Spur line depreciation',
'cap_spurline_debt_interest': 'Capital: Spur line debt interest',
'cap_spurline_equity_return': 'Capital: Spur line equity return',
'cap_spurline_income_tax': 'Capital: Spur line income tax',
'cap_converter_dep_expense': 'Capital: Transmission AC/DC converter depreciation',
'cap_converter_debt_interest': 'Capital: Transmission AC/DC converter debt interest',
'cap_converter_equity_return': 'Capital: Transmission AC/DC converter equity return',
'cap_converter_income_tax': 'Capital: Transmission AC/DC converter income tax',
}
#%% ===========================================================================
### --- UTILITY FUNCTIONS ---
### ===========================================================================
### Functions for interpolating between solve years
def interp_between_solve_years(
df, value_name, modeled_years, non_modeled_years,
first_year, last_year, region_list, region_type):
"""
"""
# Pivot for just the solve years first, so we can fill in zero-value years
df_pivot_solve_years = pd.DataFrame(index=modeled_years, columns=region_list)
df_pivot_solve_years.update(df.pivot(index='t', columns=region_type, values=value_name))
df_pivot_solve_years = df_pivot_solve_years.fillna(0.0)
# Then pivot all the years, filling in the values that we start with
df_pivot = pd.DataFrame(index=np.arange(first_year,last_year+1,1), columns=region_list)
df_pivot.update(df_pivot_solve_years)
# Interpolate between solve years
for year in non_modeled_years:
preceding_model_year = np.max([x for x in modeled_years if x<year])
following_model_year = np.min([x for x in modeled_years if x>year])
interp_f = (year-preceding_model_year) / (following_model_year-preceding_model_year)
df_pivot.loc[year,:] = (
df_pivot.loc[preceding_model_year,:]
+ interp_f * (df_pivot.loc[following_model_year,:] - df_pivot.loc[preceding_model_year,:])
)
# Melt the result back to the original tidy format
df_pivot = df_pivot.reset_index().rename(columns={'index':'t'})
df = df_pivot.melt(id_vars='t', value_name=value_name)
df[value_name] = df[value_name].astype(float)
return df
def distribute_between_solve_years(df, value_col, modeled_years, years):
"""
"""
first_year = np.min(modeled_years)
year_expander = pd.DataFrame(index=years)
year_expander['t_modeled'] = None
year_expander['alloc_f'] = 0
year_expander.loc[first_year, ['t_modeled', 'alloc_f']] = [first_year, 1.0]
for year in year_expander.index[1:]:
preceding_model_year = np.max([x for x in modeled_years if x<year])
following_model_year = np.min([x for x in modeled_years if x>=year])
if year in list(modeled_years):
year_expander.loc[year,'t_modeled'] = year
else:
year_expander.loc[year,'t_modeled'] = following_model_year
year_expander.loc[year, 'alloc_f'] = 1 / (following_model_year - preceding_model_year)
year_expander = year_expander.reset_index().rename(columns={'index':'t'})
df = df.merge(year_expander[['t', 't_modeled', 'alloc_f']], on='t_modeled', how='left')
df[value_col] = df[value_col] * df['alloc_f']
return df
def duplicate_between_solve_years(df, modeled_years, years):
"""
"""
first_year = np.min(modeled_years)
year_expander = pd.DataFrame(index=years)
year_expander['t_modeled'] = None
year_expander.loc[first_year, ['t_modeled']] = [first_year]
for year in year_expander.index[1:]:
following_model_year = np.min([x for x in modeled_years if x>=year])
if year in list(modeled_years):
year_expander.loc[year,'t_modeled'] = year
else:
year_expander.loc[year,'t_modeled'] = following_model_year
year_expander = year_expander.reset_index().rename(columns={'index':'t'})
df = df.merge(year_expander[['t', 't_modeled']], on='t_modeled', how='left')
return df
### WACC (used for special excluded costs)
def get_wacc_nominal(
debt_fraction=0.55, equity_return_nominal=0.096,
debt_interest_nominal=0.039, tax_rate=0.21):
"""
Inputs
------
debt_fraction: fraction
equity_return_nominal: fraction
debt_interest_nominal: fraction
tax_rate: fraction
Outputs
-------
float: nominal wacc
Sources
-------
ATB2020 WACC Calc spreadsheet
"""
wacc = (
debt_fraction * debt_interest_nominal * (1 - tax_rate)
+ (1 - debt_fraction) * equity_return_nominal
)
return wacc
def get_wacc_real(wacc_nominal, inflation=0.025):
"""
Inputs
------
wacc_nominal: fraction
inflation: fraction (without the 1)
Outputs
-------
float: real wacc (fraction)
Sources
-------
ATB2020 WACC Calc spreadsheet
"""
wacc_real = (1 + wacc_nominal) / (1 + inflation) - 1
return wacc_real
### CRF (used for special excluded costs)
def get_crf(wacc_real, lifetime):
"""
Inputs
------
wacc_real (float) : fraction
lifetime (int) : years
"""
crf = ((wacc_real * (1 + wacc_real) ** lifetime)
/ ((1 + wacc_real) ** lifetime - 1))
return crf
def read_file(filename):
"""
Read input file of various types (for backwards-compatibility)
"""
try:
f = pd.read_hdf(filename+'.h5')
except FileNotFoundError:
try:
f = pd.read_csv(filename+'.csv.gz')
except FileNotFoundError:
try:
f = pd.read_pickle(filename+'.pkl')
except ValueError:
import pickle5
with open(filename+'.pkl', 'rb') as p:
f = pickle5.load(p)
return f
#%% ===========================================================================================
### --- MAIN FUNCTION: RETAIL RATE CALCULATION ---
### ===========================================================================================
def main(run_dir, inputpath='inputs.csv', write=True, verbose=0):
"""
"""
# Get module directory for relative paths
print('Starting retail_rate_calculations.py')
mdir = os.path.dirname(os.path.abspath(__file__))
# #%% Settings for testing/debugging
# run_dir = os.path.join('C:\\', 'Users', 'aschleif', 'Documents', 'ReEDS_', 'ReEDS-2.0',
# 'runs', 'stdscen_091923_Mid_Case')
# mdir = os.path.join('C:\\', 'Users', 'aschleif', 'Documents', 'ReEDS_', 'ReEDS-2.0',
# 'postprocessing', 'retail_rate_module')
# inputpath = 'inputs.csv'
# write = True
# plots = True
# verbose = 0
# plot_dollar_year = 2022
# startyear = 2010
#%% INPUTS - read and parse from inputs.csv (except for ReEDS case, which is provided via command line)
dfinputs = pd.read_csv(inputpath)
# Create a dictionary from the 'inputs' column of dfinputs
inputs = dict(
dfinputs.loc[dfinputs['input_dict']=='inputs',
['input_key','input_value']].values
)
# Ensure that dictionary values are of the proper type
intkeys = [
'working_capital_days', 'trans_timeframe', 'eval_period_overwrite', 'dollar_year',
'drop_pgesce_20182019', 'numslopeyears', 'numprojyears', 'current_t', 'cleanup',
]
floatkeys = ['distloss','FOM_capitalization_rate']
inputs = {key: (int(inputs[key]) if key in intkeys
else float(inputs[key]) if key in floatkeys
else str(inputs[key]))
for key in inputs}
# Create a dictionary from the 'input_daproj' column of dfinputs
input_daproj = dict(
dfinputs.loc[dfinputs.input_dict=='input_daproj',
['input_key','input_value']].values
)
# Ensure that dictionary values are of the proper type
input_daproj = {key: (int(input_daproj[key]) if key in intkeys else str(input_daproj[key]))
for key in input_daproj}
# Create a dictionary from the 'input_eval_periods' column of dfinputs
input_eval_periods = dict(
dfinputs.loc[dfinputs.input_dict=='input_eval_periods',
['input_key','input_value']].values
)
# Ensure that dictionary values are of the proper type
input_eval_periods = {key: int(input_eval_periods[key]) for key in input_eval_periods}
# Create a dictionary from the 'input_depreciation_schedules' column of dfinputs
input_depreciation_schedules = dict(
dfinputs.loc[dfinputs.input_dict=='input_depreciation_schedules',
['input_key','input_value']].values
)
# Ensure that dictionary values are of the proper type
input_depreciation_schedules = {
key: str(int(input_depreciation_schedules[key])) for key in input_depreciation_schedules}
if verbose > 1:
print(f'inputs: \n{inputs}')
print(f'input_daproj: \n{input_daproj}')
print(f'input_eval_periods: \n{input_eval_periods}')
print(f'input_depreciation_schedules: \n{input_depreciation_schedules}')
#%% Start calculations
print(' - Gathering retail rate components')
# Load regions
regions_map = pd.read_csv(
os.path.join(run_dir, 'inputs_case', 'hierarchy.csv')
).rename(columns={'*r':'r','st':'state'})
stacked_regions_map = regions_map[['r', 'state']].drop_duplicates().rename(columns={'r':'region'})
reedsregion2state = dict(zip(stacked_regions_map.region.values, stacked_regions_map.state.values))
states = list(set(reedsregion2state.values()))
# Load map to convert s regions to p regions
rs_map = pd.read_csv(os.path.join(mdir, 'inputs', 'rsmap.csv'))
s2r = dict(zip(rs_map['rs'], rs_map['r']))
# Ingest load from ReEDS
load_rt = (
pd.read_csv(os.path.join(run_dir, 'outputs', 'load_cat.csv')
).rename(columns={'loadtype':'load_category', 'Dim1':'load_category',
'Dim2':'r', 'Dim3':'t', 'Value':'busbar_load', 'Val':'busbar_load'})
)
# Omit extra load categories that include losses; this leaves
# only loads that will count toward electricity sales
omit_list = ['stor_charge', 'trans_loss']
overall_list = list(load_rt['load_category'].drop_duplicates())
final_list = list(set(overall_list) - set(omit_list))
load_rt = load_rt[load_rt['load_category'].isin(final_list)]
load_rt = load_rt.groupby(['r', 't'], as_index=False).agg({'busbar_load':'sum'})
# Use load to identify which regions and which years are covered.
r_list = load_rt['r'].drop_duplicates()
regions_map = regions_map[regions_map['r'].isin(r_list)]
state_list = regions_map['state'].drop_duplicates()
ba_state_map = regions_map[['r', 'state']].drop_duplicates()
# Use load to identify the year span and modeled vs non-modeled years
first_year = load_rt['t'].min()
last_year = load_rt['t'].max()
modeled_years = load_rt['t'].drop_duplicates()
non_modeled_years = list(set(np.arange(first_year,last_year,1)) - set(modeled_years))
years_reeds = np.arange(first_year, last_year+1)
# Ingest inflation
inflation = pd.read_csv(
os.path.join(run_dir, 'inputs_case', 'inflation.csv'), index_col='t'
).squeeze(1)
#%% Derive loads, customer counts, energy intensities
load_rt = interp_between_solve_years(
load_rt, 'busbar_load', modeled_years, non_modeled_years, first_year,
last_year, r_list, 'r'
)
load_rt['end_use_load'] = load_rt['busbar_load'] * (1 - inputs['distloss'])
load_rt = load_rt.merge(ba_state_map, on='r', how='left')
load_by_state = load_rt.groupby(
['state', 't'], as_index=False
).agg({'busbar_load':'sum', 'end_use_load':'sum'})
load_by_state_eia = pd.read_csv(os.path.join(mdir, 'load_by_state_eia.csv'))
load_by_state_eia['busbar_load'] = (
load_by_state_eia['end_use_load'] / (1 - inputs['distloss']))
# Subset the historical years and append to the project load in ReEDS
load_historical = load_by_state_eia[load_by_state_eia['t']<first_year]
load_by_state = pd.concat([
load_by_state,
load_historical[['state', 't', 'busbar_load', 'end_use_load']]],
sort=False).reset_index(drop=True)
first_hist_year = load_by_state['t'].min() # cutoff for historical calculations
# Initialize the main dfall, which tracks outputs by [state, year]
dfall = pd.DataFrame(
list(itertools.product(state_list, np.arange(first_hist_year, last_year+1))),
columns=['state', 't'])
dfall = dfall.merge(
load_by_state[['state', 't', 'busbar_load', 'end_use_load']],
on=['state', 't'], how='left')
#%% Ingest system_costs, which includes some capital expenditures and all operational expenditures
# Note that the values can be either 'r' or 's' region type in this file
system_costs = pd.read_csv(
os.path.join(run_dir, 'outputs', 'systemcost_ba_retailrate.csv'))
system_costs = system_costs.rename(
columns={'sys_costs':'cost_type', 'r':'region', 't':'t', 'Value':'cost',
'Dim1':'cost_type','Dim2':'region','Dim3':'t','Val':'cost'})
# Convert s regions to p regions if necessary
system_costs.loc[system_costs['region'].str.contains('s'), 'region'] = (
system_costs.loc[system_costs['region'].str.contains('s'), 'region'].map(s2r))
system_costs = system_costs.groupby(
by=['cost_type', 'region', 't'], as_index=False).agg({'cost':'sum'})
system_costs['cost'] = system_costs['cost'].replace('Undf',0).astype(float)
# Merge on state
system_costs = system_costs.merge(
stacked_regions_map[['region', 'state']], on='region', how='left')
#%% Ingest capital financing assumptions
# Note that these assumptions are for a regulated utility, whereas ReEDS uses
# technology-specific financing from an IPP perspective.
financepath = inputs['financefile']
if not os.path.exists(financepath):
financepath = os.path.join(mdir, financepath)
df_finance = pd.read_csv(financepath, index_col='t')
#%%####################################
# -- State-Flow Expenditures -- #
#######################################
print(' - State-Flow Expenditures')
# Digest State Expenditure flows
state_flows = (
pd.read_csv(os.path.join(run_dir, 'outputs', 'expenditure_flow.csv'))
.rename(columns={
'*':'price_type', 'r':'sending_region',
'rr':'receiving_region', 't':'t', 'Value':'expenditure_flow',
'Dim1':'price_type', 'Dim2':'sending_region',
'Dim3':'receiving_region', 'Dim4':'t', 'Val':'expenditure_flow'})
)
state_rps_flows = (
pd.read_csv(os.path.join(run_dir, 'outputs', 'expenditure_flow_rps.csv'))
.rename(columns={
'st':'sending_state', 'ast':'receiving_state', 'Value':'expenditure_flow',
'Dim1':'sending_state', 'Dim2':'receiving_state',
'Dim3':'t', 'Val':'expenditure_flow'})
)
state_rps_flows['price_type'] = 'rps'
###### International flows
state_international_flows = (
pd.read_csv(os.path.join(run_dir, 'outputs', 'expenditure_flow_int.csv'))
.rename(columns={
'r':'receiving_region', 't':'t', 'Value':'expenditure_flow',
'Dim1':'receiving_region','Dim2':'t','Val':'expenditure_flow'})
)
### According to e_report.gms, all international flows are load to/from Canada
# (not capacity, reserves, rps, or Mexico)
state_international_flows['price_type'] = 'load'
state_international_flows['sending_state'] = 'Canada'
### International exports are negative expenditures, imports are positive
state_international_flows['flowtype'] = state_international_flows['expenditure_flow'].map(
lambda x: 'export' if x<0 else 'import')
### Map regions to states
state_international_flows['receiving_state'] = (
state_international_flows['receiving_region'].map(reedsregion2state))
### Change sign and sending/receiving state to match conventions for intra-US flows
for i in state_international_flows.index:
if state_international_flows.loc[i,'expenditure_flow'] < 0:
(state_international_flows.loc[i,'sending_state'],
state_international_flows.loc[i,'receiving_state']) = (
state_international_flows.loc[i,'receiving_state'],
state_international_flows.loc[i,'sending_state'])
state_international_flows.loc[i,'expenditure_flow'] = (
-state_international_flows.loc[i,'expenditure_flow'])
# Map regions to states
state_flows['sending_state'] = state_flows['sending_region'].map(reedsregion2state)
state_flows['receiving_state'] = state_flows['receiving_region'].map(reedsregion2state)
# Filter Intrastate Expenditure Flows
state_flows = pd.concat([
state_flows.loc[state_flows['sending_state'] != state_flows['receiving_state']],
state_rps_flows,
state_international_flows],
sort=False)
# Aggregate imports and exports by year, type and state
sent_expenditures = state_flows.groupby(
by=['price_type','t', 'sending_state'], as_index=False
).agg({'expenditure_flow':'sum'}).rename(columns={
'sending_state':'state', 'expenditure_flow':'expenditure_exports'})
received_expenditures = state_flows.groupby(
by=['price_type','t', 'receiving_state'], as_index=False
).agg({'expenditure_flow':'sum'}).rename(columns={
'receiving_state':'state', 'expenditure_flow':'expenditure_imports'})
state_flow_expenditures = sent_expenditures.merge(
received_expenditures, on=['price_type', 't', 'state'], how='outer').fillna(0)
# As costs are positive, subtract exports (revenue) from imports (costs)
state_flow_expenditures['net_interstate_expenditures'] = (
state_flow_expenditures['expenditure_imports']
- state_flow_expenditures['expenditure_exports'])
state_flow_expenditures = state_flow_expenditures.groupby(
['t', 'state', 'price_type'])['net_interstate_expenditures'].sum(
).unstack('price_type').reset_index()
state_flow_expenditures = state_flow_expenditures.add_suffix('_flow').rename(
columns={'t_flow':'t', 'state_flow':'state'})
state_flow_expenditures_expanded = interp_between_solve_years(
state_flow_expenditures, 'load_flow', modeled_years, non_modeled_years,
first_year, last_year, state_list, 'state')
if 'oper_res_flow' in state_flow_expenditures:
state_flow_expenditures_expanded = state_flow_expenditures_expanded.merge(
interp_between_solve_years(
state_flow_expenditures, 'oper_res_flow', modeled_years,
non_modeled_years, first_year, last_year, state_list, 'state'),
on=['t', 'state'])
if 'rps_flow' in state_flow_expenditures:
state_flow_expenditures_expanded = state_flow_expenditures_expanded.merge(
interp_between_solve_years(
state_flow_expenditures, 'rps_flow', modeled_years,
non_modeled_years, first_year, last_year, state_list, 'state'),
on=['t', 'state'])
state_flow_expenditures_expanded = state_flow_expenditures_expanded.merge(
interp_between_solve_years(
state_flow_expenditures, 'res_marg_ann_flow', modeled_years,
non_modeled_years, first_year, last_year, state_list, 'state'),
on=['t', 'state'])
### Canada is dropped since we merge left
dfall = dfall.merge(
state_flow_expenditures_expanded, on = ['t','state'], how = 'left').fillna(0)
#%%#############################################
# -- Operational (pass-through) costs -- #
################################################
# All "op_" values in the systemcost_ba output file are assumed to be pass-through
# operational costs (i.e. not part of the rate base)
print(' - Operational (pass-through) Expenditures')
# Excluded costs
op_costs_types_omitted = ['op_transmission_fom',
'op_ptc_payments_negative',
'op_co2_incentive_negative',
'op_h2_ptc_payments_negative',
'op_h2_storage',
'op_h2_transport',
'op_h2_fuel_costs',
'op_h2_vom',
'op_consume_vom',
'op_consume_fom']
# Identify operational costs (by the op_ prefix) and extract just those
op_cost_types = [i for i in system_costs['cost_type'].drop_duplicates()
# Leave out 'op_transmission_fom' for now since it's already accounted
# for separately in 'op_trans' (using FERC data instead of ReEDS)
if (('op_' in i) and (i not in op_costs_types_omitted))]
op_costs_modeled_years = system_costs[system_costs['cost_type'].isin(op_cost_types)].copy()
# Group to states
op_costs_modeled_years = op_costs_modeled_years.groupby(
by=['cost_type', 't', 'state'], as_index=False).agg({'cost':'sum'})
# Expand op_costs to include all years (not just model years),
# interpolating the costs between model years
op_costs = pd.DataFrame()
for op_cost_type in op_cost_types:
op_costs_single = (
op_costs_modeled_years[op_costs_modeled_years['cost_type']==op_cost_type]
.rename(columns={'cost':op_cost_type}))
op_costs_single = interp_between_solve_years(
op_costs_single, op_cost_type, modeled_years, non_modeled_years,
first_year, last_year, state_list, 'state')
op_costs_single['cost_type'] = op_cost_type
op_costs_single = op_costs_single.rename(columns={op_cost_type:'cost'})
op_costs = pd.concat([op_costs, op_costs_single], sort=False).reset_index(drop=True)
op_costs_pivot = op_costs.pivot_table(
index=['t', 'state'], columns='cost_type', values='cost', fill_value=0.0).reset_index()
### Redistributing the DAC op costs
# DAC has negative CO2 emissions, which allows fossil generators to continue to operate.
# This redistribution shares the cost of the DAC with any region that is still emitting CO2.
# In this way, states with fossil units but no DAC still incur costs for the DAC.
if 'op_co2_transport_storage' in op_costs_pivot.columns:
# Reading in the BA-level emissions
emissions_r = (
pd.read_csv(os.path.join(run_dir, 'outputs', 'emit_r.csv'))
.rename(columns={'eall':'type', 'r':'r', 't':'t', 'Value':'emissions',
'Dim1':'type', 'Dim2':'r', 'Dim3':'t', 'Val':'emissions'}))
# Consider only CO2-equivalent emissions
emissions_r = emissions_r[emissions_r['type']=='CO2e']
emissions_r.drop('type', axis=1, inplace=True)
# Load the list of BAs with emissions
r_list_emissions = emissions_r['r'].drop_duplicates()
# Interpolate the emissions in between the solve years
emissions_r = interp_between_solve_years(
emissions_r, 'emissions', modeled_years, non_modeled_years, first_year, last_year, r_list_emissions, 'r')
# Remove negative emissions
emissions_r.loc[emissions_r['emissions'] < 0, 'emissions'] = 0
# Matching the BAs with the respective states
# regions_map_emissions = pd.read_csv(os.path.join(run_dir, 'inputs_case', 'regions.csv')).rename(
# columns={'p':'r','st':'state'})
regions_map_emissions = regions_map.copy()[['r','state']]
regions_map_emissions = regions_map_emissions[regions_map_emissions['r'].isin(r_list_emissions)]
ba_state_map_emissions = regions_map_emissions[['r', 'state']].drop_duplicates()
# Consolidating emissions by state
emissions_r = emissions_r.merge(ba_state_map_emissions, on='r', how='left')
emissions_by_state = emissions_r.groupby(['state', 't'], as_index=False).sum()
emissions_by_state = emissions_by_state.pivot_table(
index='t', columns='state', values='emissions').fillna(0)
# Filling in zero for states where no emissions info is available
num_states = len(state_list)
if num_states != emissions_by_state.shape[1]:
col_list = list(emissions_by_state.columns)
missing_states = list(set(state_list) - set(col_list))
for state in missing_states:
emissions_by_state[state] = 0
# Calculating the fraction of emissions by state
emissions_by_state['Total'] = emissions_by_state.sum(axis=1)
emissions_by_state_fraction = emissions_by_state.copy()
st_cols = [c for c in emissions_by_state.columns if c != 'Total']
emissions_by_state_fraction[st_cols] = (
emissions_by_state_fraction[st_cols].div(emissions_by_state_fraction['Total'], axis=0)
)
emissions_by_state_fraction.drop(columns=['Total'], inplace=True)
del st_cols
# Redistributing DAC costs by emissions fraction
op_costs_dac_corrections = op_costs_pivot[['t','state','op_co2_transport_storage']].copy()
op_costs_dac_corrections['op_co2_transport_storage'] = 0
op_costs_dac_corrections = op_costs_dac_corrections.pivot_table(
index='t', columns='state', values='op_co2_transport_storage')
for i in range(op_costs_pivot.shape[0]):
cost = op_costs_pivot.loc[i, 'op_co2_transport_storage']
year = op_costs_pivot.loc[i, 't']
multiplier = emissions_by_state_fraction.loc[year]
assert(multiplier.shape[0]==num_states)
op_costs_dac_corrections.loc[year] += (cost * multiplier)
# Assigining the redistributed DAC costs to the orginal dataframe
op_costs_dac_corrections = op_costs_dac_corrections.T
op_costs_dac_corrections_unstacked = op_costs_dac_corrections.unstack()
op_costs_pivot['op_co2_transport_storage'] = op_costs_dac_corrections_unstacked.values
#%%
# Extrapolate FOM costs backwards using the constant normalized cost by load
# from first modeled year
historical_years = np.arange(load_by_state['t'].min(), load_rt['t'].min() )
df_extrapolate = pd.DataFrame(
list(itertools.product(state_list, historical_years)),
columns=['state', 't'])
op_costs_pivot = op_costs_pivot.merge(
load_by_state[['state', 't', 'end_use_load']],
on=['state', 't'], how='left')
op_costs_first_year = (
op_costs_pivot.loc[op_costs_pivot['t'] == 2010,
['state', 'end_use_load', 'op_fom_costs']])
op_costs_first_year = op_costs_first_year.rename(
columns={'end_use_load':'load_first_year', 'op_fom_costs':'op_fom_costs_first_year'})
df_extrapolate = df_extrapolate.merge(op_costs_first_year, on=['state'], how='left')
df_extrapolate = df_extrapolate.merge(load_by_state, on=['state', 't'], how='left')
df_extrapolate['op_fom_costs'] = (
df_extrapolate['end_use_load']
/ df_extrapolate['load_first_year']
* df_extrapolate['op_fom_costs_first_year'])
df_extrapolate = df_extrapolate[['t','state','op_fom_costs']]
op_costs_pivot = pd.concat([op_costs_pivot, df_extrapolate], sort=False)
op_costs_pivot['op_fom_costs'] = (
(1-inputs['FOM_capitalization_rate']) * op_costs_pivot['op_fom_costs'])
# Merge on financing assumptions, for calculating return on working capital,
# which we consider an operating cost
op_costs_pivot = op_costs_pivot.merge(df_finance, on='t', how='left')
# Working capital is the net value of current assets minus current liabilities
# that the utility needs to conduct its operations. We estimate the total amount
# of working capital as the equivalent of 45 days of all operating expenses
# (i.e., 45/365 × annual operating expenses).
op_costs_pivot['wc'] = (
(inputs['working_capital_days'] / 365) * op_costs_pivot[op_cost_types].sum(axis=1))
op_costs_pivot['op_wc_debt_interest'] = (
op_costs_pivot['wc'] * op_costs_pivot['debt_fraction']
* op_costs_pivot['debt_interest_nominal'])
op_costs_pivot['op_wc_equity_return'] = (
op_costs_pivot['wc']
* (1.0 - op_costs_pivot['debt_fraction'])
* op_costs_pivot['equity_return_nominal'])
op_costs_pivot['op_wc_return_to_capital'] = (
op_costs_pivot['op_wc_debt_interest'] + op_costs_pivot['op_wc_equity_return'])
op_costs_pivot['op_wc_income_tax'] = (
op_costs_pivot['op_wc_equity_return'] / (1.0 - op_costs_pivot['tax_rate'])
- op_costs_pivot['op_wc_equity_return'])
dfall = dfall.merge(
op_costs_pivot[
op_cost_types
+ ['t', 'state', 'op_wc_debt_interest', 'op_wc_equity_return', 'op_wc_income_tax']],
on=['t', 'state'], how='left')
#%%#################################
# -- Capital Expenditures -- #
####################################
print(' - Capital Expenditures')
# Calculate the portion of FOM costs that are capitalized,
# and use that to initialize the df_capex dataframe
df_fom_capitalized = op_costs_pivot[['t', 'state', 'op_fom_costs']].copy()
df_fom_capitalized['capex'] = (
df_fom_capitalized['op_fom_costs']
/ (1.0 - inputs['FOM_capitalization_rate']) * inputs['FOM_capitalization_rate'])
df_fom_capitalized.drop(columns=['op_fom_costs'], inplace=True)
df_fom_capitalized['eval_period'] = input_eval_periods['fom_capitalized']
df_fom_capitalized['depreciation_sch'] = input_depreciation_schedules['fom_capitalized']
df_fom_capitalized['i'] = 'capitalized_fom'
df_fom_capitalized['region'] = None
df_fom_capitalized['cost_cat'] = 'cap_fom'
# df_capex has all capital expenditures, including historical expenditures
df_capex = df_fom_capitalized.copy()
#%% Calculate capex for generators, add to df_capex
# Note that it would be better to directly calculate the capital expenditures within ReEDS,
# but we have not implemented that approach yet.
# Ingest annual capacity builds (note that cap_new_ivrt includes refurbished capacity)
cap_new_ivrt = pd.read_csv(
os.path.join(run_dir, 'outputs', 'cap_new_ivrt.csv')
).rename(columns={
'i':'i', 'r':'region', 't':'t_modeled', 'Value':'cap_new',
'Dim1':'i', 'Dim2':'v', 'Dim3':'region', 'Dim4':'t_modeled', 'Val':'cap_new'})
# Convert s regions to p regions if necessary
cap_new_ivrt.loc[cap_new_ivrt['region'].str.contains('s'), 'region'] = (
cap_new_ivrt.loc[cap_new_ivrt['region'].str.contains('s'), 'region'].map(s2r))
cap_new_ivrt = cap_new_ivrt.groupby(
by=['i', 'region', 't_modeled'], as_index=False).agg({'cap_new':'sum'})
# Equally distribute the capacity across the solve years. This is not exactly how ReEDS
# sees it, but smooths out some unrealistic periodicity in the expensing patterns that
# would otherwise appear.
cap_new_ivrt_distributed = distribute_between_solve_years(
cap_new_ivrt, 'cap_new', modeled_years, years_reeds)
# Calculate the capital cost multipliers. This includes the construction interest multiplier
# and regional capital cost multipliers, but not other adjustments like the ITC or depreciation.
ccmult = pd.read_csv(
os.path.join(run_dir, 'inputs_case', 'ccmult.csv'))
reg_cap_cost_mult = pd.read_csv(
os.path.join(run_dir, 'inputs_case', 'reg_cap_cost_mult.csv'))
cap_cost_mult = ccmult.merge(reg_cap_cost_mult, on='*i', how='outer')
cap_cost_mult[['CCmult', 'reg_cap_cost_mult']] = (
cap_cost_mult[['CCmult', 'reg_cap_cost_mult']].fillna(1.0))
cap_cost_mult.rename(columns={'r':'region', '*i':'i'}, inplace=True)
cap_cost_mult['cap_cost_mult_for_ratebase'] = (
cap_cost_mult['CCmult'] * cap_cost_mult['reg_cap_cost_mult'])
# Ingest remaining technology capital costs, adjust for multipliers
cost_cap = pd.read_csv(
os.path.join(run_dir, 'outputs', 'cost_cap.csv')
).rename(columns={
'i':'i', 't':'t', 'Value':'cost_cap',
'Dim1':'i', 'Dim2':'t', 'Val':'cost_cap'})
cost_cap = cap_cost_mult.merge(cost_cap, on=['i', 't'], how='left')
cost_cap['cost_cap'] = cost_cap['cost_cap'] * cost_cap['cap_cost_mult_for_ratebase']
#%% ### Redistribute DAC Capital costs
# See comments above for the redistribution of DAC operating costs
if 'dac' in list(cost_cap['i'].drop_duplicates()):
# Reading in the BA-level emissions
emissions_r = pd.read_csv(os.path.join(run_dir, 'outputs', 'emit_r.csv'))
if emissions_r.shape[1] == 4:
emissions_r = emissions_r.rename(
columns={'eall':'type', 'r':'r', 't':'t', 'Value':'emissions',
'Dim1':'type', 'Dim2':'r', 'Dim3':'t', 'Val':'emissions'})
emissions_r = emissions_r[emissions_r['type']=='CO2e']
emissions_r.drop('type', axis=1, inplace=True)
else:
emissions_r = emissions_r.rename(
columns={'r':'r', 't':'t', 'Value':'emissions',
'Dim1':'r', 'Dim2':'t', 'Val':'emissions'})
# Load the list of BAs with emissions
r_list_emissions = emissions_r['r'].drop_duplicates()
# Interpolate the emissions in between the solve years
emissions_r = interp_between_solve_years(
emissions_r, 'emissions', modeled_years, non_modeled_years, first_year,
last_year, r_list_emissions, 'r')
# Remove negative emissions
emissions_r.loc[emissions_r['emissions'] < 0, 'emissions'] = 0
# Calculating the fraction of emissions by BA
emissions_r = emissions_r.pivot_table(
index='t', columns='r', values='emissions').fillna(0)
emissions_r['Total'] = emissions_r.sum(axis=1)
ba_cols = [c for c in emissions_r.columns if c != 'Total']
emissions_r_fraction = emissions_r.copy()
emissions_r_fraction[ba_cols] = (
emissions_r_fraction[ba_cols].div(emissions_r_fraction['Total'], axis=0)
)
emissions_r_fraction.drop(columns=['Total'], inplace=True)
del ba_cols
# Redistributing DAC costs by emissions fraction
cap_costs_dac = cost_cap[cost_cap['i']=='dac'].fillna(0)
# cap_costs_dac.drop(['i', 'cap_cost_mult_for_ratebase'], axis=1, inplace=True)
cap_costs_dac.drop(['i'], axis=1, inplace=True)
cap_costs_dac = cap_costs_dac.rename(columns={'region':'r'})
cap_costs_dac = cap_costs_dac.reset_index(drop=True)
cap_costs_dac_pivot = cap_costs_dac.pivot_table(
index='r', columns='t', values='cost_cap')
cap_costs_dac_corrections = copy.deepcopy(cap_costs_dac_pivot)
cap_costs_dac_corrections.loc[:, :] = 0
# Remove missing BAs where emissions info is not available
missing_r = list(set(cap_costs_dac_corrections.index) - set(emissions_r_fraction.columns))
cap_costs_dac_corrections.drop(missing_r, axis=0, inplace=True)
num_r = cap_costs_dac_corrections.shape[0]
# Recalculate the DAC capital costs
for i in range(cap_costs_dac.shape[0]):
cost = cap_costs_dac.loc[i, 'cost_cap']
year = cap_costs_dac.loc[i, 't']
if year <= last_year:
multiplier = emissions_r_fraction.loc[year]
assert(multiplier.shape[0]==num_r)
cap_costs_dac_corrections.loc[:,year] += (cost * multiplier)
# Assign zero to missing BAs
for r in missing_r:
cap_costs_dac_corrections.loc[r, :] = 0
# Assigning the redistributed DAC costs to the original dataframe
for i in range(cap_costs_dac.shape[0]):
year = cap_costs_dac.loc[i, 't']
if year <= last_year:
region = cap_costs_dac.loc[i, 'r']
cap_costs_dac.loc[i, 'cost_cap'] = cap_costs_dac_corrections.loc[region, year]
cost_cap.loc[cost_cap['i']=='dac', 'cost_cap'] = cap_costs_dac['cost_cap'].values
#%%
# Merge on cost_cap to the cap additions
df_gen_capex = cap_new_ivrt_distributed[['i', 'region', 't', 'cap_new']].copy()
# Get rid of the v index
df_gen_capex = df_gen_capex.groupby(
by=['i', 'region', 't'], as_index=False).agg({'cap_new':'sum'})
# Read in generator capex
# All costs except upgrades are calculated using cost_cap_fin_mult_no_credits
# Upgrade costs are calculated using cost_cap_fin_mult_out (full ITC/PTC/depreciation)
df_capex_irt = pd.read_csv(
os.path.join(run_dir, 'outputs', 'capex_ivrt.csv')
).rename(columns={
'r':'region', 't':'t_modeled', 'Value':'capex',
'Dim1':'i', 'Dim3':'region', 'Dim4':'t_modeled', 'Val':'capex'})
# Convert s regions to p regions if necessary
df_capex_irt.loc[df_capex_irt['region'].str.contains('s'), 'region'] = (
df_capex_irt.loc[df_capex_irt['region'].str.contains('s'), 'region'].map(s2r))
# Get rid of the v index
df_capex_irt = df_capex_irt.groupby(
by=['i', 'region', 't_modeled'], as_index=False).agg({'capex':'sum'})
# Read in Tech|BA-Level system costs
# Most costs are calculated using cost_cap_fin_mult_noITC
# rsc tech costs are calculated using rsc_fin_mult or rsc_fin_mult_noITC
invcapcosts = ['inv_h2_production', 'inv_investment_capacity_costs',
'inv_investment_refurbishment_capacity',
'inv_investment_spurline_costs_rsc_technologies',]
df_syscost_irt = pd.read_csv(
os.path.join(run_dir, 'outputs', 'systemcost_techba.csv')
).rename(columns={
'r':'region', 't':'t_modeled', 'Value':'capex',
'Dim1':'sys_costs', 'Dim2':'i', 'Dim3':'region', 'Dim4':'t_modeled', 'Val':'capex'})
df_syscost_irt = df_syscost_irt[df_syscost_irt['sys_costs'].isin(invcapcosts)]
# Convert s regions to p regions if necessary
df_syscost_irt.loc[df_syscost_irt['region'].str.contains('s'), 'region'] = (
df_syscost_irt.loc[df_syscost_irt['region'].str.contains('s'), 'region'].map(s2r))
df_syscost_irt = df_syscost_irt.groupby(
by=['i', 'region', 't_modeled'], as_index=False).agg({'capex':'sum'})
# Merge and take maximum of two capex sources
df_capex_irt = df_capex_irt.merge(
df_syscost_irt, on=['i', 'region', 't_modeled'], how='outer',
suffixes=('_capex','_syscost'))
df_capex_irt['capex'] = df_capex_irt[['capex_capex', 'capex_syscost']].max(axis=1)
df_capex_irt = df_capex_irt[['i', 'region', 't_modeled', 'capex']]
# Distribute among all years / between solve years
df_capex_irt_distributed = distribute_between_solve_years(
df_capex_irt, 'capex', modeled_years, years_reeds)
# Merge new capacity and capex
df_gen_capex = df_gen_capex.merge(
df_capex_irt_distributed[['i', 'region', 't', 'capex']],
on=['i', 'region', 't'], how='outer')
#%% # Ingest evaluation period and tax depreciation schedule info for generators
eval_period = read_file(os.path.join(run_dir, 'inputs_case', 'retail_eval_period'))
depreciation_sch = read_file(os.path.join(run_dir,'inputs_case','retail_depreciation_sch'))
depreciation_sch['depreciation_sch'] = depreciation_sch['depreciation_sch'].astype(str)
# Merge generator capex on eval_period and depreciation_sch
df_gen_capex = df_gen_capex.merge(
eval_period[['i', 't', 'eval_period']],
on=['i', 't'], how='left')
# Fill in any missing eval_period with the default 20 years
# This should apply to upgrades only
df_gen_capex['eval_period'].fillna(20, inplace=True)
df_gen_capex = df_gen_capex.merge(
depreciation_sch[['i', 't', 'depreciation_sch']],
on=['i', 't'], how='left')
# Fill in any missing eval_period with the default 20 years
# This should also apply to upgrades only
df_gen_capex['depreciation_sch'].fillna('20', inplace=True)
#%% # For pre-2010 capital expenditures, we use a pre-calculated result.
# The expenditures are based on a EIA-NEMS database of historical capacity
# builds, using the 2010 capital costs from the 2019 version of ReEDS.
# The values in this file are in 2004 dollars. This file is generated by
# calc_historical_capex.py
df_gen_capex_init = pd.read_csv(
os.path.join(mdir, 'calc_historical_capex', 'df_capex_init.csv'))
df_gen_capex_init = df_gen_capex_init[df_gen_capex_init['t']<=first_year]
df_gen_capex_init = df_gen_capex_init[df_gen_capex_init['t']>=first_hist_year]
# Convert s regions to p regions
df_gen_capex_init.loc[df_gen_capex_init['region'].str.contains('s'), 'region'] = (
df_gen_capex_init.loc[df_gen_capex_init['region'].str.contains('s'), 'region'].map(s2r))
df_gen_capex_init = df_gen_capex_init.groupby(
by=['i', 'region', 't'], as_index=False).agg({'cap_new':'sum', 'capex':'sum'})
# Find tech-region-year combos for historical builds,
# for expanding out eval_period and dep_schedules
init_irt = df_gen_capex_init[['i', 'region', 't']].copy().drop_duplicates()
# Expand eval_period for historical builds (assigning historical builds the earliest data)
eval_period_init = init_irt.copy()
eval_period_init = eval_period_init.merge(
eval_period[eval_period['t']==first_year][['i', 'eval_period']],
on='i', how='left')
eval_period_init = eval_period_init[eval_period_init['t']<=first_year]
# Expand depreciation_sch for historical builds (assigning historical builds the earliest data)
dep_sch_init = init_irt.copy()
dep_sch_init = dep_sch_init.merge(
depreciation_sch[depreciation_sch['t']==first_year][['i', 'depreciation_sch']],
on='i', how='left')
dep_sch_init = dep_sch_init[dep_sch_init['t']<=first_year]
# Merge on eval_period, depreciation_sch, state, and cost category for generator capex
df_gen_capex_init = df_gen_capex_init.merge(
eval_period_init[['i', 'region', 't', 'eval_period']],
on=['i', 'region', 't'], how='left')
# Fill in any missing eval_period with the default 20 years
df_gen_capex_init['eval_period'].fillna(20, inplace=True)
df_gen_capex_init = df_gen_capex_init.merge(
dep_sch_init[['i', 'region', 't', 'depreciation_sch']],
on=['i', 'region', 't'], how='left')
df_gen_capex_init['depreciation_sch'].fillna('20', inplace=True)
#%% # Combine both new and historical capital expenditures
df_gen_capex = pd.concat(
[df_gen_capex, df_gen_capex_init], sort=False).reset_index(drop=True)
df_gen_capex = df_gen_capex.merge(
stacked_regions_map[['region', 'state']], on=['region'], how='left')
df_gen_capex['cost_cat'] = 'cap_gen'
# Remove null capex values to remove distpv
# Also removes 5 MW pumped-hydro built in p64 in 2012 (cap_new but no capex)
df_gen_capex.dropna(
axis=0, how='all', subset='capex', inplace=True, ignore_index=True)
# Toggle to test for longer accounting depreciation periods.
if inputs['eval_period_overwrite'] != 0:
df_gen_capex['eval_period'] = inputs['eval_period_overwrite']
# Add generator capex to df_capex
df_capex = pd.concat(
[df_capex,
df_gen_capex[
['i', 'region', 'state', 't', 'cost_cat', 'capex',
'eval_period', 'depreciation_sch']]],
sort=False).reset_index(drop=True)
#%% Add non-generator, within-ReEDS capital expenditures to df_capex
# Transmission, converter, and intertie capital expenditures
# These could be wrapped into various other cost types (intra-BA transmission,