scirs2-text 0.4.3

Text processing module for SciRS2 (scirs2-text)
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
//! Text similarity module
//!
//! Provides multiple methods for computing similarity between text strings:
//!
//! - **TF-IDF Cosine**: Cosine similarity over TF-IDF document vectors
//! - **Jaccard**: Token-level and character n-gram Jaccard similarity
//! - **BM25**: Okapi BM25 relevance scoring
//! - **Edit Distance**: Normalised Levenshtein similarity
//!
//! All methods are available through the unified [`text_similarity`] function
//! or through dedicated structs for finer-grained configuration.

use crate::error::{Result, TextError};
use crate::tokenize::{Tokenizer, WordTokenizer};
use crate::vectorize::{TfidfVectorizer, Vectorizer};
use std::collections::{HashMap, HashSet};

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

/// Similarity method selector.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SimilarityMethod {
    /// Cosine similarity on TF-IDF vectors.
    TfIdfCosine,
    /// Token-level Jaccard similarity.
    Jaccard,
    /// Character n-gram Jaccard similarity.
    CharNgramJaccard {
        /// N-gram size (e.g. 3 for trigrams).
        n: usize,
    },
    /// BM25 relevance score (text2 is treated as the "document", text1 as the "query").
    Bm25,
    /// Normalised Levenshtein similarity (1 - normalised_distance).
    EditDistance,
}

/// Result of a similarity computation.
#[derive(Debug, Clone)]
pub struct SimilarityResult {
    /// The computed similarity score. Range depends on the method:
    /// - Cosine, Jaccard, EditDistance: [0, 1]
    /// - BM25: [0, +inf)
    pub score: f64,
    /// The method that was used.
    pub method: SimilarityMethod,
}

// ---------------------------------------------------------------------------
// Unified API
// ---------------------------------------------------------------------------

/// Compute similarity between `text1` and `text2` using the specified method.
///
/// # Errors
///
/// Returns an error when tokenization fails or the method parameters are
/// invalid (e.g. a zero n-gram size).
pub fn text_similarity(
    text1: &str,
    text2: &str,
    method: SimilarityMethod,
) -> Result<SimilarityResult> {
    let score = match method {
        SimilarityMethod::TfIdfCosine => tfidf_cosine_similarity(text1, text2)?,
        SimilarityMethod::Jaccard => jaccard_token_similarity(text1, text2)?,
        SimilarityMethod::CharNgramJaccard { n } => char_ngram_jaccard_similarity(text1, text2, n)?,
        SimilarityMethod::Bm25 => bm25_score(text1, text2)?,
        SimilarityMethod::EditDistance => edit_distance_similarity(text1, text2),
    };
    Ok(SimilarityResult { score, method })
}

// ---------------------------------------------------------------------------
// TF-IDF cosine similarity
// ---------------------------------------------------------------------------

/// Compute cosine similarity between two texts via TF-IDF vectors.
///
/// Both texts are treated as a mini-corpus (2 documents) to derive IDF weights.
pub fn tfidf_cosine_similarity(text1: &str, text2: &str) -> Result<f64> {
    if text1.trim().is_empty() && text2.trim().is_empty() {
        return Ok(1.0);
    }
    if text1.trim().is_empty() || text2.trim().is_empty() {
        return Ok(0.0);
    }

    let docs = vec![text1, text2];
    let mut vectorizer = TfidfVectorizer::default();
    let matrix = vectorizer.fit_transform(&docs)?;

    let n = matrix.ncols();
    if n == 0 {
        return Ok(0.0);
    }

    let mut dot = 0.0_f64;
    let mut norm1_sq = 0.0_f64;
    let mut norm2_sq = 0.0_f64;

    for col in 0..n {
        let a = matrix[[0, col]];
        let b = matrix[[1, col]];
        dot += a * b;
        norm1_sq += a * a;
        norm2_sq += b * b;
    }

    let norm1 = norm1_sq.sqrt();
    let norm2 = norm2_sq.sqrt();

    if norm1 == 0.0 || norm2 == 0.0 {
        return Ok(0.0);
    }

    Ok(dot / (norm1 * norm2))
}

/// Configurable TF-IDF cosine similarity calculator.
pub struct TfIdfCosineSimilarity {
    tokenizer: Box<dyn Tokenizer + Send + Sync>,
}

impl TfIdfCosineSimilarity {
    /// Create a new calculator with the default word tokenizer.
    pub fn new() -> Self {
        Self {
            tokenizer: Box::new(WordTokenizer::default()),
        }
    }

    /// Compute the similarity between two texts.
    pub fn similarity(&self, text1: &str, text2: &str) -> Result<f64> {
        tfidf_cosine_similarity(text1, text2)
    }

