evalsuite-python 1.2.1__py3-none-any.whl → 1.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- evalsuite/__init__.py +105 -0
- evalsuite/agreement.py +405 -0
- evalsuite/bayes.py +325 -0
- evalsuite/calibration.py +52 -11
- evalsuite/drift.py +291 -0
- evalsuite/forecasting.py +383 -0
- evalsuite/multilabel.py +448 -0
- evalsuite/recalibration.py +265 -0
- evalsuite/stats/intervals.py +1 -1
- evalsuite/version.py +1 -1
- {evalsuite_python-1.2.1.dist-info → evalsuite_python-1.3.0.dist-info}/METADATA +79 -3
- {evalsuite_python-1.2.1.dist-info → evalsuite_python-1.3.0.dist-info}/RECORD +16 -10
- {evalsuite_python-1.2.1.dist-info → evalsuite_python-1.3.0.dist-info}/WHEEL +0 -0
- {evalsuite_python-1.2.1.dist-info → evalsuite_python-1.3.0.dist-info}/entry_points.txt +0 -0
- {evalsuite_python-1.2.1.dist-info → evalsuite_python-1.3.0.dist-info}/licenses/LICENSE +0 -0
- {evalsuite_python-1.2.1.dist-info → evalsuite_python-1.3.0.dist-info}/licenses/LICENSE-APACHE +0 -0
evalsuite/__init__.py
CHANGED
|
@@ -30,9 +30,22 @@ if TYPE_CHECKING: # static analysers and IDEs see the full eager API
|
|
|
30
30
|
text,
|
|
31
31
|
vision,
|
|
32
32
|
)
|
|
33
|
+
from .agreement import (
|
|
34
|
+
BlandAltman,
|
|
35
|
+
ICCForm,
|
|
36
|
+
ICCResult,
|
|
37
|
+
bland_altman,
|
|
38
|
+
icc,
|
|
39
|
+
lins_ccc,
|
|
40
|
+
)
|
|
33
41
|
from .api import (
|
|
34
42
|
evaluate,
|
|
35
43
|
)
|
|
44
|
+
from .bayes import (
|
|
45
|
+
BayesComparison,
|
|
46
|
+
bayes_compare,
|
|
47
|
+
bayes_correlated_ttest,
|
|
48
|
+
)
|
|
36
49
|
from .calibration import (
|
|
37
50
|
CalibrationReport,
|
|
38
51
|
calibration_intercept,
|
|
@@ -100,10 +113,26 @@ if TYPE_CHECKING: # static analysers and IDEs see the full eager API
|
|
|
100
113
|
EvaluationResult,
|
|
101
114
|
MetricResult,
|
|
102
115
|
)
|
|
116
|
+
from .drift import (
|
|
117
|
+
DriftReport,
|
|
118
|
+
drift_report,
|
|
119
|
+
)
|
|
103
120
|
from .fairness import (
|
|
104
121
|
FairnessReport,
|
|
105
122
|
fairness_report,
|
|
106
123
|
)
|
|
124
|
+
from .forecasting import (
|
|
125
|
+
ForecastReport,
|
|
126
|
+
crps,
|
|
127
|
+
diebold_mariano,
|
|
128
|
+
forecast_report,
|
|
129
|
+
interval_coverage,
|
|
130
|
+
interval_score,
|
|
131
|
+
mase,
|
|
132
|
+
msis,
|
|
133
|
+
pinball_loss,
|
|
134
|
+
rmsse,
|
|
135
|
+
)
|
|
107
136
|
from .harness import (
|
|
108
137
|
Leaderboard,
|
|
109
138
|
leaderboard,
|
|
@@ -129,10 +158,20 @@ if TYPE_CHECKING: # static analysers and IDEs see the full eager API
|
|
|
129
158
|
ks_drift,
|
|
130
159
|
population_stability_index,
|
|
131
160
|
)
|
|
161
|
+
from .multilabel import (
|
|
162
|
+
MultilabelReport,
|
|
163
|
+
RankingReport,
|
|
164
|
+
multilabel_report,
|
|
165
|
+
ranking_report,
|
|
166
|
+
)
|
|
132
167
|
from .rag_report import (
|
|
133
168
|
RAGReport,
|
|
134
169
|
rag_report,
|
|
135
170
|
)
|
|
171
|
+
from .recalibration import (
|
|
172
|
+
Calibrator,
|
|
173
|
+
recalibrate,
|
|
174
|
+
)
|
|
136
175
|
from .regression import (
|
|
137
176
|
adjusted_r2,
|
|
138
177
|
explained_variance,
|
|
@@ -306,6 +345,45 @@ _EXPORTS: dict[str, tuple[str, ...]] = {
|
|
|
306
345
|
"EvaluationResult",
|
|
307
346
|
"MetricResult",
|
|
308
347
|
),
|
|
348
|
+
".agreement": (
|
|
349
|
+
"BlandAltman",
|
|
350
|
+
"ICCForm",
|
|
351
|
+
"ICCResult",
|
|
352
|
+
"bland_altman",
|
|
353
|
+
"icc",
|
|
354
|
+
"lins_ccc",
|
|
355
|
+
),
|
|
356
|
+
".bayes": (
|
|
357
|
+
"BayesComparison",
|
|
358
|
+
"bayes_compare",
|
|
359
|
+
"bayes_correlated_ttest",
|
|
360
|
+
),
|
|
361
|
+
".drift": (
|
|
362
|
+
"DriftReport",
|
|
363
|
+
"drift_report",
|
|
364
|
+
),
|
|
365
|
+
".forecasting": (
|
|
366
|
+
"ForecastReport",
|
|
367
|
+
"crps",
|
|
368
|
+
"diebold_mariano",
|
|
369
|
+
"forecast_report",
|
|
370
|
+
"interval_coverage",
|
|
371
|
+
"interval_score",
|
|
372
|
+
"mase",
|
|
373
|
+
"msis",
|
|
374
|
+
"pinball_loss",
|
|
375
|
+
"rmsse",
|
|
376
|
+
),
|
|
377
|
+
".multilabel": (
|
|
378
|
+
"MultilabelReport",
|
|
379
|
+
"RankingReport",
|
|
380
|
+
"multilabel_report",
|
|
381
|
+
"ranking_report",
|
|
382
|
+
),
|
|
383
|
+
".recalibration": (
|
|
384
|
+
"Calibrator",
|
|
385
|
+
"recalibrate",
|
|
386
|
+
),
|
|
309
387
|
".fairness": (
|
|
310
388
|
"FairnessReport",
|
|
311
389
|
"fairness_report",
|
|
@@ -594,16 +672,23 @@ _LAZY.update({"UpdateInfo": "._update", "check_for_update": "._update", "upgrade
|
|
|
594
672
|
__all__ = [
|
|
595
673
|
"Alert",
|
|
596
674
|
"BENCHMARKS",
|
|
675
|
+
"BayesComparison",
|
|
676
|
+
"BlandAltman",
|
|
597
677
|
"CalibrationReport",
|
|
678
|
+
"Calibrator",
|
|
598
679
|
"ClassificationReport",
|
|
599
680
|
"ComparisonResult",
|
|
600
681
|
"ConfidenceInterval",
|
|
601
682
|
"DecisionCurve",
|
|
602
683
|
"DetectionReport",
|
|
603
684
|
"DiagnosticReport",
|
|
685
|
+
"DriftReport",
|
|
604
686
|
"EvalSuiteError",
|
|
605
687
|
"EvaluationResult",
|
|
606
688
|
"FairnessReport",
|
|
689
|
+
"ForecastReport",
|
|
690
|
+
"ICCForm",
|
|
691
|
+
"ICCResult",
|
|
607
692
|
"InputValidationError",
|
|
608
693
|
"JudgeReport",
|
|
609
694
|
"Leaderboard",
|
|
@@ -611,10 +696,12 @@ __all__ = [
|
|
|
611
696
|
"MetricInputError",
|
|
612
697
|
"MetricResult",
|
|
613
698
|
"Monitor",
|
|
699
|
+
"MultilabelReport",
|
|
614
700
|
"OptionalDependencyError",
|
|
615
701
|
"PII_PATTERNS",
|
|
616
702
|
"PYTHON_KEYWORDS",
|
|
617
703
|
"RAGReport",
|
|
704
|
+
"RankingReport",
|
|
618
705
|
"ReportCard",
|
|
619
706
|
"RubricReport",
|
|
620
707
|
"SampleSize",
|
|
@@ -645,9 +732,12 @@ __all__ = [
|
|
|
645
732
|
"average_precision_detection",
|
|
646
733
|
"average_surface_distance",
|
|
647
734
|
"balanced_accuracy",
|
|
735
|
+
"bayes_compare",
|
|
736
|
+
"bayes_correlated_ttest",
|
|
648
737
|
"benchmark_accuracy",
|
|
649
738
|
"bertscore",
|
|
650
739
|
"bitext_mining_accuracy",
|
|
740
|
+
"bland_altman",
|
|
651
741
|
"bleu",
|
|
652
742
|
"bootstrap_ci",
|
|
653
743
|
"boundary_iou",
|
|
@@ -694,6 +784,7 @@ __all__ = [
|
|
|
694
784
|
"cross_document_consistency",
|
|
695
785
|
"cross_entropy",
|
|
696
786
|
"cross_lingual_consistency",
|
|
787
|
+
"crps",
|
|
697
788
|
"cultural_appropriateness",
|
|
698
789
|
"decision_curve",
|
|
699
790
|
"delong_test",
|
|
@@ -703,9 +794,11 @@ __all__ = [
|
|
|
703
794
|
"diagnostic_odds_ratio",
|
|
704
795
|
"diagnostic_report",
|
|
705
796
|
"dice",
|
|
797
|
+
"diebold_mariano",
|
|
706
798
|
"direct_assessment",
|
|
707
799
|
"distinct_n",
|
|
708
800
|
"distribution_shift_drop",
|
|
801
|
+
"drift_report",
|
|
709
802
|
"elo_ratings",
|
|
710
803
|
"embedding_similarity",
|
|
711
804
|
"energy_per_request",
|
|
@@ -726,6 +819,7 @@ __all__ = [
|
|
|
726
819
|
"fbeta",
|
|
727
820
|
"fisher_exact_test",
|
|
728
821
|
"fleiss_kappa",
|
|
822
|
+
"forecast_report",
|
|
729
823
|
"format_compliance",
|
|
730
824
|
"format_multiple_choice",
|
|
731
825
|
"friedman_test",
|
|
@@ -741,10 +835,13 @@ __all__ = [
|
|
|
741
835
|
"html_report",
|
|
742
836
|
"huber_loss",
|
|
743
837
|
"human_intervention_rate",
|
|
838
|
+
"icc",
|
|
744
839
|
"inference_cost",
|
|
745
840
|
"instruction_compliance_rate",
|
|
746
841
|
"instruction_retention",
|
|
747
842
|
"integrated_brier_score",
|
|
843
|
+
"interval_coverage",
|
|
844
|
+
"interval_score",
|
|
748
845
|
"invalid_tool_call_rate",
|
|
749
846
|
"invariance_violation_rate",
|
|
750
847
|
"iou",
|
|
@@ -764,6 +861,7 @@ __all__ = [
|
|
|
764
861
|
"latency_percentiles",
|
|
765
862
|
"latency_summary",
|
|
766
863
|
"leaderboard",
|
|
864
|
+
"lins_ccc",
|
|
767
865
|
"list_metrics",
|
|
768
866
|
"llmsys",
|
|
769
867
|
"load_benchmark",
|
|
@@ -775,6 +873,7 @@ __all__ = [
|
|
|
775
873
|
"majority_vote_accuracy",
|
|
776
874
|
"mann_whitney_test",
|
|
777
875
|
"mape",
|
|
876
|
+
"mase",
|
|
778
877
|
"mauve",
|
|
779
878
|
"max_error",
|
|
780
879
|
"maximum_calibration_error",
|
|
@@ -792,7 +891,9 @@ __all__ = [
|
|
|
792
891
|
"moverscore",
|
|
793
892
|
"mrr",
|
|
794
893
|
"mse",
|
|
894
|
+
"msis",
|
|
795
895
|
"msle",
|
|
896
|
+
"multilabel_report",
|
|
796
897
|
"ndcg_at_k",
|
|
797
898
|
"needle_in_haystack",
|
|
798
899
|
"net_benefit",
|
|
@@ -809,6 +910,7 @@ __all__ = [
|
|
|
809
910
|
"per_image_scores",
|
|
810
911
|
"perplexity",
|
|
811
912
|
"pii_leakage_rate",
|
|
913
|
+
"pinball_loss",
|
|
812
914
|
"pixel_accuracy",
|
|
813
915
|
"plan_adherence",
|
|
814
916
|
"plot",
|
|
@@ -829,6 +931,8 @@ __all__ = [
|
|
|
829
931
|
"r2",
|
|
830
932
|
"rae",
|
|
831
933
|
"rag_report",
|
|
934
|
+
"ranking_report",
|
|
935
|
+
"recalibrate",
|
|
832
936
|
"recall",
|
|
833
937
|
"recall_at_k",
|
|
834
938
|
"recovery_success_rate",
|
|
@@ -846,6 +950,7 @@ __all__ = [
|
|
|
846
950
|
"risk_coverage_curve",
|
|
847
951
|
"rmse",
|
|
848
952
|
"rmsle",
|
|
953
|
+
"rmsse",
|
|
849
954
|
"roc_auc",
|
|
850
955
|
"roc_auc_ci",
|
|
851
956
|
"roc_curve",
|
evalsuite/agreement.py
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
"""Agreement studies: how well raters, instruments or methods agree on the same subjects.
|
|
2
|
+
|
|
3
|
+
>>> import evalsuite as es
|
|
4
|
+
>>> icc = es.icc(ratings) # subjects × raters matrix → all six ICC forms with CIs
|
|
5
|
+
>>> icc["ICC2"].value, icc["ICC2"].low, icc["ICC2"].high
|
|
6
|
+
>>> ba = es.bland_altman(method_a, method_b) # bias, limits of agreement (with CIs), proportional bias
|
|
7
|
+
>>> ccc = es.lins_ccc(method_a, method_b) # Lin's concordance correlation with a CI
|
|
8
|
+
|
|
9
|
+
ICC forms follow Shrout & Fleiss (1979) and McGraw & Wong (1996), with the exact F-based confidence intervals
|
|
10
|
+
(ICC2 by Satterthwaite's approximation), as in pingouin and R's ``psych::ICC``. Bland–Altman limits use the
|
|
11
|
+
Bland & Altman (1999) standard errors; Lin's CCC uses the Fisher-z interval of Lin (1989).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
import math
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from typing import Any, Optional
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
|
|
23
|
+
from .core.exceptions import InputValidationError
|
|
24
|
+
|
|
25
|
+
__all__ = ["ICCResult", "ICCForm", "BlandAltman", "icc", "bland_altman", "lins_ccc"]
|
|
26
|
+
|
|
27
|
+
_ICC_DESCRIPTIONS = {
|
|
28
|
+
"ICC1": "One-way random effects, single rater (absolute agreement)",
|
|
29
|
+
"ICC2": "Two-way random effects, single rater (absolute agreement)",
|
|
30
|
+
"ICC3": "Two-way mixed effects, single rater (consistency)",
|
|
31
|
+
"ICC1k": "One-way random effects, mean of k raters",
|
|
32
|
+
"ICC2k": "Two-way random effects, mean of k raters (absolute agreement)",
|
|
33
|
+
"ICC3k": "Two-way mixed effects, mean of k raters (consistency)",
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _level(level: float) -> float:
|
|
38
|
+
if not 0 < level < 1:
|
|
39
|
+
raise InputValidationError(f"level must be in (0, 1); got {level}.")
|
|
40
|
+
return float(level)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class ICCForm:
|
|
45
|
+
"""One intraclass correlation: estimate, F test against zero and confidence interval."""
|
|
46
|
+
|
|
47
|
+
name: str
|
|
48
|
+
description: str
|
|
49
|
+
value: float
|
|
50
|
+
f: float
|
|
51
|
+
df1: float
|
|
52
|
+
df2: float
|
|
53
|
+
p_value: float
|
|
54
|
+
low: float
|
|
55
|
+
high: float
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class ICCResult:
|
|
60
|
+
"""All six ICC forms for a subjects × raters table. Index by form name (``result["ICC2"]``)."""
|
|
61
|
+
|
|
62
|
+
forms: tuple[ICCForm, ...]
|
|
63
|
+
n_subjects: int
|
|
64
|
+
n_raters: int
|
|
65
|
+
level: float
|
|
66
|
+
anova: dict[str, float] = field(default_factory=dict)
|
|
67
|
+
|
|
68
|
+
def __getitem__(self, name: str) -> ICCForm:
|
|
69
|
+
for f in self.forms:
|
|
70
|
+
if f.name.lower() == name.lower():
|
|
71
|
+
return f
|
|
72
|
+
raise KeyError(f"{name!r}; available: {', '.join(f.name for f in self.forms)}")
|
|
73
|
+
|
|
74
|
+
def summary(self, *, digits: int = 3) -> str:
|
|
75
|
+
d = digits
|
|
76
|
+
head = (
|
|
77
|
+
f"Intraclass correlation: {self.n_subjects} subjects × {self.n_raters} raters, "
|
|
78
|
+
f"{self.level * 100:g}% CIs"
|
|
79
|
+
)
|
|
80
|
+
lines = [head]
|
|
81
|
+
for f in self.forms:
|
|
82
|
+
lines.append(
|
|
83
|
+
f" {f.name:<6} {f.value:.{d}f} ({f.low:.{d}f}–{f.high:.{d}f}) "
|
|
84
|
+
f"F={f.f:.{d}f} p={f.p_value:.{d}g} {f.description}"
|
|
85
|
+
)
|
|
86
|
+
lines.append(" Koo & Li (2016): <0.5 poor, 0.5–0.75 moderate, 0.75–0.9 good, >0.9 excellent.")
|
|
87
|
+
return "\n".join(lines)
|
|
88
|
+
|
|
89
|
+
def __repr__(self) -> str:
|
|
90
|
+
return self.summary()
|
|
91
|
+
|
|
92
|
+
def to_dict(self) -> dict[str, Any]:
|
|
93
|
+
from .core.result import _json_safe
|
|
94
|
+
|
|
95
|
+
out: dict[str, Any] = _json_safe(
|
|
96
|
+
{
|
|
97
|
+
"forms": [f.__dict__ for f in self.forms],
|
|
98
|
+
"n_subjects": self.n_subjects,
|
|
99
|
+
"n_raters": self.n_raters,
|
|
100
|
+
"level": self.level,
|
|
101
|
+
"anova": self.anova,
|
|
102
|
+
}
|
|
103
|
+
)
|
|
104
|
+
return out
|
|
105
|
+
|
|
106
|
+
def to_json(self, *, indent: Optional[int] = 2) -> str:
|
|
107
|
+
return json.dumps(self.to_dict(), indent=indent)
|
|
108
|
+
|
|
109
|
+
def to_markdown(self, *, digits: int = 3) -> str:
|
|
110
|
+
d = digits
|
|
111
|
+
rows = ["| Form | ICC | CI | F | p | Meaning |", "| --- | ---: | --- | ---: | ---: | --- |"]
|
|
112
|
+
rows += [
|
|
113
|
+
f"| {f.name} | {f.value:.{d}f} | {f.low:.{d}f}–{f.high:.{d}f} | {f.f:.{d}f} | {f.p_value:.{d}g} | "
|
|
114
|
+
f"{f.description} |"
|
|
115
|
+
for f in self.forms
|
|
116
|
+
]
|
|
117
|
+
return "\n".join(rows) + "\n"
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _table(ratings: Any, subjects: Any, raters: Any) -> np.ndarray:
|
|
121
|
+
if subjects is None and raters is None:
|
|
122
|
+
try:
|
|
123
|
+
x = np.asarray(ratings, dtype=np.float64)
|
|
124
|
+
except (TypeError, ValueError) as exc:
|
|
125
|
+
raise InputValidationError("ratings must be numeric.") from exc
|
|
126
|
+
if x.ndim != 2:
|
|
127
|
+
raise InputValidationError(
|
|
128
|
+
"ratings must be a subjects × raters table (2-D), or long format with subjects= and raters=."
|
|
129
|
+
)
|
|
130
|
+
return x
|
|
131
|
+
if subjects is None or raters is None:
|
|
132
|
+
raise InputValidationError("Long format needs both subjects= and raters=.")
|
|
133
|
+
vals = np.asarray(ratings, dtype=np.float64).ravel()
|
|
134
|
+
s = np.asarray(subjects).ravel()
|
|
135
|
+
r = np.asarray(raters).ravel()
|
|
136
|
+
if not (vals.size == s.size == r.size):
|
|
137
|
+
raise InputValidationError(
|
|
138
|
+
f"ratings, subjects and raters must have the same length; got {vals.size}, {s.size} and {r.size}."
|
|
139
|
+
)
|
|
140
|
+
su, si = np.unique(s, return_inverse=True)
|
|
141
|
+
ru, ri = np.unique(r, return_inverse=True)
|
|
142
|
+
x = np.full((su.size, ru.size), np.nan)
|
|
143
|
+
seen = np.zeros_like(x, dtype=bool)
|
|
144
|
+
for a, b, v in zip(si, ri, vals):
|
|
145
|
+
if seen[a, b]:
|
|
146
|
+
raise InputValidationError(f"Subject {su[a]!r} has more than one rating from rater {ru[b]!r}.")
|
|
147
|
+
seen[a, b] = True
|
|
148
|
+
x[a, b] = v
|
|
149
|
+
return x
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def icc(
|
|
153
|
+
ratings: Any,
|
|
154
|
+
*,
|
|
155
|
+
subjects: Any = None,
|
|
156
|
+
raters: Any = None,
|
|
157
|
+
level: float = 0.95,
|
|
158
|
+
missing: str = "drop",
|
|
159
|
+
) -> ICCResult:
|
|
160
|
+
"""Intraclass correlation coefficients (all six Shrout–Fleiss forms) with F tests and confidence intervals.
|
|
161
|
+
|
|
162
|
+
``ratings`` is a subjects × raters table, or one rating per row with ``subjects=`` and ``raters=``
|
|
163
|
+
(long format). Subjects with a missing rating are dropped (``missing="drop"``) or rejected
|
|
164
|
+
(``missing="raise"``). Choose the form by design: ICC2 / ICC2k when the raters are a sample of possible raters
|
|
165
|
+
and absolute agreement matters, ICC3 / ICC3k for these fixed raters' consistency, ICC1 when each subject has
|
|
166
|
+
different raters; "k" forms describe the mean of the k ratings."""
|
|
167
|
+
from scipy import stats
|
|
168
|
+
|
|
169
|
+
lv = _level(level)
|
|
170
|
+
x = _table(ratings, subjects, raters)
|
|
171
|
+
bad = ~np.all(np.isfinite(x), axis=1)
|
|
172
|
+
if bad.any():
|
|
173
|
+
if missing != "drop":
|
|
174
|
+
raise InputValidationError(f"{int(bad.sum())} subject(s) have missing or non-finite ratings.")
|
|
175
|
+
x = x[~bad]
|
|
176
|
+
n, k = x.shape
|
|
177
|
+
if n < 2 or k < 2:
|
|
178
|
+
raise InputValidationError(f"ICC needs at least 2 complete subjects and 2 raters; got {n} × {k}.")
|
|
179
|
+
gm = x.mean()
|
|
180
|
+
ss_r = k * float(np.sum((x.mean(axis=1) - gm) ** 2))
|
|
181
|
+
ss_c = n * float(np.sum((x.mean(axis=0) - gm) ** 2))
|
|
182
|
+
ss_t = float(np.sum((x - gm) ** 2))
|
|
183
|
+
ss_e = ss_t - ss_r - ss_c
|
|
184
|
+
msr, msc = ss_r / (n - 1), ss_c / (k - 1)
|
|
185
|
+
mse = ss_e / ((n - 1) * (k - 1))
|
|
186
|
+
msw = (ss_c + ss_e) / (n * (k - 1))
|
|
187
|
+
if msr == 0 and mse == 0 and msw == 0:
|
|
188
|
+
raise InputValidationError("All ratings are identical; the ICC is undefined.")
|
|
189
|
+
a = (1 - lv) / 2
|
|
190
|
+
df1, df2_1, df2_3 = n - 1, n * (k - 1), (n - 1) * (k - 1)
|
|
191
|
+
|
|
192
|
+
def ratio(num: float, den: float) -> float:
|
|
193
|
+
if den == 0:
|
|
194
|
+
return math.inf if num > 0 else math.nan
|
|
195
|
+
return num / den
|
|
196
|
+
|
|
197
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
198
|
+
icc1 = ratio(msr - msw, msr + (k - 1) * msw)
|
|
199
|
+
icc2 = ratio(msr - mse, msr + (k - 1) * mse + k * (msc - mse) / n)
|
|
200
|
+
icc3 = ratio(msr - mse, msr + (k - 1) * mse)
|
|
201
|
+
icc1k = ratio(msr - msw, msr)
|
|
202
|
+
icc2k = ratio(msr - mse, msr + (msc - mse) / n)
|
|
203
|
+
icc3k = ratio(msr - mse, msr)
|
|
204
|
+
f1 = ratio(msr, msw)
|
|
205
|
+
f3 = ratio(msr, mse)
|
|
206
|
+
f1l = f1 / stats.f.ppf(1 - a, df1, df2_1)
|
|
207
|
+
f1u = f1 * stats.f.ppf(1 - a, df2_1, df1)
|
|
208
|
+
f3l = f3 / stats.f.ppf(1 - a, df1, df2_3)
|
|
209
|
+
f3u = f3 * stats.f.ppf(1 - a, df2_3, df1)
|
|
210
|
+
l1, u1 = (f1l - 1) / (f1l + k - 1), (f1u - 1) / (f1u + k - 1)
|
|
211
|
+
l3, u3 = (f3l - 1) / (f3l + k - 1), (f3u - 1) / (f3u + k - 1)
|
|
212
|
+
fj = ratio(msc, mse)
|
|
213
|
+
vn = (k - 1) * (n - 1) * (k * icc2 * fj + n * (1 + (k - 1) * icc2) - k * icc2) ** 2
|
|
214
|
+
vd = (n - 1) * k**2 * icc2**2 * fj**2 + (n * (1 + (k - 1) * icc2) - k * icc2) ** 2
|
|
215
|
+
v = vn / vd
|
|
216
|
+
f2u = stats.f.ppf(1 - a, n - 1, v)
|
|
217
|
+
f2l = stats.f.ppf(1 - a, v, n - 1)
|
|
218
|
+
l2 = n * (msr - f2u * mse) / (f2u * (k * msc + (k * n - k - n) * mse) + n * msr)
|
|
219
|
+
u2 = n * (f2l * msr - mse) / (k * msc + (k * n - k - n) * mse + n * f2l * msr)
|
|
220
|
+
p1 = float(stats.f.sf(f1, df1, df2_1))
|
|
221
|
+
p3 = float(stats.f.sf(f3, df1, df2_3))
|
|
222
|
+
rows = [
|
|
223
|
+
("ICC1", icc1, f1, df1, df2_1, p1, l1, u1),
|
|
224
|
+
("ICC2", icc2, f3, df1, df2_3, p3, l2, u2),
|
|
225
|
+
("ICC3", icc3, f3, df1, df2_3, p3, l3, u3),
|
|
226
|
+
("ICC1k", icc1k, f1, df1, df2_1, p1, 1 - 1 / f1l, 1 - 1 / f1u),
|
|
227
|
+
("ICC2k", icc2k, f3, df1, df2_3, p3, l2 * k / (1 + l2 * (k - 1)), u2 * k / (1 + u2 * (k - 1))),
|
|
228
|
+
("ICC3k", icc3k, f3, df1, df2_3, p3, 1 - 1 / f3l, 1 - 1 / f3u),
|
|
229
|
+
]
|
|
230
|
+
forms = tuple(
|
|
231
|
+
ICCForm(nm, _ICC_DESCRIPTIONS[nm], float(val), float(f), float(d1), float(d2), p, float(lo), float(hi))
|
|
232
|
+
for nm, val, f, d1, d2, p, lo, hi in rows
|
|
233
|
+
)
|
|
234
|
+
anova = {"ms_subjects": msr, "ms_raters": msc, "ms_error": mse, "ms_within": msw}
|
|
235
|
+
return ICCResult(forms, n, k, lv, anova)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
@dataclass(frozen=True)
|
|
239
|
+
class BlandAltman:
|
|
240
|
+
"""Bland–Altman analysis of two measurement methods on the same subjects."""
|
|
241
|
+
|
|
242
|
+
n: int
|
|
243
|
+
bias: float
|
|
244
|
+
bias_low: float
|
|
245
|
+
bias_high: float
|
|
246
|
+
sd: float
|
|
247
|
+
lower_loa: float
|
|
248
|
+
upper_loa: float
|
|
249
|
+
lower_loa_ci: tuple[float, float]
|
|
250
|
+
upper_loa_ci: tuple[float, float]
|
|
251
|
+
proportional_bias_slope: float
|
|
252
|
+
proportional_bias_p: float
|
|
253
|
+
level: float
|
|
254
|
+
loa_level: float
|
|
255
|
+
within_loa: float
|
|
256
|
+
means: np.ndarray = field(repr=False)
|
|
257
|
+
differences: np.ndarray = field(repr=False)
|
|
258
|
+
|
|
259
|
+
def summary(self, *, digits: int = 3) -> str:
|
|
260
|
+
d = digits
|
|
261
|
+
pct = f"{self.level * 100:g}%"
|
|
262
|
+
loa = f"{self.loa_level * 100:g}%"
|
|
263
|
+
return "\n".join(
|
|
264
|
+
[
|
|
265
|
+
f"Bland–Altman analysis (n={self.n}; {pct} CIs; {loa} limits of agreement)",
|
|
266
|
+
f" Bias (mean difference) {self.bias:.{d}f} ({self.bias_low:.{d}f} to {self.bias_high:.{d}f})",
|
|
267
|
+
f" Lower limit {self.lower_loa:.{d}f} "
|
|
268
|
+
f"({self.lower_loa_ci[0]:.{d}f} to {self.lower_loa_ci[1]:.{d}f})",
|
|
269
|
+
f" Upper limit {self.upper_loa:.{d}f} "
|
|
270
|
+
f"({self.upper_loa_ci[0]:.{d}f} to {self.upper_loa_ci[1]:.{d}f})",
|
|
271
|
+
f" Differences within limits: {self.within_loa * 100:.1f}%",
|
|
272
|
+
f" Proportional bias: slope {self.proportional_bias_slope:.{d}f} of difference on mean "
|
|
273
|
+
f"(p={self.proportional_bias_p:.{d}g})",
|
|
274
|
+
]
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
def __repr__(self) -> str:
|
|
278
|
+
return self.summary()
|
|
279
|
+
|
|
280
|
+
def to_dict(self) -> dict[str, Any]:
|
|
281
|
+
from .core.result import _json_safe
|
|
282
|
+
|
|
283
|
+
out: dict[str, Any] = _json_safe(
|
|
284
|
+
{k: v for k, v in self.__dict__.items() if k not in ("means", "differences")}
|
|
285
|
+
)
|
|
286
|
+
return out
|
|
287
|
+
|
|
288
|
+
def to_json(self, *, indent: Optional[int] = 2) -> str:
|
|
289
|
+
return json.dumps(self.to_dict(), indent=indent)
|
|
290
|
+
|
|
291
|
+
def to_markdown(self, *, digits: int = 3) -> str:
|
|
292
|
+
d = digits
|
|
293
|
+
rows = ["| Quantity | Estimate | CI |", "| --- | ---: | --- |"]
|
|
294
|
+
rows.append(f"| Bias | {self.bias:.{d}f} | {self.bias_low:.{d}f} to {self.bias_high:.{d}f} |")
|
|
295
|
+
lo, hi = self.lower_loa_ci, self.upper_loa_ci
|
|
296
|
+
rows.append(f"| Lower limit of agreement | {self.lower_loa:.{d}f} | {lo[0]:.{d}f} to {lo[1]:.{d}f} |")
|
|
297
|
+
rows.append(f"| Upper limit of agreement | {self.upper_loa:.{d}f} | {hi[0]:.{d}f} to {hi[1]:.{d}f} |")
|
|
298
|
+
return "\n".join(rows) + "\n"
|
|
299
|
+
|
|
300
|
+
def plot(self, ax: Any = None) -> Any:
|
|
301
|
+
"""Difference against mean with bias and limits of agreement (Matplotlib)."""
|
|
302
|
+
from .core.exceptions import OptionalDependencyError
|
|
303
|
+
|
|
304
|
+
try:
|
|
305
|
+
import matplotlib.pyplot as plt
|
|
306
|
+
except ImportError as exc: # pragma: no cover - depends on the environment
|
|
307
|
+
raise OptionalDependencyError("matplotlib", "plot", "BlandAltman.plot") from exc
|
|
308
|
+
if ax is None:
|
|
309
|
+
_, ax = plt.subplots(figsize=(5.5, 4))
|
|
310
|
+
ax.scatter(self.means, self.differences, s=12, alpha=0.7)
|
|
311
|
+
for y, style in ((self.bias, "-"), (self.lower_loa, "--"), (self.upper_loa, "--")):
|
|
312
|
+
ax.axhline(y, linestyle=style, color="0.3", linewidth=1)
|
|
313
|
+
ax.set_xlabel("Mean of the two methods")
|
|
314
|
+
ax.set_ylabel("Difference (A − B)")
|
|
315
|
+
ax.set_title("Bland–Altman")
|
|
316
|
+
return ax
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _pair(a: Any, b: Any) -> tuple[np.ndarray, np.ndarray]:
|
|
320
|
+
try:
|
|
321
|
+
x = np.asarray(a, dtype=np.float64).ravel()
|
|
322
|
+
y = np.asarray(b, dtype=np.float64).ravel()
|
|
323
|
+
except (TypeError, ValueError) as exc:
|
|
324
|
+
raise InputValidationError("Both methods' measurements must be numeric.") from exc
|
|
325
|
+
if x.size != y.size:
|
|
326
|
+
raise InputValidationError(f"The two methods must measure the same subjects; got {x.size} and {y.size}.")
|
|
327
|
+
if not (np.all(np.isfinite(x)) and np.all(np.isfinite(y))):
|
|
328
|
+
raise InputValidationError("Measurements must be finite (drop missing pairs first).")
|
|
329
|
+
if x.size < 3:
|
|
330
|
+
raise InputValidationError("Agreement needs at least 3 paired measurements.")
|
|
331
|
+
return x, y
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def bland_altman(method_a: Any, method_b: Any, *, level: float = 0.95, loa_level: float = 0.95) -> BlandAltman:
|
|
335
|
+
"""Bias and limits of agreement between two methods (Bland & Altman 1986), with confidence intervals for the
|
|
336
|
+
bias (t) and for each limit (Bland & Altman 1999), and a test for proportional bias (regression of the
|
|
337
|
+
difference on the mean)."""
|
|
338
|
+
from scipy import stats
|
|
339
|
+
|
|
340
|
+
lv, ll = _level(level), _level(loa_level)
|
|
341
|
+
a, b = _pair(method_a, method_b)
|
|
342
|
+
d = a - b
|
|
343
|
+
m = (a + b) / 2
|
|
344
|
+
n = d.size
|
|
345
|
+
bias = float(d.mean())
|
|
346
|
+
sd = float(d.std(ddof=1))
|
|
347
|
+
z = float(stats.norm.ppf(1 - (1 - ll) / 2))
|
|
348
|
+
t = float(stats.t.ppf(1 - (1 - lv) / 2, n - 1))
|
|
349
|
+
se_bias = sd / math.sqrt(n)
|
|
350
|
+
se_loa = sd * math.sqrt(1 / n + z**2 / (2 * (n - 1)))
|
|
351
|
+
lo, hi = bias - z * sd, bias + z * sd
|
|
352
|
+
if np.ptp(m) > 0:
|
|
353
|
+
reg = stats.linregress(m, d)
|
|
354
|
+
slope, p = float(reg.slope), float(reg.pvalue)
|
|
355
|
+
else:
|
|
356
|
+
slope, p = math.nan, math.nan
|
|
357
|
+
return BlandAltman(
|
|
358
|
+
n=n,
|
|
359
|
+
bias=bias,
|
|
360
|
+
bias_low=bias - t * se_bias,
|
|
361
|
+
bias_high=bias + t * se_bias,
|
|
362
|
+
sd=sd,
|
|
363
|
+
lower_loa=lo,
|
|
364
|
+
upper_loa=hi,
|
|
365
|
+
lower_loa_ci=(lo - t * se_loa, lo + t * se_loa),
|
|
366
|
+
upper_loa_ci=(hi - t * se_loa, hi + t * se_loa),
|
|
367
|
+
proportional_bias_slope=slope,
|
|
368
|
+
proportional_bias_p=p,
|
|
369
|
+
level=lv,
|
|
370
|
+
loa_level=ll,
|
|
371
|
+
within_loa=float(np.mean((d >= lo) & (d <= hi))),
|
|
372
|
+
means=m,
|
|
373
|
+
differences=d,
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def lins_ccc(method_a: Any, method_b: Any, *, level: float = 0.95) -> Any:
|
|
378
|
+
"""Lin's concordance correlation coefficient (agreement with the identity line) with the Fisher-z confidence
|
|
379
|
+
interval of Lin (1989); returns a :class:`~evalsuite.MetricResult`."""
|
|
380
|
+
from scipy import stats
|
|
381
|
+
|
|
382
|
+
from .core.result import MetricResult
|
|
383
|
+
|
|
384
|
+
lv = _level(level)
|
|
385
|
+
x, y = _pair(method_a, method_b)
|
|
386
|
+
n = x.size
|
|
387
|
+
sx2, sy2 = x.var(), y.var() # maximum-likelihood variances, as in Lin (1989)
|
|
388
|
+
sxy = float(np.mean((x - x.mean()) * (y - y.mean())))
|
|
389
|
+
denom = sx2 + sy2 + (x.mean() - y.mean()) ** 2
|
|
390
|
+
if denom == 0:
|
|
391
|
+
raise InputValidationError("Both methods are constant and equal; the CCC is undefined.")
|
|
392
|
+
ccc = 2 * sxy / denom
|
|
393
|
+
r = sxy / math.sqrt(sx2 * sy2) if sx2 > 0 and sy2 > 0 else math.nan
|
|
394
|
+
params: dict[str, Any] = {"pearson_r": r, "n": n, "ci_level": lv}
|
|
395
|
+
if abs(ccc) < 1 and np.isfinite(r) and abs(r) < 1:
|
|
396
|
+
u = (x.mean() - y.mean()) / (sx2 * sy2) ** 0.25
|
|
397
|
+
var_z = (
|
|
398
|
+
(1 - r**2) * ccc**2 / ((1 - ccc**2) * r**2)
|
|
399
|
+
+ 2 * ccc**3 * (1 - ccc) * u**2 / (r * (1 - ccc**2) ** 2)
|
|
400
|
+
- ccc**4 * u**4 / (2 * r**2 * (1 - ccc**2) ** 2)
|
|
401
|
+
) / (n - 2)
|
|
402
|
+
zc = math.atanh(ccc)
|
|
403
|
+
half = float(stats.norm.ppf(1 - (1 - lv) / 2)) * math.sqrt(max(var_z, 0.0))
|
|
404
|
+
params.update(ci_low=math.tanh(zc - half), ci_high=math.tanh(zc + half), ci_method="Fisher z (Lin 1989)")
|
|
405
|
+
return MetricResult(name="Lin's concordance correlation", value=float(ccc), metric="lins_ccc", params=params)
|