holomap 0.1.0

Deterministic UMAP — the bulk, on the boundary. Same input, same params, same seed: bit-identical embeddings.
Documentation
//! M1 exit gate: full Stage-1/2 parity against umap-learn 0.5.12 fixtures.
//!
//! Fixtures live in `tests/fixtures/stage2_*.json`, generated by
//! `dev/export_stage2_fixtures.py` from the pinned reference. Each is the
//! oracle for the whole M1 pipeline: exact kNN (indices exact, distances to
//! float tolerance), rho/sigma calibration, and the symmetrized fuzzy graph
//! (support exact, weights to float tolerance).

use crate::fuzzy::fuzzy_simplicial_set;
use crate::knn::exact_knn;
use crate::metric::Metric;
use crate::smooth_knn::smooth_knn;
use serde_json::Value;

/// Combined relative/absolute float tolerance. The Rust pipeline mirrors the
/// reference's float32 arithmetic but not bit-for-bit (e.g. mean reductions,
/// libm exp) — parity within 1e-5 scaled is the M1 bar.
fn assert_close(actual: f32, expected: f64, what: &str) {
    let tol = 1e-5 * (1.0 + expected.abs());
    assert!(
        (f64::from(actual) - expected).abs() <= tol,
        "{what}: actual {actual} vs expected {expected}"
    );
}

fn floats(v: &Value) -> Vec<f64> {
    v.as_array()
        .unwrap()
        .iter()
        .map(|x| x.as_f64().unwrap())
        .collect()
}

fn ints(v: &Value) -> Vec<u32> {
    v.as_array()
        .unwrap()
        .iter()
        .map(|x| x.as_u64().unwrap() as u32)
        .collect()
}

fn run_fixture(name: &str) {
    let path = format!(
        "{}/tests/fixtures/stage2_{name}.json",
        env!("CARGO_MANIFEST_DIR")
    );
    let fixture: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();

    let n = fixture["n_samples"].as_u64().unwrap() as usize;
    let d = fixture["n_features"].as_u64().unwrap() as usize;
    let k = fixture["n_neighbors"].as_u64().unwrap() as usize;
    let metric = match fixture["metric"].as_str().unwrap() {
        "euclidean" => Metric::Euclidean,
        "cosine" => Metric::Cosine,
        other => panic!("unknown metric {other}"),
    };
    let data: Vec<f32> = fixture["data"]
        .as_array()
        .unwrap()
        .iter()
        .flat_map(|row| row.as_array().unwrap().iter())
        .map(|x| x.as_f64().unwrap() as f32)
        .collect();
    assert_eq!(data.len(), n * d);

    // Stage 1 — kNN: neighbour identity exact, distances to tolerance
    let knn = exact_knn(&data, d, k, metric);
    let expected_indices: Vec<u32> = fixture["knn_indices"]
        .as_array()
        .unwrap()
        .iter()
        .flat_map(|row| row.as_array().unwrap().iter())
        .map(|x| x.as_u64().unwrap() as u32)
        .collect();
    assert_eq!(knn.indices, expected_indices, "{name}: knn indices");
    let expected_dists: Vec<f64> = fixture["knn_dists"]
        .as_array()
        .unwrap()
        .iter()
        .flat_map(|row| row.as_array().unwrap().iter())
        .map(|x| x.as_f64().unwrap())
        .collect();
    for (i, (&a, &e)) in knn.dists.iter().zip(&expected_dists).enumerate() {
        assert_close(a, e, &format!("{name}: knn dist [{i}]"));
    }

    // Stage 2a — rho/sigma calibration
    let calib = smooth_knn(&knn.dists, k);
    for (i, (&a, &e)) in calib.rhos.iter().zip(&floats(&fixture["rhos"])).enumerate() {
        assert_close(a, e, &format!("{name}: rho [{i}]"));
    }
    for (i, (&a, &e)) in calib
        .sigmas
        .iter()
        .zip(&floats(&fixture["sigmas"]))
        .enumerate()
    {
        assert_close(a, e, &format!("{name}: sigma [{i}]"));
    }

    // Stage 2b — symmetrized fuzzy graph: support exact, weights to tolerance
    let graph = fuzzy_simplicial_set(&knn, &calib);
    assert_eq!(
        graph.rows,
        ints(&fixture["graph_rows"]),
        "{name}: graph rows"
    );
    assert_eq!(
        graph.cols,
        ints(&fixture["graph_cols"]),
        "{name}: graph cols"
    );
    let expected_vals = floats(&fixture["graph_vals"]);
    assert_eq!(graph.vals.len(), expected_vals.len());
    for (i, (&a, &e)) in graph.vals.iter().zip(&expected_vals).enumerate() {
        assert_close(a, e, &format!("{name}: graph val [{i}]"));
    }
}