    /// Compute pairwise similarities for a corpus.
    /// Returns a flat vector of (i, j, score) for all i < j.
    pub fn pairwise(&self, texts: &[&str]) -> Result<Vec<(usize, usize, f64)>> {
        if texts.len() < 2 {
            return Ok(Vec::new());
        }

        let mut vectorizer = TfidfVectorizer::default();
        let matrix = vectorizer.fit_transform(texts)?;
        let n = texts.len();
        let cols = matrix.ncols();
        let mut results = Vec::new();

        for i in 0..n {
            for j in (i + 1)..n {
                let mut dot = 0.0_f64;
                let mut n1 = 0.0_f64;
                let mut n2 = 0.0_f64;
                for c in 0..cols {
                    let a = matrix[[i, c]];
                    let b = matrix[[j, c]];
                    dot += a * b;
                    n1 += a * a;
                    n2 += b * b;
                }
                let sim = if n1 == 0.0 || n2 == 0.0 {
                    0.0
                } else {
                    dot / (n1.sqrt() * n2.sqrt())
                };
                results.push((i, j, sim));
            }
        }

        Ok(results)
    }
}

impl Default for TfIdfCosineSimilarity {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Jaccard similarity
// ---------------------------------------------------------------------------

/// Token-level Jaccard similarity.
pub fn jaccard_token_similarity(text1: &str, text2: &str) -> Result<f64> {
    let tokenizer = WordTokenizer::default();
    let tokens1 = tokenizer.tokenize(text1)?;
    let tokens2 = tokenizer.tokenize(text2)?;

    if tokens1.is_empty() && tokens2.is_empty() {
        return Ok(1.0);
    }

    let set1: HashSet<&str> = tokens1.iter().map(|s| s.as_str()).collect();
    let set2: HashSet<&str> = tokens2.iter().map(|s| s.as_str()).collect();

    let intersection = set1.intersection(&set2).count();
    let union = set1.union(&set2).count();

    if union == 0 {
        return Ok(1.0);
    }

    Ok(intersection as f64 / union as f64)
}

/// Character n-gram Jaccard similarity.
///
/// Computes Jaccard similarity over the sets of character n-grams derived
/// from both texts.
pub fn char_ngram_jaccard_similarity(text1: &str, text2: &str, n: usize) -> Result<f64> {
    if n == 0 {
        return Err(TextError::InvalidInput(
            "N-gram size must be at least 1".to_string(),
        ));
    }

    let ngrams1 = char_ngrams(text1, n);
    let ngrams2 = char_ngrams(text2, n);

    if ngrams1.is_empty() && ngrams2.is_empty() {
        return Ok(1.0);
    }

    let set1: HashSet<&str> = ngrams1.iter().map(|s| s.as_str()).collect();
    let set2: HashSet<&str> = ngrams2.iter().map(|s| s.as_str()).collect();

    let intersection = set1.intersection(&set2).count();
    let union = set1.union(&set2).count();

    if union == 0 {
        return Ok(1.0);
    }

    Ok(intersection as f64 / union as f64)
}

/// Extract character n-grams from text.
fn char_ngrams(text: &str, n: usize) -> Vec<String> {
    let lower = text.to_lowercase();
    let chars: Vec<char> = lower.chars().collect();
    if chars.len() < n {
        return Vec::new();
    }
    chars.windows(n).map(|w| w.iter().collect()).collect()
}

// ---------------------------------------------------------------------------
// BM25
// ---------------------------------------------------------------------------

/// BM25 (Okapi Best Matching 25) scoring parameters.
#[derive(Debug, Clone)]
pub struct Bm25Config {
    /// Term frequency saturation parameter (typical: 1.2 - 2.0).
    pub k1: f64,
    /// Length normalization parameter (typical: 0.75).
    pub b: f64,
}

impl Default for Bm25Config {
    fn default() -> Self {
        Self { k1: 1.5, b: 0.75 }
    }
}

/// Compute BM25 relevance of `document` with respect to `query`.
///
/// The function treats the query and document each as a single text.
/// IDF is estimated from a synthetic 2-document corpus for simplicity;
/// for a full corpus-aware BM25, use [`Bm25Scorer`].
pub fn bm25_score(query: &str, document: &str) -> Result<f64> {
    let scorer = Bm25Scorer::new(Bm25Config::default());
    scorer.score_single(query, document)
}

/// A BM25 scorer that can score a query against an entire corpus.
pub struct Bm25Scorer {
    config: Bm25Config,
    tokenizer: Box<dyn Tokenizer + Send + Sync>,
}

impl Bm25Scorer {
    /// Create a new BM25 scorer with the given configuration.
    pub fn new(config: Bm25Config) -> Self {
        Self {
            config,
            tokenizer: Box::new(WordTokenizer::default()),
        }
    }

