-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtable_generator.py
More file actions
1667 lines (1370 loc) · 52.8 KB
/
Copy pathtable_generator.py
File metadata and controls
1667 lines (1370 loc) · 52.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 python3
# -*- coding: utf-8 -*-
"""
Generate LaTeX-ready performance tables, Wilcoxon significance summaries, and
critical-difference diagrams for the UCI Lipschitz benchmark.
The script consumes the JSON artifacts emitted by ``uci_training.py`` and produces
publication-quality tables compliant with JMLR two-column formatting constraints.
Runtime behavior matches the original version; only type hints and documentation were
added.
"""
import argparse
import json
import math
from collections.abc import Mapping, Sequence
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
from scipy.stats import rankdata, f, studentized_range
type SummaryDict = dict[str, Any]
type PerAlgorithmSummaries = dict[str, SummaryDict]
type MetricTableMap = dict[str, pd.DataFrame]
type NumericTableMap = dict[str, pd.DataFrame]
# ------------------------------- Helpers -------------------------------- #
ALG_PRETTY = {
"mlp": "MLP",
"sdp": "SLL",
"ldlt": "LDLT-L",
"ldlt-resnet": "LDLT-R",
"aol": "AOL",
"ortho": "Orthogonal",
"sandwich": "Sandwich",
}
METRICS_PRETTY = {
'mean_cert_acc_108': "Mean Certified Accuracy (108/255)",
'mean_cert_acc_255': "Mean Certified Accuracy (255/255)",
'mean_cert_acc_36': "Mean Certified Accuracy (36/255)",
'mean_cert_acc_72': "Mean Certified Accuracy (72/255)",
'mean_test_acc': "Mean Accuracy"
}
STAR_THRESH = [(0.001, r"^{***}"), (0.01, r"^{**}"), (0.05, r"^{*}")]
def alg_pretty(a: str) -> str:
"""
Canonicalize internal algorithm keys into human-readable labels.
Parameters
----------
a : str
Algorithm identifier as used in training summaries (e.g., ``"ldlt"``).
Returns
-------
label : str
Pretty-printed label; falls back to the original key if no mapping exists.
Raises
------
None
Notes
-----
The mapping is defined in the module-level ``ALG_PRETTY`` dictionary to keep table
captions consistent across outputs.
Mathematical sketch
--------------------
Not applicable.
Examples
--------
>>> alg_pretty("ldlt")
'LDLT-L'
>>> alg_pretty("unknown")
'unknown'
"""
return ALG_PRETTY.get(a, a)
def fmt_mean_std(x: pd.Series) -> str:
"""
Format mean and standard deviation into a LaTeX-friendly string.
Parameters
----------
x : pandas.Series
Row containing ``"mean"`` and ``"std"`` entries derived from dataset aggregations.
Returns
-------
formatted : str
Expression such as ``"0.9123\\,\\tiny$\\pm$0.0123"`` or an em-dash when values
are missing.
Raises
------
None
Notes
-----
Uses four decimal places to match prior tables and inserts a ``\\tiny`` marker so
uncertainty occupies minimal horizontal space.
Mathematical sketch
--------------------
No additional computation beyond simple rounding.
Examples
--------
>>> row = pd.Series({"mean": 0.9, "std": 0.05})
>>> fmt_mean_std(row)
'0.9000\\,\\tiny$\\pm$0.0500'
"""
if pd.isna(x["mean"]) or pd.isna(x["std"]):
return r"\textemdash"
return rf"{x['mean']:.4f}\,\tiny$\pm${x['std']:.4f}"
def p_to_stars(p: float | np.floating[Any]) -> str:
"""
Map a p-value to LaTeX superscript stars following significance thresholds.
Parameters
----------
p : float
Two-sided p-value in `[0, 1]`; NaNs produce an empty string.
Returns
-------
stars : str
One of ``"^{***}"``, ``"^{**}"``, ``"^{*}"``, or ``""``.
Raises
------
None
Notes
-----
Thresholds are defined in ``STAR_THRESH`` with increasingly lenient cutoffs.
Mathematical sketch
--------------------
Not applicable.
Examples
--------
>>> p_to_stars(0.004)
'^{**}'
"""
if pd.isna(p):
return ""
for th, tag in STAR_THRESH:
if p <= th:
return tag
return ""
def bestbold(series: pd.Series) -> pd.Series:
"""
Boldface the maximum numeric entry in a LaTeX-formatted series.
Parameters
----------
series : pandas.Series
Column of formatted strings such as ``"0.9000\\,\\tiny$\\pm$0.0100"`` or
``"\\textemdash"`` placeholders.
Returns
-------
highlighted : pandas.Series
Copy of the input where the maximal numeric entry is wrapped in ``\\textbf{...}``.
Raises
------
None
Notes
-----
Extracts the first floating number using a regex, so the behavior assumes the value
precedes any ``±`` annotations.
Mathematical sketch
--------------------
Equivalent to computing ``argmax`` over extracted floats and boldfacing the matching
entries.
Examples
--------
>>> s = pd.Series(["0.80", "0.85", "0.83"])
>>> bestbold(s).tolist()
['0.80', '\\\\textbf{0.85}', '0.83']
"""
vals = pd.to_numeric(series.str.extract(r"([0-9]+\.?[0-9]*)")[0], errors="coerce")
if vals.isna().all():
return series
best = vals.max(skipna=True)
mask = vals.eq(best)
out = series.copy()
out[mask] = out[mask].apply(lambda s: rf"\textbf{{{s}}}")
return out
def latex_escape(s: str) -> str:
"""
Escape LaTeX-special characters in a string.
Parameters
----------
s : str
Input text potentially containing characters interpreted specially by TeX.
Returns
-------
escaped : str
String safe for insertion into tabular environments.
Raises
------
None
Notes
-----
Covers underscores, percent signs, ampersands, hash marks, braces, tildes, carets,
dollar signs, and backslashes.
Mathematical sketch
--------------------
Not applicable.
Examples
--------
>>> latex_escape("A_1%")
'A\\_1\\%'
"""
return (s.replace("_", r"\_")
.replace("%", r"\%")
.replace("&", r"\&")
.replace("#", r"\#")
.replace("$", r"\$")
.replace("{", r"\{")
.replace("}", r"\}")
.replace("~", r"\textasciitilde{}")
.replace("^", r"\textasciicircum{}")
.replace("\\", r"\textbackslash{}"))
def metric_to_name(s: str) -> str:
"""
Map internal metric identifiers to descriptive names.
Parameters
----------
s : str
Metric key (e.g., ``"mean_cert_acc_36"``).
Returns
-------
label : str
Human-friendly description with LaTeX escapes applied when necessary.
Raises
------
None
Notes
-----
Falls back to escaping the original key when the identifier is not present in
``METRICS_PRETTY``.
Mathematical sketch
--------------------
Not applicable.
Examples
--------
>>> metric_to_name("mean_test_acc")
'Mean Accuracy'
"""
return METRICS_PRETTY.get(s, latex_escape(s))
def ensure_algos(path: Path) -> list[str]:
"""
Detect algorithm subdirectories containing ``summary.json`` artifacts.
Parameters
----------
path : Path
Output directory passed to the training script (contains per-algorithm folders).
Returns
-------
algorithms : list of str
Sorted list of algorithm identifiers derived from subfolder names.
Raises
------
OSError
If the directory cannot be listed.
Notes
-----
This helper mirrors the discovery logic from the training orchestrator to avoid
re-specifying algorithm names during table generation.
Mathematical sketch
--------------------
Not applicable.
Examples
--------
>>> ensure_algos(Path('runs/UCI')) # doctest: +SKIP
['ldlt', 'sdp', ...]
"""
algs = []
for p in path.iterdir():
if p.is_dir() and (p / "summary.json").exists():
algs.append(p.name)
return sorted(algs)
# -------------------------- Load experiment data ------------------------- #
def load_all(out_dir: Path, algorithms: Sequence[str] | None = None) -> tuple[
PerAlgorithmSummaries, pd.DataFrame, list[str]]:
"""
Load per-algorithm summaries and the Wilcoxon comparison table from disk.
Parameters
----------
out_dir : Path
Directory containing subfolders for each algorithm plus shared JSON artifacts.
algorithms : sequence of str, optional
Explicit subset of algorithms to load; defaults to auto-discovery via
:func:`ensure_algos`.
Returns
-------
per_alg : dict
Mapping from algorithm key to its full ``summary.json`` dictionary.
wilc_df : pandas.DataFrame
Dataframe representation of ``wilcoxon_pairwise_all.json`` (empty if missing).
loaded_algs : list of str
Actual algorithms inspected, preserving the requested/auto-discovered order.
Raises
------
None
Notes
-----
Each ``summary.json`` file originates from ``schedule_and_run`` and includes
dataset-level fold aggregates under ``"datasets"``.
Mathematical sketch
--------------------
Not applicable.
Examples
--------
>>> summaries, wilc, algs = load_all(Path('runs/UCI')) # doctest: +SKIP
"""
if algorithms is None:
algorithms = ensure_algos(out_dir)
per_alg: PerAlgorithmSummaries = {}
for alg in algorithms:
f = out_dir / alg / "summary.json"
if not f.exists():
continue
with open(f, "r") as fh:
j = json.load(fh)
per_alg[alg] = j
# Wilcoxon pairwise (produced by run_wilcoxon_tests_all_metrics)
wilc = out_dir / "wilcoxon_pairwise_all.json"
wilc_df = pd.read_json(wilc) if wilc.exists() else pd.DataFrame()
return per_alg, wilc_df, list(algorithms)
# --------------------- Build metric summary across DS -------------------- #
def sorting_key(m: str) -> tuple[int, int | str]:
"""
Provide a deterministic ordering for metric identifiers.
Parameters
----------
m : str
Metric key such as ``"mean_test_acc"`` or ``"mean_cert_acc_36"``.
Returns
-------
key : tuple
Tuple used for sorting: accuracy first, then certified metrics ordered by
epsilon value, followed by any remaining metrics alphabetically.
Raises
------
None
Notes
-----
Ensures tables list accuracy metrics before robustness metrics to align with
reporting conventions.
Mathematical sketch
--------------------
Parsing splits the identifier on underscores and attempts to convert the last token
to an integer epsilon value.
Examples
--------
>>> sorting_key('mean_cert_acc_36')
(1, 36)
"""
if m == 'mean_test_acc':
return (0, 0)
try:
return (1, int(m.split('_')[-1]))
except Exception:
return (2, m)
def build_metric_summary(per_alg: PerAlgorithmSummaries) -> tuple[MetricTableMap, NumericTableMap]:
r"""
Aggregate mean metrics across datasets for each algorithm.
Parameters
----------
per_alg : dict
Mapping returned by :func:`load_all` containing dataset-level ``mean_*`` entries.
Returns
-------
pretty_tables : dict[str, pandas.DataFrame]
Table per metric with columns ``["Algorithm", "$N$ datasets", "Value"]`` where
``Value`` is a ``mean±std`` string and the maximum entry is bolded.
numeric_tables : dict[str, pandas.DataFrame]
Companion numeric tables containing raw means/stds indexed by algorithm for
downstream ranking.
Raises
------
None
Notes
-----
Only keys starting with ``"mean_"`` are considered, mirroring the training output.
Missing metrics yield empty dictionaries.
Mathematical sketch
--------------------
For each algorithm and metric, the method computes
\( \mu = \frac{1}{|D|}\sum_{d \in D} v_{d} \) and the sample standard deviation over
datasets \( D \), where \( v_d \) is the dataset-level metric.
Examples
--------
>>> build_metric_summary({"mlp": {"datasets": {"foo": {"mean_test_acc": 0.9}}}})[0].keys()
dict_keys(['mean_test_acc'])
"""
rows = []
for alg, j in per_alg.items():
for ds, payload in j.get("datasets", {}).items():
for k, v in payload.items():
if k.startswith("mean_") and (isinstance(v, (int, float)) and math.isfinite(v)):
rows.append({"dataset": ds, "algorithm": alg, "metric": k, "value": float(v)})
df = pd.DataFrame(rows)
if df.empty:
return {}, {}
metrics = sorted(df["metric"].unique().tolist(), key=sorting_key)
result_tables: MetricTableMap = {}
numeric_tables: NumericTableMap = {}
for m in metrics:
sub = df[df["metric"] == m]
grp = sub.groupby("algorithm")["value"].agg(["mean", "std", "count"]).reset_index()
grp["Algorithm"] = grp["algorithm"].map(alg_pretty)
grp = grp.sort_values("Algorithm")
show = grp[["Algorithm", "count", "mean", "std"]].copy()
show.rename(columns={"count": "$N$ datasets"}, inplace=True)
show["Value"] = show.apply(fmt_mean_std, axis=1)
show = show[["Algorithm", "$N$ datasets", "Value"]]
show["Value"] = bestbold(show["Value"])
result_tables[m] = show
numeric_tables[m] = grp[["Algorithm", "mean", "std"]].set_index("Algorithm")[["mean", 'std']]
return result_tables, numeric_tables
# ------------------------ Build Wilcoxon tables -------------------------- #
def format_small_p(p: float | np.floating[Any]) -> str:
"""
Render a p-value in scientific notation with optional significance stars.
Parameters
----------
p : float
P-value in `[0, 1]`; a value of zero is displayed explicitly.
Returns
-------
formatted : str
LaTeX math-mode string (e.g., ``"$1.2e-03^{**}$"``).
Raises
------
None
Notes
-----
Calls :func:`p_to_stars` for star annotation.
Mathematical sketch
--------------------
Not applicable.
Examples
--------
>>> format_small_p(0.0)
'$0^{***}$'
"""
if p == 0:
return f"$0{p_to_stars(p)}$"
return f"${p:.1e}{p_to_stars(p)}$"
def build_wilcoxon_tables(wilc_df: pd.DataFrame) -> dict[str, pd.DataFrame]:
"""
Post-process Wilcoxon pairwise statistics for LaTeX rendering.
Parameters
----------
wilc_df : pandas.DataFrame
Output of ``wilcoxon_pairwise_all.json`` containing pairwise comparisons.
Returns
-------
tables : dict[str, pandas.DataFrame]
Mapping from metric key to a formatted dataframe with pretty algorithm names,
integer counts, and scientific-notation p-values.
Raises
------
None
Notes
-----
The function retains Holm-adjusted p-values for sorting but drops them from the
displayed output to avoid redundant columns.
Mathematical sketch
--------------------
Not applicable.
Examples
--------
>>> build_wilcoxon_tables(pd.DataFrame()) # empty input
{}
"""
if wilc_df.empty:
return {}
tdict: dict[str, pd.DataFrame] = {}
for m, sub in wilc_df.groupby("metric"):
t = sub.copy()
t["Alg A"] = t["alg_a"].map(alg_pretty)
t["Alg B"] = t["alg_b"].map(alg_pretty)
t["WinRate A"] = (t["win_rate_a_over_b"]).round(4)
t["Median AB"] = t["median_diff_a_minus_b"].round(4)
t["W"] = t["W_stat"].round(4)
t["p"] = t["p_two_sided"].apply(format_small_p)
t["p_within"] = t["p_holm_within_metric"].apply(format_small_p)
t["p_global"] = t["p_holm_global"].apply(format_small_p)
t["r"] = t["effect_size_r"].round(4)
t["n"] = t["n_common"].astype(int)
t["winsA"] = t["wins_a"].astype(int)
t["winsB"] = t["wins_b"].astype(int)
t["ties"] = t["ties"].astype(int)
cols = ["Alg A", "Alg B", "n", "winsA", "winsB", "ties",
"WinRate A", "Median AB", "W", "p", "p_within", "p_global", "r",
"p_holm_within_metric"]
tdict[m] = t[cols].sort_values(["p_holm_within_metric", "Alg A", "Alg B"]).drop(
columns=["p_holm_within_metric"])
return tdict
# ------------------------ Model size ranges table ------------------------ #
def build_model_size_ranges(per_alg: PerAlgorithmSummaries) -> pd.DataFrame:
"""
Compute min–max architecture statistics across all datasets and folds.
Parameters
----------
per_alg : dict
Summary dictionary whose ``"datasets"`` entries include ``fold_results``.
Returns
-------
ranges : pandas.DataFrame
Table with columns ``["Algorithm", "Width", "Depth", "Parameters", "Padding",
"Input dim", "Output dim"]`` containing string ranges (e.g., ``"64--256"``) or
em-dashes when unavailable.
Raises
------
None
Notes
-----
Iterates through every recorded fold to capture architecture variation introduced
by hyperparameter sweeps.
Mathematical sketch
--------------------
Each column reports ``min(value) -- max(value)`` over the collected list per
algorithm.
Examples
--------
>>> build_model_size_ranges({"mlp": {"datasets": {}}}).empty
False
"""
recs = []
for alg, j in per_alg.items():
ws, ds, ps, pad, din, dout = [], [], [], [], [], []
for ds_name, payload in j.get("datasets", {}).items():
for fr in payload.get("fold_results", []):
for key, bag in [("width", ws), ("depth", ds), ("parameters", ps),
("padding", pad), ("in_features", din), ("out_features", dout)]:
if key in fr and fr[key] is not None:
bag.append(fr[key])
def rng(a):
if not a:
return r"\textemdash"
return rf"{int(np.min(a))}--{int(np.max(a))}" # TeX en-dash
recs.append({
"Algorithm": alg_pretty(alg),
"Width": rng(ws),
"Depth": rng(ds),
"Parameters": rng(ps),
"Padding": rng(pad),
"Input dim": rng(din),
"Output dim": rng(dout),
})
df = pd.DataFrame(recs)
df = df.sort_values(
by="Algorithm",
key=lambda s: list(zip(s.ne("MLP"), s.str.contains("LDLT", na=False), s.str.casefold()))
).reset_index(drop=True)
return df
def _dataset_metric_matrix(per_alg: PerAlgorithmSummaries, metric: str) -> pd.DataFrame:
"""
Construct a dataset-by-algorithm pivot table for a specific metric.
Parameters
----------
per_alg : dict
Loaded summaries keyed by algorithm.
metric : str
Metric identifier (must exist inside the per-dataset payloads).
Returns
-------
pivot : pandas.DataFrame
Wide table with datasets as rows and pretty algorithm labels as columns.
Raises
------
None
Notes
-----
Filters out missing or non-finite entries to keep subsequent statistical tests well
defined.
Mathematical sketch
--------------------
Equivalent to pivoting the long-format table on columns `(dataset, algorithm)`.
Examples
--------
>>> _dataset_metric_matrix({"mlp": {"datasets": {"foo": {"mean_test_acc": 0.9}}}}, "mean_test_acc")
algorithm MLP
dataset
foo 0.9
"""
rows = []
for alg, js in per_alg.items():
for ds, payload in js.get("datasets", {}).items():
v = payload.get(metric, None)
if isinstance(v, (int, float)) and np.isfinite(v):
rows.append({"dataset": ds, "algorithm": alg_pretty(alg), "value": float(v)})
if not rows:
return pd.DataFrame()
df = pd.DataFrame(rows)
return df.pivot_table(index="dataset", columns="algorithm", values="value", aggfunc="mean")
def _friedman_iman_nemenyi(pivot: pd.DataFrame, alpha: float = 0.05) -> dict[str, Any] | None:
r"""
Compute Friedman/Iman–Davenport statistics and the Nemenyi critical difference.
Parameters
----------
pivot : pandas.DataFrame
Dataset-by-algorithm matrix with higher values indicating better performance.
alpha : float, default=0.05
Family-wise error rate for the Nemenyi test.
Returns
-------
stats : dict or None
Dictionary containing ``N`` datasets, ``k`` algorithms, average ranks (Series),
F-statistic, p-value, and the critical difference. Returns ``None`` if less than
two algorithms are present.
Raises
------
None
Notes
-----
Ranks are assigned per row with 1 denoting the best algorithm. The Iman–Davenport
F-statistic refines the Friedman test for finite samples, and the CD is derived from
the Studentized range distribution.
Mathematical sketch
--------------------
Computes:
* Friedman statistic \( \chi_F^2 = \frac{12N}{k(k+1)} \sum_j \bar{r}_j^2 - 3N(k+1) \).
* Iman–Davenport \( F_F = \frac{(N-1)\chi_F^2}{N(k-1) - \chi_F^2} \).
* Critical difference \( \text{CD} = q_\alpha \sqrt{\frac{k(k+1)}{6N}} \).
Examples
--------
>>> pivot = pd.DataFrame({'A': [0.9, 0.8], 'B': [0.85, 0.82]})
>>> _friedman_iman_nemenyi(pivot) is not None
True
"""
if pivot.empty or pivot.shape[1] < 2:
return None
X = pivot.to_numpy(float)
N, k = X.shape
ranks = np.vstack([rankdata(-row, method="average") for row in X])
avg_ranks = pd.Series(ranks.mean(axis=0), index=pivot.columns).sort_values()
chi2_F = (12 * N) / (k * (k + 1)) * (np.sum(avg_ranks.values ** 2) - k * (k + 1) ** 2 / 4.0)
denom = N * (k - 1) - chi2_F
F_F = ((N - 1) * chi2_F) / denom if denom > 1e-12 else np.inf
p_F = 1 - f.cdf(F_F, k - 1, (k - 1) * (N - 1))
q_alpha = studentized_range.isf(alpha, k, np.inf) / math.sqrt(2.0)
CD = float(q_alpha * np.sqrt(k * (k + 1) / (6.0 * N)))
return {"N": N, "k": k, "avg_ranks": avg_ranks, "F_F": float(F_F), "p_F": float(p_F), "CD": CD}
def _wilcoxon_summary_for_metric(wilc_df: pd.DataFrame, metric: str, alpha: float = 0.05) -> pd.DataFrame:
"""
Summarize significant Wilcoxon wins/losses per algorithm for a metric.
Parameters
----------
wilc_df : pandas.DataFrame
Full Wilcoxon comparison table.
metric : str
Metric identifier to filter.
alpha : float, default=0.05
Holm-adjusted significance level.
Returns
-------
summary : pandas.DataFrame
Index by pretty algorithm name with columns reporting significant wins, losses,
net wins, share of significant wins, and average effect size `r`.
Raises
------
None
Notes
-----
Counts both roles (Alg A/B) to ensure symmetry. When no comparisons exist, returns
an empty dataframe.
Mathematical sketch
--------------------
For each pair (a, b) the summary increments wins when the median difference is
positive and the Holm-adjusted p-value does not exceed ``alpha``.
Examples
--------
>>> _wilcoxon_summary_for_metric(pd.DataFrame(), "mean_test_acc").empty
True
"""
if wilc_df is None or wilc_df.empty:
return pd.DataFrame()
sub = wilc_df[wilc_df["metric"] == metric].copy()
if sub.empty:
return pd.DataFrame()
sub["win_A"] = (sub["median_diff_a_minus_b"] > 0) & (sub["p_holm_within_metric"] <= alpha)
sub["win_B"] = (sub["median_diff_a_minus_b"] < 0) & (sub["p_holm_within_metric"] <= alpha)
algs = sorted(set(sub["alg_a"]).union(set(sub["alg_b"])))
rows = []
for a in algs:
sig_wins = int(sub[(sub["alg_a"] == a) & sub["win_A"]].shape[0] +
sub[(sub["alg_b"] == a) & sub["win_B"]].shape[0])
sig_losses = int(sub[(sub["alg_a"] == a) & sub["win_B"]].shape[0] +
sub[(sub["alg_b"] == a) & sub["win_A"]].shape[0])
r_wins = []
r_wins += sub[(sub["alg_a"] == a) & sub["win_A"]]["effect_size_r"].tolist()
r_wins += sub[(sub["alg_b"] == a) & sub["win_B"]]["effect_size_r"].tolist()
mean_r_win = float(np.mean(r_wins)) if len(r_wins) else 0.0
total_pairs = len(algs) - 1
rows.append({
"Algorithm": alg_pretty(a),
"sig_wins": sig_wins,
"sig_losses": sig_losses,
"net_sig_wins": sig_wins - sig_losses,
"sig_win_share": sig_wins / total_pairs if total_pairs > 0 else np.nan,
"mean_r_win": mean_r_win,
})
return pd.DataFrame(rows).set_index("Algorithm").sort_values(
["net_sig_wins", "sig_wins", "mean_r_win"], ascending=False
)
def build_overall_metric_stats(
per_alg: PerAlgorithmSummaries,
wilc_df: pd.DataFrame,
alpha: float = 0.05,
) -> tuple[dict[str, pd.DataFrame], dict[str, dict[str, float]]]:
"""
Combine average ranks, Wilcoxon outcomes, and CD statistics per metric.
Parameters
----------
per_alg : dict
Summary dictionaries by algorithm.
wilc_df : pandas.DataFrame
Wilcoxon pairwise results.
alpha : float, default=0.05
Significance level for Wilcoxon and CD computations.
Returns
-------
tables : dict[str, pandas.DataFrame]
Table per metric with columns: average rank, significant wins/losses, net wins,
win share, and mean effect size.
captions : dict[str, dict[str, float]]
Metadata containing ``N``, ``k``, ``F_F``, ``p_F``, and ``CD`` for caption text.
Raises
------
None
Notes
-----
LDLT variants are kept at the bottom of the table to emphasize other methods first,
mirroring paper layout preferences.
Mathematical sketch
--------------------
Relies on :func:`_friedman_iman_nemenyi` for rank statistics and merges them with
:func:`_wilcoxon_summary_for_metric` outputs.
Examples
--------
>>> build_overall_metric_stats({"mlp": {"datasets": {}}}, pd.DataFrame())
({}, {})
"""
metrics = set()
for _, js in per_alg.items():
for _, payload in js.get("datasets", {}).items():
for k, v in payload.items():
if k.startswith("mean_") and isinstance(v, (int, float)) and np.isfinite(v):
metrics.add(k)
metrics = sorted(metrics, key=sorting_key)
out_tables: dict[str, pd.DataFrame] = {}
caps: dict[str, dict[str, float]] = {}
for m in metrics:
pivot = _dataset_metric_matrix(per_alg, m)
fried = _friedman_iman_nemenyi(pivot, alpha=alpha)
if fried is None:
continue
avg = fried["avg_ranks"].rename("Avg rank ↓").to_frame()
wsum = _wilcoxon_summary_for_metric(wilc_df, m, alpha=alpha)
tbl = avg.join(wsum, how="left").fillna(
{"sig_wins": 0, "sig_losses": 0, "net_sig_wins": 0, "sig_win_share": 0.0, "mean_r_win": 0.0}
)
upper = tbl.drop(index=[i for i in tbl.index if i in ("LDLT-L", "LDLT-R")], errors="ignore")
lower = tbl.loc[[i for i in ("LDLT-L", "LDLT-R") if i in tbl.index]]
out_tables[m] = pd.concat([upper, lower], axis=0)
caps[m] = {"N": fried["N"], "k": fried["k"], "F_F": fried["F_F"], "p_F": fried["p_F"], "CD": fried["CD"]}
return out_tables, caps
# ---------------------------- LaTeX emitters ---------------------------- #
HEADER = r"""
% JMLR-ready tables for two-column papers
% Required packages (no siunitx):
% \usepackage{booktabs}
% \usepackage{threeparttable}
% \usepackage{threeparttablex} % for TableNotes + longtable
% \usepackage{longtable}
% Optional for landscape: \usepackage{pdflscape}
"""
def tex_table_metric_summary(metric_name: str, df: pd.DataFrame, wide: bool = False) -> str:
"""
Render a per-metric mean±std table into LaTeX.
Parameters
----------
metric_name : str
Metric key used for caption and label.
df : pandas.DataFrame
Summary table produced by :func:`build_metric_summary`.
wide : bool, default=False
If ``True``, emit a ``table*`` environment for two-column layouts.
Returns
-------
latex : str
LaTeX source string.
Raises
------
None
Notes
-----
Sorts rows by descending value to highlight top performers.
Mathematical sketch
--------------------
Not applicable.
Examples
--------
>>> tex_table_metric_summary("mean_test_acc", pd.DataFrame(columns=["Algorithm","$N$ datasets","Value"]))
'\\\\begin{table}[t]\\n\\\\centering\\n...'
"""
cap = f"Sorted mean$\\pm$std across $N$ datasets for each algorithm on {metric_to_name(metric_name)}."
lab = f"tab:{metric_name}"
env = "table*" if wide else "table"
colspec = "l r l"
lines = [fr"\begin{{{env}}}[t]",
r"\centering",
r"\begin{threeparttable}",
rf"\caption{{{cap}}}",
rf"\label{{{lab}}}",
rf"\begin{{tabular}}{{{colspec}}}",
r"\toprule",
r"Algorithm & $N$ & Value \\",
r"\midrule"]
df = df.sort_values(by='Value', ascending=False)
for _, r in df.iterrows():
lines.append(rf"{r['Algorithm']} & {int(r['$N$ datasets'])} & {r['Value']} \\")
lines += [r"\bottomrule",
r"\end{tabular}",
r"\end{threeparttable}",
fr"\end{{{env}}}"]