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/__init__.py +101 -0
- srdkit/_utils.py +75 -0
- srdkit/_version.py +1 -0
- srdkit/anova.py +185 -0
- srdkit/clustering.py +110 -0
- srdkit/core.py +364 -0
- srdkit/datasets/__init__.py +160 -0
- srdkit/datasets/data/co2_2018.csv +148 -0
- srdkit/diagnostics.py +186 -0
- srdkit/distances.py +204 -0
- srdkit/distribution.py +503 -0
- srdkit/framework.py +368 -0
- srdkit/fusion.py +221 -0
- srdkit/gpcm.py +138 -0
- srdkit/mcda.py +201 -0
- srdkit/nmf.py +141 -0
- srdkit/parcoord.py +283 -0
- srdkit/pareto.py +126 -0
- srdkit/promethee.py +371 -0
- srdkit/ranking.py +193 -0
- srdkit/reference.py +232 -0
- srdkit/report.py +114 -0
- srdkit/representation.py +127 -0
- srdkit/segmentation.py +247 -0
- srdkit/simulate.py +171 -0
- srdkit/tournament.py +167 -0
- srdkit/utility.py +277 -0
- srdkit/validation.py +501 -0
- srdkit/value.py +189 -0
- srdkit/viz/__init__.py +31 -0
- srdkit/viz/_style.py +87 -0
- srdkit/viz/applications.py +156 -0
- srdkit/viz/basic.py +201 -0
- srdkit/viz/framework.py +148 -0
- srdkit/viz/maps.py +145 -0
- srdkit/viz/validation.py +149 -0
- srdkit/weighted.py +167 -0
- srdkit/weights.py +230 -0
- srdkit-1.0.dist-info/METADATA +151 -0
- srdkit-1.0.dist-info/RECORD +42 -0
- srdkit-1.0.dist-info/WHEEL +4 -0
- srdkit-1.0.dist-info/licenses/LICENSE +21 -0
srdkit/viz/maps.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""SRD maps, constellations, dendrograms and SRD-ordered parallel coordinates."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from matplotlib import pyplot as plt
|
|
8
|
+
|
|
9
|
+
from ._style import BRAND, GRAY, INK, REFERENCE_COLOR, VERDICT_COLORS, ax_or_new, cat_colors, despine
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def plot_srd_map(coords: pd.DataFrame, ax=None, verdicts=None, labels: bool = True):
|
|
13
|
+
"""Scatter of an :func:`srdkit.srd_map` embedding; the reference is a green star at the origin."""
|
|
14
|
+
ax = ax_or_new(ax, (5.0, 4.4))
|
|
15
|
+
for name, (x, y) in coords[["dim1", "dim2"]].iterrows():
|
|
16
|
+
if name == "reference":
|
|
17
|
+
ax.plot(x, y, marker="*", ms=14, color=REFERENCE_COLOR, zorder=3)
|
|
18
|
+
continue
|
|
19
|
+
col = VERDICT_COLORS.get(verdicts.get(name), BRAND) if verdicts is not None else BRAND
|
|
20
|
+
ax.plot(x, y, "o", ms=6, color=col)
|
|
21
|
+
if labels:
|
|
22
|
+
ax.annotate(str(name), (x, y), xytext=(4, 3), textcoords="offset points", fontsize=7.5, color=INK)
|
|
23
|
+
ax.set_aspect("equal", adjustable="datalim")
|
|
24
|
+
st = coords.attrs.get("stress")
|
|
25
|
+
ax.set_xlabel("dimension 1" + (f" (stress = {st:.3f})" if st is not None else ""))
|
|
26
|
+
ax.set_ylabel("dimension 2")
|
|
27
|
+
despine(ax)
|
|
28
|
+
return ax
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def plot_constellation(const: pd.DataFrame, ax=None, verdicts=None, rings=(0.25, 0.5, 2 / 3, 0.75, 1.0), percentiles=None):
|
|
32
|
+
"""Polar SRD constellation: the reference at the centre, every solution at its exact normalized SRD.
|
|
33
|
+
|
|
34
|
+
Rings mark normalized SRD levels (2/3 is the expected value of a random
|
|
35
|
+
ranking); ``percentiles`` (a dict as returned by
|
|
36
|
+
:meth:`SRDDistribution.percentiles`) adds the XX1 and XX19 circles.
|
|
37
|
+
"""
|
|
38
|
+
ax = ax_or_new(ax, (5.0, 5.0))
|
|
39
|
+
t = np.linspace(0, 2 * np.pi, 361)
|
|
40
|
+
for r in rings:
|
|
41
|
+
ax.plot(r * np.cos(t), r * np.sin(t), color=GRAY, lw=0.6, ls="--" if abs(r - 2 / 3) < 1e-9 else ":")
|
|
42
|
+
ax.text(r * np.cos(np.radians(100)), r * np.sin(np.radians(100)), f"{100 * r:.0f}%", fontsize=6.5, color=GRAY)
|
|
43
|
+
if percentiles is not None:
|
|
44
|
+
for key in ("XX1", "XX19"):
|
|
45
|
+
r = percentiles[key]
|
|
46
|
+
ax.plot(r * np.cos(t), r * np.sin(t), color=VERDICT_COLORS["reversed" if key == "XX19" else "similar"],
|
|
47
|
+
lw=0.8, alpha=0.6)
|
|
48
|
+
ax.plot(0, 0, marker="*", ms=14, color=REFERENCE_COLOR, zorder=3)
|
|
49
|
+
for name, row in const.iterrows():
|
|
50
|
+
col = VERDICT_COLORS.get(verdicts.get(name), BRAND) if verdicts is not None else BRAND
|
|
51
|
+
ax.plot([0, row.x], [0, row.y], color=col, lw=0.6, alpha=0.5)
|
|
52
|
+
ax.plot(row.x, row.y, "o", ms=6, color=col)
|
|
53
|
+
ax.annotate(str(name), (row.x, row.y), xytext=(4, 3), textcoords="offset points", fontsize=7.5, color=INK)
|
|
54
|
+
lim = max(1.02, float(const["radius"].max()) * 1.1)
|
|
55
|
+
ax.set_xlim(-lim, lim)
|
|
56
|
+
ax.set_ylim(-lim, lim)
|
|
57
|
+
ax.set_aspect("equal")
|
|
58
|
+
ax.axis("off")
|
|
59
|
+
st = const.attrs.get("stress")
|
|
60
|
+
if st is not None:
|
|
61
|
+
ax.set_title(f"SRD constellation (stress {st:.3f})", fontsize=9, loc="left")
|
|
62
|
+
return ax
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def plot_dendrogram(X, ax=None, method: str = "average", kind: str = "srd", color_threshold=None):
|
|
66
|
+
"""Dendrogram of the solutions from pairwise SRD-type dissimilarities."""
|
|
67
|
+
from scipy.cluster import hierarchy
|
|
68
|
+
|
|
69
|
+
from ..clustering import srd_linkage
|
|
70
|
+
|
|
71
|
+
Z, labels = srd_linkage(X, method=method, kind=kind)
|
|
72
|
+
ax = ax_or_new(ax, (0.45 * len(labels) + 2, 3.4))
|
|
73
|
+
hierarchy.dendrogram(Z, labels=labels, ax=ax, color_threshold=color_threshold, above_threshold_color=GRAY,
|
|
74
|
+
leaf_rotation=90, leaf_font_size=8)
|
|
75
|
+
ax.set_ylabel(f"{kind} dissimilarity")
|
|
76
|
+
despine(ax, ("left",))
|
|
77
|
+
return ax
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def plot_parallel(X, reference="mean", method: str = "angle", ax=None, color_by: str = "quantile", spacing: str = "srd",
|
|
81
|
+
show_reference: bool = True, lw: float = 0.7, alpha: float = 0.7):
|
|
82
|
+
"""Parallel coordinates of the ranks with SRD-based axis order (Ipkovich, Héberger and Abonyi, 2021).
|
|
83
|
+
|
|
84
|
+
``method``: an ordering of :func:`srdkit.parcoord.order_axes`. With
|
|
85
|
+
``spacing="srd"`` the axes are placed at their positions (SRD values or
|
|
86
|
+
cumulative distances), with ``"uniform"`` equidistantly. Lines are coloured by
|
|
87
|
+
the quantile class of the reference (``color_by="quantile"``) or by the
|
|
88
|
+
reference rank (``"rank"``).
|
|
89
|
+
"""
|
|
90
|
+
from .._utils import as_frame
|
|
91
|
+
from ..core import srd
|
|
92
|
+
from ..parcoord import order_axes, total_crossings
|
|
93
|
+
from ..ranking import rank_matrix
|
|
94
|
+
from ..reference import make_reference
|
|
95
|
+
|
|
96
|
+
df = as_frame(X)
|
|
97
|
+
order, pos = order_axes(df, method, reference)
|
|
98
|
+
y = make_reference(df, reference)
|
|
99
|
+
ext = pd.concat([pd.Series(y, index=df.index, name="reference"), df], axis=1)
|
|
100
|
+
if "reference" not in order and show_reference:
|
|
101
|
+
order = ["reference"] + list(order)
|
|
102
|
+
pos = np.concatenate([[0.0], np.asarray(pos) + (np.min(np.diff(pos)) if len(pos) > 1 else 1.0) - np.min(pos)
|
|
103
|
+
if len(pos) else []])
|
|
104
|
+
R = rank_matrix(ext[order])
|
|
105
|
+
xs = np.asarray(pos, float) if spacing == "srd" else np.arange(len(order), dtype=float)
|
|
106
|
+
if spacing == "srd" and np.ptp(xs) > 0:
|
|
107
|
+
# keep a minimum gap so that close axes stay legible
|
|
108
|
+
o = np.argsort(xs)
|
|
109
|
+
gaps = np.diff(xs[o])
|
|
110
|
+
min_gap = 0.015 * np.ptp(xs)
|
|
111
|
+
xs[o] = xs[o][0] + np.concatenate([[0], np.cumsum(np.maximum(gaps, min_gap))])
|
|
112
|
+
ax = ax_or_new(ax, (max(7.0, 0.5 * len(order) + 3), 4.2))
|
|
113
|
+
qref = R["reference"].to_numpy()
|
|
114
|
+
n = len(qref)
|
|
115
|
+
if color_by == "quantile":
|
|
116
|
+
edges = np.quantile(qref, [0.1, 0.25, 0.5, 0.75])
|
|
117
|
+
cls = np.digitize(qref, edges)
|
|
118
|
+
palette = ["#D55E00", "#E69F00", "#009E73", "#56B4E9", "#285780"]
|
|
119
|
+
labels = ["D1", "Q1", "Q2", "Q3", "Q4"]
|
|
120
|
+
cols = [palette[c] for c in cls]
|
|
121
|
+
else:
|
|
122
|
+
cmap = plt.get_cmap("viridis")
|
|
123
|
+
cols = [cmap(v / n) for v in qref]
|
|
124
|
+
idx = np.argsort(xs)
|
|
125
|
+
for i in range(n):
|
|
126
|
+
ax.plot(xs[idx], R.to_numpy()[i, idx], color=cols[i], lw=lw, alpha=alpha)
|
|
127
|
+
for k, name in enumerate(order):
|
|
128
|
+
ax.axvline(xs[k], color=REFERENCE_COLOR if name == "reference" else INK, lw=1.4 if name == "reference" else 0.8, ls=":")
|
|
129
|
+
ax.text(xs[k], n + 2 + 0.02 * n, str(name), rotation=90, ha="center", va="top", fontsize=7.5,
|
|
130
|
+
color=REFERENCE_COLOR if name == "reference" else INK)
|
|
131
|
+
ax.set_ylim(n + 1, 0)
|
|
132
|
+
ax.set_xticks([])
|
|
133
|
+
ax.set_ylabel("rank")
|
|
134
|
+
if color_by == "quantile":
|
|
135
|
+
from ._style import legend_patches
|
|
136
|
+
|
|
137
|
+
legend_patches(dict(zip(labels, palette)), ax, title="reference class", loc="upper left", bbox=(1.01, 1.0))
|
|
138
|
+
tc = total_crossings(ext, [o for o in np.array(order)[idx]])
|
|
139
|
+
ax.set_title(f"{method} ordering: {tc} crossings", fontsize=9, loc="left")
|
|
140
|
+
despine(ax, ("left",))
|
|
141
|
+
_ = (srd, cat_colors, BRAND)
|
|
142
|
+
return ax
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
__all__ = ["plot_srd_map", "plot_constellation", "plot_dendrogram", "plot_parallel"]
|
srdkit/viz/validation.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Plots of cross-validation, critical differences, ANOVA, influence and power."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
from matplotlib import pyplot as plt
|
|
8
|
+
|
|
9
|
+
from ._style import BRAND, BRAND_HEAT, GRAY, INK, VERM, ax_or_new, cat_colors, despine
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def plot_cv(cv, ax=None, test: str | None = "wilcoxon", whiskers: str = "range", alpha: float = 0.05, percent: bool = True):
|
|
13
|
+
"""Box plots of cross-validated SRD values in the order of their medians.
|
|
14
|
+
|
|
15
|
+
``whiskers="range"`` draws min/max (as rSRD), ``"xx"`` the 5% and 95% points.
|
|
16
|
+
Consecutive pairs are tested (``test``) and marked: ``n.s.``, ``.``, ``*``, ``**``, ``***``.
|
|
17
|
+
"""
|
|
18
|
+
s = cv.summary()
|
|
19
|
+
f = cv.folds[s.index] * (100 if percent else 1)
|
|
20
|
+
ax = ax_or_new(ax, (0.6 * f.shape[1] + 2.5, 3.6))
|
|
21
|
+
pos = np.arange(f.shape[1])
|
|
22
|
+
lo, hi = ("min", "max") if whiskers == "range" else ("XX1", "XX19")
|
|
23
|
+
k = 100 if percent else 1
|
|
24
|
+
for i, c in enumerate(s.index):
|
|
25
|
+
q1, med, q3 = s.loc[c, "Q1"] * k, s.loc[c, "median"] * k, s.loc[c, "Q3"] * k
|
|
26
|
+
ax.add_patch(plt.Rectangle((i - 0.3, q1), 0.6, max(q3 - q1, 1e-9), facecolor=BRAND, alpha=0.18, edgecolor=BRAND))
|
|
27
|
+
ax.plot([i - 0.3, i + 0.3], [med, med], color=BRAND, lw=2)
|
|
28
|
+
ax.plot([i, i], [s.loc[c, lo] * k, q1], color=BRAND, lw=1)
|
|
29
|
+
ax.plot([i, i], [q3, s.loc[c, hi] * k], color=BRAND, lw=1)
|
|
30
|
+
ax.plot(np.full(f.shape[0], i) + np.linspace(-0.12, 0.12, f.shape[0]), f[c], ".", color=INK, ms=2.5, alpha=0.6)
|
|
31
|
+
if cv.full is not None:
|
|
32
|
+
ax.plot([i], [cv.full[c] * k], marker="D", color=VERM, ms=4)
|
|
33
|
+
ax.set_xticks(pos)
|
|
34
|
+
ax.set_xticklabels(s.index, rotation=90, fontsize=8)
|
|
35
|
+
ax.set_ylabel("SRD (%)" if percent else "normalized SRD")
|
|
36
|
+
ax.set_xlim(-0.6, f.shape[1] - 0.4)
|
|
37
|
+
if test is not None and f.shape[1] > 1:
|
|
38
|
+
try:
|
|
39
|
+
t = cv.test(test=test, pairs="consecutive", alpha=alpha)
|
|
40
|
+
top = f.to_numpy().max()
|
|
41
|
+
for i, row in enumerate(t.itertuples()):
|
|
42
|
+
y = top * 1.04
|
|
43
|
+
ax.plot([i + 0.1, i + 0.9], [y, y], color=GRAY, lw=0.8)
|
|
44
|
+
ax.text(i + 0.5, y, row.mark, ha="center", va="bottom", fontsize=7, color=INK)
|
|
45
|
+
ax.set_ylim(top=top * 1.12)
|
|
46
|
+
except ValueError:
|
|
47
|
+
pass
|
|
48
|
+
despine(ax)
|
|
49
|
+
return ax
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def plot_cd(friedman: dict, ax=None):
|
|
53
|
+
"""Critical difference diagram (Demšar, 2006) from :meth:`srdkit.CVResult.friedman`."""
|
|
54
|
+
r = friedman["mean_ranks"].sort_values()
|
|
55
|
+
cd = friedman["cd"]
|
|
56
|
+
k = len(r)
|
|
57
|
+
ax = ax_or_new(ax, (7.0, 0.32 * k + 1.4))
|
|
58
|
+
lo, hi = 1, k
|
|
59
|
+
ax.hlines(0, lo, hi, color=INK, lw=1)
|
|
60
|
+
for t in range(lo, hi + 1):
|
|
61
|
+
ax.vlines(t, -0.06, 0.06, color=INK, lw=1)
|
|
62
|
+
ax.text(t, 0.12, str(t), ha="center", fontsize=8)
|
|
63
|
+
half = (k + 1) // 2
|
|
64
|
+
for i, (name, v) in enumerate(r.items()):
|
|
65
|
+
left = i < half
|
|
66
|
+
y = -0.3 - 0.25 * (i if left else k - 1 - i)
|
|
67
|
+
x_end = lo - 0.3 if left else hi + 0.3
|
|
68
|
+
ax.plot([v, v, x_end], [0, y, y], color=BRAND, lw=1)
|
|
69
|
+
ax.text(x_end + (-0.05 if left else 0.05), y, f"{name} ({v:.2f})", ha="right" if left else "left", va="center", fontsize=8)
|
|
70
|
+
# cliques: maximal groups of consecutive solutions within CD
|
|
71
|
+
vals = r.to_numpy()
|
|
72
|
+
cliques = []
|
|
73
|
+
for i in range(k):
|
|
74
|
+
j = i
|
|
75
|
+
while j + 1 < k and vals[j + 1] - vals[i] <= cd:
|
|
76
|
+
j += 1
|
|
77
|
+
if j > i and not any(a <= i and j <= b for a, b in cliques):
|
|
78
|
+
cliques.append((i, j))
|
|
79
|
+
for c, (i, j) in enumerate(cliques):
|
|
80
|
+
y = -0.18 - 0.07 * c
|
|
81
|
+
ax.hlines(y, vals[i] - 0.03, vals[j] + 0.03, color=VERM, lw=3)
|
|
82
|
+
ax.hlines(0.42, lo, lo + cd, color=INK, lw=1.5)
|
|
83
|
+
ax.text(lo + cd / 2, 0.47, f"CD = {cd:.2f}", ha="center", fontsize=8)
|
|
84
|
+
ax.set_xlim(lo - 2.5, hi + 2.5)
|
|
85
|
+
ax.set_ylim(-0.4 - 0.25 * half, 0.6)
|
|
86
|
+
ax.axis("off")
|
|
87
|
+
return ax
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def plot_anova_means(data: pd.DataFrame, factor: str, by: str | None = None, response: str = "srd", ax=None, percent: bool = True):
|
|
91
|
+
"""Means with 95% confidence intervals of the SRD values by ``factor`` (and lines by ``by``)."""
|
|
92
|
+
ax = ax_or_new(ax, (6.5, 3.4))
|
|
93
|
+
k = 100 if percent else 1
|
|
94
|
+
groups = [None] if by is None else list(pd.unique(data[by]))
|
|
95
|
+
cols = cat_colors(len(groups))
|
|
96
|
+
levels = list(pd.unique(data[factor]))
|
|
97
|
+
x = np.arange(len(levels))
|
|
98
|
+
for gi, g in enumerate(groups):
|
|
99
|
+
sub = data if g is None else data[data[by] == g]
|
|
100
|
+
st = sub.groupby(factor, sort=False)[response].agg(["mean", "std", "count"]).reindex(levels)
|
|
101
|
+
ci = 1.96 * st["std"] / np.sqrt(st["count"])
|
|
102
|
+
off = (gi - (len(groups) - 1) / 2) * 0.08
|
|
103
|
+
ax.errorbar(x + off, k * st["mean"], yerr=k * ci, marker="o", ms=4, capsize=3, color=cols[gi], lw=1.2,
|
|
104
|
+
label=None if g is None else str(g))
|
|
105
|
+
ax.set_xticks(x)
|
|
106
|
+
ax.set_xticklabels(levels, rotation=90, fontsize=8)
|
|
107
|
+
ax.set_ylabel("SRD (%)" if percent else "normalized SRD")
|
|
108
|
+
if by is not None:
|
|
109
|
+
ax.legend(title=by, fontsize=7, title_fontsize=7, frameon=False)
|
|
110
|
+
despine(ax)
|
|
111
|
+
return ax
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def plot_influence(influence: dict, ax=None, top: int = 25, cmap=BRAND_HEAT):
|
|
115
|
+
"""Heatmap of the leave-one-object-out changes of the normalized SRD (largest absolute effects first)."""
|
|
116
|
+
D = influence["delta"]
|
|
117
|
+
score = D.abs().max(axis=1).sort_values(ascending=False)
|
|
118
|
+
D = D.loc[score.index[:top]]
|
|
119
|
+
ax = ax_or_new(ax, (0.5 * D.shape[1] + 2.8, 0.22 * D.shape[0] + 1.5))
|
|
120
|
+
v = np.abs(D.to_numpy()).max() or 1.0
|
|
121
|
+
from ._style import DIVERGING
|
|
122
|
+
|
|
123
|
+
im = ax.imshow(100 * D.to_numpy(), cmap=DIVERGING, vmin=-100 * v, vmax=100 * v, aspect="auto")
|
|
124
|
+
ax.set_xticks(range(D.shape[1]))
|
|
125
|
+
ax.set_xticklabels(D.columns, rotation=90, fontsize=8)
|
|
126
|
+
ax.set_yticks(range(D.shape[0]))
|
|
127
|
+
ax.set_yticklabels([f"{o} ({int(influence['order_changes'][o])})" for o in D.index], fontsize=7)
|
|
128
|
+
ax.set_ylabel("removed object (order changes)")
|
|
129
|
+
plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04, label="change of SRD (%-points)")
|
|
130
|
+
_ = cmap
|
|
131
|
+
return ax
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def plot_power(table: pd.DataFrame, ax=None, target: float = 0.8):
|
|
135
|
+
"""Power curves of the CRRN test (rows = n, columns = correlation with the reference)."""
|
|
136
|
+
ax = ax_or_new(ax, (6.0, 3.4))
|
|
137
|
+
cols = cat_colors(table.shape[1])
|
|
138
|
+
for c, col in zip(table.columns, cols):
|
|
139
|
+
ax.plot(table.index, table[c], marker="o", ms=3.5, color=col, label=f"rho = {c}")
|
|
140
|
+
ax.axhline(target, color=GRAY, ls=":", lw=1)
|
|
141
|
+
ax.set_xlabel("number of objects n")
|
|
142
|
+
ax.set_ylabel("probability of 'better than random'")
|
|
143
|
+
ax.set_ylim(0, 1.02)
|
|
144
|
+
ax.legend(fontsize=7, frameon=False)
|
|
145
|
+
despine(ax)
|
|
146
|
+
return ax
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
__all__ = ["plot_cv", "plot_cd", "plot_anova_means", "plot_influence", "plot_power"]
|
srdkit/weighted.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
r"""Weighted SRD: object weights, position weights and top-*k* emphasis.
|
|
2
|
+
|
|
3
|
+
Classical SRD treats every object and every rank position equally. Many
|
|
4
|
+
applications are top-heavy (the best few alternatives matter most, as in
|
|
5
|
+
draft rankings or virtual screening) or weight the objects by importance.
|
|
6
|
+
Following the generalized footrule of Kumar and Vassilvitskii (2010), a
|
|
7
|
+
displacement of object :math:`i` from position :math:`a` to position :math:`b`
|
|
8
|
+
costs
|
|
9
|
+
|
|
10
|
+
.. math:: w_i\,\lvert P(a)-P(b)\rvert,\qquad P(a)=\sum_{l\le a}\delta_l,
|
|
11
|
+
|
|
12
|
+
where :math:`w_i` are object weights and :math:`\delta_l` position weights
|
|
13
|
+
(mid-ranks are interpolated linearly). With unit weights the measure is SRD.
|
|
14
|
+
|
|
15
|
+
The normalizing constant is the *largest attainable* weighted distance, found
|
|
16
|
+
exactly as a maximum-cost assignment problem (Hungarian algorithm), so the
|
|
17
|
+
normalized weighted SRD lies in :math:`[0,1]` for any weights. The null
|
|
18
|
+
distribution is obtained by permutation (Monte Carlo); weighting adds
|
|
19
|
+
subjectivity and lowers the power of the test, as noted by Sziklai et al. (2026).
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import numpy as np
|
|
25
|
+
import pandas as pd
|
|
26
|
+
from scipy.optimize import linear_sum_assignment
|
|
27
|
+
|
|
28
|
+
from ._utils import as_frame, as_rng
|
|
29
|
+
from .core import SRDResult, srd
|
|
30
|
+
from .distribution import SRDDistribution
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def position_weights(n: int, kind="uniform", k: int | None = None, base: float = 2.0) -> np.ndarray:
|
|
34
|
+
"""Position weights ``delta_1..delta_n`` (position 1 = rank 1).
|
|
35
|
+
|
|
36
|
+
``kind``: ``"uniform"``; ``"linear"`` (``n, n-1, ..., 1``); ``"dcg"``
|
|
37
|
+
(``1/log_base(l+1)``, the discount of discounted cumulative gain);
|
|
38
|
+
``"reciprocal"`` (``1/l``); ``"topk"`` (1 for the first ``k`` positions, 0 after);
|
|
39
|
+
or an array of length ``n``.
|
|
40
|
+
"""
|
|
41
|
+
pos = np.arange(1, n + 1, dtype=float)
|
|
42
|
+
if not isinstance(kind, str):
|
|
43
|
+
w = np.asarray(kind, dtype=float)
|
|
44
|
+
if w.size != n:
|
|
45
|
+
raise ValueError("position weights must have length n")
|
|
46
|
+
return w
|
|
47
|
+
if kind == "uniform":
|
|
48
|
+
return np.ones(n)
|
|
49
|
+
if kind == "linear":
|
|
50
|
+
return n + 1 - pos
|
|
51
|
+
if kind == "dcg":
|
|
52
|
+
return 1.0 / (np.log(pos + 1) / np.log(base))
|
|
53
|
+
if kind == "reciprocal":
|
|
54
|
+
return 1.0 / pos
|
|
55
|
+
if kind == "topk":
|
|
56
|
+
if k is None:
|
|
57
|
+
raise ValueError("kind='topk' needs k")
|
|
58
|
+
return (pos <= k).astype(float)
|
|
59
|
+
raise ValueError("kind must be 'uniform', 'linear', 'dcg', 'reciprocal', 'topk' or an array")
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _cumulative_position(r, delta: np.ndarray) -> np.ndarray:
|
|
63
|
+
"""P(r) with linear interpolation at mid-ranks; P(0) = 0, P(l) = delta_1 + ... + delta_l."""
|
|
64
|
+
cum = np.concatenate([[0.0], np.cumsum(delta)])
|
|
65
|
+
grid = np.arange(0, delta.size + 1, dtype=float)
|
|
66
|
+
# positions are centred: position l occupies (l-1, l]; use the centre of mass of each unit cell
|
|
67
|
+
centre = (cum[:-1] + cum[1:]) / 2
|
|
68
|
+
return np.interp(np.asarray(r, float), grid[1:], centre)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def weighted_footrule(r, q, object_weights=None, position_weights_=None) -> float:
|
|
72
|
+
"""Generalized (weighted) footrule between two rank vectors."""
|
|
73
|
+
r = np.asarray(r, float)
|
|
74
|
+
q = np.asarray(q, float)
|
|
75
|
+
n = r.size
|
|
76
|
+
w = np.ones(n) if object_weights is None else np.asarray(object_weights, float)
|
|
77
|
+
delta = np.ones(n) if position_weights_ is None else np.asarray(position_weights_, float)
|
|
78
|
+
return float(np.sum(w * np.abs(_cumulative_position(r, delta) - _cumulative_position(q, delta))))
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def weighted_max(r, q, object_weights=None, position_weights_=None) -> float:
|
|
82
|
+
"""Largest weighted footrule over all rearrangements of ``r`` (maximum-cost assignment)."""
|
|
83
|
+
r = np.asarray(r, float)
|
|
84
|
+
q = np.asarray(q, float)
|
|
85
|
+
n = r.size
|
|
86
|
+
w = np.ones(n) if object_weights is None else np.asarray(object_weights, float)
|
|
87
|
+
delta = np.ones(n) if position_weights_ is None else np.asarray(position_weights_, float)
|
|
88
|
+
Pr = _cumulative_position(r, delta)
|
|
89
|
+
Pq = _cumulative_position(q, delta)
|
|
90
|
+
cost = w[:, None] * np.abs(Pr[None, :] - Pq[:, None]) # object i (reference side) receives value k
|
|
91
|
+
i, k = linear_sum_assignment(cost, maximize=True)
|
|
92
|
+
return float(cost[i, k].sum())
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def weighted_srd(X, reference="mean", object_weights=None, position="uniform", k: int | None = None,
|
|
96
|
+
top: str = "low", ties: str = "average", n_sim: int = 0, random_state=None, **reference_kwargs) -> SRDResult:
|
|
97
|
+
"""Weighted SRD of every column.
|
|
98
|
+
|
|
99
|
+
Parameters
|
|
100
|
+
----------
|
|
101
|
+
object_weights : array-like, optional
|
|
102
|
+
One weight per object (row).
|
|
103
|
+
position : str or array-like
|
|
104
|
+
Position weights (see :func:`position_weights`); ``"dcg"`` or ``"topk"``
|
|
105
|
+
emphasise the top of the ranking.
|
|
106
|
+
top : {"low", "high"}
|
|
107
|
+
Which end of the rank scale is the "top": rank 1 (``"low"``, e.g. the
|
|
108
|
+
smallest error) or rank ``n`` (``"high"``, e.g. the largest score).
|
|
109
|
+
n_sim : int
|
|
110
|
+
If positive, a permutation null distribution with ``n_sim`` draws is
|
|
111
|
+
attached to every column (``result.meta["null"]``) together with lower-tail
|
|
112
|
+
p-values (``result.meta["p_lower"]``).
|
|
113
|
+
|
|
114
|
+
Returns
|
|
115
|
+
-------
|
|
116
|
+
SRDResult
|
|
117
|
+
``srd`` holds the weighted distances, ``srd_max`` the largest attainable one.
|
|
118
|
+
"""
|
|
119
|
+
base = srd(X, reference=reference, ties=ties, **reference_kwargs)
|
|
120
|
+
R = base.ranks.to_numpy()
|
|
121
|
+
q = base.reference_ranks
|
|
122
|
+
n = base.n
|
|
123
|
+
if top == "high":
|
|
124
|
+
R = n + 1 - R
|
|
125
|
+
q = n + 1 - q
|
|
126
|
+
delta = position_weights(n, position, k=k)
|
|
127
|
+
vals = np.array([weighted_footrule(R[:, j], q, object_weights, delta) for j in range(R.shape[1])])
|
|
128
|
+
smax = max(weighted_max(R[:, j], q, object_weights, delta) for j in range(R.shape[1]))
|
|
129
|
+
res = SRDResult(srd=pd.Series(vals, index=base.columns, name="wSRD"), srd_max=smax, n=n, ranks=base.ranks,
|
|
130
|
+
reference=base.reference, reference_ranks=base.reference_ranks, differences=base.differences,
|
|
131
|
+
data=base.data, reference_method=base.reference_method, ties=ties, distance="weighted footrule",
|
|
132
|
+
meta={"object_weights": object_weights, "position": position, "k": k, "top": top})
|
|
133
|
+
if n_sim:
|
|
134
|
+
rng = as_rng(random_state)
|
|
135
|
+
nulls, pl = {}, {}
|
|
136
|
+
for j, c in enumerate(base.columns):
|
|
137
|
+
d = np.array([weighted_footrule(R[rng.permutation(n), j], q, object_weights, delta) for _ in range(n_sim)])
|
|
138
|
+
v, cnt = np.unique(np.round(d, 9), return_counts=True)
|
|
139
|
+
nulls[c] = SRDDistribution(values=v, probs=cnt / cnt.sum(), n=n, scale=smax, kind="monte-carlo")
|
|
140
|
+
pl[c] = float(np.mean(d <= vals[j] + 1e-9))
|
|
141
|
+
res.meta["null"] = nulls
|
|
142
|
+
res.meta["p_lower"] = pd.Series(pl)
|
|
143
|
+
return res
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def topk_srd(X, k: int, reference="mean", top: str = "low", ties: str = "average", **kwargs) -> SRDResult:
|
|
147
|
+
"""SRD restricted to the top-*k* positions (Fagin et al. location parameter ``k+1``)."""
|
|
148
|
+
from .distances import topk_footrule
|
|
149
|
+
|
|
150
|
+
base = srd(X, reference=reference, ties=ties, **kwargs)
|
|
151
|
+
R = base.ranks.to_numpy()
|
|
152
|
+
q = base.reference_ranks
|
|
153
|
+
asc = top == "low"
|
|
154
|
+
vals = np.array([topk_footrule(R[:, j], q, k, ascending=asc) for j in range(R.shape[1])])
|
|
155
|
+
smax = k * (k + 1) # two disjoint top-k lists
|
|
156
|
+
return SRDResult(srd=pd.Series(vals, index=base.columns, name=f"top{k}SRD"), srd_max=float(smax), n=base.n,
|
|
157
|
+
ranks=base.ranks, reference=base.reference, reference_ranks=q, differences=base.differences,
|
|
158
|
+
data=base.data, reference_method=base.reference_method, ties=ties, distance=f"top-{k} footrule",
|
|
159
|
+
meta={"k": k, "top": top})
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def object_weight_profile(X, reference="mean", ties: str = "average") -> pd.DataFrame:
|
|
163
|
+
"""Share of every object in the SRD of every solution (columns sum to one)."""
|
|
164
|
+
res = srd(as_frame(X), reference=reference, ties=ties)
|
|
165
|
+
C = res.contributions
|
|
166
|
+
tot = C.sum(axis=0).replace(0, np.nan)
|
|
167
|
+
return C / tot
|