    /// Score a single `query` against a single `document`.
    pub fn score_single(&self, query: &str, document: &str) -> Result<f64> {
        let query_tokens = self.tokenizer.tokenize(query)?;
        let doc_tokens = self.tokenizer.tokenize(document)?;

        if query_tokens.is_empty() || doc_tokens.is_empty() {
            return Ok(0.0);
        }

        // Document term frequencies.
        let mut doc_tf: HashMap<String, f64> = HashMap::new();
        for token in &doc_tokens {
            *doc_tf.entry(token.clone()).or_insert(0.0) += 1.0;
        }

        let doc_len = doc_tokens.len() as f64;
        // For a single-document scenario we use avgdl = doc_len.
        let avgdl = doc_len;
        // Total docs = 1, containing term => df = 1 for matching terms.
        let n_docs = 1.0_f64;

        let mut score = 0.0_f64;
        let query_terms: HashSet<String> = query_tokens.into_iter().collect();

        for term in &query_terms {
            let tf = doc_tf.get(term).copied().unwrap_or(0.0);
            if tf == 0.0 {
                continue;
            }
            let df = 1.0_f64; // the document contains the term
            let idf = ((n_docs - df + 0.5) / (df + 0.5) + 1.0).ln();
            let numerator = tf * (self.config.k1 + 1.0);
            let denominator =
                tf + self.config.k1 * (1.0 - self.config.b + self.config.b * doc_len / avgdl);
            score += idf * numerator / denominator;
        }

        Ok(score)
    }

    /// Score a query against every document in a corpus.
    /// Returns a vector of (document_index, score) sorted by score descending.
    pub fn score_corpus(&self, query: &str, corpus: &[&str]) -> Result<Vec<(usize, f64)>> {
        let query_tokens = self.tokenizer.tokenize(query)?;
        if query_tokens.is_empty() {
            return Ok(Vec::new());
        }

        let n_docs = corpus.len() as f64;

        // Tokenize all documents and compute term frequencies.
        let mut all_doc_tokens: Vec<Vec<String>> = Vec::with_capacity(corpus.len());
        let mut all_doc_tf: Vec<HashMap<String, f64>> = Vec::with_capacity(corpus.len());
        let mut total_len: f64 = 0.0;

        for doc in corpus {
            let tokens = self.tokenizer.tokenize(doc)?;
            total_len += tokens.len() as f64;
            let mut tf_map: HashMap<String, f64> = HashMap::new();
            for token in &tokens {
                *tf_map.entry(token.clone()).or_insert(0.0) += 1.0;
            }
            all_doc_tokens.push(tokens);
            all_doc_tf.push(tf_map);
        }

        let avgdl = if corpus.is_empty() {
            1.0
        } else {
            total_len / n_docs
        };

        // Compute document frequency for each query term.
        let query_terms: HashSet<String> = query_tokens.into_iter().collect();
        let mut df: HashMap<String, f64> = HashMap::new();
        for term in &query_terms {
            let count = all_doc_tf
                .iter()
                .filter(|tf_map| tf_map.contains_key(term))
                .count();
            df.insert(term.clone(), count as f64);
        }

        // Score each document.
        let mut results: Vec<(usize, f64)> = Vec::with_capacity(corpus.len());
        for (idx, doc_tf) in all_doc_tf.iter().enumerate() {
            let doc_len = all_doc_tokens[idx].len() as f64;
            let mut score = 0.0_f64;

            for term in &query_terms {
                let tf = doc_tf.get(term).copied().unwrap_or(0.0);
                if tf == 0.0 {
                    continue;
                }
                let term_df = df.get(term).copied().unwrap_or(0.0);
                let idf = ((n_docs - term_df + 0.5) / (term_df + 0.5) + 1.0).ln();
                let numerator = tf * (self.config.k1 + 1.0);
                let denominator =
                    tf + self.config.k1 * (1.0 - self.config.b + self.config.b * doc_len / avgdl);
                score += idf * numerator / denominator;
            }

            results.push((idx, score));
        }

        results.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));

        Ok(results)
    }
}

// ---------------------------------------------------------------------------
// Edit distance similarity
// ---------------------------------------------------------------------------

