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/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Static visualizations of SRD analyses (matplotlib). Every function returns the ``Axes`` (or ``Figure``) and accepts ``ax=``."""
|
|
2
|
+
|
|
3
|
+
from .applications import (
|
|
4
|
+
plot_change_score,
|
|
5
|
+
plot_displacement,
|
|
6
|
+
plot_gaia,
|
|
7
|
+
plot_local_profile,
|
|
8
|
+
plot_pareto_layers,
|
|
9
|
+
plot_ranking_sequence,
|
|
10
|
+
plot_utilities,
|
|
11
|
+
)
|
|
12
|
+
from .basic import plot_contributions, plot_distribution, plot_heatmap, plot_rank_flow, plot_report, plot_srd
|
|
13
|
+
from .framework import (
|
|
14
|
+
plot_consensus,
|
|
15
|
+
plot_covat,
|
|
16
|
+
plot_fair_comparison,
|
|
17
|
+
plot_method_parallel,
|
|
18
|
+
plot_pwr_sequence,
|
|
19
|
+
plot_weights,
|
|
20
|
+
)
|
|
21
|
+
from .maps import plot_constellation, plot_dendrogram, plot_parallel, plot_srd_map
|
|
22
|
+
from .validation import plot_anova_means, plot_cd, plot_cv, plot_influence, plot_power
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"plot_srd", "plot_distribution", "plot_heatmap", "plot_contributions", "plot_rank_flow", "plot_report",
|
|
26
|
+
"plot_cv", "plot_cd", "plot_anova_means", "plot_influence", "plot_power",
|
|
27
|
+
"plot_srd_map", "plot_constellation", "plot_dendrogram", "plot_parallel",
|
|
28
|
+
"plot_local_profile", "plot_ranking_sequence", "plot_change_score", "plot_gaia", "plot_pareto_layers",
|
|
29
|
+
"plot_utilities", "plot_displacement",
|
|
30
|
+
"plot_covat", "plot_consensus", "plot_method_parallel", "plot_fair_comparison", "plot_pwr_sequence", "plot_weights",
|
|
31
|
+
]
|
srdkit/viz/_style.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""Shared palette and drawing helpers of the static visualizations.
|
|
2
|
+
|
|
3
|
+
The palette is the house style of the ComplexSystemsIntelligence toolboxes:
|
|
4
|
+
Pannon blue for structure, the colour-blind-safe Okabe–Ito colours for
|
|
5
|
+
categories, gray for context. SRD verdicts have fixed colours: similar to the
|
|
6
|
+
reference (Pannon blue), random (gray), reversed (vermilion); the reference is
|
|
7
|
+
drawn in bluish green.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import matplotlib.colors as mcolors
|
|
13
|
+
import numpy as np
|
|
14
|
+
from matplotlib import pyplot as plt
|
|
15
|
+
|
|
16
|
+
OKABE_ITO = ["#0072B2", "#D55E00", "#009E73", "#CC79A7", "#E69F00", "#56B4E9", "#F0E442"]
|
|
17
|
+
EXTRA = ["#1B9E9E", "#8C6BB1", "#B2742F", "#5A8F29", "#C2185B", "#3B6FB6", "#E07B91", "#6E7F80"]
|
|
18
|
+
CATEGORICAL = OKABE_ITO + EXTRA
|
|
19
|
+
|
|
20
|
+
BRAND = "#285780"
|
|
21
|
+
NAVY = "#14304A"
|
|
22
|
+
INK = "#1F2A36"
|
|
23
|
+
GRAY = "#8A96A3"
|
|
24
|
+
LIGHT = "#D9DEE4"
|
|
25
|
+
PAPER = "#F4F6F8"
|
|
26
|
+
VERM = "#D55E00"
|
|
27
|
+
GREEN = "#009E73"
|
|
28
|
+
AMBER = "#E69F00"
|
|
29
|
+
WINE = "#7A0019"
|
|
30
|
+
|
|
31
|
+
#: colours of the CRRN verdicts and of the reference
|
|
32
|
+
VERDICT_COLORS = {"similar": BRAND, "random": GRAY, "reversed": VERM}
|
|
33
|
+
REFERENCE_COLOR = GREEN
|
|
34
|
+
|
|
35
|
+
BRAND_SEQ = mcolors.LinearSegmentedColormap.from_list("srdkit_seq", ["#CFE3F3", "#7FB2DA", BRAND, NAVY])
|
|
36
|
+
BRAND_HEAT = mcolors.LinearSegmentedColormap.from_list("srdkit_heat", ["#FFFFFF", "#CFE3F3", "#7FB2DA", BRAND, NAVY])
|
|
37
|
+
DIVERGING = mcolors.LinearSegmentedColormap.from_list("srdkit_div", ["#D55E00", "#F3E6DC", "#FFFFFF", "#DCE7F2", "#0072B2"])
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def ax_or_new(ax=None, figsize=(7.0, 3.2)):
|
|
41
|
+
if ax is None:
|
|
42
|
+
_, ax = plt.subplots(figsize=figsize)
|
|
43
|
+
return ax
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def despine(ax, keep=("left", "bottom")):
|
|
47
|
+
for s in ("top", "right", "left", "bottom"):
|
|
48
|
+
ax.spines[s].set_visible(s in keep)
|
|
49
|
+
return ax
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def clean(ax, equal: bool = False):
|
|
53
|
+
ax.set_xticks([])
|
|
54
|
+
ax.set_yticks([])
|
|
55
|
+
for s in ax.spines.values():
|
|
56
|
+
s.set_visible(False)
|
|
57
|
+
if equal:
|
|
58
|
+
ax.set_aspect("equal")
|
|
59
|
+
return ax
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def scale(values, lo: float, hi: float, vmin=None, vmax=None) -> np.ndarray:
|
|
63
|
+
"""Linear rescaling of ``values`` to ``[lo, hi]`` (constant input → midpoint)."""
|
|
64
|
+
v = np.asarray(values, dtype=float)
|
|
65
|
+
a = np.nanmin(v) if vmin is None else vmin
|
|
66
|
+
b = np.nanmax(v) if vmax is None else vmax
|
|
67
|
+
if not np.isfinite(a) or not np.isfinite(b) or b - a < 1e-12:
|
|
68
|
+
return np.full(v.shape, (lo + hi) / 2)
|
|
69
|
+
return lo + (np.clip(v, a, b) - a) / (b - a) * (hi - lo)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def cat_colors(n: int) -> list[str]:
|
|
73
|
+
"""``n`` categorical colours (Okabe–Ito first)."""
|
|
74
|
+
return [CATEGORICAL[k % len(CATEGORICAL)] for k in range(n)]
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def legend_patches(mapping: dict, ax, title=None, loc="upper left", bbox=(1.01, 1.0), ncol=1, fontsize=8):
|
|
78
|
+
from matplotlib.patches import Patch
|
|
79
|
+
|
|
80
|
+
handles = [Patch(facecolor=c, edgecolor="none", label=str(k)) for k, c in mapping.items()]
|
|
81
|
+
return ax.legend(handles=handles, title=title, loc=loc, bbox_to_anchor=bbox, frameon=False, fontsize=fontsize,
|
|
82
|
+
title_fontsize=fontsize, ncol=ncol)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def text_color(bg) -> str:
|
|
86
|
+
r, g, b = mcolors.to_rgb(bg)
|
|
87
|
+
return INK if (0.299 * r + 0.587 * g + 0.114 * b) > 0.6 else "white"
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Plots of segmentation, local profiles, Promethee-GAIA, Pareto fronts and utilities."""
|
|
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, VERM, ax_or_new, cat_colors, despine
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def plot_local_profile(profile: pd.DataFrame, ax=None, xxlines=None):
|
|
13
|
+
"""Sliding-window SRD of the solutions along the reference (output of :func:`srdkit.local_srd_profile`)."""
|
|
14
|
+
ax = ax_or_new(ax, (6.5, 3.4))
|
|
15
|
+
cols = cat_colors(profile.shape[1])
|
|
16
|
+
for c, col in zip(profile.columns, cols):
|
|
17
|
+
ax.plot(profile.index, 100 * profile[c], color=col, lw=1.4, label=str(c))
|
|
18
|
+
ax.axhline(100 * 2 / 3, color=GRAY, ls="--", lw=0.8)
|
|
19
|
+
ax.text(profile.index.min(), 100 * 2 / 3, " random (2/3)", va="bottom", fontsize=7, color=GRAY)
|
|
20
|
+
if xxlines is not None:
|
|
21
|
+
for v in xxlines:
|
|
22
|
+
ax.axhline(100 * v, color=GRAY, ls=":", lw=0.8)
|
|
23
|
+
ax.set_xlabel("reference value (window mean)")
|
|
24
|
+
ax.set_ylabel("local SRD (%)")
|
|
25
|
+
ax.legend(fontsize=7, frameon=False, ncol=2)
|
|
26
|
+
despine(ax)
|
|
27
|
+
return ax
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def plot_ranking_sequence(seg, ax=None, objects=None, cmap="viridis"):
|
|
31
|
+
"""Ranks of the objects over time with the segment boundaries of :func:`srdkit.segment_rankings`."""
|
|
32
|
+
R = seg.meta["ranks"]
|
|
33
|
+
T, n = R.shape
|
|
34
|
+
ax = ax_or_new(ax, (7.5, 3.8))
|
|
35
|
+
cm = plt.get_cmap(cmap)
|
|
36
|
+
show = range(n) if objects is None else objects
|
|
37
|
+
for i in show:
|
|
38
|
+
ax.plot(np.arange(T), R[:, i], color=cm(i / max(n - 1, 1)), lw=1.0, alpha=0.85)
|
|
39
|
+
for b in seg.change_points:
|
|
40
|
+
ax.axvline(b - 0.5, color=VERM, lw=1.5)
|
|
41
|
+
ax.set_xlabel("time")
|
|
42
|
+
ax.set_ylabel("rank")
|
|
43
|
+
ax.invert_yaxis()
|
|
44
|
+
ax.set_title(f"{seg.n_segments} regimes; within-regime SRD: " + ", ".join(f"{100 * v:.0f}%" for v in seg.within_srd),
|
|
45
|
+
fontsize=9, loc="left")
|
|
46
|
+
despine(ax)
|
|
47
|
+
return ax
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def plot_change_score(score: pd.Series, ax=None, change_points=()):
|
|
51
|
+
"""Profile of :func:`srdkit.change_score`."""
|
|
52
|
+
ax = ax_or_new(ax, (7.5, 2.4))
|
|
53
|
+
ax.plot(score.index, 100 * score, color=BRAND, lw=1.4)
|
|
54
|
+
for b in change_points:
|
|
55
|
+
ax.axvline(b, color=VERM, lw=1.0, ls="--")
|
|
56
|
+
ax.set_xlabel("time")
|
|
57
|
+
ax.set_ylabel("change score (%)")
|
|
58
|
+
despine(ax)
|
|
59
|
+
return ax
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def plot_gaia(gaia, ax=None, labels_alternatives: bool = False, phi=None, top: int | None = None):
|
|
63
|
+
"""GAIA plane: alternatives as points (coloured by the net flow), criteria as axes, the decision stick in red."""
|
|
64
|
+
ax = ax_or_new(ax, (5.6, 5.0))
|
|
65
|
+
S = gaia.scores.iloc[:, :2].to_numpy()
|
|
66
|
+
sc = ax.scatter(S[:, 0], S[:, 1], c=None if phi is None else np.asarray(phi), cmap="viridis", s=14,
|
|
67
|
+
color=GRAY if phi is None else None, alpha=0.8)
|
|
68
|
+
if phi is not None:
|
|
69
|
+
plt.colorbar(sc, ax=ax, fraction=0.046, pad=0.04, label="net flow")
|
|
70
|
+
if labels_alternatives:
|
|
71
|
+
for name, (x, y) in zip(gaia.scores.index, S):
|
|
72
|
+
ax.annotate(str(name), (x, y), fontsize=6, color=GRAY)
|
|
73
|
+
L = gaia.loadings.iloc[:, :2]
|
|
74
|
+
if top is not None:
|
|
75
|
+
L = L.loc[(L ** 2).sum(axis=1).sort_values(ascending=False).index[:top]]
|
|
76
|
+
sc_len = np.abs(S).max() / max(np.abs(L.to_numpy()).max(), 1e-12) * 0.9
|
|
77
|
+
for name, (x, y) in L.iterrows():
|
|
78
|
+
if x == 0 and y == 0:
|
|
79
|
+
continue
|
|
80
|
+
ax.annotate("", xy=(x * sc_len, y * sc_len), xytext=(0, 0), arrowprops={"arrowstyle": "->", "color": BRAND, "lw": 1.0})
|
|
81
|
+
ax.text(x * sc_len * 1.06, y * sc_len * 1.06, str(name), fontsize=7, color=BRAND)
|
|
82
|
+
st = np.asarray(gaia.decision_stick[:2]) * sc_len
|
|
83
|
+
ax.annotate("", xy=(st[0], st[1]), xytext=(0, 0), arrowprops={"arrowstyle": "-|>", "color": VERM, "lw": 2.0})
|
|
84
|
+
ex = gaia.explained
|
|
85
|
+
ax.set_xlabel(f"PC1 ({100 * ex[0]:.0f}%)")
|
|
86
|
+
ax.set_ylabel(f"PC2 ({100 * ex[1]:.0f}%)")
|
|
87
|
+
ax.set_aspect("equal", adjustable="datalim")
|
|
88
|
+
ax.set_title("sparse GAIA plane" if gaia.sparse else "GAIA plane", fontsize=9, loc="left")
|
|
89
|
+
despine(ax)
|
|
90
|
+
return ax
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def plot_pareto_layers(scores: pd.DataFrame, layers, ax=None, max_layers: int = 6, annotate=None):
|
|
94
|
+
"""Two objectives (first two columns) coloured by the non-dominated sorting layer."""
|
|
95
|
+
ax = ax_or_new(ax, (5.4, 4.4))
|
|
96
|
+
S = scores.iloc[:, :2].to_numpy()
|
|
97
|
+
L = np.asarray(layers)
|
|
98
|
+
cols = cat_colors(max_layers)
|
|
99
|
+
for k in range(min(L.max() + 1, max_layers)):
|
|
100
|
+
sel = L == k
|
|
101
|
+
pts = S[sel]
|
|
102
|
+
o = np.argsort(pts[:, 0])
|
|
103
|
+
ax.plot(pts[o, 0], pts[o, 1], "-o", ms=4, lw=0.8, color=cols[k], label=f"layer {k + 1}")
|
|
104
|
+
rest = L >= max_layers
|
|
105
|
+
if rest.any():
|
|
106
|
+
ax.plot(S[rest, 0], S[rest, 1], ".", color=GRAY, ms=3, label=f"layer > {max_layers}")
|
|
107
|
+
if annotate is not None:
|
|
108
|
+
for name in annotate:
|
|
109
|
+
i = list(scores.index).index(name)
|
|
110
|
+
ax.annotate(str(name), S[i], xytext=(4, 3), textcoords="offset points", fontsize=7, color=INK)
|
|
111
|
+
ax.set_xlabel(scores.columns[0])
|
|
112
|
+
ax.set_ylabel(scores.columns[1])
|
|
113
|
+
ax.legend(fontsize=7, frameon=False)
|
|
114
|
+
despine(ax)
|
|
115
|
+
return ax
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def plot_utilities(x, utilities: dict, ax=None, xlabel: str = "value"):
|
|
119
|
+
"""Utility (transformation) functions evaluated on the values ``x``."""
|
|
120
|
+
ax = ax_or_new(ax, (6.0, 3.4))
|
|
121
|
+
xs = np.sort(np.asarray(x, float))
|
|
122
|
+
cols = cat_colors(len(utilities))
|
|
123
|
+
for (name, f), col in zip(utilities.items(), cols):
|
|
124
|
+
u = np.asarray(f(xs), float)
|
|
125
|
+
if u.min() < 0 or u.max() > 1:
|
|
126
|
+
u = (u - u.min()) / (np.ptp(u) or 1.0)
|
|
127
|
+
ax.plot(xs, u, color=col, lw=1.5, label=name)
|
|
128
|
+
ax.set_xlabel(xlabel)
|
|
129
|
+
ax.set_ylabel("utility (scaled to [0, 1])")
|
|
130
|
+
ax.legend(fontsize=7, frameon=False)
|
|
131
|
+
despine(ax)
|
|
132
|
+
return ax
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def plot_displacement(result, column: str, ax=None, segments: pd.DataFrame | None = None):
|
|
136
|
+
"""Contributions ``|r - q|`` of one solution along the reference, with optional segment means."""
|
|
137
|
+
q = result.reference_ranks if result.reference_ranks.ndim == 1 else result.reference_ranks[:, 0]
|
|
138
|
+
y = result.reference if result.reference.ndim == 1 else result.reference[:, 0]
|
|
139
|
+
o = np.argsort(y, kind="stable")
|
|
140
|
+
d = result.contributions[column].to_numpy()[o]
|
|
141
|
+
ax = ax_or_new(ax, (6.5, 3.0))
|
|
142
|
+
ax.bar(np.arange(d.size), d, color=BRAND, alpha=0.6, width=0.85)
|
|
143
|
+
if segments is not None:
|
|
144
|
+
start = 0
|
|
145
|
+
for _, row in segments.iterrows():
|
|
146
|
+
ax.plot([start - 0.4, start + row.n - 0.6], [row.mean_displacement] * 2, color=VERM, lw=2)
|
|
147
|
+
start += int(row.n)
|
|
148
|
+
ax.set_xlabel("objects in reference order")
|
|
149
|
+
ax.set_ylabel(f"|rank difference| of {column}")
|
|
150
|
+
despine(ax)
|
|
151
|
+
_ = (q, REFERENCE_COLOR)
|
|
152
|
+
return ax
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
__all__ = ["plot_local_profile", "plot_ranking_sequence", "plot_change_score", "plot_gaia", "plot_pareto_layers",
|
|
156
|
+
"plot_utilities", "plot_displacement"]
|
srdkit/viz/basic.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""The classical SRD plot, null distributions, heatmaps, contributions and rank flows."""
|
|
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, DIVERGING, GRAY, INK, REFERENCE_COLOR, VERDICT_COLORS, VERM, ax_or_new, despine
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def plot_srd(result, crrn=None, ax=None, show: str = "cumulative", label_rotation: float = 90, colors=None,
|
|
13
|
+
annotate: bool = True, title=None):
|
|
14
|
+
"""The classical SRD plot (Héberger, 2010).
|
|
15
|
+
|
|
16
|
+
Every solution is a vertical line at its normalized SRD (in %) whose height
|
|
17
|
+
equals the same value (left axis), labelled by its name. The right axis shows
|
|
18
|
+
the null distribution of random rankings (``show="cumulative"``: cumulative
|
|
19
|
+
relative frequency in %, ``"density"``: relative frequencies, ``None``: nothing)
|
|
20
|
+
with the XX1 (5%), Med and XX19 (95%) points as dotted lines. With a CRRN
|
|
21
|
+
result the lines are coloured by the verdict (similar, random, reversed).
|
|
22
|
+
"""
|
|
23
|
+
from ..validation import crrn as _crrn
|
|
24
|
+
|
|
25
|
+
ax = ax_or_new(ax, (7.2, 4.0))
|
|
26
|
+
if crrn is None and show is not None:
|
|
27
|
+
crrn = _crrn(result)
|
|
28
|
+
vals = 100 * result.normalized
|
|
29
|
+
order = vals.sort_values(kind="stable")
|
|
30
|
+
xs_ = order.to_numpy(dtype=float)
|
|
31
|
+
# rotated labels need about 2.2 %-units of horizontal room at the default size;
|
|
32
|
+
# when neighbours are closer, the labels move to a row above the plot with leader lines
|
|
33
|
+
fig_w = ax.figure.get_size_inches()[0] * ax.get_position().width
|
|
34
|
+
min_gap = 102 * (8.5 / 72) / max(fig_w, 1e-3)
|
|
35
|
+
dodge = annotate and xs_.size > 1 and np.min(np.diff(xs_)) < min_gap
|
|
36
|
+
if dodge:
|
|
37
|
+
pos = xs_.copy()
|
|
38
|
+
for k in range(1, pos.size):
|
|
39
|
+
pos[k] = max(pos[k], pos[k - 1] + min_gap)
|
|
40
|
+
shift = (pos - xs_).mean()
|
|
41
|
+
pos = np.clip(pos - shift, 0, None)
|
|
42
|
+
for k in range(1, pos.size):
|
|
43
|
+
pos[k] = max(pos[k], pos[k - 1] + min_gap)
|
|
44
|
+
longest = max((len(str(c)) for c in order.index), default=1)
|
|
45
|
+
top = 104 + 2.6 * longest if dodge else 115
|
|
46
|
+
for k, (c, v) in enumerate(order.items()):
|
|
47
|
+
col = colors.get(c, BRAND) if isinstance(colors, dict) else (
|
|
48
|
+
VERDICT_COLORS[crrn.table.loc[c, "verdict"]] if crrn is not None else BRAND)
|
|
49
|
+
ax.plot([v, v], [0, v], color=col, lw=2.0, solid_capstyle="butt", clip_on=False, zorder=3)
|
|
50
|
+
ax.plot([v], [v], marker="o", ms=3.5, color=col, clip_on=False, zorder=3)
|
|
51
|
+
if annotate and not dodge:
|
|
52
|
+
ax.text(v, v + 1.5, str(c), rotation=label_rotation, ha="center", va="bottom", fontsize=7.5, color=INK)
|
|
53
|
+
elif annotate:
|
|
54
|
+
ax.plot([v, v, pos[k]], [v, 100.5, 102.5], color=col, lw=0.5, alpha=0.8, zorder=2, clip_on=False)
|
|
55
|
+
ax.text(pos[k], 103.0, str(c), rotation=90, ha="center", va="bottom", fontsize=7.5, color=INK)
|
|
56
|
+
ax.set_xlim(-1, max(101, (pos.max() + 1) if dodge else 101))
|
|
57
|
+
ax.set_ylim(0, top if annotate else 100)
|
|
58
|
+
name = str(result.distance) if result.meta.get("value_based") else "SRD"
|
|
59
|
+
ax.set_xlabel(f"{name} (%)")
|
|
60
|
+
ax.set_ylabel(f"{name} (%)")
|
|
61
|
+
despine(ax, ("left", "bottom", "right"))
|
|
62
|
+
if crrn is not None and show is not None:
|
|
63
|
+
d = crrn.distribution
|
|
64
|
+
ax2 = ax.twinx()
|
|
65
|
+
x = 100 * d.normalized_values
|
|
66
|
+
if show == "cumulative":
|
|
67
|
+
ax2.plot(x, 100 * np.cumsum(d.probs), color=INK, lw=1.0)
|
|
68
|
+
ax2.set_ylabel("cumulative relative frequency (%)")
|
|
69
|
+
ax2.set_ylim(0, top if annotate else 100)
|
|
70
|
+
else:
|
|
71
|
+
if hasattr(d, "mu") and d.kind == "normal":
|
|
72
|
+
xs = np.linspace(0, 100, 400)
|
|
73
|
+
from scipy import stats
|
|
74
|
+
|
|
75
|
+
pdf = stats.norm.pdf(xs / 100 * d.scale, d.mu, d.sigma) * d.scale / 100
|
|
76
|
+
ax2.plot(xs, pdf, color=INK, lw=1.0)
|
|
77
|
+
else:
|
|
78
|
+
ax2.plot(x, d.probs, color=INK, lw=1.0, marker="^", ms=2.5, markevery=2)
|
|
79
|
+
ax2.set_ylabel("relative frequency")
|
|
80
|
+
ax2.set_ylim(bottom=0)
|
|
81
|
+
p = d.percentiles(normalized=True)
|
|
82
|
+
for key in ("XX1", "Med", "XX19"):
|
|
83
|
+
ax.plot([100 * p[key]] * 2, [0, 100], color=GRAY, ls=":", lw=1.0)
|
|
84
|
+
ax.text(100 * p[key], 100.5, key, ha="center", va="bottom", fontsize=6.5, color=GRAY,
|
|
85
|
+
bbox={"facecolor": "white", "edgecolor": "none", "pad": 0.3})
|
|
86
|
+
ax2.spines["top"].set_visible(False)
|
|
87
|
+
if title:
|
|
88
|
+
ax.set_title(title, fontsize=10, loc="left")
|
|
89
|
+
return ax
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def plot_distribution(dist, values=None, ax=None, cumulative: bool = False, normalized: bool = True, color=BRAND, label=None):
|
|
93
|
+
"""Plot a null distribution (pmf or cdf) and optionally mark observed values."""
|
|
94
|
+
ax = ax_or_new(ax, (6.0, 3.0))
|
|
95
|
+
x = dist.normalized_values if normalized else dist.values
|
|
96
|
+
y = np.cumsum(dist.probs) if cumulative else dist.probs
|
|
97
|
+
if cumulative:
|
|
98
|
+
ax.step(x, y, where="post", color=color, lw=1.2, label=label)
|
|
99
|
+
else:
|
|
100
|
+
ax.vlines(x, 0, y, color=color, lw=1.0, label=label)
|
|
101
|
+
if values is not None:
|
|
102
|
+
for k, v in dict(values).items() if isinstance(values, (dict, pd.Series)) else enumerate(np.atleast_1d(values)):
|
|
103
|
+
ax.axvline(v, color=VERM, lw=1.0, ls="--")
|
|
104
|
+
ax.text(v, ax.get_ylim()[1] * 0.95, str(k), rotation=90, va="top", ha="right", fontsize=7, color=VERM)
|
|
105
|
+
ax.set_xlabel("normalized SRD" if normalized else "SRD")
|
|
106
|
+
ax.set_ylabel("cumulative probability" if cumulative else "probability")
|
|
107
|
+
despine(ax)
|
|
108
|
+
return ax
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def plot_heatmap(D, ax=None, annotate: bool = True, cmap=BRAND_HEAT, cluster: bool = False, fmt: str = ".2f", vmax=None):
|
|
112
|
+
"""Heatmap of a pairwise SRD (or other dissimilarity) matrix; ``cluster`` reorders by optimal leaf ordering."""
|
|
113
|
+
D = D if isinstance(D, pd.DataFrame) else pd.DataFrame(D)
|
|
114
|
+
if cluster and D.shape[0] > 2:
|
|
115
|
+
from scipy.cluster import hierarchy
|
|
116
|
+
from scipy.spatial.distance import squareform
|
|
117
|
+
|
|
118
|
+
Z = hierarchy.linkage(squareform(D.to_numpy(), checks=False), "average", optimal_ordering=True)
|
|
119
|
+
idx = hierarchy.leaves_list(Z)
|
|
120
|
+
D = D.iloc[idx, idx]
|
|
121
|
+
k = D.shape[0]
|
|
122
|
+
ax = ax_or_new(ax, (0.42 * k + 2.2, 0.42 * k + 1.2))
|
|
123
|
+
im = ax.imshow(D.to_numpy(), cmap=cmap, vmin=0, vmax=vmax)
|
|
124
|
+
ax.set_xticks(range(k))
|
|
125
|
+
ax.set_yticks(range(k))
|
|
126
|
+
ax.set_xticklabels(D.columns, rotation=90, fontsize=8)
|
|
127
|
+
ax.set_yticklabels(D.index, fontsize=8)
|
|
128
|
+
if annotate and k <= 20:
|
|
129
|
+
vmx = np.nanmax(D.to_numpy()) if vmax is None else vmax
|
|
130
|
+
for i in range(k):
|
|
131
|
+
for j in range(k):
|
|
132
|
+
v = D.iat[i, j]
|
|
133
|
+
ax.text(j, i, format(v, fmt), ha="center", va="center", fontsize=6.5,
|
|
134
|
+
color="white" if v > 0.55 * vmx else INK)
|
|
135
|
+
plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
|
|
136
|
+
return ax
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def plot_contributions(result, ax=None, sort_objects: bool = True, cmap=BRAND_HEAT, max_objects: int = 60):
|
|
140
|
+
"""Heatmap of the absolute rank differences (objects x solutions, solutions in SRD order)."""
|
|
141
|
+
C = result.contributions[result.order]
|
|
142
|
+
if sort_objects:
|
|
143
|
+
q = result.reference_ranks if result.reference_ranks.ndim == 1 else result.reference_ranks[:, 0]
|
|
144
|
+
C = C.iloc[np.argsort(q, kind="stable")]
|
|
145
|
+
C = C.iloc[:max_objects]
|
|
146
|
+
ax = ax_or_new(ax, (0.45 * C.shape[1] + 2.5, 0.18 * C.shape[0] + 1.5))
|
|
147
|
+
im = ax.imshow(C.to_numpy(), cmap=cmap, aspect="auto")
|
|
148
|
+
ax.set_xticks(range(C.shape[1]))
|
|
149
|
+
ax.set_xticklabels(C.columns, rotation=90, fontsize=8)
|
|
150
|
+
ax.set_yticks(range(C.shape[0]))
|
|
151
|
+
ax.set_yticklabels(C.index, fontsize=6.5)
|
|
152
|
+
ax.set_xlabel("solution (in SRD order)")
|
|
153
|
+
ax.set_ylabel("object (in reference order)")
|
|
154
|
+
plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04, label="|rank difference|")
|
|
155
|
+
return ax
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def plot_rank_flow(result, columns=None, ax=None, highlight=None, cmap=DIVERGING):
|
|
159
|
+
"""Bump chart: the ranks of the objects in the reference and in the selected solutions."""
|
|
160
|
+
cols = result.order[:4] if columns is None else list(columns)
|
|
161
|
+
q = result.reference_ranks if result.reference_ranks.ndim == 1 else result.reference_ranks[:, 0]
|
|
162
|
+
R = result.ranks[cols].to_numpy()
|
|
163
|
+
n = result.n
|
|
164
|
+
ax = ax_or_new(ax, (1.6 * (len(cols) + 1) + 1.5, 4.2))
|
|
165
|
+
xs = np.arange(len(cols) + 1)
|
|
166
|
+
norm = plt.Normalize(1, n)
|
|
167
|
+
for i, obj in enumerate(result.ranks.index):
|
|
168
|
+
ys = np.concatenate([[q[i]], R[i]])
|
|
169
|
+
lw, alpha = (2.2, 1.0) if highlight is not None and obj in highlight else (1.0, 0.8)
|
|
170
|
+
ax.plot(xs, ys, color=cmap(norm(q[i])), lw=lw, alpha=alpha, marker="o", ms=3)
|
|
171
|
+
ax.set_xticks(xs)
|
|
172
|
+
ax.set_xticklabels(["reference"] + cols, fontsize=8)
|
|
173
|
+
ax.set_ylabel("rank")
|
|
174
|
+
ax.invert_yaxis()
|
|
175
|
+
ax.get_xticklabels()[0].set_color(REFERENCE_COLOR)
|
|
176
|
+
despine(ax, ("left",))
|
|
177
|
+
return ax
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def plot_report(report, figsize=(11.0, 7.4)):
|
|
181
|
+
"""Four-panel overview of an :class:`srdkit.SRDReport`: SRD plot, CV boxes, heatmap, constellation."""
|
|
182
|
+
from ..core import pairwise_srd
|
|
183
|
+
from ..representation import constellation
|
|
184
|
+
from .maps import plot_constellation
|
|
185
|
+
from .validation import plot_cv
|
|
186
|
+
|
|
187
|
+
fig, axs = plt.subplots(2, 2, figsize=figsize)
|
|
188
|
+
plot_srd(report.result, report.crrn, ax=axs[0, 0])
|
|
189
|
+
if report.cv is not None:
|
|
190
|
+
plot_cv(report.cv, ax=axs[0, 1])
|
|
191
|
+
else:
|
|
192
|
+
axs[0, 1].axis("off")
|
|
193
|
+
ref = report.result.meta.get("reference_spec", "mean")
|
|
194
|
+
refv = ref if isinstance(ref, str) or callable(ref) else report.result.reference
|
|
195
|
+
plot_heatmap(pairwise_srd(report.result.data, reference=refv), ax=axs[1, 0], annotate=report.result.srd.size <= 10)
|
|
196
|
+
plot_constellation(constellation(report.result.data, reference=refv), ax=axs[1, 1])
|
|
197
|
+
fig.tight_layout()
|
|
198
|
+
return fig
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
__all__ = ["plot_srd", "plot_distribution", "plot_heatmap", "plot_contributions", "plot_rank_flow", "plot_report"]
|
srdkit/viz/framework.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
"""Plots of the consensus framework: COVAT heatmap, mean ranks with spread, method parallel coordinates, PWR sequences."""
|
|
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_covat(cov, ax=None, annotate: bool = True, fmt: str = ".0f", cmap=BRAND_HEAT):
|
|
13
|
+
"""Heatmap of a :class:`srdkit.framework.CovatResult`, rows/columns ordered by increasing sums.
|
|
14
|
+
|
|
15
|
+
The column sums are given in brackets after the column names; the leftmost
|
|
16
|
+
column is the alternative most similar to all others.
|
|
17
|
+
"""
|
|
18
|
+
M = cov.matrix
|
|
19
|
+
k = M.shape[0]
|
|
20
|
+
ax = ax_or_new(ax, (0.45 * k + 2.4, 0.45 * k + 1.6))
|
|
21
|
+
im = ax.imshow(M.to_numpy(), cmap=cmap, vmin=0)
|
|
22
|
+
ax.set_xticks(range(k))
|
|
23
|
+
ax.set_yticks(range(k))
|
|
24
|
+
ax.set_xticklabels([f"{c} ({cov.sums[c]:.0f})" for c in M.columns], rotation=90, fontsize=8)
|
|
25
|
+
ax.set_yticklabels(M.index, fontsize=8)
|
|
26
|
+
if annotate and k <= 22:
|
|
27
|
+
vmx = np.nanmax(M.to_numpy())
|
|
28
|
+
for i in range(k):
|
|
29
|
+
for j in range(k):
|
|
30
|
+
v = M.iat[i, j]
|
|
31
|
+
ax.text(j, i, format(v, fmt), ha="center", va="center", fontsize=6.5, color="white" if v > 0.55 * vmx else INK)
|
|
32
|
+
ax.set_xlabel("benchmark (each alternative once; column sum in brackets)", fontsize=8)
|
|
33
|
+
plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04, label=f"{cov.measure.upper()} [%]")
|
|
34
|
+
return ax
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def plot_consensus(fc, ax=None, show_methods: bool = True):
|
|
38
|
+
"""Mean ranks of the alternatives with their spread across the methods.
|
|
39
|
+
|
|
40
|
+
Boxes span the inter-quartile range of the method ranks, whiskers the range,
|
|
41
|
+
the dot is the mean rank; significant neighbouring differences (pairwise
|
|
42
|
+
table of the result) are marked by asterisks between the boxes.
|
|
43
|
+
"""
|
|
44
|
+
R = fc.ranks.loc[fc.order]
|
|
45
|
+
k, m = R.shape
|
|
46
|
+
ax = ax_or_new(ax, (max(5.5, 0.55 * k + 1.5), 3.6))
|
|
47
|
+
bp = ax.boxplot(R.to_numpy().T, positions=range(k), widths=0.55, whis=(0, 100), patch_artist=True,
|
|
48
|
+
medianprops={"color": INK, "lw": 1.0})
|
|
49
|
+
for b in bp["boxes"]:
|
|
50
|
+
b.set_facecolor("#DCE7F2")
|
|
51
|
+
b.set_edgecolor(BRAND)
|
|
52
|
+
if show_methods:
|
|
53
|
+
cols = cat_colors(m)
|
|
54
|
+
for j, c in enumerate(R.columns):
|
|
55
|
+
ax.scatter(np.arange(k) + (j - (m - 1) / 2) * 0.05, R[c], s=9, color=cols[j], zorder=3, label=c)
|
|
56
|
+
ax.legend(frameon=False, fontsize=7, ncol=1, loc="upper left", bbox_to_anchor=(1.01, 1.0), title="method",
|
|
57
|
+
title_fontsize=7)
|
|
58
|
+
ax.plot(range(k), R.mean(axis=1), "D", color=VERM, ms=5, zorder=4)
|
|
59
|
+
pw = fc.pairwise
|
|
60
|
+
if len(pw) and fc.meta.get("pairs") == "neighbors":
|
|
61
|
+
col = "p_adj" if "p_adj" in pw else "p"
|
|
62
|
+
for i, row in pw.reset_index(drop=True).iterrows():
|
|
63
|
+
p = row[col]
|
|
64
|
+
star = "***" if p < 0.001 else "**" if p < 0.01 else "*" if p < 0.05 else ""
|
|
65
|
+
if star:
|
|
66
|
+
ax.text(i + 0.5, 0.6, star, ha="center", va="bottom", fontsize=9, color=VERM)
|
|
67
|
+
ax.set_xticks(range(k))
|
|
68
|
+
ax.set_xticklabels(R.index, rotation=90, fontsize=8)
|
|
69
|
+
ax.set_ylim(k + 0.6, 0.4)
|
|
70
|
+
ax.set_ylabel("rank by the methods (1 = best)")
|
|
71
|
+
f = fc.friedman
|
|
72
|
+
ax.set_title(f"Friedman p = {f['p']:.2g}, Kendall W = {f['W']:.2f}", fontsize=9, loc="left")
|
|
73
|
+
despine(ax)
|
|
74
|
+
return ax
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def plot_method_parallel(fc, ax=None, order=None, highlight=None):
|
|
78
|
+
"""Parallel coordinates of the method rankings, axes in the optimal adjacent order.
|
|
79
|
+
|
|
80
|
+
Every line is an alternative; ``order`` defaults to ``fc.adjacent[0]`` (the
|
|
81
|
+
order minimizing the summed absolute rank differences of neighbouring axes).
|
|
82
|
+
"""
|
|
83
|
+
order = list(fc.adjacent[0]) if order is None else list(order)
|
|
84
|
+
R = fc.ranks[order]
|
|
85
|
+
k, m = R.shape
|
|
86
|
+
ax = ax_or_new(ax, (max(5.5, 0.9 * m + 2.0), 3.6))
|
|
87
|
+
cons = fc.consensus["consensus_rank"].reindex(R.index)
|
|
88
|
+
cmap = plt.get_cmap("viridis")
|
|
89
|
+
for alt in R.index:
|
|
90
|
+
lw = 2.2 if highlight is not None and alt in highlight else 1.0
|
|
91
|
+
ax.plot(range(m), R.loc[alt], color=cmap((cons[alt] - 1) / max(k - 1, 1)), lw=lw, alpha=0.85)
|
|
92
|
+
ax.text(m - 1 + 0.08, R.loc[alt].iloc[-1], alt, fontsize=6.5, va="center", color=INK)
|
|
93
|
+
for j in range(m):
|
|
94
|
+
ax.axvline(j, color=GRAY, lw=0.6, ls=":")
|
|
95
|
+
ax.set_xticks(range(m))
|
|
96
|
+
ax.set_xticklabels(order, rotation=90, fontsize=8)
|
|
97
|
+
ax.set_xlim(-0.25, m - 1 + 1.1)
|
|
98
|
+
ax.set_ylim(k + 0.5, 0.5)
|
|
99
|
+
ax.set_ylabel("rank")
|
|
100
|
+
ax.set_title(f"summed adjacent rank differences: {fc.adjacent[1]:.0f}", fontsize=9, loc="left")
|
|
101
|
+
despine(ax, ("left",))
|
|
102
|
+
return ax
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def plot_fair_comparison(fc, axes=None, figsize=(12.5, 4.0)):
|
|
106
|
+
"""Two panels: consensus of the alternatives and the parallel coordinates of the methods."""
|
|
107
|
+
if axes is None:
|
|
108
|
+
fig, axes = plt.subplots(1, 2, figsize=figsize, gridspec_kw={"width_ratios": [1.3, 1], "wspace": 0.6})
|
|
109
|
+
plot_consensus(fc, ax=axes[0])
|
|
110
|
+
plot_method_parallel(fc, ax=axes[1])
|
|
111
|
+
return axes
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def plot_pwr_sequence(seq: dict, ax=None):
|
|
115
|
+
"""Ranks of the alternatives along a :func:`srdkit.tournament.pwr_sequence` (thresholds on the x axis)."""
|
|
116
|
+
R = seq["ranks"]
|
|
117
|
+
k, t = R.shape
|
|
118
|
+
ax = ax_or_new(ax, (6.0, 3.4))
|
|
119
|
+
cons = seq["consensus"]["rank"].reindex(R.index)
|
|
120
|
+
cmap = plt.get_cmap("viridis")
|
|
121
|
+
for alt in R.index:
|
|
122
|
+
ax.plot(range(t), R.loc[alt], marker="o", ms=3, color=cmap((cons[alt] - 1) / max(k - 1, 1)), lw=1.0)
|
|
123
|
+
ax.text(t - 1 + 0.1, R.loc[alt].iloc[-1], alt, fontsize=6.5, va="center")
|
|
124
|
+
ax.set_xticks(range(t))
|
|
125
|
+
ax.set_xticklabels(R.columns, fontsize=8)
|
|
126
|
+
ax.set_ylim(k + 0.5, 0.5)
|
|
127
|
+
ax.set_ylabel("PWR rank")
|
|
128
|
+
ax.set_xlabel("indifference threshold (fraction of the criterion range)")
|
|
129
|
+
despine(ax)
|
|
130
|
+
return ax
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def plot_weights(weights: pd.Series, ax=None, groups: pd.Series | None = None):
|
|
134
|
+
"""Bar chart of data-driven weights (coloured by group when given)."""
|
|
135
|
+
w = weights.sort_values(ascending=False)
|
|
136
|
+
ax = ax_or_new(ax, (max(4.5, 0.35 * len(w) + 1.5), 2.8))
|
|
137
|
+
if groups is not None:
|
|
138
|
+
g = groups.reindex(w.index)
|
|
139
|
+
pal = cat_colors(int(g.max()))
|
|
140
|
+
colors = [pal[int(v) - 1] for v in g]
|
|
141
|
+
else:
|
|
142
|
+
colors = BRAND
|
|
143
|
+
ax.bar(range(len(w)), w.to_numpy(), color=colors)
|
|
144
|
+
ax.set_xticks(range(len(w)))
|
|
145
|
+
ax.set_xticklabels(w.index, rotation=90, fontsize=8)
|
|
146
|
+
ax.set_ylabel("weight")
|
|
147
|
+
despine(ax)
|
|
148
|
+
return ax
|