|
| 1 | +"""Diagnose divergences between bioimage-cpp and nifty agglomeration policies. |
| 2 | +
|
| 3 | +Targeted at the cases where the benchmark sweep showed ARI < 0.90: |
| 4 | +
|
| 5 | +* mala on A/B/C small and C medium, |
| 6 | +* edge_weighted on C medium, |
| 7 | +* gasp_max on A/B small. |
| 8 | +
|
| 9 | +For each case, run both implementations, compare partitions, and (for the |
| 10 | +hypothesised root cause) print enough state to confirm or deny it. |
| 11 | +""" |
| 12 | + |
| 13 | +from __future__ import annotations |
| 14 | + |
| 15 | +import argparse |
| 16 | +import numpy as np |
| 17 | + |
| 18 | +import bioimage_cpp as bic |
| 19 | + |
| 20 | +from _compatibility import load_problem |
| 21 | + |
| 22 | + |
| 23 | +def _ari(a: np.ndarray, b: np.ndarray) -> float: |
| 24 | + try: |
| 25 | + from sklearn.metrics import adjusted_rand_score |
| 26 | + return float(adjusted_rand_score(a, b)) |
| 27 | + except ImportError: |
| 28 | + return float("nan") |
| 29 | + |
| 30 | + |
| 31 | +def _cluster_sizes(labels: np.ndarray, top: int = 8) -> str: |
| 32 | + _, counts = np.unique(labels, return_counts=True) |
| 33 | + counts = np.sort(counts)[::-1] |
| 34 | + head = counts[:top].tolist() |
| 35 | + return f"n_clusters={len(counts)} top{top}={head} max={int(counts[0])} median={int(np.median(counts))}" |
| 36 | + |
| 37 | + |
| 38 | +def diagnose_mala(sample: str, size: str) -> None: |
| 39 | + print(f"\n=== MALA sample={sample} size={size} ===") |
| 40 | + bic_graph, nifty_graph, indicators, _, _ = load_problem(sample, size, timeout=120.0) |
| 41 | + n = int(bic_graph.number_of_nodes) |
| 42 | + e = int(bic_graph.number_of_edges) |
| 43 | + print(f" nodes={n} edges={e}") |
| 44 | + |
| 45 | + bic_labels = bic.graph.agglomeration.MalaClusterPolicy( |
| 46 | + num_bins=40, bin_min=0.0, bin_max=1.0, |
| 47 | + num_clusters_stop=1000, threshold=0.5, |
| 48 | + ).optimize(bic_graph, indicators) |
| 49 | + |
| 50 | + import nifty.graph.agglo as nagglo |
| 51 | + policy = nagglo.malaClusterPolicy( |
| 52 | + graph=nifty_graph, |
| 53 | + edgeIndicators=indicators.astype(np.float32), |
| 54 | + nodeSizes=np.ones(n, dtype=np.float32), |
| 55 | + edgeSizes=np.ones(e, dtype=np.float32), |
| 56 | + threshold=0.5, numberOfNodesStop=1000, |
| 57 | + ) |
| 58 | + clustering = nagglo.agglomerativeClustering(policy) |
| 59 | + clustering.run() |
| 60 | + nifty_labels = np.asarray(clustering.result(), dtype=np.uint64) |
| 61 | + |
| 62 | + print(f" bic : {_cluster_sizes(bic_labels)}") |
| 63 | + print(f" nifty : {_cluster_sizes(nifty_labels)}") |
| 64 | + print(f" ARI : {_ari(bic_labels, nifty_labels):.4f}") |
| 65 | + # Sample a handful of indicators near 0.5 — the threshold — to highlight |
| 66 | + # how bin-center vs interpolated median changes the stop decision. |
| 67 | + mid = indicators[np.abs(indicators - 0.5) < 0.1] |
| 68 | + print(f" #indicators within 0.1 of threshold=0.5: {len(mid)} " |
| 69 | + f"(out of {len(indicators)})") |
| 70 | + |
| 71 | + |
| 72 | +def diagnose_edge_weighted(sample: str, size: str) -> None: |
| 73 | + print(f"\n=== EDGE_WEIGHTED sample={sample} size={size} ===") |
| 74 | + bic_graph, nifty_graph, indicators, _, _ = load_problem(sample, size, timeout=120.0) |
| 75 | + n = int(bic_graph.number_of_nodes) |
| 76 | + e = int(bic_graph.number_of_edges) |
| 77 | + print(f" nodes={n} edges={e}") |
| 78 | + |
| 79 | + edge_sizes = np.ones(e, dtype=np.float64) |
| 80 | + node_sizes = np.ones(n, dtype=np.float64) |
| 81 | + |
| 82 | + bic_labels = bic.graph.agglomeration.EdgeWeightedClusterPolicy( |
| 83 | + num_clusters_stop=1000, size_regularizer=0.5, |
| 84 | + ).optimize(bic_graph, indicators, edge_sizes=edge_sizes, node_sizes=node_sizes) |
| 85 | + |
| 86 | + import nifty.graph.agglo as nagglo |
| 87 | + policy = nagglo.edgeWeightedClusterPolicy( |
| 88 | + graph=nifty_graph, |
| 89 | + edgeIndicators=indicators.astype(np.float32), |
| 90 | + edgeSizes=edge_sizes.astype(np.float32), |
| 91 | + nodeSizes=node_sizes.astype(np.float32), |
| 92 | + numberOfNodesStop=1000, sizeRegularizer=0.5, |
| 93 | + ) |
| 94 | + clustering = nagglo.agglomerativeClustering(policy) |
| 95 | + clustering.run() |
| 96 | + nifty_labels = np.asarray(clustering.result(), dtype=np.uint64) |
| 97 | + |
| 98 | + print(f" bic : {_cluster_sizes(bic_labels)}") |
| 99 | + print(f" nifty : {_cluster_sizes(nifty_labels)}") |
| 100 | + print(f" ARI : {_ari(bic_labels, nifty_labels):.4f}") |
| 101 | + |
| 102 | + # How many edges share the smallest-bucket priority? (tie-breaking |
| 103 | + # signal: large equal-priority cohorts let the two impls diverge.) |
| 104 | + p = np.round(indicators, 6) |
| 105 | + _, counts = np.unique(p, return_counts=True) |
| 106 | + top = np.sort(counts)[::-1][:5].tolist() |
| 107 | + print(f" unique-priorities up to 6 dp: {len(counts)} top-5 counts: {top}") |
| 108 | + |
| 109 | + |
| 110 | +def diagnose_gasp_max(sample: str, size: str) -> None: |
| 111 | + print(f"\n=== GASP max sample={sample} size={size} ===") |
| 112 | + bic_graph, nifty_graph, _, signed_weights, _ = load_problem(sample, size, timeout=120.0) |
| 113 | + n = int(bic_graph.number_of_nodes) |
| 114 | + e = int(bic_graph.number_of_edges) |
| 115 | + print(f" nodes={n} edges={e}") |
| 116 | + print(f" signed_weights: min={signed_weights.min():.3f} max={signed_weights.max():.3f} " |
| 117 | + f"positive_fraction={(signed_weights > 0).mean():.3f}") |
| 118 | + |
| 119 | + edge_sizes = np.ones(e, dtype=np.float64) |
| 120 | + |
| 121 | + bic_labels = bic.graph.agglomeration.GaspClusterPolicy( |
| 122 | + num_clusters_stop=1000, linkage="max", |
| 123 | + ).optimize(bic_graph, signed_weights, edge_sizes=edge_sizes) |
| 124 | + |
| 125 | + import nifty.graph.agglo as nagglo |
| 126 | + policy = nagglo.gaspClusterPolicy( |
| 127 | + graph=nifty_graph, |
| 128 | + signedWeights=signed_weights.astype(np.float64), |
| 129 | + isMergeEdge=np.ones(e, dtype=np.uint8), |
| 130 | + edgeSizes=edge_sizes.astype(np.float64), |
| 131 | + nodeSizes=np.ones(n, dtype=np.float64), |
| 132 | + updateRule0=nagglo.MaxSettings(), |
| 133 | + numberOfNodesStop=1000, |
| 134 | + ) |
| 135 | + clustering = nagglo.agglomerativeClustering(policy) |
| 136 | + clustering.run() |
| 137 | + nifty_labels = np.asarray(clustering.result(), dtype=np.uint64) |
| 138 | + |
| 139 | + print(f" bic : {_cluster_sizes(bic_labels)}") |
| 140 | + print(f" nifty : {_cluster_sizes(nifty_labels)}") |
| 141 | + print(f" ARI : {_ari(bic_labels, nifty_labels):.4f}") |
| 142 | + |
| 143 | + |
| 144 | +def main() -> None: |
| 145 | + parser = argparse.ArgumentParser(description=__doc__) |
| 146 | + parser.add_argument("--policy", choices=["mala", "edge_weighted", "gasp_max", "all"], |
| 147 | + default="all") |
| 148 | + parser.add_argument("--sample", default=None) |
| 149 | + parser.add_argument("--size", default=None) |
| 150 | + args = parser.parse_args() |
| 151 | + |
| 152 | + cases_mala = [("A", "small"), ("B", "small"), ("C", "small"), ("C", "medium")] |
| 153 | + cases_ew = [("C", "medium")] |
| 154 | + cases_gm = [("A", "small"), ("B", "small")] |
| 155 | + |
| 156 | + if args.sample and args.size: |
| 157 | + cases_mala = [(args.sample, args.size)] |
| 158 | + cases_ew = [(args.sample, args.size)] |
| 159 | + cases_gm = [(args.sample, args.size)] |
| 160 | + |
| 161 | + if args.policy in ("mala", "all"): |
| 162 | + for s, z in cases_mala: |
| 163 | + diagnose_mala(s, z) |
| 164 | + if args.policy in ("edge_weighted", "all"): |
| 165 | + for s, z in cases_ew: |
| 166 | + diagnose_edge_weighted(s, z) |
| 167 | + if args.policy in ("gasp_max", "all"): |
| 168 | + for s, z in cases_gm: |
| 169 | + diagnose_gasp_max(s, z) |
| 170 | + |
| 171 | + |
| 172 | +if __name__ == "__main__": |
| 173 | + main() |
0 commit comments