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/promethee.py ADDED
@@ -0,0 +1,371 @@
1
+ r"""Promethee II, GAIA and the Promethee-based SRD (P-SRD).
2
+
3
+ Promethee (Brans and Vincke, 1985) compares the alternatives :math:`a_i` pairwise
4
+ on every criterion :math:`g_k`. A preference function :math:`F_k` maps the
5
+ difference :math:`d_k(a_i,a_j)=g_k(a_i)-g_k(a_j)` to a preference degree
6
+ :math:`P_k(a_i,a_j)\in[0,1]`; the unicriterion net flow is
7
+
8
+ .. math:: \phi_k(a_i)=\frac{1}{n-1}\sum_{j}\bigl[P_k(a_i,a_j)-P_k(a_j,a_i)\bigr],
9
+
10
+ and Promethee II ranks the alternatives by the global net flow
11
+ :math:`\phi(a_i)=\sum_k w_k\phi_k(a_i)`. GAIA projects the matrix of unicriterion
12
+ flows onto its first principal plane (Brans and Mareschal).
13
+
14
+ SRD as a special case of Promethee
15
+ ----------------------------------
16
+ Abonyi, Czvetkó, Kosztyán and Héberger (2022) showed that SRD is a special case
17
+ of Promethee and proposed P-SRD, :math:`\sum_i|\phi_k(a_i)-\phi(a_i)|`. The
18
+ connection is exact: with the *usual* preference function
19
+ (:math:`P=1` if :math:`d>0`, else 0) the unicriterion flow is an affine function of
20
+ the mid-rank,
21
+
22
+ .. math:: \phi_k(a_i)=\frac{L_i-G_i}{n-1}=\frac{2r_{ik}-n-1}{n-1},
23
+
24
+ where :math:`L_i` (:math:`G_i`) counts the alternatives below (above) :math:`a_i`;
25
+ hence the footrule distance of two criteria equals
26
+ :math:`\frac{n-1}{2}\sum_i|\phi_k(a_i)-\phi_l(a_i)|` (:func:`srd_promethee_identity`
27
+ checks this numerically). P-SRD with the usual criterion is SRD against the mean
28
+ rank, and other preference functions give a family of SRD variants that use the
29
+ size of the differences. The module also implements the two other improvements of
30
+ the paper: principal factoring with communality analysis (P-PFA) and sparse
31
+ principal components for the GAIA plane (P-sPCA).
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ from dataclasses import dataclass, field
37
+
38
+ import numpy as np
39
+ import pandas as pd
40
+
41
+ from ._utils import as_frame, srd_max
42
+ from .core import SRDResult
43
+ from .ranking import rank_vector
44
+
45
+
46
+ # --------------------------------------------------------------------------- preference functions
47
+ def preference(d, kind: str = "usual", q: float = 0.0, p: float = 1.0, s: float = 1.0):
48
+ """Preference degree of a difference (or array of differences).
49
+
50
+ ``kind``: ``"usual"``, ``"ushape"`` (indifference threshold ``q``),
51
+ ``"vshape"`` (preference threshold ``p``), ``"level"`` (``q``, ``p``),
52
+ ``"linear"`` (``q``, ``p``), ``"gaussian"`` (``s``).
53
+ """
54
+ d = np.asarray(d, float)
55
+ if kind == "usual":
56
+ return (d > 0).astype(float)
57
+ if kind == "ushape":
58
+ return (d > q).astype(float)
59
+ if kind == "vshape":
60
+ return np.clip(d / p, 0, 1) * (d > 0)
61
+ if kind == "level":
62
+ return np.where(d > p, 1.0, np.where(d > q, 0.5, 0.0))
63
+ if kind == "linear":
64
+ return np.where(d > p, 1.0, np.where(d > q, (d - q) / (p - q), 0.0))
65
+ if kind == "gaussian":
66
+ return np.where(d > 0, 1 - np.exp(-d ** 2 / (2 * s ** 2)), 0.0)
67
+ raise ValueError("kind must be 'usual', 'ushape', 'vshape', 'level', 'linear' or 'gaussian'")
68
+
69
+
70
+ @dataclass
71
+ class PrometheeResult:
72
+ """Flows of Promethee: ``phi_plus``, ``phi_minus``, ``phi`` (net) and the unicriterion flows ``unicriterion``."""
73
+
74
+ phi_plus: pd.Series
75
+ phi_minus: pd.Series
76
+ phi: pd.Series
77
+ unicriterion: pd.DataFrame
78
+ weights: np.ndarray
79
+ meta: dict = field(default_factory=dict)
80
+
81
+ @property
82
+ def ranking(self) -> pd.Series:
83
+ """Promethee II ranks (1 = best)."""
84
+ return pd.Series(rank_vector(-self.phi.to_numpy(), ties="min"), index=self.phi.index, name="rank")
85
+
86
+ def to_frame(self) -> pd.DataFrame:
87
+ return pd.DataFrame({"phi+": self.phi_plus, "phi-": self.phi_minus, "phi": self.phi,
88
+ "rank": self.ranking}).sort_values("rank")
89
+
90
+
91
+ def _spec(spec, columns, default):
92
+ if isinstance(spec, dict):
93
+ return [spec.get(c, default) for c in columns]
94
+ if isinstance(spec, (list, tuple)):
95
+ return list(spec)
96
+ return [spec] * len(columns)
97
+
98
+
99
+ def promethee(X, weights=None, functions="usual", params=None, directions=None) -> PrometheeResult:
100
+ """Promethee I/II flows.
101
+
102
+ Parameters
103
+ ----------
104
+ X : array-like or DataFrame (alternatives x criteria)
105
+ weights : array-like, optional
106
+ Criteria weights (normalized to sum to one); equal by default.
107
+ functions : str, list or dict
108
+ Preference function(s) (see :func:`preference`).
109
+ params : dict, list of dicts or dict of dicts
110
+ Thresholds ``q``, ``p``, ``s`` of the preference functions.
111
+ directions : list or dict
112
+ ``"max"`` (default) or ``"min"`` per criterion.
113
+ """
114
+ df = as_frame(X)
115
+ A = df.to_numpy(float)
116
+ n, m = A.shape
117
+ w = np.full(m, 1.0 / m) if weights is None else np.asarray(weights, float) / np.sum(weights)
118
+ funcs = _spec(functions, df.columns, "usual")
119
+ if params is None:
120
+ pars = [{}] * m
121
+ elif isinstance(params, dict) and set(params) <= set(df.columns):
122
+ pars = [params.get(c, {}) for c in df.columns]
123
+ elif isinstance(params, dict):
124
+ pars = [params] * m
125
+ else:
126
+ pars = list(params)
127
+ dirs = _spec(directions if directions is not None else "max", df.columns, "max")
128
+ uni = np.zeros((n, m))
129
+ plus = np.zeros(n)
130
+ minus = np.zeros(n)
131
+ for k in range(m):
132
+ g = A[:, k] if str(dirs[k]).lower() != "min" else -A[:, k]
133
+ D = g[:, None] - g[None, :]
134
+ P = preference(D, funcs[k], **pars[k])
135
+ np.fill_diagonal(P, 0.0)
136
+ fp = P.sum(axis=1) / (n - 1)
137
+ fm = P.sum(axis=0) / (n - 1)
138
+ uni[:, k] = fp - fm
139
+ plus += w[k] * fp
140
+ minus += w[k] * fm
141
+ U = pd.DataFrame(uni, index=df.index, columns=df.columns)
142
+ return PrometheeResult(phi_plus=pd.Series(plus, index=df.index, name="phi+"),
143
+ phi_minus=pd.Series(minus, index=df.index, name="phi-"),
144
+ phi=pd.Series(plus - minus, index=df.index, name="phi"), unicriterion=U, weights=w,
145
+ meta={"functions": funcs, "params": pars, "directions": dirs})
146
+
147
+
148
+ def srd_promethee_identity(X) -> float:
149
+ """Largest deviation between the usual-criterion unicriterion flows and ``(2 r - n - 1)/(n - 1)``.
150
+
151
+ The value is zero up to rounding, which is the exact form of "SRD is a special
152
+ case of Promethee".
153
+
154
+ >>> X = np.array([[1, 5], [2, 2], [2, 7], [9, 1]], dtype=float)
155
+ >>> srd_promethee_identity(X) < 1e-12
156
+ True
157
+ """
158
+ df = as_frame(X)
159
+ n = df.shape[0]
160
+ res = promethee(df, functions="usual")
161
+ dev = 0.0
162
+ for c in df.columns:
163
+ r = rank_vector(df[c].to_numpy())
164
+ dev = max(dev, float(np.max(np.abs(res.unicriterion[c].to_numpy() - (2 * r - n - 1) / (n - 1)))))
165
+ return dev
166
+
167
+
168
+ def p_srd(X, weights=None, functions="usual", params=None, directions=None, rerank: bool = False) -> SRDResult:
169
+ r"""Promethee-based SRD (P-SRD) of every criterion against the global net flow.
170
+
171
+ The flows are mapped to the rank scale, :math:`r=((n-1)\phi+n+1)/2`, so that
172
+ the values are directly comparable with SRD (with the usual preference function
173
+ P-SRD equals SRD against the mean rank). With ``rerank=True`` the global net
174
+ flow is ranked first (the classical SRD convention of a ranked reference).
175
+ """
176
+ df = as_frame(X)
177
+ n = df.shape[0]
178
+ pr = promethee(df, weights, functions, params, directions)
179
+ to_rank = lambda v: ((n - 1) * np.asarray(v, float) + n + 1) / 2.0 # noqa: E731
180
+ R = pr.unicriterion.apply(to_rank)
181
+ q = rank_vector(pr.phi.to_numpy()) if rerank else to_rank(pr.phi.to_numpy())
182
+ diff = R.sub(q, axis=0)
183
+ vals = diff.abs().sum(axis=0)
184
+ res = SRDResult(srd=pd.Series(vals.to_numpy(), index=df.columns, name="P-SRD"), srd_max=srd_max(n), n=n, ranks=R,
185
+ reference=pr.phi.to_numpy(), reference_ranks=np.asarray(q, float), differences=diff, data=df,
186
+ reference_method="Promethee net flow", ties="average", distance="footrule",
187
+ meta={"promethee": pr, "flow_l1": pr.unicriterion.sub(pr.phi, axis=0).abs().sum(axis=0),
188
+ "label": "P-SRD"})
189
+ return res
190
+
191
+
192
+ # --------------------------------------------------------------------------- GAIA
193
+ @dataclass
194
+ class GAIAResult:
195
+ scores: pd.DataFrame
196
+ loadings: pd.DataFrame
197
+ explained: np.ndarray
198
+ decision_stick: np.ndarray
199
+ sparse: bool = False
200
+
201
+
202
+ def gaia(flows, weights=None, n_components: int = 2, sparse_nonzero: int | None = None) -> GAIAResult:
203
+ """GAIA plane: principal components of the unicriterion net flow matrix.
204
+
205
+ ``flows`` is a :class:`PrometheeResult` or an (alternatives x criteria) flow
206
+ matrix. With ``sparse_nonzero`` the loadings are sparse (P-sPCA): every
207
+ component keeps that many criteria (truncated power method).
208
+ """
209
+ U = flows.unicriterion if isinstance(flows, PrometheeResult) else as_frame(flows)
210
+ if weights is None and isinstance(flows, PrometheeResult):
211
+ weights = flows.weights
212
+ Z = U.to_numpy(float) - U.to_numpy(float).mean(axis=0)
213
+ m = Z.shape[1]
214
+ if sparse_nonzero is None:
215
+ u, s, vt = np.linalg.svd(Z, full_matrices=False)
216
+ V = vt[:n_components].T
217
+ explained = s[:n_components] ** 2 / (s ** 2).sum()
218
+ else:
219
+ V = sparse_pca(Z, n_components, sparse_nonzero)
220
+ tot = (Z ** 2).sum()
221
+ explained = np.array([((Z @ V[:, k]) ** 2).sum() / tot for k in range(n_components)])
222
+ scores = Z @ V
223
+ w = np.full(m, 1.0 / m) if weights is None else np.asarray(weights, float) / np.sum(weights)
224
+ stick = w @ V
225
+ cols = [f"PC{k + 1}" for k in range(n_components)]
226
+ return GAIAResult(scores=pd.DataFrame(scores, index=U.index, columns=cols),
227
+ loadings=pd.DataFrame(V, index=U.columns, columns=cols), explained=explained,
228
+ decision_stick=stick, sparse=sparse_nonzero is not None)
229
+
230
+
231
+ def sparse_pca(Z, n_components: int = 2, n_nonzero: int = 5, max_iter: int = 500, tol: float = 1e-10, random_state=0) -> np.ndarray:
232
+ """Sparse loadings by the truncated power method with deflation (exactly ``n_nonzero`` per component)."""
233
+ Z = np.asarray(Z, float)
234
+ S = Z.T @ Z
235
+ m = S.shape[0]
236
+ k = min(int(n_nonzero), m)
237
+ V = np.zeros((m, n_components))
238
+ rng = np.random.default_rng(random_state)
239
+ for c in range(n_components):
240
+ w, vecs = np.linalg.eigh(S)
241
+ v = vecs[:, -1] + 1e-6 * rng.standard_normal(m)
242
+ for _ in range(max_iter):
243
+ u = S @ v
244
+ keep = np.argsort(np.abs(u))[-k:]
245
+ new = np.zeros(m)
246
+ new[keep] = u[keep]
247
+ nrm = np.linalg.norm(new)
248
+ if nrm == 0:
249
+ break
250
+ new /= nrm
251
+ if np.linalg.norm(new - v) < tol:
252
+ v = new
253
+ break
254
+ v = new
255
+ V[:, c] = v
256
+ lam = v @ S @ v
257
+ S = S - lam * np.outer(v, v) # Hotelling deflation
258
+ return V
259
+
260
+
261
+ def index_of_sparseness(Z, V) -> float:
262
+ r"""Index of sparseness :math:`(V_a V_s/V_o^2)\cdot(\#0/(n p))` of sparse loadings ``V``.
263
+
264
+ :math:`V_a` is the adjusted variance (QR decomposition of the scores),
265
+ :math:`V_s` the unadjusted variance of the sparse scores, :math:`V_o` the
266
+ variance of the same number of ordinary principal components and
267
+ :math:`\#0` the number of zero loadings among the :math:`n p` loadings.
268
+ """
269
+ Z = np.asarray(Z, float)
270
+ V = np.asarray(V, float)
271
+ T = Z @ V
272
+ _, Rq = np.linalg.qr(T)
273
+ va = float((np.diag(Rq) ** 2).sum())
274
+ vs = float((T ** 2).sum())
275
+ s = np.linalg.svd(Z, compute_uv=False)
276
+ vo = float((s[:V.shape[1]] ** 2).sum())
277
+ zeros = int(np.sum(np.isclose(V, 0)))
278
+ return va * vs / vo ** 2 * zeros / V.size
279
+
280
+
281
+ # --------------------------------------------------------------------------- P-PFA
282
+ def msa(X) -> tuple[float, pd.Series]:
283
+ r"""Kaiser's measure of sampling adequacy: overall value and one value per criterion.
284
+
285
+ :math:`\mathrm{MSA}_j=\sum_{i\ne j}r_{ij}^2/\bigl(\sum_{i\ne j}r_{ij}^2+\sum_{i\ne j}q_{ij}^2\bigr)` with
286
+ the correlations :math:`r_{ij}` and partial correlations :math:`q_{ij}`.
287
+ """
288
+ df = as_frame(X)
289
+ Rm = np.corrcoef(df.to_numpy(float), rowvar=False)
290
+ Pinv = np.linalg.pinv(Rm)
291
+ d = np.sqrt(np.outer(np.diag(Pinv), np.diag(Pinv)))
292
+ Qm = -Pinv / d
293
+ np.fill_diagonal(Rm, 0)
294
+ np.fill_diagonal(Qm, 0)
295
+ r2, q2 = Rm ** 2, Qm ** 2
296
+ per = r2.sum(axis=0) / (r2.sum(axis=0) + q2.sum(axis=0))
297
+ overall = r2.sum() / (r2.sum() + q2.sum())
298
+ return float(overall), pd.Series(per, index=df.columns, name="MSA")
299
+
300
+
301
+ def varimax(L, gamma: float = 1.0, max_iter: int = 100, tol: float = 1e-8) -> np.ndarray:
302
+ """Varimax rotation of a loading matrix."""
303
+ L = np.asarray(L, float)
304
+ p, k = L.shape
305
+ Rot = np.eye(k)
306
+ d = 0.0
307
+ for _ in range(max_iter):
308
+ Lr = L @ Rot
309
+ u, s, vt = np.linalg.svd(L.T @ (Lr ** 3 - (gamma / p) * Lr @ np.diag((Lr ** 2).sum(axis=0))))
310
+ Rot = u @ vt
311
+ d_new = s.sum()
312
+ if d_new < d * (1 + tol):
313
+ break
314
+ d = d_new
315
+ return L @ Rot
316
+
317
+
318
+ def principal_factors(X, n_factors: int = 2, rotate: bool = True) -> tuple[pd.DataFrame, pd.Series]:
319
+ """Principal component factoring of the correlation matrix (optionally varimax rotated); loadings and communalities."""
320
+ df = as_frame(X)
321
+ Rm = np.corrcoef(df.to_numpy(float), rowvar=False)
322
+ w, V = np.linalg.eigh(Rm)
323
+ idx = np.argsort(w)[::-1][:n_factors]
324
+ L = V[:, idx] * np.sqrt(np.clip(w[idx], 0, None))
325
+ if rotate and n_factors > 1:
326
+ L = varimax(L)
327
+ load = pd.DataFrame(L, index=df.columns, columns=[f"F{k + 1}" for k in range(n_factors)])
328
+ return load, (load ** 2).sum(axis=1).rename("communality")
329
+
330
+
331
+ def p_pfa(X, n_factors: int = 2, msa_min: float = 0.5, communality_min: float = 0.5, c_min: float = 0.2,
332
+ max_rounds: int = 50) -> dict:
333
+ """Criteria reduction by principal factoring (P-PFA, Abonyi et al. 2022).
334
+
335
+ Criteria are removed in turn when their MSA is below ``msa_min``, when their
336
+ communality is below ``communality_min`` and when they are *common* to several
337
+ factors, i.e. their largest absolute loading :math:`|p_{j1}|` exceeds neither
338
+ :math:`|p_{j2}|+c_{\\min}` nor :math:`2|p_{j2}|`. Returns the kept criteria, the
339
+ rotated loadings, the factor assignment and the removal log.
340
+ """
341
+ df = as_frame(X)
342
+ keep = list(df.columns)
343
+ log = []
344
+ for _ in range(max_rounds):
345
+ changed = False
346
+ _, per = msa(df[keep])
347
+ low = per[per < msa_min]
348
+ if len(low) and len(keep) - 1 > n_factors:
349
+ worst = low.idxmin()
350
+ keep.remove(worst)
351
+ log.append((worst, "MSA", float(low.min())))
352
+ continue
353
+ load, comm = principal_factors(df[keep], n_factors)
354
+ lowc = comm[comm < communality_min]
355
+ if len(lowc) and len(keep) - 1 > n_factors:
356
+ worst = lowc.idxmin()
357
+ keep.remove(worst)
358
+ log.append((worst, "communality", float(lowc.min())))
359
+ continue
360
+ a = np.sort(np.abs(load.to_numpy()), axis=1)[:, ::-1]
361
+ common = [c for c, (p1, p2) in zip(load.index, a[:, :2]) if not (p1 > p2 + c_min or p1 > 2 * p2)] if n_factors > 1 else []
362
+ if common and len(keep) - 1 > n_factors:
363
+ keep.remove(common[0])
364
+ log.append((common[0], "common", None))
365
+ changed = True
366
+ if not changed:
367
+ break
368
+ load, comm = principal_factors(df[keep], n_factors)
369
+ assign = load.abs().idxmax(axis=1).rename("factor")
370
+ return {"kept": keep, "loadings": load, "communality": comm, "assignment": assign,
371
+ "removed": pd.DataFrame(log, columns=["criterion", "reason", "value"])}
srdkit/ranking.py ADDED
@@ -0,0 +1,193 @@
1
+ r"""Rank transformation, tie handling and soft (probabilistic) ranks.
2
+
3
+ SRD compares solutions through the ranks of the objects. Every column of the
4
+ input matrix is ranked separately in ascending order (1 for the smallest value,
5
+ :math:`n` for the largest). Equal values (ties) get the mean of the positions they
6
+ occupy (fractional or *mid*-ranks), as introduced for SRD by Kollár-Hunek and
7
+ Héberger (2013); other conventions are available for sensitivity studies.
8
+
9
+ Soft ranks replace the step function of the rank transform by a smooth one: if
10
+ every value carries a Gaussian measurement error with standard deviation
11
+ :math:`\sigma`, the expected rank of object :math:`i` is
12
+
13
+ .. math:: \mathbb{E}[r_i] = 1 + \sum_{k\neq i} \Phi\!\left(\frac{x_i-x_k}{\sigma\sqrt2}\right),
14
+
15
+ which tends to the mid-rank as :math:`\sigma\to0` (a tie contributes
16
+ :math:`\Phi(0)=1/2`). Soft ranks make SRD continuous in the data and robust to
17
+ measurement noise that is smaller than the resolution of the ranking.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import numpy as np
23
+ import pandas as pd
24
+ from scipy import special, stats
25
+
26
+ from ._utils import as_frame, as_rng
27
+
28
+ TIE_METHODS = ("average", "min", "max", "dense", "ordinal", "random")
29
+
30
+
31
+ def rank_vector(x, ties: str = "average", ascending: bool = True, random_state=None) -> np.ndarray:
32
+ """Ranks of a 1-D array (1 = smallest when ``ascending``).
33
+
34
+ Parameters
35
+ ----------
36
+ x : array-like
37
+ The values.
38
+ ties : {"average", "min", "max", "dense", "ordinal", "random"}
39
+ Treatment of equal values. ``"average"`` gives mid-ranks (the SRD
40
+ convention); ``"random"`` breaks ties at random.
41
+ ascending : bool
42
+ Rank in ascending order (default) or descending order.
43
+ random_state : int, Generator or None
44
+ Used by ``ties="random"``.
45
+
46
+ Examples
47
+ --------
48
+ >>> rank_vector([32, 52, 44, 44, 47]).tolist()
49
+ [1.0, 5.0, 2.5, 2.5, 4.0]
50
+ """
51
+ a = np.asarray(x, dtype=float)
52
+ if not ascending:
53
+ a = -a
54
+ if ties not in TIE_METHODS:
55
+ raise ValueError(f"ties must be one of {TIE_METHODS}")
56
+ if ties == "random":
57
+ rng = as_rng(random_state)
58
+ perm = rng.permutation(a.size)
59
+ r = np.empty(a.size)
60
+ order = np.lexsort((perm, a))
61
+ r[order] = np.arange(1, a.size + 1)
62
+ return r
63
+ return stats.rankdata(a, method=ties).astype(float)
64
+
65
+
66
+ def rank_matrix(X, ties: str = "average", ascending: bool | dict | list = True, axis: int = 0, random_state=None) -> pd.DataFrame:
67
+ """Rank every column (``axis=0``) or every row (``axis=1``) of ``X``.
68
+
69
+ ``ascending`` may be a single flag, a list (one per column) or a mapping
70
+ ``{column: bool}`` so that criteria with different directions can be put on
71
+ the same scale before ranking.
72
+ """
73
+ df = as_frame(X)
74
+ if axis == 1:
75
+ return rank_matrix(df.T, ties=ties, ascending=ascending, random_state=random_state).T
76
+ rng = as_rng(random_state)
77
+ out = {}
78
+ for j, c in enumerate(df.columns):
79
+ if isinstance(ascending, dict):
80
+ asc = ascending.get(c, True)
81
+ elif isinstance(ascending, (list, tuple, np.ndarray)):
82
+ asc = bool(ascending[j])
83
+ else:
84
+ asc = bool(ascending)
85
+ out[c] = rank_vector(df[c].to_numpy(), ties=ties, ascending=asc, random_state=rng)
86
+ return pd.DataFrame(out, index=df.index)
87
+
88
+
89
+ def tie_blocks(r) -> list[int]:
90
+ """Sizes of the tie blocks of a rank (or value) vector, in increasing order of the values.
91
+
92
+ >>> tie_blocks([1, 2.5, 2.5, 4, 5])
93
+ [1, 2, 1, 1]
94
+ """
95
+ v = np.sort(np.asarray(r, dtype=float))
96
+ if v.size == 0:
97
+ return []
98
+ cuts = np.flatnonzero(np.diff(v) != 0) + 1
99
+ edges = np.concatenate([[0], cuts, [v.size]])
100
+ return np.diff(edges).astype(int).tolist()
101
+
102
+
103
+ def midranks_from_blocks(blocks) -> np.ndarray:
104
+ """Mid-rank values (sorted) of a tie pattern given by block sizes.
105
+
106
+ >>> midranks_from_blocks([1, 2, 1]).tolist()
107
+ [1.0, 2.5, 2.5, 4.0]
108
+ """
109
+ out, start = [], 0
110
+ for b in blocks:
111
+ out += [start + (b + 1) / 2.0] * int(b)
112
+ start += int(b)
113
+ return np.asarray(out, dtype=float)
114
+
115
+
116
+ def tie_probability(x) -> float:
117
+ """Share of tied adjacent positions in the sorted vector, as in the rSRD package.
118
+
119
+ A vector of length :math:`n` has :math:`n-1` adjacent positions; the tie
120
+ probability is the number of positions occupied by equal neighbours divided
121
+ by :math:`n-1`.
122
+
123
+ >>> tie_probability([1, 2, 2, 3, 4, 4, 4])
124
+ 0.5
125
+ """
126
+ v = np.sort(np.asarray(x, dtype=float))
127
+ if v.size < 2:
128
+ return 0.0
129
+ return float(np.mean(np.diff(v) == 0))
130
+
131
+
132
+ def rank_normalize(x) -> np.ndarray:
133
+ r"""Rank-based normalization to :math:`[0,1]`, :math:`(r-1)/(\max r - 1)`."""
134
+ r = rank_vector(x)
135
+ m = r.max()
136
+ return (r - 1) / (m - 1) if m > 1 else np.zeros_like(r)
137
+
138
+
139
+ def soft_rank_vector(x, sigma) -> np.ndarray:
140
+ r"""Expected ranks of ``x`` under independent Gaussian errors with standard deviation ``sigma``.
141
+
142
+ ``sigma`` may be a scalar or one value per element. For ``sigma -> 0`` the
143
+ result tends to the mid-ranks.
144
+
145
+ >>> np.round(soft_rank_vector([0.0, 0.0, 10.0], 1e-9), 6).tolist()
146
+ [1.5, 1.5, 3.0]
147
+ """
148
+ a = np.asarray(x, dtype=float)
149
+ s = np.broadcast_to(np.asarray(sigma, dtype=float), a.shape)
150
+ diff = a[:, None] - a[None, :]
151
+ scale = np.sqrt(s[:, None] ** 2 + s[None, :] ** 2)
152
+ with np.errstate(divide="ignore", invalid="ignore"):
153
+ z = np.where(scale > 0, diff / np.where(scale > 0, scale, 1.0), np.sign(diff) * np.inf)
154
+ p = special.ndtr(z)
155
+ p[np.isnan(p)] = 0.5
156
+ np.fill_diagonal(p, 0.0)
157
+ return 1.0 + p.sum(axis=1)
158
+
159
+
160
+ def soft_rank_matrix(X, sigma=0.05, relative: bool = True) -> pd.DataFrame:
161
+ """Soft ranks of every column.
162
+
163
+ ``sigma`` is the error standard deviation; with ``relative=True`` it is given
164
+ as a fraction of the column's standard deviation (a scale-free choice).
165
+ """
166
+ df = as_frame(X)
167
+ out = {}
168
+ for c in df.columns:
169
+ v = df[c].to_numpy()
170
+ s = sigma * (np.std(v, ddof=1) if v.size > 1 else 1.0) if relative else sigma
171
+ out[c] = soft_rank_vector(v, s)
172
+ return pd.DataFrame(out, index=df.index)
173
+
174
+
175
+ def orient(X, directions) -> pd.DataFrame:
176
+ """Flip the columns (or rows) to be minimized so that larger is better everywhere.
177
+
178
+ ``directions`` maps column names to ``"max"`` or ``"min"`` (or is a list in
179
+ column order). Minimized columns are multiplied by -1, which reverses their
180
+ ranking and leaves maximized ones unchanged.
181
+ """
182
+ df = as_frame(X)
183
+ if isinstance(directions, dict):
184
+ dirs = [directions.get(c, "max") for c in df.columns]
185
+ else:
186
+ dirs = list(directions)
187
+ if len(dirs) != df.shape[1]:
188
+ raise ValueError("one direction per column is required")
189
+ out = df.copy()
190
+ for c, d in zip(df.columns, dirs):
191
+ if str(d).lower() in ("min", "minimize", "cost", "-1", "smaller"):
192
+ out[c] = -out[c]
193
+ return out