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/reference.py ADDED
@@ -0,0 +1,232 @@
1
+ r"""Reference (gold standard, benchmark) construction.
2
+
3
+ SRD measures every solution against a reference vector :math:`\mathbf{y}`. When
4
+ a known standard exists (a certified value, a measured property, the true class
5
+ of a sample) it is passed as an external vector. Otherwise the reference is
6
+ *fused* from the data row by row (Héberger, 2010; Héberger and Kollár-Hunek,
7
+ 2019): the row mean (random errors cancel), the row median (robust to
8
+ outliers), the row minimum (errors, residuals, PRESS) or maximum (accuracies,
9
+ correlation coefficients), or a different rule for every row (``"mixed"``).
10
+
11
+ Beyond the classical rules this module offers
12
+
13
+ * rank aggregates: the Borda (mean-rank) reference, the footrule-optimal
14
+ consensus ranking computed exactly as a linear assignment problem (Dwork et al.,
15
+ 2001), and the Kemeny (Kendall-optimal) consensus (exact dynamic programming over
16
+ subsets for :math:`n\le 16` objects, local search above);
17
+ * a first-principal-component reference;
18
+ * leave-one-out (jackknife) references: the reference of solution :math:`j` is
19
+ fused from the other solutions only, which removes the self-influence of a
20
+ solution on a reference built with its own participation.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import itertools
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+ from scipy.optimize import linear_sum_assignment
30
+
31
+ from ._utils import as_frame
32
+ from .ranking import rank_matrix
33
+
34
+ ROW_RULES = ("mean", "median", "min", "max")
35
+ REFERENCE_METHODS = ROW_RULES + ("mixed", "trimmed", "weighted", "geometric", "borda", "consensus", "footrule",
36
+ "kemeny", "pc1", "loo-mean", "loo-median", "loo-min", "loo-max")
37
+
38
+
39
+ def _row_rule(a: np.ndarray, rule: str) -> np.ndarray:
40
+ if rule == "mean":
41
+ return a.mean(axis=1)
42
+ if rule == "median":
43
+ return np.median(a, axis=1)
44
+ if rule == "min":
45
+ return a.min(axis=1)
46
+ if rule == "max":
47
+ return a.max(axis=1)
48
+ raise ValueError(f"unknown row rule {rule!r}; use one of {ROW_RULES}")
49
+
50
+
51
+ def footrule_consensus(R) -> np.ndarray:
52
+ r"""Footrule-optimal consensus ranking of the columns of a rank matrix.
53
+
54
+ The ranking :math:`\pi` minimizing :math:`\sum_j\sum_i |r_{ij}-\pi_i|` is the
55
+ optimal assignment of objects to positions with cost
56
+ :math:`c_{ip}=\sum_j |r_{ij}-p|` (Dwork, Kumar, Naor and Sivakumar, 2001); it is
57
+ solved exactly by the Hungarian algorithm. Returns ranks ``1..n``.
58
+
59
+ >>> footrule_consensus(np.array([[1, 1, 2], [2, 3, 1], [3, 2, 3]])).tolist()
60
+ [1.0, 2.0, 3.0]
61
+ """
62
+ R = np.asarray(R, dtype=float)
63
+ n = R.shape[0]
64
+ pos = np.arange(1, n + 1, dtype=float)
65
+ cost = np.abs(R[:, :, None] - pos[None, None, :]).sum(axis=1)
66
+ rows, cols = linear_sum_assignment(cost)
67
+ out = np.empty(n)
68
+ out[rows] = pos[cols]
69
+ return out
70
+
71
+
72
+ def _pairwise_preference(R: np.ndarray) -> np.ndarray:
73
+ """P[a, b] = number of columns ranking a before b (ties count 1/2)."""
74
+ d = R[:, None, :] - R[None, :, :]
75
+ return (d < 0).sum(axis=2) + 0.5 * (d == 0).sum(axis=2) - 0.5 * R.shape[1] * np.eye(R.shape[0])
76
+
77
+
78
+ def kemeny_consensus(R, method: str = "auto", max_exact: int = 16) -> np.ndarray:
79
+ r"""Kemeny (Kendall-distance optimal) consensus ranking of the columns of ``R``.
80
+
81
+ ``method="exact"`` solves the problem by dynamic programming over subsets
82
+ (:math:`O(2^n n^2)`), ``"local"`` starts from the Borda order and improves it
83
+ by insertion moves until a local optimum. ``"auto"`` is exact for
84
+ :math:`n\le` ``max_exact``. Returns ranks ``1..n`` (1 = first).
85
+ """
86
+ R = np.asarray(R, dtype=float)
87
+ n = R.shape[0]
88
+ P = _pairwise_preference(R)
89
+ if method == "auto":
90
+ method = "exact" if n <= max_exact else "local"
91
+ if method == "exact":
92
+ full = (1 << n) - 1
93
+ best = np.full(1 << n, np.inf)
94
+ choice = np.zeros(1 << n, dtype=int)
95
+ best[0] = 0.0
96
+ # cost of putting object a right after the set S: disagreements with objects not in S
97
+ for S in range(1 << n):
98
+ if not np.isfinite(best[S]):
99
+ continue
100
+ rest = [b for b in range(n) if not (S >> b) & 1]
101
+ for a in rest:
102
+ c = best[S] + sum(P[b, a] for b in rest if b != a)
103
+ T = S | (1 << a)
104
+ if c < best[T] - 1e-12:
105
+ best[T] = c
106
+ choice[T] = a
107
+ order, S = [], full
108
+ while S:
109
+ a = choice[S]
110
+ order.append(a)
111
+ S &= ~(1 << a)
112
+ order = order[::-1]
113
+ elif method == "local":
114
+ order = list(np.argsort(R.mean(axis=1), kind="stable"))
115
+
116
+ def cost(o):
117
+ return sum(P[o[j], o[i]] for i in range(n) for j in range(i + 1, n))
118
+
119
+ cur = cost(order)
120
+ improved = True
121
+ while improved:
122
+ improved = False
123
+ for i, j in itertools.permutations(range(n), 2):
124
+ o = order[:]
125
+ a = o.pop(i)
126
+ o.insert(j, a)
127
+ c = cost(o)
128
+ if c < cur - 1e-12:
129
+ order, cur, improved = o, c, True
130
+ break
131
+ else:
132
+ raise ValueError("method must be 'auto', 'exact' or 'local'")
133
+ ranks = np.empty(n)
134
+ ranks[np.asarray(order)] = np.arange(1, n + 1)
135
+ return ranks
136
+
137
+
138
+ def make_reference(X, method="mean", *, weights=None, row_methods=None, trim: float = 0.1, ties: str = "average") -> np.ndarray:
139
+ r"""Build the reference vector (or one reference per column for ``"loo-*"``).
140
+
141
+ Parameters
142
+ ----------
143
+ X : array-like or DataFrame, shape (n_objects, n_solutions)
144
+ The input matrix (without the reference column).
145
+ method : str, callable or array-like
146
+ ``"mean"``, ``"median"``, ``"min"``, ``"max"`` (row rules);
147
+ ``"mixed"`` (a row rule per row given in ``row_methods``);
148
+ ``"trimmed"`` (trimmed mean, ``trim`` fraction cut at both ends);
149
+ ``"weighted"`` (weighted mean with ``weights``); ``"geometric"``;
150
+ ``"borda"`` (mean rank); ``"consensus"``/``"footrule"`` (footrule-optimal
151
+ consensus ranking); ``"kemeny"``; ``"pc1"`` (first principal component of
152
+ the standardized columns, oriented to correlate positively with the mean);
153
+ ``"loo-mean"``, ``"loo-median"``, ``"loo-min"``, ``"loo-max"`` (leave-one-out,
154
+ returns an ``(n, m)`` matrix); a callable applied to every row; or an
155
+ external vector of length ``n``.
156
+
157
+ Returns
158
+ -------
159
+ numpy.ndarray of shape (n,) or (n, m)
160
+
161
+ Examples
162
+ --------
163
+ >>> X = np.array([[1., 2.], [3., 5.], [2., 2.]])
164
+ >>> make_reference(X, "mean").tolist()
165
+ [1.5, 4.0, 2.0]
166
+ >>> make_reference(X, "mixed", row_methods=["min", "max", "mean"]).tolist()
167
+ [1.0, 5.0, 2.0]
168
+ """
169
+ df = as_frame(X)
170
+ a = df.to_numpy(dtype=float)
171
+ n, m = a.shape
172
+ if callable(method):
173
+ return np.asarray([method(row) for row in a], dtype=float)
174
+ if not isinstance(method, str):
175
+ ref = np.asarray(method, dtype=float).ravel()
176
+ if ref.size != n:
177
+ raise ValueError(f"external reference must have {n} elements, got {ref.size}")
178
+ return ref
179
+ method = method.lower()
180
+ if method in ROW_RULES:
181
+ return _row_rule(a, method)
182
+ if method == "mixed":
183
+ if row_methods is None or len(row_methods) != n:
184
+ raise ValueError("'mixed' needs row_methods with one rule per row")
185
+ return np.asarray([_row_rule(a[i:i + 1], str(r).lower())[0] for i, r in enumerate(row_methods)])
186
+ if method == "trimmed":
187
+ from scipy.stats import trim_mean
188
+
189
+ return np.asarray(trim_mean(a, trim, axis=1), dtype=float)
190
+ if method == "weighted":
191
+ w = np.ones(m) if weights is None else np.asarray(weights, dtype=float)
192
+ if w.size != m:
193
+ raise ValueError("one weight per column is required")
194
+ return a @ (w / w.sum())
195
+ if method == "geometric":
196
+ if (a <= 0).any():
197
+ raise ValueError("the geometric mean needs positive data")
198
+ return np.exp(np.log(a).mean(axis=1))
199
+ if method in ("borda", "consensus", "footrule", "kemeny"):
200
+ R = rank_matrix(df, ties=ties).to_numpy()
201
+ if method == "borda":
202
+ return R.mean(axis=1)
203
+ if method == "kemeny":
204
+ return kemeny_consensus(R)
205
+ return footrule_consensus(R)
206
+ if method == "pc1":
207
+ z = (a - a.mean(axis=0)) / np.where(a.std(axis=0, ddof=1) > 0, a.std(axis=0, ddof=1), 1.0)
208
+ u, s, vt = np.linalg.svd(z, full_matrices=False)
209
+ score = u[:, 0] * s[0]
210
+ if np.corrcoef(score, z.mean(axis=1))[0, 1] < 0:
211
+ score = -score
212
+ return score
213
+ if method.startswith("loo-"):
214
+ rule = method[4:]
215
+ if m < 2:
216
+ raise ValueError("leave-one-out references need at least two solutions")
217
+ out = np.empty((n, m))
218
+ for j in range(m):
219
+ out[:, j] = _row_rule(np.delete(a, j, axis=1), rule)
220
+ return out
221
+ raise ValueError(f"unknown reference method {method!r}; available: {REFERENCE_METHODS}")
222
+
223
+
224
+ def reference_name(method) -> str:
225
+ """A short label of a reference specification (used in tables and plots)."""
226
+ if callable(method):
227
+ return getattr(method, "__name__", "custom")
228
+ if isinstance(method, str):
229
+ return method
230
+ if isinstance(method, pd.Series) and method.name is not None:
231
+ return str(method.name)
232
+ return "external"
srdkit/report.py ADDED
@@ -0,0 +1,114 @@
1
+ r"""One-call SRD analysis and report.
2
+
3
+ :func:`analyze` runs the complete SRD procedure — SRD values, the exact
4
+ randomization test, cross-validation with paired tests, the compact letter
5
+ display of indistinguishable solutions and optional diagnostics — and returns an
6
+ :class:`SRDReport` that can be printed, exported to Markdown or HTML, or plotted.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+
13
+ import numpy as np
14
+ import pandas as pd
15
+
16
+ from .core import SRDResult, srd
17
+ from .validation import CRRNResult, CVResult, cross_validate, crrn
18
+
19
+
20
+ def summarize(result: SRDResult, crrn_result: CRRNResult | None = None, cv: CVResult | None = None, test: str = "wilcoxon",
21
+ alpha: float = 0.05) -> pd.DataFrame:
22
+ """Summary table: SRD, SRD%, CRRN probabilities and verdict, CV median and IQR, group letters."""
23
+ tab = result.to_frame()
24
+ if crrn_result is not None:
25
+ tab = tab.join(crrn_result.table[["p_lower", "p_upper", "verdict"]])
26
+ if cv is not None:
27
+ s = cv.summary()
28
+ tab["CV_median%"] = 100 * s["median"]
29
+ tab["CV_IQR%"] = 100 * (s["Q3"] - s["Q1"])
30
+ if len(result.srd) >= 2 and cv.n_folds >= 5:
31
+ try:
32
+ tab["group"] = cv.groups(test=test, alpha=alpha)
33
+ except ValueError:
34
+ pass
35
+ return tab
36
+
37
+
38
+ @dataclass
39
+ class SRDReport:
40
+ """Everything an SRD analysis produces (see :func:`analyze`)."""
41
+
42
+ result: SRDResult
43
+ crrn: CRRNResult
44
+ cv: CVResult | None
45
+ table: pd.DataFrame
46
+ tests: pd.DataFrame | None = None
47
+ extras: dict = field(default_factory=dict)
48
+
49
+ def to_markdown(self, digits: int = 3) -> str:
50
+ """The summary table and the tests as Markdown (no extra dependency)."""
51
+ lines = [f"## SRD analysis (n = {self.result.n} objects, m = {len(self.result.srd)} solutions, "
52
+ f"reference = {self.result.reference_method})", ""]
53
+ p = self.crrn.percentiles
54
+ lines.append(f"Random-ranking limits (normalized): XX1 = {p['XX1']:.3f}, Med = {p['Med']:.3f}, XX19 = {p['XX19']:.3f}")
55
+ lines.append("")
56
+ lines += _md_table(self.table.reset_index(), digits)
57
+ if self.tests is not None and len(self.tests):
58
+ lines += ["", f"Paired tests ({self.tests.attrs.get('test', '')}):", ""]
59
+ lines += _md_table(self.tests, digits)
60
+ return "\n".join(lines)
61
+
62
+ def to_html(self, digits: int = 3) -> str:
63
+ head = f"<h2>SRD analysis</h2><p>n = {self.result.n}, reference = {self.result.reference_method}</p>"
64
+ body = self.table.round(digits).to_html()
65
+ tests = self.tests.round(digits).to_html(index=False) if self.tests is not None else ""
66
+ return head + body + tests
67
+
68
+ def plot(self, **kwargs):
69
+ from .viz import plot_report
70
+
71
+ return plot_report(self, **kwargs)
72
+
73
+ def __repr__(self) -> str:
74
+ return self.to_markdown()
75
+
76
+
77
+ def _md_table(df: pd.DataFrame, digits: int) -> list[str]:
78
+ def fmt(v):
79
+ if isinstance(v, (float, np.floating)):
80
+ return f"{v:.{digits}g}" if abs(v) < 1e-3 and v != 0 else f"{v:.{digits}f}"
81
+ return str(v)
82
+
83
+ cols = list(df.columns)
84
+ out = ["| " + " | ".join(map(str, cols)) + " |", "|" + "|".join("---" for _ in cols) + "|"]
85
+ for _, row in df.iterrows():
86
+ out.append("| " + " | ".join(fmt(row[c]) for c in cols) + " |")
87
+ return out
88
+
89
+
90
+ def analyze(X, reference="mean", ties: str = "average", alpha: float = 0.05, cv_scheme: str = "random", n_folds: int = 8,
91
+ test: str = "wilcoxon", diagnostics: bool = False, random_state=0, **srd_kwargs) -> SRDReport:
92
+ """The complete SRD procedure in one call.
93
+
94
+ Wilcoxon tests with eight random folds are the default, the variant found most
95
+ effective overall by Sziklai, Baranyi and Héberger (2025).
96
+ """
97
+ res = srd(X, reference=reference, ties=ties, **srd_kwargs)
98
+ val = crrn(res, alpha=alpha)
99
+ cv = None
100
+ tests = None
101
+ if res.n >= 5:
102
+ scheme_folds = 5 if cv_scheme == "5x2" else n_folds
103
+ cv = cross_validate(res.data, reference=res.meta.get("reference_spec", reference), scheme=cv_scheme,
104
+ n_folds=scheme_folds, ties=ties, random_state=random_state, **srd_kwargs)
105
+ if len(res.srd) >= 2:
106
+ tests = cv.test(test=test, pairs="consecutive", alpha=alpha)
107
+ table = summarize(res, val, cv, test=test, alpha=alpha)
108
+ extras = {}
109
+ if diagnostics:
110
+ from .diagnostics import object_influence, reference_sensitivity
111
+
112
+ extras["influence"] = object_influence(res.data, reference=res.meta.get("reference_spec", reference), ties=ties)
113
+ extras["references"] = reference_sensitivity(res.data, ties=ties)
114
+ return SRDReport(result=res, crrn=val, cv=cv, table=table, tests=tests, extras=extras)
@@ -0,0 +1,127 @@
1
+ r"""Representations of SRD results: maps, constellations and profiles.
2
+
3
+ SRD values are distances, and a set of solutions together with the reference
4
+ forms a finite metric space (the footrule is a metric on rankings). Three
5
+ representations make that space visible:
6
+
7
+ * the **SRD map** (:func:`srd_map`): classical multidimensional scaling of the
8
+ pairwise SRD matrix including the reference; distances on the map approximate
9
+ the SRD values between any two solutions;
10
+ * the **SRD constellation** (:func:`constellation`): a polar layout in which the
11
+ reference sits at the origin and every solution at its *exact* normalized SRD
12
+ from the reference (the radius); the angles are the deviation angles of
13
+ Ipkovich, Héberger and Abonyi (2021), measured from the best solution and signed
14
+ so that the planar distances reproduce the pairwise SRD values as well as
15
+ possible. Unlike the one-dimensional SRD plot it separates solutions that are
16
+ equally far from the reference but far from each other;
17
+ * the **rank profile** (:func:`rank_profile`): a long table of the ranks of every
18
+ object in the reference and in every solution, the input of bump (slope) charts.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import numpy as np
24
+ import pandas as pd
25
+
26
+ from ._utils import as_frame
27
+ from .core import pairwise_srd, srd
28
+ from .parcoord import deviation_angle
29
+
30
+
31
+ def classical_mds(D, n_components: int = 2) -> tuple[np.ndarray, np.ndarray]:
32
+ """Classical (Torgerson) MDS of a distance matrix; coordinates and eigenvalues."""
33
+ D = np.asarray(D, float)
34
+ m = D.shape[0]
35
+ J = np.eye(m) - 1.0 / m
36
+ B = -0.5 * J @ (D ** 2) @ J
37
+ w, V = np.linalg.eigh(B)
38
+ idx = np.argsort(w)[::-1]
39
+ w, V = w[idx], V[:, idx]
40
+ X = V[:, :n_components] * np.sqrt(np.clip(w[:n_components], 0, None))
41
+ return X, w
42
+
43
+
44
+ def srd_map(X, reference="mean", ties: str = "average", n_components: int = 2, distance="footrule") -> pd.DataFrame:
45
+ """Classical MDS map of the solutions and the reference (columns ``dim1``, ``dim2``; the reference is centred).
46
+
47
+ The table has the attribute ``stress`` (Kruskal stress-1 of the embedding) in ``.attrs``.
48
+ """
49
+ D = pairwise_srd(X, ties=ties, reference=reference, distance=distance)
50
+ Y, w = classical_mds(D.to_numpy(), n_components)
51
+ Y = Y - Y[0] # reference at the origin
52
+ out = pd.DataFrame(Y, index=D.index, columns=[f"dim{k + 1}" for k in range(n_components)])
53
+ De = np.sqrt(((Y[:, None, :] - Y[None, :, :]) ** 2).sum(axis=2))
54
+ Dm = D.to_numpy()
55
+ out.attrs["stress"] = float(np.sqrt(((Dm - De) ** 2).sum() / max((Dm ** 2).sum(), 1e-300)))
56
+ out.attrs["explained"] = float(np.clip(w[:n_components], 0, None).sum() / np.clip(w, 0, None).sum())
57
+ return out
58
+
59
+
60
+ def constellation(X, reference="mean", ties: str = "average", anchor: str | None = None) -> pd.DataFrame:
61
+ """Polar SRD constellation: radius = normalized SRD from the reference, angle = signed deviation angle.
62
+
63
+ Returns a table with ``radius``, ``angle`` (degrees), ``x`` and ``y``; the
64
+ reference is the origin. ``anchor`` (default: the best solution with a positive
65
+ SRD; solutions identical to the reference sit at the origin) lies on the
66
+ positive x axis. Solutions are placed in increasing SRD; the sign of each angle
67
+ is the one whose planar distances to the already placed solutions match their
68
+ SRD values better.
69
+ """
70
+ D = pairwise_srd(X, ties=ties, reference=reference)
71
+ s0 = D.loc["reference"].drop("reference").sort_values(kind="stable")
72
+ names = list(s0.index)
73
+ nonzero = [c for c in names if s0[c] > 0]
74
+ a = anchor or (nonzero[0] if nonzero else names[0])
75
+ order = [a] + [c for c in names if c != a]
76
+ placed: dict[str, np.ndarray] = {}
77
+ rows = []
78
+ for c in order:
79
+ r = float(s0[c])
80
+ if c == a:
81
+ ang = 0.0
82
+ else:
83
+ ang = deviation_angle(s0[c], s0[a], D.loc[c, a]) if s0[a] > 0 and r > 0 else 0.0
84
+ ang = 0.0 if not np.isfinite(ang) else ang
85
+ best_err, best_sign = np.inf, 1.0
86
+ for sign in (1.0, -1.0):
87
+ p = r * np.array([np.cos(np.radians(sign * ang)), np.sin(np.radians(sign * ang))])
88
+ err = sum((np.linalg.norm(p - q) - D.loc[c, k]) ** 2 for k, q in placed.items())
89
+ if err < best_err - 1e-15:
90
+ best_err, best_sign = err, sign
91
+ ang *= best_sign
92
+ p = r * np.array([np.cos(np.radians(ang)), np.sin(np.radians(ang))])
93
+ placed[c] = p
94
+ rows.append({"solution": c, "radius": r, "angle": ang, "x": p[0], "y": p[1]})
95
+ out = pd.DataFrame(rows).set_index("solution")
96
+ pts = out[["x", "y"]].to_numpy()
97
+ De = np.sqrt(((pts[:, None] - pts[None]) ** 2).sum(axis=2))
98
+ Dm = D.loc[out.index, out.index].to_numpy()
99
+ out.attrs["stress"] = float(np.sqrt(((Dm - De) ** 2).sum() / max((Dm ** 2).sum(), 1e-300)))
100
+ return out
101
+
102
+
103
+ def rank_profile(X, reference="mean", ties: str = "average") -> pd.DataFrame:
104
+ """Long table (object, solution, rank, reference rank, difference) for bump charts and further analysis."""
105
+ res = srd(X, reference=reference, ties=ties)
106
+ q = res.reference_ranks if res.reference_ranks.ndim == 1 else res.reference_ranks[:, 0]
107
+ long = res.ranks.copy()
108
+ long["__reference__"] = q
109
+ out = long.reset_index(names="object").melt(id_vars="object", var_name="solution", value_name="rank")
110
+ qmap = dict(zip(res.ranks.index, q))
111
+ out["reference_rank"] = out["object"].map(qmap)
112
+ out["difference"] = out["rank"] - out["reference_rank"]
113
+ return out
114
+
115
+
116
+ def soft_srd(X, reference="mean", sigma: float = 0.05, **kwargs):
117
+ """SRD on soft ranks (expected ranks under Gaussian error with relative standard deviation ``sigma``)."""
118
+ return srd(X, reference=reference, soft_sigma=sigma, **kwargs)
119
+
120
+
121
+ def srd_fingerprint(X, reference="mean", ties: str = "average", normalize: bool = True) -> pd.DataFrame:
122
+ """Per-object contribution profile of every solution (objects x solutions), optionally as shares of SRD."""
123
+ res = srd(as_frame(X), reference=reference, ties=ties)
124
+ C = res.contributions
125
+ if normalize:
126
+ C = C / C.sum(axis=0).replace(0, np.nan)
127
+ return C