Cotton code
486 lines · 17.2 KB · RustRaw
//! Every number below came out of the TypeScript. That matters more here than//! anywhere else in this directory: the answers are single-precision centroids//! read back as doubles, and a port that accumulated in `f64` and rounded once//! at the end would agree to five decimals and disagree in the sixth — which//! is the decimal [`SUGGEST_MARGIN`] is measured in.use super::*;/// A unit vector along one axis, nudged by `noise` on a second axis — the/// TypeScript test's own helper, with its defaults spelled out.fn toward(axis: usize, noise: f64) -> Vec<f64> {    let mut v = vec![0.0f64; 8];    v[axis] = 1.0;    v[7] = noise;    v}fn face(face_id: &str, person_id: Option<&str>, embedding: Vec<f64>) -> FaceForPeople {    FaceForPeople {        face_id: face_id.to_string(),        person_id: person_id.map(str::to_string),        suggested_person_id: None,        dismissed: false,        embedding,    }}/// Three of Ravi's faces along axis 0, three of Meera's along axis 1.fn seeds() -> Vec<FaceForPeople> {    vec![        face("r1", Some("ravi"), toward(0, 0.05)),        face("r2", Some("ravi"), toward(0, -0.05)),        face("r3", Some("ravi"), toward(0, 0.02)),        face("m1", Some("meera"), toward(1, 0.05)),        face("m2", Some("meera"), toward(1, -0.05)),        face("m3", Some("meera"), toward(1, 0.01)),    ]}fn suggest(faces: &[FaceForPeople]) -> Vec<PersonSuggestion> {    suggest_people(faces, &SuggestPeopleOptions::default()).expect("vectors agree in length")}fn seeds_of(faces: &[FaceForPeople], min: usize) -> Vec<String> {    seed_centroids(faces, min)        .expect("vectors agree in length")        .into_iter()        .map(|seed| seed.person_id)        .collect()}// ── vectors ──────────────────────────────────────────────────────────────────#[test]fn normalises_and_leaves_a_zero_vector_zero() {    assert_eq!(        widen(&normalise(&[3.0, 4.0])),        vec![0.6000000238418579, 0.800000011920929]    );    assert_eq!(widen(&normalise(&[0.0, 0.0])), vec![0.0, 0.0]);}#[test]fn cosine_distance_is_0_for_the_same_direction_1_for_orthogonal_2_for_opposite() {    assert_eq!(cosine_distance(&[1.0, 0.0], &[2.0, 0.0]), Ok(0.0));    assert_eq!(cosine_distance(&[1.0, 0.0], &[0.0, 1.0]), Ok(1.0));    assert_eq!(cosine_distance(&[1.0, 0.0], &[-1.0, 0.0]), Ok(2.0));    // A vector of nothing matches nothing rather than everything.    assert_eq!(cosine_distance(&[0.0, 0.0], &[1.0, 0.0]), Ok(2.0));    assert_eq!(        cosine_distance(&[1.0], &[1.0, 2.0]),        Err(PeopleError::CosineLength { a: 1, b: 2 })    );    assert_eq!(        cosine_distance(&[1.0], &[1.0, 2.0])            .unwrap_err()            .to_string(),        "cosineDistance: vectors differ in length (1 vs 2)"    );}#[test]fn a_centroid_is_the_normalised_mean_of_normalised_vectors() {    let c = centroid_of(&[&[1.0, 0.0], &[0.0, 1.0]]).expect("two vectors");    assert!((f64::from(c[0]) - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-6);    assert!((f64::from(c[1]) - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-6);    // Magnitude does not weight a member: a long vector counts once.    let c2 = centroid_of(&[&[100.0, 0.0], &[0.0, 1.0]]).expect("two vectors");    assert!((f64::from(c2[0]) - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-6);    assert_eq!(centroid_of(&[]), Err(PeopleError::NoVectors));    assert_eq!(        centroid_of(&[]).unwrap_err().to_string(),        "centroidOf: no vectors"    );    assert_eq!(        centroid_of(&[&[1.0, 0.0], &[0.0]]),        Err(PeopleError::CentroidLength {            found: 1,            expected: 2        })    );}/// Eight normalisations, eight distances and five centroids, all read out of/// Node.////// `normalise([3, 4])` answering `0.6000000238418579` rather than `0.6` is the/// whole reason `Vec<f32>` is the return type: the TypeScript writes into a/// `Float32Array`, and dropping that rounding would change every distance in/// the fifth decimal. Two opposite vectors average to the ZERO vector, which/// normalises to zero and then matches nothing — a person whose faces point/// two ways has no usable centroid, and this is the shape that says so.#[test]fn the_vector_maths_matches_the_typescript_digit_for_digit() {    let normalisations: &[(&[f64], &[f64])] = &[        (&[3.0, 4.0], &[0.6000000238418579, 0.800000011920929]),        (&[0.0, 0.0], &[0.0, 0.0]),        (&[1.0, 1.0, 1.0, 1.0], &[0.5, 0.5, 0.5, 0.5]),        (&[-2.0, 0.0, 0.0], &[-1.0, 0.0, 0.0]),        (            &[0.1, 0.2, 0.3],            &[0.26726123690605164, 0.5345224738121033, 0.8017837405204773],        ),        (&[1e-8, 1e-8], &[0.7071067690849304, 0.7071067690849304]),        (            &[100.0, 0.0, 0.0, 1.0],            &[0.9999499917030334, 0.0, 0.0, 0.009999499656260014],        ),        (            &[0.05, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.02],            &[                0.04992765560746193,                0.9985531568527222,                0.0,                0.0,                0.0,                0.0,                0.0,                0.01997106336057186,            ],        ),    ];    for (input, expected) in normalisations {        assert_eq!(widen(&normalise(input)), *expected, "normalise({input:?})");    }    let distances: &[(&[f64], &[f64], f64)] = &[        (&[1.0, 0.0], &[2.0, 0.0], 0.0),        (&[1.0, 0.0], &[0.0, 1.0], 1.0),        (&[1.0, 0.0], &[-1.0, 0.0], 2.0),        (&[0.0, 0.0], &[1.0, 0.0], 2.0),        (&[1.0, 1.0], &[1.0, 0.0], 0.29289321881345254),        (            &[0.05, 1.0, 0.0, 0.0],            &[0.0, 1.0, 0.0, 0.0],            0.0012476611221553524,        ),        (            &[1.0, 0.6, 0.0, 0.0],            &[1.0, 0.0, 0.0, 0.0],            0.14250707428745568,        ),        (&[3.0, 4.0], &[4.0, 3.0], 0.040000000000000036),    ];    for (a, b, expected) in distances {        assert_eq!(            cosine_distance(a, b),            Ok(*expected),            "cosine_distance({a:?}, {b:?})"        );    }    let centroids: &[(&[&[f64]], &[f64])] = &[        (            &[&[1.0, 0.0], &[0.0, 1.0]],            &[0.7071067690849304, 0.7071067690849304],        ),        (            &[&[100.0, 0.0], &[0.0, 1.0]],            &[0.7071067690849304, 0.7071067690849304],        ),        (            &[&[1.0, 0.0, 0.0], &[1.0, 0.0, 0.0], &[0.0, 1.0, 0.0]],            &[0.8944271802902222, 0.4472135901451111, 0.0],        ),        (            &[                &[0.05, 1.0, 0.0, 0.0],                &[-0.05, 1.0, 0.0, 0.0],                &[0.02, 1.0, 0.0, 0.0],            ],            &[0.00667117815464735, 0.9999777674674988, 0.0, 0.0],        ),        (&[&[1.0, 0.0], &[-1.0, 0.0]], &[0.0, 0.0]),    ];    for (input, expected) in centroids {        assert_eq!(            widen(&centroid_of(input).expect("non-empty")),            *expected,            "centroid_of({input:?})"        );    }}// ── seedCentroids ────────────────────────────────────────────────────────────#[test]fn seeds_only_a_person_with_enough_embedded_faces() {    let mut faces = seeds();    faces.push(face("s1", Some("solo"), toward(2, 0.0)));    let mut named = seeds_of(&faces, MIN_SEED_FACES);    named.sort();    assert_eq!(named, vec!["meera", "ravi"]);    assert_eq!(MIN_SEED_FACES, 3);    assert!(seeds_of(&faces, 1).contains(&"solo".to_string()));}#[test]fn ignores_faces_with_no_person() {    let faces = vec![        face("x", None, toward(0, 0.0)),        face("y", None, toward(0, 0.0)),        face("z", None, toward(0, 0.0)),    ];    assert_eq!(seeds_of(&faces, MIN_SEED_FACES).len(), 0);}/// The two seed centroids, as Node printed them, and the fact that the ORDER/// is the order each person's first face appears — which is why this crate/// returns a `Vec` where a `HashMap` would have been the obvious shape./// `suggest_people`'s "nearest" is a strict `<`, so two people at exactly/// equal distance are settled by that order and nothing else.#[test]fn seed_centroids_match_node_and_keep_the_input_order() {    let centroids = seed_centroids(&seeds(), MIN_SEED_FACES).expect("even lengths");    assert_eq!(        centroids            .iter()            .map(|seed| seed.person_id.as_str())            .collect::<Vec<_>>(),        vec!["ravi", "meera"]    );    assert_eq!(        widen(&centroids[0].centroid),        vec![            0.9999777674674988,            0.0,            0.0,            0.0,            0.0,            0.0,            0.0,            0.00667117815464735        ]    );    assert_eq!(        widen(&centroids[1].centroid),        vec![            0.0,            0.9999944567680359,            0.0,            0.0,            0.0,            0.0,            0.0,            0.0033359783701598644        ]    );    let mut reversed = seeds();    reversed.reverse();    assert_eq!(seeds_of(&reversed, MIN_SEED_FACES), vec!["meera", "ravi"]);}// ── suggestPeople ────────────────────────────────────────────────────────────#[test]fn suggests_the_nearest_seed_for_a_face_that_is_near_enough_and_clearly_nearest() {    let mut faces = seeds();    faces.push(face("u1", None, toward(0, 0.1)));    let out = suggest(&faces);    assert_eq!(out.len(), 1);    assert_eq!(out[0].face_id, "u1");    assert_eq!(out[0].suggested_person_id, "ravi");    assert!(out[0].distance < SUGGEST_MAX_DISTANCE);    assert!(out[0].distance >= 0.0);    // Read out of Node.    assert_eq!(out[0].distance, 0.004321144887144968);}/// Axis 3 is orthogonal to both seeds: distance ≈ 1, well past the threshold.#[test]fn stays_silent_when_the_nearest_seed_is_too_far() {    let mut faces = seeds();    faces.push(face("u1", None, toward(3, 0.0)));    assert_eq!(suggest(&faces), vec![]);}#[test]fn stays_silent_when_two_seeds_are_too_close_to_call() {    let loose = SuggestPeopleOptions {        max_distance: Some(0.5),        ..SuggestPeopleOptions::default()    };    // Halfway between Ravi and Meera: both at the same distance.    let between = widen(&normalise(&[1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]));    let mut faces = seeds();    faces.push(face("u1", None, between));    assert_eq!(suggest_people(&faces, &loose), Ok(vec![]));    // Nudge it towards Ravi by more than the margin and it speaks.    let leaning = widen(&normalise(&[1.0, 0.6, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]));    let mut faces = seeds();    faces.push(face("u2", None, leaning));    let out = suggest_people(&faces, &loose).expect("even lengths");    assert_eq!(        out.iter()            .map(|s| s.suggested_person_id.as_str())            .collect::<Vec<_>>(),        vec!["ravi"]    );    assert_eq!(out[0].distance, 0.14252614517829998);    assert_eq!(SUGGEST_MARGIN, 0.05);}#[test]fn never_touches_a_face_that_has_a_person_an_open_suggestion_or_a_dismissal() {    let mut faces = seeds();    // Meera's by the owner, looks like Ravi — not ours to say.    faces.push(face("known", Some("meera"), toward(0, 0.1)));    faces.push(FaceForPeople {        suggested_person_id: Some("ravi".to_string()),        ..face("open", None, toward(0, 0.1))    });    faces.push(FaceForPeople {        dismissed: true,        ..face("no", None, toward(0, 0.1))    });    faces.push(face("fresh", None, toward(0, 0.1)));    assert_eq!(        suggest(&faces)            .iter()            .map(|s| s.face_id.as_str())            .collect::<Vec<_>>(),        vec!["fresh"]    );}/// Two people whose faces all point the same way — a duplicate person the/// owner has not merged. Neither is ever suggested onto the other's faces, and/// an unknown face between them gets nothing: the margin cannot be met.#[test]fn does_not_merge_two_seeds_however_close_their_centroids() {    let mut faces = vec![        face("a1", Some("ravi"), toward(0, 0.01)),        face("a2", Some("ravi"), toward(0, -0.01)),        face("a3", Some("ravi"), toward(0, 0.02)),        face("b1", Some("ravi-2"), toward(0, 0.015)),        face("b2", Some("ravi-2"), toward(0, -0.015)),        face("b3", Some("ravi-2"), toward(0, 0.0)),    ];    assert_eq!(suggest(&faces), vec![]);    faces.push(face("u", None, toward(0, 0.0)));    assert_eq!(suggest(&faces), vec![]);}#[test]fn with_no_seeds_there_is_nothing_to_say() {    assert_eq!(suggest(&[face("u", None, toward(0, 0.0))]), vec![]);}/// A whole three-person library with five unknown faces, run through the/// TypeScript and pinned as its answer.////// It is the case the small tests cannot make: `q2` sits between Ravi and/// Meera and is refused on the MARGIN, `q4` points at all three and is refused/// on the DISTANCE, `q5` points away from everyone, and `q1`/`q3` are the two/// that speak — with the distances Node computed, to the last digit. Loosening/// both thresholds changes nothing, which is the useful half: the two refusals/// are not near misses.#[test]fn the_whole_pass_over_a_three_person_library_matches_node() {    let mix = |a: f64, b: f64, c: f64| vec![a, b, c, 0.0, 0.0, 0.0, 0.0, 0.0];    let mut wide = seeds();    wide.extend([        face("k1", Some("kiran"), mix(0.0, 0.0, 1.0)),        face("k2", Some("kiran"), mix(0.0, 0.03, 1.0)),        face("k3", Some("kiran"), mix(0.01, 0.0, 1.0)),        face("q1", None, mix(1.0, 0.1, 0.0)),        face("q2", None, mix(0.9, 0.9, 0.0)),        face("q3", None, mix(0.0, 0.1, 1.0)),        face("q4", None, mix(0.5, 0.5, 0.5)),        face("q5", None, mix(-1.0, 0.0, 0.0)),    ]);    let expected = vec![        PersonSuggestion {            face_id: "q1".to_string(),            suggested_person_id: "ravi".to_string(),            distance: 0.004984951910492086,        },        PersonSuggestion {            face_id: "q3".to_string(),            suggested_person_id: "kiran".to_string(),            distance: 0.0040233579901762795,        },    ];    assert_eq!(suggest(&wide), expected);    assert_eq!(        suggest_people(            &wide,            &SuggestPeopleOptions {                min_seed_faces: None,                max_distance: Some(0.9),                margin: Some(0.01),            }        ),        Ok(expected.clone())    );    assert_eq!(        suggest_people(            &wide,            &SuggestPeopleOptions {                min_seed_faces: Some(1),                max_distance: None,                margin: None,            }        ),        Ok(expected)    );}#[test]fn the_wire_shape_is_the_typescript_object() {    let suggestion = PersonSuggestion {        face_id: "face-1".to_string(),        suggested_person_id: "person-1".to_string(),        distance: 0.25,    };    assert_eq!(        serde_json::to_string(&suggestion).expect("serialises"),        r#"{"faceId":"face-1","suggestedPersonId":"person-1","distance":0.25}"#    );}fn print(angle: f64) -> Vec<f64> {    // Unit vectors on a circle in the first two dimensions: cosine distance    // between two of them is 1 - cos(angle difference).    let mut v = vec![0.0; 8];    v[0] = angle.cos();    v[1] = angle.sin();    v}fn open_face(id: &str, angle: f64) -> FaceForPeople {    FaceForPeople { face_id: id.into(), person_id: None, suggested_person_id: None, dismissed: false, embedding: print(angle) }}/// RULE: A person with a face print has every matching face linked in one pass — one print (a profile picture) is enough, and an open suggestion does not stop the link.#[test]fn one_print_links_every_matching_face_in_one_pass() {    let people = vec![PersonPrints { person_id: "asha".into(), prints: vec![print(0.0)] }];    let mut faces: Vec<FaceForPeople> = (0..50).map(|i| open_face(&format!("f{i}"), 0.1 + f64::from(i) * 0.005)).collect();    faces[3].suggested_person_id = Some("asha".into());    faces.push(open_face("far", 1.5));    let links = match_people(&people, &faces).unwrap();    assert_eq!(links.len(), 50, "every near face is linked, the far one is not");    assert!(links.iter().all(|link| link.person_id == "asha" && link.face_id != "far"));}/// RULE: The owner's answer about a face stands over the matcher — a face with a person or a dismissal is never linked — and two people the model cannot tell apart link nobody.#[test]fn the_owners_answer_stands_and_a_tie_links_nobody() {    let people = vec![        PersonPrints { person_id: "asha".into(), prints: vec![print(0.0)] },        PersonPrints { person_id: "ravi".into(), prints: vec![print(0.04)] },        PersonPrints { person_id: "meera".into(), prints: vec![print(-1.2)] },    ];    let mut named = open_face("named", -1.2);    named.person_id = Some("someone".into());    let mut dismissed = open_face("dismissed", -1.2);    dismissed.dismissed = true;    let faces = vec![named, dismissed, open_face("between", 0.02), open_face("meera", -1.19)];    let links = match_people(&people, &faces).unwrap();    assert_eq!(links.iter().map(|l| l.face_id.as_str()).collect::<Vec<_>>(), vec!["meera"]);}