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/utility.py ADDED
@@ -0,0 +1,277 @@
1
+ r"""Utility function-based SRD (uSRD).
2
+
3
+ Ipkovich, Héberger, Sebestyén and Abonyi (2024) observed that the
4
+ transformation applied to the data before SRD and the rule that fuses the
5
+ reference are, in decision-analytic terms, *single-attribute utility functions*
6
+ :math:`u_j` and a *multi-attribute utility function*. The utility-based SRD of
7
+ indicator :math:`j` is
8
+
9
+ .. math:: \mathrm{uSRD}_j=\sum_{i=1}^{N}\bigl|\operatorname{rank}(u_j(x_{ij}))-\operatorname{rank}(\rho_i)\bigr|,
10
+
11
+ where the reference :math:`\rho_i` aggregates the utilities of row :math:`i`:
12
+
13
+ * additive: :math:`\rho_i=\sum_j w_j u_j(x_{ij})` (utilities on a common range, additive independence);
14
+ * multiplicative: :math:`1+\omega\rho_i=\prod_j(1+\omega w_j u_j(x_{ij}))`, with the scaling constant
15
+ :math:`\omega` solving :math:`1+\omega=\prod_j(1+\omega w_j)` (mutual utility independence;
16
+ :math:`\omega=0` is the additive case);
17
+ * preferential: :math:`\rho_i=\max_j w_j u_j(x_{ij})`;
18
+ * conjunctive (min) and disjunctive (max).
19
+
20
+ A strictly increasing utility leaves the ranks of its indicator unchanged
21
+ (:func:`is_rank_preserving`, eq. 1 of the paper) and influences uSRD only through
22
+ the reference; non-monotone utilities such as target-is-best desirabilities change
23
+ the ranks themselves. The module provides the transformation catalogue of the
24
+ paper (min-max, p-norm min-max, compare with leader, level, standardization, Pareto
25
+ scaling, unit length, rank, rank-normalization, log, Box-Cox, Yeo-Johnson,
26
+ logistic) together with empirical-distribution (quantile) utilities and the
27
+ Derringer-Suich and Harrington desirability functions.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ from collections.abc import Callable
33
+
34
+ import numpy as np
35
+ import pandas as pd
36
+ from scipy import optimize, stats
37
+
38
+ from ._utils import as_frame
39
+ from .core import SRDResult, srd
40
+ from .ranking import rank_normalize, rank_vector
41
+
42
+
43
+ # --------------------------------------------------------------------------- transformations
44
+ def minmax(x):
45
+ """Min-max scaling to [0, 1]."""
46
+ x = np.asarray(x, float)
47
+ r = np.ptp(x)
48
+ return (x - x.min()) / r if r > 0 else np.zeros_like(x)
49
+
50
+
51
+ def minmax_p(x, p: float = 2.0):
52
+ """Min-max scaling in the p-norm: ``(x - min) / ||x - min||_p``."""
53
+ x = np.asarray(x, float)
54
+ z = x - x.min()
55
+ nrm = (np.abs(z) ** p).sum() ** (1 / p)
56
+ return z / nrm if nrm > 0 else z
57
+
58
+
59
+ def compare_with_leader(x):
60
+ """``x / max(x)``."""
61
+ x = np.asarray(x, float)
62
+ return x / x.max()
63
+
64
+
65
+ def level_scale(x):
66
+ """``(x - mean) / mean``."""
67
+ x = np.asarray(x, float)
68
+ return (x - x.mean()) / x.mean()
69
+
70
+
71
+ def standardize(x):
72
+ """z-scores."""
73
+ x = np.asarray(x, float)
74
+ s = x.std(ddof=1)
75
+ return (x - x.mean()) / s if s > 0 else np.zeros_like(x)
76
+
77
+
78
+ def pareto_scale(x):
79
+ """``(x - mean) / sqrt(std)``."""
80
+ x = np.asarray(x, float)
81
+ s = x.std(ddof=1)
82
+ return (x - x.mean()) / np.sqrt(s) if s > 0 else np.zeros_like(x)
83
+
84
+
85
+ def unit_length(x):
86
+ """``x / ||x||_2``."""
87
+ x = np.asarray(x, float)
88
+ nrm = np.sqrt((x ** 2).sum())
89
+ return x / nrm if nrm > 0 else x
90
+
91
+
92
+ def log_center(x):
93
+ """``log10(x) - mean(log10(x))`` (positive data)."""
94
+ lx = np.log10(np.asarray(x, float))
95
+ return lx - lx.mean()
96
+
97
+
98
+ def boxcox(x, lam: float | None = None):
99
+ """Box-Cox transformation (positive data); ``lam=None`` estimates it by maximum likelihood."""
100
+ x = np.asarray(x, float)
101
+ if lam is None:
102
+ return stats.boxcox(x)[0]
103
+ return stats.boxcox(x, lmbda=lam)
104
+
105
+
106
+ def yeojohnson(x, lam: float | None = None):
107
+ """Yeo-Johnson transformation; ``lam=None`` estimates it by maximum likelihood."""
108
+ x = np.asarray(x, float)
109
+ if lam is None:
110
+ return stats.yeojohnson(x)[0]
111
+ return stats.yeojohnson(x, lmbda=lam)
112
+
113
+
114
+ def logistic(x, center: float | None = None, scale: float | None = None):
115
+ """Logistic (sigmoid) utility ``1 / (1 + exp(-(x - center)/scale))`` (defaults: median and IQR/2)."""
116
+ x = np.asarray(x, float)
117
+ c = np.median(x) if center is None else center
118
+ s = (np.subtract(*np.percentile(x, [75, 25])) / 2 or 1.0) if scale is None else scale
119
+ return 1.0 / (1.0 + np.exp(-(x - c) / s))
120
+
121
+
122
+ def ecdf(x):
123
+ """Empirical cumulative distribution function value of every element (a quantile utility)."""
124
+ x = np.asarray(x, float)
125
+ return rank_vector(x, ties="max") / x.size
126
+
127
+
128
+ def derringer(x, low: float, high: float, kind: str = "larger", target: float | None = None, s: float = 1.0, t: float = 1.0):
129
+ r"""Derringer-Suich desirability.
130
+
131
+ ``kind="larger"``: 0 below ``low``, :math:`((x-L)/(U-L))^s` between, 1 above ``high``;
132
+ ``kind="smaller"``: 1 below ``low``, :math:`((U-x)/(U-L))^s` between, 0 above;
133
+ ``kind="target"``: two-sided with exponents ``s`` (below the target) and ``t`` (above).
134
+ """
135
+ x = np.asarray(x, float)
136
+ L, U = float(low), float(high)
137
+ if kind == "larger":
138
+ return np.clip((x - L) / (U - L), 0, 1) ** s
139
+ if kind == "smaller":
140
+ return np.clip((U - x) / (U - L), 0, 1) ** s
141
+ if kind == "target":
142
+ T = (L + U) / 2 if target is None else float(target)
143
+ left = np.clip((x - L) / (T - L), 0, 1) ** s
144
+ right = np.clip((U - x) / (U - T), 0, 1) ** t
145
+ return np.where(x <= T, left, right)
146
+ raise ValueError("kind must be 'larger', 'smaller' or 'target'")
147
+
148
+
149
+ def derringer_percentile(x, lower: float = 25, upper: float = 75, kind: str = "larger", s: float = 1.0):
150
+ """Derringer desirability with the zone limits set at percentiles of the data.
151
+
152
+ The detrimental zone lies beyond the ``lower`` (or ``upper``) percentile, the
153
+ acceptable zone beyond the other one, with a linear (``s=1``) transition between.
154
+ """
155
+ x = np.asarray(x, float)
156
+ lo, hi = np.percentile(x, [lower, upper])
157
+ if hi <= lo:
158
+ hi = lo + 1e-12
159
+ return derringer(x, lo, hi, kind=kind, s=s)
160
+
161
+
162
+ def harrington(x, low: float, high: float, kind: str = "larger"):
163
+ r"""Harrington's one-sided desirability :math:`\exp(-\exp(-z))`, with ``low`` and ``high``
164
+ mapped to the desirabilities 0.2 and 0.8 (``kind="smaller"`` mirrors it)."""
165
+ x = np.asarray(x, float)
166
+ z_lo, z_hi = -np.log(-np.log(0.2)), -np.log(-np.log(0.8))
167
+ b1 = (z_hi - z_lo) / (high - low)
168
+ b0 = z_lo - b1 * low
169
+ z = b0 + b1 * x
170
+ if kind == "smaller":
171
+ z = b0 + b1 * (high + low - x)
172
+ return np.exp(-np.exp(-z))
173
+
174
+
175
+ TRANSFORMS: dict[str, Callable] = {
176
+ "identity": lambda x: np.asarray(x, float), "minmax": minmax, "minmax_p": minmax_p, "leader": compare_with_leader,
177
+ "level": level_scale, "standardize": standardize, "pareto": pareto_scale, "unit": unit_length, "rank": rank_vector,
178
+ "rank_normalize": rank_normalize, "log": log_center, "boxcox": boxcox, "yeojohnson": yeojohnson,
179
+ "logistic": logistic, "ecdf": ecdf, "derringer_percentile": derringer_percentile,
180
+ }
181
+
182
+
183
+ def transform(X, utilities="minmax", directions=None) -> pd.DataFrame:
184
+ """Apply single-attribute utilities column by column.
185
+
186
+ ``utilities`` is a transformation name, a callable, or a mapping
187
+ ``{column: name or callable}``. ``directions`` (``{column: "min"/"max"}``)
188
+ reverses utilities of indicators to be minimized (``1 - u`` for utilities on
189
+ [0, 1], ``-u`` otherwise).
190
+ """
191
+ df = as_frame(X)
192
+ out = {}
193
+ for c in df.columns:
194
+ spec = utilities.get(c, "identity") if isinstance(utilities, dict) else utilities
195
+ f = TRANSFORMS[spec] if isinstance(spec, str) else spec
196
+ u = np.asarray(f(df[c].to_numpy()), float)
197
+ if directions is not None and str(directions.get(c, "max")).lower() == "min":
198
+ u = 1 - u if (u.min() >= 0 and u.max() <= 1) else -u
199
+ out[c] = u
200
+ return pd.DataFrame(out, index=df.index)
201
+
202
+
203
+ def is_rank_preserving(u: Callable, x) -> bool:
204
+ """Eq. (1) of Ipkovich et al. (2024): does the utility keep the ranking of ``x``?"""
205
+ x = np.asarray(x, float)
206
+ return bool(np.array_equal(rank_vector(np.asarray(u(x), float)), rank_vector(x)))
207
+
208
+
209
+ # --------------------------------------------------------------------------- aggregation
210
+ def multiplicative_constant(weights) -> float:
211
+ r"""Scaling constant :math:`\omega` of the multiplicative utility, :math:`1+\omega=\prod_j(1+\omega w_j)`.
212
+
213
+ Returns 0 when the weights sum to one (additive case).
214
+
215
+ >>> round(multiplicative_constant([0.3, 0.3]), 4)
216
+ 4.4444
217
+ """
218
+ w = np.asarray(weights, float)
219
+ s = w.sum()
220
+ if abs(s - 1) < 1e-12:
221
+ return 0.0
222
+
223
+ def f(om):
224
+ return np.prod(1 + om * w) - (1 + om)
225
+
226
+ if s < 1: # omega > 0
227
+ hi = 1.0
228
+ while f(hi) < 0:
229
+ hi *= 2
230
+ return float(optimize.brentq(f, 1e-12, hi))
231
+ return float(optimize.brentq(f, -1 + 1e-12, -1e-12))
232
+
233
+
234
+ def aggregate(U, method: str = "additive", weights=None) -> np.ndarray:
235
+ """Aggregate a utility matrix row by row into the reference (gold standard).
236
+
237
+ ``method``: ``"additive"``, ``"multiplicative"``, ``"preferential"``,
238
+ ``"min"`` (conjunction), ``"max"`` (disjunction), ``"geometric"``.
239
+ """
240
+ A = as_frame(U).to_numpy(float)
241
+ m = A.shape[1]
242
+ w = np.full(m, 1.0 / m) if weights is None else np.asarray(weights, float)
243
+ if method == "additive":
244
+ return A @ w
245
+ if method == "multiplicative":
246
+ om = multiplicative_constant(w)
247
+ if om == 0.0:
248
+ return A @ w
249
+ return (np.prod(1 + om * w[None, :] * A, axis=1) - 1) / om
250
+ if method == "preferential":
251
+ return (A * w[None, :]).max(axis=1)
252
+ if method == "min":
253
+ return A.min(axis=1)
254
+ if method == "max":
255
+ return A.max(axis=1)
256
+ if method == "geometric":
257
+ if (A <= 0).any():
258
+ raise ValueError("geometric aggregation needs positive utilities")
259
+ return np.exp(np.log(A) @ (w / w.sum()))
260
+ raise ValueError("method must be 'additive', 'multiplicative', 'preferential', 'min', 'max' or 'geometric'")
261
+
262
+
263
+ def usrd(X, utilities="minmax", aggregation: str = "additive", weights=None, directions=None, reference=None,
264
+ ties: str = "average", **srd_kwargs) -> SRDResult:
265
+ """Utility function-based SRD (Ipkovich et al., 2024).
266
+
267
+ The columns of ``X`` are mapped to utilities (:func:`transform`), the
268
+ reference is the multi-attribute utility (:func:`aggregate`) unless an
269
+ external ``reference`` is given, and SRD is computed on the utilities. The
270
+ utility matrix is stored in ``result.meta["utilities"]``.
271
+ """
272
+ U = transform(X, utilities, directions=directions)
273
+ ref = aggregate(U, aggregation, weights) if reference is None else reference
274
+ res = srd(U, reference=ref, ties=ties, **srd_kwargs)
275
+ res.reference_method = f"{aggregation} utility" if reference is None else res.reference_method
276
+ res.meta.update({"utilities": U, "aggregation": aggregation, "weights": weights, "original": as_frame(X), "label": "uSRD"})
277
+ return res