"""세션 단위 대응 표본 통계 (성능평가확인서: Wilcoxon signed-rank, 부트스트랩 10,000회 95% 신뢰구간). Wilcoxon signed-rank (양측) - 차이 d = 개발 − 베이스라인. 차이가 0인 세션은 뺀다 (wilcox 방식) - |d| 의 순위를 매기고 동순위는 평균 순위 - 동순위가 없고 n ≤ EXACT_MAX_N 이면 정확 분포, 아니면 정규근사(동순위 보정, 연속성 보정) 부트스트랩 - 세션을 복원 추출해 개선율 = (개발 평균 − 베이스라인 평균) ÷ 베이스라인 평균 × 100 을 반복 계산하고 백분위 구간을 낸다 """ import math import random from dataclasses import dataclass from typing import Optional EXACT_MAX_N = 25 @dataclass(frozen=True) class WilcoxonResult: n: int # 차이가 0이 아닌 세션 수 w_plus: float w_minus: float p_value: float method: str # "exact" | "normal" | "none" def _ranks(values: list[float]) -> list[float]: order = sorted(range(len(values)), key=lambda i: values[i]) ranks = [0.0] * len(values) i = 0 while i < len(order): j = i while j + 1 < len(order) and values[order[j + 1]] == values[order[i]]: j += 1 avg = (i + j) / 2 + 1 for k in range(i, j + 1): ranks[order[k]] = avg i = j + 1 return ranks def _exact_p(n: int, w: float) -> float: """순위 1..n 의 부분집합 합이 w 이하인 경우의 수로 양측 p.""" limit = int(math.floor(w)) counts = [0] * (limit + 1) counts[0] = 1 for r in range(1, n + 1): for s in range(limit, r - 1, -1): counts[s] += counts[s - r] return min(1.0, 2 * sum(counts) / 2 ** n) def wilcoxon(baseline: list[float], developed: list[float]) -> WilcoxonResult: if len(baseline) != len(developed): raise ValueError("baseline 과 developed 의 세션 수가 다릅니다") diffs = [d - b for b, d in zip(baseline, developed) if d - b != 0] n = len(diffs) if n == 0: return WilcoxonResult(0, 0.0, 0.0, 1.0, "none") abs_d = [abs(d) for d in diffs] ranks = _ranks(abs_d) w_plus = sum(r for r, d in zip(ranks, diffs) if d > 0) w_minus = sum(r for r, d in zip(ranks, diffs) if d < 0) has_ties = len(set(abs_d)) < n if not has_ties and n <= EXACT_MAX_N: return WilcoxonResult(n, w_plus, w_minus, _exact_p(n, min(w_plus, w_minus)), "exact") mean = n * (n + 1) / 4 tie_sizes = [abs_d.count(v) for v in set(abs_d)] var = n * (n + 1) * (2 * n + 1) / 24 - sum(t ** 3 - t for t in tie_sizes) / 48 if var <= 0: return WilcoxonResult(n, w_plus, w_minus, 1.0, "normal") diff = w_plus - mean z = (abs(diff) - 0.5) / math.sqrt(var) if abs(diff) >= 0.5 else 0.0 p = math.erfc(z / math.sqrt(2)) return WilcoxonResult(n, w_plus, w_minus, min(1.0, p), "normal") def improvement_pct(baseline_mean: float, developed_mean: float) -> Optional[float]: if baseline_mean == 0: return None return (developed_mean - baseline_mean) / baseline_mean * 100 def bootstrap_improvement_ci(baseline: list[float], developed: list[float], iterations: int = 10_000, confidence: float = 0.95, seed: int = 0) -> Optional[tuple[float, float]]: """세션 복원 추출 부트스트랩의 개선율(%) 백분위 신뢰구간. 계산할 수 없으면 None.""" if len(baseline) != len(developed): raise ValueError("baseline 과 developed 의 세션 수가 다릅니다") n = len(baseline) if n == 0: return None rng = random.Random(seed) values = [] for _ in range(iterations): idx = [rng.randrange(n) for _ in range(n)] b = sum(baseline[i] for i in idx) / n d = sum(developed[i] for i in idx) / n pct = improvement_pct(b, d) if pct is not None: values.append(pct) if not values: return None values.sort() alpha = (1 - confidence) / 2 lo = values[int(math.floor(alpha * (len(values) - 1)))] hi = values[int(math.ceil((1 - alpha) * (len(values) - 1)))] return lo, hi