from __future__ import annotations from typing import Iterable import cv2 import numpy as np import torch from data.degradation import DegradationPipeline from models.concept_head import ConceptHead def _rankdata(x: np.ndarray) -> np.ndarray: order = np.argsort(x) ranks = np.empty_like(order, dtype=np.float64) ranks[order] = np.arange(len(x), dtype=np.float64) return ranks def _spearman(x: np.ndarray, y: np.ndarray) -> float: if len(x) < 2 or len(y) < 2: return 0.0 rx = _rankdata(x) ry = _rankdata(y) return float(np.corrcoef(rx, ry)[0, 1]) @torch.no_grad() def compute_crosstalk_matrix( model: torch.nn.Module, degradation_pipeline: DegradationPipeline, test_images: Iterable[np.ndarray], device: str = "cpu", ) -> list[dict[str, float | str]]: """Return row-wise crosstalk values as list of dicts. Each row corresponds to one degradation type and contains Spearman correlation with all concept outputs. """ model.eval() deg_types = ["blur", "noise", "jpeg", "occlusion", "dry_skin", "wet_press"] rows: list[dict[str, float | str]] = [] to_tensor = lambda img: torch.from_numpy(img.astype(np.float32) / 255.0).unsqueeze(0).unsqueeze(0) for deg_type in deg_types: severity_vals: list[float] = [] concept_vals: list[np.ndarray] = [] for image in test_images: if image.ndim == 3: image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) for level in DegradationPipeline.LEVELS: # Fix: seed np.random per level so occlusion block lands at a # consistent position across severity levels. Without this, each # level draws a random block position → Spearman ρ is computed # over randomly-placed blocks of increasing size, not a coherent # severity sweep → sign of ρ is unreliable for occlusion. np.random.seed(level) degraded = degradation_pipeline.apply(image, deg_type, level) x = to_tensor(degraded).to(device) outputs = model(x) concepts = outputs["concepts"].squeeze(0).detach().cpu().numpy() concept_vals.append(concepts) severity_vals.append(float(level)) if not concept_vals: continue concept_arr = np.stack(concept_vals, axis=0) sev_arr = np.asarray(severity_vals, dtype=np.float64) row: dict[str, float | str] = {"degradation": deg_type} for idx, cname in enumerate(ConceptHead.CONCEPT_NAMES): row[cname] = _spearman(sev_arr, concept_arr[:, idx]) rows.append(row) return rows