scalerank 0.1.0__tar.gz

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.
@@ -0,0 +1,295 @@
1
+ # This file is automatically @generated by Cargo.
2
+ # It is not intended for manual editing.
3
+ version = 4
4
+
5
+ [[package]]
6
+ name = "autocfg"
7
+ version = "1.5.1"
8
+ source = "registry+https://github.com/rust-lang/crates.io-index"
9
+ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
10
+
11
+ [[package]]
12
+ name = "crossbeam-deque"
13
+ version = "0.8.8"
14
+ source = "registry+https://github.com/rust-lang/crates.io-index"
15
+ checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
16
+ dependencies = [
17
+ "crossbeam-epoch",
18
+ "crossbeam-utils",
19
+ ]
20
+
21
+ [[package]]
22
+ name = "crossbeam-epoch"
23
+ version = "0.9.21"
24
+ source = "registry+https://github.com/rust-lang/crates.io-index"
25
+ checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
26
+ dependencies = [
27
+ "crossbeam-utils",
28
+ ]
29
+
30
+ [[package]]
31
+ name = "crossbeam-utils"
32
+ version = "0.8.23"
33
+ source = "registry+https://github.com/rust-lang/crates.io-index"
34
+ checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
35
+
36
+ [[package]]
37
+ name = "either"
38
+ version = "1.19.0"
39
+ source = "registry+https://github.com/rust-lang/crates.io-index"
40
+ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
41
+
42
+ [[package]]
43
+ name = "heck"
44
+ version = "0.5.0"
45
+ source = "registry+https://github.com/rust-lang/crates.io-index"
46
+ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
47
+
48
+ [[package]]
49
+ name = "libc"
50
+ version = "0.2.191"
51
+ source = "registry+https://github.com/rust-lang/crates.io-index"
52
+ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
53
+
54
+ [[package]]
55
+ name = "matrixmultiply"
56
+ version = "0.3.11"
57
+ source = "registry+https://github.com/rust-lang/crates.io-index"
58
+ checksum = "3f607c237553f086e7043417a51df26b2eb899d3caff94e6a67592ff992fedc7"
59
+ dependencies = [
60
+ "autocfg",
61
+ "rawpointer",
62
+ ]
63
+
64
+ [[package]]
65
+ name = "ndarray"
66
+ version = "0.17.2"
67
+ source = "registry+https://github.com/rust-lang/crates.io-index"
68
+ checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d"
69
+ dependencies = [
70
+ "matrixmultiply",
71
+ "num-complex",
72
+ "num-integer",
73
+ "num-traits",
74
+ "portable-atomic",
75
+ "portable-atomic-util",
76
+ "rawpointer",
77
+ ]
78
+
79
+ [[package]]
80
+ name = "num-complex"
81
+ version = "0.4.6"
82
+ source = "registry+https://github.com/rust-lang/crates.io-index"
83
+ checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"
84
+ dependencies = [
85
+ "num-traits",
86
+ ]
87
+
88
+ [[package]]
89
+ name = "num-integer"
90
+ version = "0.1.47"
91
+ source = "registry+https://github.com/rust-lang/crates.io-index"
92
+ checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
93
+ dependencies = [
94
+ "num-traits",
95
+ ]
96
+
97
+ [[package]]
98
+ name = "num-traits"
99
+ version = "0.2.19"
100
+ source = "registry+https://github.com/rust-lang/crates.io-index"
101
+ checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
102
+ dependencies = [
103
+ "autocfg",
104
+ ]
105
+
106
+ [[package]]
107
+ name = "numpy"
108
+ version = "0.30.0"
109
+ source = "registry+https://github.com/rust-lang/crates.io-index"
110
+ checksum = "aa0b9111761885449e894981fa8051dcf69e0bd114aecbd4bcdd830b6be4ed92"
111
+ dependencies = [
112
+ "libc",
113
+ "ndarray",
114
+ "num-complex",
115
+ "num-integer",
116
+ "num-traits",
117
+ "pyo3",
118
+ "pyo3-build-config",
119
+ "rustc-hash",
120
+ ]
121
+
122
+ [[package]]
123
+ name = "once_cell"
124
+ version = "1.21.4"
125
+ source = "registry+https://github.com/rust-lang/crates.io-index"
126
+ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
127
+
128
+ [[package]]
129
+ name = "portable-atomic"
130
+ version = "1.15.0"
131
+ source = "registry+https://github.com/rust-lang/crates.io-index"
132
+ checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
133
+
134
+ [[package]]
135
+ name = "portable-atomic-util"
136
+ version = "0.2.8"
137
+ source = "registry+https://github.com/rust-lang/crates.io-index"
138
+ checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
139
+ dependencies = [
140
+ "portable-atomic",
141
+ ]
142
+
143
+ [[package]]
144
+ name = "proc-macro2"
145
+ version = "1.0.107"
146
+ source = "registry+https://github.com/rust-lang/crates.io-index"
147
+ checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
148
+ dependencies = [
149
+ "unicode-ident",
150
+ ]
151
+
152
+ [[package]]
153
+ name = "pyo3"
154
+ version = "0.30.1"
155
+ source = "registry+https://github.com/rust-lang/crates.io-index"
156
+ checksum = "229ca13b8a15bb0d1487b81ab975bfcd97513416499a8312011b6036e42e0de4"
157
+ dependencies = [
158
+ "libc",
159
+ "once_cell",
160
+ "portable-atomic",
161
+ "pyo3-build-config",
162
+ "pyo3-ffi",
163
+ "pyo3-macros",
164
+ ]
165
+
166
+ [[package]]
167
+ name = "pyo3-build-config"
168
+ version = "0.30.1"
169
+ source = "registry+https://github.com/rust-lang/crates.io-index"
170
+ checksum = "70130e2b6dd1ee589a8788026a429561ca5c40fa7a2fa7914c2282eddae24700"
171
+ dependencies = [
172
+ "target-lexicon",
173
+ ]
174
+
175
+ [[package]]
176
+ name = "pyo3-ffi"
177
+ version = "0.30.1"
178
+ source = "registry+https://github.com/rust-lang/crates.io-index"
179
+ checksum = "5e7ff73c555c286d212d4ce7e5fbda845a973c4f61bd5f160f5f2c3c2a04d1c4"
180
+ dependencies = [
181
+ "libc",
182
+ "pyo3-build-config",
183
+ ]
184
+
185
+ [[package]]
186
+ name = "pyo3-macros"
187
+ version = "0.30.1"
188
+ source = "registry+https://github.com/rust-lang/crates.io-index"
189
+ checksum = "c46d2e5862c7bb8207e3b639f713dda3c499933444784154c11d013c5a691b60"
190
+ dependencies = [
191
+ "proc-macro2",
192
+ "pyo3-macros-backend",
193
+ "quote",
194
+ "syn",
195
+ ]
196
+
197
+ [[package]]
198
+ name = "pyo3-macros-backend"
199
+ version = "0.30.1"
200
+ source = "registry+https://github.com/rust-lang/crates.io-index"
201
+ checksum = "38b89f066f2ae72a2aef52d1537ca2fcd104440ebfadee06e97aa90738a25b9b"
202
+ dependencies = [
203
+ "heck",
204
+ "proc-macro2",
205
+ "quote",
206
+ "syn",
207
+ ]
208
+
209
+ [[package]]
210
+ name = "quote"
211
+ version = "1.0.47"
212
+ source = "registry+https://github.com/rust-lang/crates.io-index"
213
+ checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
214
+ dependencies = [
215
+ "proc-macro2",
216
+ ]
217
+
218
+ [[package]]
219
+ name = "rawpointer"
220
+ version = "0.2.1"
221
+ source = "registry+https://github.com/rust-lang/crates.io-index"
222
+ checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
223
+
224
+ [[package]]
225
+ name = "rayon"
226
+ version = "1.12.0"
227
+ source = "registry+https://github.com/rust-lang/crates.io-index"
228
+ checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
229
+ dependencies = [
230
+ "either",
231
+ "rayon-core",
232
+ ]
233
+
234
+ [[package]]
235
+ name = "rayon-core"
236
+ version = "1.13.0"
237
+ source = "registry+https://github.com/rust-lang/crates.io-index"
238
+ checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
239
+ dependencies = [
240
+ "crossbeam-deque",
241
+ "crossbeam-utils",
242
+ ]
243
+
244
+ [[package]]
245
+ name = "rustc-hash"
246
+ version = "2.1.3"
247
+ source = "registry+https://github.com/rust-lang/crates.io-index"
248
+ checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
249
+
250
+ [[package]]
251
+ name = "scalerank"
252
+ version = "0.1.0"
253
+ dependencies = [
254
+ "rayon",
255
+ ]
256
+
257
+ [[package]]
258
+ name = "scalerank-baselines"
259
+ version = "0.1.0"
260
+ dependencies = [
261
+ "scalerank",
262
+ ]
263
+
264
+ [[package]]
265
+ name = "scalerank-py"
266
+ version = "0.1.0"
267
+ dependencies = [
268
+ "numpy",
269
+ "pyo3",
270
+ "scalerank",
271
+ "scalerank-baselines",
272
+ ]
273
+
274
+ [[package]]
275
+ name = "syn"
276
+ version = "3.0.10"
277
+ source = "registry+https://github.com/rust-lang/crates.io-index"
278
+ checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
279
+ dependencies = [
280
+ "proc-macro2",
281
+ "quote",
282
+ "unicode-ident",
283
+ ]
284
+
285
+ [[package]]
286
+ name = "target-lexicon"
287
+ version = "0.13.6"
288
+ source = "registry+https://github.com/rust-lang/crates.io-index"
289
+ checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da"
290
+
291
+ [[package]]
292
+ name = "unicode-ident"
293
+ version = "1.0.27"
294
+ source = "registry+https://github.com/rust-lang/crates.io-index"
295
+ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
@@ -0,0 +1,18 @@
1
+ [workspace]
2
+ resolver = "3"
3
+ members = ["crates/scalerank", "crates/scalerank-baselines", "crates/scalerank-py"]
4
+
5
+ [workspace.package]
6
+ version = "0.1.0"
7
+ edition = "2024"
8
+ rust-version = "1.88"
9
+ license = "BSD-3-Clause"
10
+ repository = "https://github.com/tsjshg/scalerank"
11
+
12
+ [profile.release]
13
+ lto = "thin"
14
+ codegen-units = 1
15
+
16
+ # tests run the optimiser on small data; unoptimised they take minutes
17
+ [profile.test]
18
+ opt-level = 3
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, Shingo Tsuji
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,29 @@
1
+ Metadata-Version: 2.4
2
+ Name: scalerank
3
+ Version: 0.1.0
4
+ Classifier: Programming Language :: Python :: 3
5
+ Classifier: Programming Language :: Rust
6
+ Classifier: Topic :: Scientific/Engineering
7
+ Requires-Dist: numpy
8
+ License-File: LICENSE
9
+ Summary: ScaleRank dimensionality reduction: neighbour ranks over a range of scales, in Rust
10
+ Keywords: dimensionality reduction,embedding,visualisation,single-cell
11
+ License-Expression: BSD-3-Clause
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
14
+ Project-URL: Repository, https://github.com/tsjshg/scalerank
15
+
16
+ # scalerank
17
+
18
+ Python package of [ScaleRank](https://github.com/tsjshg/scalerank), a
19
+ dimensionality reduction that preserves neighbour ranks over a range of
20
+ scales. The implementation is in Rust.
21
+
22
+ ```python
23
+ from scalerank import ScaleRank
24
+
25
+ Y = ScaleRank(gamma=0.5, random_state=0).fit_transform(X) # X: (n, d) float array
26
+ ```
27
+
28
+ See the repository's README for the method and the parameters.
29
+
@@ -0,0 +1,13 @@
1
+ # scalerank
2
+
3
+ Python package of [ScaleRank](https://github.com/tsjshg/scalerank), a
4
+ dimensionality reduction that preserves neighbour ranks over a range of
5
+ scales. The implementation is in Rust.
6
+
7
+ ```python
8
+ from scalerank import ScaleRank
9
+
10
+ Y = ScaleRank(gamma=0.5, random_state=0).fit_transform(X) # X: (n, d) float array
11
+ ```
12
+
13
+ See the repository's README for the method and the parameters.
@@ -0,0 +1,15 @@
1
+ [package]
2
+ name = "scalerank"
3
+ description = "ScaleRank dimensionality reduction: neighbour ranks over a range of scales, without N x N structures"
4
+ version.workspace = true
5
+ edition.workspace = true
6
+ rust-version.workspace = true
7
+ license.workspace = true
8
+ repository.workspace = true
9
+
10
+ [features]
11
+ default = ["parallel"]
12
+ parallel = ["dep:rayon"]
13
+
14
+ [dependencies]
15
+ rayon = { version = "1.12", optional = true }
@@ -0,0 +1,260 @@
1
+ //! Embedding quality, as in drbench's `metrics` module.
2
+ //!
3
+ //! Rank metrics follow Lee & Verleysen (2009): co-ranking based Q_NX / R_NX,
4
+ //! the log-K weighted AUC of R_NX (Lee et al. 2015), trustworthiness and
5
+ //! continuity. Each is a mean over rows, so with `anchors` only those rows
6
+ //! are ranked (O(anchors x N)) and the result is an unbiased estimate.
7
+ //! Ranks break distance ties by index; self gets rank 0 and is left out.
8
+
9
+ use crate::knn::Knn;
10
+ use crate::par;
11
+ use crate::points::Points;
12
+ use crate::rng::Rng;
13
+
14
+ #[derive(Clone, Debug)]
15
+ pub struct RankMetrics {
16
+ pub n: usize,
17
+ /// rows the estimates are based on (n when exact)
18
+ pub n_anchors: usize,
19
+ /// index K -> R_NX(K), K = 1..n-2 (index 0 unused)
20
+ pub r_nx: Vec<f64>,
21
+ pub auc_r_nx: f64,
22
+ /// (K, trustworthiness, continuity)
23
+ pub trust_cont: Vec<(usize, f64, f64)>,
24
+ /// mean |rank_h - rank_l| / (n-1)^2 over pairs; about 1/3 for a random layout
25
+ pub footrule: f64,
26
+ }
27
+
28
+ /// Ranks of all points as seen from row i (self 0, others 1..n-1).
29
+ fn row_ranks(dist: &mut Vec<(f64, u32)>, i: usize, ranks: &mut [u32], d_of: impl Fn(usize) -> f64) {
30
+ let n = ranks.len();
31
+ dist.clear();
32
+ dist.extend((0..n).map(|j| (if j == i { f64::NEG_INFINITY } else { d_of(j) }, j as u32)));
33
+ dist.sort_unstable_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));
34
+ for (r, &(_, j)) in dist.iter().enumerate() {
35
+ ranks[j as usize] = r as u32;
36
+ }
37
+ }
38
+
39
+ pub fn rank_metrics(x: &Points, y: &[f64], dy: usize, anchors: Option<&[u32]>, ks: &[usize]) -> RankMetrics {
40
+ let n = x.n;
41
+ assert_eq!(y.len(), n * dy);
42
+ assert!(n >= 4);
43
+ let all: Vec<u32>;
44
+ let anchors = match anchors {
45
+ Some(a) => a,
46
+ None => {
47
+ all = (0..n as u32).collect();
48
+ &all
49
+ }
50
+ };
51
+ let s = anchors.len();
52
+ let ks: Vec<usize> = ks.iter().copied().filter(|&k| k >= 1 && 2 * k < n).collect();
53
+ let ranges = par::ranges(s);
54
+ // per part: histogram of max(rank_h, rank_l), trust/cont penalties, sum |rank_h - rank_l|
55
+ let parts = par::map_collect(ranges.len(), |c| {
56
+ let mut hist = vec![0u64; n];
57
+ let mut trust = vec![0f64; ks.len()];
58
+ let mut cont = vec![0f64; ks.len()];
59
+ let mut abs_diff = 0f64;
60
+ let (mut rh, mut rl) = (vec![0u32; n], vec![0u32; n]);
61
+ let mut buf = Vec::with_capacity(n);
62
+ for a in ranges[c].clone() {
63
+ let i = anchors[a] as usize;
64
+ let xi = x.row(i);
65
+ row_ranks(&mut buf, i, &mut rh, |j| crate::points::sqdist(xi, x.row(j)) as f64);
66
+ let yi = &y[i * dy..(i + 1) * dy];
67
+ row_ranks(&mut buf, i, &mut rl, |j| (0..dy).map(|t| (yi[t] - y[j * dy + t]).powi(2)).sum());
68
+ for j in 0..n {
69
+ let (h, l) = (rh[j], rl[j]);
70
+ hist[h.max(l) as usize] += 1;
71
+ abs_diff += (h as f64 - l as f64).abs();
72
+ if j == i {
73
+ continue;
74
+ }
75
+ for (t, &k) in ks.iter().enumerate() {
76
+ let (in_h, in_l) = (h as usize <= k, l as usize <= k);
77
+ if in_l && !in_h {
78
+ trust[t] += (h as usize - k) as f64; // intrusion
79
+ } else if in_h && !in_l {
80
+ cont[t] += (l as usize - k) as f64; // extrusion
81
+ }
82
+ }
83
+ }
84
+ }
85
+ (hist, trust, cont, abs_diff)
86
+ });
87
+ let mut hist = vec![0u64; n];
88
+ let mut trust = vec![0f64; ks.len()];
89
+ let mut cont = vec![0f64; ks.len()];
90
+ let mut abs_diff = 0f64;
91
+ for (h, t, c, a) in parts {
92
+ hist.iter_mut().zip(h).for_each(|(x, y)| *x += y);
93
+ trust.iter_mut().zip(t).for_each(|(x, y)| *x += y);
94
+ cont.iter_mut().zip(c).for_each(|(x, y)| *x += y);
95
+ abs_diff += a;
96
+ }
97
+ // Q_NX(K) = #{(i, j): max rank <= K} / (K s); the self pair has max rank 0
98
+ let mut r_nx = vec![0f64; n - 1];
99
+ let mut cum = 0u64;
100
+ let (mut num, mut den) = (0f64, 0f64);
101
+ for k in 1..n - 1 {
102
+ cum += hist[k];
103
+ let q = cum as f64 / (k * s) as f64;
104
+ r_nx[k] = ((n - 1) as f64 * q - k as f64) / (n - 1 - k) as f64;
105
+ num += r_nx[k] / k as f64;
106
+ den += 1.0 / k as f64;
107
+ }
108
+ let norm = |k: usize| 2.0 / (s as f64 * k as f64 * (2 * n - 3 * k - 1) as f64);
109
+ RankMetrics {
110
+ n,
111
+ n_anchors: s,
112
+ r_nx,
113
+ auc_r_nx: num / den,
114
+ trust_cont: ks.iter().enumerate().map(|(t, &k)| (k, 1.0 - norm(k) * trust[t], 1.0 - norm(k) * cont[t])).collect(),
115
+ footrule: abs_diff / (s as f64 * ((n - 1) as f64).powi(2)),
116
+ }
117
+ }
118
+
119
+ /// `s` distinct random rows, sorted.
120
+ pub fn sample_anchors(n: usize, s: usize, seed: u64) -> Vec<u32> {
121
+ let mut a = Rng::new(seed).sample(n, s.min(n));
122
+ a.sort_unstable();
123
+ a
124
+ }
125
+
126
+ /// Per point, the share of its k nearest neighbours in X that are also among
127
+ /// its k nearest in Y (both lists must hold at least k neighbours).
128
+ pub fn knn_overlap(knn_x: &Knn, knn_y: &Knn, k: usize) -> Vec<f64> {
129
+ assert!(k <= knn_x.k && k <= knn_y.k);
130
+ let n = knn_x.ids.len() / knn_x.k;
131
+ (0..n)
132
+ .map(|i| {
133
+ let mut a = knn_x.ids(i)[..k].to_vec();
134
+ a.sort_unstable();
135
+ knn_y.ids(i)[..k].iter().filter(|j| a.binary_search(j).is_ok()).count() as f64 / k as f64
136
+ })
137
+ .collect()
138
+ }
139
+
140
+ /// Spearman correlation of pairwise distances (all pairs, or `max_pairs` random ones).
141
+ pub fn distance_spearman(x: &Points, y: &[f64], dy: usize, max_pairs: usize, seed: u64) -> f64 {
142
+ let n = x.n;
143
+ let mut pairs = Vec::new();
144
+ if n * (n - 1) / 2 <= max_pairs {
145
+ for i in 0..n {
146
+ for j in i + 1..n {
147
+ pairs.push((i, j));
148
+ }
149
+ }
150
+ } else {
151
+ let mut rng = Rng::new(seed);
152
+ while pairs.len() < max_pairs {
153
+ let (i, j) = (rng.below(n), rng.below(n));
154
+ if i != j {
155
+ pairs.push((i, j));
156
+ }
157
+ }
158
+ }
159
+ let dh: Vec<f64> = pairs.iter().map(|&(i, j)| crate::points::dist(x.row(i), x.row(j)) as f64).collect();
160
+ let dl: Vec<f64> = pairs
161
+ .iter()
162
+ .map(|&(i, j)| (0..dy).map(|t| (y[i * dy + t] - y[j * dy + t]).powi(2)).sum::<f64>().sqrt())
163
+ .collect();
164
+ spearman(&dh, &dl)
165
+ }
166
+
167
+ /// Spearman correlation of log mean distances to the k nearest neighbours
168
+ /// (a local density proxy, as used to evaluate densMAP).
169
+ pub fn density_correlation(knn_x: &Knn, knn_y: &Knn, k: usize) -> f64 {
170
+ let n = knn_x.ids.len() / knn_x.k;
171
+ let radius = |knn: &Knn, i: usize| {
172
+ (knn.dist(i)[..k].iter().map(|&d| d as f64).sum::<f64>() / k as f64 + 1e-12).ln()
173
+ };
174
+ let rx: Vec<f64> = (0..n).map(|i| radius(knn_x, i)).collect();
175
+ let ry: Vec<f64> = (0..n).map(|i| radius(knn_y, i)).collect();
176
+ spearman(&rx, &ry)
177
+ }
178
+
179
+ /// Leave-one-out k-NN classification accuracy (majority vote, ties to the
180
+ /// nearest neighbour's label) from a kNN list.
181
+ pub fn knn_accuracy(knn: &Knn, labels: &[u32], k: usize) -> f64 {
182
+ let n = labels.len();
183
+ let n_lab = labels.iter().max().map_or(0, |&m| m as usize + 1);
184
+ let mut votes = vec![0usize; n_lab];
185
+ let mut hit = 0;
186
+ for i in 0..n {
187
+ votes.iter_mut().for_each(|v| *v = 0);
188
+ let ids = &knn.ids(i)[..k];
189
+ for &j in ids {
190
+ votes[labels[j as usize] as usize] += 1;
191
+ }
192
+ let best = *votes.iter().max().unwrap();
193
+ // among tied labels, the one of the nearest neighbour wins
194
+ let pred = ids.iter().map(|&j| labels[j as usize]).find(|&l| votes[l as usize] == best).unwrap();
195
+ hit += (pred == labels[i]) as usize;
196
+ }
197
+ hit as f64 / n as f64
198
+ }
199
+
200
+ /// Average ranks (ties share their mean rank), 1-based.
201
+ fn ranks(v: &[f64]) -> Vec<f64> {
202
+ let mut o: Vec<usize> = (0..v.len()).collect();
203
+ o.sort_unstable_by(|&a, &b| v[a].total_cmp(&v[b]));
204
+ let mut r = vec![0f64; v.len()];
205
+ let mut s = 0;
206
+ while s < o.len() {
207
+ let mut e = s + 1;
208
+ while e < o.len() && v[o[e]] == v[o[s]] {
209
+ e += 1;
210
+ }
211
+ let mean = (s + e + 1) as f64 / 2.0;
212
+ o[s..e].iter().for_each(|&t| r[t] = mean);
213
+ s = e;
214
+ }
215
+ r
216
+ }
217
+
218
+ pub fn spearman(a: &[f64], b: &[f64]) -> f64 {
219
+ let (ra, rb) = (ranks(a), ranks(b));
220
+ let n = a.len() as f64;
221
+ let (ma, mb) = (ra.iter().sum::<f64>() / n, rb.iter().sum::<f64>() / n);
222
+ let (mut sab, mut saa, mut sbb) = (0.0, 0.0, 0.0);
223
+ for (x, y) in ra.iter().zip(&rb) {
224
+ sab += (x - ma) * (y - mb);
225
+ saa += (x - ma).powi(2);
226
+ sbb += (y - mb).powi(2);
227
+ }
228
+ sab / (saa * sbb).sqrt()
229
+ }
230
+
231
+ #[cfg(test)]
232
+ mod tests {
233
+ use super::*;
234
+
235
+ #[test]
236
+ fn identity_embedding_is_perfect_and_anchors_agree() {
237
+ let mut r = Rng::new(9);
238
+ let n = 400;
239
+ let x: Vec<f32> = (0..n * 2).map(|_| r.normal() as f32).collect();
240
+ let y: Vec<f64> = x.iter().map(|&v| 3.0 * v as f64).collect();
241
+ let p = Points::new(&x, n, 2);
242
+ let m = rank_metrics(&p, &y, 2, None, &[5, 10]);
243
+ assert!(m.r_nx[1..].iter().all(|&v| (v - 1.0).abs() < 1e-12));
244
+ assert!(m.trust_cont.iter().all(|&(_, t, c)| t == 1.0 && c == 1.0));
245
+ assert_eq!(m.footrule, 0.0);
246
+ assert!((distance_spearman(&p, &y, 2, 1_000_000, 0) - 1.0).abs() < 1e-6);
247
+ // a noisy embedding: anchors estimate the full metrics
248
+ let y: Vec<f64> = x.iter().map(|&v| v as f64 + 0.5 * r.normal()).collect();
249
+ let full = rank_metrics(&p, &y, 2, None, &[10]);
250
+ let est = rank_metrics(&p, &y, 2, Some(&sample_anchors(n, 200, 1)), &[10]);
251
+ assert!((full.r_nx[10] - est.r_nx[10]).abs() < 0.05);
252
+ assert!((full.auc_r_nx - est.auc_r_nx).abs() < 0.03);
253
+ }
254
+
255
+ #[test]
256
+ fn spearman_handles_ties() {
257
+ assert!((spearman(&[1.0, 2.0, 2.0, 3.0], &[1.0, 2.0, 2.0, 3.0]) - 1.0).abs() < 1e-12);
258
+ assert!((spearman(&[1.0, 2.0, 3.0], &[3.0, 2.0, 1.0]) + 1.0).abs() < 1e-12);
259
+ }
260
+ }