evalsuite-python 0.5.3__py3-none-any.whl → 0.5.4__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/core/context.py CHANGED
@@ -92,7 +92,23 @@ class ClassificationContext:
92
92
  def _index(self) -> dict[Any, int]:
93
93
  return {lab.item() if hasattr(lab, "item") else lab: i for i, lab in enumerate(self.labels)}
94
94
 
95
+ @cached_property
96
+ def _contiguous_int_labels(self) -> Optional[int]:
97
+ """The first label when labels are consecutive integers lo, lo+1, …; encoding is then y − lo."""
98
+ lab = self.labels
99
+ if (
100
+ lab.dtype.kind in "iu"
101
+ and lab.size
102
+ and np.array_equal(lab, np.arange(int(lab[0]), int(lab[0]) + lab.size))
103
+ ):
104
+ return int(lab[0])
105
+ return None
106
+
95
107
  def encode(self, y: NDArray[Any]) -> NDArray[np.int64]:
108
+ lo = self._contiguous_int_labels
109
+ if lo is not None and y.dtype.kind in "iu":
110
+ yi = y.astype(np.int64, copy=False)
111
+ return yi - lo if lo else yi
96
112
  sorted_labels = np.all(self.labels[:-1] <= self.labels[1:]) if self.labels.dtype != object else False
97
113
  if sorted_labels:
98
114
  return np.searchsorted(self.labels, y).astype(np.int64)
@@ -123,6 +139,8 @@ class ClassificationContext:
123
139
  )
124
140
  k = self.labels.shape[0]
125
141
  flat = self.true_idx * k + self.pred_idx
142
+ if self.sample_weight is None: # integer counting is faster than summing unit weights
143
+ return np.bincount(flat, minlength=k * k).reshape(k, k).astype(np.float64)
126
144
  return np.bincount(flat, weights=self.weights, minlength=k * k).reshape(k, k).astype(np.float64)
127
145
 
128
146
  @cached_property
@@ -65,7 +65,7 @@ def _label_kind(arr: NDArray[Any]) -> str:
65
65
 
66
66
 
67
67
  def check_finite(arr: NDArray[Any], name: str) -> None:
68
- if np.issubdtype(arr.dtype, np.number) and not np.all(np.isfinite(arr)):
68
+ if arr.dtype.kind in "fc" and not np.all(np.isfinite(arr)): # integers and booleans are always finite
69
69
  n_nan = int(np.isnan(arr).sum())
70
70
  n_inf = int(np.isinf(arr).sum())
