forked from ainetus/Grid2Op_MORL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyze_morl_wandb_runs.py
More file actions
2689 lines (2257 loc) · 93.8 KB
/
Copy pathanalyze_morl_wandb_runs.py
File metadata and controls
2689 lines (2257 loc) · 93.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
Comprehensive analysis of gated tiered MORL runs from a W&B CSV export.
Key ideas:
- Use *base* MORL metrics (not blocks / scalar reward) + ave_alive as true
objectives.
- Treat blocks (primary / fairness / sustain / structural) as *derived*
metrics, not independent objectives.
- Ignore ave_r for multi-objective evaluation (reward depends on weights).
- Min-max normalize metrics to [0, 1] and build a high-dimensional Pareto
front in that normalized space.
- Add gating-aware "effective weight" features (alpha_* * w_*).
- For each normalized metric, fit Linear, Ridge, and Lasso regression on all
weights + effective weights.
- Compute PCA + UMAP on normalized base metric space and plot, labeling
Pareto-front runs with run_idx.
- Save readable summaries for Pareto runs and regression-based weight
suggestions.
- Print all key tables to stdout and save them as red–yellow–green table
heatmap images.
- NEW: Given 1–4 target metrics and a notion of "max is good" vs "min is good",
propose two weight sets:
- Candidate A: best observed run for those targets.
- Candidate B: regression-guided synthetic configuration.
Available via --mode analysis (with optional --targets) or --mode suggest.
Usage:
python analyze_morl_wandb_runs.py path/to/wandb_export.csv \
--mode analysis
--targets ave_alive,morl/n1_proxy_mean_1000
python analyze_morl_wandb_runs.py path/to/wandb_export.csv \
--mode suggest \
--targets ave_alive,morl/n1_proxy_mean_1000
"""
import sys
from pathlib import Path
import argparse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.patches import Ellipse
from matplotlib.patches import Circle
from sklearn.neighbors import KernelDensity
# sklearn (regression + PCA)
try:
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.metrics import r2_score
from sklearn.decomposition import PCA
SKLEARN_AVAILABLE = True
except ImportError:
SKLEARN_AVAILABLE = False
# UMAP (optional)
try:
import umap
UMAP_AVAILABLE = True
except ImportError:
UMAP_AVAILABLE = False
# ---------------- CONFIG ----------------
# Default CSV if none provided on CLI
DEFAULT_CSV = "logs/wandb/wandb_export_2025-12-12T13_57_49.286+01_00.csv"
# Define which direction is "good" for each base metric (max or min)
# If a metric is missing from this dict, "max" is assumed.
METRIC_DIRECTION = {
# Survival / longevity
"ave_alive": "max",
"morl/survival_mean_1000": "max",
"morl/longevity_mean_1000": "max",
# Fairness / equity
"morl/fair_rho_mean_1000": "min",
"morl/fair_curtail_mean_1000": "min",
"morl/equity_curtail_mean_1000": "min",
# Structural
"morl/n1_proxy_mean_1000": "min",
"morl/l2rpn_reward_mean_1000": "max",
# Sustainability
"morl/renewable_ratio_mean_1000": "max",
"morl/co2_mean_1000": "min",
# Cost / risk / simplicity (lower is better)
"morl/econ_cost_mean_1000": "min",
"morl/risk_mean_1000": "min",
"morl/simplicity_mean_1000": "min",
}
# ---------------- CANONICAL ORDERING ----------------
# We keep plots and tables readable by grouping metrics/weights by MORL block.
# The order below is the canonical order used everywhere (base metrics, derived metrics, weights, etc.).
#
# Blocks in morl_objectives.py:
# - Primary: survival
# - Fairness: fair_rho, fair_curtail, equity_curtail
# - Sustainability: renewable_ratio, co2
# - Structural: risk, n1_proxy, econ_cost, simplicity, l2rpn_reward
# Base (true) metrics (stripped of optional "_norm")
BASE_METRIC_ORDER = [
# Primary-ish / survival signals
"ave_alive",
"morl/survival_mean_1000",
"morl/longevity_mean_1000",
# Fairness block
"morl/fair_rho_mean_1000",
"morl/fair_curtail_mean_1000",
"morl/equity_curtail_mean_1000",
# Sustainability block
"morl/renewable_ratio_mean_1000",
"morl/co2_mean_1000",
# Structural block
"morl/risk_mean_1000",
"morl/n1_proxy_mean_1000",
"morl/econ_cost_mean_1000",
"morl/simplicity_mean_1000",
"morl/l2rpn_reward_mean_1000",
]
# Derived metrics (blocks + scalar reward) (stripped of optional "_norm")
DERIVED_METRIC_ORDER = [
"morl/primary_block_mean_1000",
"morl/fairness_block_mean_1000",
"morl/sustain_block_mean_1000",
"morl/structural_block_mean_1000",
"morl/scalar_reward_mean_1000",
]
# Weights / hyper-parameters (stripped of optional "_norm")
WEIGHT_ORDER = [
# Gate threshold + block scalers (most "conceptual" parameters)
"morl/tau_primary",
"morl/alpha_fair",
"morl/alpha_sust",
"morl/alpha_struct",
# Fairness weights
"morl/w_fair_rho",
"morl/w_fair_curt",
"morl/w_equity",
# Sustainability weights
"morl/w_ren",
"morl/w_co2",
# Structural weights
"morl/w_risk",
"morl/w_n1",
"morl/w_econ",
"morl/w_simplicity",
"morl/w_l2rpn",
]
# Effective weights (alpha_* * w_*) produced by add_effective_weights()
EFF_WEIGHT_ORDER = [
"eff_fair_rho",
"eff_fair_curt",
"eff_equity",
"eff_ren",
"eff_co2",
"eff_risk",
"eff_n1",
"eff_econ",
"eff_simplicity",
"eff_l2rpn",
]
# Non-morl/ helper columns we often plot alongside weights
AUX_FEATURE_ORDER = [
"alpha_total",
"gate_active",
"gate_margin",
]
def _strip_norm_suffix(col: str) -> str:
# Helper used for ordering: drop plotting/analysis suffixes.
if col.endswith("_util"):
col = col[:-5]
if col.endswith("_norm"):
col = col[:-5]
return col
def order_columns(cols, canonical_order):
"""
Order `cols` so that:
1) columns appearing in `canonical_order` come first (in that order),
2) for each base name, the non-_norm version comes before _norm,
3) interaction features like *_x_gate are placed right after their base,
4) unknown columns are appended (stable alphabetical).
"""
cols = list(dict.fromkeys(cols)) # de-dup, keep first occurrence
base_index = {name: i for i, name in enumerate(canonical_order)}
def key(c):
base = _strip_norm_suffix(c)
# Place "*_x_gate" right after its base
is_gate_interaction = base.endswith("_x_gate")
base_for_order = base[:-7] if is_gate_interaction else base
idx = base_index.get(base_for_order, 10**9)
# within the same base: raw then norm then interaction
is_norm = c.endswith("_norm")
within = 0
if is_norm:
within = 1
if is_gate_interaction:
within = 2
return (idx, within, base, c)
known = [c for c in cols if base_index.get(_strip_norm_suffix(c).replace("_x_gate",""), None) is not None]
unknown = [c for c in cols if c not in known]
# Sort all with key; unknown will drift to the end because idx=1e9
return sorted(cols, key=key)
# Make pandas print full tables
pd.set_option("display.max_rows", None)
pd.set_option("display.max_columns", None)
pd.set_option("display.width", 0)
pd.set_option("display.max_colwidth", None)
# Custom red-yellow-green colormap for table images / heatmaps
TABLE_CMAP = LinearSegmentedColormap.from_list(
"ryg", ["red", "yellow", "green"]
)
# Mapping from effective weights to their parent raw weights
EFFECTIVE_PARENT = {
"eff_fair_rho": "morl/w_fair_rho",
"eff_fair_curt": "morl/w_fair_curt",
"eff_equity": "morl/w_equity",
"eff_ren": "morl/w_ren",
"eff_co2": "morl/w_co2",
"eff_risk": "morl/w_risk",
"eff_n1": "morl/w_n1",
"eff_econ": "morl/w_econ",
"eff_simplicity": "morl/w_simplicity",
"eff_l2rpn": "morl/w_l2rpn",
}
# NEW: mapping from effective weights back to their gating alpha
EFFECTIVE_ALPHA = {
"eff_fair_rho": "morl/alpha_fair",
"eff_fair_curt": "morl/alpha_fair",
"eff_equity": "morl/alpha_fair",
"eff_ren": "morl/alpha_sust",
"eff_co2": "morl/alpha_sust",
"eff_risk": "morl/alpha_struct",
"eff_n1": "morl/alpha_struct",
"eff_econ": "morl/alpha_struct",
"eff_simplicity": "morl/alpha_struct",
"eff_l2rpn": "morl/alpha_struct",
}
# ---------------- PLOT FUNCTIONS ----------------
def save_metrics_corr_heatmap_table_redesigned(
corr_df,
out_path,
*,
title="Metric–metric correlations",
metric_direction=None,
order=None,
block_breaks=None,
cmap="RdYlGn",
vmin=-1.0,
vmax=1.0,
annotate=True,
annot_fmt="{:.3f}",
dpi=200,
):
"""
Redesigned metric–metric correlation heatmap:
- reorder rows/cols by `order` (base names, no suffixes needed)
- robustly matches corr_df labels that may include *_util / *_norm suffixes
- draws thick lines at `block_breaks`
- colors tick labels by metric_direction (max/min/derived)
"""
if metric_direction is None:
metric_direction = {}
def _base_name(s: str) -> str:
# match your _strip_norm_suffix semantics: remove _util then _norm
if s.endswith("_util"):
s = s[:-5]
if s.endswith("_norm"):
s = s[:-5]
return s
# --- default order (your requested NEW order) ---
if order is None:
order = [
"ave_alive",
"morl/scalar_reward_mean_1000",
"morl/primary_block_mean_1000",
"morl/survival_mean_1000",
"morl/longevity_mean_1000",
"morl/fairness_block_mean_1000",
"morl/fair_rho_mean_1000",
"morl/fair_curtail_mean_1000",
"morl/equity_curtail_mean_1000",
"morl/sustain_block_mean_1000",
"morl/renewable_ratio_mean_1000",
"morl/co2_mean_1000",
"morl/structural_block_mean_1000",
"morl/risk_mean_1000",
"morl/n1_proxy_mean_1000",
"morl/econ_cost_mean_1000",
"morl/simplicity_mean_1000",
"morl/l2rpn_reward_mean_1000",
]
# [2] global, [3] primary, [4] fairness, [3] sustain, [6] structural
if block_breaks is None:
block_breaks = [2, 5, 9, 12]
# --- Build mapping base_name -> actual label in corr_df ---
# corr_df is square (rows=cols), but we build from columns anyway
col_map = {}
for c in list(corr_df.columns):
b = _base_name(str(c))
# keep first occurrence
if b not in col_map:
col_map[b] = c
# Resolve desired order into actual labels present in corr_df
present_base = [b for b in order if b in col_map]
missing_base = [b for b in order if b not in col_map]
if len(present_base) < 2:
# don’t crash the whole analysis: emit useful debug and return
print("[WARN] metrics_corr_heatmap: not enough metrics found to plot after resolving names.")
print(f" corr_df columns (sample): {list(corr_df.columns)[:10]}")
print(f" missing from order: {missing_base}")
return
present_labels = [col_map[b] for b in present_base]
# Reindex both rows and cols using actual labels
corr = corr_df.loc[present_labels, present_labels].copy()
# Plot
n = len(present_labels)
fig_w = max(7, 0.55 * n + 2)
fig_h = max(6, 0.55 * n + 2)
fig, ax = plt.subplots(figsize=(fig_w, fig_h))
im = ax.imshow(corr.values.astype(float), cmap=cmap, vmin=vmin, vmax=vmax, aspect="auto")
# ticks show base names (clean, consistent)
ax.set_xticks(np.arange(n))
ax.set_yticks(np.arange(n))
ax.set_xticklabels(present_base, rotation=90)
ax.set_yticklabels(present_base)
# label colors by objective direction
def label_color(base_metric: str) -> str:
direction = metric_direction.get(base_metric, None)
if direction == "max":
return "#1b9e77"
if direction == "min":
return "#d95f02"
return "#444444"
for lab in ax.get_xticklabels():
lab.set_color(label_color(lab.get_text()))
for lab in ax.get_yticklabels():
lab.set_color(label_color(lab.get_text()))
# annotate
if annotate:
data = corr.values.astype(float)
for i in range(n):
for j in range(n):
val = data[i, j]
if np.isnan(val):
continue
ax.text(j, i, annot_fmt.format(val), ha="center", va="center", fontsize=7, color="black")
# separators (still based on your intended block indices)
for b in block_breaks:
if 0 < b < n:
ax.axhline(b - 0.5, color="black", linewidth=2.5)
ax.axvline(b - 0.5, color="black", linewidth=2.5)
ax.set_title(title)
cbar = fig.colorbar(im, ax=ax, shrink=0.8)
cbar.set_label("Pearson r")
fig.tight_layout()
fig.savefig(out_path, dpi=dpi)
plt.close(fig)
if missing_base:
print(f"[WARN] metrics_corr_heatmap: {len(missing_base)} ordered metrics missing and were skipped: {missing_base}")
def save_weights_vs_metrics_corr_heatmap_table_redesigned(
corr_wm_df,
out_path,
*,
title="Weight–metric correlations",
metric_direction=None,
rows_order=None,
cols_order=None,
row_block_breaks=None,
col_block_breaks=None,
cmap="RdYlGn",
vmin=-1.0,
vmax=1.0,
annotate=True,
annot_fmt="{:.3f}",
dpi=200,
):
"""
Redesigned weights-vs-metrics correlation heatmap:
- corr_wm_df rows: weights/effective weights
- corr_wm_df cols: metrics (may be *_util)
- robustly matches cols_order base names to actual corr_wm_df columns
- draws thick separators for row/col blocks
- colors metric x-axis labels by objective direction
"""
if metric_direction is None:
metric_direction = {}
def _base_name(s: str) -> str:
if s.endswith("_util"):
s = s[:-5]
if s.endswith("_norm"):
s = s[:-5]
return s
# --- defaults from your requested NEW order ---
if rows_order is None:
rows_order = [
"morl/tau_primary",
"morl/alpha_fair",
"morl/w_fair_rho",
"morl/w_fair_curt",
"morl/w_equity",
"eff_fair_rho",
"eff_fair_curt",
"eff_equity",
"morl/alpha_sust",
"morl/w_ren",
"morl/w_co2",
"eff_ren",
"eff_co2",
"morl/alpha_struct",
"morl/w_risk",
"morl/w_n1",
"morl/w_econ",
"morl/w_simplicity",
"morl/w_l2rpn",
"eff_risk",
"eff_n1",
"eff_econ",
"eff_simplicity",
"eff_l2rpn",
]
if cols_order is None:
cols_order = [
"ave_alive",
"morl/scalar_reward_mean_1000",
"morl/primary_block_mean_1000",
"morl/survival_mean_1000",
"morl/longevity_mean_1000",
"morl/fairness_block_mean_1000",
"morl/fair_rho_mean_1000",
"morl/fair_curtail_mean_1000",
"morl/equity_curtail_mean_1000",
"morl/sustain_block_mean_1000",
"morl/renewable_ratio_mean_1000",
"morl/co2_mean_1000",
"morl/structural_block_mean_1000",
"morl/risk_mean_1000",
"morl/n1_proxy_mean_1000",
"morl/econ_cost_mean_1000",
"morl/simplicity_mean_1000",
"morl/l2rpn_reward_mean_1000",
]
# Rows: [1] tau, [7] fairness, [5] sust, [11] structural
if row_block_breaks is None:
row_block_breaks = [1, 8, 13]
# Cols: [2] global, [3] primary, [4] fairness, [3] sustain, [6] structural
if col_block_breaks is None:
col_block_breaks = [2, 5, 9, 12]
# --- rows (weights) must match exactly (they are not *_util) ---
present_rows = [r for r in rows_order if r in corr_wm_df.index]
missing_rows = [r for r in rows_order if r not in corr_wm_df.index]
# --- cols (metrics) may be *_util, so resolve by base name ---
col_map = {}
for c in list(corr_wm_df.columns):
b = _base_name(str(c))
if b not in col_map:
col_map[b] = c
present_cols_base = [b for b in cols_order if b in col_map]
missing_cols_base = [b for b in cols_order if b not in col_map]
present_cols = [col_map[b] for b in present_cols_base]
if len(present_rows) < 2 or len(present_cols) < 2:
print("[WARN] weights_vs_metrics_heatmap: not enough rows/cols found to plot after resolving names.")
print(f" present_rows={len(present_rows)} present_cols={len(present_cols)}")
return
corr = corr_wm_df.loc[present_rows, present_cols].copy()
# plot
n_rows = len(present_rows)
n_cols = len(present_cols)
fig_w = max(8, 0.45 * n_cols + 4)
fig_h = max(7, 0.35 * n_rows + 4)
fig, ax = plt.subplots(figsize=(fig_w, fig_h))
im = ax.imshow(corr.values.astype(float), cmap=cmap, vmin=vmin, vmax=vmax, aspect="auto")
ax.set_xticks(np.arange(n_cols))
ax.set_yticks(np.arange(n_rows))
# show base metric names on x-axis
ax.set_xticklabels(present_cols_base, rotation=90)
ax.set_yticklabels([_base_name(r) for r in present_rows])
# x-label colors by direction
def metric_label_color(base_metric: str) -> str:
direction = metric_direction.get(base_metric, None)
if direction == "max":
return "#1b9e77"
if direction == "min":
return "#d95f02"
return "#444444"
for lab in ax.get_xticklabels():
lab.set_color(metric_label_color(lab.get_text()))
for lab in ax.get_yticklabels():
lab.set_color("#111111")
# annotate
if annotate:
data = corr.values.astype(float)
for i in range(n_rows):
for j in range(n_cols):
val = data[i, j]
if np.isnan(val):
continue
ax.text(j, i, annot_fmt.format(val), ha="center", va="center", fontsize=7, color="black")
# separators (clip to plotted size)
for b in row_block_breaks:
if 0 < b < n_rows:
ax.axhline(b - 0.5, color="black", linewidth=2.5)
for b in col_block_breaks:
if 0 < b < n_cols:
ax.axvline(b - 0.5, color="black", linewidth=2.5)
ax.set_title(title)
cbar = fig.colorbar(im, ax=ax, shrink=0.85)
cbar.set_label("Pearson r")
fig.tight_layout()
fig.savefig(out_path, dpi=dpi)
plt.close(fig)
if missing_rows:
print(f"[WARN] weights_vs_metrics_heatmap: {len(missing_rows)} ordered rows missing and were skipped: {missing_rows}")
if missing_cols_base:
print(f"[WARN] weights_vs_metrics_heatmap: {len(missing_cols_base)} ordered metrics missing and were skipped: {missing_cols_base}")
# ---------------- HELPER FUNCTIONS ----------------
def ensure_output_dir(dirname="analysis_outputs"):
out_dir = Path(dirname)
out_dir.mkdir(parents=True, exist_ok=True)
return out_dir
def save_df_and_print(df: pd.DataFrame, path: Path, name: str | None = None):
"""Save a DataFrame to CSV and print the full table to stdout."""
df.to_csv(path, index=False)
label = name or path.name
print(f"\n=== {label} (saved to {path}) ===")
print(df)
print("\n")
def save_df(df: pd.DataFrame, path: Path, name: str | None = None):
"""Save a DataFrame to CSV and print the full table to stdout."""
df.to_csv(path, index=False)
label = name or path.name
print(f"\n=== {label} (saved to {path}) ===")
def save_table_heatmap(df: pd.DataFrame, path: Path, title: str):
"""
Create an image of a 'table' with colored cells.
Only numeric columns are visualized; index and column names are used
as labels. Colors go from min (red) over mid (yellow) to max (green).
"""
numeric_df = df.select_dtypes(include=[np.number])
if numeric_df.empty:
print(f"No numeric data in table for heatmap: {title}")
return
data = numeric_df.values.astype(float)
vmin = np.nanmin(data)
vmax = np.nanmax(data)
# Auto figure size based on table size
n_rows, n_cols = numeric_df.shape
fig_w = max(6, 0.5 * n_cols + 2)
fig_h = max(4, 0.4 * n_rows + 2)
fig, ax = plt.subplots(figsize=(fig_w, fig_h))
im = ax.imshow(data, cmap=TABLE_CMAP, vmin=vmin, vmax=vmax, aspect="auto")
ax.set_xticks(np.arange(n_cols))
ax.set_xticklabels([_strip_norm_suffix(str(c)) for c in numeric_df.columns], rotation=90)
ax.set_yticks(np.arange(n_rows))
ax.set_yticklabels([_strip_norm_suffix(str(i)) for i in numeric_df.index])
# Annotate cells with values
for i in range(n_rows):
for j in range(n_cols):
val = data[i, j]
if np.isnan(val):
text = ""
else:
text = f"{val:.3f}"
ax.text(j, i, text, ha="center", va="center", fontsize=6, color="black")
ax.set_title(title)
fig.colorbar(im, ax=ax, shrink=0.8)
fig.tight_layout()
fig.savefig(path, dpi=150)
plt.close(fig)
print(f"Saved table heatmap: {path}")
def load_and_filter(csv_path: Path) -> pd.DataFrame:
"""Load CSV and filter to runs that have MORL weights logged."""
df = pd.read_csv(csv_path)
# Weight columns are morl/w_* and alpha/tau (non-metric, non-transformed)
weight_cols = [
c for c in df.columns
if c.startswith("morl/")
and "transformed" not in c
and not c.endswith("_mean_1000")
]
if not weight_cols:
raise RuntimeError("No MORL weight columns (morl/*) found in CSV!")
mask_morl = ~df[weight_cols].isna().all(axis=1)
df_morl = df[mask_morl].copy().reset_index(drop=True)
# Add a simple integer ID for each run (for plotting labels)
df_morl["run_idx"] = np.arange(1, len(df_morl) + 1)
print(f"Loaded {len(df)} runs, kept {len(df_morl)} MORL runs.")
return df_morl
def select_metric_and_weight_cols(df: pd.DataFrame):
"""
Identify:
- base metrics (true objectives): all morl/*_mean_1000 except blocks &
scalar_reward & transformed_* plus ave_alive
- derived metrics: block_* and scalar_reward_* (still morl/*_mean_1000)
- weights: all morl/* that are not metrics & not transformed
"""
base_metric_cols = []
derived_metric_cols = []
for c in df.columns:
if not c.startswith("morl/"):
continue
if "transformed" in c:
continue
if not c.endswith("_mean_1000"):
continue
# Block metrics and scalar reward are "derived"
if "block" in c or "scalar_reward" in c:
derived_metric_cols.append(c)
else:
base_metric_cols.append(c)
# Add ave_alive as a base metric if present
if "ave_alive" in df.columns:
base_metric_cols.insert(0, "ave_alive")
# Weight columns (alphas, taus, w_*, etc. – non-transformed, non-metric)
weight_cols = [
c for c in df.columns
if c.startswith("morl/")
and "transformed" not in c
and not c.endswith("_mean_1000")
]
# Apply canonical ordering for readability / interpretability
base_metric_cols = order_columns(base_metric_cols, BASE_METRIC_ORDER)
derived_metric_cols = order_columns(derived_metric_cols, DERIVED_METRIC_ORDER)
weight_cols = order_columns(weight_cols, WEIGHT_ORDER)
print(f"Identified {len(base_metric_cols)} base metrics, "
f"{len(derived_metric_cols)} derived metrics, "
f"{len(weight_cols)} weights.")
return base_metric_cols, derived_metric_cols, weight_cols
def add_effective_weights(df: pd.DataFrame, weight_cols):
"""
Add gating-aware "effective" weights: alpha_* * w_* combinations.
Returns: df, eff_weight_cols (list of new column names)
"""
eff_weight_cols = []
def maybe_create_eff(name, alpha_col, w_col):
nonlocal df, eff_weight_cols
if alpha_col in df.columns and w_col in df.columns:
eff_name = f"eff_{name}"
df[eff_name] = df[alpha_col].astype(float) * df[w_col].astype(float)
eff_weight_cols.append(eff_name)
maybe_create_eff("fair_rho", "morl/alpha_fair", "morl/w_fair_rho")
maybe_create_eff("fair_curt", "morl/alpha_fair", "morl/w_fair_curt")
maybe_create_eff("equity", "morl/alpha_fair", "morl/w_equity")
maybe_create_eff("ren", "morl/alpha_sust", "morl/w_ren")
maybe_create_eff("co2", "morl/alpha_sust", "morl/w_co2")
maybe_create_eff("risk", "morl/alpha_struct", "morl/w_risk")
maybe_create_eff("n1", "morl/alpha_struct", "morl/w_n1")
maybe_create_eff("econ", "morl/alpha_struct", "morl/w_econ")
maybe_create_eff("simplicity", "morl/alpha_struct", "morl/w_simplicity")
maybe_create_eff("l2rpn", "morl/alpha_struct", "morl/w_l2rpn")
if eff_weight_cols:
print(f"Created {len(eff_weight_cols)} effective weight columns.")
else:
print("No effective weight columns created (check alpha_*/w_* names).")
return df, eff_weight_cols
def minmax_normalize(df: pd.DataFrame, metric_cols, out_dir: Path):
"""Add *_norm columns: min-max normalized metrics to [0, 1]."""
norm_cols = []
stats_rows = []
for col in metric_cols:
values = df[col].astype(float)
vmin = values.min()
vmax = values.max()
if np.isclose(vmax, vmin):
# constant metric: set to 0.5
norm = np.full_like(values, 0.5, dtype=float)
else:
norm = (values - vmin) / (vmax - vmin)
norm_name = f"{col}_norm"
df[norm_name] = norm
norm_cols.append(norm_name)
stats_rows.append({"metric": col, "norm_col": norm_name,
"min": vmin, "max": vmax})
stats_df = pd.DataFrame(stats_rows)
stats_path = out_dir / "metric_minmax_stats.csv"
save_df(stats_df, stats_path, name="metric_minmax_stats")
# Also create a simple min/max heatmap (metric x [min,max])
stats_heat_df = stats_df.set_index("metric")[["min", "max"]]
save_table_heatmap(
stats_heat_df,
out_dir / "metric_minmax_stats_heatmap.png",
"Metric min/max stats"
)
return df, norm_cols
def add_utility_aligned_columns(df: pd.DataFrame, cols, *, mode: str):
"""Create utility-aligned columns where 'higher = better' for all metrics.
Parameters
----------
df : pd.DataFrame
Input dataframe (not modified in-place).
cols : list[str]
Columns to transform. These can be raw metrics or *_norm columns.
mode : {"raw", "norm"}
- "raw": for direction=="min" -> multiply by -1
- "norm": for direction=="min" -> (1 - x)
Returns
-------
df_out : pd.DataFrame
Copy of df with additional *_util columns added.
util_cols : list[str]
Names of created utility-aligned columns in the same order as `cols`.
"""
if mode not in ("raw", "norm"):
raise ValueError(f"mode must be 'raw' or 'norm', got {mode!r}")
df_out = df.copy()
util_cols = []
for col in cols:
base = _strip_norm_suffix(col) # remove _norm if present
direction = METRIC_DIRECTION.get(base, "max")
out_col = f"{col}_util"
x = df_out[col].astype(float)
if direction == "min":
df_out[out_col] = (-x) if mode == "raw" else (1.0 - x)
else:
df_out[out_col] = x
util_cols.append(out_col)
return df_out, util_cols
def compute_pareto_ranks(df: pd.DataFrame, objective_cols_norm):
"""
Compute Pareto ranks for the given normalized objectives (all maximized).
Rank 1: non-dominated (Pareto front)
Rank 2: front after removing rank-1 runs, etc.
"""
data = df[objective_cols_norm].values.astype(float)
n = data.shape[0]
ranks = np.zeros(n, dtype=int)
current_rank = 1
remaining = np.arange(n)
while remaining.size > 0:
is_dominated = np.zeros(remaining.size, dtype=bool)
for i_idx, i in enumerate(remaining):
for j_idx, j in enumerate(remaining):
if i == j:
continue
# all >= and at least one >
if np.all(data[j] >= data[i]) and np.any(data[j] > data[i]):
is_dominated[i_idx] = True
break
front = remaining[~is_dominated]
ranks[front] = current_rank
remaining = remaining[is_dominated]
current_rank += 1
df["pareto_rank"] = ranks
df["is_pareto_front"] = df["pareto_rank"] == 1
# Distance to ideal (1,1,...,1) in normalized space
ideal = np.ones(data.shape[1], dtype=float)
dists = np.sqrt(((data - ideal) ** 2).sum(axis=1))
df["ideal_distance"] = dists
# Composite score: lower rank + closer to ideal
max_rank = df["pareto_rank"].max()
df["multiobj_score"] = (
(max_rank + 1 - df["pareto_rank"]) / (max_rank + 1)
+ (data.shape[1] - dists) / data.shape[1]
)
return df
def _label_front_points_2d(ax, df, x_col, y_col):
front = df[df["is_pareto_front"]]
for _, row in front.iterrows():
ax.text(row[x_col], row[y_col], str(int(row["run_idx"])),
fontsize=7, ha="center", va="bottom")
def plot_pareto_2d(df, x_col, y_col, out_path):
fig, ax = plt.subplots(figsize=(7, 6))
colors = np.where(df["is_pareto_front"], "red", "gray")
ax.scatter(df[x_col], df[y_col], c=colors, alpha=0.7, edgecolors="none")
ax.set_xlabel(x_col)
ax.set_ylabel(y_col)
ax.set_title(f"Pareto Front in 2D: {x_col} vs {y_col}")
# Highlight front
front = df[df["is_pareto_front"]]
if not front.empty:
ax.scatter(front[x_col], front[y_col], color="red",
s=90, edgecolors="black")
_label_front_points_2d(ax, df, x_col, y_col)
fig.tight_layout()
fig.savefig(out_path, dpi=150)
plt.close(fig)
print(f"Saved 2D Pareto plot: {out_path}")
def plot_pareto_3d(df, x_col, y_col, z_col, out_path):
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
fig = plt.figure(figsize=(8, 7))
ax = fig.add_subplot(111, projection="3d")
colors = np.where(df["is_pareto_front"], "red", "gray")
ax.scatter(df[x_col], df[y_col], df[z_col], c=colors, alpha=0.8)
ax.set_xlabel(x_col)
ax.set_ylabel(y_col)
ax.set_zlabel(z_col)
ax.set_title("3D Pareto Surface")
# Label Pareto-front points
front = df[df["is_pareto_front"]]
for _, row in front.iterrows():
ax.text(row[x_col], row[y_col], row[z_col],
str(int(row["run_idx"])), fontsize=7)
fig.tight_layout()
fig.savefig(out_path, dpi=150)
plt.close(fig)
print(f"Saved 3D Pareto plot: {out_path}")
def corr_heatmap(df, cols, out_path, title):
"""Simple correlation heatmap between selected columns (Pearson)."""
corr = df[cols].corr(method="pearson")
fig, ax = plt.subplots(figsize=(0.5 * len(cols) + 2,
0.5 * len(cols) + 2))
im = ax.imshow(corr.values, cmap=TABLE_CMAP, vmin=-1, vmax=1)
ax.set_xticks(range(len(cols)))
labels = [_strip_norm_suffix(c) for c in cols]
ax.set_xticklabels(labels, rotation=90)
ax.set_yticks(range(len(cols)))
ax.set_yticklabels(labels)
ax.set_title(title)
fig.colorbar(im, ax=ax, shrink=0.8)
fig.tight_layout()
fig.savefig(out_path, dpi=150)
plt.close(fig)
print(f"Saved correlation heatmap: {out_path}")
return corr
def run_regressions(df, feature_cols, target_norm_cols, out_dir: Path,
prefix=""):
"""
For each normalized target metric, fit Linear, Ridge, and Lasso regression
vs all features (weights + effective weights). Save coefficient
and summary tables (CSV + printed) and R²/coef heatmaps.
"""
if not SKLEARN_AVAILABLE:
print("sklearn not available, skipping regression models.")
return None, None
X = df[feature_cols].values.astype(float)
summary_rows = []
coef_rows = []
for metric in target_norm_cols:
y = df[metric].values.astype(float)
if np.allclose(y, y[0]):