srdkit 1.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.
srdkit/framework.py ADDED
@@ -0,0 +1,368 @@
1
+ r"""A statistically tested consensus of complementary ranking methods (fair model comparison).
2
+
3
+ More than two hundred MCDM methods exist, and with the many weighting schemes
4
+ almost any ranking of the alternatives can be produced by *some* method. As
5
+ far as Héberger (2026a, Table 4) could establish, the classical MCDM methods
6
+ have no built-in statistical validation, whereas SRD has two: the
7
+ randomization test (CRRN) and the uncertainties obtained by cross-validation,
8
+ which make statistical comparison of the alternatives possible. Héberger
9
+ (2026b) therefore proposed a standard: a small consensus of *complementary*
10
+ methods guided by parsimony, the bias--variance trade-off, different
11
+ theoretical foundations and statistical testing. His seven methods fall into
12
+ four groups,
13
+
14
+ * A --- SRD, DnE and DnM against a gold standard (reference),
15
+ * B --- the generalized pair-correlation method with the conditional exact test
16
+ (CEpW) and with Williams' :math:`t` test (WtpW), probability-weighted ordering,
17
+ * C --- the heatmap of SRD values with every alternative serving once as the
18
+ benchmark (HM, the COVAT idea of Andrić and Héberger, 2017), ordered by the
19
+ column sums,
20
+ * D --- the benchmark-agnostic power-eigenvector ranking (DRAPE; here the
21
+ power--weakness ratio of :mod:`srdkit.tournament`).
22
+
23
+ The rankings are put in the same direction (rank 1 = best), the mean ranks give
24
+ the consensus and their standard deviations the variation across methods;
25
+ Wilcoxon matched-pairs tests compare the alternatives and the Friedman test
26
+ (with Kendall's coefficient of concordance :math:`W`) tests them all at once.
27
+ The methods themselves are characterized by the sum of their Kendall
28
+ distances, by the order of axes that minimizes the summed absolute rank
29
+ differences of neighbouring methods in a parallel-coordinate plot, and by a
30
+ leave-one-method-out validation. No more than thirteen methods are recommended
31
+ because of rank degeneration.
32
+
33
+ :func:`covat` computes the heatmap matrix and its ordering, :func:`method_ranks`
34
+ the rank table of the methods and :func:`fair_comparison` the whole framework.
35
+ As additions the result reports proficiency-test :math:`z`-scores of the
36
+ methods (the analogy with round-robin tests is Héberger's) and accepts further
37
+ methods as extra columns.
38
+
39
+ References
40
+ ----------
41
+ Héberger, K. (2026a). Sum of Euclidean distance differences and sum of absolute
42
+ Manhattan distance differences: multicriteria decision making tools for small
43
+ data tables. *Analytica Chimica Acta* 1381, 344649.
44
+
45
+ Héberger, K. (2026b). Framework for fair model comparison as standard for
46
+ multicriteria decision making. *Decision Making and Analysis* 4(1), 257--283.
47
+
48
+ Andrić, F. and Héberger, K. (2017). How to compare separation selectivity of
49
+ high-performance liquid chromatographic columns properly? *Journal of
50
+ Chromatography A* 1488, 45--56.
51
+ """
52
+
53
+ from __future__ import annotations
54
+
55
+ import itertools
56
+ import warnings
57
+ from dataclasses import dataclass, field
58
+
59
+ import numpy as np
60
+ import pandas as pd
61
+ from scipy import stats
62
+
63
+ from ._utils import as_frame
64
+ from .core import pairwise_srd, srd
65
+ from .reference import make_reference
66
+
67
+ LOWER_IS_BETTER = {"SRD", "DnE", "DnM", "HM"}
68
+ DEFAULT_METHODS = ("SRD", "DnE", "DnM", "HM", "CEpW", "WtpW", "PWR")
69
+ MAX_METHODS = 13
70
+
71
+
72
+ # ============================================================================ COVAT heatmap
73
+ @dataclass
74
+ class CovatResult:
75
+ """Every column as the benchmark of the others once (Andrić and Héberger, 2017)."""
76
+
77
+ matrix: pd.DataFrame # reordered by increasing column sums
78
+ sums: pd.Series # column sums, ascending
79
+ measure: str
80
+
81
+ @property
82
+ def order(self) -> list[str]:
83
+ return list(self.sums.index)
84
+
85
+ @property
86
+ def ranks(self) -> pd.Series:
87
+ return self.sums.rank(method="average").rename("rank")
88
+
89
+ def plot(self, ax=None, **kwargs):
90
+ from .viz import plot_covat
91
+
92
+ return plot_covat(self, ax=ax, **kwargs)
93
+
94
+
95
+ def covat(X, measure: str = "srd", ties: str = "average") -> CovatResult:
96
+ """SRD (or DnE/DnM) of every pair of columns, ordered by increasing column sums.
97
+
98
+ ``measure``: ``"srd"`` (normalized SRD in percent), ``"dne"`` or ``"dnm"``
99
+ (in percent). The column with the smallest sum is the most similar to all
100
+ others; HM in the consensus framework ranks the alternatives by these sums.
101
+ """
102
+ df = as_frame(X)
103
+ if measure == "srd":
104
+ M = 100 * pairwise_srd(df, ties=ties, normalize=True)
105
+ elif measure in ("dne", "dnm"):
106
+ from .value import pairwise_value_srd
107
+
108
+ M = 100 * pairwise_value_srd(df, p=2.0 if measure == "dne" else 1.0)
109
+ else:
110
+ raise ValueError("measure must be 'srd', 'dne' or 'dnm'")
111
+ sums = M.sum(axis=0).sort_values(kind="stable")
112
+ order = list(sums.index)
113
+ return CovatResult(matrix=M.loc[order, order], sums=sums.rename("sum"), measure=measure)
114
+
115
+
116
+ # ============================================================================ the method table
117
+ def _infer_directions(df: pd.DataFrame, reference, reference_kwargs: dict):
118
+ if isinstance(reference, str):
119
+ if reference == "min":
120
+ return -np.ones(df.shape[0])
121
+ if reference == "mixed" and reference_kwargs.get("row_methods") is not None:
122
+ rm = reference_kwargs["row_methods"]
123
+ rm = [rm.get(i, "max") for i in df.index] if isinstance(rm, dict) else list(rm)
124
+ return np.array([-1.0 if str(r) == "min" else 1.0 for r in rm])
125
+ return np.ones(df.shape[0])
126
+
127
+
128
+ def method_scores(X, reference="mean", methods=DEFAULT_METHODS, directions=None, value_scaling=None, ties: str = "average",
129
+ alpha_gpcm: float = 0.05, reference_kwargs: dict | None = None) -> pd.DataFrame:
130
+ """Raw scores of the alternatives (columns of ``X``) by the consensus methods.
131
+
132
+ SRD, DnE, DnM and HM: smaller is better; CEpW, WtpW and PWR: larger is better.
133
+ ``directions`` (+1/-1 per row) is needed by PWR only; by default it follows the
134
+ reference (``"min"`` → smaller is better, ``"mixed"`` → its row rules,
135
+ otherwise larger is better). ``value_scaling`` is passed to DnE/DnM
136
+ (``"row-range"`` puts criteria of different units on a common scale).
137
+ """
138
+ from .gpcm import gpcm
139
+ from .tournament import pwr
140
+ from .value import value_srd
141
+
142
+ df = as_frame(X)
143
+ rk = reference_kwargs or {}
144
+ y = make_reference(df, reference, ties=ties, **rk)
145
+ out = {}
146
+ for m in methods:
147
+ if m == "SRD":
148
+ out[m] = srd(df, reference=reference, ties=ties, **rk).normalized
149
+ elif m in ("DnE", "DnM"):
150
+ out[m] = value_srd(df, reference=y, p=2.0 if m == "DnE" else 1.0, scaling=value_scaling).normalized
151
+ elif m == "HM":
152
+ out[m] = covat(df, "srd", ties=ties).sums.reindex(df.columns)
153
+ elif m in ("CEpW", "WtpW"):
154
+ g = gpcm(df, y, test="ce" if m == "CEpW" else "williams", alpha=alpha_gpcm)
155
+ out[m] = g["ranking"]["pW"].reindex(df.columns)
156
+ elif m == "PWR":
157
+ d = _infer_directions(df, reference, rk) if directions is None else directions
158
+ out[m] = pwr(df, directions=d)["PWR"].reindex(df.columns)
159
+ else:
160
+ raise ValueError(f"unknown method {m!r}; choose from {DEFAULT_METHODS}")
161
+ return pd.DataFrame(out, index=df.columns)
162
+
163
+
164
+ def method_ranks(X, reference="mean", methods=DEFAULT_METHODS, extra=None, **kwargs) -> pd.DataFrame:
165
+ """Ranks (1 = best, mid-ranks for ties) of the alternatives by every method.
166
+
167
+ ``extra``: a DataFrame of further *ranks* (alternatives x methods, 1 = best),
168
+ e.g. from :func:`srdkit.mcda_ranks`, appended as columns.
169
+ """
170
+ S = method_scores(X, reference=reference, methods=methods, **kwargs)
171
+ R = pd.DataFrame({m: (S[m] if m in LOWER_IS_BETTER else -S[m]).rank(method="average") for m in S.columns})
172
+ if extra is not None:
173
+ E = pd.DataFrame(extra).reindex(R.index)
174
+ R = pd.concat([R, E.astype(float)], axis=1)
175
+ return R
176
+
177
+
178
+ # ============================================================================ statistics
179
+ def friedman_concordance(R: pd.DataFrame) -> dict:
180
+ r"""Friedman test of a rank table (alternatives x methods) and Kendall's :math:`W`.
181
+
182
+ With tie correction, :math:`W=12S/[m^2(k^3-k)-m\sum T]`,
183
+ :math:`\chi^2=m(k-1)W` with :math:`k-1` degrees of freedom, and the mean
184
+ Spearman correlation of the methods :math:`\bar r_s=(mW-1)/(m-1)`.
185
+
186
+ >>> import pandas as pd
187
+ >>> R = pd.DataFrame({"m1": [1, 2, 3], "m2": [1, 2, 3], "m3": [1, 3, 2]})
188
+ >>> round(friedman_concordance(R)["W"], 4)
189
+ 0.7778
190
+ """
191
+ A = R.to_numpy(float)
192
+ k, m = A.shape
193
+ Rj = A.sum(axis=1)
194
+ S = float(np.sum((Rj - m * (k + 1) / 2) ** 2))
195
+ T = 0.0
196
+ for c in range(m):
197
+ _, cnt = np.unique(A[:, c], return_counts=True)
198
+ T += float(np.sum(cnt ** 3 - cnt))
199
+ den = m ** 2 * (k ** 3 - k) - m * T
200
+ W = 12 * S / den if den > 0 else 1.0
201
+ chi2 = m * (k - 1) * W
202
+ p = float(stats.chi2.sf(chi2, k - 1))
203
+ rs = (m * W - 1) / (m - 1) if m > 1 else np.nan
204
+ return {"chi2": chi2, "df": k - 1, "p": p, "W": W, "mean_spearman": rs, "k": k, "m": m}
205
+
206
+
207
+ def kendall_distance_matrix(R: pd.DataFrame) -> pd.DataFrame:
208
+ r"""Normalized Kendall distances :math:`(1-\tau_b)/2` between the columns (methods) of a rank table."""
209
+ cols = list(R.columns)
210
+ D = pd.DataFrame(0.0, index=cols, columns=cols)
211
+ for a, b in itertools.combinations(cols, 2):
212
+ tau = stats.kendalltau(R[a], R[b]).statistic
213
+ d = (1 - (tau if np.isfinite(tau) else 0.0)) / 2
214
+ D.loc[a, b] = D.loc[b, a] = d
215
+ return D
216
+
217
+
218
+ def adjacent_order(R: pd.DataFrame) -> tuple[list[str], float]:
219
+ """Order of methods minimizing the summed absolute rank differences of neighbours.
220
+
221
+ The path is exact (Held--Karp) for up to 13 methods, nearest neighbour with
222
+ 2-opt above. Returns the order and its total; the reverse order is equally optimal.
223
+ """
224
+ from .parcoord import _held_karp_path, _two_opt
225
+
226
+ A = R.to_numpy(float)
227
+ D = np.abs(A[:, :, None] - A[:, None, :]).sum(axis=0)
228
+ m = D.shape[0]
229
+ if m <= MAX_METHODS:
230
+ path = _held_karp_path(D)
231
+ else:
232
+ start = int(np.argmin(D.sum(axis=1)))
233
+ path, left = [start], set(range(m)) - {start}
234
+ while left:
235
+ nxt = min(left, key=lambda j: D[path[-1], j])
236
+ path.append(nxt)
237
+ left.remove(nxt)
238
+ path = _two_opt(path, D)
239
+ total = float(sum(D[path[i], path[i + 1]] for i in range(m - 1)))
240
+ return [R.columns[i] for i in path], total
241
+
242
+
243
+ def pairwise_alternatives(R: pd.DataFrame, order=None, pairs: str = "neighbors", test: str = "wilcoxon",
244
+ correction: str | None = None) -> pd.DataFrame:
245
+ """Pairwise tests of the alternatives on their ranks across the methods.
246
+
247
+ ``test``: ``"wilcoxon"`` (matched pairs, the methods are the blocks; default),
248
+ ``"mannwhitney"`` or ``"ttest"`` (two-sample). ``pairs``: neighbours in
249
+ ``order`` (default: by mean rank) or ``"all"``; ``correction``: None,
250
+ ``"holm"`` or ``"bonferroni"``.
251
+ """
252
+ order = list(R.mean(axis=1).sort_values(kind="stable").index) if order is None else list(order)
253
+ combos = list(zip(order[:-1], order[1:])) if pairs == "neighbors" else list(itertools.combinations(order, 2))
254
+ rows = []
255
+ for a, b in combos:
256
+ x, y = R.loc[a].to_numpy(float), R.loc[b].to_numpy(float)
257
+ if test == "wilcoxon":
258
+ d = x - y
259
+ p = 1.0 if np.allclose(d, 0) else float(stats.wilcoxon(x, y, zero_method="wilcox").pvalue)
260
+ elif test == "mannwhitney":
261
+ p = float(stats.mannwhitneyu(x, y, alternative="two-sided").pvalue)
262
+ elif test == "ttest":
263
+ p = float(stats.ttest_ind(x, y).pvalue) if (np.std(x) + np.std(y)) > 0 else 1.0
264
+ else:
265
+ raise ValueError("test must be 'wilcoxon', 'mannwhitney' or 'ttest'")
266
+ rows.append({"A": a, "B": b, "mean_A": x.mean(), "mean_B": y.mean(), "p": p})
267
+ tab = pd.DataFrame(rows)
268
+ if correction and len(tab):
269
+ from .validation import _adjust
270
+
271
+ tab["p_adj"] = _adjust(tab["p"].to_numpy(), correction)
272
+ return tab
273
+
274
+
275
+ # ============================================================================ the framework
276
+ @dataclass
277
+ class FairComparison:
278
+ """Result of :func:`fair_comparison`."""
279
+
280
+ ranks: pd.DataFrame
281
+ consensus: pd.DataFrame
282
+ friedman: dict
283
+ pairwise: pd.DataFrame
284
+ kendall: pd.DataFrame
285
+ methods: pd.DataFrame
286
+ adjacent: tuple
287
+ zscores: pd.DataFrame
288
+ meta: dict = field(default_factory=dict)
289
+
290
+ @property
291
+ def order(self) -> list[str]:
292
+ return list(self.consensus.index)
293
+
294
+ def summary(self) -> str:
295
+ f = self.friedman
296
+ return (f"{len(self.ranks)} alternatives, {self.ranks.shape[1]} methods; Friedman chi2={f['chi2']:.2f} "
297
+ f"(df={f['df']}), p={f['p']:.3g}; Kendall W={f['W']:.3f}, mean Spearman={f['mean_spearman']:.3f}; "
298
+ f"best: {self.order[0]}")
299
+
300
+ def plot(self, axes=None, **kwargs):
301
+ from .viz import plot_fair_comparison
302
+
303
+ return plot_fair_comparison(self, axes=axes, **kwargs)
304
+
305
+ def __repr__(self) -> str:
306
+ return f"FairComparison({self.summary()})"
307
+
308
+
309
+ def fair_comparison(X, reference="mean", methods=DEFAULT_METHODS, extra=None, test: str = "wilcoxon",
310
+ pairs: str = "neighbors", correction: str | None = None, **kwargs) -> FairComparison:
311
+ """The consensus framework of Héberger (2026b) for a fair comparison of alternatives.
312
+
313
+ Parameters
314
+ ----------
315
+ X : array-like or DataFrame
316
+ Rows = criteria, columns = alternatives (the SRD orientation).
317
+ reference : str or array-like
318
+ Gold standard of the reference-based methods (SRD, DnE, DnM, CEpW,
319
+ WtpW); row means, maxima, minima or mixed rules as in :func:`srdkit.srd`.
320
+ methods : sequence of str
321
+ Any subset of ``("SRD", "DnE", "DnM", "HM", "CEpW", "WtpW", "PWR")``.
322
+ extra : DataFrame, optional
323
+ Further ranks (alternatives x methods, 1 = best), e.g. TOPSIS or VIKOR.
324
+ test, pairs, correction
325
+ Pairwise comparison of the alternatives (:func:`pairwise_alternatives`).
326
+ **kwargs
327
+ Passed to :func:`method_scores` (``directions``, ``value_scaling``, ``ties``...).
328
+
329
+ Returns
330
+ -------
331
+ FairComparison
332
+ ``ranks`` (alternatives x methods), ``consensus`` (mean rank, standard
333
+ deviation, consensus rank), ``friedman``, ``pairwise`` tests, ``kendall``
334
+ distances of the methods, ``methods`` (sum of Kendall distances,
335
+ leave-one-method-out displacement of the consensus, mean absolute
336
+ :math:`z`-score), ``adjacent`` (optimal axis order and its total) and
337
+ ``zscores``.
338
+ """
339
+ R = method_ranks(X, reference=reference, methods=methods, extra=extra, **kwargs)
340
+ m = R.shape[1]
341
+ if m > MAX_METHODS:
342
+ warnings.warn(f"{m} methods: more than {MAX_METHODS} methods are not recommended (rank degeneration)",
343
+ stacklevel=2)
344
+ mean, sd = R.mean(axis=1), R.std(axis=1, ddof=1)
345
+ cons = pd.DataFrame({"mean_rank": mean, "sd": sd, "min": R.min(axis=1), "max": R.max(axis=1)})
346
+ cons["consensus_rank"] = mean.rank(method="average")
347
+ cons = cons.sort_values(["mean_rank", "sd"], kind="stable")
348
+ fr = friedman_concordance(R)
349
+ pw = pairwise_alternatives(R, order=cons.index, pairs=pairs, test=test, correction=correction)
350
+ K = kendall_distance_matrix(R)
351
+ # leave-one-method-out: how far the consensus moves without the method
352
+ full = mean.rank(method="average")
353
+ lomo = {}
354
+ for c in R.columns:
355
+ r_wo = R.drop(columns=c).mean(axis=1).rank(method="average")
356
+ tau = stats.kendalltau(full, r_wo).statistic
357
+ lomo[c] = {"footrule": float(np.abs(full - r_wo).sum()), "kendall": (1 - (tau if np.isfinite(tau) else 1.0)) / 2}
358
+ sdz = sd.replace(0, np.nan)
359
+ Z = R.sub(mean, axis=0).div(sdz, axis=0).fillna(0.0)
360
+ meth = pd.DataFrame({"kendall_sum": K.sum(axis=1),
361
+ "lomo_footrule": pd.Series({c: v["footrule"] for c, v in lomo.items()}),
362
+ "lomo_kendall": pd.Series({c: v["kendall"] for c, v in lomo.items()}),
363
+ "mean_abs_z": Z.abs().mean(axis=0),
364
+ "share_abs_z_gt_2": (Z.abs() > 2).mean(axis=0)})
365
+ meth = meth.sort_values("kendall_sum", kind="stable")
366
+ adj = adjacent_order(R)
367
+ return FairComparison(ranks=R, consensus=cons, friedman=fr, pairwise=pw, kendall=K, methods=meth, adjacent=adj,
368
+ zscores=Z, meta={"reference": reference, "test": test, "pairs": pairs})
srdkit/fusion.py ADDED
@@ -0,0 +1,221 @@
1
+ r"""SRD as a data-fusion tool: model-merit fusion, consensus outlier detection, one-class decisions.
2
+
3
+ Model selection by fusing merits
4
+ --------------------------------
5
+ Kalivas, Héberger and Andries (2015) select the tuning parameter of a
6
+ calibration model (PLS latent variables, ridge parameter) by SRD without any
7
+ weighting of the merits. The rows of the matrix are model merits (RMSEC, RMSECV,
8
+ :math:`R^2`, the norm of the regression vector, jaggedness, or split-wise values of
9
+ a merit), the columns the candidate models; every row is scaled (to unit length
10
+ by default), the target of each row is its best value (row minimum for errors,
11
+ maximum for :math:`R^2`-type merits) and the model with the smallest SRD is
12
+ selected. Models whose cross-validated SRD values do not differ significantly form
13
+ an equivalent set. :func:`merit_fusion` implements the procedure.
14
+
15
+ Consensus outlier detection
16
+ ---------------------------
17
+ Brownfield and Kalivas (2017) evaluate many outlier measures (Hotelling's
18
+ :math:`T^2`, Q-residuals, studentized residuals, ...) across windows of tuning
19
+ parameters with SRD. :func:`consensus_outliers` ranks the samples by every
20
+ measure and scores each sample by the sum of its rank differences from the most
21
+ outlying rank (its SRD against the row-maximum profile); a null
22
+ distribution that accounts for the correlation of the measures decides which
23
+ samples are consistently outlying; optionally the analysis is repeated without
24
+ them (a masking check).
25
+
26
+ One-class classification
27
+ ------------------------
28
+ Lemos and Kalivas (2020) combine SRD with a receiver operating characteristic
29
+ (ROC) curve to set the decision threshold of one-class classification;
30
+ :func:`srd_roc` computes the curve, its area and the threshold maximizing
31
+ Youden's index from SRD values of target and non-target samples.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import numpy as np
37
+ import pandas as pd
38
+
39
+ from ._utils import as_frame
40
+ from .core import srd
41
+
42
+
43
+ def _scale_rows(M: pd.DataFrame, scaling: str) -> pd.DataFrame:
44
+ A = M.to_numpy(float)
45
+ if scaling == "unit":
46
+ nrm = np.sqrt((A ** 2).sum(axis=1, keepdims=True))
47
+ A = A / np.where(nrm > 0, nrm, 1.0)
48
+ elif scaling == "range":
49
+ lo, hi = A.min(axis=1, keepdims=True), A.max(axis=1, keepdims=True)
50
+ A = (A - lo) / np.where(hi > lo, hi - lo, 1.0)
51
+ elif scaling == "auto":
52
+ mu, sd = A.mean(axis=1, keepdims=True), A.std(axis=1, ddof=1, keepdims=True)
53
+ A = (A - mu) / np.where(sd > 0, sd, 1.0)
54
+ elif scaling in (None, "none"):
55
+ pass
56
+ else:
57
+ raise ValueError("scaling must be 'unit', 'range', 'auto' or None")
58
+ return pd.DataFrame(A, index=M.index, columns=M.columns)
59
+
60
+
61
+ def merit_fusion(merits, directions=None, scaling: str = "unit", cv: bool = True, n_folds: int = 7, alpha: float = 0.05,
62
+ random_state=0) -> dict:
63
+ """Select a model (or a set of equivalent models) by SRD fusion of model merits.
64
+
65
+ Parameters
66
+ ----------
67
+ merits : DataFrame
68
+ Rows = merits (or merit blocks, e.g. split-wise RMSECV values), columns =
69
+ candidate models (tuning parameter values).
70
+ directions : dict or list
71
+ ``"min"`` (default; errors, norms, roughness) or ``"max"`` (R^2-type) per row.
72
+ scaling : {"unit", "range", "auto", None}
73
+ Row scaling (unit length in the original paper).
74
+ cv : bool
75
+ Run the cross-validation and Wilcoxon tests to find the models equivalent to the best one.
76
+
77
+ Returns
78
+ -------
79
+ dict
80
+ ``srd`` (SRDResult), ``best`` (selected model), ``equivalent`` (models not
81
+ significantly different from the best), ``cv`` (CVResult or None).
82
+ """
83
+ M = as_frame(merits)
84
+ rows = list(M.index)
85
+ if directions is None:
86
+ dirs = ["min"] * len(rows)
87
+ elif isinstance(directions, dict):
88
+ dirs = [directions.get(r, "min") for r in rows]
89
+ else:
90
+ dirs = list(directions)
91
+ S = _scale_rows(M, scaling)
92
+ sign = np.array([1.0 if str(d).lower() == "min" else -1.0 for d in dirs])
93
+ S = S.mul(sign, axis=0) # every row: smaller is better, target = row minimum
94
+ res = srd(S, reference="min")
95
+ out = {"srd": res, "best": res.best, "equivalent": [res.best], "cv": None, "scaled": S}
96
+ if cv and S.shape[0] >= 4:
97
+ from .validation import cross_validate
98
+
99
+ cvr = cross_validate(S, reference="min", scheme="random", n_folds=n_folds, random_state=random_state)
100
+ best = res.best
101
+ eq = [best]
102
+ for c in res.order[1:]:
103
+ t = cvr.test(pairs=[(best, c)], alpha=alpha)
104
+ if not bool(t["significant"].iloc[0]):
105
+ eq.append(c)
106
+ out["cv"], out["equivalent"] = cvr, eq
107
+ return out
108
+
109
+
110
+ def _uniform_sum_null(n: int, K: int) -> np.ndarray:
111
+ """Exact distribution of the sum of K independent discrete uniforms on 0..n-1 (probabilities by value)."""
112
+ p = np.ones(n) / n
113
+ out = np.array([1.0])
114
+ for _ in range(K):
115
+ out = np.convolve(out, p)
116
+ return out
117
+
118
+
119
+ def consensus_outliers(measures, alpha: float = 0.05, correction: str | None = None, null: str = "correlated",
120
+ max_rounds: int = 1) -> dict:
121
+ r"""Consensus outlier detection by fusing many outlier measures with rank differences.
122
+
123
+ Following the idea of Brownfield and Kalivas (2017) — fuse many outlier
124
+ measures (across tuning windows) by their rank differences from the most
125
+ outlying value — every measure ranks the samples (1 = least, ``n`` = most
126
+ outlying) and every sample gets the sum of its rank differences from the top
127
+ rank, :math:`D_s=\sum_k (n-r_{sk})`, normalized by :math:`K(n-1)`. This is the
128
+ SRD of the sample's rank profile against the row-maximum profile. Small values
129
+ mean *consistently outlying*. Under the null hypothesis of exchangeable samples
130
+ every rank is uniform on :math:`1..n`; ``null="independent"`` uses the exact
131
+ convolution of discrete uniform distributions (valid for independent
132
+ measures, anti-conservative when they are positively correlated, as outlier
133
+ measures usually are), ``null="correlated"`` (default) a normal approximation
134
+ whose variance :math:`\frac{n^2-1}{12}\sum_{k,l}\rho_{kl}` accounts for the
135
+ rank correlations :math:`\rho_{kl}` of the measures (new). With
136
+ ``max_rounds > 1`` flagged samples are removed and the analysis is repeated
137
+ (masking check).
138
+
139
+ Parameters
140
+ ----------
141
+ measures : DataFrame
142
+ Rows = outlier measures, columns = samples; larger = more outlying in every row.
143
+ alpha : float
144
+ Error level; ``correction="bonferroni"`` divides it by the number of samples.
145
+ max_rounds : int
146
+ Number of rounds; with more than one round the flagged samples are removed
147
+ and the ranks recomputed (masking check). The test is exploratory: ranks
148
+ cannot express how far a sample lies, only how consistently it is on top.
149
+ """
150
+ from .ranking import rank_vector
151
+
152
+ M = as_frame(measures)
153
+ flagged, log, table = [], [], None
154
+ for rnd in range(max_rounds):
155
+ cur = [s for s in M.columns if s not in flagged]
156
+ n, K = len(cur), M.shape[0]
157
+ if n < 3:
158
+ break
159
+ R = np.vstack([rank_vector(M.loc[k, cur].to_numpy()) for k in M.index])
160
+ D = (n - R).sum(axis=0)
161
+ if null == "independent":
162
+ cdf = np.cumsum(_uniform_sum_null(n, K))
163
+ p = np.array([cdf[min(int(np.floor(d + 1e-9)), cdf.size - 1)] for d in D])
164
+ elif null == "correlated":
165
+ rho = np.corrcoef(R) if K > 1 else np.ones((1, 1))
166
+ var = (n * n - 1) / 12.0 * float(np.nansum(rho))
167
+ from scipy import stats
168
+
169
+ p = stats.norm.cdf(D + 0.5, loc=K * (n - 1) / 2.0, scale=np.sqrt(max(var, 1e-12)))
170
+ else:
171
+ raise ValueError("null must be 'correlated' or 'independent'")
172
+ a = alpha / n if correction == "bonferroni" else alpha
173
+ table = pd.DataFrame({"D": D, "D_norm": D / (K * (n - 1)), "p": p}, index=cur).sort_values("D")
174
+ new = list(table.index[table["p"] <= a])
175
+ if not new:
176
+ break
177
+ flagged += new
178
+ log += [(s, rnd) for s in new]
179
+ return {"outliers": flagged, "rounds": pd.DataFrame(log, columns=["sample", "round"]), "table": table}
180
+
181
+
182
+ def srd_roc(srd_target, srd_nontarget) -> dict:
183
+ """ROC curve of a one-class decision ``SRD <= threshold`` and the Youden-optimal threshold.
184
+
185
+ ``srd_target`` are SRD values of samples of the target class (expected small),
186
+ ``srd_nontarget`` those of other samples.
187
+ """
188
+ t = np.asarray(srd_target, float)
189
+ f = np.asarray(srd_nontarget, float)
190
+ thr = np.unique(np.concatenate([t, f, [-np.inf, np.inf]]))
191
+ tpr = np.array([(t <= h).mean() for h in thr])
192
+ fpr = np.array([(f <= h).mean() for h in thr])
193
+ order = np.argsort(fpr, kind="stable")
194
+ x, yv = fpr[order], tpr[order]
195
+ auc = float(np.sum(np.diff(x) * (yv[1:] + yv[:-1]) / 2))
196
+ j = tpr - fpr
197
+ k = int(np.argmax(j))
198
+ return {"thresholds": thr, "tpr": tpr, "fpr": fpr, "auc": auc, "threshold": float(thr[k]), "youden": float(j[k]),
199
+ "sensitivity": float(tpr[k]), "specificity": float(1 - fpr[k])}
200
+
201
+
202
+ def merits_from_cv(predictions: dict, y, extra: dict | None = None) -> pd.DataFrame:
203
+ """Build a merit table (rows = merits, columns = models) from cross-validated predictions.
204
+
205
+ ``predictions`` maps model names to arrays of predicted values of ``y``; RMSE,
206
+ MAE, bias, the largest absolute error and ``1 - R^2`` are computed (all to be
207
+ minimized). ``extra`` adds rows ``{merit: {model: value}}``.
208
+ """
209
+ y = np.asarray(y, float)
210
+ rows = {}
211
+ for name, p in predictions.items():
212
+ p = np.asarray(p, float)
213
+ e = p - y
214
+ ss = ((y - y.mean()) ** 2).sum()
215
+ rows[name] = {"RMSE": np.sqrt((e ** 2).mean()), "MAE": np.abs(e).mean(), "|bias|": abs(e.mean()),
216
+ "MaxAE": np.abs(e).max(), "1-R2": (e ** 2).sum() / ss if ss > 0 else np.nan}
217
+ M = pd.DataFrame(rows)
218
+ if extra:
219
+ for k, v in extra.items():
220
+ M.loc[k] = pd.Series(v)
221
+ return M