-
Notifications
You must be signed in to change notification settings - Fork 1
/
analysis.py
executable file
·1991 lines (1760 loc) · 71.5 KB
/
analysis.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
import argparse
import copy
import os
import pickle
import traceback
from typing import Any, Dict, List
import jax
import jax.numpy as jnp
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy
import seaborn as sns
import yaml
from natsort import natsort_keygen
from qdax.utils.plotting import (
plot_2d_map_elites_repertoire,
plot_multidimensional_map_elites_grid,
)
from scipy.stats import ranksums
from yaml.loader import SafeLoader
####################################################
# Some global variable to easily modify the graphs #
parser = argparse.ArgumentParser()
parser.add_argument("--results", default="results", type=str)
parser.add_argument("--plots", default="plots", type=str)
parser.add_argument("--print-median", action="store_true", help="Print median.")
parser.add_argument("--convergence", action="store_true")
parser.add_argument("--final-interval-qd-score", action="store_true")
parser.add_argument("--loss-interval", action="store_true")
parser.add_argument(
"--paper-metrics",
action="store_true",
help="Plot all additional metrics from the paper.",
)
parser.add_argument("--archives", action="store_true", help="Plot paper archives.")
parser.add_argument("--archives-solo", action="store_true", help="Plot all archives.")
parser.add_argument("--p-values", action="store_true", help="Write p-values.")
args = parser.parse_args()
# Display parameters
graph_palette = "colorblind" # mako
font_size_big = 26
font_size_title = 30
font_size_small = 20
line_width = 4
# Number of columns for the legend at the bottom of the graph
graph_columns = 1
# Size of the margin to put the legend at the bottom of the graph
bottom_size = 0.20
# Environments order for plot
graph_env_order = ["arm", "hexapod_omni", "ant_uni", "anttrap"]
# Environments that are deterministics (for which reeval metrics = metrics)
env_deterministics = ["arm", "hexapod_omni"]
# Environments name correspondances
graph_env_names = {
"anttrap": "AntTrap",
"ant_uni": "Ant",
"hexapod_omni": "Hexapod",
"arm": "Arm",
}
# Environments max gen
graph_env_max_gen = {
"anttrap": 10000,
"ant_uni": 2000,
"hexapod_omni": 2000,
"arm": 2000,
}
# Environments num cells
graph_env_num_cells = {
"anttrap": 2500,
"ant_uni": 1296,
"hexapod_omni": 2500,
"arm": 2500,
}
# Environments BD correspondances for archives
graph_env_bds = {
"anttrap": [[0, -8], [30, 8]],
"ant_uni": [jnp.array([0, 0, 0, 0]), jnp.array([1, 1, 1, 1])],
"hexapod_omni": [[-2, -2], [2, 2]],
"arm": [[0, 0], [1, 1]],
}
# Environments line for BD-distance plot
graph_env_line = {
"anttrap": 0.46, # Average over 2 dimensions
"ant_uni": 0.17,
"hexapod_omni": 0.08,
"arm": 0.02,
"default": 0.02,
}
# Set up the graph names
new_names = {
"me": "ME",
"pga": "PGA-ME",
"mees": "ME-ES",
"cmame": "CMA-ME",
"ns_es": "NS-ES",
"nsr_es": "NSR-ES",
"nsra_es": "NSRA-ES",
"vanilla_es": "ES",
"naive": "ME-Sampling",
"memes": "MEMES (ours)",
"all_memes": "MEMES-all (ours)",
"ga_memes": "MEMES - GA",
"memes_adapt_nov_arch": "MEMES - Novelty-archive",
"memes_adapt_repertoire": "MEMES - Elites-archive",
"sequential_memes": "MEMES - Sequential",
"fix_reset_memes": "MEMES - Fix reset",
}
final_new_names = {
"ME-batch-128.0": "ME - 128",
"ME-batch-16384.0": "ME - 16384",
"ME-batch-65536.0": "ME - 65536",
"ME-Sampling-batch-512.0-smpl-32.0": "ME-Sampling - 32",
"ME-Sampling-batch-32.0-smpl-512.0": "ME-Sampling - 512",
"MEMES - Fix reset-num_generations_sample-50.0": "MEMES - Fix reset 50",
"MEMES - Fix reset-num_generations_sample-20.0": "MEMES - Fix reset 20",
"MEMES - Fix reset-num_generations_sample-100.0": "MEMES - Fix reset 100",
"MEMES (ours)-batch-32.0": "MEMES - 32 (ours)",
"MEMES (ours)-batch-128.0": "MEMES - 128 (ours)",
"MEMES-all (ours)-batch-16416.0": "MEMES-all - 16384 (ours)",
"MEMES-all (ours)-batch-32832.0": "MEMES-all - 32768 (ours)",
"MEMES-all (ours)-batch-65664.0": "MEMES-all - 65536 (ours)",
}
# Order for legend
order = [
"MEMES (ours)",
"MEMES - 32 (ours)",
"MEMES - 128 (ours)",
"MEMES-all (ours)",
"MEMES-all - 16384 (ours)",
"MEMES-all - 32768 (ours)",
"MEMES-all - 65536 (ours)",
"ME - 128",
"ME - 16384",
"ME - 65536",
"ME-ES",
"PGA-ME",
"CMA-ME",
"ME-Sampling",
"ME-Sampling - 32",
"ME-Sampling - 512",
"ES",
"NS-ES",
"NSR-ES",
"NSRA-ES",
"MEMES - Fix reset 100",
"MEMES - Fix reset 50",
"MEMES - Fix reset 20",
"MEMES - Fix reset 10",
"MEMES - Sequential",
"MEMES - Novelty-archive",
"MEMES - Elites-archive",
"MEMES - GA",
]
# Never considered in the name
not_name = [
"folder",
"env_name",
"plot_grid_log_period",
"store_repertoire_log_period",
"scan_batch_size",
"plot_grid",
"num_evaluations",
"alg_name",
"episode_length",
"num_steps",
"model_period",
"surrogate_model_update_period",
"grid_shape",
"scan_novelty",
"num_iterations",
"adaptive_reset",
"num_reevals",
"log_period",
"seed",
"log_period_reevals",
"fixed_init_state",
"num_generations_stagnate",
]
# Correspondances to simplify name
name_dict = {
"batch_size": "batch",
"num_samples": "smpl",
"sample_number": " es-smpl",
"learning_rate": "lr",
"sample_sigma": "sig",
"l2_coefficient": "l2",
"novelty_nearest_neighbors": "knn",
"use_novelty_archive": "novelty_arch",
"use_novelty_fifo": "novelty_fifo",
"use_explore": "expl",
"num_in_optimizer_steps": "in_opt_steps",
"num_generations_stagnate": "stag",
}
##############
# Plot utils #
def isnan(num: float) -> bool:
return num != num
def customize_axis(ax: Any) -> Any:
"""
Customise axis for plots
"""
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.tick_params(axis="y", length=0)
# ax.get_yaxis().tick_left()
# offset the spines
for spine in ax.spines.values():
spine.set_position(("outward", 5))
# put the grid behind
ax.set_axisbelow(True)
ax.grid(axis="y", color="0.9", linestyle="-", linewidth=1.5)
return ax
def sub_plot(
x: str,
y: str,
data: pd.DataFrame,
ax: Any,
xlabel: str,
ylabel: str,
scientific: bool,
) -> None:
# Plot
sns.lineplot(
x=x,
y=y,
data=data,
hue="algo",
estimator=np.median,
errorbar=("pi", 50),
style="algo",
ax=ax,
)
# Scientific units
if scientific:
if "qd_score" in y or "max_fitness" in y:
ax.ticklabel_format(axis="y", style="sci", scilimits=(0, 0))
# Cosmetics
ax.set_ylabel(ylabel)
ax.set_xlabel(xlabel)
customize_axis(ax)
def sub_interval(
y: str,
data: pd.DataFrame,
ax: Any,
algos: np.ndarray,
colors: pd.DataFrame,
xlabel: str,
ylabel: str,
scientific: bool,
) -> None:
h = 0.6
# Plot algorithms one by one
algos = np.flip(algos)
for alg_idx, algo in enumerate(algos):
# Get color
algo_color = colors[colors["Label"] == algo]["Color"].values[0]
# Get values to plot
values = np.expand_dims(data[data["algo"] == algo][y].values, axis=1)
if len(values) == 1 and values[0] == 0.0:
ax.barh(
y=alg_idx,
width=0.0,
height=h,
left=0.0,
color=algo_color,
alpha=0.0,
label=algo,
)
continue
aggregate_values = scipy.stats.trim_mean(
values.squeeze(), proportiontocut=0.25, axis=None
)
aggregate_values_cis = scipy.stats.mstats.mquantiles(
values.squeeze(), prob=[0.25, 0.75]
)
# Plot interval estimates
lower, upper = aggregate_values_cis
ax.barh(
y=alg_idx,
width=upper - lower,
height=h,
left=lower,
color=algo_color,
alpha=0.8,
label=algo,
)
# Plot point estimates
ax.vlines(
x=aggregate_values,
ymin=alg_idx - (8 * h / 16),
ymax=alg_idx + (7.98 * h / 16),
label=algo,
color="k",
alpha=1.0,
linewidth=3,
)
# Plot datapoints
# datapoints = np.ones_like(values.squeeze()) * alg_idx
# ax.scatter(y=datapoints, x=values.squeeze(), marker='o', color=algo_color, s=50, alpha=0.25)
# Scientific units
if scientific:
if "qd_score" in y or "max_fitness" in y:
ax.ticklabel_format(axis="x", style="sci", scilimits=(0, 0))
# Cosmetics
ax.set_xlabel(xlabel)
ax.set_yticks(list(range(len(algos))))
ax.xaxis.set_major_locator(plt.MaxNLocator(4))
ax.tick_params(axis="y", which="both", length=0.0)
ax.tick_params(axis="x", which="both", length=6)
if ylabel is not None:
ax.set_yticklabels(algos)
# ax.set_ylabel(ylabel)
else:
ax.set_yticklabels([])
ax.grid(True, axis="y", alpha=0.25)
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
ax.spines["left"].set_visible(False)
ax.spines["bottom"].set_linewidth(2)
ax.spines["left"].set_position(("outward", 10))
ax.spines["bottom"].set_position(("outward", 10))
def extract_algo(data: pd.DataFrame, algos: str, columns: List) -> pd.DataFrame:
sub_data = data[(data["algo"] == algos)].reset_index(drop=True)
if sub_data.empty:
return sub_data
sub_data = sub_data.sort_values(columns, key=natsort_keygen(), ignore_index=True)
return sub_data
def extract_nonalgo(data: pd.DataFrame, algos: str, columns: List) -> pd.DataFrame:
sub_data = data[~(data["algo"] == algos)].reset_index(drop=True)
if sub_data.empty:
return sub_data
sub_data = sub_data.sort_values(columns, key=natsort_keygen(), ignore_index=True)
return sub_data
def sort_data(
data: pd.DataFrame,
columns: List,
order: List,
) -> pd.DataFrame:
final_data = extract_algo(data, order[0], columns=columns)
left_data = extract_nonalgo(data, order[0], columns=columns)
added_names = order[0]
for i in range(1, len(order)):
final_data = pd.concat(
[
final_data,
extract_algo(left_data, order[i], columns=columns),
],
ignore_index=True,
)
added_names += "|" + order[i]
left_data = extract_nonalgo(data, added_names, columns=columns)
final_data = pd.concat([final_data, left_data], ignore_index=True)
return final_data
#######################
# Main plot functions #
def all_env_plot(
x: str,
xlabel: str,
data: pd.DataFrame,
color_data: pd.DataFrame,
file_name: str,
columns: List,
names: List,
hline_values: Dict = None,
split_column=None,
height=18,
width=32,
interval: bool = False,
scientific: bool = False,
) -> None:
assert len(columns) == len(
names
), "!!!ERROR!!! columns and names do not have same size."
# Get all env names
env_names = data["env_name"].drop_duplicates().values
ncols = max(2, len(env_names))
nrows = len(columns)
if split_column is not None:
if nrows > 1:
assert 0, "!!!ERROR!!! more than 1 line on multi lines not implemented yet."
ncols = ncols // split_column
nrows = nrows * split_column
# Order envs
ordered_env_names = []
for env_name in graph_env_order:
if env_name in env_names:
ordered_env_names.append(env_name)
for env_name in env_names:
if env_name not in ordered_env_names:
print(
"!!!WARNING!!!",
env_name,
"not in environment order, adding it as last.",
)
ordered_env_names.append(env_name)
env_names = ordered_env_names
# Plot parameters
params = {
"lines.linewidth": line_width,
"axes.titlesize": font_size_title,
"axes.labelsize": font_size_big,
"legend.fontsize": font_size_big,
"xtick.labelsize": font_size_small,
"ytick.labelsize": font_size_small,
"text.usetex": False,
}
mpl.rcParams.update(params)
# Create subplots
fig, axes = plt.subplots(
nrows=nrows,
ncols=ncols,
figsize=(width, height), # sharex="col"
)
# Plot one env per column
all_handles: List = []
all_labels: List = []
for col in range(ncols):
if col >= len(env_names):
continue
# Plot one metric per row
for subplot in range(nrows):
# Select axis
if nrows == 1 or ncols == 1:
ax = axes[col]
else:
ax = axes[subplot, col]
# Select idx for metric and env
if split_column is not None:
n_metric = 0
n_env = subplot + 2 * col
else:
n_metric = subplot
n_env = col
env_data = data[data["env_name"] == env_names[n_env]]
# Set palette
algos = env_data["algo"].drop_duplicates().values
env_color_data = color_data[color_data["Label"].isin(algos)]
env_palette = env_color_data["Color"].values
sns.set_palette(env_palette)
# Plot
if interval:
sub_interval(
y=columns[n_metric],
data=env_data,
ax=ax,
algos=algos,
colors=env_color_data,
xlabel=names[n_metric]
if not split_column
else (names[n_metric] if subplot == 1 else None),
ylabel=names[n_metric] if col == 0 else None,
scientific=scientific,
)
else:
sub_plot(
x=x,
y=columns[n_metric],
data=env_data,
ax=ax,
xlabel=xlabel,
ylabel=names[n_metric] if col == 0 else None,
scientific=scientific,
)
# Accumulate all the legends
if not interval:
handles, labels = ax.get_legend_handles_labels()
for i in range(len(labels)):
if labels[i] not in all_labels:
all_handles.append(handles[i])
all_labels.append(labels[i])
ax.legend_.remove()
# Add env as title to first subplot
if n_metric == 0:
title = env_names[n_env]
if title in graph_env_names.keys():
title = graph_env_names[title]
else:
print(
"!!!WARNING!!!",
title,
"is not in graph_env_names, keeping this name.",
)
ax.set_title(title)
# Add hline
if hline_values is not None:
env_line = hline_values[env_names[n_env]]
ax.axhline(env_line, c="r", linestyle="--", linewidth=3)
# Spacing between subplots
if not interval:
plt.tight_layout(h_pad=1.70)
else:
plt.tight_layout(h_pad=2.0, w_pad=3.0)
# Add legend below the plot
if not interval:
fig.subplots_adjust(bottom=bottom_size)
fig.legend(
handles=all_handles,
labels=all_labels,
loc="lower center",
frameon=False,
ncol=graph_columns if ncols > 1 else 2,
)
# Save plot
plt.savefig(file_name)
plt.close()
############
# P-values #
def p_value_ranksum(
frame: pd.DataFrame, reference_label: str, compare_label: str, stat: str
) -> Any:
"""Compute one p-value for one reference and one compare label for a given stat."""
reference_frame = frame[frame["algo"] == reference_label]
reference_max_gen = reference_frame["gen"].max()
reference_frame = reference_frame[reference_frame["gen"] == reference_max_gen]
compare_frame = frame[frame["algo"] == compare_label]
compare_max_gen = compare_frame["gen"].max()
compare_frame = compare_frame[compare_frame["gen"] == compare_max_gen]
_, p = ranksums(
reference_frame[stat].to_numpy(),
compare_frame[stat].to_numpy(),
)
return p
def compute_p_values(
frame: pd.DataFrame,
file_name: str,
stat: str,
) -> pd.DataFrame:
"""Write p-value of stat in a table."""
p_frame = pd.DataFrame(columns=["Reference label", "Label", "p-value"])
labels = frame["algo"].drop_duplicates().values
# For each labels-couple
for reference_label in labels:
for compare_label in labels:
p_frame = pd.concat(
[
p_frame,
pd.DataFrame.from_dict(
{
"Reference label": [reference_label],
"Label": [compare_label],
"p-value": [
p_value_ranksum(
frame, reference_label, compare_label, stat
)
],
}
),
],
ignore_index=True,
)
# When writting in frame, writting it as double entry table
written_p_frame = p_frame.pivot(
index="Reference label", columns="Label", values="p-value"
)
p_file = open(file_name, "a")
p_file.write(written_p_frame.to_markdown())
p_file.close()
# Still returning the frame just in case
return p_frame
################
# Find results #
# Opening all config files in the results folder
print("\n\nOpening config files")
folders = [
root
for root, dirs, files in os.walk(args.results)
for name in files
if "config.yaml" in name
]
assert len(folders) > 0, "\n!!!ERROR!!! No config files in result folder.\n"
# Go through folders to remove .hydra from path
for i in range(len(folders)):
folders[i] = folders[i][: -len(".hydra")]
# Create a dataframe with the parameters of the config files
config_frame = pd.DataFrame()
for folder in folders:
with open(os.path.join(folder, ".hydra/config.yaml")) as f:
config = yaml.load(f, Loader=SafeLoader)
for key in config.keys():
config[key] = [config[key]]
config["folder"] = [folder]
config_frame = pd.concat(
[config_frame, pd.DataFrame.from_dict(config)], ignore_index=True
)
print("\nFound", config_frame.shape[0], "results folder")
################
# Name results #
# Create results folder if needed
try:
if not os.path.exists(args.plots):
os.mkdir(args.plots)
if not os.path.exists(f"{args.plots}_csv"):
os.mkdir(f"{args.plots}_csv")
except Exception:
if not args.no_traceback:
print("\n!!!WARNING!!! Cannot create folders for plots.")
print(traceback.format_exc(-1))
print("\nSetting up algorithms names")
# First use name from new_name
algos = []
for line in range(config_frame.shape[0]):
original_name = config_frame["alg_name"][line]
if original_name in new_names.keys():
algo = new_names[original_name]
else:
algo = original_name
algos.append(algo)
config_frame["algo"] = algos
# Second get parameters that are different
use_in_name_dict = {}
for name in config_frame["algo"].drop_duplicates().values:
sub_config_frame = config_frame[config_frame["algo"] == name]
use_in_name = []
for column in sub_config_frame.columns:
if column not in not_name and not sub_config_frame[column].dropna().empty:
ref = str(sub_config_frame[column].dropna().values[0])
if any(
[str(val) != ref for val in sub_config_frame[column].dropna().values]
):
use_in_name.append(column)
use_in_name_dict[name] = use_in_name
# Third add parameters to name
algos = []
for line in range(config_frame.shape[0]):
algo = config_frame["algo"][line]
# Build name for parameters that change across baselines
use_in_name = use_in_name_dict[algo]
for name in use_in_name:
# Only if parameters is not nan
if not isnan(config_frame[name][line]):
name_simpl = name_dict[name] if name in name_dict.keys() else name
if type(config_frame[name][line]) != bool:
algo += "-" + name_simpl + "-" + str(config_frame[name][line])
elif type(config_frame[name][line]) == bool and config_frame[name][line]:
algo += "-" + name_simpl
algos.append(algo)
# Fourth check that this does not corresponds to final_new_names
for idx in range(len(algos)):
if algos[idx] in final_new_names:
algos[idx] = final_new_names[algos[idx]]
config_frame["algo"] = algos
print("\n Final names for graphs:")
print(config_frame["algo"].drop_duplicates())
########################
# Opening metric files #
print("\n Opening metric files")
metrics_frame = pd.DataFrame()
reeval_metrics_frame = pd.DataFrame()
final_metrics_frame = pd.DataFrame()
loss_metrics_frame = pd.DataFrame()
var_metrics_frame = pd.DataFrame()
for line in range(config_frame.shape[0]):
metrics_file = os.path.join(
config_frame["folder"][line], "checkpoints/last_metrics/metrics.pkl"
)
reeval_metrics_file = os.path.join(
config_frame["folder"][line], "checkpoints/last_metrics/reeval_metrics.pkl"
)
try:
# Load metrics
with open(metrics_file, "rb") as f:
metrics = pickle.load(f)
metrics = pd.DataFrame.from_dict(metrics)
# Add x axis
num_gen = jnp.arange(jnp.shape(metrics["coverage"])[0])
metrics["gen"] = num_gen
# Add necessary informations
algo = config_frame["algo"][line]
env_name = config_frame["env_name"][line]
metrics["env_name"] = env_name
metrics["algo"] = algo
metrics["line"] = line
# If xlim given remove all points after
if env_name in graph_env_max_gen.keys():
metrics = metrics[metrics["gen"] <= graph_env_max_gen[env_name]]
# Add to overall metrics frame
metrics_frame = pd.concat([metrics_frame, metrics], ignore_index=True)
if env_name in env_deterministics:
reeval_metrics = metrics
reeval_metrics["reeval_qd_score"] = metrics["qd_score"]
reeval_metrics["reeval_coverage"] = metrics["coverage"]
reeval_metrics["reeval_max_fitness"] = metrics["max_fitness"]
reeval_metrics["desc_var_qd_score"] = jnp.zeros_like(num_gen)
reeval_metrics["desc_var_coverage"] = jnp.zeros_like(num_gen)
reeval_metrics["desc_var_max_fitness"] = jnp.zeros_like(num_gen)
reeval_metrics["desc_var_min_fitness"] = jnp.zeros_like(num_gen)
reeval_metrics["reeval_desc_var_qd_score"] = jnp.zeros_like(num_gen)
reeval_metrics["reeval_desc_var_coverage"] = jnp.zeros_like(num_gen)
reeval_metrics["reeval_desc_var_max_fitness"] = jnp.zeros_like(num_gen)
reeval_metrics["reeval_desc_var_min_fitness"] = jnp.zeros_like(num_gen)
reeval_metrics["fit_var_qd_score"] = jnp.zeros_like(num_gen)
reeval_metrics["fit_var_coverage"] = jnp.zeros_like(num_gen)
reeval_metrics["fit_var_max_fitness"] = jnp.zeros_like(num_gen)
reeval_metrics["fit_var_min_fitness"] = jnp.zeros_like(num_gen)
reeval_metrics["reeval_fit_var_qd_score"] = jnp.zeros_like(num_gen)
reeval_metrics["reeval_fit_var_coverage"] = jnp.zeros_like(num_gen)
reeval_metrics["reeval_fit_var_max_fitness"] = jnp.zeros_like(num_gen)
reeval_metrics["reeval_fit_var_min_fitness"] = jnp.zeros_like(num_gen)
# Add to overall reeval metrics frame
reeval_metrics_frame = pd.concat(
[reeval_metrics_frame, reeval_metrics], ignore_index=True
)
# Do the same for reeval metrics
elif (
"num_reevals" in config_frame.columns
and not isnan(config_frame["num_reevals"][line])
and config_frame["num_reevals"][line] > 0
):
# Load reeval metrics
with open(reeval_metrics_file, "rb") as f:
reeval_metrics = pickle.load(f)
reeval_metrics = pd.DataFrame.from_dict(reeval_metrics)
# Add x axis to reeval
num_gen = (
jnp.arange(jnp.shape(reeval_metrics["reeval_coverage"])[0])
* config_frame["log_period_reevals"][line]
)
reeval_metrics["gen"] = num_gen
# Add necessary informations
reeval_metrics["env_name"] = env_name
reeval_metrics["algo"] = algo
reeval_metrics["line"] = line
# If xlim given remove all points after
if env_name in graph_env_max_gen.keys():
reeval_metrics = reeval_metrics[
reeval_metrics["gen"] <= graph_env_max_gen[env_name]
]
# Add to overall reeval metrics frame
reeval_metrics_frame = pd.concat(
[reeval_metrics_frame, reeval_metrics], ignore_index=True
)
else:
print(f"WARNING {algo} in {env_name} has no reeval.")
reeval_metrics = metrics
reeval_metrics["reeval_qd_score"] = metrics["qd_score"]
reeval_metrics["reeval_coverage"] = metrics["coverage"]
reeval_metrics["reeval_max_fitness"] = metrics["max_fitness"]
reeval_metrics["desc_var_qd_score"] = jnp.zeros_like(num_gen)
reeval_metrics["desc_var_coverage"] = jnp.zeros_like(num_gen)
reeval_metrics["desc_var_max_fitness"] = jnp.zeros_like(num_gen)
reeval_metrics["desc_var_min_fitness"] = jnp.zeros_like(num_gen)
reeval_metrics["reeval_desc_var_qd_score"] = jnp.zeros_like(num_gen)
reeval_metrics["reeval_desc_var_coverage"] = jnp.zeros_like(num_gen)
reeval_metrics["reeval_desc_var_max_fitness"] = jnp.zeros_like(num_gen)
reeval_metrics["reeval_desc_var_min_fitness"] = jnp.zeros_like(num_gen)
reeval_metrics["fit_var_qd_score"] = jnp.zeros_like(num_gen)
reeval_metrics["fit_var_coverage"] = jnp.zeros_like(num_gen)
reeval_metrics["fit_var_max_fitness"] = jnp.zeros_like(num_gen)
reeval_metrics["fit_var_min_fitness"] = jnp.zeros_like(num_gen)
reeval_metrics["reeval_fit_var_qd_score"] = jnp.zeros_like(num_gen)
reeval_metrics["reeval_fit_var_coverage"] = jnp.zeros_like(num_gen)
reeval_metrics["reeval_fit_var_max_fitness"] = jnp.zeros_like(num_gen)
reeval_metrics["reeval_fit_var_min_fitness"] = jnp.zeros_like(num_gen)
# Add to overall reeval metrics frame
reeval_metrics_frame = pd.concat(
[reeval_metrics_frame, reeval_metrics], ignore_index=True
)
max_gen = max(metrics["gen"])
reeval_max_gen = max(reeval_metrics["gen"])
# Get the final metrics
final_metrics: Dict = {}
final_metrics["qd_score"] = metrics[metrics["gen"] == max_gen][
"qd_score"
].values[0]
final_metrics["coverage"] = metrics[metrics["gen"] == max_gen][
"coverage"
].values[0]
final_metrics["max_fitness"] = metrics[metrics["gen"] == max_gen][
"max_fitness"
].values[0]
# Reeval metrics
final_metrics["reeval_qd_score"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen
]["reeval_qd_score"].values[0]
final_metrics["reeval_coverage"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen
]["reeval_coverage"].values[0]
final_metrics["reeval_max_fitness"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen
]["reeval_max_fitness"].values[0]
# Add necessary informations
final_metrics["env_name"] = [env_name]
final_metrics["algo"] = [algo]
final_metrics["line"] = [line]
# Add to overall final metrics frame
final_metrics = pd.DataFrame.from_dict(final_metrics)
final_metrics_frame = pd.concat(
[final_metrics_frame, final_metrics], ignore_index=True
)
# Get the loss metrics
loss_metrics: Dict = {}
loss_metrics["loss_qd_score"] = (
(final_metrics["qd_score"] - final_metrics["reeval_qd_score"])
/ final_metrics["qd_score"]
* 100
)
loss_metrics["loss_coverage"] = (
(final_metrics["coverage"] - final_metrics["reeval_coverage"])
/ final_metrics["coverage"]
* 100
)
loss_metrics["loss_max_fitness"] = (
(final_metrics["max_fitness"] - final_metrics["reeval_max_fitness"])
/ final_metrics["max_fitness"]
* 100
)
# Add necessary informations
loss_metrics["env_name"] = [env_name]
loss_metrics["algo"] = [algo]
loss_metrics["line"] = [line]
# Add to overall loss metrics frame
loss_metrics = pd.DataFrame.from_dict(loss_metrics)
loss_metrics_frame = pd.concat(
[loss_metrics_frame, loss_metrics], ignore_index=True
)
# Get the var metrics
var_metrics: Dict = {}
var_metrics["desc_var_qd_score"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen
]["desc_var_qd_score"].values[0]
var_metrics["desc_var_coverage"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen
]["desc_var_coverage"].values[0]
var_metrics["desc_var_max_fitness"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen
]["desc_var_max_fitness"].values[0]
var_metrics["desc_var_min_fitness"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen
]["desc_var_min_fitness"].values[0]
var_metrics["reeval_desc_var_qd_score"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen
]["reeval_desc_var_qd_score"].values[0]
var_metrics["reeval_desc_var_coverage"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen
]["reeval_desc_var_coverage"].values[0]
var_metrics["reeval_desc_var_max_fitness"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen
]["reeval_desc_var_max_fitness"].values[0]
var_metrics["reeval_desc_var_min_fitness"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen
]["reeval_desc_var_min_fitness"].values[0]
var_metrics["fit_var_qd_score"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen
]["fit_var_qd_score"].values[0]
var_metrics["fit_var_coverage"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen
]["fit_var_coverage"].values[0]
var_metrics["fit_var_max_fitness"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen
]["fit_var_max_fitness"].values[0]
var_metrics["fit_var_min_fitness"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen
]["fit_var_min_fitness"].values[0]
var_metrics["reeval_fit_var_qd_score"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen
]["reeval_fit_var_qd_score"].values[0]
var_metrics["reeval_fit_var_coverage"] = reeval_metrics[
reeval_metrics["gen"] == reeval_max_gen