/// M2 exit gate: eigenpairs of the normalized Laplacian vs scipy eigsh
/// (tol=1e-12 oracle) on a connected single-component fuzzy graph built by
/// the full Stage-1/2 pipeline. Both eigen paths must match: the dense
/// SymmetricEigen route AND the Lanczos route (forced explicitly — at n=60
/// the dispatcher would pick dense).
#[test]
fn spectral_parity_vs_scipy() {
    let path = format!(
        "{}/tests/fixtures/spectral_cloud_connected.json",
        env!("CARGO_MANIFEST_DIR")
    );
    let fixture: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();

    let n = fixture["n_samples"].as_u64().unwrap() as usize;
    let d = fixture["n_features"].as_u64().unwrap() as usize;
    let k = fixture["n_neighbors"].as_u64().unwrap() as usize;
    let dim = fixture["dim"].as_u64().unwrap() as usize;
    let data: Vec<f32> = fixture["data"]
        .as_array()
        .unwrap()
        .iter()
        .flat_map(|row| row.as_array().unwrap().iter())
        .map(|x| x.as_f64().unwrap() as f32)
        .collect();

    let knn = exact_knn(&data, d, k, Metric::Euclidean);
    let calib = smooth_knn(&knn.dists, k);
    let graph = fuzzy_simplicial_set(&knn, &calib);
    let lap = crate::sparse::Laplacian::new(&graph);

    let expected_values = floats(&fixture["eigenvalues"]);
    let expected_vectors: Vec<Vec<f64>> = fixture["eigenvectors"]
        .as_array()
        .unwrap()
        .iter()
        .map(floats)
        .collect();

    for (label, pairs) in [
        ("dense", crate::eigen::smallest_eigenpairs(&lap, dim + 1)),
        (
            "lanczos",
            crate::eigen::lanczos_eigenpairs_for_test(&lap, dim + 1),
        ),
    ] {
        for (j, (&a, &e)) in pairs.values.iter().zip(&expected_values).enumerate() {
            assert!(
                (a - e).abs() < 1e-6,
                "{label} eigenvalue [{j}]: {a} vs scipy {e}"
            );
        }
        for (j, expected) in expected_vectors.iter().enumerate().take(dim + 1) {
            let ours = &pairs.vectors[j * n..(j + 1) * n];
            let dot: f64 = ours.iter().zip(expected).map(|(x, y)| x * y).sum();
            assert!(
                dot.abs() > 1.0 - 1e-6,
                "{label} eigenvector [{j}] misaligned: |cos| = {}",
                dot.abs()
            );
        }
    }
}

/// Determinism leg of the M2 gate: the full pipeline through spectral init
/// is bit-identical across runs with the same seed, and differs with
/// another seed (the 1e-4 noise must actually be seeded).
#[test]
fn spectral_init_double_run_bit_identity() {
    let path = format!(
        "{}/tests/fixtures/spectral_cloud_connected.json",
        env!("CARGO_MANIFEST_DIR")
    );
    let fixture: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
    let d = fixture["n_features"].as_u64().unwrap() as usize;
    let k = fixture["n_neighbors"].as_u64().unwrap() as usize;
    let data: Vec<f32> = fixture["data"]
        .as_array()
        .unwrap()
        .iter()
        .flat_map(|row| row.as_array().unwrap().iter())
        .map(|x| x.as_f64().unwrap() as f32)
        .collect();

    let run = |seed: u64| -> Vec<f32> {
        let knn = exact_knn(&data, d, k, Metric::Euclidean);
        let calib = smooth_knn(&knn.dists, k);
        let graph = fuzzy_simplicial_set(&knn, &calib);
        let mut rng = crate::rng::SeededRng::new(seed);
        crate::spectral::initial_embedding(
            &data,
            d,
            &graph,
            2,
            crate::spectral::Init::Spectral,
            &mut rng,
        )
    };
    let a = run(42);
    let b = run(42);
    assert_eq!(a, b, "same seed must be bit-identical");
    let c = run(43);
    assert_ne!(a, c, "different seed must differ (noise is seeded)");
}

#[test]
fn stage2_parity_blobs_euclidean() {
    run_fixture("blobs_euclidean");
}

#[test]
fn stage2_parity_cosine() {
    run_fixture("cosine");
}

#[test]
fn stage2_parity_duplicates_euclidean() {
    run_fixture("duplicates_euclidean");
}