arrowspace 0.26.2

Graph Wiring for embeddings using physical networks wiring. Provides graph analysis, vector search and a energy-distribution stats.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Integration tests verifying that the EigenMaps trait stages produce identical
//! results to the original ArrowSpaceBuilder::build monolithic path.
//!
//! # Test Strategy
//!
//! Each test constructs an ArrowSpace and GraphLaplacian using both:
//! 1. The original `builder.build(rows)` path (control)
//! 2. The new EigenMaps trait stages: start_clustering → eigenmaps → compute_taumode → search
//!
//! We then verify equivalence on:
//! - Clustering metadata (n_clusters, cluster_assignments, cluster_sizes)
//! - Laplacian properties (shape, nnz, sparsity, node count)
//! - Lambda values (element-wise relative equality within tolerance)
//! - Search results (same top-k indices and scores within tolerance)
//!
//! # Determinism
//!
//! Tests use `with_seed(...)` to ensure reproducible clustering and stable results
//! across both paths. Without seeding, clustering is nondeterministic due to parallel
//! processing in incremental clustering.

use crate::builder::ArrowSpaceBuilder;
use crate::clustering::{ClusteredOutput, ClusteringHeuristic};
use crate::core::ArrowSpace;
use crate::graph::GraphLaplacian;
use crate::maps::eigenmaps::EigenMaps;
use crate::search::taumode::TauMode;
use crate::tests::GAUSSIAN_DATA;
use crate::tests::init;

use approx::{relative_eq, relative_ne};
use log::{debug, info};

/// Helper: Compare two ArrowSpace lambda vectors element-wise with tolerance.
fn assert_lambdas_equal(a: &[f64], b: &[f64], tol: f64, label: &str, spectral: bool) {
    init();
    assert_eq!(a.len(), b.len(), "{}: lambda vector length mismatch", label);
    for (i, (&la, &lb)) in a.iter().zip(b.iter()).enumerate() {
        if !spectral {
            assert!(
                la >= 0.0 && lb >= 0.0,
                "lambda_a is {} and lambda_b {}",
                la,
                lb
            );
        }
        if relative_ne!(la, lb, epsilon = tol, max_relative = tol) {
            debug!("lambdas are not equal: {} {}", la, lb);
            panic!("{}[{}]: lambda mismatch", label, i)
        } else {
        };
    }
}

/// Helper: Compare clustering metadata between two ArrowSpace instances.
fn assert_clustering_equal(a: &ArrowSpace, b: &ArrowSpace, label: &str) {
    init();
    assert_eq!(a.n_clusters, b.n_clusters, "{}: n_clusters mismatch", label);
    assert_eq!(
        a.cluster_assignments, b.cluster_assignments,
        "{}: cluster_assignments mismatch",
        label
    );
    assert_eq!(
        a.cluster_sizes, b.cluster_sizes,
        "{}: cluster_sizes mismatch",
        label
    );
    if relative_ne!(a.cluster_radius, b.cluster_radius, epsilon = 1e-9) {
        panic!("{}: cluster_radius mismatch", label)
    } else {
    };
}

/// Helper: Compare GraphLaplacian properties (shape, nnodes, nnz, sparsity).
fn assert_laplacian_equal(a: &GraphLaplacian, b: &GraphLaplacian, label: &str) {
    init();
    assert_eq!(a.shape(), b.shape(), "{}: Laplacian shape mismatch", label);
    assert_eq!(a.nnodes, b.nnodes, "{}: nnodes mismatch", label);
    assert_eq!(a.nnz(), b.nnz(), "{}: nnz mismatch", label);
    if relative_ne!(
        GraphLaplacian::sparsity(&a.matrix),
        GraphLaplacian::sparsity(&b.matrix),
        epsilon = 1e-9
    ) {
        panic!("{}: sparsity mismatch", label)
    } else {
    };
}

