Skip to content

Benchmarking

The benchmark module provides a framework for systematically comparing solver performance across different datasets and conditions.

Overview

The benchmarking framework supports:

  • Multiple datasets: Test solvers on various simulated and real datasets
  • Solver categories: Compare solvers within and across categories
  • Parallel execution: Efficient batch processing of many solver-dataset combinations
  • Result visualization: Built-in plotting for benchmark results

Quick Start

from invert.benchmark import BenchmarkRunner, create_datasets

# Create benchmark datasets
datasets = create_datasets(forward, n_samples=100)

# Run benchmarks
runner = BenchmarkRunner(
    solvers=["MNE", "dSPM", "LCMV", "Champagne"],
    datasets=datasets,
)
results = runner.run()

# Visualize results
from invert.benchmark import visualize_results
visualize_results(results)

API Reference

BenchmarkRunner

invert.benchmark.BenchmarkRunner

Source code in invert/benchmark/runner.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
class BenchmarkRunner:
    def __init__(
        self,
        forward: mne.Forward,
        info: mne.Info,
        solvers: list[str] | None = None,
        categories: list[str] | None = None,
        exclude_solvers: list[str] | None = None,
        datasets: dict[str, DatasetConfig] | None = None,
        n_samples: int = 50,
        n_jobs: int | None = None,
        random_seed: int | None = None,
        solver_params: dict[str, dict[str, Any]] | None = None,
    ):
        self.forward = forward
        self.info = info
        if solvers is None and categories is None:
            self.solvers = [
                s for s in _DEFAULT_SOLVERS if s not in set(exclude_solvers or [])
            ]
        else:
            self.solvers = resolve_solvers(
                solvers=solvers, categories=categories, exclude=exclude_solvers
            )
        self.datasets = datasets or dict(BENCHMARK_DATASETS)
        self.n_samples = n_samples
        self.random_seed = random_seed
        self.solver_params = solver_params or {}

        # Auto-detect n_jobs if not specified
        if n_jobs is None:
            cpu_count = os.cpu_count()
            self.n_jobs = max(1, cpu_count - 1) if cpu_count is not None else 1
        elif n_jobs == -1:
            self.n_jobs = os.cpu_count() or 1
        else:
            self.n_jobs = max(1, n_jobs)

        self._results: list[BenchmarkResult] = []

    def run(self) -> list[BenchmarkResult]:
        pos = pos_from_forward(self.forward)
        adjacency = mne.spatial_src_adjacency(self.forward["src"], verbose=0)
        results = []

        # Total number of (dataset, solver) combinations for overall progress
        total_combinations = len(self.datasets) * len(self.solvers)

        with tqdm(
            total=total_combinations, desc="Overall Progress", position=0
        ) as pbar_overall:
            for ds_name, ds_config in self.datasets.items():
                logger.info("Dataset: %s", ds_name)

                # Generate all samples for this dataset once
                sim_config = SimulationConfig(
                    batch_size=self.n_samples,
                    n_sources=ds_config.n_sources,
                    n_orders=ds_config.n_orders,
                    snr_range=ds_config.snr_range,
                    n_timepoints=ds_config.n_timepoints,
                    random_seed=self.random_seed,
                )
                gen = SimulationGenerator(self.forward, config=sim_config)
                x_batch, y_batch, _ = next(gen.generate())

                for solver_name in self.solvers:
                    logger.info("  Solver: %s", solver_name)
                    solver_cls = get_solver_class(solver_name)
                    solver = solver_cls()

                    # Best-effort determinism for fair comparisons when a seed is provided.
                    if self.random_seed is not None:
                        seed = int(self.random_seed)
                        random.seed(seed)
                        np.random.seed(seed)
                        try:  # torch is optional
                            import torch  # type: ignore[import-not-found]

                            torch.manual_seed(seed)
                            if torch.cuda.is_available():
                                torch.cuda.manual_seed_all(seed)
                        except Exception:
                            pass

                    # Neural-network solvers train from SimulationConfig and then
                    # apply the trained model to each sample.
                    if _expects_simulation_config(solver_cls):
                        train_sim_config = sim_config.model_copy(
                            update={"batch_size": _default_nn_batch_size(self.forward)}
                        )
                        logger.info(
                            "ANN training batch_size=%d (default=2*n_dipoles) for %s",
                            int(train_sim_config.batch_size),
                            solver_name,
                        )
                        params = dict(self.solver_params.get(solver_name, {}))
                        alpha = params.pop("alpha", "auto")
                        solver.make_inverse_operator(
                            self.forward, train_sim_config, alpha=alpha, **params
                        )
                        sample_metrics: list[SampleMetrics] = []
                        for i in tqdm(
                            range(self.n_samples),
                            desc=f"{ds_name}/{solver_name}",
                            position=1,
                            leave=False,
                        ):
                            evoked = mne.EvokedArray(
                                x_batch[i], self.info, tmin=0.0, verbose=0
                            )
                            stc = solver.apply_inverse_operator(evoked)
                            y_pred = stc.data
                            metrics = evaluate_all(
                                y_batch[i], y_pred, adjacency, adjacency, pos, pos
                            )
                            sample_metrics.append(self._metrics_from_dict(metrics))

                    # Parallelize based on require_recompute
                    elif not solver.require_recompute:
                        # Compute inverse operator once, then parallelize application
                        if solver.require_data:
                            evoked = mne.EvokedArray(
                                x_batch[0], self.info, tmin=0.0, verbose=0
                            )
                            solver.make_inverse_operator(
                                self.forward, evoked, alpha="auto"
                            )
                        else:
                            solver.make_inverse_operator(self.forward, alpha="auto")

                        # Check if solver has inverse_operators attribute
                        # Some solvers (e.g., SolverRandomNoise) don't create inverse operators
                        if not hasattr(solver, "inverse_operators"):
                            # Fall back to direct application for each sample
                            sample_metrics = []
                            for i in range(len(x_batch)):
                                evoked = mne.EvokedArray(
                                    x_batch[i], self.info, tmin=0.0, verbose=0
                                )
                                stc = solver.apply_inverse_operator(evoked)
                                y_pred = stc.data
                                metrics = evaluate_all(
                                    y_batch[i], y_pred, adjacency, adjacency, pos, pos
                                )
                                sample_metrics.append(self._metrics_from_dict(metrics))
                        else:
                            # Select optimal regularization via L-curve/GCV
                            if len(solver.inverse_operators) > 1:  # type: ignore[attr-defined]
                                _, optimal_idx = solver.regularise_gcv(x_batch[0])  # type: ignore[attr-defined]
                            else:
                                optimal_idx = 0
                            inv_op = solver.inverse_operators[optimal_idx]  # type: ignore[attr-defined]

                            # Extract the inverse operator matrix (numpy array)
                            inv_op_matrix = inv_op.data[0]

                            # Parallel application
                            sample_metrics = self._run_parallel_apply(
                                inv_op_matrix,
                                x_batch,
                                y_batch,
                                adjacency,
                                pos,
                                ds_name,
                                solver_name,
                            )
                    else:
                        # Parallelize full computation (require_recompute=True)
                        module_path, class_name = _SOLVER_REGISTRY[solver_name]

                        sample_metrics = self._run_parallel_compute(
                            module_path,
                            class_name,
                            self.forward,
                            self.info,
                            x_batch,
                            y_batch,
                            adjacency,
                            pos,
                            solver.require_data,
                            ds_name,
                            solver_name,
                        )

                    result = self._aggregate(solver_name, ds_name, sample_metrics)
                    results.append(result)
                    pbar_overall.update(1)
                    pbar_overall.set_postfix(
                        {"dataset": ds_name, "solver": solver_name}
                    )

        self._results = results
        return results

    def _run_parallel_apply(
        self,
        inv_op_matrix: np.ndarray,
        x_batch: np.ndarray,
        y_batch: np.ndarray,
        adjacency,
        pos: np.ndarray,
        ds_name: str,
        solver_name: str,
    ) -> list[SampleMetrics]:
        """Parallelize inverse operator application (require_recompute=False)."""
        if self.n_jobs == 1:
            sample_metrics = []
            for i in tqdm(
                range(self.n_samples),
                desc=f"{ds_name}/{solver_name}",
                position=1,
                leave=False,
            ):
                _, metrics = _apply_inverse_worker(
                    i, inv_op_matrix, x_batch[i], y_batch[i], adjacency, pos
                )
                sample_metrics.append(self._metrics_from_dict(metrics))
            return sample_metrics

        sample_metrics_dict = {}
        with ThreadPoolExecutor(max_workers=self.n_jobs) as executor:
            futures = {
                executor.submit(
                    _apply_inverse_worker,
                    i,
                    inv_op_matrix,
                    x_batch[i],
                    y_batch[i],
                    adjacency,
                    pos,
                ): i
                for i in range(self.n_samples)
            }

            with tqdm(
                total=self.n_samples,
                desc=f"{ds_name}/{solver_name}",
                position=1,
                leave=False,
            ) as pbar:
                for future in as_completed(futures):
                    try:
                        idx, metrics = future.result()
                        sample_metrics_dict[idx] = self._metrics_from_dict(metrics)
                    except Exception as e:
                        logger.error(f"Sample {futures[future]} failed: {e}")
                        idx = futures[future]
                        sample_metrics_dict[idx] = SampleMetrics(
                            mle=float("nan"),
                            emd=float("nan"),
                            sd=float("nan"),
                            ap=float("nan"),
                            correlation=float("nan"),
                        )
                    pbar.update(1)

        return [sample_metrics_dict[i] for i in range(self.n_samples)]

    def _run_parallel_compute(
        self,
        solver_module: str,
        solver_class: str,
        forward: mne.Forward,
        info: mne.Info,
        x_batch: np.ndarray,
        y_batch: np.ndarray,
        adjacency,
        pos: np.ndarray,
        require_data: bool,
        ds_name: str,
        solver_name: str,
    ) -> list[SampleMetrics]:
        """Parallelize full computation (require_recompute=True)."""
        if self.n_jobs == 1:
            sample_metrics = []
            for i in tqdm(
                range(self.n_samples),
                desc=f"{ds_name}/{solver_name}",
                position=1,
                leave=False,
            ):
                _, metrics = _compute_and_apply_worker(
                    i,
                    solver_module,
                    solver_class,
                    forward,
                    info,
                    x_batch[i],
                    y_batch[i],
                    adjacency,
                    pos,
                    require_data,
                )
                sample_metrics.append(self._metrics_from_dict(metrics))
            return sample_metrics

        sample_metrics_dict = {}
        with ThreadPoolExecutor(max_workers=self.n_jobs) as executor:
            futures = {
                executor.submit(
                    _compute_and_apply_worker,
                    i,
                    solver_module,
                    solver_class,
                    forward,
                    info,
                    x_batch[i],
                    y_batch[i],
                    adjacency,
                    pos,
                    require_data,
                ): i
                for i in range(self.n_samples)
            }

            with tqdm(
                total=self.n_samples,
                desc=f"{ds_name}/{solver_name}",
                position=1,
                leave=False,
            ) as pbar:
                for future in as_completed(futures):
                    try:
                        idx, metrics = future.result()
                        sample_metrics_dict[idx] = self._metrics_from_dict(metrics)
                    except Exception as e:
                        logger.error(f"Sample {futures[future]} failed: {e}")
                        idx = futures[future]
                        sample_metrics_dict[idx] = SampleMetrics(
                            mle=float("nan"),
                            emd=float("nan"),
                            sd=float("nan"),
                            ap=float("nan"),
                            correlation=float("nan"),
                        )
                    pbar.update(1)

        return [sample_metrics_dict[i] for i in range(self.n_samples)]

    @staticmethod
    def _metrics_from_dict(m: dict) -> SampleMetrics:
        return SampleMetrics(
            mle=float(m["Mean_Localization_Error"]),
            emd=float(m["EMD"]),
            sd=float(m["sd"]),
            ap=float(m["average_precision"]),
            correlation=float(m["correlation"]),
        )

    @staticmethod
    def _aggregate(
        solver_name: str,
        dataset_name: str,
        samples: list[SampleMetrics],
    ) -> BenchmarkResult:
        # Metrics where higher is better (worst = 10th percentile)
        # Others are lower is better (worst = 90th percentile)
        higher_is_better = {"average_precision", "correlation"}

        arrays = {
            "mean_localization_error": np.array([s.mle for s in samples]),
            "emd": np.array([s.emd for s in samples]),
            "spatial_dispersion": np.array([s.sd for s in samples]),
            "average_precision": np.array([s.ap for s in samples]),
            "correlation": np.array([s.correlation for s in samples]),
        }
        metrics = {}
        for key, arr in arrays.items():
            # For higher-is-better metrics, worst 10% = 10th percentile (lowest)
            # For lower-is-better metrics, worst 10% = 90th percentile (highest)
            worst_pct = 10 if key in higher_is_better else 90
            metrics[key] = AggregateStats(
                mean=float(np.nanmean(arr)),
                std=float(np.nanstd(arr)),
                median=float(np.nanmedian(arr)),
                worst_10_pct=float(np.nanpercentile(arr, worst_pct)),
            )
        return BenchmarkResult(
            solver_name=solver_name,
            dataset_name=dataset_name,
            category=get_solver_category(solver_name),
            metrics=metrics,
            samples=samples,
        )

    def _compute_best_solvers(self) -> dict[str, Any]:
        """Compute best solver per dataset for each metric.

        Returns
        -------
        dict
            Structure: {dataset_name: {metric_name: {"solver": solver_name, "value": metric_value}}}
        """
        # Metrics where lower is better
        lower_is_better = {"mean_localization_error", "emd", "spatial_dispersion"}
        # Metrics where higher is better
        higher_is_better = {"average_precision", "correlation"}

        datasets = sorted(set(r.dataset_name for r in self._results))
        all_metrics: set[str] = set()
        for r in self._results:
            all_metrics.update(r.metrics.keys())

        best_solvers: dict[str, Any] = {}
        for dataset in datasets:
            best_solvers[dataset] = {}
            for metric in all_metrics:
                # Find all results for this dataset
                dataset_results = [
                    r for r in self._results if r.dataset_name == dataset
                ]

                if not dataset_results:
                    continue

                # Get metric values for all solvers on this dataset
                # Filter out NaN values
                solver_values = {}
                for r in dataset_results:
                    if metric in r.metrics:
                        value = r.metrics[metric].mean
                        if not np.isnan(value):
                            solver_values[r.solver_name] = value

                if not solver_values:
                    continue

                # Determine best based on metric type
                if metric in lower_is_better:
                    best_solver = min(solver_values.items(), key=lambda x: x[1])
                elif metric in higher_is_better:
                    best_solver = max(solver_values.items(), key=lambda x: x[1])
                else:
                    # Default to lower is better if unknown
                    best_solver = min(solver_values.items(), key=lambda x: x[1])

                best_solvers[dataset][metric] = {
                    "solver": best_solver[0],
                    "value": round(best_solver[1], 4),
                }

        return best_solvers

    def _compute_average_ranks(
        self,
    ) -> tuple[dict[str, dict[str, float]], dict[str, float]]:
        """Compute per-dataset and global average ranks for each solver.

        For each (dataset, metric) pair, solvers are ranked 1..N (best=1).
        Per-dataset rank: average rank across metrics for that dataset.
        Global rank: average of the per-dataset ranks.

        Returns
        -------
        tuple
            (per_dataset_ranks, global_ranks) where:
            - per_dataset_ranks: {dataset_name: {solver_name: avg_rank}}
            - global_ranks: {solver_name: avg_rank}
        """
        lower_is_better = {"mean_localization_error", "emd", "spatial_dispersion"}

        datasets = sorted(set(r.dataset_name for r in self._results))
        all_metrics: set[str] = set()
        for r in self._results:
            all_metrics.update(r.metrics.keys())

        # Collect ranks per dataset: dataset -> solver_name -> list of ranks
        dataset_solver_ranks: dict[str, dict[str, list[float]]] = {}

        for dataset in datasets:
            dataset_results = [r for r in self._results if r.dataset_name == dataset]
            dataset_solver_ranks[dataset] = {}
            for metric in all_metrics:
                # Gather (solver, value) pairs, skip NaN
                solver_values = []
                for r in dataset_results:
                    if metric in r.metrics:
                        val = r.metrics[metric].mean
                        if not np.isnan(val):
                            solver_values.append((r.solver_name, val))

                if not solver_values:
                    continue

                # Sort: ascending for lower-is-better, descending for higher-is-better
                reverse = metric not in lower_is_better
                solver_values.sort(key=lambda x: x[1], reverse=reverse)

                # Dense ranking: tied values get the same rank
                rank = 1
                for i, (solver_name, val) in enumerate(solver_values):
                    if i > 0 and val != solver_values[i - 1][1]:
                        rank = i + 1
                    dataset_solver_ranks[dataset].setdefault(solver_name, []).append(
                        rank
                    )

        # Per-dataset ranks: average across metrics for each dataset
        per_dataset_ranks: dict[str, dict[str, float]] = {}
        for dataset in datasets:
            per_dataset_ranks[dataset] = {
                name: round(float(np.mean(ranks)), 2)
                for name, ranks in sorted(
                    dataset_solver_ranks[dataset].items(),
                    key=lambda x: np.mean(x[1]),
                )
            }

        # Global ranks: average of per-dataset ranks
        solver_dataset_ranks: dict[str, list[float]] = {}
        for _dataset, solver_ranks in per_dataset_ranks.items():
            for solver_name, avg_rank in solver_ranks.items():
                solver_dataset_ranks.setdefault(solver_name, []).append(avg_rank)

        global_ranks = {
            name: round(float(np.mean(ranks)), 2)
            for name, ranks in sorted(
                solver_dataset_ranks.items(), key=lambda x: np.mean(x[1])
            )
        }

        return per_dataset_ranks, global_ranks

    def save(
        self,
        path: str | Path,
        *,
        compact: bool = False,
        name: str | None = None,
        description: str | None = None,
    ) -> None:
        path = Path(path)

        per_dataset_ranks, global_ranks = self._compute_average_ranks()

        datasets_payload = {
            key: cfg.model_dump() if isinstance(cfg, BaseModel) else dict(cfg)  # type: ignore[arg-type]
            for key, cfg in self.datasets.items()
        }

        m_electrodes: int | None = None
        n_leadfield_columns: int | None = None
        n_sources_space: int | None = None
        n_orient: int | None = None
        try:
            lf = self.forward["sol"]["data"]
            m_electrodes = int(lf.shape[0])
            n_leadfield_columns = int(lf.shape[1])
        except Exception:
            m_electrodes = None
            n_leadfield_columns = None

        try:
            raw_nsource = self.forward.get("nsource")  # type: ignore[call-arg]
            if raw_nsource is not None:
                n_sources_space = int(raw_nsource)
        except Exception:
            n_sources_space = None

        if n_sources_space is None:
            try:
                src = self.forward.get("src")  # type: ignore[call-arg]
                if isinstance(src, (list, tuple)):
                    n_sources_space = int(
                        sum(
                            len(s.get("vertno", [])) for s in src if isinstance(s, dict)
                        )
                    )
            except Exception:
                n_sources_space = None

        if (
            n_sources_space is not None
            and n_leadfield_columns is not None
            and n_sources_space > 0
            and n_leadfield_columns % n_sources_space == 0
        ):
            n_orient = int(n_leadfield_columns // n_sources_space)

        if compact:
            # Minimal payload for the MkDocs dashboard: aggregated metrics only.
            output = {
                "ranks": per_dataset_ranks,
                "global_ranks": global_ranks,
                "metadata": {
                    "name": name,
                    "description": description,
                    "timestamp": datetime.now().isoformat(),
                    "n_samples": self.n_samples,
                    "random_seed": self.random_seed,
                    "solvers": self.solvers,
                    "m": m_electrodes,
                    "n": n_sources_space,
                    "m_electrodes": m_electrodes,
                    "n_sources": n_sources_space,
                    "n_leadfield_columns": n_leadfield_columns,
                    "n_orient": n_orient,
                },
                "datasets": datasets_payload,
                "results": [
                    {
                        "solver_name": r.solver_name,
                        "dataset_name": r.dataset_name,
                        "category": r.category,
                        "metrics": {
                            metric: {
                                "mean": float(stats.mean),
                                "std": float(stats.std),
                                "median": float(stats.median),
                                "worst_10_pct": (
                                    float(stats.worst_10_pct)
                                    if stats.worst_10_pct is not None
                                    else None
                                ),
                            }
                            for metric, stats in r.metrics.items()
                        },
                        "samples": [],
                    }
                    for r in self._results
                ],
            }
            path.write_text(json.dumps(output, indent=2))
            logger.info("Compact results saved to %s", path)
            return

        # Full payload (includes per-sample metrics)
        summary = {}
        for r in self._results:
            key = f"{r.solver_name} | {r.dataset_name}"
            summary[key] = {m: round(s.mean, 4) for m, s in r.metrics.items()}

        best_solvers = self._compute_best_solvers()
        output = {
            "summary": summary,
            "best_solvers": best_solvers,
            "ranks": per_dataset_ranks,
            "global_ranks": global_ranks,
            "metadata": {
                "name": name,
                "description": description,
                "timestamp": datetime.now().isoformat(),
                "n_samples": self.n_samples,
                "random_seed": self.random_seed,
                "solvers": self.solvers,
                "m": m_electrodes,
                "n": n_sources_space,
                "m_electrodes": m_electrodes,
                "n_sources": n_sources_space,
                "n_leadfield_columns": n_leadfield_columns,
                "n_orient": n_orient,
            },
            "datasets": datasets_payload,
            "results": [r.model_dump() for r in self._results],
        }
        path.write_text(json.dumps(output, indent=2))
        logger.info("Results saved to %s", path)

    @classmethod
    def load(cls, path: str | Path) -> list[BenchmarkResult]:
        path = Path(path)
        data = json.loads(path.read_text())
        results = []
        for r in data["results"]:
            # Populate category if missing (for backward compatibility)
            if "category" not in r or r["category"] is None:
                r["category"] = get_solver_category(r["solver_name"])
            # Add correlation if missing (backward compatibility)
            for sample in r.get("samples", []):
                if "correlation" not in sample:
                    sample["correlation"] = float("nan")
            results.append(BenchmarkResult(**r))
        return results

    @classmethod
    def update_summary_statistics(cls, path: str | Path) -> None:
        """Update summary statistics (including best_solvers) for an existing results file.

        This is useful when you want to regenerate the summary from existing results
        without re-running the benchmark.

        Parameters
        ----------
        path : str or Path
            Path to the benchmark results JSON file.
        """
        path = Path(path)
        data = json.loads(path.read_text())
        results = []
        for r in data["results"]:
            # Populate category if missing (for backward compatibility)
            if "category" not in r or r["category"] is None:
                r["category"] = get_solver_category(r["solver_name"])
            # Add correlation if missing (backward compatibility)
            for sample in r.get("samples", []):
                if "correlation" not in sample:
                    sample["correlation"] = float("nan")
            results.append(BenchmarkResult(**r))

        # Create a temporary runner instance to use the _compute_best_solvers method
        # We need to set _results manually
        temp_runner = cls.__new__(cls)
        temp_runner._results = results

        # Recompute summary
        summary = {}
        for r in results:
            key = f"{r.solver_name} | {r.dataset_name}"
            summary[key] = {m: round(s.mean, 4) for m, s in r.metrics.items()}

        # Compute best solvers and ranks
        best_solvers = temp_runner._compute_best_solvers()
        per_dataset_ranks, global_ranks = temp_runner._compute_average_ranks()

        # Update the data structure
        data["summary"] = summary
        data["best_solvers"] = best_solvers
        data["ranks"] = per_dataset_ranks
        data["global_ranks"] = global_ranks

        # Write back
        path.write_text(json.dumps(data, indent=2))
        logger.info("Updated summary statistics in %s", path)

update_summary_statistics classmethod

update_summary_statistics(path: str | Path) -> None

Update summary statistics (including best_solvers) for an existing results file.

This is useful when you want to regenerate the summary from existing results without re-running the benchmark.

Parameters:

Name Type Description Default
path str or Path

Path to the benchmark results JSON file.

required
Source code in invert/benchmark/runner.py
@classmethod
def update_summary_statistics(cls, path: str | Path) -> None:
    """Update summary statistics (including best_solvers) for an existing results file.

    This is useful when you want to regenerate the summary from existing results
    without re-running the benchmark.

    Parameters
    ----------
    path : str or Path
        Path to the benchmark results JSON file.
    """
    path = Path(path)
    data = json.loads(path.read_text())
    results = []
    for r in data["results"]:
        # Populate category if missing (for backward compatibility)
        if "category" not in r or r["category"] is None:
            r["category"] = get_solver_category(r["solver_name"])
        # Add correlation if missing (backward compatibility)
        for sample in r.get("samples", []):
            if "correlation" not in sample:
                sample["correlation"] = float("nan")
        results.append(BenchmarkResult(**r))

    # Create a temporary runner instance to use the _compute_best_solvers method
    # We need to set _results manually
    temp_runner = cls.__new__(cls)
    temp_runner._results = results

    # Recompute summary
    summary = {}
    for r in results:
        key = f"{r.solver_name} | {r.dataset_name}"
        summary[key] = {m: round(s.mean, 4) for m, s in r.metrics.items()}

    # Compute best solvers and ranks
    best_solvers = temp_runner._compute_best_solvers()
    per_dataset_ranks, global_ranks = temp_runner._compute_average_ranks()

    # Update the data structure
    data["summary"] = summary
    data["best_solvers"] = best_solvers
    data["ranks"] = per_dataset_ranks
    data["global_ranks"] = global_ranks

    # Write back
    path.write_text(json.dumps(data, indent=2))
    logger.info("Updated summary statistics in %s", path)

BenchmarkResult

invert.benchmark.BenchmarkResult

Bases: BaseModel

Source code in invert/benchmark/runner.py
class BenchmarkResult(BaseModel):
    solver_name: str
    dataset_name: str
    category: str | None = None
    metrics: dict[str, AggregateStats]
    samples: list[SampleMetrics]

Dataset Configuration

invert.benchmark.DatasetConfig

Bases: BaseModel

Source code in invert/benchmark/datasets.py
class DatasetConfig(BaseModel):
    name: str
    description: str
    n_sources: Union[int, tuple[int, int]]
    n_orders: Union[int, tuple[int, int]]
    snr_range: tuple[float, float]
    n_timepoints: int
    n_samples: int = 50

invert.benchmark.create_datasets

create_datasets() -> dict[str, DatasetConfig]
Source code in invert/benchmark/datasets.py
def create_datasets() -> dict[str, DatasetConfig]:
    return dict(BENCHMARK_DATASETS)

Visualization

invert.benchmark.visualize_results

visualize_results(
    results_path_or_data: Union[
        str, Path, list[BenchmarkResult]
    ],
    metrics: Optional[list[str]] = None,
    save_path: Optional[Union[str, Path]] = None,
) -> list[plt.Figure]
Source code in invert/benchmark/visualize.py
def visualize_results(
    results_path_or_data: Union[str, Path, list[BenchmarkResult]],
    metrics: Optional[list[str]] = None,
    save_path: Optional[Union[str, Path]] = None,
) -> list[plt.Figure]:
    if isinstance(results_path_or_data, (str, Path)):
        path = Path(results_path_or_data)
        data = json.loads(path.read_text())
        results = [BenchmarkResult(**r) for r in data["results"]]
    else:
        results = results_path_or_data

    if metrics is None:
        metrics = list(METRIC_LABELS.keys())

    datasets = sorted(set(r.dataset_name for r in results))
    solvers = sorted(set(r.solver_name for r in results))

    lookup: dict[tuple[str, str], BenchmarkResult] = {}
    for r in results:
        lookup[(r.dataset_name, r.solver_name)] = r

    # Sort solvers by category for visual grouping
    solvers.sort(key=lambda s: (_solver_to_category(s), s))

    # Build color map: solvers in the same category share a base hue with
    # slight lightness variation so individual bars are distinguishable.
    solver_colors: dict[str, str] = {}
    cat_groups: dict[str, list[str]] = {}
    for s in solvers:
        cat = _solver_to_category(s)
        cat_groups.setdefault(cat, []).append(s)
    for cat, members in cat_groups.items():
        base = np.array(
            plt.matplotlib.colors.to_rgb(CATEGORY_COLORS.get(cat, "#7f7f7f"))
        )
        n = len(members)
        for i, s in enumerate(members):
            # vary lightness: blend toward white for later members
            t = 0.15 * (i / max(n - 1, 1))  # 0 to 0.15
            solver_colors[s] = tuple((base * (1 - t) + t).tolist())  # type: ignore[assignment]

    n_solvers = len(solvers)
    n_datasets = len(datasets)
    fig_width = max(10, 1.0 * n_solvers * n_datasets + 2)
    fig_width = min(fig_width, 40)
    bar_width = min(0.8 / n_solvers, 0.15)

    figures = []
    for metric in metrics:
        fig, ax = plt.subplots(figsize=(fig_width, 6))
        x = np.arange(n_datasets)

        for j, solver in enumerate(solvers):
            means = []
            stds = []
            for ds in datasets:
                entry = lookup.get((ds, solver))
                if entry and metric in entry.metrics:
                    means.append(entry.metrics[metric].mean)
                    stds.append(entry.metrics[metric].std)
                else:
                    means.append(0.0)
                    stds.append(0.0)
            offset = (j - n_solvers / 2 + 0.5) * bar_width
            ax.bar(
                x + offset,
                means,
                bar_width,
                yerr=stds,
                capsize=2,
                color=solver_colors[solver],
                edgecolor="white",
                linewidth=0.3,
                label=solver,
            )

        ax.set_xlabel("Dataset")
        ax.set_ylabel(METRIC_LABELS.get(metric, metric))
        ax.set_title(METRIC_LABELS.get(metric, metric))
        ax.set_xticks(x)
        ax.set_xticklabels(datasets, rotation=15, ha="right")

        # Build legend grouped by category, placed below the plot
        handles, labels = ax.get_legend_handles_labels()
        label_to_handle = dict(zip(labels, handles))

        legend_handles = []
        legend_labels = []
        for cat, members in cat_groups.items():
            # Category header as invisible patch
            legend_handles.append(
                plt.matplotlib.patches.Patch(
                    facecolor="none",
                    edgecolor="none",
                )
            )
            legend_labels.append(f"$\\bf{{{cat.replace('_', ' ')}}}$")
            for s in members:
                if s in label_to_handle:
                    legend_handles.append(label_to_handle[s])
                    legend_labels.append(s)

        ncol = max(1, n_solvers // 8)
        ax.legend(
            legend_handles,
            legend_labels,
            loc="upper center",
            bbox_to_anchor=(0.5, -0.12),
            ncol=ncol,
            fontsize="small",
            frameon=False,
            columnspacing=1.0,
            handletextpad=0.4,
        )
        fig.tight_layout()
        fig.subplots_adjust(bottom=0.3)
        figures.append(fig)

        if save_path:
            sp = Path(save_path)
            sp.mkdir(parents=True, exist_ok=True)
            fig.savefig(sp / f"{metric}.png", dpi=150, bbox_inches="tight")

    return figures

Solver Resolution

invert.benchmark.resolve_solvers

resolve_solvers(
    solvers: list[str] | None = None,
    categories: list[str] | None = None,
    exclude: list[str] | None = None,
) -> list[str]

Resolve a list of solver names from explicit names and/or categories.

Parameters:

Name Type Description Default
solvers list of str

Explicit solver short names (e.g. ["MNE", "LCMV"]).

None
categories list of str

Category names to include (e.g. ["beamformer", "loreta"]). Use "all" to include every registered (non-neural-net) solver.

None
exclude list of str

Solver names to exclude from the result.

None

Returns:

Type Description
list of str

Deduplicated, order-preserved list of solver names.

Source code in invert/benchmark/runner.py
def resolve_solvers(
    solvers: list[str] | None = None,
    categories: list[str] | None = None,
    exclude: list[str] | None = None,
) -> list[str]:
    """Resolve a list of solver names from explicit names and/or categories.

    Parameters
    ----------
    solvers : list of str, optional
        Explicit solver short names (e.g. ``["MNE", "LCMV"]``).
    categories : list of str, optional
        Category names to include (e.g. ``["beamformer", "loreta"]``).
        Use ``"all"`` to include every registered (non-neural-net) solver.
    exclude : list of str, optional
        Solver names to exclude from the result.

    Returns
    -------
    list of str
        Deduplicated, order-preserved list of solver names.
    """
    result: list[str] = []
    seen: set[str] = set()
    exclude_set = set(exclude) if exclude else set()

    if categories:
        for cat in categories:
            if cat == "all":
                names = list(_SOLVER_REGISTRY.keys())
            elif cat in SOLVER_CATEGORIES:
                names = SOLVER_CATEGORIES[cat]
            else:
                raise ValueError(
                    f"Unknown category {cat!r}. "
                    f"Available: {sorted(SOLVER_CATEGORIES)} or 'all'"
                )
            for n in names:
                if n not in seen and n not in exclude_set:
                    seen.add(n)
                    result.append(n)

    if solvers:
        for n in solvers:
            if n not in _SOLVER_REGISTRY:
                raise ValueError(
                    f"Unknown solver {n!r}. Available: {sorted(_SOLVER_REGISTRY)}"
                )
            if n not in seen and n not in exclude_set:
                seen.add(n)
                result.append(n)

    return result