71
71
  raise InputValidationError(
@@ -104,25 +104,38 @@ def unique_labels(y: NDArray[Any]) -> NDArray[Any]:
104
104
  are found with one marking pass instead of a sort, which is several times faster on large arrays."""
105
105
  if y.size and np.issubdtype(y.dtype, np.integer):
106
106
  lo, hi = int(y.min()), int(y.max())
107
+ if hi - lo <= 1: # min and max are themselves the labels (the binary case): no counting pass
108
+ return np.array([lo] if hi == lo else [lo, hi], dtype=y.dtype)
107
109
  if lo > -(2**62) and hi < 2**62 and hi - lo <= max(1024, y.size):
108
- present = np.zeros(hi - lo + 1, dtype=bool)
109
- present[(y.astype(np.int64) - lo).ravel()] = True # int64 offsets: no overflow for small dtypes
110
- return (np.flatnonzero(present).astype(np.int64) + lo).astype(y.dtype)
110
+ flat = y.ravel()
111
+ # bincount counts in one pass; offsets in int64 so small dtypes cannot overflow.
112
+ counts = np.bincount(flat if lo == 0 and flat.dtype.itemsize <= 8 else flat.astype(np.int64) - lo)
113
+ return (np.flatnonzero(counts).astype(np.int64) + lo).astype(y.dtype)
111
114
  return np.unique(y)
112
115
 
113
116
 
117
+ def _has_fraction(y: NDArray[Any]) -> bool:
118
+ """Whether any value is non-integral. Real-valued targets almost always show it in the first few values,
119
+ so a short leading chunk is checked before the whole array."""
120
+ flat = y.ravel()
121
+ head = flat[:1024]
122
+ if not np.all(np.mod(head, 1) == 0):
123
+ return True
124
+ return flat.size > head.size and not np.all(np.mod(flat[head.size :], 1) == 0)
125
+
126
+
114
127
  def target_type(y: NDArray[Any]) -> TargetType:
115
128
  """Infer the type of a label array."""
116
129
  if y.ndim == 2:
117
130
  if y.shape[1] > 1 and np.isin(y, (0, 1)).all():
118
131
  return "multilabel"
119
- if np.issubdtype(y.dtype, np.floating) and not np.all(np.mod(y, 1) == 0):
132
+ if np.issubdtype(y.dtype, np.floating) and _has_fraction(y):
120
133
  return "continuous" # multi-output regression
121
134
  raise InputValidationError(
122
135
  "2-D targets must be a binary indicator matrix (0/1, one column per label) for multilabel tasks; "
123
136
  f"received shape {y.shape} with values other than 0 and 1."
124
137
  )
125
- if np.issubdtype(y.dtype, np.floating) and not np.all(np.mod(y, 1) == 0):
138
+ if np.issubdtype(y.dtype, np.floating) and _has_fraction(y):
126
139
  return "continuous"
127
140
  try:
128
141
  n_unique = unique_labels(y).shape[0]
@@ -147,6 +160,14 @@ def resolve_labels(
147
160
  f"y_true has {_label_kind(y_true)} labels but y_pred has {_label_kind(y_pred)} labels; "
148
161
  "use the same label type in both (for example map class names to integers first)."
149
162
  )
163
+ if (
164
+ y_pred is not None
165
+ and np.issubdtype(y_true.dtype, np.integer)
166
+ and np.issubdtype(y_pred.dtype, np.integer)
167
+ and y_true.dtype == y_pred.dtype
168
+ ):
169
+ # Union of each array's labels: no concatenated copy of the data.
170
+ return np.union1d(unique_labels(y_true), unique_labels(y_pred)).astype(y_true.dtype)
150
171
  present = y_true if y_pred is None else np.concatenate([y_true, y_pred])
151
172
  try:
152
173
  return unique_labels(present)
@@ -60,12 +60,15 @@ def floats(x: Any, name: str, *, lo: Optional[float] = None, hi: Optional[float]
60
60
  raise InputValidationError(f"{name} must contain numbers.") from exc
61
61
  if a.ndim != 1:
62
62
  raise InputValidationError(f"{name} must be one-dimensional (one number per example).")
63
- if not np.all(np.isfinite(a)):
64
- raise InputValidationError(f"{name} contains NaN or infinite values.")
65
- if lo is not None and np.any(a < lo):
66
- raise InputValidationError(f"{name} must be >= {lo}.")
67
- if hi is not None and np.any(a > hi):
68
- raise InputValidationError(f"{name} must be <= {hi}.")
63
+ if a.size:
64
+ # min and max propagate NaN and ±inf, so two reductions check finiteness and both bounds.
65
+ mn, mx = float(a.min()), float(a.max())
66
+ if not (math.isfinite(mn) and math.isfinite(mx)):
67
+ raise InputValidationError(f"{name} contains NaN or infinite values.")
68
+ if lo is not None and mn < lo:
69
+ raise InputValidationError(f"{name} must be >= {lo}.")
70
+ if hi is not None and mx > hi:
71
+ raise InputValidationError(f"{name} must be <= {hi}.")
69
72
  return a
70
73
 
71
74
 
@@ -130,20 +133,27 @@ def quantiles(a: np.ndarray, qs: Sequence[float]) -> list[float]:
130
133
  def summary(a: np.ndarray, extra: Sequence[float] = ()) -> dict[str, float]:
131
134
  """Mean, standard deviation, min, max and the p50/p90/p95/p99 percentiles (linear interpolation), plus any
132
135
  ``extra`` percentiles under keys ``p<q>``; all order statistics come from one partition."""
133
- qs = [0.0, 50.0, 90.0, 95.0, 99.0, 100.0, *extra]
136
+ qs = [50.0, 90.0, 95.0, 99.0, *[q for q in extra if q not in (0.0, 50.0, 90.0, 95.0, 99.0, 100.0)]]
134
137
  v = quantiles(a, qs)
138
+ by_q = dict(zip(qs, v))
139
+ mean = float(a.mean())
140
+ if a.size > 1:
141
+ c = a - mean
142
+ std = math.sqrt(float(np.dot(c, c)) / (a.size - 1))
143
+ else:
144
+ std = 0.0
135
145
  out = {
136
- "mean": float(a.mean()),
137
- "std": float(a.std(ddof=1)) if a.size > 1 else 0.0,
138
- "min": v[0],
139
- "max": v[5],
140
- "p50": v[1],
141
- "p90": v[2],
142
- "p95": v[3],
143
- "p99": v[4],
146
+ "mean": mean,
147
+ "std": std,
148
+ "min": float(a.min()),
149
+ "max": float(a.max()),
150
+ "p50": by_q[50.0],
151
+ "p90": by_q[90.0],
152
+ "p95": by_q[95.0],
153
+ "p99": by_q[99.0],
144
154
  }
145
- for q, val in zip(extra, v[6:]):
146
- out[f"p{q:g}"] = val
155
+ for q in extra:
156
+ out[f"p{q:g}"] = float(a.min()) if q == 0 else float(a.max()) if q == 100 else by_q[q]
147
157
  return out
148
158
 
149
159
 
@@ -64,6 +64,15 @@ _REF_MARCHISIO = (
64
64
  )
65
65
 
66
66
 
67
+ def _str_array(x: Any, name: str) -> np.ndarray:
68
+ """Labels as a NumPy string array (each value's ``str``)."""
69
+ if isinstance(x, np.ndarray) and x.dtype.kind == "U" and x.ndim == 1:
70
+ if x.size == 0:
71
+ seq(x, name) # raises the usual empty-input error
72
+ return x
73
+ return np.asarray([str(v) for v in seq(x, name)], dtype=str)
74
+
75
+
67
76
  @register(
68
77
  category=_C,
69
78
  task="language-identification",
@@ -75,21 +84,24 @@ _REF_MARCHISIO = (
75
84
  references=(_REF_LANGID,),
76
85
  )
77
86
  def language_id_accuracy(true_languages: Any, predicted_languages: Any) -> MetricResult:
78
- t = [str(v) for v in seq(true_languages, "true_languages")]
79
- p = [str(v) for v in seq(predicted_languages, "predicted_languages")]
87
+ t = _str_array(true_languages, "true_languages")
88
+ p = _str_array(predicted_languages, "predicted_languages")
80
89
  same_length(("true_languages", t), ("predicted_languages", p))
81
- labels = sorted(set(t) | set(p))
82
- f1s, recall = [], {}
83
- for lab in labels:
84
- tp = sum(a == lab and b == lab for a, b in zip(t, p))
85
- fp = sum(a != lab and b == lab for a, b in zip(t, p))
86
- fn = sum(a == lab and b != lab for a, b in zip(t, p))
87
- f1s.append(0.0 if tp == 0 else 2 * tp / (2 * tp + fp + fn))
88
- if tp + fn:
89
- recall[lab] = tp / (tp + fn)
90
- acc = float(np.mean([a == b for a, b in zip(t, p)]))
90
+ # One encoding of both arrays, then a confusion matrix by bincount (labels in sorted order).
91
+ labels_arr, codes = np.unique(np.concatenate([t, p]), return_inverse=True)
92
+ k = labels_arr.shape[0]
93
+ n = t.shape[0]
94
+ cm = np.bincount(codes[:n] * k + codes[n:], minlength=k * k).reshape(k, k)
95
+ tp = np.diag(cm)
96
+ fp = cm.sum(axis=0) - tp
97
+ fn = cm.sum(axis=1) - tp
98
+ denom = 2 * tp + fp + fn
99
+ f1s = np.where(tp > 0, 2 * tp / np.maximum(denom, 1), 0.0)
100
+ labels = labels_arr.tolist()
101
+ recall = {lab: int(tp[i]) / int(tp[i] + fn[i]) for i, lab in enumerate(labels) if tp[i] + fn[i]}
102
+ acc = float(tp.sum() / n)
91
103
  return MetricResult(
92
- "language_id_accuracy", "Language-ID accuracy", acc, {"macro_f1": float(np.mean(f1s)), "recall": recall}
104
+ "language_id_accuracy", "Language-ID accuracy", acc, {"macro_f1": float(f1s.mean()), "recall": recall}
93
105
  )
94
106
 
95
107
 
@@ -80,6 +80,18 @@ class _Inputs:
80
80
  def error(self) -> FloatArray:
81
81
  return self.y_pred - self.y_true
82
82
 
83
+ @cached_property
84
+ def sq_error(self) -> FloatArray:
85
+ """Squared errors, shared by MSE, RMSE and R² when evaluate() computes them together."""
86
+ e = self.error
87
+ with np.errstate(over="ignore"):
88
+ return e * e
89
+
90
+ @cached_property
91
+ def mse_per_output(self) -> FloatArray:
92
+ with np.errstate(over="ignore"):
93
+ return self.mean(self.sq_error)
94
+
83
95
  def mean(self, values: FloatArray) -> FloatArray:
84
96
  """Weighted mean over observations, per output column."""
85
97
  if self.weight is None:
@@ -176,7 +188,7 @@ def mse(
176
188
  ) -> MetricResult:
177
189
  """Mean squared error."""
178
190
  inp = _inputs(y_true, y_pred, sample_weight)
179
- return _finish(inp.mean(inp.error**2), inp, multioutput, "mse", "MSE")
191
+ return _finish(inp.mse_per_output, inp, multioutput, "mse", "MSE")
180
192
 
181
193
 
182
194
  @register(
@@ -203,7 +215,7 @@ def rmse(
203
215
  """Root mean squared error (square root taken per output, then averaged)."""
204
216
  inp = _inputs(y_true, y_pred, sample_weight)
205
217
  with np.errstate(over="ignore"):
206
- per_output = np.sqrt(inp.mean(inp.error**2))
218
+ per_output = np.sqrt(inp.mse_per_output)
207
219
  if not np.all(np.isfinite(per_output)):
208
220
  # Errors above ~1e154 overflow when squared although the RMSE itself is representable:
209
221
  # rescale by the largest error and square again.
@@ -214,10 +226,15 @@ def rmse(
214
226
 
215
227
 
216
228
  def _r2_per_output(inp: _Inputs) -> FloatArray:
217
- w = inp.w[:, None]
218
- ss_res = (w * inp.error**2).sum(0)
219
229
  mean = inp.mean(inp.y_true)
220
- ss_tot = (w * (inp.y_true - mean) ** 2).sum(0)
230
+ dev = inp.y_true - mean
231
+ if inp.weight is None: # no array of unit weights to multiply by
232
+ ss_res = inp.sq_error.sum(0)
233
+ ss_tot = (dev * dev).sum(0)
234
+ else:
235
+ w = inp.weight[:, None]
236
+ ss_res = (w * inp.sq_error).sum(0)
237
+ ss_tot = (w * dev * dev).sum(0)
221
238
  out = np.empty_like(ss_res)
222
239
  const = ss_tot == 0
223
240
  out[~const] = 1 - ss_res[~const] / ss_tot[~const]
evalsuite/stats/effect.py CHANGED
@@ -93,8 +93,6 @@ def cramers_v(table: ArrayLike, *, bias_correction: bool = False) -> float:
93
93
  References: Cramér H. Mathematical Methods of Statistics. Princeton; 1946. Bergsma W. A bias-correction for
94
94
  Cramér's V and Tschuprow's T. J Korean Stat Soc. 2013;42(3):323-328.
95
95
  """
96
- from scipy import stats
97
-
98
96
  t = np.asarray(table, dtype=np.float64)
99
97
  if t.ndim != 2 or min(t.shape) < 2:
100
98
  raise InputValidationError("Give a contingency table with at least 2 rows and 2 columns.")
@@ -103,7 +101,10 @@ def cramers_v(table: ArrayLike, *, bias_correction: bool = False) -> float:
103
101
  if np.any(t.sum(axis=0) == 0) or np.any(t.sum(axis=1) == 0):
104
102
  raise StatisticalTestError("Cramér's V is undefined when a row or column total is zero.")
105
103
  n = t.sum()
106
- chi2 = stats.chi2_contingency(t, correction=False)[0]
104
+ rows, cols = t.sum(axis=1), t.sum(axis=0)
105
+ expected = np.outer(rows, cols) / n
106
+ dev = t - expected
107
+ chi2 = float(np.sum(dev * dev / expected)) # uncorrected Pearson χ², as scipy.stats.chi2_contingency
107
108
  r, k = t.shape
108
109
  if not bias_correction:
109
110
  return float(np.sqrt(chi2 / (n * (min(r, k) - 1))))
@@ -132,16 +133,17 @@ def adjust_pvalues(
132
133
  Benjamini Y, Hochberg Y. J R Stat Soc B. 1995;57(1):289-300. Benjamini Y, Yekutieli D. Ann Stat.
133
134
  2001;29(4):1165-1188.
134
135
  """
135
- p = to_numpy(p_values, "p_values").astype(np.float64)
136
+ p = to_numpy(p_values, "p_values").astype(np.float64, copy=False)
136
137
  check_finite(p, "p_values")
137
- if np.any((p < 0) | (p > 1)):
138
+ if float(np.min(p)) < 0 or float(np.max(p)) > 1:
138
139
  raise InputValidationError("p-values must be between 0 and 1.")
139
140
  m = p.shape[0]
141
+ if method == "bonferroni": # no ranking needed
142
+ bonf: NDArray[np.float64] = np.minimum(p * m, 1.0)
143
+ return bonf
140
144
  order = np.argsort(p) # ties get the same adjusted value whatever their order
141
145
  ranked = p[order]
142
- if method == "bonferroni":
143
- adj = np.minimum(ranked * m, 1)
144
- elif method == "holm":
146
+ if method == "holm":
145
147
  adj = np.minimum(np.maximum.accumulate(ranked * (m - np.arange(m))), 1)
146
148
  elif method == "hochberg":
147
149
  scaled = ranked * (m - np.arange(m))
@@ -8,7 +8,7 @@ implementations are the reference; EvalSuite adds input validation, effect sizes
8
8
  from __future__ import annotations
9
9
 
10
10
  import math
11
- from typing import TYPE_CHECKING, Literal
11
+ from typing import TYPE_CHECKING, Literal, Optional
12
12
 
13
13
  import numpy as np
14
14
  from numpy.typing import NDArray
@@ -72,6 +72,49 @@ def _mean_diff_ci(
72
72
  return ConfidenceInterval(diff, lo, hi, level, "t", name, {"df": float(df), "se": float(se)})
73
73
 
74
74
 
75
+ def _t_pvalue(t: float, df: float, alternative: str) -> float:
76
+ """Student-t p-value for statistic ``t`` (identical to SciPy's t-tests)."""
77
+ if alternative == "two-sided":
78
+ return min(2.0 * float(special.stdtr(df, -abs(t))), 1.0)
79
+ if alternative == "less":
80
+ return float(special.stdtr(df, t))
81
+ return float(special.stdtr(df, -t))
82
+
83
+
84
+ def _z_pvalue(z: float, alternative: str) -> float:
85
+ if alternative == "two-sided":
86
+ return min(2.0 * float(special.ndtr(-abs(z))), 1.0)
87
+ if alternative == "less":
88
+ return float(special.ndtr(z))
89
+ return float(special.ndtr(-z))
90
+
91
+
92
+ def _rank_sums(
93
+ values: NDArray[np.float64], labels: NDArray[np.intp], k: int
94
+ ) -> tuple[NDArray[np.float64], NDArray[np.intp]]:
95
+ """Sum of average ranks (as ``scipy.stats.rankdata``) per label 0..k-1, and the tie-group sizes.
96
+
97
+ One unstable sort: tied values share their group's average rank, so their order does not matter, and the
98
+ per-label sums come from ``bincount`` without scattering ranks back to the input order."""
99
+ order = np.argsort(values)
100
+ sv = values[order]
101
+ n = sv.shape[0]
102
+ new = np.empty(n, dtype=bool)
103
+ new[0] = True
104
+ np.not_equal(sv[1:], sv[:-1], out=new[1:])
105
+ starts = np.flatnonzero(new)
106
+ sizes = np.diff(np.r_[starts, n])
107
+ avg = starts + (sizes + 1) / 2.0
108
+ ranks = avg[np.cumsum(new) - 1]
109
+ return np.bincount(labels[order], weights=ranks, minlength=k), sizes
110
+
111
+
112
+ def _signed_rank(nz: NDArray[np.float64]) -> tuple[float, float, NDArray[np.float64]]:
113
+ """Wilcoxon signed-rank sums of the non-zero differences: (T+, T-, tie-group sizes)."""
114
+ sums, sizes = _rank_sums(np.abs(nz), (nz > 0).astype(np.intp), 2)
115
+ return float(sums[1]), float(sums[0]), sizes.astype(np.float64)
116
+
117
+
75
118
  def t_test(
76
119
  a: ArrayLike,
77
120
  b: ArrayLike,
@@ -105,13 +148,7 @@ def t_test(
105
148
  df = (v1 / n1 + v2 / n2) ** 2 / ((v1 / n1) ** 2 / (n1 - 1) + (v2 / n2) ** 2 / (n2 - 1)) if se else math.nan
106
149
  t = (m1 - m2) / se
107
150
  # Student-t tail probabilities directly (what scipy.stats.ttest_ind returns), without re-reading the data.
108
- if alternative == "two-sided":
109
- p = 2.0 * float(special.stdtr(df, -abs(t)))
110
- elif alternative == "less":
111
- p = float(special.stdtr(df, t))
112
- else:
113
- p = float(special.stdtr(df, -t))
114
- p = min(p, 1.0)
151
+ p = _t_pvalue(t, df, alternative)
115
152
  diff = m1 - m2
116
153
  pooled = math.sqrt(((n1 - 1) * v1 + (n2 - 1) * v2) / (n1 + n2 - 2))
117
154
  return TestResult(
@@ -141,17 +178,19 @@ def paired_t_test(
141
178
  x, y = _vec(a, "a"), _vec(b, "b")
142
179
  if x.shape != y.shape:
143
180
  raise InputValidationError(f"Paired samples must have the same length; got {x.shape[0]} and {y.shape[0]}.")
181
+ _alt(alternative)
144
182
  d = x - y
145
- sd = d.std(ddof=1)
146
- if sd == 0:
147
- raise StatisticalTestError("The paired t-test is undefined: every difference is identical.")
148
- res = stats.ttest_rel(x, y, alternative=_alt(alternative))
149
183
  n = d.shape[0]
150
184
  diff = float(d.mean())
185
+ c = d - diff
186
+ sd = math.sqrt(float(np.dot(c, c)) / (n - 1))
187
+ if sd == 0:
188
+ raise StatisticalTestError("The paired t-test is undefined: every difference is identical.")
189
+ t = diff / (sd / math.sqrt(n))
151
190
  return TestResult(
152
191
  "paired-t",
153
- float(res.statistic),
154
- float(res.pvalue),
192
+ t,
193
+ _t_pvalue(t, n - 1, alternative),
155
194
  alternative=alternative,
156
195
  estimate=diff,
157
196
  ci=_mean_diff_ci(diff, sd / math.sqrt(n), n - 1, level, alternative, "mean_difference"),
@@ -167,19 +206,73 @@ def mann_whitney_test(a: ArrayLike, b: ArrayLike, *, alternative: Alternative =
167
206
  References: Mann HB, Whitney DR. Ann Math Stat. 1947;18(1):50-60. Kerby DS. Compr Psychol. 2014;3:11.IT.3.1.
168
207
  """
169
208
  x, y = _vec(a, "a", 1), _vec(b, "b", 1)
170
- res = stats.mannwhitneyu(x, y, alternative=_alt(alternative), method="auto")
171
- u = float(res.statistic)
209
+ _alt(alternative)
172
210
  n1, n2 = x.shape[0], y.shape[0]
211
+ labels = np.zeros(n1 + n2, dtype=np.intp)
212
+ labels[n1:] = 1
213
+ sums, sizes = _rank_sums(np.concatenate([x, y]), labels, 2)
214
+ u = float(sums[0]) - n1 * (n1 + 1) / 2
215
+ ties = sizes[sizes > 1].astype(np.float64)
216
+ if (n1 <= 8 or n2 <= 8) and ties.size == 0:
217
+ # SciPy's method="auto" uses the exact null distribution here.
218
+ p = float(stats.mannwhitneyu(x, y, alternative=alternative, method="exact").pvalue)
219
+ else:
220
+ # Tie-corrected normal approximation with continuity correction, as scipy.stats.mannwhitneyu.
221
+ n = n1 + n2
222
+ s_ = math.sqrt(n1 * n2 / 12 * ((n + 1) - float(np.sum(ties**3 - ties)) / (n * (n - 1))))
223
+ num = u - n1 * n2 / 2
224
+ sign = 1.0 if alternative == "greater" else -1.0 if alternative == "less" else float(np.sign(num))
225
+ num -= 0.5 * sign
226
+ p = _z_pvalue(num / s_, alternative) if s_ > 0 else math.nan
173
227
  return TestResult(
174
228
  "mann-whitney",
175
229
  u,
176
- float(res.pvalue),
230
+ p,
177
231
  alternative=alternative,
178
232
  estimate=2 * u / (n1 * n2) - 1,
179
233
  params={"effect_size": "rank-biserial correlation", "auc": u / (n1 * n2), "n_a": n1, "n_b": n2},
180
234
  )
181
235
 
182
236
 
237
+ def _wilcoxon_fast(
238
+ d: NDArray[np.float64],
239
+ nz: NDArray[np.float64],
240
+ t_plus: float,
241
+ t_minus: float,
242
+ ties: NDArray[np.float64],
243
+ alternative: str,
244
+ zero_method: str,
245
+ ) -> tuple[float, Optional[float]]:
246
+ """SciPy's ``wilcoxon`` (method="auto", correction=False) from ranks already computed: the exact null
247
+ distribution without ties or zeros, the tie-corrected normal approximation otherwise. Returns p=None where
248
+ SciPy would run a permutation test (ties or zeros with n <= 13), other zero methods, or old SciPy. As in
249
+ SciPy, samples of more than 50 pairs always use the normal approximation."""
250
+ stat = min(t_plus, t_minus) if alternative == "two-sided" else t_plus
251
+ if zero_method != "wilcox":
252
+ return stat, None
253
+ n_zero = d.shape[0] - nz.shape[0]
254
+ has_ties = bool(np.any(ties > 1))
255
+ count = nz.shape[0]
256
+ if d.shape[0] <= 50 and not (has_ties or n_zero > 0):
257
+ try:
258
+ from scipy.stats._wilcoxon import WilcoxonDistribution
259
+ except ImportError: # SciPy < 1.12
260
+ return stat, None
261
+ dist = WilcoxonDistribution(np.asarray(count))
262
+ if alternative == "less":
263
+ p = float(dist.cdf(np.ceil(t_plus)))
264
+ elif alternative == "greater":
265
+ p = float(dist.sf(np.floor(t_plus)))
266
+ else:
267
+ p = float(np.clip(2 * min(dist.sf(np.floor(t_plus)), dist.cdf(np.ceil(t_plus))), 0, 1))
268
+ return stat, p
269
+ if d.shape[0] <= 13 and (has_ties or n_zero > 0):
270
+ return stat, None
271
+ mn = count * (count + 1.0) * 0.25
272
+ se = math.sqrt((count * (count + 1.0) * (2.0 * count + 1.0) - float(np.sum(ties**3 - ties)) / 2) / 24)
273
+ return stat, _z_pvalue((t_plus - mn) / se, alternative)
274
+
275
+
183
276
  def wilcoxon_test(
184
277
  a: ArrayLike,
185
278
  b: ArrayLike,
@@ -199,13 +292,16 @@ def wilcoxon_test(
199
292
  nz = d[d != 0]
200
293
  if nz.shape[0] == 0:
201
294
  raise StatisticalTestError("The Wilcoxon test is undefined: every difference is zero.")
202
- res = stats.wilcoxon(x, y, alternative=_alt(alternative), zero_method=zero_method)
203
- ranks = stats.rankdata(np.abs(nz))
204
- t_plus, t_minus = ranks[nz > 0].sum(), ranks[nz < 0].sum()
295
+ _alt(alternative)
296
+ t_plus, t_minus, ties = _signed_rank(nz)
297
+ stat, p = _wilcoxon_fast(d, nz, t_plus, t_minus, ties, alternative, zero_method)
298
+ if p is None:
299
+ res = stats.wilcoxon(x, y, alternative=alternative, zero_method=zero_method)
300
+ stat, p = float(res.statistic), float(res.pvalue)
205
301
  return TestResult(
206
302
  "wilcoxon",
207
- float(res.statistic),
208
- float(res.pvalue),
303
+ stat,
304
+ p,
209
305
  alternative=alternative,
210
306
  estimate=float((t_plus - t_minus) / (t_plus + t_minus)),
211
307
  params={
@@ -231,13 +327,20 @@ def kruskal_wallis_test(*groups: ArrayLike) -> TestResult:
231
327
  2014;1(21):19-25.
232
328
  """
233
329
  gs = _groups(groups, 2, "The Kruskal–Wallis test")
234
- res = stats.kruskal(*gs)
235
- n = sum(g.shape[0] for g in gs)
236
- h = float(res.statistic)
330
+ sizes_g = np.array([g.shape[0] for g in gs])
331
+ n = int(sizes_g.sum())
332
+ labels = np.repeat(np.arange(len(gs), dtype=np.intp), sizes_g)
333
+ sums, ties = _rank_sums(np.concatenate(gs), labels, len(gs))
334
+ # H with the tie correction 1 − Σ(t³ − t)/(n³ − n), as scipy.stats.kruskal.
335
+ t = ties[ties > 1].astype(np.float64)
336
+ correction = 1.0 - float(np.sum(t**3 - t)) / (n**3 - n)
337
+ if correction == 0:
338
+ raise StatisticalTestError("The Kruskal–Wallis test is undefined: all values are identical.")
339
+ h = (12.0 / (n * (n + 1)) * float(np.sum(sums**2 / sizes_g)) - 3 * (n + 1)) / correction
237
340
  return TestResult(
238
341
  "kruskal-wallis",
239
342
  h,
240
- float(res.pvalue),
343
+ float(special.chdtrc(len(gs) - 1, h)),
241
344
  estimate=h / ((n**2 - 1) / (n + 1)),
242
345
  params={"df": len(gs) - 1, "effect_size": "epsilon-squared", "n": n, "k": len(gs)},
243
346
  )
@@ -256,13 +359,32 @@ def friedman_test(*groups: ArrayLike) -> TestResult:
256
359
  raise InputValidationError("Every sample in the Friedman test needs the same number of blocks.")
257
360
  if n < 2:
258
361
  raise StatisticalTestError("The Friedman test needs at least two blocks.")
259
- res = stats.friedmanchisquare(*gs)
260
362
  k = len(gs)
261
- chi = float(res.statistic)
363
+ if k > 32:
364
+ res = stats.friedmanchisquare(*gs)
365
+ chi, p = float(res.statistic), float(res.pvalue)
366
+ else:
367
+ # Within-block average ranks by pairwise comparison (k is small): rank = 1 + #less + (#equal − 1)/2,
368
+ # and each tie group of size t contributes Σ(eq² − 1) = t³ − t; the statistic and tie correction are
369
+ # those of scipy.stats.friedmanchisquare.
370
+ data = np.stack(gs, axis=1)
371
+ less = np.zeros(data.shape)
372
+ eq = np.zeros(data.shape)
373
+ for j in range(k):
374
+ col = data[:, j : j + 1]
375
+ less += col < data
376
+ eq += col == data
377
+ ranks = 1.0 + less + (eq - 1.0) / 2.0
378
+ r = ranks.sum(axis=0)
379
+ c = 1.0 - float(np.sum(eq * eq - 1.0)) / (n * k * (k * k - 1))
380
+ if c == 0:
381
+ raise StatisticalTestError("The Friedman test is undefined: every block has all values tied.")
382
+ chi = (12.0 / (n * k * (k + 1)) * float(np.dot(r, r)) - 3.0 * n * (k + 1)) / c
383
+ p = float(special.chdtrc(k - 1, chi))
262
384
  return TestResult(
263
385
  "friedman",
264
386
  chi,
265
- float(res.pvalue),
387
+ p,
266
388
  estimate=chi / (n * (k - 1)),
267
389
  params={"df": k - 1, "effect_size": "Kendall's W", "n_blocks": n, "k": k},
268
390
  )
@@ -300,9 +422,22 @@ def chi_square_test(table: ArrayLike, *, correction: bool = True) -> TestResult:
300
422
  t = _table(table)
301
423
  if np.any(t.sum(axis=0) == 0) or np.any(t.sum(axis=1) == 0):
302
424
  raise StatisticalTestError("The χ² test is undefined when a row or column total is zero.")
303
- chi2, p, dof, expected = stats.chi2_contingency(t, correction=correction)
304
- n = t.sum()
305
- uncorrected = stats.chi2_contingency(t, correction=False)[0]
425
+ # Same computation as scipy.stats.chi2_contingency, but the expected table is built once and serves both
426
+ # the (possibly Yates-corrected) test statistic and the uncorrected statistic behind Cramér's V.
427
+ n = float(t.sum())
428
+ expected = np.outer(t.sum(axis=1), t.sum(axis=0)) / n
429
+ dof = (t.shape[0] - 1) * (t.shape[1] - 1)
430
+ dev = t - expected
431
+ uncorrected = float(np.sum(dev * dev / expected))
432
+ if dof == 0:
433
+ chi2, p = 0.0, 1.0
434
+ else:
435
+ if correction and dof == 1:
436
+ adj = np.abs(dev) - np.minimum(0.5, np.abs(dev))
437
+ chi2 = float(np.sum(adj * adj / expected))
438
+ else:
439
+ chi2 = uncorrected
440
+ p = float(special.chdtrc(dof, chi2))
306
441
  v = math.sqrt((uncorrected / n) / (min(t.shape) - 1))
307
442
  return TestResult(
308
443
  "chi-square",
@@ -319,6 +454,33 @@ def chi_square_test(table: ArrayLike, *, correction: bool = True) -> TestResult:
319
454
  )
320
455
 
321
456
 
457
+ def _fisher_p(a: int, b: int, c: int, d: int, alternative: str) -> float:
458
+ """Fisher's exact test p-value for [[a, b], [c, d]] from the hypergeometric pmf in log space.
459
+
460
+ Only tables within 40 standard deviations of the mode are summed: anything farther has a probability below
461
+ e^-800 relative to the mode and underflows to zero anyway. Two-sided: tables no more probable than the
462
+ observed one (relative tolerance 1e-7, as R's fisher.test). Matches scipy.stats.fisher_exact to ~1e-12."""
463
+ n1, n2, n = a + b, c + d, a + c
464
+ total = n1 + n2
465
+ lo, hi = max(0, n - n2), min(n, n1)
466
+ mode = (n + 1) * (n1 + 1) // (total + 2)
467
+ sd = math.sqrt(max(n * (n1 / total) * (n2 / total) * (total - n) / max(total - 1, 1), 1.0))
468
+ wlo, whi = max(lo, int(mode - 40 * sd) - 2), min(hi, int(mode + 40 * sd) + 2)
469
+ x = np.arange(wlo, whi + 1, dtype=np.float64)
470
+ gl = special.gammaln
471
+ lp = -(gl(x + 1) + gl(n1 - x + 1) + gl(n - x + 1) + gl(n2 - n + x + 1))
472
+ w = np.exp(lp - lp.max())
473
+ tot = float(w.sum())
474
+ i = a - wlo
475
+ if alternative == "less":
476
+ p = 0.0 if i < 0 else 1.0 if i >= w.shape[0] else float(w[: i + 1].sum()) / tot
477
+ elif alternative == "greater":
478
+ p = 1.0 if i < 0 else 0.0 if i >= w.shape[0] else float(w[i:].sum()) / tot
479
+ else:
480
+ p = 0.0 if not 0 <= i < w.shape[0] else float(w[w <= w[i] * (1 + 1e-7)].sum()) / tot
481
+ return min(p, 1.0)
482
+
483
+
322
484
  def fisher_exact_test(table: ArrayLike, *, alternative: Alternative = "two-sided") -> TestResult:
323
485
  """Fisher's exact test for a 2 × 2 table. ``estimate`` is the sample odds ratio (a·d)/(b·c).
324
486
 
@@ -329,7 +491,13 @@ def fisher_exact_test(table: ArrayLike, *, alternative: Alternative = "two-sided
329
491
  raise InputValidationError("Fisher's exact test here is for 2 × 2 tables.")
330
492
  if not np.all(t == np.round(t)):
331
493
  raise InputValidationError("Fisher's exact test needs integer counts.")
332
- odds, p = stats.fisher_exact(t.astype(np.int64), alternative=_alt(alternative)) # tuple in every SciPy
494
+ _alt(alternative)
495
+ a, b, c, d = (int(v) for v in t.ravel())
496
+ if 0 in (a + b, c + d, a + c, b + d):
497
+ odds, p = math.nan, 1.0 # a zero margin: as scipy.stats.fisher_exact
498
+ else:
499
+ odds = a * d / (b * c) if b > 0 and c > 0 else math.inf
500
+ p = _fisher_p(a, b, c, d, alternative)
333
501
  return TestResult(
334
502
  "fisher-exact",
335
503
  float(odds),