File size: 1,665 Bytes
dadf189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from itertools import combinations

import numpy as np

try:
    from scipy.stats import ks_2samp
except Exception:  # pragma: no cover
    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:
            # Fallback approximation using ECDF max difference.
            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])