Skip to main content

qualia_core_db/specialized_libs/medical_computing/
similarity.rs

1/// Tanimoto similarity of the overlapping prefix; an empty union returns zero.
2pub fn tanimoto_bits(a: &[bool], b: &[bool]) -> f64 {
3    let n = a.len().min(b.len());
4    let mut intersection = 0usize;
5    let mut union = 0usize;
6    for i in 0..n {
7        if a[i] && b[i] {
8            intersection += 1;
9        }
10        if a[i] || b[i] {
11            union += 1;
12        }
13    }
14    if union == 0 {
15        0.0
16    } else {
17        intersection as f64 / union as f64
18    }
19}
20
21#[cfg(test)]
22mod tests {
23    use super::tanimoto_bits;
24
25    #[test]
26    fn boolean_similarity_preserves_overlap_and_empty_union() {
27        assert_eq!(
28            tanimoto_bits(&[true, false, true], &[true, true, false]),
29            1.0 / 3.0
30        );
31        assert_eq!(tanimoto_bits(&[true, true], &[true]), 1.0);
32        assert_eq!(tanimoto_bits(&[false], &[false]), 0.0);
33        assert_eq!(tanimoto_bits(&[], &[true]), 0.0);
34    }
35}