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/segmentation.py ADDED
@@ -0,0 +1,247 @@
1
+ r"""Segmentation with SRD: regimes of ranking sequences and range-dependent agreement.
2
+
3
+ Two segmentation problems arise naturally around SRD and are solved here
4
+ exactly by dynamic programming over contiguous segments (Bellman's optimal
5
+ partition, :math:`O(KT^2)` segment evaluations):
6
+
7
+ **Regimes of a ranking sequence.** When the same :math:`n` objects are ranked at
8
+ :math:`T` consecutive times (league tables, yearly indicators, process states),
9
+ the sequence splits into periods in which the ranking is stable. The cost of a
10
+ segment is the summed SRD (footrule) of its rankings from the segment's
11
+ footrule-optimal consensus; this consensus is computed exactly as an assignment
12
+ problem whose cost matrix is a difference of prefix sums, so every segment costs
13
+ one Hungarian solve. The number of segments is chosen by a permutation test on
14
+ the cost reduction (the time order is shuffled) or given by the user.
15
+ :func:`change_score` gives a quick profile: the SRD between the consensus of a
16
+ window before and after every time point.
17
+
18
+ **Range-dependent agreement.** A method may follow the reference well for small
19
+ values and fail for large ones. Sorting the objects by the reference turns the
20
+ contributions :math:`|r_{ij}-q_i|` into a signal; its optimal piecewise-constant
21
+ segmentation (:func:`displacement_segmentation`) and the sliding-window SRD
22
+ (:func:`local_srd_profile`) show *where* in the range a solution departs from
23
+ the reference.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from dataclasses import dataclass, field
29
+
30
+ import numpy as np
31
+ import pandas as pd
32
+ from scipy.optimize import linear_sum_assignment
33
+
34
+ from ._utils import as_frame, as_rng, srd_max
35
+ from .ranking import rank_matrix, rank_vector
36
+ from .reference import make_reference
37
+
38
+
39
+ # --------------------------------------------------------------------------- generic optimal partition
40
+ def optimal_partition(C: np.ndarray, n_segments: int, min_size: int = 1) -> tuple[list[int], float]:
41
+ """Exact optimal partition of ``0..T`` into ``n_segments`` contiguous segments.
42
+
43
+ ``C[a, b]`` is the cost of the segment ``[a, b)`` (``inf`` where not allowed).
44
+ Returns the boundaries ``[0, b1, ..., T]`` and the total cost.
45
+ """
46
+ T = C.shape[0] - 1
47
+ K = int(n_segments)
48
+ F = np.full((K + 1, T + 1), np.inf)
49
+ arg = np.zeros((K + 1, T + 1), dtype=int)
50
+ F[0, 0] = 0.0
51
+ for k in range(1, K + 1):
52
+ for b in range(k * min_size, T + 1):
53
+ a = np.arange((k - 1) * min_size, b - min_size + 1)
54
+ if a.size == 0:
55
+ continue
56
+ vals = F[k - 1, a] + C[a, b]
57
+ j = int(np.argmin(vals))
58
+ F[k, b], arg[k, b] = vals[j], a[j]
59
+ bounds = [T]
60
+ for k in range(K, 0, -1):
61
+ bounds.append(arg[k, bounds[-1]])
62
+ return bounds[::-1], float(F[K, T])
63
+
64
+
65
+ # --------------------------------------------------------------------------- ranking sequences
66
+ def _rank_rows(seq, ascending=True) -> np.ndarray:
67
+ A = np.asarray(seq, float)
68
+ return np.vstack([rank_vector(row, ascending=ascending) for row in A])
69
+
70
+
71
+ def segment_costs(R: np.ndarray, consensus: str = "footrule", min_size: int = 1) -> np.ndarray:
72
+ """Cost matrix ``C[a, b]`` = summed footrule of the rankings ``R[a:b]`` from their consensus."""
73
+ T, n = R.shape
74
+ pos = np.arange(1, n + 1, dtype=float)
75
+ # prefix sums of the assignment cost |r_ti - p| and of the ranks
76
+ D = np.abs(R[:, :, None] - pos[None, None, :])
77
+ cum = np.concatenate([np.zeros((1, n, n)), np.cumsum(D, axis=0)])
78
+ cumr = np.concatenate([np.zeros((1, n)), np.cumsum(R, axis=0)])
79
+ C = np.full((T + 1, T + 1), np.inf)
80
+ for a in range(T):
81
+ for b in range(a + min_size, T + 1):
82
+ M = cum[b] - cum[a]
83
+ if consensus == "footrule":
84
+ i, p = linear_sum_assignment(M)
85
+ C[a, b] = M[i, p].sum()
86
+ elif consensus == "borda":
87
+ q = rank_vector((cumr[b] - cumr[a]) / (b - a))
88
+ C[a, b] = np.abs(R[a:b] - q[None, :]).sum()
89
+ else:
90
+ raise ValueError("consensus must be 'footrule' or 'borda'")
91
+ return C
92
+
93
+
94
+ @dataclass
95
+ class RankingSegmentation:
96
+ """Result of :func:`segment_rankings`."""
97
+
98
+ boundaries: list
99
+ segments: list
100
+ consensus: pd.DataFrame
101
+ cost_curve: pd.Series
102
+ within_srd: pd.Series
103
+ n_segments: int
104
+ meta: dict = field(default_factory=dict)
105
+
106
+ @property
107
+ def change_points(self) -> list:
108
+ """Indices of the first time point of every segment after the first."""
109
+ return list(self.boundaries[1:-1])
110
+
111
+
112
+ def segment_rankings(seq, n_segments: int | None = None, max_segments: int = 8, min_size: int = 2,
113
+ consensus: str = "footrule", ascending: bool = True, n_perm: int = 19, alpha: float = 0.05,
114
+ random_state=0, index=None, objects=None) -> RankingSegmentation:
115
+ """Optimal segmentation of a sequence of rankings into stable regimes.
116
+
117
+ Parameters
118
+ ----------
119
+ seq : array-like, shape (T, n)
120
+ Row ``t`` holds the scores (or ranks) of the ``n`` objects at time ``t``;
121
+ every row is ranked.
122
+ n_segments : int, optional
123
+ Number of segments; selected by a permutation test when ``None``: the
124
+ largest ``K`` whose cost reduction over ``K-1`` exceeds the ``1-alpha``
125
+ quantile of the reductions obtained after shuffling the time order.
126
+ consensus : {"footrule", "borda"}
127
+ Segment consensus (exact footrule median or mean-rank).
128
+ """
129
+ A = np.asarray(seq, float)
130
+ T, n = A.shape
131
+ R = _rank_rows(A, ascending)
132
+ C = segment_costs(R, consensus, min_size)
133
+ Kmax = max(1, min(max_segments, T // min_size))
134
+ costs = [optimal_partition(C, k, min_size)[1] for k in range(1, Kmax + 1)]
135
+ if n_segments is None:
136
+ rng = as_rng(random_state)
137
+ gains = np.zeros((n_perm, Kmax))
138
+ for p in range(n_perm):
139
+ Rp = R[rng.permutation(T)]
140
+ Cp = segment_costs(Rp, consensus, min_size)
141
+ cp = [optimal_partition(Cp, k, min_size)[1] for k in range(1, Kmax + 1)]
142
+ gains[p, 1:] = -np.diff(cp)
143
+ obs = np.concatenate([[0.0], -np.diff(costs)])
144
+ thr = np.quantile(gains, 1 - alpha, axis=0)
145
+ K = 1
146
+ for k in range(2, Kmax + 1):
147
+ if obs[k - 1] > thr[k - 1]:
148
+ K = k
149
+ else:
150
+ break
151
+ else:
152
+ K = int(n_segments)
153
+ bounds, _ = optimal_partition(C, K, min_size)
154
+ segs = list(zip(bounds[:-1], bounds[1:]))
155
+ pos = np.arange(1, n + 1, dtype=float)
156
+ cons, within = {}, {}
157
+ for a, b in segs:
158
+ M = np.abs(R[a:b, :, None] - pos[None, None, :]).sum(axis=0)
159
+ i, p = linear_sum_assignment(M)
160
+ q = np.empty(n)
161
+ q[i] = pos[p]
162
+ cons[f"{a}-{b - 1}"] = q
163
+ within[f"{a}-{b - 1}"] = float(np.abs(R[a:b] - q[None, :]).sum(axis=1).mean() / srd_max(n))
164
+ obj = objects if objects is not None else [f"o{i + 1}" for i in range(n)]
165
+ tidx = list(index) if index is not None else list(range(T))
166
+ return RankingSegmentation(boundaries=[int(b) for b in bounds], segments=[(tidx[a], tidx[b - 1]) for a, b in segs],
167
+ consensus=pd.DataFrame(cons, index=obj), cost_curve=pd.Series(costs, index=range(1, Kmax + 1)),
168
+ within_srd=pd.Series(within), n_segments=K, meta={"ranks": R, "time": tidx})
169
+
170
+
171
+ def change_score(seq, window: int = 5, ascending: bool = True) -> pd.Series:
172
+ """Normalized SRD between the mean-rank consensus of ``window`` rankings before and after every time point."""
173
+ R = _rank_rows(seq, ascending)
174
+ T, n = R.shape
175
+ out = np.full(T, np.nan)
176
+ for t in range(window, T - window + 1):
177
+ left = rank_vector(R[t - window:t].mean(axis=0))
178
+ right = rank_vector(R[t:t + window].mean(axis=0))
179
+ out[t] = np.abs(left - right).sum() / srd_max(n)
180
+ return pd.Series(out, name="change_score")
181
+
182
+
183
+ # --------------------------------------------------------------------------- range-dependent agreement
184
+ def local_srd_profile(X, reference="mean", window: int | None = None, step: int = 1, columns=None, ties: str = "average") -> pd.DataFrame:
185
+ """Sliding-window SRD along the reference.
186
+
187
+ The objects are sorted by the reference; for every window of ``window``
188
+ consecutive objects the columns and the reference are re-ranked inside the
189
+ window and the normalized SRD is computed. Returns a DataFrame indexed by the
190
+ mean reference value of the windows.
191
+ """
192
+ df = as_frame(X)
193
+ y = make_reference(df, reference, ties=ties)
194
+ order = np.argsort(y, kind="stable")
195
+ n = df.shape[0]
196
+ w = window or max(5, n // 5)
197
+ cols = list(df.columns) if columns is None else list(columns)
198
+ rows, idx = [], []
199
+ for s in range(0, n - w + 1, step):
200
+ sel = order[s:s + w]
201
+ q = rank_vector(y[sel], ties=ties)
202
+ R = rank_matrix(df.iloc[sel][cols], ties=ties).to_numpy()
203
+ rows.append(np.abs(R - q[:, None]).sum(axis=0) / srd_max(w))
204
+ idx.append(float(np.mean(y[sel])))
205
+ return pd.DataFrame(rows, index=pd.Index(idx, name="reference"), columns=cols)
206
+
207
+
208
+ def piecewise_constant(signal, n_segments: int, min_size: int = 2) -> tuple[list[int], np.ndarray]:
209
+ """Least-squares optimal piecewise-constant segmentation of a 1-D signal (boundaries, segment means)."""
210
+ s = np.asarray(signal, float)
211
+ T = s.size
212
+ c1 = np.concatenate([[0.0], np.cumsum(s)])
213
+ c2 = np.concatenate([[0.0], np.cumsum(s ** 2)])
214
+ a = np.arange(T + 1)[:, None]
215
+ b = np.arange(T + 1)[None, :]
216
+ L = np.where(b > a, b - a, 1)
217
+ S1 = c1[None, :] - c1[:, None]
218
+ S2 = c2[None, :] - c2[:, None]
219
+ C = np.where(b - a >= min_size, S2 - S1 ** 2 / L, np.inf)
220
+ bounds, _ = optimal_partition(C, n_segments, min_size)
221
+ means = np.array([s[bounds[k]:bounds[k + 1]].mean() for k in range(len(bounds) - 1)])
222
+ return bounds, means
223
+
224
+
225
+ def displacement_segmentation(X, column: str, reference="mean", n_segments: int = 3, min_size: int = 3,
226
+ ties: str = "average") -> pd.DataFrame:
227
+ """Segments of the reference range with homogeneous displacement of one solution.
228
+
229
+ The contributions ``|r_ij - q_i|`` of ``column`` are ordered by the
230
+ reference and segmented optimally; the table gives, for every segment, the
231
+ range of the reference, the number of objects, the mean displacement and its
232
+ share of the SRD of the column.
233
+ """
234
+ from .core import srd
235
+
236
+ res = srd(X, reference=reference, ties=ties)
237
+ y = res.reference if res.reference.ndim == 1 else res.reference[:, 0]
238
+ order = np.argsort(y, kind="stable")
239
+ d = res.contributions[column].to_numpy()[order]
240
+ bounds, means = piecewise_constant(d, n_segments, min_size)
241
+ tot = d.sum() or 1.0
242
+ rows = []
243
+ for k in range(len(bounds) - 1):
244
+ a, b = bounds[k], bounds[k + 1]
245
+ rows.append({"segment": k + 1, "ref_min": float(y[order][a]), "ref_max": float(y[order][b - 1]), "n": b - a,
246
+ "mean_displacement": float(means[k]), "share_of_srd": float(d[a:b].sum() / tot)})
247
+ return pd.DataFrame(rows).set_index("segment")
srdkit/simulate.py ADDED
@@ -0,0 +1,171 @@
1
+ r"""Synthetic data for SRD studies: method comparisons, ranking models, sequences, decision problems.
2
+
3
+ Every example of the book uses either bundled real data or one of these
4
+ generators, so that the expected answer is known:
5
+
6
+ * :func:`make_method_comparison` — :math:`m` methods measure a latent property of
7
+ :math:`n` objects with method-specific noise, bias, nonlinearity and rounding (ties);
8
+ * :func:`mallows` — rankings from the Mallows model with Kendall distance, sampled
9
+ exactly by the repeated insertion model;
10
+ * :func:`perturb_ranking` — the adjacent-swap perturbations used in the cross-
11
+ validation study of Sziklai, Baranyi and Héberger (2025);
12
+ * :func:`make_ranking_sequence` — a sequence of rankings with regime changes
13
+ (for :func:`srdkit.segment_rankings`);
14
+ * :func:`make_decision_problem` — alternatives evaluated on correlated, partly
15
+ conflicting criteria (for MCDM, Promethee and NMF examples).
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import numpy as np
21
+ import pandas as pd
22
+
23
+ from ._utils import as_rng
24
+
25
+
26
+ def make_method_comparison(n_objects: int = 20, noise=(0.1, 0.3, 0.6, 1.0, 2.0), bias=None, nonlinear=None,
27
+ decimals=None, reversed_methods=(), random_state=None, return_truth: bool = True):
28
+ """Methods measuring a latent property with increasing noise.
29
+
30
+ Parameters
31
+ ----------
32
+ noise : sequence of float
33
+ Noise standard deviation of every method (relative to the unit variance of the truth).
34
+ bias : sequence of float, optional
35
+ Additive bias of every method (does not change SRD).
36
+ nonlinear : sequence of str, optional
37
+ ``None``, ``"exp"``, ``"square"`` or ``"saturate"`` per method (monotone or not).
38
+ decimals : int or sequence, optional
39
+ Rounding of every method (produces ties).
40
+ reversed_methods : sequence of int
41
+ Indices of methods that measure the negative of the property.
42
+
43
+ Returns
44
+ -------
45
+ X : DataFrame (objects x methods), and the truth (Series) if ``return_truth``.
46
+ """
47
+ rng = as_rng(random_state)
48
+ t = rng.standard_normal(n_objects)
49
+ cols = {}
50
+ for j, s in enumerate(noise):
51
+ v = t + rng.normal(0, s, n_objects)
52
+ f = None if nonlinear is None else nonlinear[j]
53
+ if f == "exp":
54
+ v = np.exp(v)
55
+ elif f == "square":
56
+ v = v ** 2
57
+ elif f == "saturate":
58
+ v = np.tanh(v)
59
+ if j in reversed_methods:
60
+ v = -v
61
+ if bias is not None:
62
+ v = v + bias[j]
63
+ if decimals is not None:
64
+ d = decimals[j] if np.ndim(decimals) else decimals
65
+ v = np.round(v, d)
66
+ cols[f"M{j + 1}"] = v
67
+ X = pd.DataFrame(cols, index=[f"obj{i + 1}" for i in range(n_objects)])
68
+ truth = pd.Series(t, index=X.index, name="truth")
69
+ return (X, truth) if return_truth else X
70
+
71
+
72
+ def mallows(n: int, theta: float, size: int = 1, center=None, random_state=None) -> np.ndarray:
73
+ r"""Rankings from the Mallows model :math:`P(\pi)\propto e^{-\theta d_K(\pi,\pi_0)}` (repeated insertion model).
74
+
75
+ Returns an array (size x n) of ranks (1 = first) around ``center`` (identity by default).
76
+ """
77
+ rng = as_rng(random_state)
78
+ q = np.exp(-theta)
79
+ out = np.empty((size, n))
80
+ c = np.arange(1, n + 1) if center is None else np.asarray(center)
81
+ for s in range(size):
82
+ order: list[int] = []
83
+ for i in range(n):
84
+ # insert item i at position j (0..i) with probability prop. to q^(i-j)
85
+ w = q ** (i - np.arange(i + 1))
86
+ j = rng.choice(i + 1, p=w / w.sum())
87
+ order.insert(j, i)
88
+ ranks = np.empty(n)
89
+ ranks[np.asarray(order)] = np.arange(1, n + 1)
90
+ out[s] = ranks[np.argsort(np.argsort(c))] # relabel around the centre
91
+ return out
92
+
93
+
94
+ def perturb_ranking(n: int, kind: str = "x", n_swaps: int = 1, random_state=None) -> np.ndarray:
95
+ """Adjacent-swap perturbations of the identity ranking (scenarios of Sziklai et al., 2025).
96
+
97
+ ``kind``: ``"x"`` swaps anywhere, ``"xt"`` in the top half, ``"xb"`` in the
98
+ bottom half, ``"1u"`` a random bottom-half object swapped with the first,
99
+ ``"4m"`` four swaps spaced ``ceil(n/4)`` apart.
100
+ """
101
+ rng = as_rng(random_state)
102
+ r = np.arange(1, n + 1, dtype=float)
103
+ pos = np.argsort(r) # positions of the objects in rank order
104
+
105
+ def swap(i):
106
+ a, b = pos[i], pos[i + 1]
107
+ r[a], r[b] = r[b], r[a]
108
+ pos[i], pos[i + 1] = b, a
109
+
110
+ if kind == "x":
111
+ for _ in range(n_swaps):
112
+ swap(rng.integers(0, n - 1))
113
+ elif kind == "xt":
114
+ for _ in range(n_swaps):
115
+ swap(rng.integers(0, max(n // 2 - 1, 1)))
116
+ elif kind == "xb":
117
+ for _ in range(n_swaps):
118
+ swap(rng.integers(n // 2, n - 1))
119
+ elif kind == "1u":
120
+ k = rng.integers(n // 2, n)
121
+ a, b = pos[0], pos[k]
122
+ r[a], r[b] = r[b], r[a]
123
+ elif kind == "4m":
124
+ step = int(np.ceil(n / 4))
125
+ for i in range(0, n - 1, step):
126
+ swap(i)
127
+ else:
128
+ raise ValueError("kind must be 'x', 'xt', 'xb', '1u' or '4m'")
129
+ return r
130
+
131
+
132
+ def make_ranking_sequence(T: int = 60, n: int = 12, change_points=(20, 40), theta: float = 1.0, random_state=None,
133
+ return_centers: bool = False):
134
+ """A sequence of ``T`` rankings of ``n`` objects with regime changes at ``change_points``.
135
+
136
+ Every regime has its own central ranking; the rankings of a regime are drawn
137
+ from the Mallows model around it with concentration ``theta``.
138
+ """
139
+ rng = as_rng(random_state)
140
+ bounds = [0, *change_points, T]
141
+ rows, centers = [], []
142
+ for a, b in zip(bounds[:-1], bounds[1:]):
143
+ center = rng.permutation(n) + 1.0
144
+ centers.append(center)
145
+ rows.append(mallows(n, theta, size=b - a, center=center, random_state=rng))
146
+ R = pd.DataFrame(np.vstack(rows), columns=[f"o{i + 1}" for i in range(n)])
147
+ return (R, centers) if return_centers else R
148
+
149
+
150
+ def make_decision_problem(n_alternatives: int = 30, n_criteria: int = 8, n_groups: int = 2, conflict: float = 0.5,
151
+ noise: float = 0.3, random_state=None) -> pd.DataFrame:
152
+ """Alternatives on criteria driven by ``n_groups`` latent factors.
153
+
154
+ Criteria of the same group are positively correlated; with ``conflict > 0``
155
+ the latent factors are negatively correlated (correlation ``-conflict`` between
156
+ neighbouring factors), which makes the criteria groups partly conflicting.
157
+ Values are shifted to be positive.
158
+ """
159
+ rng = as_rng(random_state)
160
+ C = np.eye(n_groups)
161
+ for g in range(n_groups - 1):
162
+ C[g, g + 1] = C[g + 1, g] = -conflict
163
+ w, V = np.linalg.eigh(C)
164
+ L = V @ np.diag(np.sqrt(np.clip(w, 1e-9, None)))
165
+ F = rng.standard_normal((n_alternatives, n_groups)) @ L.T
166
+ cols = {}
167
+ for k in range(n_criteria):
168
+ g = k % n_groups
169
+ cols[f"C{k + 1}"] = F[:, g] * rng.uniform(0.6, 1.0) + rng.normal(0, noise, n_alternatives)
170
+ X = pd.DataFrame(cols, index=[f"A{i + 1}" for i in range(n_alternatives)])
171
+ return X - X.min() + 1.0
srdkit/tournament.py ADDED
@@ -0,0 +1,167 @@
1
+ r"""Tournament tables and the power–weakness ratio (PWR, sPWR, threshold sequences).
2
+
3
+ The power–weakness ratio goes back to Ramanujacharyulu (1964): in a tournament
4
+ table :math:`\mathbf T` (entry :math:`T_{ab}` = how much alternative :math:`a`
5
+ beats :math:`b`) the dominant eigenvector :math:`\mathbf l` of :math:`\mathbf T`
6
+ measures *power* and that of :math:`\mathbf T^{\mathsf T}`, :math:`\mathbf l^*`,
7
+ *weakness*. Todeschini, Grisoni and Ballabio (2019) built a data-driven ranking
8
+ method on it (DRAPE): the tournament table is obtained from the data matrix by
9
+ pairwise comparisons over the criteria,
10
+
11
+ .. math::
12
+
13
+ T_{ab}=\sum_j w_j\,\delta_{ab,j},\qquad
14
+ \delta_{ab,j}=\begin{cases}1 & a \text{ better than } b \text{ in criterion } j\\
15
+ \tfrac12 & \text{equal}\\ 0 & \text{worse,}\end{cases}
16
+
17
+ and the alternatives are ranked by :math:`\mathrm{PWR}_a=(\alpha+l_a)/(\alpha+l^*_a)`
18
+ with :math:`\alpha=1/m` (Consonni et al., 2026). The smoothed PWR (sPWR) of
19
+ Consonni et al. (2026) replaces :math:`\delta` by the graded dominance
20
+ :math:`q_{ab,j}=\tfrac12[1+\omega_j(x_{ja}-x_{jb})/\Delta x_j]` (:math:`\omega_j=\pm1`
21
+ is the direction of criterion :math:`j`, :math:`\Delta x_j` its range).
22
+
23
+ PWR needs no reference and no scaling, only the direction of every criterion,
24
+ so it complements the reference-based SRD family (Héberger, 2026, uses DRAPE as
25
+ the benchmark-agnostic member of his consensus framework). DRAPE itself returns
26
+ a *sequence* of rankings; :func:`pwr_sequence` produces a sequence in the same
27
+ spirit by increasing an indifference threshold (differences below a fraction of
28
+ the criterion's range count as ties) and summarizes it by the first principal
29
+ component, as DRAPE summarizes its rankings. The DRAPE thresholding schedule and
30
+ its "retro"-regression are not reproduced here.
31
+
32
+ Orientation follows the rest of the package: rows are criteria (objects),
33
+ columns are the alternatives (solutions) to be ranked.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import numpy as np
39
+ import pandas as pd
40
+
41
+ from ._utils import as_frame
42
+
43
+
44
+ def _directions(df: pd.DataFrame, directions) -> np.ndarray:
45
+ n = df.shape[0]
46
+ if directions is None:
47
+ return np.ones(n)
48
+ if isinstance(directions, str):
49
+ if directions in ("max", "larger", "benefit"):
50
+ return np.ones(n)
51
+ if directions in ("min", "smaller", "cost"):
52
+ return -np.ones(n)
53
+ raise ValueError("directions must be 'max', 'min' or a vector of +1/-1")
54
+ d = np.asarray(pd.Series(directions, index=df.index) if isinstance(directions, dict) else directions, dtype=float)
55
+ if d.size != n:
56
+ raise ValueError("one direction per row (criterion) is needed")
57
+ return np.sign(d)
58
+
59
+
60
+ def tournament_table(X, directions=None, weights=None, kind: str = "pwr", threshold: float = 0.0) -> pd.DataFrame:
61
+ r"""Tournament table of the columns of ``X`` compared row by row.
62
+
63
+ Parameters
64
+ ----------
65
+ X : array-like or DataFrame
66
+ Rows = criteria, columns = alternatives.
67
+ directions : None, "max", "min", or sequence of +1/-1
68
+ Preferred direction of every row (default: larger is better).
69
+ weights : sequence, optional
70
+ Row weights (normalized to sum 1; equal by default).
71
+ kind : {"pwr", "spwr"}
72
+ Crisp comparisons (1, 1/2, 0) or the graded dominance of sPWR.
73
+ threshold : float
74
+ For ``kind="pwr"``: differences up to ``threshold`` times the row range
75
+ count as ties (0 = strict comparison).
76
+
77
+ Returns
78
+ -------
79
+ DataFrame
80
+ :math:`T_{ab}` with :math:`T_{ab}+T_{ba}=1` and zero diagonal.
81
+
82
+ >>> T = tournament_table([[3, 1, 2], [2, 1, 3]])
83
+ >>> T.round(2).values.tolist()
84
+ [[0.0, 1.0, 0.5], [0.0, 0.0, 0.0], [0.5, 1.0, 0.0]]
85
+ """
86
+ df = as_frame(X)
87
+ A = df.to_numpy(float)
88
+ n, m = A.shape
89
+ om = _directions(df, directions)
90
+ w = np.ones(n) if weights is None else np.asarray(weights, float)
91
+ w = w / w.sum()
92
+ rng = A.max(axis=1) - A.min(axis=1)
93
+ rng[rng == 0] = 1.0
94
+ diff = (A[:, :, None] - A[:, None, :]) * om[:, None, None] # rows x a x b
95
+ if kind == "pwr":
96
+ tol = threshold * rng[:, None, None]
97
+ delta = np.where(diff > tol, 1.0, np.where(diff < -tol, 0.0, 0.5))
98
+ elif kind == "spwr":
99
+ delta = 0.5 * (1 + diff / rng[:, None, None])
100
+ else:
101
+ raise ValueError("kind must be 'pwr' or 'spwr'")
102
+ T = np.tensordot(w, delta, axes=(0, 0))
103
+ np.fill_diagonal(T, 0.0)
104
+ return pd.DataFrame(T, index=df.columns, columns=df.columns)
105
+
106
+
107
+ def _perron(M: np.ndarray, eps: float = 1e-9) -> np.ndarray:
108
+ m = M.shape[0]
109
+ P = M + eps * (np.ones((m, m)) - np.eye(m)) # guarantees irreducibility
110
+ vals, vecs = np.linalg.eig(P)
111
+ v = np.abs(np.real(vecs[:, int(np.argmax(np.real(vals)))]))
112
+ return v / v.sum()
113
+
114
+
115
+ def pwr(X, directions=None, weights=None, kind: str = "pwr", threshold: float = 0.0, alpha: float | None = None) -> pd.DataFrame:
116
+ r"""Power, weakness and power–weakness ratio of the alternatives (columns).
117
+
118
+ The eigenvectors are scaled to unit sum; ``alpha`` defaults to :math:`1/m`.
119
+ Returns a DataFrame with ``power``, ``weakness``, ``PWR``, the row sums of the
120
+ tournament table (``score``, Copeland-like) and ``rank`` (1 = best),
121
+ sorted by rank.
122
+
123
+ >>> X = [[9, 5, 1], [8, 6, 2], [7, 4, 3]]
124
+ >>> pwr(X)["rank"].to_dict()
125
+ {'c1': 1, 'c2': 2, 'c3': 3}
126
+ """
127
+ T = tournament_table(X, directions, weights, kind, threshold)
128
+ M = T.to_numpy()
129
+ m = M.shape[0]
130
+ a = 1.0 / m if alpha is None else float(alpha)
131
+ l, ls = _perron(M), _perron(M.T)
132
+ ratio = (a + l) / (a + ls)
133
+ out = pd.DataFrame({"power": l, "weakness": ls, "PWR": ratio, "score": M.sum(axis=1)}, index=T.index)
134
+ out["rank"] = out["PWR"].rank(ascending=False, method="average")
135
+ out["rank"] = out["rank"].astype(int) if np.allclose(out["rank"], out["rank"].round()) else out["rank"]
136
+ return out.sort_values("rank", kind="stable")
137
+
138
+
139
+ def spwr(X, directions=None, weights=None, alpha: float | None = None) -> pd.DataFrame:
140
+ """Smoothed power–weakness ratio (Consonni et al., 2026); see :func:`pwr`."""
141
+ return pwr(X, directions, weights, kind="spwr", alpha=alpha)
142
+
143
+
144
+ def pwr_sequence(X, thresholds=(0.0, 0.05, 0.1, 0.15, 0.2, 0.3), directions=None, weights=None) -> dict:
145
+ """A sequence of PWR rankings with growing indifference thresholds and its consensus.
146
+
147
+ Returns a dict with ``ranks`` (alternatives x thresholds, 1 = best), ``scores``
148
+ (PWR values) and ``consensus``: the scores on the first principal component of
149
+ the standardized PWR scores (sign chosen to agree with the mean score) and the
150
+ resulting rank. ``explained`` is the variance share of that component.
151
+ """
152
+ df = as_frame(X)
153
+ scores, ranks = {}, {}
154
+ for t in thresholds:
155
+ r = pwr(df, directions, weights, threshold=float(t)).reindex(df.columns)
156
+ scores[f"t={t:g}"] = r["PWR"]
157
+ ranks[f"t={t:g}"] = r["PWR"].rank(ascending=False, method="average")
158
+ S = pd.DataFrame(scores)
159
+ Z = (S - S.mean()) / S.std(ddof=0).replace(0, 1)
160
+ U, sv, Vt = np.linalg.svd(Z.to_numpy(), full_matrices=False)
161
+ pc = U[:, 0] * sv[0]
162
+ if np.corrcoef(pc, S.mean(axis=1))[0, 1] < 0:
163
+ pc = -pc
164
+ explained = float(sv[0] ** 2 / np.sum(sv ** 2)) if np.sum(sv ** 2) > 0 else 1.0
165
+ cons = pd.DataFrame({"score": pc, "rank": pd.Series(pc, index=df.columns).rank(ascending=False, method="average")},
166
+ index=df.columns)
167
+ return {"ranks": pd.DataFrame(ranks), "scores": S, "consensus": cons.sort_values("rank"), "explained": explained}