/// Helper: Compare search results (indices and scores within tolerance).
fn assert_search_results_equal(a: &[(usize, f64)], b: &[(usize, f64)], tol: f64, label: &str) {
    assert_eq!(a.len(), b.len(), "{}: result count mismatch", label);
    for (i, ((idx_a, score_a), (idx_b, score_b))) in a.iter().zip(b.iter()).enumerate() {
        assert_eq!(idx_a, idx_b, "{}[{}]: index mismatch", label, i);
        if relative_ne!(score_a, score_b, epsilon = tol) {
            panic!("{}[{}]: score mismatch", label, i)
        } else {
        };
    }
}

#[test]
#[should_panic]
fn test_eigenmaps_non_sensical_undecidable_query() {
    crate::init(); // Initialize logger
    info!("Test: EigenMaps trait vs build() - basic dataset");

    let rows = &*GAUSSIAN_DATA;
    // this vector is not in the context of the dataset
    // it is not being generated consistently like the others
    let query = vec![0.5; 100];

    let mut builder = ArrowSpaceBuilder::new()
        .with_lambda_graph(1.0, 3, 3, 2.0, None)
        .with_synthesis(TauMode::Median)
        .with_seed(12345) // Same seed
        .with_inline_sampling(None)
        .with_dims_reduction(false, None);

    let ClusteredOutput {
        mut aspace,
        centroids,
        n_items,
        ..
    } = ArrowSpaceBuilder::start_clustering(&mut builder, rows.clone());

    let gl = aspace.eigenmaps(&builder, &centroids, n_items);
    aspace.compute_taumode(&gl);

    let _ = aspace.prepare_query_item(&query, &gl);
}

#[test]
fn test_eigenmaps_vs_build_basic() {
    crate::init(); // Initialize logger
    info!("Test: EigenMaps trait vs build() - basic dataset");

    let rows = &*GAUSSIAN_DATA;
    let query_idx = 10;
    let query = &rows[query_idx];
    let k = 5;
    let tau = 0.7;

    // Control: original build path
    let builder_control = ArrowSpaceBuilder::new()
        .with_lambda_graph(1.0, 3, 3, 2.0, None)
        .with_synthesis(TauMode::Median)
        .with_seed(12345) // Deterministic clustering
        .with_inline_sampling(None) // Disable sampling for exact equivalence
        .with_dims_reduction(false, None);

    let (aspace_control, gl_control) = builder_control.build(rows.clone());

    // Experimental: EigenMaps trait stages
    let mut builder_exp = ArrowSpaceBuilder::new()
        .with_lambda_graph(1.0, 3, 3, 2.0, None)
        .with_synthesis(TauMode::Median)
        .with_seed(12345) // Same seed
        .with_inline_sampling(None)
        .with_dims_reduction(false, None);

    let ClusteredOutput {
        mut aspace,
        centroids,
        n_items,
        ..
    } = ArrowSpaceBuilder::start_clustering(&mut builder_exp, rows.clone());

    let gl_exp = aspace.eigenmaps(&builder_exp, &centroids, n_items);
    aspace.compute_taumode(&gl_exp);

    // Verify clustering metadata
    assert_clustering_equal(&aspace_control, &aspace, "basic");

    // Verify Laplacian properties
    assert_laplacian_equal(&gl_control, &gl_exp, "basic");

    // Verify lambda values
    assert_lambdas_equal(
        aspace_control.lambdas(),
        aspace.lambdas(),
        1e-6,
        "basic lambdas",
        false,
    );

    // Verify search results
    let query_lambda = aspace_control.prepare_query_item(&query, &gl_control);
    let results_control = aspace_control.search_lambda_aware(
        &crate::core::ArrowItem::new(query, query_lambda),
        k,
        tau,
    );

    let results_exp = aspace.search(&query, &gl_exp, k, tau);

    assert_search_results_equal(&results_control, &results_exp, 1e-6, "basic search");

    info!("✓ EigenMaps trait matches build() for basic dataset");
}

