|
| 1 | +"""Benchmark scaffolding for comparing bioimage-cpp agglomeration policies |
| 2 | +against the corresponding ``nifty.graph.agglo`` implementations. |
| 3 | +
|
| 4 | +Loads the external multicut problem (a generic edge list + costs) and |
| 5 | +reinterprets the costs as boundary indicators (after a sigmoid) so the |
| 6 | +policies have something realistic to chew on. Reports median runtime over |
| 7 | +``--repeats`` invocations and partition agreement (variation of information |
| 8 | +and adjusted Rand index) between the two implementations. |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +import argparse |
| 14 | +from statistics import median |
| 15 | +from time import perf_counter |
| 16 | +from typing import Callable |
| 17 | + |
| 18 | +import numpy as np |
| 19 | + |
| 20 | + |
| 21 | +def parser(description: str) -> argparse.ArgumentParser: |
| 22 | + arg_parser = argparse.ArgumentParser(description=description) |
| 23 | + arg_parser.add_argument( |
| 24 | + "--sample", |
| 25 | + default="A", |
| 26 | + choices=["A", "B", "C"], |
| 27 | + help="Multicut problem sample to load.", |
| 28 | + ) |
| 29 | + arg_parser.add_argument( |
| 30 | + "--size", |
| 31 | + default="small", |
| 32 | + choices=["small", "medium"], |
| 33 | + help="Multicut problem size to load (small ~ 60k nodes, medium ~ 700k).", |
| 34 | + ) |
| 35 | + arg_parser.add_argument( |
| 36 | + "--repeats", |
| 37 | + type=int, |
| 38 | + default=3, |
| 39 | + help="Number of timed repeats per implementation.", |
| 40 | + ) |
| 41 | + arg_parser.add_argument( |
| 42 | + "--num-clusters-stop", |
| 43 | + type=int, |
| 44 | + default=200, |
| 45 | + help="Stop when this many clusters remain (must be > 1 to keep both " |
| 46 | + "implementations from collapsing the whole graph).", |
| 47 | + ) |
| 48 | + arg_parser.add_argument( |
| 49 | + "--size-regularizer", |
| 50 | + type=float, |
| 51 | + default=0.5, |
| 52 | + help="Size regulariser exponent for the edge-weighted policies.", |
| 53 | + ) |
| 54 | + arg_parser.add_argument( |
| 55 | + "--threshold", |
| 56 | + type=float, |
| 57 | + default=0.5, |
| 58 | + help="Threshold for the MALA policy.", |
| 59 | + ) |
| 60 | + arg_parser.add_argument( |
| 61 | + "--timeout", |
| 62 | + type=float, |
| 63 | + default=120.0, |
| 64 | + help="Download timeout in seconds if the external problem is not cached.", |
| 65 | + ) |
| 66 | + return arg_parser |
| 67 | + |
| 68 | + |
| 69 | +def load_problem(sample: str = "A", size: str = "small", *, timeout: float = 120.0): |
| 70 | + """Load a multicut problem and derive indicator / weight arrays. |
| 71 | +
|
| 72 | + Returns ``(bic_graph, nifty_graph, indicators, signed_weights, uv_ids)`` |
| 73 | + where ``indicators`` are in ``[0, 1]`` (boundary strength) and |
| 74 | + ``signed_weights`` keeps the original multicut sign (positive = attract). |
| 75 | + """ |
| 76 | + import bioimage_cpp as bic |
| 77 | + import nifty.graph as ng |
| 78 | + |
| 79 | + uv_ids, costs = bic.graph.multicut.load_multicut_problem_data( |
| 80 | + sample, size, timeout=timeout |
| 81 | + ) |
| 82 | + n_nodes = int(uv_ids.max()) + 1 |
| 83 | + |
| 84 | + bic_graph = bic.graph.UndirectedGraph.from_edges(n_nodes, uv_ids) |
| 85 | + nifty_graph = ng.undirectedGraph(n_nodes) |
| 86 | + nifty_graph.insertEdges(uv_ids) |
| 87 | + |
| 88 | + # Multicut costs are signed log-odds (positive = attractive, large |
| 89 | + # magnitude = certain). Map to a boundary-strength indicator in [0, 1] |
| 90 | + # via a sigmoid of the negated cost so 'large positive cost' becomes |
| 91 | + # 'small indicator' (weak boundary), matching nifty's convention. |
| 92 | + indicators = 1.0 / (1.0 + np.exp(np.asarray(costs, dtype=np.float64))) |
| 93 | + indicators = np.ascontiguousarray(indicators.astype(np.float64)) |
| 94 | + # Signed weights for GASP: keep the multicut sign directly. |
| 95 | + signed_weights = np.ascontiguousarray(np.asarray(costs, dtype=np.float64)) |
| 96 | + return bic_graph, nifty_graph, indicators, signed_weights, uv_ids |
| 97 | + |
| 98 | + |
| 99 | +def time_call(function: Callable[[], np.ndarray], repeats: int): |
| 100 | + timings = [] |
| 101 | + result = None |
| 102 | + for _ in range(repeats): |
| 103 | + start = perf_counter() |
| 104 | + result = function() |
| 105 | + timings.append(perf_counter() - start) |
| 106 | + assert result is not None |
| 107 | + return timings, result |
| 108 | + |
| 109 | + |
| 110 | +def variation_of_information(labels_a: np.ndarray, labels_b: np.ndarray) -> float: |
| 111 | + labels_a = np.asarray(labels_a).astype(np.int64) |
| 112 | + labels_b = np.asarray(labels_b).astype(np.int64) |
| 113 | + n = labels_a.size |
| 114 | + if n == 0: |
| 115 | + return 0.0 |
| 116 | + _, a_inv, a_counts = np.unique(labels_a, return_inverse=True, return_counts=True) |
| 117 | + _, b_inv, b_counts = np.unique(labels_b, return_inverse=True, return_counts=True) |
| 118 | + pa = a_counts / n |
| 119 | + pb = b_counts / n |
| 120 | + contingency = np.zeros((a_counts.size, b_counts.size), dtype=np.float64) |
| 121 | + np.add.at(contingency, (a_inv, b_inv), 1.0) |
| 122 | + contingency /= n |
| 123 | + with np.errstate(divide="ignore", invalid="ignore"): |
| 124 | + ha = -np.sum(pa * np.log(pa, where=pa > 0)) |
| 125 | + hb = -np.sum(pb * np.log(pb, where=pb > 0)) |
| 126 | + joint = -np.sum( |
| 127 | + contingency * np.log(contingency, where=contingency > 0) |
| 128 | + ) |
| 129 | + mutual_info = ha + hb - joint |
| 130 | + return float(2.0 * joint - ha - hb - 2.0 * mutual_info + ha + hb) |
| 131 | + |
| 132 | + |
| 133 | +def adjusted_rand(labels_a: np.ndarray, labels_b: np.ndarray) -> float: |
| 134 | + try: |
| 135 | + from sklearn.metrics import adjusted_rand_score |
| 136 | + except ImportError: |
| 137 | + return float("nan") |
| 138 | + return float(adjusted_rand_score(labels_a, labels_b)) |
| 139 | + |
| 140 | + |
| 141 | +def report( |
| 142 | + name: str, |
| 143 | + bic_timings, |
| 144 | + nifty_timings, |
| 145 | + bic_labels, |
| 146 | + nifty_labels, |
| 147 | + n_nodes, |
| 148 | + n_edges, |
| 149 | + *, |
| 150 | + sample: str | None = None, |
| 151 | + size: str | None = None, |
| 152 | +): |
| 153 | + vi = variation_of_information(bic_labels, nifty_labels) |
| 154 | + ari = adjusted_rand(bic_labels, nifty_labels) |
| 155 | + bic_clusters = int(np.unique(bic_labels).size) |
| 156 | + nifty_clusters = int(np.unique(nifty_labels).size) |
| 157 | + bic_med = median(bic_timings) |
| 158 | + nifty_med = median(nifty_timings) |
| 159 | + speedup = nifty_med / bic_med if bic_med > 0 else float("nan") |
| 160 | + suffix = "" |
| 161 | + if sample is not None and size is not None: |
| 162 | + suffix = f" [sample {sample} / {size}]" |
| 163 | + print(f"policy: {name}{suffix}") |
| 164 | + print(f"nodes: {n_nodes}, edges: {n_edges}") |
| 165 | + print(f"bioimage_cpp clusters: {bic_clusters}") |
| 166 | + print(f"nifty clusters: {nifty_clusters}") |
| 167 | + print(f"bioimage_cpp median runtime [s]: {bic_med:.6f}") |
| 168 | + print(f"nifty median runtime [s]: {nifty_med:.6f}") |
| 169 | + print(f"speedup (nifty / bioimage_cpp): {speedup:.2f}x") |
| 170 | + print(f"variation of information: {vi:.6f}") |
| 171 | + print(f"adjusted Rand index: {ari:.6f}") |
0 commit comments