/// Normalised Levenshtein similarity: `1.0 - (edit_distance / max_len)`.
///
/// Returns 1.0 for identical strings and 0.0 for completely different strings.
pub fn edit_distance_similarity(text1: &str, text2: &str) -> f64 {
    if text1.is_empty() && text2.is_empty() {
        return 1.0;
    }

    let distance = levenshtein(text1, text2);
    let max_len = std::cmp::max(text1.chars().count(), text2.chars().count()) as f64;

    if max_len == 0.0 {
        return 1.0;
    }

    1.0 - (distance as f64 / max_len)
}

/// Levenshtein distance between two strings (O(n*m) DP).
fn levenshtein(s1: &str, s2: &str) -> usize {
    let a: Vec<char> = s1.chars().collect();
    let b: Vec<char> = s2.chars().collect();
    let m = a.len();
    let n = b.len();

    if m == 0 {
        return n;
    }
    if n == 0 {
        return m;
    }

    // Use a single-row DP to save memory.
    let mut prev = vec![0usize; n + 1];
    let mut curr = vec![0usize; n + 1];

    for j in 0..=n {
        prev[j] = j;
    }

    for i in 1..=m {
        curr[0] = i;
        for j in 1..=n {
            let cost = if a[i - 1] == b[j - 1] { 0 } else { 1 };
            curr[j] = std::cmp::min(
                std::cmp::min(prev[j] + 1, curr[j - 1] + 1),
                prev[j - 1] + cost,
            );
        }
        std::mem::swap(&mut prev, &mut curr);
    }

    prev[n]
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // ---- TF-IDF cosine ----

    #[test]
    fn test_tfidf_cosine_identical() {
        let score = tfidf_cosine_similarity("hello world", "hello world").expect("Should succeed");
        assert!(
            (score - 1.0).abs() < 1e-6,
            "Identical texts should have similarity ~1.0, got {}",
            score
        );
    }

    #[test]
    fn test_tfidf_cosine_different() {
        let score = tfidf_cosine_similarity("the cat sat", "purple dinosaur robot")
            .expect("Should succeed");
        assert!(
            score < 0.5,
            "Very different texts should have low similarity, got {}",
            score
        );
    }

    #[test]
    fn test_tfidf_cosine_empty() {
        assert!(
            (tfidf_cosine_similarity("", "").expect("ok") - 1.0).abs() < 1e-6,
            "Both empty -> 1.0"
        );
        assert!(
            tfidf_cosine_similarity("hello", "").expect("ok").abs() < 1e-6,
            "One empty -> 0.0"
        );
    }

    #[test]
    fn test_tfidf_cosine_symmetric() {
        let ab = tfidf_cosine_similarity("machine learning", "deep learning").expect("ok");
        let ba = tfidf_cosine_similarity("deep learning", "machine learning").expect("ok");
        assert!((ab - ba).abs() < 1e-10, "Cosine should be symmetric");
    }

    #[test]
    fn test_tfidf_cosine_partial_overlap() {
        let score =
            tfidf_cosine_similarity("the quick brown fox", "the quick red car").expect("ok");
        assert!(score > 0.0 && score < 1.0);
    }

    #[test]
    fn test_tfidf_pairwise() {
        let calc = TfIdfCosineSimilarity::new();
        let texts = vec!["hello world", "hello there", "goodbye moon"];
        let pairs = calc.pairwise(&texts).expect("ok");
        assert_eq!(pairs.len(), 3); // C(3,2) = 3
        for (i, j, s) in &pairs {
            assert!(*i < *j);
            assert!(*s >= 0.0);
        }
    }

    // ---- Jaccard ----

    #[test]
    fn test_jaccard_identical() {
        let score = jaccard_token_similarity("hello world", "hello world").expect("ok");
        assert!((score - 1.0).abs() < 1e-6);
    }

    #[test]
    fn test_jaccard_disjoint() {
        let score = jaccard_token_similarity("alpha beta", "gamma delta").expect("ok");
        assert!(score.abs() < 1e-6);
    }

    #[test]
    fn test_jaccard_partial() {
        let score = jaccard_token_similarity("cat dog bird", "cat dog fish").expect("ok");
        // intersection={cat, dog}=2, union={cat, dog, bird, fish}=4 -> 0.5
        assert!((score - 0.5).abs() < 1e-6);
    }

    #[test]
    fn test_jaccard_empty() {
        let score = jaccard_token_similarity("", "").expect("ok");
        assert!((score - 1.0).abs() < 1e-6);
    }

    #[test]
    fn test_jaccard_symmetric() {
        let ab = jaccard_token_similarity("a b c", "b c d").expect("ok");
        let ba = jaccard_token_similarity("b c d", "a b c").expect("ok");
        assert!((ab - ba).abs() < 1e-10);
    }

    // ---- Char n-gram Jaccard ----

    #[test]
    fn test_char_ngram_identical() {
        let score = char_ngram_jaccard_similarity("hello", "hello", 3).expect("ok");
        assert!((score - 1.0).abs() < 1e-6);
    }

    #[test]
    fn test_char_ngram_different() {
        let score = char_ngram_jaccard_similarity("abcdef", "uvwxyz", 3).expect("ok");
        assert!(score.abs() < 1e-6);
    }

    #[test]
    fn test_char_ngram_partial() {
        let score = char_ngram_jaccard_similarity("abcde", "abcfg", 2).expect("ok");
        // ab, bc common; cd, de vs cf, fg unique
        assert!(score > 0.0 && score < 1.0);
    }

    #[test]
    fn test_char_ngram_zero_n() {
        let result = char_ngram_jaccard_similarity("a", "b", 0);
        assert!(result.is_err());
    }

    #[test]
    fn test_char_ngram_empty() {
        let score = char_ngram_jaccard_similarity("", "", 2).expect("ok");
        assert!((score - 1.0).abs() < 1e-6);
    }

    // ---- BM25 ----

    #[test]
    fn test_bm25_matching_query() {
        let score = bm25_score(
            "machine learning",
            "machine learning is a subset of artificial intelligence",
        )
        .expect("ok");
        assert!(score > 0.0);
    }

    #[test]
    fn test_bm25_no_match() {
        let score = bm25_score("quantum physics", "the cat sat on the mat").expect("ok");
        assert!(score.abs() < 1e-6);
    }

    #[test]
    fn test_bm25_empty() {
        let score = bm25_score("", "anything").expect("ok");
        assert!(score.abs() < 1e-6);
        let score = bm25_score("anything", "").expect("ok");
        assert!(score.abs() < 1e-6);
    }

    #[test]
    fn test_bm25_corpus_scoring() {
        let scorer = Bm25Scorer::new(Bm25Config::default());
        let corpus = vec![
            "machine learning algorithms",
            "deep learning neural networks",
            "cooking recipes for dinner",
        ];
        let results = scorer
            .score_corpus("learning algorithms", &corpus)
            .expect("ok");
        assert_eq!(results.len(), 3);
        // First result should be the most relevant document.
        assert_eq!(results[0].0, 0);
    }

    #[test]
    fn test_bm25_corpus_empty_query() {
        let scorer = Bm25Scorer::new(Bm25Config::default());
        let results = scorer.score_corpus("", &["a", "b"]).expect("ok");
        assert!(results.is_empty());
    }

    // ---- Edit distance ----

    #[test]
    fn test_edit_distance_identical() {
        let score = edit_distance_similarity("kitten", "kitten");
        assert!((score - 1.0).abs() < 1e-6);
    }

    #[test]
    fn test_edit_distance_completely_different() {
        let score = edit_distance_similarity("abc", "xyz");
        assert!((score - 0.0).abs() < 1e-6);
    }

    #[test]
    fn test_edit_distance_known_value() {
        // "kitten" -> "sitting" = distance 3, max_len 7 => similarity = 4/7
        let score = edit_distance_similarity("kitten", "sitting");
        let expected = 1.0 - 3.0 / 7.0;
        assert!(
            (score - expected).abs() < 1e-6,
            "Expected {}, got {}",
            expected,
            score
        );
    }

    #[test]
    fn test_edit_distance_empty() {
        assert!((edit_distance_similarity("", "") - 1.0).abs() < 1e-6);
        assert!(edit_distance_similarity("abc", "").abs() < 1e-6);
    }

    #[test]
    fn test_edit_distance_symmetric() {
        let ab = edit_distance_similarity("abc", "aec");
        let ba = edit_distance_similarity("aec", "abc");
        assert!((ab - ba).abs() < 1e-10);
    }

    // ---- Unified API ----

    #[test]
    fn test_unified_api_all_methods() {
        let methods = vec![
            SimilarityMethod::TfIdfCosine,
            SimilarityMethod::Jaccard,
            SimilarityMethod::CharNgramJaccard { n: 3 },
            SimilarityMethod::Bm25,
            SimilarityMethod::EditDistance,
        ];
        for method in methods {
            let result =
                text_similarity("hello world", "hello there", method).expect("Should succeed");
            assert!(
                result.score >= 0.0,
                "Score should be non-negative for {:?}",
                method
            );
        }
    }

    #[test]
    fn test_unified_api_returns_correct_method() {
        let result = text_similarity("a", "b", SimilarityMethod::Jaccard).expect("ok");
        assert_eq!(result.method, SimilarityMethod::Jaccard);
    }
}