#[test]
fn test_eigenmaps_vs_build_with_spectral() {
    crate::init();
    info!("Test: EigenMaps trait vs build() - with spectral Laplacian");

    let rows = &*GAUSSIAN_DATA;
    let query = &rows[10];
    let k = 4;
    let tau = 0.6;

    // Control: build with spectral enabled
    let builder_control = ArrowSpaceBuilder::new()
        .with_lambda_graph(1.0, 3, 3, 2.0, None)
        .with_synthesis(TauMode::Median)
        .with_spectral(true) // Enable F×F feature Laplacian
        .with_seed(5555)
        .with_dims_reduction(false, None)
        .with_inline_sampling(None);

    let (aspace_control, gl_control) = builder_control.build(rows.clone());

    // Experimental: EigenMaps with spectral stage
    let mut builder_exp = ArrowSpaceBuilder::new()
        .with_lambda_graph(1.0, 3, 3, 2.0, None)
        .with_synthesis(TauMode::Median)
        .with_spectral(true)
        .with_seed(5555)
        .with_dims_reduction(false, None)
        .with_inline_sampling(None);

    let ClusteredOutput {
        mut aspace,
        centroids,
        n_items,
        ..
    } = ArrowSpaceBuilder::start_clustering(&mut builder_exp, rows.clone());

    let gl_exp = aspace.eigenmaps(&builder_exp, &centroids, n_items);
    aspace.compute_taumode(&gl_exp);

    // Verify spectral matrix (signals field)
    assert_eq!(
        aspace_control.signals.shape(),
        aspace.signals.shape(),
        "signals shape mismatch"
    );
    assert_eq!(
        aspace_control.signals.nnz(),
        aspace.signals.nnz(),
        "signals nnz mismatch"
    );

    // Verify other properties
    assert_clustering_equal(&aspace_control, &aspace, "spectral");
    assert_laplacian_equal(&gl_control, &gl_exp, "spectral");
    assert_lambdas_equal(
        aspace_control.lambdas(),
        aspace.lambdas(),
        1e-6,
        "spectral lambdas",
        true,
    );

    // Search
    let results_control = aspace_control.search_lambda_aware(
        &crate::core::ArrowItem::new(
            query,
            aspace_control.prepare_query_item(&query, &gl_control),
        ),
        k,
        tau,
    );

    let results_exp = aspace.search(&query, &gl_exp, k, tau);

    assert_search_results_equal(&results_control, &results_exp, 1e-6, "spectral search");

    info!("✓ EigenMaps trait matches build() with spectral Laplacian");
}

#[test]
fn test_eigenmaps_vs_build_different_taumode() {
    crate::init();
    info!("Test: EigenMaps trait vs build() - Mean taumode");

    let rows = &*GAUSSIAN_DATA;
    let query_idx = 10;
    let query = &rows[query_idx];
    let k = 6;
    let tau = 0.75;

    // Control: build with Mean taumode
    let builder_control = ArrowSpaceBuilder::new()
        .with_lambda_graph(1.0, 3, 3, 2.0, None)
        .with_synthesis(TauMode::Mean) // Different tau policy
        .with_seed(7777)
        .with_inline_sampling(None);

    let (aspace_control, gl_control) = builder_control.build(rows.clone());

    // Experimental: EigenMaps with Mean taumode
    let mut builder_exp = ArrowSpaceBuilder::new()
        .with_lambda_graph(1.0, 3, 3, 2.0, None)
        .with_synthesis(TauMode::Mean)
        .with_seed(7777)
        .with_inline_sampling(None);

    let ClusteredOutput {
        mut aspace,
        centroids,
        n_items,
        ..
    } = ArrowSpaceBuilder::start_clustering(&mut builder_exp, rows.clone());

    let gl_exp = aspace.eigenmaps(&builder_exp, &centroids, n_items);
    aspace.compute_taumode(&gl_exp);

    // Verify
    assert_clustering_equal(&aspace_control, &aspace, "mean_taumode");
    assert_laplacian_equal(&gl_control, &gl_exp, "mean_taumode");
    assert_lambdas_equal(
        aspace_control.lambdas(),
        aspace.lambdas(),
        1e-6,
        "mean_taumode lambdas",
        false,
    );

    // Search
    let results_control = aspace_control.search_lambda_aware(
        &crate::core::ArrowItem::new(
            query,
            aspace_control.prepare_query_item(&query, &gl_control),
        ),
        k,
        tau,
    );

    let results_exp = aspace.search(&query, &gl_exp, k, tau);

    assert_search_results_equal(&results_control, &results_exp, 1e-10, "mean_taumode search");

    info!("✓ EigenMaps trait matches build() with Mean taumode");
}

