-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMORDM_analyze_robustness.py
1850 lines (1517 loc) · 81.1 KB
/
MORDM_analyze_robustness.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
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 12 14:18:42 2023
Script for performing uncertainty and robustness analysis.
@author: aengholm
"""
# Imports
import matplotlib.patches as mpatches
from matplotlib.ticker import MaxNLocator
import math
import pickle
import statistics
import pandas as pd
import numpy as np
import re
from statsmodels.stats.multicomp import pairwise_tukeyhsd
import scipy.stats as stats
import matplotlib.patches as patches
from ema_workbench.analysis import feature_scoring
from ema_workbench.analysis import prim
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
from ema_workbench.analysis import parcoords
import matplotlib.pyplot as plt
import seaborn as sns
# Set plotting style and scale up font size
sns.set_context("paper", font_scale=1.5)
# %% Load data and store in dataframes for subsequent analysis
policy_types = ["All levers", "No transport efficiency"]
# policy_types=["All levers"]
# "No transport efficiency"]
load_results = 1
if load_results == 1:
from ema_workbench import load_results
date = "2024-05-19"
n_scenarios = 2100
# for policy_type in policy_types:
t1 = f"./output_data/robustness_analysis_results/X_XP{n_scenarios}_scenarios_MORDM_OE_{date}.p"
data = pickle.load(open(t1, "rb"))
if len(data) > 1:
data_x = data[0][0] # Load output data for run for parameter set X
data_xp = data[0][1] # Load output data for run for parameter set XP
experiments_x = data_x[1]
outcomes_x = data_x[0]
experiments_xp = data_xp[1]
outcomes_xp = data_xp[0]
df_outcomes = pd.concat([pd.DataFrame(outcomes_x), pd.DataFrame(outcomes_xp)],
axis=0, join="inner").reset_index(drop=True)
experiments = pd.concat([experiments_x, experiments_xp], axis=0, join="outer").reset_index(drop=True)
else:
data_xp = data[0][0] # Load output data for run for parameter set XP
experiments_xp = data_xp[1]
outcomes_xp = data_xp[0]
df_outcomes = pd.DataFrame(outcomes_xp).reset_index(drop=True)
experiments = experiments_xp
# experiments, outcomes = pickle.load(open(t1, "rb"))
t2 = f"./output_data/robustness_analysis_results/{n_scenarios}_scenarios_MORDM_OE_{date}model_.p"
model = pickle.load(open(t2, "rb"))
# DF with both experiments and outcomes
df_full = pd.concat([experiments, df_outcomes], axis=1, join="inner")
df_outcomes['policy'] = experiments["policy"]
for index, row in df_full.iterrows():
if math.isnan(row["R1_fuel_price_to_car_electrification"]):
df_full.loc[index, "Uncertainty set"] = "X"
else:
df_full.loc[index, "Uncertainty set"] = "XP"
df_full["CO2 target not met"] = df_full['M1_CO2_TTW_total'] > 1.89
df_full["Bio share of fuel energy"] = df_full["M4_energy_use_bio"] / \
(df_full["Energy total"]-df_full["M5_energy_use_electricity"])
# Create helper lists of outcomes, levers and uncertainties
# Dictionary mapping keys to labels with units
key_outcomes_labels = {
'M1_CO2_TTW_total': 'M1_CO2_TTW_total [ton]', # Replace 'metric unit' with the actual unit for M1
'M2_driving_cost_car': 'M2_driving_cost_car [SEK]',
'M3_driving_cost_truck': 'M3_driving_cost_truck [SEK]',
'M4_energy_use_bio': 'M4_energy_use_bio [TWh]',
'M5_energy_use_electricity': 'M5_energy_use_electricity [TWh]'
}
# Dictionary for objective outcomes labels with units
objective_outcomes_labels = {
'M2_driving_cost_car': 'M2_driving_cost_car [SEK]',
'M3_driving_cost_truck': 'M3_driving_cost_truck [SEK]',
'M4_energy_use_bio': 'M4_energy_use_bio [TWh]',
'M5_energy_use_electricity': 'M5_energy_use_electricity [TWh]'
}
# Different outcome sets
all_outcomes = model.outcomes.keys()
key_outcomes = [
'M1_CO2_TTW_total',
'M2_driving_cost_car',
'M3_driving_cost_truck',
'M4_energy_use_bio',
'M5_energy_use_electricity']
objective_outcomes = [
'M2_driving_cost_car',
'M3_driving_cost_truck',
'M4_energy_use_bio',
'M5_energy_use_electricity']
# Levers
levers = model.levers.keys()
# Uncertainties
uncertainties = model.uncertainties.keys()
# Define color coding mapping
color_coding = {
"All levers": '#0005CC',
"No transport efficiency": '#05CC00',
"STA": '#CC0005'}
light_color_coding = {
"All levers": '#6064CC',
"No transport efficiency": '#7ECC60',
"STA": '#C77F5D'
}
ultra_light_color_coding = {
"All levers": '#EDEDFF',
"No transport efficiency": '#EDFFED',
"STA": '#FFEDED'
}
STA_colors = {
'B': '#ff0000', # Red for policy B
'C1': '#007bff', # A shade of blue for C1
'C2': '#0056b3', # A darker shade of blue for C2
'C3': '#003d80', # Even darker shade of blue for C3
'C4': '#002366', # Darkest blue for C4
'D1': '#28a745', # Green for D1
'D2': '#1e7e34', # A darker shade of green for D2
'D3': '#155724' # Darkest green for D3
}
# Speciy latex math strings for each robustness metric
rm_dict = {
"90_percentile_deviation": r"$\mathrm{RM_{90\%\,dev}}$",
"Mean_stdev": r"$\mathrm{RM_{MeanStdev}}$",
"Satisficing metric M1_CO2_TTW_total": "RMco$_{2}$sat",
}
color_sta_policies = ["green", "lightcoral", "red", "darkred", "coral", "cornflowerblue", "blue", "darkblue"]
df_full_all = df_full.copy()
df_full = df_full[df_full["policy"] != "Reference policy"]
df_full_sta = df_full[df_full["Policy type"] == "STA"]
df_sta_levers = df_full_sta[list(levers)+["policy"]].drop_duplicates()
df_reference_subset = df_full[(df_full["scenario"] == "Reference") & (df_full["Uncertainty set"] == "XP")]
# %% More plots on reference scenario performance
# Pairplot outcomes on outcomes
df_reference_subset = df_reference_subset.copy()
df_reference_subset['Policy type'] = df_reference_subset['Policy type'].astype('category')
df_reference_subset['Policy type'] = df_reference_subset['Policy type'].cat.reorder_categories(
['STA', 'All levers', 'No transport efficiency'], ordered=True
)
# Now create the pairplot.
g = sns.pairplot(
data=df_reference_subset,
x_vars=objective_outcomes,
y_vars=objective_outcomes,
hue="Policy type",
palette=color_coding,
diag_kind="hist",
diag_kws={"common_norm": False}
)
# Move the legend to the right of the figure.
# You can adjust the values inside bbox_to_anchor to best fit your figure's size.
g._legend.remove()
g.add_legend(title='', bbox_to_anchor=(1, .5), loc='center right', fontsize=16, ncols=1)
for ax in g.axes.flatten():
# Set new font sizes here
ax.set_xlabel(ax.get_xlabel(), fontsize=14) # Adjust fontsize as needed for x labels
ax.set_ylabel(ax.get_ylabel(), fontsize=14)
ax.tick_params(axis='x', labelsize=12) # Adjust labelsize as needed for x ticks
ax.tick_params(axis='y', labelsize=12) # Adjust labelsize as needed for y ticks
# Adjust the figure to make space for the legend
# plt.subplots_adjust(right=0.9) # You might need to tweak this value.
# %% Pairplots
# Levers on levers
plt.figure(figsize=(16, 16))
sns.pairplot(data=df_reference_subset, x_vars=levers, y_vars=levers,
hue="Policy type", palette=color_coding, diag_kws={"common_norm": False})
# Levers on outcomes
plt.figure(figsize=(16, 8))
sns.pairplot(data=df_reference_subset, x_vars=levers, y_vars=key_outcomes,
hue="Policy type", palette=color_coding, diag_kws={"common_norm": False})
# %% Outcomes on outcomes
plt.figure(figsize=(8, 6))
# Assuming 'df_reference_subset' is pre-filtered for a specific uncertainty set,
# if not, you would need to filter it as in the previous loop
all_policy_types = df_reference_subset["Policy type"].unique()
# Create the pairplot
plot = sns.pairplot(data=df_reference_subset, x_vars=objective_outcomes, y_vars=objective_outcomes,
hue="Policy type", palette=color_coding, diag_kws={"common_norm": False})
# Annotate Pearson correlation coefficient for each policy type
for i, policy_type in enumerate(all_policy_types):
policy_type_df = df_reference_subset[df_reference_subset['Policy type'] == policy_type]
spearman_correlation = policy_type_df[objective_outcomes].corr(method='spearman')
# Offset for the vertical position based on the policy type index
vertical_offset = 0.95 - i * 0.12 # Adjust offset as needed
# Loop through axes to annotate. Exclude diagonal.
for j in range(len(objective_outcomes)):
for k in range(len(objective_outcomes)):
if j != k: # Exclude diagonal
ax = plot.axes[j, k]
rho = spearman_correlation.iloc[j, k]
n = policy_type_df.shape[0]
# Calculate test statistic
if n > 2:
t_stat = rho * ((n - 2) ** 0.5) / ((1 - rho**2) ** 0.5)
# Calculate one-sided p-value for negative alternative hypothesis
p_value = stats.t.cdf(t_stat, df=n-2) # Use CDF to get the probability of t <= t_stat
signif = '*' if p_value < 0.01 else ''
else:
signif = ''
# Annotate in the upper right corner with offset for each policy type
text = f'ρ = {rho:.2f}{signif}'
ax.text(0.95, vertical_offset, text,
horizontalalignment='right', verticalalignment='center',
transform=ax.transAxes, color=color_coding[policy_type], fontsize=12)
# Adjust the title, labels, legend, and layout as needed
# Get handles and labels for the legend
handles, labels = plot.axes[0][0].get_legend_handles_labels()
# Create new legend on the right side
plt.legend(handles=handles, labels=labels, bbox_to_anchor=(2, 0.5), loc='center left', borderaxespad=0.)
plt.tight_layout()
# %%Relationship between biofuels and electrification rate in reference scenario
plt.figure(figsize=(8, 5))
sns.scatterplot(data=df_full[df_full["scenario"] == "Reference"], x='Electrified VKT share light vehicles',
y='M4_energy_use_bio', hue="Policy type", palette=color_coding, legend=False, s=25)
# Annotating STA policies
bbox_props = dict(boxstyle="round,pad=0.1", fc="white", ec="none", lw=0, alpha=0.5)
for sta_policy in df_full[df_full["Policy type"] == "STA"]["policy"].unique():
df_sta_policy = df_full[df_full['policy'] == sta_policy]
plt.annotate(
sta_policy,
(df_sta_policy["Electrified VKT share light vehicles"].values[0],
df_sta_policy["M4_energy_use_bio"].values[0]),
textcoords="offset points",
xytext=(0, -15),
ha='center', color=color_coding["STA"], fontsize=12, bbox=bbox_props
)
plt.axvline(x=0.68, linestyle="--", color="black", linewidth=1, zorder=10)
plt.text(s="X6_car_electrification_rate: 0.68", x=0.68+.001, y=4, color="black")
plt.xlim([0.66, .85])
sns.despine()
# %% Distribution of electrification outcomes
vars_pairplot = ["Electrified VKT share light vehicles", "Bio share of fuel energy"]
g = sns.pairplot(data=df_full, x_vars=vars_pairplot,
y_vars=vars_pairplot, hue="CO2 target not met",
palette=["green", "red"], plot_kws=dict(s=.01, alpha=1))
# %% Distribution of electrification and bio outcomes
g = sns.pairplot(data=df_full, x_vars=vars_pairplot, kind="kde",
y_vars=vars_pairplot, hue="CO2 target not met",
palette=["green", "red"], plot_kws=dict(fill=True, alpha=0.5, levels=10, gridsize=100))
# %% Calculate robustness metrics
# Define robustness metrics
all_robustness_metrics = ["90th percentile", "Reference", "90_percentile_deviation",
"Max", "Mean", "Standard deviation", "Mean_stdev", "Max_regret"]
robustness_metrics = ["90_percentile_deviation", "Mean_stdev"]
# Initial setup - Calculating Zero regret values
results = []
grouped = df_full.groupby(['Uncertainty set', 'scenario'])
for (uncertainty_set, scenario), group in grouped:
for outcome in key_outcomes:
zero_regret_value = group[outcome].min()
results.append({
"Outcome": outcome,
"Uncertainty set": uncertainty_set,
"scenario": scenario,
"Zero regret": zero_regret_value
})
zero_regret_df = pd.DataFrame(results)
# Calculate other metrics for each policy
all_policies = df_full["policy"].unique()
all_uncertainty_sets = df_full["Uncertainty set"].unique()
metrics_data = []
long_metrics_data = [] # For creating the long format DataFrame
for policy in all_policies:
if policy != "Reference policy":
for uncertainty_set in all_uncertainty_sets:
df_temp = df_full[(df_full["policy"] == policy) & (df_full["Uncertainty set"] == uncertainty_set)]
policy_data = {
"policy": policy,
"Policy type": df_temp["Policy type"].iloc[0],
"Uncertainty set": uncertainty_set
}
co2_outcome_data = df_temp["M1_CO2_TTW_total"]
satisficing_metric = (co2_outcome_data < 1.89).sum() / len(co2_outcome_data)
# Add satisficing metric to policy_data
policy_data["Satisficing metric M1_CO2_TTW_total"] = satisficing_metric
for outcome in key_outcomes:
outcome_data = df_temp[outcome]
ref_outcome_data = df_temp[df_temp["scenario"] == "Reference"][outcome]
metrics = {
f"{metric} {outcome}": (
outcome_data.quantile(0.9),
ref_outcome_data.values[0],
(outcome_data.quantile(0.9) - ref_outcome_data.values[0]) / abs(ref_outcome_data.values[0]),
outcome_data.max(),
outcome_data.mean(),
outcome_data.std(),
(outcome_data.mean()) * (outcome_data.std()),
None # Placeholder for Max_regret which will be calculated later
)[all_robustness_metrics.index(metric)] for metric in all_robustness_metrics
}
policy_data.update(metrics)
regrets = abs(outcome_data - zero_regret_df.loc[
(zero_regret_df["Uncertainty set"] == uncertainty_set) &
(zero_regret_df["Outcome"] == outcome) &
zero_regret_df["scenario"].isin(df_temp["scenario"].unique()),
"Zero regret"
].values)
policy_data[f"Max_regret {outcome}"] = regrets.max()
metrics[f"Max_regret {outcome}"] = regrets.max() # Update the metrics dictionary
# Append data to long_metrics_data
for metric in all_robustness_metrics:
long_metrics_data.append({
"policy": policy,
"Policy type": df_temp["Policy type"].iloc[0],
"Uncertainty set": uncertainty_set,
"Outcome": outcome,
"Robustness metric": metric,
"Value": metrics[f"{metric} {outcome}"]
})
metrics_data.append(policy_data)
policy_metrics_df = pd.DataFrame(metrics_data)
policy_metrics_df_long = pd.DataFrame(long_metrics_data)
policy_metrics_sta = policy_metrics_df[policy_metrics_df["Policy type"] == "STA"]
policy_metrics_sta_long = policy_metrics_df_long[policy_metrics_df_long["Policy type"] == "STA"]
# %% FIGURE18 19 visualize relationship between robustness metrics
# Use Whitegrid
sns.set_style("whitegrid")
all_uncertainty_sets = policy_metrics_df["Uncertainty set"].unique()
all_policy_types = policy_metrics_df["Policy type"].unique()
# Loop over each outcome and uncertainty set combination
rm_pairplot = ["90_percentile_deviation", "Mean_stdev"]
for rm in rm_pairplot:
pairplot_metrics = []
for outcome in key_outcomes:
pairplot_metrics.append(f"{rm} {outcome}")
for uncertainty_set in all_uncertainty_sets:
# Filter the data
subset_df = policy_metrics_df[policy_metrics_df["Uncertainty set"] == uncertainty_set]
# Create the pairplot
plot = sns.pairplot(data=subset_df, vars=pairplot_metrics, diag_kind="kde", hue="Policy type",
height=2.5, palette=color_coding, diag_kws={"common_norm": False})
plot.fig.suptitle(f"Robustness metric: {rm}", y=1, fontsize=20)
# Annotate Spearman correlation coefficient and its significance for each policy type
for i, policy_type in enumerate(all_policy_types):
# Offset the vertical position of each annotation by the index of the policy type
vertical_offset = 0.95 - i * 0.12 # Adjust offset as needed
policy_type_df = subset_df[subset_df['Policy type'] == policy_type]
spearman_correlation = policy_type_df[pairplot_metrics].corr(method='spearman')
# Loop through axes to annotate. Exclude diagonal.
for j in range(len(pairplot_metrics)):
for k in range(len(pairplot_metrics)):
if j != k: # Exclude diagonal
ax = plot.axes[j, k]
rho = spearman_correlation.iloc[j, k]
n = policy_type_df.shape[0]
# Calculate test statistic
if n > 2:
t_stat = rho * ((n - 2) ** 0.5) / ((1 - rho**2) ** 0.5)
# Calculate one-sided p-value for negative alternative hypothesis
p_value = stats.t.cdf(t_stat, df=n-2) # Use CDF to get the probability of t <= t_stat
signif = '*' if p_value < 0.01 else ''
else:
signif = ''
text = f'ρ = {rho:.2f}{signif}'
ax.text(0.95, vertical_offset, text,
horizontalalignment='right', verticalalignment='center',
transform=ax.transAxes, color=color_coding[policy_type], fontsize=12)
# Adjust labels for better readability
for ax in plot.axes.flat:
ax.set_xlabel(ax.get_xlabel().replace(" ", "\n"), rotation=0)
ax.set_ylabel(ax.get_ylabel().replace(" ", "\n"), rotation=90)
plot._legend.set_bbox_to_anchor((1.15, 0.5))
plt.tight_layout()
# %% Visualize satisficing CO2
g = sns.displot(policy_metrics_df, x="Satisficing metric M1_CO2_TTW_total",
hue="Policy type", kind="kde", common_norm=False, bw_adjust=0.5, cut=0,
palette=color_coding, fill=False)
g._legend.set_bbox_to_anchor((0.7, 0.9, 0, 0))
# Remove the legend title
g._legend.set_title('')
g = sns.FacetGrid(policy_metrics_df, col="Policy type", col_wrap=3, height=4,
sharex=True, sharey=False, hue="Policy type", palette=color_coding)
# Plot histograms
g = g.map(sns.histplot, "Satisficing metric M1_CO2_TTW_total",
stat="count", element="step", bins=10).set(xlim=(None, 1))
for ax in g.axes.flatten():
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
# Adjust x lables
g.set_axis_labels(x_var="RMco$_{2}$sat", y_var="").set_titles("Policy type: {col_name}")
g.fig.tight_layout()
plt.show()
# %% Visualize satisficing CO2 as function of car electrification rate
g = sns.displot(df_full, x="X6_car_electrification_rate",
hue="CO2 target not met", kind="kde", common_norm=False, bw_adjust=0.5, cut=0,
fill=False)
g._legend.set_bbox_to_anchor((0.7, 0.9, 0, 0))
# Remove the legend title
g._legend.set_title('')
# %%
df_long_el = df_full.melt(id_vars=["Policy type", "CO2 target not met"],
value_vars=["X6_car_electrification_rate", "Electrified VKT share light vehicles"],
var_name="Variable", value_name="value")
# Calculate the x_value for vertical lines
x_value = df_reference_subset["X6_car_electrification_rate"].unique()[0]
# Use displot with faceting
custom_palette = ['green', 'red']
g = sns.displot(
data=df_long_el,
x="value",
row="Variable",
col="Policy type",
hue="CO2 target not met",
kind="kde",
height=3,
aspect=1.5,
common_norm=True,
palette=custom_palette,
cut=0,
fill=True,
facet_kws={'sharex': False, 'sharey': False}
)
g.set_titles("{col_name}")
g.map_dataframe(lambda data, color: plt.axvline(x=x_value, color='black', linestyle='--'))
# Iterate over each row and set the x-axis labels and limits
xlims = [0, 1] # Get the x-limits from the first subplot
for i, variable in enumerate(df_long_el["Variable"].unique()):
for j, ax in enumerate(g.axes[i, :]): # Iterate over each column in the row
ax.set_xlabel(variable)
ax.set_xlim(xlims) # Set the same x-limits for each subplot to align them as if sharex=True
plt.subplots_adjust(hspace=0.5)
# Show plot with adjusted x-axis labels
plt.show()
# %%
for pt in df_full["Policy type"].unique():
plt.figure()
num_bins_x = 5 # Number of bins for 'X6_car_electrification_rate'
num_bins_y = 5 # Number of bins for 'L2_bio_share_gasoline'
# Create binned categories for the two columns
df_full['X6_binned'] = pd.cut(df_full['X6_car_electrification_rate'], bins=num_bins_x)
df_full['L2_binned'] = pd.cut(df_full['L2_bio_share_gasoline'], bins=num_bins_y)
# Use pivot_table to aggregate duplicate entries
pivoted_data = df_full[df_full["Policy type"] == pt].pivot_table(
index='X6_binned', columns='L2_binned', values='CO2 target not met', aggfunc='mean')
# Create the heatmap
plt.figure(figsize=(10, 8)) # You can adjust the figure size as needed
sns.heatmap(pivoted_data, annot=True, fmt=".2f", cmap="viridis")
plt.tight_layout()
#sns.scatterplot(df_full[df_full["Policy type"]==pt], x="X6_car_electrification_rate",y="L2_bio_share_gasoline", hue="CO2 target not met",s=2)
# %% FIGURE 5 Visualize distributions of different policy metrics
# Create the FacetGrid with specified aspect ratio
g = sns.FacetGrid(policy_metrics_df_long[policy_metrics_df_long["Robustness metric"].isin(robustness_metrics)],
row='Robustness metric', col='Outcome', sharey=False, aspect=0.5)
# Map the boxplot to the grid
g.map_dataframe(sns.boxplot, x="Policy type", y="Value", hue="Policy type",
palette=color_coding, width=0.8, dodge=False)
# Set the y-axis label for each row
# Adjust with actual row titles from 'rm_dict'
row_titles = [rm_dict["90_percentile_deviation"], rm_dict["Mean_stdev"]]
for ax, row_title in zip(g.axes[:, 0], row_titles):
ax.set_ylabel(row_title)
# Set the x-axis labels for each column
# Ensure that 'objective_outcomes' contains the column titles you want to display
for ax, col_title in zip(g.axes[0, :], objective_outcomes):
ax.set_title(col_title)
# Remove the default Seaborn FacetGrid titles and any redundant x-ticks
for ax in g.axes.flat:
ax.set_xticks([])
ax.set_xlabel('')
ax.set_title('')
# Set the FacetGrid titles again, without the row titles
g.set_titles(col_template="{col_name}", row_template="")
for ax in g.axes.flat:
title = ax.get_title()
if "|" in title:
new_title = title.replace(" | ", " ") # Replace the separator with a space
ax.set_title(new_title)
# Adjust the legend
g.add_legend(title=None, bbox_to_anchor=(0.5, 1.05), loc='center', borderaxespad=0., ncol=3, fontsize=12)
# Improve the layout
plt.tight_layout()
# Despine to clean up the look of the plot
g.despine()
# %% FIGURE 6
# Create the boxplot
plt.figure(figsize=(6, 6)) # You can adjust the figure size as needed
g = sns.boxplot(data=policy_metrics_df, x="Policy type", y="Satisficing metric M1_CO2_TTW_total", palette=color_coding)
# Remove the x-axis label and tick labels
g.set_xlabel('')
g.set_xticklabels([])
# Add a custom y-axis label
g.set_ylabel(rm_dict["Satisficing metric M1_CO2_TTW_total"], fontsize=20)
# Get the unique policy types and create a patch handle for each
policy_types = policy_metrics_df['Policy type'].unique()
legend_handles = [mpatches.Patch(color=color_coding[pt], label=pt) for pt in policy_types]
# Create the legend with rectangular handles
plt.legend(handles=legend_handles, title=None, bbox_to_anchor=(0.5, 1.05),
loc='center', borderaxespad=0., ncol=3, fontsize=16, frameon=False)
plt.ylim([0, 1])
# Despine to clean up the look of the plot
sns.despine()
# Use tight_layout to adjust subplot params for the figure area
plt.tight_layout()
# %% Pairplot of robustness
# Create a dictionary for renaming columns
for robustness_metric in robustness_metrics:
robustness_metric_outcomes = []
for outcome in key_outcomes:
robustness_metric_outcomes.append(f"{robustness_metric} {outcome}")
rename_dict = {long: short for long, short in zip(robustness_metric_outcomes, key_outcomes)}
sns.pairplot(policy_metrics_df, x_vars=robustness_metric_outcomes,
y_vars=robustness_metric_outcomes, hue="Policy type", palette=color_coding)
# %% Perform statistical test of robustness metrics differences ALl levers No transport efficiency
for robustness_metric in robustness_metrics:
for outcome in key_outcomes:
# Filter data for the two specific policy types
filtered_data = policy_metrics_df_long[policy_metrics_df_long['Policy type'].isin(
['All levers', 'No transport efficiency'])]
# Statistical Test - Mann-Whitney U Test
group1 = filtered_data[(filtered_data['Policy type'] == 'All levers') & (
filtered_data['Outcome'] == outcome) & (filtered_data["Robustness metric"] == f"{robustness_metric}")]
group2 = filtered_data[(filtered_data['Policy type'] == 'No transport efficiency') & (
filtered_data['Outcome'] == outcome) & (filtered_data["Robustness metric"] == f"{robustness_metric}")]
# Calculate Descriptive Statistics
group1_stats = group1.describe()
group2_stats = group2.describe()
print(
f"{robustness_metric} {outcome} - All levers: Median = {group1_stats.loc['50%'][0]}, Mean = {group1_stats.loc['mean'][0]}")
print(
f"{robustness_metric} {outcome} - No transport efficiency: Median = {group2_stats.loc['50%'][0]}, Mean = {group2_stats.loc['mean'][0]}")
# Perform the test (use alternative='two-sided' for a two-tailed test)
u_statistic, p_value = stats.mannwhitneyu(
group1['Value'].dropna(), group2['Value'].dropna(), alternative='two-sided')
print(f'Mann-Whitney U test for {robustness_metric} {outcome}: p-value = {p_value}')
# %% Parcoords of all policies and robustness metrics with empahis on STA or a subset of policies, two different graphs
# Save the original default size
original_figsize = plt.rcParams["figure.figsize"]
# Set the figure size
plt.rcParams["figure.figsize"] = [7, 6]
# Max/min/median All Levers and no transport efficiency policies highlighted
# Identify what policies to highlight and store the policy id in a list
highlighted_policy_info = {}
metric_to_use = '90_percentile_deviation M1_CO2_TTW_total'
for policy_type in ["All levers", "No transport efficiency"]:
df_pt = policy_metrics_df[policy_metrics_df["Policy type"] == policy_type]
# Max
# Find indices for max, min, and median
max_policy_idx = df_pt[metric_to_use].idxmax()
min_policy_idx = df_pt[metric_to_use].idxmin()
median_value = df_pt[metric_to_use].median()
median_policy_idx = (df_pt[metric_to_use] - median_value).abs().idxmin()
# Store the information in the dictionary
highlighted_policy_info[policy_type] = [
(int(df_pt.loc[max_policy_idx, 'policy']), "solid"),
(int(df_pt.loc[min_policy_idx, 'policy']), "dotted"),
(int(df_pt.loc[median_policy_idx, 'policy']), "dashdot")
]
linestyles = ["solid", "dotted", "dashdot", "solid", "dotted", "dashdot"]
for robustness_metric in robustness_metrics:
dynamic_outcomes = [f"{robustness_metric} {outcome}" for outcome in key_outcomes] # Dynamic outcomes
# for uncertainty_set in policy_metrics_df["Uncertainty set"].unique():
for uncertainty_set in ["XP"]:
policy_metrics_subset = policy_metrics_df[policy_metrics_df["Uncertainty set"] == uncertainty_set]
limits_outcomes = pd.DataFrame() # Create a dataframe for limits
for i, item in enumerate(dynamic_outcomes):
limits_outcomes.loc[0, item] = min(policy_metrics_subset[item]) # Get lower bound
limits_outcomes.loc[1, item] = max(policy_metrics_subset[item]) # Get upper bound
# Create a dictionary for renaming columns
rename_dict = {long: short for long, short in zip(dynamic_outcomes, key_outcomes)}
# Rename columns of limits_outcomes for display purposes
limits_outcomes.rename(columns=rename_dict, inplace=True)
limits = limits_outcomes
# Create the parallel coordinates
paraxes = parcoords.ParallelAxes(limits)
paraxes.ticklabels = key_outcomes
# Define your color coding for the legend
labels = list(color_coding.keys())
color_legend_elements = [Patch(facecolor=color_coding[label], label=label) for label in labels]
# Create linestyle legend elements. Adjust the labels as per your description.
linestyle_labels = ["Max", "Min", "Median"]
linestyle_legend_elements = [Line2D([0], [0], color='black', linewidth=2, linestyle=ls, label=label)
for ls, label in zip(linestyles[:3], linestyle_labels)]
# Combine color and linestyle legend elements
legend_elements = color_legend_elements + linestyle_legend_elements
sta_policies = df_full[(df_full["Policy type"] == "STA")]["policy"].unique().tolist()
# Loop over rows in dataframe. Plot all policies
for i, row in policy_metrics_subset.iterrows():
row_renamed = row.rename(rename_dict)
policy_type = row["Policy type"]
data = row_renamed[key_outcomes]
if policy_type != "STA":
color = light_color_coding[policy_type]
paraxes.plot(data, color=color, linewidth=0.5)
elif policy_type == "STA":
color = color_coding[policy_type]
paraxes.plot(data, color=color, linewidth=1)
for policy_type, policies in highlighted_policy_info.items():
for policy_id, linestyle in policies:
row = policy_metrics_subset[policy_metrics_subset['policy'] == str(policy_id)]
if not row.empty:
row_renamed = row.iloc[0].rename(rename_dict)
data = row_renamed[key_outcomes]
color = color_coding[policy_type]
paraxes.plot(data, color=color, linestyle=linestyle, linewidth=3)
# Add and adjustlegend manually
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 1),
loc="lower right", fontsize=12, frameon=False, ncol=2)
# for i, ax in enumerate(paraxes.axes):
# ax.set_xticklabels([key_outcomes[i]]) # This removes the x-axis tick labels
# ax.set_yticklabels([]) #
plt.suptitle(f"{rm_dict[robustness_metric]}", fontsize=20, x=0, y=1.05, horizontalalignment="left")
plt.show()
# %% FIGURE 3 Parcoords plot on levers
limits_levers = pd.DataFrame() # Create a dataframe for lever-based limits
for item in levers:
limits_levers.loc[0, item] = min(df_reference_subset[item]) # Get lower bound
limits_levers.loc[1, item] = max(df_reference_subset[item]) # Get upper bound
paraxes = parcoords.ParallelAxes(limits_levers, formatter={"maxima": ".1f", "minima": ".1f"}, fontsize=20, rot=90)
# Plot selected policies with the manually specified colors
for idx, policy_type in enumerate(df_reference_subset['Policy type'].unique()):
if policy_type != "STA":
selected_data = df_reference_subset[df_reference_subset['Policy type'] == policy_type]
paraxes.plot(selected_data, label=f'{policy_type}', color=light_color_coding[policy_type], linewidth=1)
elif policy_type == "STA":
selected_data = df_reference_subset[df_reference_subset['Policy type'] == policy_type]
paraxes.plot(selected_data, label=f'{policy_type}', color=color_coding[policy_type], linewidth=2)
# Loop over rows in dataframe. Plot all policies
for policy_type, policies in highlighted_policy_info.items():
for policy_id, linestyle in policies:
row = policy_metrics_subset[policy_metrics_subset['policy'] == str(policy_id)]
if not row.empty:
row_renamed = row.iloc[0].rename(rename_dict)
data = df_reference_subset[df_reference_subset["policy"] == str(policy_id)]
color = color_coding[policy_type]
paraxes.plot(data, color=color, linestyle=linestyle, linewidth=4)
# Get the figure that parcoords is using
parcoords_fig = plt.gcf() # 'gcf' stands for 'Get Current Figure'
# for ax in paraxes.axes:
# ax.set_xticklabels([]) # This removes the x-axis tick labels
# ax.set_yticklabels([]) #
# Set figure size and facecolor
parcoords_fig.set_size_inches(15, 60)
# parcoords_fig.patch.set_facecolor((1, 1, 1, 0)) # Set transparency
# Define your color coding for the legend
labels = list(color_coding.keys())
color_legend_elements = [Patch(facecolor=color_coding[label], label=label) for label in labels]
# Create linestyle legend elements. Adjust the labels as per your description.
linestyle_labels = ["Max", "Min", "Median"]
linestyle_legend_elements = [Line2D([0], [0], color='black', linewidth=2, linestyle=ls, label=label)
for ls, label in zip(linestyles[:3], linestyle_labels)]
# Combine color and linestyle legend elements
legend_elements = color_legend_elements + linestyle_legend_elements
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 1),
loc="lower right", fontsize=18, frameon=False, ncol=2)
# Instead of saving 'fig', now we save 'parcoords_fig' which is the actual figure containing the plot.
parcoords_fig.savefig("./figs/paper/Figure3_parcoords_candidate_policies_reference_levers.png",
dpi=300, format="png", bbox_inches="tight", transparent=True)
# %% FIGURE 4 Visualization of reference scenario performance
# Setup DataFrame limits for plotting
limits_outcomes = pd.DataFrame() # Create a dataframe for outcome-based limits
for item in objective_outcomes:
limits_outcomes.loc[0, item] = min(df_reference_subset[item]) # Get lower bound
limits_outcomes.loc[1, item] = max(df_reference_subset[item]) # Get upper bound
# Initialize the parallel coordinates plot
paraxes = parcoords.ParallelAxes(limits_outcomes, formatter={"maxima": ".1f", "minima": ".1f"}, fontsize=20, rot=90)
# Plot policies with different styles for each policy type
for policy_type in df_reference_subset['Policy type'].unique():
selected_data = df_reference_subset[df_reference_subset['Policy type'] == policy_type]
if policy_type == "STA":
# Highlight "STA" type policies with a thicker line
lines = paraxes.plot(selected_data, label=f'{policy_type}', color=color_coding[policy_type], linewidth=2)
for i, (line, policy_name) in enumerate(zip(selected_data[objective_outcomes].values, selected_data['policy'])):
# Normalize the y-position within the last axis limits
last_axis_limits = paraxes.limits[objective_outcomes[-1]]
y_value = line[-1] # This is the data value at the last axis
y_relative = (y_value - last_axis_limits[0]) / (last_axis_limits[1] - last_axis_limits[0])
x_relative = len(objective_outcomes) + 0.02 # Position beyond the last axis
# Annotate with the policy name
paraxes.fig.text(x_relative, y_relative, str(policy_name), transform=paraxes.axes[-1].transData,
fontsize=18, color=color_coding["STA"], ha='left', va='center',
bbox=dict(facecolor='white', alpha=0, edgecolor='none', boxstyle='round,pad=0.2'))
else:
paraxes.plot(selected_data, label=f'{policy_type}', color=light_color_coding[policy_type], linewidth=1)
# Highlight specific policies as done in Figure 3
for policy_type, policies in highlighted_policy_info.items():
for policy_id, linestyle in policies:
data = df_reference_subset[df_reference_subset["policy"] == str(policy_id)]
if not data.empty:
paraxes.plot(data, color=color_coding[policy_type], linestyle=linestyle, linewidth=4)
# Configure figure properties
parcoords_fig = plt.gcf() # Get the current figure
parcoords_fig.set_size_inches(16, 20) # Set figure size
# Create legends for color and linestyle
labels = list(color_coding.keys())
color_legend_elements = [Patch(facecolor=color_coding[label], label=label) for label in labels]
linestyle_labels = ["Max", "Min", "Median"]
linestyle_legend_elements = [Line2D([0], [0], color='black', linewidth=2, linestyle=ls, label=label)
for ls, label in zip(["-", "--", ":"], linestyle_labels)]
legend_elements = color_legend_elements + linestyle_legend_elements
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 1), loc="lower right", fontsize=18, frameon=False, ncol=2)
# Save the figure
parcoords_fig.savefig("./figs/paper/Figure4_parcoords_candidate_policies_reference_outcomes.png",
dpi=300, format="png", bbox_inches="tight", transparent=True)
# %% STA policies highlighted
# Save the original default size
original_figsize = plt.rcParams["figure.figsize"]
# Set the figure size
plt.rcParams["figure.figsize"] = [7, 6]
for robustness_metric in robustness_metrics:
dynamic_outcomes = [f"{robustness_metric} {outcome}" for outcome in key_outcomes] # Dynamic outcomes
# for uncertainty_set in policy_metrics_df["Uncertainty set"].unique():
for uncertainty_set in ["XP"]:
policy_metrics_subset = policy_metrics_df[policy_metrics_df["Uncertainty set"] == uncertainty_set]
limits_outcomes = pd.DataFrame() # Create a dataframe for limits
for i, item in enumerate(dynamic_outcomes):
limits_outcomes.loc[0, item] = min(policy_metrics_subset[item]) # Get lower bound
limits_outcomes.loc[1, item] = max(policy_metrics_subset[item]) # Get upper bound
# Create a dictionary for renaming columns
rename_dict = {long: short for long, short in zip(dynamic_outcomes, key_outcomes)}
# Rename columns of limits_outcomes for display purposes
limits_outcomes.rename(columns=rename_dict, inplace=True)
limits = limits_outcomes
# Create the parallel coordinates
paraxes = parcoords.ParallelAxes(limits)
paraxes.ticklabels = key_outcomes
# Define your color coding for the legend
labels = list(color_coding.keys())
color_legend_elements = [Patch(facecolor=color_coding[label], label=label) for label in labels]
# Create linestyle legend elements. Adjust the labels as per your description.
linestyle_labels = ["Max", "Min", "Median"]
linestyle_legend_elements = [Line2D([0], [0], color='black', linewidth=2, linestyle=ls, label=label)
for ls, label in zip(linestyles[:3], linestyle_labels)]
# Combine color and linestyle legend elements
legend_elements = color_legend_elements + linestyle_legend_elements
sta_policies = df_full[(df_full["Policy type"] == "STA")]["policy"].unique().tolist()
# Loop over rows in dataframe. Plot all policies
for i, row in policy_metrics_subset.iterrows():
row_renamed = row.rename(rename_dict)
policy_type = row["Policy type"]
data = row_renamed[key_outcomes]
color = ultra_light_color_coding[policy_type]
paraxes.plot(data, color=color)
# Initialize a variable to control the alternation of label placement
alternate = False
# Then plot the STA policies. This is to ensure STA policies are plotted on top
for i, row in policy_metrics_subset.iterrows():
policy_type = row["Policy type"]
if policy_type == 'STA':
row_renamed = row.rename(rename_dict)
data = row_renamed[key_outcomes]
color = color_coding[policy_type]
paraxes.plot(data, color=color)
# Get the axis limits for the last outcome
last_axis_limits = paraxes.limits.iloc[:, -1]
# Normalize the y-position within the last axis limits
y_value = data[rename_dict.get(dynamic_outcomes[-1])] # This is the data value at the last axis
y_relative = (y_value - last_axis_limits[0]) / (last_axis_limits[1] - last_axis_limits[0])
# Alternate the x-position to avoid clashing
x_offset = 0.05 if alternate else 0. # Alternate the offset value
x_relative = len(dynamic_outcomes) + x_offset
# Now we use the axes' transform to place the text correctly
last_axis_transform = paraxes.axes[-1].transData
text = policy_metrics_subset.loc[i, "policy"] # Use the policy name from the current row
fontsize = 16
paraxes.fig.text(x_relative, y_relative, text, transform=last_axis_transform,
fontsize=fontsize, color=color, ha='left' if alternate else 'right', va='center',
bbox=dict(facecolor='white', alpha=0, edgecolor='none', boxstyle='round,pad=0.2'))
# Flip the alternation flag
alternate = not alternate
# Add and adjustlegend manually
legend_elements = color_legend_elements
plt.legend(handles=legend_elements, bbox_to_anchor=(1, 1),
loc="lower right", fontsize=12, frameon=False, ncol=1)
# for i, ax in enumerate(paraxes.axes):
# ax.set_xticklabels([key_outcomes[i]]) # This removes the x-axis tick labels
# ax.set_yticklabels([]) #
plt.suptitle(f"{rm_dict[robustness_metric]}", fontsize=20, x=0, y=1.05, horizontalalignment="left")
plt.show()
plt.rcParams["figure.figsize"] = original_figsize
# %% Parcoords of all metrics with brushing
# Save the original default size
original_figsize = plt.rcParams["figure.figsize"]
plt.rcParams["figure.figsize"] = [10, 10]
outcomes = [
'M1_CO2_TTW_total',
'M2_driving_cost_car',
'M3_driving_cost_truck',
'M4_energy_use_bio',
'M5_energy_use_electricity'
]
metrics = ["90_percentile_deviation", "Max_regret", "Mean_stdev"]
# 1. Normalize the metrics for each outcome
for metric in metrics:
policy_metrics_df[f"sum_normalized_{metric}"] = 0 # initialize at 0
for outcome in outcomes:
col_name = f"{metric} {outcome}"
policy_metrics_df[f"normalized_{col_name}"] = (policy_metrics_df[col_name] - policy_metrics_df[col_name].min()) / \
(policy_metrics_df[col_name].max() - policy_metrics_df[col_name].min())
policy_metrics_df[f"sum_normalized_{metric}"] = policy_metrics_df[f"sum_normalized_{metric}"] + \
policy_metrics_df[f"normalized_{metric} {outcome}"]
# Main loop to plot each metric-uncertainty set combination
for metric in metrics:
dynamic_outcomes = [f"{metric} {outcome}" for outcome in outcomes]
# for uncertainty_set in policy_metrics_df["Uncertainty set"].unique():
for uncertainty_set in ["XP"]:
subset_uncertainty = policy_metrics_df[policy_metrics_df["Uncertainty set"] == uncertainty_set].copy()
# Normalize data for the robustness metrics
normalized_data = subset_uncertainty[dynamic_outcomes].apply(
lambda x: (x - x.min()) / (x.max() - x.min()), axis=0)
subset_uncertainty['sum_metric'] = normalized_data.sum(axis=1)
# Determine top 5 policies for this metric and uncertainty set, for each policy type, excluding "STA"
top_policies = []
for ptype in color_coding.keys():
if ptype != "STA":
ptype_policies = subset_uncertainty[subset_uncertainty["Policy type"]
== ptype].nsmallest(5, 'sum_metric').index.tolist()
top_policies.extend(ptype_policies)
else:
ptype_policies = subset_uncertainty[subset_uncertainty["Policy type"] == ptype].index.tolist()
top_policies.extend(ptype_policies)
# Plotting
color_list = [color_coding[ptype] if i in top_policies else light_color_coding[ptype]
for i, ptype in subset_uncertainty["Policy type"].items()]
alpha_list = [0.9 if i in top_policies else 0.1 for i, ptype in subset_uncertainty["Policy type"].items()]
linewidth_list = [2 if i in top_policies else 1 for i in subset_uncertainty.index]
zorder_list = [10 if i in top_policies else 1 for i in subset_uncertainty.index]
limits_outcomes = pd.DataFrame(
{col: [subset_uncertainty[col].min(), subset_uncertainty[col].max()] for col in dynamic_outcomes})
paraxes = parcoords.ParallelAxes(limits_outcomes)
labels = list(color_coding.keys())
legend_elements = [Patch(facecolor=color_coding[label], label=label) for label in labels]