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/parcoord.py ADDED
@@ -0,0 +1,283 @@
1
+ r"""SRD-based ordering of parallel coordinates.
2
+
3
+ In a parallel-coordinate plot of ranks every object is a polyline; two adjacent
4
+ axes produce one line crossing for every discordant pair of objects, so the
5
+ number of crossings between axes :math:`a` and :math:`b` is the Kendall distance
6
+ of their rankings, :math:`c=(1-\tau)N(N-1)/4` without ties. The plot is easiest
7
+ to read when similar variables are neighbours.
8
+
9
+ Ipkovich, Héberger and Abonyi (2021) order the axes by SRD: the reference sits at
10
+ position 0, every variable at the distance :math:`\mathrm{SRD}_{0j}` from it, and
11
+ the *deviation angle* of two variables seen from the reference,
12
+
13
+ .. math:: \cos\gamma_{jm}=\frac{\mathrm{SRD}_{0j}^2+\mathrm{SRD}_{0m}^2-\mathrm{SRD}_{jm}^2}{2\,\mathrm{SRD}_{0j}\mathrm{SRD}_{0m}},
14
+
15
+ decides on which side a variable is placed (:func:`angle_order`, a faithful port
16
+ of the authors' MATLAB/Octave toolbox, github.com/abonyilab/parcoord). The module
17
+ adds orderings that minimize the total distance (or the exact number of
18
+ crossings) of adjacent axes as a travelling-salesman path, solved exactly by the
19
+ Held-Karp dynamic programme for up to 13 axes and by nearest neighbour plus 2-opt
20
+ above, and the multidimensional scaling order used as a benchmark in the paper.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import itertools
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+
30
+ from ._utils import as_frame
31
+ from .core import pairwise_srd
32
+ from .ranking import rank_matrix
33
+
34
+
35
+ def crossings(a, b) -> int:
36
+ """Number of line crossings between two adjacent axes (discordant pairs of objects)."""
37
+ a = np.asarray(a, float)
38
+ b = np.asarray(b, float)
39
+ iu = np.triu_indices(a.size, 1)
40
+ da = (a[:, None] - a[None, :])[iu]
41
+ db = (b[:, None] - b[None, :])[iu]
42
+ return int(np.sum(da * db < 0))
43
+
44
+
45
+ def crossing_matrix(X, ties: str = "average") -> pd.DataFrame:
46
+ """Crossings of every pair of variables (on ranks)."""
47
+ R = rank_matrix(X, ties=ties)
48
+ cols = list(R.columns)
49
+ M = np.zeros((len(cols), len(cols)), dtype=int)
50
+ for i, j in itertools.combinations(range(len(cols)), 2):
51
+ M[i, j] = M[j, i] = crossings(R.iloc[:, i], R.iloc[:, j])
52
+ return pd.DataFrame(M, index=cols, columns=cols)
53
+
54
+
55
+ def total_crossings(X, order) -> int:
56
+ """Total number of crossings of a parallel-coordinate plot with the given axis order."""
57
+ R = rank_matrix(as_frame(X)[list(order)])
58
+ return int(sum(crossings(R.iloc[:, k], R.iloc[:, k + 1]) for k in range(R.shape[1] - 1)))
59
+
60
+
61
+ def kendall_crossings(a, b) -> float:
62
+ r"""The estimate :math:`(1-\tau)N(N-1)/4` of the crossings (exact without ties)."""
63
+ from scipy.stats import kendalltau
64
+
65
+ a = np.asarray(a, float)
66
+ t = kendalltau(a, b).statistic
67
+ t = 0.0 if not np.isfinite(t) else t
68
+ return float((1 - t) * a.size * (a.size - 1) / 4)
69
+
70
+
71
+ def deviation_angle(s0j: float, s0m: float, sjm: float) -> float:
72
+ """Deviation angle (degrees) of two variables seen from the reference (law of cosines)."""
73
+ if s0j <= 0 or s0m <= 0:
74
+ return float("nan")
75
+ c = (s0j ** 2 + s0m ** 2 - sjm ** 2) / (2 * s0j * s0m)
76
+ return float(np.degrees(np.arccos(np.clip(c, -1, 1))))
77
+
78
+
79
+ def angle_matrix(X, reference="mean", ties: str = "average") -> pd.DataFrame:
80
+ """Deviation angles of every pair of variables (reference = vertex)."""
81
+ D = pairwise_srd(X, ties=ties, reference=reference)
82
+ cols = [c for c in D.columns if c != "reference"]
83
+ M = np.full((len(cols), len(cols)), np.nan)
84
+ for i, j in itertools.product(range(len(cols)), repeat=2):
85
+ if i != j:
86
+ M[i, j] = deviation_angle(D.loc["reference", cols[i]], D.loc["reference", cols[j]], D.loc[cols[i], cols[j]])
87
+ return pd.DataFrame(M, index=cols, columns=cols)
88
+
89
+
90
+ def srd_order(X, reference="mean", ties: str = "average") -> tuple[list[str], np.ndarray]:
91
+ """Classical SRD order: the variables sorted by their SRD from the reference; positions = SRD values."""
92
+ D = pairwise_srd(X, ties=ties, reference=reference)
93
+ s = D.loc["reference"].drop("reference").sort_values(kind="stable")
94
+ return list(s.index), s.to_numpy()
95
+
96
+
97
+ def angle_order(X, reference="mean", ties: str = "average", matlab_compatible: bool = True) -> tuple[list[str], np.ndarray]:
98
+ """Deviation-angle ordering of Ipkovich, Héberger and Abonyi (2021).
99
+
100
+ The reference is the left anchor and the variable closest to it the right
101
+ anchor. The remaining variables are taken in increasing SRD; each is placed
102
+ next to the anchor with the smaller deviation angle (an angle is taken as 0
103
+ when the triangle inequality fails) and becomes the new anchor on that side.
104
+ Right-hand variables are placed at ``+SRD``, left-hand ones at ``-SRD``.
105
+
106
+ With ``matlab_compatible=True`` the behaviour of the original code is kept:
107
+ as long as the left anchor is the reference itself, its angle is undefined and
108
+ the variable goes to the left. With ``False`` the anchor closer in SRD wins in
109
+ that situation.
110
+
111
+ Returns the order (including ``"reference"``) and the axis positions.
112
+ """
113
+ D = pairwise_srd(X, ties=ties, reference=reference)
114
+ s0 = D.loc["reference"].drop("reference").sort_values(kind="stable")
115
+ names = ["reference"] + list(s0.index)
116
+ S = D.loc[names, names].to_numpy()
117
+ left, right = 0, 1
118
+ seq = [0, 1]
119
+ pos = {0: 0.0, 1: S[0, 1]}
120
+ for i in range(2, len(names)):
121
+ rgh = deviation_angle(S[0, i], S[0, right], S[i, right]) if S[0, i] - S[0, right] <= S[i, right] else 0.0
122
+ if left == 0 and not matlab_compatible:
123
+ # the angle at the reference itself is undefined: the closer anchor (in SRD) wins
124
+ if S[i, right] <= S[i, 0]:
125
+ seq.append(i)
126
+ pos[i] = S[0, i]
127
+ right = i
128
+ else:
129
+ seq.insert(0, i)
130
+ pos[i] = -S[0, i]
131
+ left = i
132
+ continue
133
+ if left == 0:
134
+ lft = np.nan
135
+ else:
136
+ lft = deviation_angle(S[0, i], S[0, left], S[i, left]) if S[0, i] - S[0, left] <= S[i, left] else 0.0
137
+ if np.isfinite(lft) and rgh <= lft:
138
+ seq.append(i)
139
+ pos[i] = S[0, i]
140
+ right = i
141
+ elif not np.isfinite(lft) or rgh > lft:
142
+ seq.insert(0, i)
143
+ pos[i] = -S[0, i]
144
+ left = i
145
+ order = [names[k] for k in seq]
146
+ return order, np.array([pos[k] for k in seq])
147
+
148
+
149
+ def mds_order(X, ties: str = "average", reference="mean") -> tuple[list[str], np.ndarray]:
150
+ """Order by the first coordinate of classical MDS of the Kendall dissimilarity ``1 - tau``."""
151
+ from scipy.stats import kendalltau
152
+
153
+ df = as_frame(X)
154
+ ref = None
155
+ if reference is not None:
156
+ from .reference import make_reference
157
+
158
+ ref = make_reference(df, reference)
159
+ df = pd.concat([pd.Series(ref, index=df.index, name="reference"), df], axis=1)
160
+ R = rank_matrix(df, ties=ties).to_numpy()
161
+ m = R.shape[1]
162
+ Dm = np.zeros((m, m))
163
+ for i, j in itertools.combinations(range(m), 2):
164
+ t = kendalltau(R[:, i], R[:, j]).statistic
165
+ Dm[i, j] = Dm[j, i] = 1 - (t if np.isfinite(t) else 0)
166
+ J = np.eye(m) - 1 / m
167
+ B = -0.5 * J @ (Dm ** 2) @ J
168
+ w, V = np.linalg.eigh(B)
169
+ x = V[:, -1] * np.sqrt(max(w[-1], 0))
170
+ idx = np.argsort(x, kind="stable")
171
+ return [df.columns[k] for k in idx], x[idx]
172
+
173
+
174
+ def _held_karp_path(D: np.ndarray) -> list[int]:
175
+ m = D.shape[0]
176
+ full = 1 << m
177
+ best = np.full((full, m), np.inf)
178
+ parent = np.full((full, m), -1, dtype=int)
179
+ for j in range(m):
180
+ best[1 << j, j] = 0.0
181
+ for S in range(full):
182
+ for j in range(m):
183
+ if not (S >> j) & 1 or not np.isfinite(best[S, j]):
184
+ continue
185
+ for k in range(m):
186
+ if (S >> k) & 1:
187
+ continue
188
+ T = S | (1 << k)
189
+ c = best[S, j] + D[j, k]
190
+ if c < best[T, k]:
191
+ best[T, k] = c
192
+ parent[T, k] = j
193
+ end = int(np.argmin(best[full - 1]))
194
+ path, S = [end], full - 1
195
+ while parent[S, path[-1]] != -1:
196
+ j = parent[S, path[-1]]
197
+ S ^= 1 << path[-1]
198
+ path.append(j)
199
+ return path[::-1]
200
+
201
+
202
+ def _two_opt(path: list[int], D: np.ndarray) -> list[int]:
203
+ improved = True
204
+ best = path[:]
205
+
206
+ def length(p):
207
+ return sum(D[p[k], p[k + 1]] for k in range(len(p) - 1))
208
+
209
+ cur = length(best)
210
+ while improved:
211
+ improved = False
212
+ for i in range(0, len(best) - 1):
213
+ for j in range(i + 2, len(best) + 1):
214
+ cand = best[:i] + best[i:j][::-1] + best[j:]
215
+ c = length(cand)
216
+ if c < cur - 1e-12:
217
+ best, cur, improved = cand, c, True
218
+ return best
219
+
220
+
221
+ def tsp_order(X, criterion: str = "srd", reference=None, ties: str = "average", exact_limit: int = 13) -> tuple[list[str], np.ndarray]:
222
+ """Axis order minimizing the summed SRD (or the exact crossings) of adjacent axes.
223
+
224
+ ``criterion="srd"`` uses the pairwise SRD matrix, ``"crossings"`` the exact
225
+ crossing counts. With a ``reference`` it is included as an axis. Positions are
226
+ the cumulative distances along the path.
227
+ """
228
+ df = as_frame(X)
229
+ if reference is not None:
230
+ from .reference import make_reference
231
+
232
+ df = pd.concat([pd.Series(make_reference(df, reference), index=df.index, name="reference"), df], axis=1)
233
+ if criterion == "crossings":
234
+ D = crossing_matrix(df, ties=ties).to_numpy(float)
235
+ else:
236
+ D = pairwise_srd(df, ties=ties).to_numpy()
237
+ m = D.shape[0]
238
+ if m <= exact_limit:
239
+ path = _held_karp_path(D)
240
+ else:
241
+ start = int(np.argmin(D.sum(axis=1)))
242
+ path, left = [start], set(range(m)) - {start}
243
+ while left:
244
+ nxt = min(left, key=lambda k: D[path[-1], k])
245
+ path.append(nxt)
246
+ left.remove(nxt)
247
+ path = _two_opt(path, D)
248
+ pos = np.concatenate([[0.0], np.cumsum([D[path[k], path[k + 1]] for k in range(m - 1)])])
249
+ return [df.columns[k] for k in path], pos
250
+
251
+
252
+ def order_axes(X, method: str = "angle", reference="mean", ties: str = "average") -> tuple[list[str], np.ndarray]:
253
+ """Dispatch: ``"alphabetical"``, ``"srd"``, ``"angle"``, ``"mds"``, ``"tsp"``, ``"tsp-crossings"``."""
254
+ df = as_frame(X)
255
+ if method == "alphabetical":
256
+ o = sorted(df.columns)
257
+ return o, np.arange(len(o), dtype=float)
258
+ if method == "srd":
259
+ return srd_order(df, reference, ties)
260
+ if method == "angle":
261
+ return angle_order(df, reference, ties)
262
+ if method == "mds":
263
+ return mds_order(df, ties, reference)
264
+ if method == "tsp":
265
+ return tsp_order(df, "srd", reference, ties)
266
+ if method == "tsp-crossings":
267
+ return tsp_order(df, "crossings", reference, ties)
268
+ raise ValueError("method must be 'alphabetical', 'srd', 'angle', 'mds', 'tsp' or 'tsp-crossings'")
269
+
270
+
271
+ def compare_orderings(X, reference="mean", methods=("alphabetical", "mds", "srd", "angle", "tsp", "tsp-crossings")) -> pd.DataFrame:
272
+ """Total crossings of the parallel-coordinate plot for several orderings (the benchmark of the paper)."""
273
+ from .reference import make_reference
274
+
275
+ df = as_frame(X)
276
+ ext = pd.concat([pd.Series(make_reference(df, reference), index=df.index, name="reference"), df], axis=1)
277
+ rows = []
278
+ for m in methods:
279
+ order, _ = order_axes(df, m, reference)
280
+ if "reference" not in order:
281
+ order = ["reference"] + list(order)
282
+ rows.append({"method": m, "crossings": total_crossings(ext, order), "order": " | ".join(order)})
283
+ return pd.DataFrame(rows).set_index("method").sort_values("crossings")
srdkit/pareto.py ADDED
@@ -0,0 +1,126 @@
1
+ r"""Pareto fronts, non-dominated sorting and post-Pareto analysis with SRD.
2
+
3
+ A solution dominates another if it is at least as good in every objective and
4
+ strictly better in one. Removing the non-dominated set repeatedly gives the
5
+ "onion" layers of non-dominated sorting (Deb et al., 2002), the ranking used on
6
+ the NMF-reduced objectives by Abonyi, Ipkovich, Dörgő and Héberger (2023).
7
+ The relative entropy of the layer sizes measures how evenly a ranking spreads
8
+ the solutions over its ranks (their eq. 13):
9
+
10
+ .. math:: \mathrm{RE}(D)=\frac{\sum_r \frac{D(r)}{N}\log\frac{D(r)}{N}}{\log(1/N)} .
11
+
12
+ Post-Pareto analysis (Lourenço and Lebensztajn, 2018) has to pick one solution
13
+ of a Pareto set; :func:`post_pareto_srd` ranks the Pareto solutions with several
14
+ MCDM methods, uses SRD to find which methods agree with their consensus, and uses
15
+ the transposed SRD problem to pick the solution that is consistently at the top.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import numpy as np
21
+
22
+ from ._utils import as_frame, as_rng
23
+
24
+
25
+ def _oriented(F, directions):
26
+ df = as_frame(F)
27
+ A = df.to_numpy(float)
28
+ if directions is not None:
29
+ if isinstance(directions, dict):
30
+ directions = [directions.get(c, "max") for c in df.columns]
31
+ sign = np.array([-1.0 if str(d).lower() == "min" else 1.0 for d in directions])
32
+ A = A * sign
33
+ return df, A
34
+
35
+
36
+ def dominates(a, b) -> bool:
37
+ """Whether ``a`` dominates ``b`` (maximization)."""
38
+ a, b = np.asarray(a, float), np.asarray(b, float)
39
+ return bool(np.all(a >= b) and np.any(a > b))
40
+
41
+
42
+ def nondominated_layers(F, directions=None) -> np.ndarray:
43
+ """Non-dominated sorting: layer index of every solution (0 = Pareto front), maximization by default."""
44
+ _, A = _oriented(F, directions)
45
+ n = A.shape[0]
46
+ ge = (A[:, None, :] >= A[None, :, :]).all(axis=2)
47
+ gt = (A[:, None, :] > A[None, :, :]).any(axis=2)
48
+ dom = ge & gt # dom[i, j]: i dominates j
49
+ count = dom.sum(axis=0)
50
+ layer = np.full(n, -1)
51
+ current = np.flatnonzero(count == 0)
52
+ k = 0
53
+ while current.size:
54
+ layer[current] = k
55
+ for i in current:
56
+ count[dom[i]] -= 1
57
+ nxt = np.flatnonzero((count == 0) & (layer == -1))
58
+ current = nxt
59
+ k += 1
60
+ return layer
61
+
62
+
63
+ def pareto_front(F, directions=None) -> np.ndarray:
64
+ """Boolean mask of the non-dominated solutions."""
65
+ return nondominated_layers(F, directions) == 0
66
+
67
+
68
+ def relative_entropy(ranks) -> float:
69
+ """Relative entropy of the rank (layer) frequencies, eq. 13 of Abonyi et al. (2023): 1 = all ranks distinct."""
70
+ r = np.asarray(ranks)
71
+ N = r.size
72
+ _, cnt = np.unique(r, return_counts=True)
73
+ p = cnt / N
74
+ return float((p * np.log(p)).sum() / np.log(1.0 / N)) if N > 1 else 1.0
75
+
76
+
77
+ def hypervolume(F, reference_point=None, directions=None, n_samples: int = 200_000, random_state=None) -> float:
78
+ """Hypervolume dominated by the Pareto front (maximization); exact in 2-D, Monte Carlo above.
79
+
80
+ ``reference_point`` defaults to the component-wise minimum (a point dominated by all).
81
+ """
82
+ _, A = _oriented(F, directions)
83
+ A = A[pareto_front(A)]
84
+ ref = A.min(axis=0) if reference_point is None else np.asarray(reference_point, float)
85
+ if A.shape[1] == 2:
86
+ P = A[np.argsort(-A[:, 0])]
87
+ hv, ymax = 0.0, ref[1]
88
+ for x, y in P:
89
+ if y > ymax:
90
+ hv += (x - ref[0]) * (y - ymax)
91
+ ymax = y
92
+ return float(hv)
93
+ rng = as_rng(random_state)
94
+ hi = A.max(axis=0)
95
+ S = rng.uniform(ref, hi, size=(n_samples, A.shape[1]))
96
+ dom = np.zeros(n_samples, bool)
97
+ for a in A:
98
+ dom |= (S <= a).all(axis=1)
99
+ return float(dom.mean() * np.prod(hi - ref))
100
+
101
+
102
+ def post_pareto_srd(F, weights=None, directions=None, methods=None, pareto_only: bool = True) -> dict:
103
+ """Post-Pareto selection with SRD.
104
+
105
+ 1. (optionally) keep the Pareto-optimal solutions;
106
+ 2. score them with several MCDM methods (:func:`srdkit.mcda.mcda_scores`);
107
+ 3. compare the methods by SRD against the mean-rank consensus;
108
+ 4. transpose: methods become objects, solutions become columns, the row
109
+ maximum (best score of every method) is the reference; the solution with
110
+ the smallest SRD is the one most consistently at the top.
111
+
112
+ Returns a dict with the scores, the method comparison and the solution ranking.
113
+ """
114
+ from .core import srd
115
+ from .mcda import mcda_scores
116
+
117
+ df, _ = _oriented(F, None)
118
+ mask = pareto_front(df, directions) if pareto_only else np.ones(len(df), bool)
119
+ P = df[mask]
120
+ S = mcda_scores(P, weights, directions, methods)
121
+ methods_srd = srd(S, reference="borda")
122
+ # transposed problem: rank solutions within every method on a common [0, 1] scale
123
+ Sn = (S - S.min()) / (S.max() - S.min()).replace(0, 1)
124
+ sol = srd(Sn.T, reference="max")
125
+ labels = {str(i): i for i in P.index}
126
+ return {"pareto": P, "scores": S, "methods": methods_srd, "solutions": sol, "best": labels.get(sol.best, sol.best)}