-
Notifications
You must be signed in to change notification settings - Fork 17
/
AnalyseBenchmarkResults.py
executable file
·1860 lines (1654 loc) · 52.6 KB
/
AnalyseBenchmarkResults.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
"""Analysis script dedicated to the HADDOCK3 + haddock-runner benchmarks.
Generates multiple-plots analysing different scenarios performances.
- Barplots: Standard best performing model among top X from all targets.
- Melquiplots: Per-target complex performances among top 200.
- Violinplots: Performance distribution among top X from all targets.
Please modify the Global variable: CAPRIEVAL_STEPS to suite your needs.
It is used to generate nice title to the caprieval steps.
Usage:
>python3 AnalyseBenchmarkResults.py <path/to/benchmark/dir/to/analyse/>
"""
import argparse
import glob
import json
import os
import sys
import zipfile
from pathlib import Path
from typing import Callable, Optional, Union
# Try to load external libraries
try:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
except ModuleNotFoundError:
sys.exit(
"\n[ERROR]: Issue when loading the external libraries.\n\n"
"This script is using `numpy` and `matplotlib` libraries.\n"
"Please make sure they are accessible with current environment.\n"
"(e.g.: >pip install numpy matplotlib)\n"
)
__version__ = "1.0.5" # August 2024
__author__ = ", ".join((
"BonvinLab",
"Computational Structural Biology group",
"Utrecht University",
"the Netherlands",
"Europe",
"Planet Earth",
"Milky Way",
))
__dev__ = (
"Victor G.P. Reys",
)
####################
# GLOBAL VARIABLES #
####################
# Define custom caprieval steps names
# NOTE: "Feel free to modify this `CAPRIEVAL_STEPS` dict content to fit your experiment" # noqa : E501
# This dict must have:
# as keys -> Index of the caprieval stage (used to parse data)
# as values -> Name to give to this stage (used as legends plots)
# NOTE: e.g.: for the following run: [topoaa, rigidbody, caprieval, seletop, caprieval.1, flexref, caprieval.2, emref, caprieval.3, clustfcc, seletopclusts, caprieval.4] # noqa : E501
# CAPRIEVAL_STEPS = {
# '02': 'rigidbody',
# '04': 'seletop 200',
# '06': 'flexref',
# '08': 'emref',
# '11': 'top 4 models per fcc clust',
# }
CAPRIEVAL_STEPS = {
'02': 'rigidbody',
'04': 'seletop 200',
'06': 'flexref',
'08': 'emref',
'11': 'top 4 models per fcc clust',
}
# Set threshold of top X structures to take into account
TOP_X_THRESHOLDS = (1, 5, 10, 20, 50, 100, 200, 500, 1000, )
# Set number of entries to display in melquiplot
MELQUIPLOT_NB_ENTRIES = 200
# CAPRI performances classes
# NOTE: for each class, we define the lower and upper limit
ALL_PERFORMANCES_CLASSES = {
"protein": {
"irmsd": {
"High": (0, 1),
"Medium": (1, 2),
"Acceptable": (2, 4),
"Near-acceptable": (4, 6),
"Low": (6, 99999),
"Missing": (-2, -0.5),
},
"dockq": {
"High": (0.8, 1),
"Medium": (0.6, 0.8),
"Acceptable": (0.5, 0.6),
"Near-acceptable": (0.4, 0.5),
"Low": (0, 0.4),
"Missing": (-2, -0.5),
},
},
"peptide": {
"irmsd": {
"High": (0, 0.5),
"Medium": (0.5, 1),
"Acceptable": (1, 2),
"Near-acceptable": (2, 3),
"Low": (3, 99999),
"Missing": (-2, -0.5),
},
"dockq": {
"High": (0.895, 1),
"Medium": (0.71, 0.895),
"Acceptable": (0.43, 0.71),
"Near-acceptable": (0.35, 0.43),
"Low": (0, 0.35),
"Missing": (-2, -0.5),
},
},
# FIXME: Optimize irmsd and dockq values for glycan
"glycan": {
"irmsd": {
"High": (0, 0.5),
"Medium": (0.5, 1),
"Acceptable": (1, 2),
"Near-acceptable": (2, 3),
"Low": (3, 99999),
"Missing": (-2, -0.5),
},
"dockq": {
"High": (0.895, 1),
"Medium": (0.71, 0.895),
"Acceptable": (0.43, 0.71),
"Near-acceptable": (0.35, 0.43),
"Low": (0, 0.35),
"Missing": (-2, -0.5),
},
"ilrmsd": {
"High": (0, 1),
"Medium": (1, 2),
"Acceptable": (2, 3),
"Near-acceptable": (3, 4),
"Low": (4, 99999),
"Missing": (-2, -0.5),
},
},
}
PERFORMANCES_CLASSES = ALL_PERFORMANCES_CLASSES["protein"]
# Add color mapper
COLORS_MAPPER = {
"High": "darkgreen",
"Medium": "lightgreen",
"Acceptable": "lightblue",
"Near-acceptable": "gainsboro",
"Low": "white",
"Missing": "dimgrey",
}
# Performance order
PERF_ORDER = (
"High",
"Medium",
"Acceptable",
"Near-acceptable",
"Low",
"Missing",
)
# DPI of the generated figures
DPI = 400
####################
# DEFINE FUNCTIONS #
####################
def gen_graph(
ax: plt.Axes,
high: list,
med: list,
acc: list,
nacc: list,
low: list,
miss: list,
top: list,
width: float = 0.5,
percentage: bool = True,
) -> None:
"""Plot a barplot on the provided axis `ax`.
Parameters
----------
ax : `matplotlib.pyplot.Axes`
The axis on which to draw the plot.
high : list
List containing number of `high performances` models
for each threshold in `top`.
med : list
List containing number of `medium performances` models
for each threshold in `top`.
acc : list
List containing number of `acceptable performances` models
for each threshold in `top`.
nacc : list
List containing number of `near acceptable performances` models
for each threshold in `top`.
low : list
List containing number of `low performances` models
for each threshold in `top`.
miss : list
List containing number of missing model data
for each threshold in `top`.
top : list
List of number of entries take into consideration.
width : float
Width of the bar to draw.
percentage : bool
If true, number of entries are converted into % sucess
"""
# Performances mapper
performances = {
"High": high,
"Medium": med,
"Acceptable": acc,
"Near-acceptable": nacc,
"Low": low,
"Missing": miss,
}
if percentage:
# Compute total at each position
indices_total: dict[int, int] = {}
for label, counts in performances.items():
for i, val in enumerate(counts):
total = indices_total.setdefault(i, 0)
indices_total[i] = total + val
# Compute percentages
percentage_perfs: dict[str, list[float]] = {}
for label, counts in performances.items():
for ind, val in enumerate(counts):
try:
percent = 100 * val / indices_total[ind]
except ZeroDivisionError:
percent = 0
finally:
precent_list = percentage_perfs.setdefault(label, [])
precent_list.append(percent)
performances = percentage_perfs
# X labels
tops = [f'Top{v}' for v in top]
# initialize first bottom values with 0s
bottom = np.zeros(len(high))
# Loop over performances
for label in PERF_ORDER:
# point performances data
perfs = performances[label]
# draw bars
ax.bar(
tops,
perfs,
width,
label=label,
bottom=bottom,
color=COLORS_MAPPER[label],
)
# increment bottom value
bottom += perfs
# New labels for percentage specific displaying
if percentage:
yticks = [0, 25, 50, 75, 100]
ax.set_yticks(yticks)
ax.set_yticklabels(yticks)
# Draw horizontal lines for better reading
xlims = ax.get_xlim()
xstart = np.floor(xlims[0])
xend = np.ceil(xlims[1])
for yposition in yticks[1:-1]:
ax.plot(
[xstart, xend],
[yposition, yposition],
linestyle="dashed",
color="gray",
alpha=0.7,
)
# Orient X labels
ax.set_xticks(ax.get_xticks())
ax.set_xticklabels(ax.get_xticklabels(), rotation=30, ha='right')
ylabel = "Nb. entries" if not percentage else "% sucess rate"
ax.set_ylabel(ylabel)
def clear_plt() -> None:
"""Clear all previous instances/data generated by matplotlib."""
plt.gca()
plt.cla()
plt.clf()
def gen_violin(
ax: plt.Axes,
perf_data: list,
labels: list,
metric: str = "",
) -> None:
"""Draw a violinplot on the axis.
inspired from:
https://matplotlib.org/stable/gallery/statistics/customized_violin.html
Parameters
----------
ax : `matplotlib.pyplot.Axes`
The axis on which to draw the plot.
perf_data : list
List of performances values.
labels : list
List of labels (same order as `perf_data`).
"""
# Draw it
parts = ax.violinplot(
perf_data,
showmeans=False,
showmedians=False,
showextrema=False,
)
# Get color ramp
nbcolors = 10 if len(perf_data) <= 10 else 20
colorramp = mpl.colormaps[f'tab{nbcolors}']
# Modify colors
for vi, pc in enumerate(parts['bodies']):
pc.set_facecolor(colorramp((vi + 0.5) / nbcolors))
pc.set_edgecolor('black')
pc.set_alpha(1)
quartile1, medians, quartile3 = np.percentile(
perf_data,
[25, 50, 75],
axis=1,
)
whiskers = np.array([
adjacent_values(sorted_array, q1, q3)
for sorted_array, q1, q3 in zip(perf_data, quartile1, quartile3)
])
whiskers_min, whiskers_max = whiskers[:, 0], whiskers[:, 1]
inds = np.arange(1, len(medians) + 1)
ax.scatter(inds, medians, marker='_', color='white', s=30, zorder=3)
ax.vlines(inds, quartile1, quartile3, color='k', linestyle='-', lw=5)
ax.vlines(inds, whiskers_min, whiskers_max, color='k', linestyle='-', lw=1)
ax.set_ylabel(metric)
# Set labels
if labels:
ax.set_xticks(list(range(1, len(labels) + 1)))
ax.set_xticklabels(
labels,
rotation=40,
ha='right',
rotation_mode='anchor',
)
def adjacent_values(
vals: list[float],
q1: float,
q3: float,
) -> tuple[float, float]:
"""Find adjacent values.
Inspired from:
https://matplotlib.org/stable/gallery/statistics/customized_violin.html
Parameters
----------
vals : list
List of values
q1 : float
Value of the first quartil
q3 : float
Value of the 3rd quartil
Return
------
lower_adjacent_value : float
Closest true value under q1
upper_adjacent_value : float
Closest true value above q3
"""
# Finds closest true value above q3
upper_adjacent_value = q3 + (q3 - q1) * 1.5
upper_adjacent_value = np.clip(upper_adjacent_value, q3, vals[-1])
# Find closest true value under q1
lower_adjacent_value = q1 - (q3 - q1) * 1.5
lower_adjacent_value = np.clip(lower_adjacent_value, vals[0], q1)
return lower_adjacent_value, upper_adjacent_value
def stage_name(cname: str) -> str:
"""Try to return the user defined stage name, or return default.
Parameters
----------
cname : str
Index of the caprieval stage
Returns
-------
name : str
Name of the stage
"""
try:
name = CAPRIEVAL_STEPS[cname]
except KeyError:
name = f"{cname}_caprieval"
return name
def gen_full_comparison_violins(
scenars_perfs: dict,
basepath: str = "./",
title: str = "",
metric: str = "",
progress: bool = True,
) -> None:
"""Combine all scenarios caprieval within same plot.
Parameters
----------
scenars_perfs : dict
Dictionary of all scenario stages performances.
basepath : str
Basepath where to write plot.
title : str
Title of the figure.
"""
# Clear pervious instances of matplotlib
clear_plt()
# Compute number of rows (scenarios)
scenars_order = sorted(scenars_perfs)
nb_scenar = len(scenars_order)
# Compute number of colums (capri steps)
steps_order = sorted(scenars_perfs[scenars_order[0]])
nb_steps = len(steps_order)
# Get number of threshodls
tops_order = sorted(
scenars_perfs[scenars_order[0]][steps_order[0]]['values'],
)
nb_thresh = len(tops_order)
# Compute total number of plots
total_plots = nb_thresh * nb_steps
processed = 0
# Initate figures / axis
fig, axes = plt.subplots(
figsize=((nb_steps * 4) + 1, (nb_thresh * 3) + 1),
nrows=nb_thresh,
ncols=nb_steps,
sharey=True,
sharex=True,
)
# Loop over rows
for ri, topx in enumerate(tops_order):
for ci, cname in enumerate(steps_order):
processed += 1
if progress:
print(f"{100 * processed / total_plots:>6.2f} %", end="\r")
# Point axis
ax = axes[ri][ci]
# Build sub-dt dict
perf_data = [
sorted(scenars_perfs[scenar][cname]['values'][topx])
for scenar in scenars_order
]
# Set labels on last row only
labels = None
if ri + 1 == nb_thresh:
labels = [so.replace('scenario-', '') for so in scenars_order]
# Write bars
gen_violin(
ax,
perf_data,
labels,
metric=metric,
)
# Add columns titles
pad = 5
for ax, cname in zip(axes[0], steps_order):
# Annotate column
ax.annotate(
stage_name(cname),
xy=(0.5, 1),
xytext=(0, pad),
xycoords='axes fraction',
textcoords='offset points',
size='large',
ha='center',
va='baseline',
)
# Add rows titles
for ax, topx in zip(axes[:, 0], tops_order):
ax.annotate(
f'Top {topx}',
xy=(0, 0.5),
xytext=(-ax.yaxis.labelpad - pad, 0),
xycoords=ax.yaxis.label,
textcoords='offset points',
size='large',
ha='right',
va='center',
)
# Add figure title
fig.suptitle(title, fontsize=16)
# Get color ramp
nbcolors = 10 if nb_scenar <= 10 else 20
colorramp = mpl.colormaps[f'tab{nbcolors}']
# Add bars legend
fig.legend(
[
mpatches.FancyBboxPatch(
(-0.025, -0.05), 0.05, 0.1, ec="none",
boxstyle=mpatches.BoxStyle("Round", pad=0.02),
color=colorramp((si + 0.5) / nbcolors),
)
for si, _perfclass in enumerate(scenars_order)
],
[so.replace('scenario-', '') for so in scenars_order],
loc='outside lower center',
ncols=4,
title="Screnarios",
)
plt.gca().set_ylim(bottom=0)
# adjust border to let annotations fit inside graph
fig.subplots_adjust(left=0.08, top=0.95, bottom=0.12, right=0.98)
# save figure
plt.savefig(f"{basepath}_violins.png", format='png', dpi=DPI)
return
def gen_full_comparison_melquiplots(
scenars_perfs: dict,
perf_dtype: str = "irmsd",
basepath: str = "./",
progress: bool = True,
) -> str:
"""Generate multiple melquiplots for each scenario.
Parameters
----------
scenars_perfs : dict
Dict containing performances for each scenario.
perf_dtype : str, optional
Model quality metric to use, by default "irmsd"
title : str, optional
Prefix to give to archive, by default "benchmark_melquis"
basepath : str, optional
Where to write the files, by default "./"
Returns
-------
archive_path : str
Path to the generated archive.zip
"""
# Clear pervious instances of matplotlib
clear_plt()
# Set progression variables
all_generated_melquis: list[str] = []
processed = 0
total_plots = len(scenars_perfs)
# Loop over scenarios
for scenar_name, scenar_perfs in scenars_perfs.items():
processed += 1
if progress:
print(f"{100 * processed / total_plots:>6.2f} %", end="\r")
# Generate melquiplot for this scenario
scenar_melqui_path = make_scenar_melquiplots(
scenar_perfs,
perf_dtype=perf_dtype,
title=scenar_name,
basepath=basepath,
)
all_generated_melquis.append(scenar_melqui_path)
# Generate archive of melqui plots
archive_path = Path(f"{basepath}_melquiplots.zip")
path = archive_path.parent
archive_name = archive_path.name
initdir = os.getcwd()
os.chdir(path)
with zipfile.ZipFile(archive_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
for figure in all_generated_melquis:
zipf.write(Path(figure).name)
os.chdir(initdir)
# Remove all original files
for generated_melqui in all_generated_melquis:
os.remove(generated_melqui)
# Return archive path
return archive_path
def make_scenar_melquiplots(
scenar_perfs: dict,
perf_dtype: str = "irmsd",
title: str = "melquiplot",
basepath: str = "./",
) -> str:
"""Generate multiples melquiplots for each Caprieval steps of a scenario.
Parameters
----------
scenar_perfs : dict
Dict containing performances of a scenario.
perf_dtype : str, optional
Model quality metric to use, by default "irmsd"
title : str, optional
Title to the figure, by default "melquiplot"
basepath : str, optional
Where to write the files, by default "./"
Returns
-------
figpath : str
Path to the generated figure.
"""
# Count nb_steps and entries
steps = sorted(scenar_perfs)
nb_rows = len(steps)
nb_entries = len(scenar_perfs[steps[0]].keys())
dtype_perf_classes = PERFORMANCES_CLASSES[perf_dtype]
# Initate figures / axis
fig, axes = plt.subplots(
figsize=((nb_entries * 1) + 1, (nb_rows * 5) + 3),
nrows=nb_rows,
ncols=1,
)
# Loop over stages
for si, (stage, stage_perfs) in enumerate(scenar_perfs.items()):
# Point axis
ax = axes[si]
# Draw a melquiplot on this axis
melquiplot(ax, stage_perfs, width=min(1, 5 / nb_entries))
# Add title to graph
ax.annotate(
stage_name(stage),
xy=(0.5, 1),
xytext=(0, 5),
xycoords='axes fraction',
textcoords='offset points',
size='large',
ha='center',
va='baseline',
)
# Add figure title
fig.suptitle(title, fontsize=16)
# Add Legend
legend_data = [
(
plt.Rectangle((0, 0), 1, 1, fc=COLORS_MAPPER[perfclass]),
rf'{perfclass} | {dtype_perf_classes[perfclass][0]} <= {perf_dtype.upper()} < {dtype_perf_classes[perfclass][1]}$\AA$', # noqa : E501
)
for perfclass in PERF_ORDER
]
legend_proxies, legend_labels = zip(*legend_data)
# Add bars legend
fig.legend(
legend_proxies,
legend_labels,
loc='outside lower center',
ncols=len(PERF_ORDER),
title="performance classes",
)
# adjust border to let annotations fit inside graph
fig.subplots_adjust(left=0.02, top=0.95, bottom=0.06, right=0.98)
# save figure
figpath = f"{basepath}_{title}_melquiplot.png"
plt.savefig(figpath, format='png', dpi=DPI)
return figpath
def melquiplot(
ax: plt.Axes,
pdb_perfs: dict[str, list[str]],
width: float = 0.3,
) -> None:
"""Draw a melquiplot on an sub-figure with provided input data.
Parameters
----------
ax : plt.Axes
The axis on which to draw the Melquiplot
pdb_perfs : dict[str, list[str]]
Performances for each entry at a give stage.
"""
width = 0.1
max_stack_y = 0
pdb_labels = sorted(pdb_perfs)
stack_h_labels_pos: list[float] = []
# Loop over each input entry
for entry_index, pdb in enumerate(pdb_labels, start=0):
# Point data
perfs = pdb_perfs[pdb][MELQUIPLOT_NB_ENTRIES]
x_coord = entry_index * width
y_coord = 0
# Loop over perfs
for perf_label in perfs:
# Draw a bar
ax.bar(
x_coord,
2,
align="edge",
bottom=y_coord,
color=COLORS_MAPPER[perf_label],
width=width * 0.98,
edgecolor='none',
linewidth=0,
)
y_coord += 1
max_stack_y = max(max_stack_y, y_coord)
stack_h_labels_pos.append(x_coord + (width / 2))
# Aesthetics
ax.set_xlim((0, len(pdb_labels) * width))
ax.set_ylim((0, max_stack_y))
ax.set_ylabel('Energy Score Ranking (lower is better)')
ax.set_xticks(stack_h_labels_pos)
ax.set_xticklabels(pdb_labels, rotation=45, fontsize='small')
ax.xaxis.set_ticks_position('none')
def melquiplot_original(
ax: plt.Axes,
pdb_perfs: dict[str, list[str]],
) -> None:
"""Draw a melquiplot on an sub-figure with provided input data.
Parameters
----------
ax : plt.Axes
The axis on which to draw the Melquiplot
pdb_perfs : dict[str, list[str]]
Performances for each entry at a give stage.
"""
max_stack_v = 0
pdb_labels = sorted(pdb_perfs)
stack_h_labels_pos: list[float] = []
# Loop over each input entry
for entry_index, pdb in enumerate(pdb_labels, start=1):
# Point data
perfs = pdb_perfs[pdb][MELQUIPLOT_NB_ENTRIES]
stack_v = 0
# Loop over perfs
for perf_label in perfs:
# Draw a bar
ax.bar(
entry_index - 0.5,
2,
bottom=stack_v,
color=COLORS_MAPPER[perf_label],
width=0.99,
edgecolor='none',
linewidth=0,
)
stack_v += 1
max_stack_v = max(max_stack_v, stack_v)
stack_h_labels_pos.append(entry_index - 0.501)
# Aesthetics
ax.set_xlim((0.05, len(pdb_labels) + 0.05))
ax.set_ylim((0, max_stack_v))
ax.set_ylabel('Energy Score Ranking (lower is better)')
ax.set_xticks(stack_h_labels_pos)
ax.set_xticklabels(pdb_labels, rotation=45, fontsize='small')
ax.xaxis.set_ticks_position('none')
def gen_full_comparison_barplots(
scenars_perfs: dict,
basepath: str = "./",
title: str = "",
progress: bool = True,
no_percentage: bool = False,
) -> None:
"""Combine all scenarios caprieval within same plot.
Parameters
----------
scenars_perfs : dict
Dictionary of all scenario stages performances.
basepath : str
Basepath where to write plot.
title : str
Title of the figure.
"""
# Clear pervious instances of matplotlib
clear_plt()
# Compute number of rows
rows_order = sorted(scenars_perfs)
nb_rows = len(rows_order)
# Compute number of colums
cols_order = sorted(scenars_perfs[rows_order[0]])
nb_cols = len(cols_order)
# Compute total number of plots
total_plots = nb_rows * nb_cols
processed = 0
# Initate figures / axis
fig, axes = plt.subplots(
figsize=((nb_cols * 4) + 1, (nb_rows * 3) + 4),
nrows=nb_rows, ncols=nb_cols,
)
# Loop over rows
for ri, rname in enumerate(rows_order):
# Point row axe(s)
if len(rows_order) == 1:
axr = axes
else:
axr = axes[ri]
for ci, cname in enumerate(cols_order):
# Display progression
processed += 1
if progress:
print(f"{100 * processed / total_plots:>6.2f} %", end="\r")
# Point column axe(s)
if len(cols_order) == 1:
ax = axr
else:
ax = axr[ci]
# Point data
perf_data = scenars_perfs[rname][cname]['classes']
# Get sorted entreis
topx = sorted(perf_data)
# attribute perf classes at each topX model
high = [perf_data[top]['High'] for top in topx]
med = [perf_data[top]['Medium'] for top in topx]
acc = [perf_data[top]['Acceptable'] for top in topx]
nacc = [perf_data[top]['Near-acceptable'] for top in topx]
low = [perf_data[top]['Low'] for top in topx]
miss = [perf_data[top]['Missing'] for top in topx]
# Write bars
gen_graph(
ax,
high,
med,
acc,
nacc,
low,
miss,
topx,
percentage=not no_percentage,
)
# Set padding between two plots
pad = 5
# Search for first row
if len(rows_order) == 1:
first_row = axes
else:
first_row = axes[0]
# Add columns titles
for ax, cname in zip(first_row, cols_order):
# Add column name
ax.annotate(
stage_name(cname),
xy=(0.5, 1),
xytext=(0, pad),
xycoords='axes fraction',
textcoords='offset points',
size='large',
ha='center',
va='baseline',
)
# Find all first row columns
if len(rows_order) == 1:
axrows = [axes]
else:
axrows = axes
if len(cols_order) == 1:
axrows_firstcols = axrows
else:
axrows_firstcols = [ax[0] for ax in axrows]
# Add rows titles
for ax, rname in zip(axrows_firstcols, rows_order):
ax.annotate(
rname.replace('scenario-', ''),
xy=(0, 0.5),
xytext=(-ax.yaxis.labelpad - pad, 0),
xycoords=ax.yaxis.label,
textcoords='offset points',
size='large',
ha='right',
va='center',
)
# Add figure title
fig.suptitle(title, fontsize=16)
# Add bars legend
fig.legend(
[mpatches.FancyBboxPatch(
(-0.025, -0.05), 0.05, 0.1, ec="none",
boxstyle=mpatches.BoxStyle("Round", pad=0.02),
color=COLORS_MAPPER[perfclass],
)
for perfclass in PERF_ORDER],
PERF_ORDER,
loc='outside lower center',
ncols=len(PERF_ORDER),
title="performance classes",
)
# Adjust border to let annotations fit inside graph
fig.subplots_adjust(left=0.15, top=0.9, bottom=0.15, right=0.98)
# Save figure
plt.savefig(f"{basepath}_capribarpolots.png", format='png', dpi=DPI)
return
def get_pdb_entries(basepath: str) -> list:
"""Retrieve list of PDBid.
Parameters
----------
basepath : str
Path to a scenario directory containing pdb entries.
Return
------
pdbids : str
List of pdb entries benchmarked in this scenario.
"""
pdbids = [
pdbid_path.stem
for pdbid_path in Path(basepath).glob("*/")
if pdbid_path.is_dir()
]
return pdbids
def get_scenarios_names(basepath: str) -> list:
"""Retrieve list of scenario names.
Parameters
----------
basepath : str
Path to the benchmark directory to analyse containing X scenarios.
Return
------
scenarios_names : list
List of tested scenario names.
"""
scenario_paths = glob.glob(f'{basepath}scenario*/')
scenarios_names = [sp.split('/')[-2] for sp in scenario_paths]
return scenarios_names
def scenario_name_2_threshold(scenar_name: str) -> float:
"""Gather threshold value from scenario name.
NOTE: function used for CPORT-ARCTIC3D-BM5 benchmark
Parameters
----------
scenar_name : str
Name of a scenario.
Return
------
threshold : float
CPORT threshold value used in this scenario.
"""
# Get last part of scenario name
str_thresh = scenar_name.split('-')[-1]
# Replace underscore by a dot
dot_thresh = str_thresh.replace('_', '.')
# Cast it to float
threshold = float(dot_thresh)
return threshold