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/distribution.py
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
r"""Null distributions of SRD: exact, Monte Carlo and normal.
|
|
2
|
+
|
|
3
|
+
The first validation step of SRD, the *comparison of ranks with random numbers*
|
|
4
|
+
(CRRN; Héberger and Kollár-Hunek, 2011), asks whether a solution is closer to
|
|
5
|
+
the reference than a random ranking would be. Its null distribution is that of
|
|
6
|
+
|
|
7
|
+
.. math:: D = \sum_{i=1}^{n} \lvert x_{\pi(i)} - y_i \rvert ,
|
|
8
|
+
|
|
9
|
+
where :math:`\mathbf{y}` are the reference ranks, :math:`\mathbf{x}` the
|
|
10
|
+
(multi)set of ranks of the solution and :math:`\pi` a uniformly random
|
|
11
|
+
permutation.
|
|
12
|
+
|
|
13
|
+
Exact distribution for any tie pattern
|
|
14
|
+
--------------------------------------
|
|
15
|
+
Héberger and Kollár-Hunek enumerated all permutations up to :math:`n=13` and used
|
|
16
|
+
a normal approximation above; the rSRD package simulates the distribution. Here
|
|
17
|
+
the distribution is computed *exactly* and in polynomial time for arbitrary tie
|
|
18
|
+
patterns of both vectors by a transfer-matrix (sweep) dynamic programme:
|
|
19
|
+
|
|
20
|
+
* write every rank as an integer in half units (mid-ranks of ties become
|
|
21
|
+
integers) and sweep a cut point :math:`t` from left to right;
|
|
22
|
+
* :math:`\sum_i |x_{\pi(i)}-y_i| = \int N(t)\,dt`, where :math:`N(t)` is the number of
|
|
23
|
+
pairs straddling the cut, i.e. :math:`u+v` with :math:`u` the solution slots left of
|
|
24
|
+
:math:`t` whose partner lies to the right and :math:`v` the reference positions
|
|
25
|
+
left of :math:`t` whose partner lies to the right;
|
|
26
|
+
* :math:`u - v` equals the known difference of the numbers of solution and
|
|
27
|
+
reference values left of :math:`t`, so :math:`u` alone is the state;
|
|
28
|
+
* a block of :math:`m` solution values closes :math:`a` open reference positions in
|
|
29
|
+
:math:`\binom{m}{a} v^{\underline{a}}` ways and leaves :math:`m-a` open; a block of
|
|
30
|
+
reference values is handled symmetrically.
|
|
31
|
+
|
|
32
|
+
The programme runs in :math:`O(n^2 \cdot n^2)` time at worst and reproduces, without
|
|
33
|
+
ties, the classical result that Spearman's footrule takes the values
|
|
34
|
+
:math:`0,2,\dots,2\lfloor n^2/4\rfloor` (OEIS A062869; Guay-Paquet and Petersen,
|
|
35
|
+
2014). With ``exact=True`` it returns integer counts that sum to :math:`n!`.
|
|
36
|
+
|
|
37
|
+
Exact moments for any tie pattern
|
|
38
|
+
---------------------------------
|
|
39
|
+
By Hoeffding's combinatorial central limit theorem (Hoeffding, 1951), with
|
|
40
|
+
:math:`c_{ik}=|x_k-y_i|` and :math:`d_{ik}` its doubly centred version,
|
|
41
|
+
:math:`\mathbb{E}D = \frac1n\sum_{i,k}c_{ik}` and
|
|
42
|
+
:math:`\mathrm{Var}\,D = \frac{1}{n-1}\sum_{i,k}d_{ik}^2`; without ties these are
|
|
43
|
+
:math:`(n^2-1)/3` and :math:`(n+1)(2n^2+7)/45` (Diaconis and Graham, 1977).
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
from __future__ import annotations
|
|
47
|
+
|
|
48
|
+
import itertools
|
|
49
|
+
import math
|
|
50
|
+
from dataclasses import dataclass, field
|
|
51
|
+
|
|
52
|
+
import numpy as np
|
|
53
|
+
from scipy import stats
|
|
54
|
+
|
|
55
|
+
from ._utils import as_rng, falling_factorial, srd_max
|
|
56
|
+
from .ranking import midranks_from_blocks, tie_blocks
|
|
57
|
+
|
|
58
|
+
PERCENTILES = {"XX1": 0.05, "Q1": 0.25, "Med": 0.5, "Q3": 0.75, "XX19": 0.95}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# --------------------------------------------------------------------------- distribution object
|
|
62
|
+
@dataclass
|
|
63
|
+
class SRDDistribution:
|
|
64
|
+
"""A discrete null distribution of SRD (or of another rank distance).
|
|
65
|
+
|
|
66
|
+
Attributes
|
|
67
|
+
----------
|
|
68
|
+
values : numpy.ndarray
|
|
69
|
+
Support in raw units (sorted).
|
|
70
|
+
probs : numpy.ndarray
|
|
71
|
+
Probabilities of the support points.
|
|
72
|
+
n : int
|
|
73
|
+
Number of objects.
|
|
74
|
+
scale : float
|
|
75
|
+
Normalizing constant (``floor(n^2/2)`` for SRD).
|
|
76
|
+
kind : str
|
|
77
|
+
``"exact"``, ``"monte-carlo"``, ``"normal"`` or ``"enumeration"``.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
values: np.ndarray
|
|
81
|
+
probs: np.ndarray
|
|
82
|
+
n: int
|
|
83
|
+
scale: float
|
|
84
|
+
kind: str = "exact"
|
|
85
|
+
counts: list | None = None
|
|
86
|
+
info: dict = field(default_factory=dict)
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def normalized_values(self) -> np.ndarray:
|
|
90
|
+
return self.values / self.scale if self.scale > 0 else self.values
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def mean(self) -> float:
|
|
94
|
+
return float(np.dot(self.values, self.probs))
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def std(self) -> float:
|
|
98
|
+
mu = self.mean
|
|
99
|
+
return float(np.sqrt(np.dot((self.values - mu) ** 2, self.probs)))
|
|
100
|
+
|
|
101
|
+
def cdf(self, d, normalized: bool = False):
|
|
102
|
+
"""P(D <= d)."""
|
|
103
|
+
d = np.asarray(d, dtype=float) * (self.scale if normalized else 1.0)
|
|
104
|
+
c = np.cumsum(self.probs)
|
|
105
|
+
idx = np.searchsorted(self.values, d + 1e-9, side="right") - 1
|
|
106
|
+
out = np.where(idx >= 0, c[np.clip(idx, 0, None)], 0.0)
|
|
107
|
+
return np.clip(out, 0.0, 1.0) if out.ndim else float(np.clip(out, 0.0, 1.0))
|
|
108
|
+
|
|
109
|
+
def sf(self, d, normalized: bool = False):
|
|
110
|
+
"""P(D >= d)."""
|
|
111
|
+
d = np.asarray(d, dtype=float) * (self.scale if normalized else 1.0)
|
|
112
|
+
tail = np.cumsum(self.probs[::-1])[::-1]
|
|
113
|
+
idx = np.searchsorted(self.values, d - 1e-9, side="left")
|
|
114
|
+
out = np.where(idx < self.values.size, tail[np.clip(idx, None, self.values.size - 1)], 0.0)
|
|
115
|
+
return np.clip(out, 0.0, 1.0) if out.ndim else float(np.clip(out, 0.0, 1.0))
|
|
116
|
+
|
|
117
|
+
def ppf(self, q, normalized: bool = False):
|
|
118
|
+
"""Smallest support value ``d`` with ``P(D <= d) >= q``."""
|
|
119
|
+
c = np.cumsum(self.probs)
|
|
120
|
+
idx = np.searchsorted(c, np.asarray(q, dtype=float) - 1e-12, side="left")
|
|
121
|
+
v = self.values[np.clip(idx, 0, self.values.size - 1)]
|
|
122
|
+
return v / self.scale if normalized else v
|
|
123
|
+
|
|
124
|
+
def percentiles(self, normalized: bool = True) -> dict:
|
|
125
|
+
"""The XX1 (5%), Q1, Med, Q3 and XX19 (95%) points used on SRD plots."""
|
|
126
|
+
return {k: float(self.ppf(q, normalized=normalized)) for k, q in PERCENTILES.items()}
|
|
127
|
+
|
|
128
|
+
def pvalues(self, d, normalized: bool = False):
|
|
129
|
+
"""Lower and upper tail probabilities (similar-to-reference and reversed)."""
|
|
130
|
+
return self.cdf(d, normalized=normalized), self.sf(d, normalized=normalized)
|
|
131
|
+
|
|
132
|
+
def sample(self, size: int, random_state=None) -> np.ndarray:
|
|
133
|
+
rng = as_rng(random_state)
|
|
134
|
+
return rng.choice(self.values, size=size, p=self.probs / self.probs.sum())
|
|
135
|
+
|
|
136
|
+
def __repr__(self) -> str:
|
|
137
|
+
p = self.percentiles()
|
|
138
|
+
return (f"SRDDistribution(n={self.n}, kind={self.kind!r}, mean={self.mean / self.scale:.4f}, "
|
|
139
|
+
f"XX1={p['XX1']:.4f}, Med={p['Med']:.4f}, XX19={p['XX19']:.4f})")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
@dataclass
|
|
143
|
+
class NormalSRD(SRDDistribution):
|
|
144
|
+
"""Normal approximation with exact first two moments (continuous)."""
|
|
145
|
+
|
|
146
|
+
mu: float = 0.0
|
|
147
|
+
sigma: float = 1.0
|
|
148
|
+
|
|
149
|
+
@property
|
|
150
|
+
def mean(self) -> float:
|
|
151
|
+
return self.mu
|
|
152
|
+
|
|
153
|
+
@property
|
|
154
|
+
def std(self) -> float:
|
|
155
|
+
return self.sigma
|
|
156
|
+
|
|
157
|
+
def cdf(self, d, normalized: bool = False):
|
|
158
|
+
d = np.asarray(d, dtype=float) * (self.scale if normalized else 1.0)
|
|
159
|
+
out = stats.norm.cdf(d, self.mu, self.sigma)
|
|
160
|
+
return out if out.ndim else float(out)
|
|
161
|
+
|
|
162
|
+
def sf(self, d, normalized: bool = False):
|
|
163
|
+
d = np.asarray(d, dtype=float) * (self.scale if normalized else 1.0)
|
|
164
|
+
out = stats.norm.sf(d, self.mu, self.sigma)
|
|
165
|
+
return out if out.ndim else float(out)
|
|
166
|
+
|
|
167
|
+
def ppf(self, q, normalized: bool = False):
|
|
168
|
+
v = stats.norm.ppf(np.asarray(q, dtype=float), self.mu, self.sigma)
|
|
169
|
+
return v / self.scale if normalized else v
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# --------------------------------------------------------------------------- exact DP
|
|
173
|
+
def _as_multiset(spec, n: int | None = None) -> np.ndarray:
|
|
174
|
+
"""Mid-rank multiset from a rank vector, a value vector or ``None`` (no ties)."""
|
|
175
|
+
if spec is None:
|
|
176
|
+
if n is None:
|
|
177
|
+
raise ValueError("n is required when no rank vector is given")
|
|
178
|
+
return np.arange(1, n + 1, dtype=float)
|
|
179
|
+
return midranks_from_blocks(tie_blocks(spec))
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def footrule_null_exact(x=None, y=None, n: int | None = None, exact: bool = False) -> SRDDistribution:
|
|
183
|
+
r"""Exact null distribution of :math:`\sum_i |x_{\pi(i)}-y_i|` for any tie patterns.
|
|
184
|
+
|
|
185
|
+
Parameters
|
|
186
|
+
----------
|
|
187
|
+
x, y : array-like or None
|
|
188
|
+
Rank (or value) vectors of the solution and of the reference; only their
|
|
189
|
+
tie patterns matter. ``None`` means no ties.
|
|
190
|
+
n : int, optional
|
|
191
|
+
Number of objects (needed if both ``x`` and ``y`` are ``None``).
|
|
192
|
+
exact : bool
|
|
193
|
+
Return integer counts (Python integers, summing to ``n!``) in
|
|
194
|
+
``SRDDistribution.counts``; otherwise floating point is used throughout.
|
|
195
|
+
|
|
196
|
+
Examples
|
|
197
|
+
--------
|
|
198
|
+
>>> d = footrule_null_exact(n=4, exact=True)
|
|
199
|
+
>>> d.values.tolist(), d.counts
|
|
200
|
+
([0.0, 2.0, 4.0, 6.0, 8.0], [1, 3, 7, 9, 4])
|
|
201
|
+
"""
|
|
202
|
+
xs = _as_multiset(x, n)
|
|
203
|
+
ys = _as_multiset(y, xs.size if n is None else n)
|
|
204
|
+
if xs.size != ys.size:
|
|
205
|
+
raise ValueError("x and y must have the same length")
|
|
206
|
+
n = xs.size
|
|
207
|
+
cx = np.rint(2 * xs).astype(int)
|
|
208
|
+
cy = np.rint(2 * ys).astype(int)
|
|
209
|
+
coords = np.unique(np.concatenate([cx, cy]))
|
|
210
|
+
mxs = {int(c): int(k) for c, k in zip(*np.unique(cx, return_counts=True))}
|
|
211
|
+
mys = {int(c): int(k) for c, k in zip(*np.unique(cy, return_counts=True))}
|
|
212
|
+
dtype = object if exact else float
|
|
213
|
+
Hmax = n * n + 2 # half-unit distances never exceed n^2
|
|
214
|
+
P = np.zeros((n + 1, Hmax), dtype=dtype)
|
|
215
|
+
Q = np.zeros((n + 1, Hmax), dtype=dtype)
|
|
216
|
+
if exact:
|
|
217
|
+
P[:] = 0
|
|
218
|
+
Q[:] = 0
|
|
219
|
+
P[0, 0] = 1
|
|
220
|
+
L = 1 # active length of the distance axis
|
|
221
|
+
lo, hi = 0, 0 # active range of the state u
|
|
222
|
+
A = B = 0
|
|
223
|
+
prev = int(coords[0])
|
|
224
|
+
for c in coords.tolist():
|
|
225
|
+
gap = c - prev
|
|
226
|
+
if gap:
|
|
227
|
+
d0 = A - B
|
|
228
|
+
Lnew = L
|
|
229
|
+
for u in range(lo, hi + 1):
|
|
230
|
+
if u - d0 >= 0:
|
|
231
|
+
Lnew = max(Lnew, gap * (2 * u - d0) + L)
|
|
232
|
+
if Lnew > Hmax:
|
|
233
|
+
raise RuntimeError("distance buffer overflow")
|
|
234
|
+
Q[:, :Lnew] = 0
|
|
235
|
+
for u in range(lo, hi + 1):
|
|
236
|
+
if u - d0 < 0:
|
|
237
|
+
continue
|
|
238
|
+
s = gap * (2 * u - d0)
|
|
239
|
+
Q[u, s:s + L] = P[u, :L]
|
|
240
|
+
P, Q = Q, P
|
|
241
|
+
L = Lnew
|
|
242
|
+
mx = mxs.get(c, 0)
|
|
243
|
+
if mx:
|
|
244
|
+
d0 = A - B
|
|
245
|
+
nlo, nhi = n + 1, -1
|
|
246
|
+
Q[:, :L] = 0
|
|
247
|
+
for a in range(mx + 1):
|
|
248
|
+
k = mx - a
|
|
249
|
+
for u in range(lo, hi + 1):
|
|
250
|
+
v = u - d0
|
|
251
|
+
# keep only completable states: open slots need partners still to come
|
|
252
|
+
if v < a or u + k > n - B or (v - a) > n - (A + mx):
|
|
253
|
+
continue
|
|
254
|
+
w = math.comb(mx, a) * falling_factorial(v, a)
|
|
255
|
+
Q[u + k, :L] += (w if exact else float(w)) * P[u, :L]
|
|
256
|
+
nlo, nhi = min(nlo, u + k), max(nhi, u + k)
|
|
257
|
+
P, Q = Q, P
|
|
258
|
+
lo, hi = nlo, nhi
|
|
259
|
+
A += mx
|
|
260
|
+
my = mys.get(c, 0)
|
|
261
|
+
if my:
|
|
262
|
+
nlo, nhi = n + 1, -1
|
|
263
|
+
Q[:, :L] = 0
|
|
264
|
+
for b in range(min(my, n) + 1):
|
|
265
|
+
for u in range(max(lo, b), hi + 1):
|
|
266
|
+
v2 = u - (A - B) + my - b
|
|
267
|
+
if u - b > n - (B + my) or v2 > n - A or v2 < 0:
|
|
268
|
+
continue
|
|
269
|
+
w = math.comb(my, b) * falling_factorial(u, b)
|
|
270
|
+
Q[u - b, :L] += (w if exact else float(w)) * P[u, :L]
|
|
271
|
+
nlo, nhi = min(nlo, u - b), max(nhi, u - b)
|
|
272
|
+
P, Q = Q, P
|
|
273
|
+
lo, hi = nlo, nhi
|
|
274
|
+
B += my
|
|
275
|
+
if not exact:
|
|
276
|
+
tot = P[lo:hi + 1, :L].sum()
|
|
277
|
+
if tot > 0:
|
|
278
|
+
P[lo:hi + 1, :L] /= tot
|
|
279
|
+
prev = c
|
|
280
|
+
P = P[:, :L]
|
|
281
|
+
final = P[0]
|
|
282
|
+
nz = [h for h in range(final.size) if final[h] != 0]
|
|
283
|
+
values = np.asarray(nz, dtype=float) / 2.0
|
|
284
|
+
if exact:
|
|
285
|
+
counts = [int(final[h]) for h in nz]
|
|
286
|
+
tot = sum(counts)
|
|
287
|
+
probs = np.asarray([cnt / tot for cnt in counts], dtype=float)
|
|
288
|
+
else:
|
|
289
|
+
counts = None
|
|
290
|
+
probs = np.asarray([final[h] for h in nz], dtype=float)
|
|
291
|
+
probs = probs / probs.sum()
|
|
292
|
+
return SRDDistribution(values=values, probs=probs, n=n, scale=srd_max(n), kind="exact", counts=counts,
|
|
293
|
+
info={"x_blocks": tie_blocks(xs), "y_blocks": tie_blocks(ys)})
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def footrule_null_enumerate(x=None, y=None, n: int | None = None) -> SRDDistribution:
|
|
297
|
+
"""Brute-force enumeration of all ``n!`` arrangements (reference implementation, ``n <= 10``)."""
|
|
298
|
+
xs = _as_multiset(x, n)
|
|
299
|
+
ys = _as_multiset(y, xs.size if n is None else n)
|
|
300
|
+
n = xs.size
|
|
301
|
+
if n > 10:
|
|
302
|
+
raise ValueError("enumeration is limited to n <= 10")
|
|
303
|
+
vals: dict[float, int] = {}
|
|
304
|
+
for p in itertools.permutations(range(n)):
|
|
305
|
+
d = float(np.abs(xs[list(p)] - ys).sum())
|
|
306
|
+
vals[d] = vals.get(d, 0) + 1
|
|
307
|
+
keys = sorted(vals)
|
|
308
|
+
counts = [vals[k] for k in keys]
|
|
309
|
+
probs = np.asarray(counts, dtype=float) / math.factorial(n)
|
|
310
|
+
return SRDDistribution(values=np.asarray(keys), probs=probs, n=n, scale=srd_max(n), kind="enumeration", counts=counts)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
# --------------------------------------------------------------------------- moments, normal
|
|
314
|
+
def footrule_null_moments(x=None, y=None, n: int | None = None) -> tuple[float, float]:
|
|
315
|
+
r"""Exact mean and variance of the null distribution (Hoeffding, 1951), any ties.
|
|
316
|
+
|
|
317
|
+
>>> m, v = footrule_null_moments(n=10)
|
|
318
|
+
>>> round(m, 6), round(v, 6)
|
|
319
|
+
(33.0, 50.6)
|
|
320
|
+
"""
|
|
321
|
+
xs = _as_multiset(x, n)
|
|
322
|
+
ys = _as_multiset(y, xs.size if n is None else n)
|
|
323
|
+
nn = xs.size
|
|
324
|
+
C = np.abs(ys[:, None] - xs[None, :])
|
|
325
|
+
mean = C.sum() / nn
|
|
326
|
+
D = C - C.mean(axis=1, keepdims=True) - C.mean(axis=0, keepdims=True) + C.mean()
|
|
327
|
+
var = (D ** 2).sum() / (nn - 1) if nn > 1 else 0.0
|
|
328
|
+
return float(mean), float(var)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def footrule_null_normal(x=None, y=None, n: int | None = None) -> NormalSRD:
|
|
332
|
+
"""Normal approximation with exact moments for the given tie patterns."""
|
|
333
|
+
xs = _as_multiset(x, n)
|
|
334
|
+
m, v = footrule_null_moments(xs, y, xs.size)
|
|
335
|
+
nn = xs.size
|
|
336
|
+
return NormalSRD(values=np.array([m]), probs=np.array([1.0]), n=nn, scale=srd_max(nn), kind="normal",
|
|
337
|
+
mu=m, sigma=math.sqrt(max(v, 1e-300)))
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
# --------------------------------------------------------------------------- Monte Carlo
|
|
341
|
+
def random_ranking_with_ties(n: int, tie_probability: float = 0.0, rng=None) -> np.ndarray:
|
|
342
|
+
"""A random ranking of ``n`` objects in which adjacent positions are tied with the given probability."""
|
|
343
|
+
rng = as_rng(rng)
|
|
344
|
+
order = rng.permutation(n)
|
|
345
|
+
tied = rng.random(n - 1) < tie_probability if n > 1 else np.zeros(0, bool)
|
|
346
|
+
blocks, b = [], 1
|
|
347
|
+
for t in tied:
|
|
348
|
+
if t:
|
|
349
|
+
b += 1
|
|
350
|
+
else:
|
|
351
|
+
blocks.append(b)
|
|
352
|
+
b = 1
|
|
353
|
+
blocks.append(b)
|
|
354
|
+
mids = midranks_from_blocks(blocks)
|
|
355
|
+
r = np.empty(n)
|
|
356
|
+
r[order] = mids
|
|
357
|
+
return r
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def footrule_null_monte_carlo(x=None, y=None, n: int | None = None, n_sim: int = 100_000, option: str = "f",
|
|
361
|
+
tie_probability: float | None = None, random_state=None, chunk: int = 20_000) -> SRDDistribution:
|
|
362
|
+
"""Monte Carlo null distribution with the options of the rSRD package.
|
|
363
|
+
|
|
364
|
+
``option``:
|
|
365
|
+
``"n"`` no ties, fixed reference; ``"r"`` no ties, both vectors random;
|
|
366
|
+
``"t"`` both vectors with ties of probability ``tie_probability``;
|
|
367
|
+
``"p"`` random solution with tie probability ``tie_probability``, fixed reference;
|
|
368
|
+
``"d"`` the solution keeps its observed tie pattern, fixed reference;
|
|
369
|
+
``"f"`` (default) both keep their observed tie patterns (the permutation null).
|
|
370
|
+
"""
|
|
371
|
+
rng = as_rng(random_state)
|
|
372
|
+
if x is None and y is None and n is None:
|
|
373
|
+
raise ValueError("give x, y or n")
|
|
374
|
+
nn = n if n is not None else (len(x) if x is not None else len(y))
|
|
375
|
+
xs = _as_multiset(x, nn)
|
|
376
|
+
ys = _as_multiset(y, nn) if y is not None else np.arange(1, nn + 1, dtype=float)
|
|
377
|
+
out = []
|
|
378
|
+
done = 0
|
|
379
|
+
while done < n_sim:
|
|
380
|
+
k = min(chunk, n_sim - done)
|
|
381
|
+
if option in ("n", "r"):
|
|
382
|
+
base_x, base_y = np.arange(1, nn + 1, dtype=float), np.arange(1, nn + 1, dtype=float)
|
|
383
|
+
elif option == "d":
|
|
384
|
+
base_x, base_y = xs, np.arange(1, nn + 1, dtype=float)
|
|
385
|
+
elif option == "f":
|
|
386
|
+
base_x, base_y = xs, ys
|
|
387
|
+
elif option in ("t", "p"):
|
|
388
|
+
if tie_probability is None:
|
|
389
|
+
raise ValueError("option 't' or 'p' needs tie_probability")
|
|
390
|
+
base_x = base_y = None
|
|
391
|
+
else:
|
|
392
|
+
raise ValueError("option must be one of 'n', 'r', 't', 'p', 'd', 'f'")
|
|
393
|
+
if base_x is not None:
|
|
394
|
+
perm = np.argsort(rng.random((k, nn)), axis=1)
|
|
395
|
+
Xp = base_x[perm]
|
|
396
|
+
if option == "r":
|
|
397
|
+
Yp = base_y[np.argsort(rng.random((k, nn)), axis=1)]
|
|
398
|
+
else:
|
|
399
|
+
Yp = np.broadcast_to(base_y, (k, nn))
|
|
400
|
+
d = np.abs(Xp - Yp).sum(axis=1)
|
|
401
|
+
else:
|
|
402
|
+
d = np.empty(k)
|
|
403
|
+
yfix = np.arange(1, nn + 1, dtype=float)
|
|
404
|
+
for s in range(k):
|
|
405
|
+
xr = random_ranking_with_ties(nn, tie_probability, rng)
|
|
406
|
+
yr = random_ranking_with_ties(nn, tie_probability, rng) if option == "t" else yfix
|
|
407
|
+
d[s] = np.abs(xr - yr).sum()
|
|
408
|
+
out.append(d)
|
|
409
|
+
done += k
|
|
410
|
+
d = np.concatenate(out)
|
|
411
|
+
vals, cnt = np.unique(np.round(d * 2) / 2, return_counts=True)
|
|
412
|
+
return SRDDistribution(values=vals.astype(float), probs=cnt / cnt.sum(), n=nn, scale=srd_max(nn), kind="monte-carlo",
|
|
413
|
+
info={"n_sim": n_sim, "option": option})
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
# --------------------------------------------------------------------------- other distances
|
|
417
|
+
def kendall_null_exact(n: int) -> SRDDistribution:
|
|
418
|
+
r"""Exact distribution of the number of discordant pairs (Mahonian numbers).
|
|
419
|
+
|
|
420
|
+
The generating function is :math:`\prod_{k=1}^{n}(1+q+\dots+q^{k-1})`.
|
|
421
|
+
|
|
422
|
+
>>> kendall_null_exact(3).counts
|
|
423
|
+
[1, 2, 2, 1]
|
|
424
|
+
"""
|
|
425
|
+
c = [1]
|
|
426
|
+
for k in range(1, n + 1):
|
|
427
|
+
new = [0] * (len(c) + k - 1)
|
|
428
|
+
for i, ci in enumerate(c):
|
|
429
|
+
for j in range(k):
|
|
430
|
+
new[i + j] += ci
|
|
431
|
+
c = new
|
|
432
|
+
tot = sum(c)
|
|
433
|
+
return SRDDistribution(values=np.arange(len(c), dtype=float), probs=np.asarray([x / tot for x in c]), n=n,
|
|
434
|
+
scale=n * (n - 1) / 2, kind="exact", counts=c)
|
|
435
|
+
|
|
436
|
+
|
|
437
|
+
def cayley_null_exact(n: int) -> SRDDistribution:
|
|
438
|
+
"""Exact distribution of the Cayley distance ``n - #cycles`` (Stirling numbers of the first kind)."""
|
|
439
|
+
s = [[0] * (n + 1) for _ in range(n + 1)]
|
|
440
|
+
s[0][0] = 1
|
|
441
|
+
for i in range(1, n + 1):
|
|
442
|
+
for k in range(1, i + 1):
|
|
443
|
+
s[i][k] = s[i - 1][k - 1] + (i - 1) * s[i - 1][k]
|
|
444
|
+
counts = [s[n][n - d] for d in range(n)]
|
|
445
|
+
tot = sum(counts)
|
|
446
|
+
return SRDDistribution(values=np.arange(n, dtype=float), probs=np.asarray([c / tot for c in counts]), n=n,
|
|
447
|
+
scale=max(n - 1, 1), kind="exact", counts=counts)
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def hamming_null_exact(n: int) -> SRDDistribution:
|
|
451
|
+
"""Exact distribution of the Hamming distance ``n - #fixed points`` (rencontres numbers)."""
|
|
452
|
+
der = [1, 0]
|
|
453
|
+
for k in range(2, n + 1):
|
|
454
|
+
der.append((k - 1) * (der[-1] + der[-2]))
|
|
455
|
+
counts = [math.comb(n, n - d) * der[d] for d in range(n + 1)]
|
|
456
|
+
tot = sum(counts)
|
|
457
|
+
return SRDDistribution(values=np.arange(n + 1, dtype=float), probs=np.asarray([c / tot for c in counts]), n=n,
|
|
458
|
+
scale=n, kind="exact", counts=counts)
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def distance_null_monte_carlo(distance, r, q, n_sim: int = 20_000, random_state=None) -> SRDDistribution:
|
|
462
|
+
"""Permutation null distribution of any rank distance (keeps both tie patterns)."""
|
|
463
|
+
from .distances import distance_max, get_distance
|
|
464
|
+
|
|
465
|
+
f, name = get_distance(distance)
|
|
466
|
+
rng = as_rng(random_state)
|
|
467
|
+
r = np.asarray(r, dtype=float)
|
|
468
|
+
q = np.asarray(q, dtype=float)
|
|
469
|
+
d = np.asarray([f(r[rng.permutation(r.size)], q) for _ in range(n_sim)])
|
|
470
|
+
vals, cnt = np.unique(np.round(d, 9), return_counts=True)
|
|
471
|
+
return SRDDistribution(values=vals, probs=cnt / cnt.sum(), n=r.size, scale=distance_max(name, r.size),
|
|
472
|
+
kind="monte-carlo", info={"n_sim": n_sim, "distance": name})
|
|
473
|
+
|
|
474
|
+
|
|
475
|
+
# --------------------------------------------------------------------------- dispatcher
|
|
476
|
+
def null_distribution(x=None, y=None, n: int | None = None, method: str = "auto", distance: str = "footrule",
|
|
477
|
+
n_sim: int = 100_000, random_state=None, max_exact: int = 200) -> SRDDistribution:
|
|
478
|
+
"""Null distribution of SRD (or of another rank distance) for the given tie patterns.
|
|
479
|
+
|
|
480
|
+
``method``: ``"exact"`` (dynamic programme), ``"enumerate"`` (brute force,
|
|
481
|
+
``n <= 10``), ``"monte-carlo"``, ``"normal"`` (exact moments) or ``"auto"``
|
|
482
|
+
(exact up to ``max_exact`` objects, normal above).
|
|
483
|
+
"""
|
|
484
|
+
nn = n if n is not None else (len(x) if x is not None else len(y))
|
|
485
|
+
if distance != "footrule":
|
|
486
|
+
no_ties = (x is None or len(tie_blocks(x)) == nn) and (y is None or len(tie_blocks(y)) == nn)
|
|
487
|
+
exact_fun = {"kendall": kendall_null_exact, "cayley": cayley_null_exact, "hamming": hamming_null_exact}
|
|
488
|
+
if no_ties and distance in exact_fun and method in ("auto", "exact"):
|
|
489
|
+
return exact_fun[distance](nn)
|
|
490
|
+
xr = np.arange(1, nn + 1, dtype=float) if x is None else np.asarray(x, dtype=float)
|
|
491
|
+
yr = np.arange(1, nn + 1, dtype=float) if y is None else np.asarray(y, dtype=float)
|
|
492
|
+
return distance_null_monte_carlo(distance, xr, yr, n_sim=min(n_sim, 20_000), random_state=random_state)
|
|
493
|
+
if method == "auto":
|
|
494
|
+
method = "exact" if nn <= max_exact else "normal"
|
|
495
|
+
if method == "exact":
|
|
496
|
+
return footrule_null_exact(x, y, nn)
|
|
497
|
+
if method == "enumerate":
|
|
498
|
+
return footrule_null_enumerate(x, y, nn)
|
|
499
|
+
if method in ("monte-carlo", "mc"):
|
|
500
|
+
return footrule_null_monte_carlo(x, y, nn, n_sim=n_sim, random_state=random_state)
|
|
501
|
+
if method == "normal":
|
|
502
|
+
return footrule_null_normal(x, y, nn)
|
|
503
|
+
raise ValueError("method must be 'auto', 'exact', 'enumerate', 'monte-carlo' or 'normal'")
|