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 | def postprocessing(Result, df_annual=True, df_flow=True, df_monthly=True) -> Result:
"""
Performs post-processing of EnergyScope results by organizing and categorizing key metrics into annual and monthly dataframes.
Adds a new column "Annual_Use" to the `df_annual` DataFrame.
Parameters:
----------
Result : object
The result object containing the outputs of the model's run.
df_annual : bool, optional
If True, the function processes and stores annual results, including investment costs, maintenance costs, production, and the economic lifetimes (tau) of technologies. Defaults to True.
df_flow : bool, optional
If True, the function processes and stores flows of energy. Defaults to True.
df_monthly : bool, optional
If True, the function processes and stores monthly results, including the flows of different technologies. Defaults to True.
Only available for models with a monthly resolution (variable 'F_Mult_t'): skipped with a warning otherwise
(e.g. core model, which uses typical days).
Returns:
-------
Result : object
The updated Result object, containing the processed dataframes.
"""
sector_technologies = {
"Electricity": ["CCGT", "CCGT_CC", "COAL_US", "COAL_IGCC", "COAL_US_CC", "COAL_IGCC_CC", "HYDRO_GAS_CHP"],
"Nuclear": ["NUCLEAR"],
"Mobility": ["TRAMWAY", "COACH_CNG_STOICH", "COACH_DIESEL", "COACH_EV", "COACH_FC_HYBRID_H2",
"COACH_FC_HYBRID_CH4", "COACH_HY_DIESEL", "COMMUTER_RAIL_DIESEL", "COMMUTER_RAIL_ELEC",
"TRAIN_DIESEL",
"TRAIN_ELEC", "TRAIN_NG", "TRAIN_H2", "BUS_CNG_STOICH", "BUS_DIESEL", "BUS_FC_HYBRID_H2",
"BUS_FC_HYBRID_CH4", "BUS_HY_DIESEL", "BUS_EV", "CAR_BEV_LOWRANGE", "CAR_BEV_MEDRANGE_LOCAL",
"CAR_DIESEL_LOCAL", "CAR_DME_D10_LOCAL", "CAR_ETOH_E10_LOCAL", "CAR_ETOH_E85_LOCAL",
"CAR_FC_H2_LOCAL",
"CAR_FC_CH4_LOCAL", "CAR_GASOLINE_LOCAL", "CAR_HEV_LOCAL", "CAR_MEOH_LOCAL", "CAR_NG_LOCAL",
"CAR_PHEV_LOCAL", "CAR_BEV_MEDRANGE_LONGD", "CAR_DIESEL_LONGD", "CAR_DME_D10_LONGD",
"CAR_ETOH_E10_LONGD",
"CAR_ETOH_E85_LONGD", "CAR_FC_H2_LONGD", "CAR_FC_CH4_LONGD", "CAR_GASOLINE_LONGD", "CAR_HEV_LONGD",
"CAR_HEV", "CAR_MEOH_LONGD", "CAR_NG_LONGD", "CAR_PHEV_LONGD", "TRAIN_FREIGHT",
"TRAIN_FREIGHT_DIESEL",
"TRAIN_FREIGHT_NG", "TRAIN_FREIGHT_H2", "TRUCK", "TRUCK_CO2", "TRUCK_EV", "TRUCK_SNG", "TRUCK_FC",
"PLANE",
"CAR_GASOLINE", "CAR_DIESEL", "CAR_NG", "CAR_PHEV", "CAR_MEOH", "CAR_FC_H2", "CAR_FC_CH4",
"CAR_BEV_MEDRANGE", "CAR_ETOH_E10", "CAR_ETOH_E85", "CAR_DME_D10"],
"Electric Infrastructure": ["TRAFO_ML", "TRAFO_LM", "TRAFO_HM", "TRAFO_MH", "TRAFO_EH", "TRAFO_HE", "EHV_GRID",
"HV_GRID", "MV_GRID", "LV_GRID", "GRID"],
"Gas Infrastructure": ["EHP_H2_GRID", "HP_H2_GRID", "MP_H2_GRID", "LP_H2_GRID", "EHP_NG_GRID", "HP_NG_GRID",
"MP_NG_GRID", "LP_NG_GRID", "NG_EXP_EH", "NG_EXP_HM", "NG_EXP_ML", "NG_EXP_EH_COGEN",
"NG_EXP_HM_COGEN",
"NG_EXP_ML_COGEN", "NG_COMP_HE", "NG_COMP_MH", "NG_COMP_LM", "H2_EXP_EH", "H2_EXP_HM",
"H2_EXP_ML",
"H2_EXP_EH_COGEN", "H2_EXP_HM_COGEN", "H2_EXP_ML_COGEN", "H2_COMP_HE", "H2_COMP_MH",
"H2_COMP_LM"],
"Wind": ["WIND", "WIND_ONSHORE", "WIND_OFFSHORE"], "PV": ["PV_LV", "PV_MV", "PV_HV", "PV_EHV", "PV"],
"Geothermal": ["GEOTHERMAL", "DHN_DEEP_GEO", "DEC_DEEP_GEO"],
"Hydro River & Dam": ["NEW_HYDRO_RIVER", "NEW_HYDRO_DAM", "HYDRO_RIVER", "HYDRO_DAM"],
"Industry": ["AL_MAKING", "AL_MAKING_HR", "CEMENT_PROD", "CEMENT_PROD_HP", "FOOD_PROD", "FOOD_PROD_HP",
"FOOD_PROD_HR", "PAPER_MAKING", "PAPER_MAKING_HP", "PAPER_MAKING_HR", "STEEL_MAKING",
"STEEL_MAKING_HP",
"STEEL_MAKING_HR", "WOOD_METHANOL", "CO2_METHANOL", "METHANOL_FT", "METHANE_TO_METHANOL",
"CUMENE_PROCESS",
"METHANOL_CARBONYLATION", "ETHANE_OXIDATION", "ETHYLENE_POLYMERIZATION", "PET_FORMATION",
"PVC_FORMATION",
"POLYPROPYLENE_PP", "STYRENE_POLYMERIZATION", "HYDRO_GAS", "AN_DIG_SI", "BIOMASS_ETHANOL", "FT",
"AN_DIG",
"SNG_NG", "EFFICIENCY", "METHANATION", "GASIFICATION_SNG", "PYROLYSIS", "NG_REFORMING",
"METHANOL_TO_AROMATICS", "METHANOL_TO_OLEFINS", "CO2-To-Diesel", "ETHANE_CRACKING",
"METATHESIS_PROPYLENE",
"SMART_PROCESS", "CROPS_TO_JETFUELS", "CO2_TO_JETFUELS", "BIOGAS_BIOMETHANE", "CROPS_TO_ETHANOL",
"ETHANE_TO_ETHYLENE", "ETHANOL_TO_JETFUELS", "GASIFICATION_H2", "OTHER_BIOMASS", "EOR", "DOGR",
"UNMINEABLE_COAL_SEAM", "DEEP_SALINE", "MINES_STORAGE", "DIRECT_USAGE", "CEMENT"],
"Low Temperature Heat": ["DHN_HP_ELEC", "DHN_COGEN_GAS", "DHN_COGEN_WOOD", "DHN_COGEN_WASTE", "DHN_BOILER_GAS",
"DHN_BOILER_WOOD", "DHN_BOILER_OIL", "DHN_RENOVATION", "DEC_HP_ELEC", "DEC_THHP_GAS",
"DEC_COGEN_GAS",
"DEC_COGEN_OIL", "DEC_COGEN_WOOD", "DEC_ADVCOGEN_H2", "DEC_BOILER_GAS",
"DEC_BOILER_WOOD", "DEC_BOILER_OIL",
"DEC_SOLAR", "DEC_DIRECT_ELEC", "DEC_RENOVATION", "DHN", "LT_DEC_WH", "LT_DHN_WH",
"HT_LT", "HT_LT_DEC", ],
"High Temperature Heat": ["IND_COGEN_GAS", "IND_COGEN_WOOD", "IND_COGEN_WASTE", "IND_BOILER_GAS",
"IND_BOILER_WOOD", "IND_BOILER_OIL", "IND_BOILER_COAL", "IND_BOILER_WASTE",
"IND_HP_ELEC",
"IND_DIRECT_ELEC"],
"Storage": ["DIE_STO", "STO_DIE", "GASO_STO", "STO_GASO", "ELEC_STO", "STO_ELEC", "H2_STO", "STO_H2", "CO2_STO",
"STO_CO2", "NG_STO", "STO_NG", "DHN_TH_STORAGE", "DEC_TH_STORAGE", "BATTERY", ""],
"Electrolysis": ["ALKALINE_ELECTROLYSIS", "PEM_ELECTROLYSIS", "SOEC_ELECTROLYSIS"],
"Carbon Capture": ["CARBON_CAPTURE", "DAC_HT", "DAC_LT"]}
# Extract all technologies from Result for dynamic assignment
all_technologies = Result.sets['TECHNOLOGIES']['TECHNOLOGIES'].tolist()
# Ensure keywords and technology names are checked in a case-insensitive manner
mobility_keywords = ["BUS_", "CAR_", "COACH_", "PLANE_", "SEMI_", "SUV_", "TRAIN_", "TRUCK_"]
# Iterate through all technologies and check if any match the keywords
for tech in all_technologies:
if any(keyword in tech.upper() for keyword in mobility_keywords):
sector_technologies.setdefault("Mobility", []).append(tech)
# Extract and add all resources to the "Resources" category
all_resources = Result.sets['RESOURCES']['RESOURCES'].tolist()
sector_technologies['Resources'] = all_resources
# For core model, get periods for each [hour, td]
if 'T_H_TD' in Result.sets:
thtd = Result.sets['T_H_TD'].rename(columns={'index0':'Period', 'index1':'Hour', 'index2':'Typical_day'})
thtd = thtd.groupby(['Hour', 'Typical_day']).count()
if df_annual or df_flow:
# Process annual data as in the original function
df_ = [Result.variables['C_inv'].set_index('Run', append=True),
Result.variables['C_maint'].set_index('Run', append=True),
Result.parameters['tau'].set_index('Run', append=True),
Result.variables['C_op'].set_index('Run', append=True), ]
# Handle core version: didn't have 'Annual_prod' and 'F_Mult' -> use 'F'
if 'Annual_Prod' in Result.variables:
df_.append(Result.variables['Annual_Prod'].set_index('Run', append=True))
if 'F_Mult' in Result.variables:
df_.append(Result.variables['F_Mult'].set_index('Run', append=True))
elif 'F' in Result.variables:
df_.append(Result.variables['F'].set_index('Run', append=True).rename(columns={'F':'F_Mult'}))
# Aggregate into one df
df_ = pd.concat(df_, axis=1).loc[:, ~pd.concat(df_, axis=1).columns.duplicated()]
df_.rename(columns={'C_in': 'C_inv'}, inplace=True)
df_['C_inv_an'] = df_['C_inv'] * df_['tau']
# Replace NaN with 0
df_ = df_.fillna(0)
# Calculate "Annual_Use" directly for `df_annual`
if 'F_Mult_t' in Result.variables:
F_Mult_t = Result.variables['F_Mult_t'].reset_index().rename(columns={"index0": "Technologies", "index1": "Periods"})
t_op = Result.parameters['t_op'].reset_index().rename(columns={'index': 'Periods'})
# Merge to calculate monthly usage
monthly_usage = pd.merge(F_Mult_t, t_op, on=["Periods", 'Run'])
monthly_usage['Monthly_Use'] = monthly_usage['F_Mult_t'] * monthly_usage['t_op']
# Sum over all months to get the annual use
annual_usage = monthly_usage.groupby(['Technologies', 'Run'])['Monthly_Use'].sum().reset_index()
annual_usage.set_index(['Technologies', 'Run'], inplace=True)
# Add column to df_
df_['Annual_Use'] = annual_usage['Monthly_Use']
# Handle core model
elif 'F_t' in Result.variables:
# Rename on a copy: keep Result.variables untouched so postprocessing can be called again
F_t = Result.variables['F_t'].rename_axis(index={'index0':'Technology', 'index1':'Hour', 'index2':'Typical_day'})
# Determine production by hour, td
period_usage = F_t.reset_index(level='Technology').merge(thtd, left_index=True, right_index=True)
period_usage['period_production'] = period_usage.F_t * period_usage.Period
annual_usage = period_usage.groupby(['Technology', 'Run'])[['period_production']].sum()
# Add values in df
df_['Annual_Use'] = annual_usage['period_production']
df_['Annual_Use'] = df_['Annual_Use'].fillna(0)
# Add categories before adding the "Annual_Use" column
df_['Category'] = df_.index.to_series().apply(
lambda x: next((k for k, v in Result.sets['TECHNOLOGIES_OF_END_USES_TYPE'].items() if x[0] in v), pd.NA))
# Create `Category_2` with correct mapping
df_["Category_2"] = df_.index.get_level_values(0).map(
{tech: sector for sector, techs in sector_technologies.items() for tech in techs})
# Add sectors based on categories
df_['Sector'] = pd.Series(dtype='str')
df_.loc[df_['Category'].str.contains('MOB_', na=False), 'Sector'] = 'Mobility'
df_.loc[df_['Category'].str.contains('ELECTRICITY_', na=False), 'Sector'] = 'Electricity'
df_.loc[df_['Category'].str.contains('HEAT_HIGH', na=False), 'Sector'] = 'Industrial Heat'
df_.loc[df_['Category'].str.contains('HEAT_LOW', na=False), 'Sector'] = 'Domestic Heat'
Industry_list = ['METHANOL', 'ALUMINUM', 'PHENOL', 'ACETIC_ACID', 'ACETONE', 'PE', 'PET', 'PVC', 'PP', 'PS',
'CEMENT', 'FOOD', 'PAPER', 'STEEL']
df_.loc[df_['Category'].isin(Industry_list), 'Sector'] = 'Industry'
df_.loc[df_['Category'].isna(), 'Sector'] = 'Others'
# Fill missing categories with "Others"
df_['Category'] = df_['Category'].fillna('Others')
df_['Category_2'] = df_['Category_2'].fillna('Others')
Result.postprocessing['df_annual'] = df_
if df_flow:
# Retrieve dfs
df_annual = Result.postprocessing['df_annual']
df_annual = df_annual[df_annual.Annual_Use != 0] # Filter to minimise computation
lyrio = Result.parameters['layers_in_out'].reset_index().rename(columns={"index0": "Technologies", "index1": "Flow"})
lyrio = lyrio[lyrio.layers_in_out != 0] # Filter to minimise computation
# Merge and determine flows of each types
df_ = df_annual.merge(lyrio, left_index=True, right_on=['Technologies', 'Run'])
df_['value'] = df_.Annual_Use * df_.layers_in_out
# Swap target and source for positive values and take absolute value
df_.rename(columns={'Technologies': 'target', 'Flow': 'source'}, inplace=True)
df_.loc[df_['value'] > 0, ['target', 'source']] = df_.loc[df_['value'] > 0, ['source', 'target']].to_numpy()
df_['value'] = abs(df_['value'])
# Aggregate and clean data
df_ = df_.groupby(['Run', 'target', 'source'])[['value']].sum().reset_index()
# Rename imported and resources flows (infra model only: core and pyomo have no BIOMASS set)
if 'BIOMASS' in Result.sets and 'BIOMASS' in Result.sets['BIOMASS'].columns:
res_flow_mask = df_['target'].isin(Result.sets['BIOMASS'].BIOMASS)
df_.loc[res_flow_mask, 'source'] = 'RES_' + df_.loc[res_flow_mask, 'source'].astype(str)
imp_flow_mask = df_['target'] == df_['source']
df_.loc[imp_flow_mask, 'source'] = 'IMP_' + df_.loc[imp_flow_mask, 'source'].astype(str)
# Drop CO2 flows except specified ones
co2_exceptions = ['CO2_TO_DIESEL', 'CO2_TO_JETFUELS', 'CO2_METHANOL']
df_ = df_[(~df_['source'].str.contains("CO2_")) | (df_['source'].isin(co2_exceptions))]
df_ = df_[(~df_['target'].str.contains("CO2_")) | (df_['target'].isin(co2_exceptions))]
# Rename ship technos
for ship_type in ['OIL_TANKER_', 'CONTAINER_', 'BULK_CARRIER_']:
df_['source'] = df_['source'].str.replace(ship_type, 'SHIP_' + ship_type, regex=False)
df_['target'] = df_['target'].str.replace(ship_type, 'SHIP_' + ship_type, regex=False)
# Aggregate data (also sorts by source within each run, required by generate_sankey_flows)
df_ = df_.groupby(['Run', 'source', 'target']).sum().reset_index()
Result.postprocessing['df_flow'] = df_
if df_monthly and 'F_Mult_t' not in Result.variables:
warnings.warn("df_monthly skipped: the model has no monthly resolution (no 'F_Mult_t' variable).")
df_monthly = False
if df_monthly:
# Existing monthly processing (unchanged)
F_Mult_t = Result.variables['F_Mult_t'].reset_index().rename(
columns={"index0": "Technologies", "index1": "Periods"})
lyrio = Result.parameters['layers_in_out'].reset_index().rename(
columns={"index0": "Technologies", "index1": "Flow"})
lyrio = lyrio.loc[lyrio['layers_in_out'] != 0, :] # Drop useless rows, lighten the postprocessing
t_op = Result.parameters['t_op'].reset_index().rename(columns={'index': 'Periods'})
F_Mult_t = F_Mult_t[F_Mult_t['F_Mult_t'] != 0]
df_ = pd.merge(F_Mult_t, t_op, on=["Periods", 'Run'])
df_ = pd.merge(df_, lyrio, on=["Technologies", 'Run'])
df_['Monthly_flow'] = df_['F_Mult_t'] * df_['t_op'] * df_['layers_in_out']
df_ = df_.loc[df_['layers_in_out'] != 0, :] # Drop rows without production info
df_['Category'] = df_['Technologies'].apply(
lambda x: next((k for k, v in Result.sets['TECHNOLOGIES_OF_END_USES_TYPE'].items() if x in v), pd.NA))
df_["Category_2"] = df_['Technologies'].map(
{tech: sector for sector, techs in sector_technologies.items() for tech in techs})
df_['Sector'] = pd.Series(dtype='object')
df_.loc[df_['Flow'].str.contains('MOB_', na=False), 'Sector'] = 'Mobility'
df_.loc[df_['Flow'].str.contains('ELECTRICITY_', na=False), 'Sector'] = 'Electricity'
df_.loc[df_['Flow'].str.contains('HEAT_HIGH', na=False), 'Sector'] = 'Industrial Heat'
df_.loc[df_['Flow'].str.contains('HEAT_LOW', na=False), 'Sector'] = 'Domestic Heat'
df_['Category'] = df_['Category'].fillna('Others')
df_['Category_2'] = df_['Category_2'].fillna('Others')
df_['Sector'] = df_['Sector'].fillna('Others')
Result.postprocessing['df_monthly'] = df_
return Result
|