| from __future__ import annotations |
|
|
| from itertools import combinations |
|
|
| import numpy as np |
|
|
| try: |
| from scipy.stats import ks_2samp |
| except Exception: |
| ks_2samp = None |
|
|
|
|
| def sensor_ks_test(scores_by_sensor: dict[str, np.ndarray]) -> list[dict[str, float | str]]: |
| """Pairwise two-sample KS test across sensors.""" |
|
|
| rows: list[dict[str, float | str]] = [] |
| for s1, s2 in combinations(sorted(scores_by_sensor.keys()), 2): |
| a = np.asarray(scores_by_sensor[s1], dtype=np.float64) |
| b = np.asarray(scores_by_sensor[s2], dtype=np.float64) |
| if len(a) == 0 or len(b) == 0: |
| continue |
|
|
| if ks_2samp is not None: |
| stat, pval = ks_2samp(a, b) |
| else: |
| |
| xa = np.sort(a) |
| xb = np.sort(b) |
| grid = np.unique(np.concatenate([xa, xb])) |
| cdfa = np.searchsorted(xa, grid, side="right") / len(xa) |
| cdfb = np.searchsorted(xb, grid, side="right") / len(xb) |
| stat = float(np.max(np.abs(cdfa - cdfb))) |
| pval = float("nan") |
|
|
| rows.append( |
| { |
| "sensor_a": s1, |
| "sensor_b": s2, |
| "ks_stat": float(stat), |
| "p_value": float(pval), |
| } |
| ) |
|
|
| return rows |
|
|
|
|
| def cross_sensor_correlation(paired_scores: list[tuple[float, float]]) -> float: |
| """Pearson correlation over matched cross-sensor quality pairs.""" |
|
|
| if len(paired_scores) < 2: |
| return 0.0 |
| arr = np.asarray(paired_scores, dtype=np.float64) |
| return float(np.corrcoef(arr[:, 0], arr[:, 1])[0, 1]) |
|
|