#[test]
#[should_panic]
fn test_search_without_taumode_panics() {
    crate::init();
    info!("Test: Search without compute_taumode should panic in debug");

    let rows = &*GAUSSIAN_DATA;
    let query = vec![0.0; 6];

    let mut builder = ArrowSpaceBuilder::new()
        .with_lambda_graph(1.0, 3, 3, 2.0, None)
        .with_seed(111)
        .with_inline_sampling(None);

    let ClusteredOutput {
        mut aspace,
        centroids,
        n_items,
        ..
    } = ArrowSpaceBuilder::start_clustering(&mut builder, rows.clone());

    let gl = aspace.eigenmaps(&builder, &centroids, n_items);

    // Skip compute_taumode - should panic in debug
    let _ = aspace.search(&query, &gl, 3, 0.7);
}

#[test]
#[ignore = "run for too long"]
fn test_eigenmaps_stages_produce_valid_state() {
    crate::init();
    info!("Test: EigenMaps stages produce valid intermediate state");

    let rows = &*GAUSSIAN_DATA;

    let mut builder = ArrowSpaceBuilder::new()
        .with_lambda_graph(1.0, 3, 3, 2.0, None)
        .with_seed(222)
        .with_inline_sampling(None);

    // Stage 1: Clustering
    let ClusteredOutput {
        mut aspace,
        centroids,
        n_items,
        n_features,
        reduced_dim,
    } = ArrowSpaceBuilder::start_clustering(&mut builder, rows.clone());

    assert_eq!(n_items, 99, "n_items should match input");
    assert_eq!(n_features, 100, "n_features should match input");
    assert!(aspace.n_clusters > 0, "Should have clustered");
    assert_eq!(reduced_dim, n_features, "No projection, dims unchanged");

    // Stage 2: Eigenmaps
    let gl = aspace.eigenmaps(&builder, &centroids, n_items);

    assert_eq!(gl.nnodes, n_items, "Laplacian nodes should match items");
    assert!(gl.nnz() > 0, "Laplacian should have edges");
    assert!(
        GraphLaplacian::sparsity(&gl.matrix) < 1.0,
        "Should not be fully sparse"
    );

    // Stage 3: Taumode (check lambdas are computed)
    let mut aspace = aspace; // Make mutable
    assert!(
        aspace.lambdas().iter().all(|&l| l == 0.0),
        "Lambdas should be zero before compute_taumode"
    );

    aspace.compute_taumode(&gl);

    assert!(
        aspace.lambdas().iter().any(|&l| l > 0.0),
        "Lambdas should be nonzero after compute_taumode"
    );

    info!("✓ All stages produce valid intermediate state");
}

#[test]
fn test_eigenmaps_with_dim_reduction() {
    crate::init(); // Initialize logger

    let rows = &*GAUSSIAN_DATA;
    let query_idx = 10;
    let query = &rows[query_idx];
    let k = 5;

    // Control: original build path
    let builder_control = ArrowSpaceBuilder::new()
        .with_lambda_graph(0.5, 3, 3, 2.0, None)
        .with_synthesis(TauMode::Median)
        .with_seed(12345) // Deterministic clustering
        .with_inline_sampling(None) // Disable sampling for exact equivalence
        .with_dims_reduction(true, Some(0.1));

    let (aspace, gl) = builder_control.build(rows.clone());

    assert_eq!(
        aspace.lambdas()[query_idx],
        aspace.prepare_query_item(query, &gl),
        "original query lambda and prepared query lambda should be equal"
    );

    let results = aspace.search(query, &gl, k, 0.62);

    assert!(
        results
            .iter()
            .any(|(i, r)| *i == query_idx && relative_eq!(*r, 1.0, epsilon = 1e-10))
    );
}