Skip to main content

oxirs_chat/utils/
ranking.rs

1//! Document ranking algorithms for RAG retrieval
2//!
3//! This module provides various ranking algorithms to score and rank
4//! documents based on relevance to a query.
5
6/// Ranking algorithm types
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum RankingAlgorithm {
9    /// BM25 (Best Matching 25) - probabilistic relevance ranking
10    BM25,
11    /// TF-IDF (Term Frequency-Inverse Document Frequency)
12    TFIDF,
13    /// Cosine similarity between query and document embeddings
14    CosineSimilarity,
15    /// Linear combination of multiple signals
16    LinearCombination,
17    /// Learning to rank model
18    LearningToRank,
19    /// Reciprocal rank fusion for combining multiple rankings
20    ReciprocalRankFusion,
21}
22
23impl RankingAlgorithm {
24    /// Get the name of the ranking algorithm
25    pub fn name(&self) -> &'static str {
26        match self {
27            RankingAlgorithm::BM25 => "BM25",
28            RankingAlgorithm::TFIDF => "TF-IDF",
29            RankingAlgorithm::CosineSimilarity => "Cosine Similarity",
30            RankingAlgorithm::LinearCombination => "Linear Combination",
31            RankingAlgorithm::LearningToRank => "Learning to Rank",
32            RankingAlgorithm::ReciprocalRankFusion => "Reciprocal Rank Fusion",
33        }
34    }
35
36    /// Get a description of the algorithm
37    pub fn description(&self) -> &'static str {
38        match self {
39            RankingAlgorithm::BM25 => {
40                "Probabilistic ranking function based on term frequency and document length"
41            }
42            RankingAlgorithm::TFIDF => {
43                "Statistical measure of term importance based on frequency and rarity"
44            }
45            RankingAlgorithm::CosineSimilarity => {
46                "Similarity measure between query and document vectors"
47            }
48            RankingAlgorithm::LinearCombination => {
49                "Weighted combination of multiple ranking signals"
50            }
51            RankingAlgorithm::LearningToRank => "Machine learning-based ranking model",
52            RankingAlgorithm::ReciprocalRankFusion => "Method for combining multiple ranked lists",
53        }
54    }
55}
56
57/// Ranking score with breakdown
58#[derive(Debug, Clone)]
59pub struct RankingScore {
60    /// Overall ranking score
61    pub score: f64,
62    /// Algorithm used for ranking
63    pub algorithm: RankingAlgorithm,
64    /// Individual signal scores contributing to the final score
65    pub signal_scores: Vec<SignalScore>,
66    /// Confidence in the ranking
67    pub confidence: f64,
68    /// Explanation of the score
69    pub explanation: Option<String>,
70}
71
72impl RankingScore {
73    /// Create a new ranking score
74    pub fn new(score: f64, algorithm: RankingAlgorithm) -> Self {
75        Self {
76            score,
77            algorithm,
78            signal_scores: Vec::new(),
79            confidence: 1.0,
80            explanation: None,
81        }
82    }
83
84    /// Add a signal score
85    pub fn with_signal(mut self, name: String, score: f64, weight: f64) -> Self {
86        self.signal_scores.push(SignalScore {
87            name,
88            score,
89            weight,
90        });
91        self
92    }
93
94    /// Set confidence
95    pub fn with_confidence(mut self, confidence: f64) -> Self {
96        self.confidence = confidence;
97        self
98    }
99
100    /// Set explanation
101    pub fn with_explanation(mut self, explanation: String) -> Self {
102        self.explanation = Some(explanation);
103        self
104    }
105
106    /// Get the weighted score considering confidence
107    pub fn weighted_score(&self) -> f64 {
108        self.score * self.confidence
109    }
110
111    /// Check if the score is above a threshold
112    pub fn is_relevant(&self, threshold: f64) -> bool {
113        self.score >= threshold
114    }
115}
116
117/// Individual signal score contributing to ranking
118#[derive(Debug, Clone)]
119pub struct SignalScore {
120    /// Name of the signal
121    pub name: String,
122    /// Raw score value
123    pub score: f64,
124    /// Weight of this signal in the final ranking
125    pub weight: f64,
126}
127
128/// BM25 parameters
129#[derive(Debug, Clone)]
130pub struct BM25Params {
131    /// Term frequency saturation parameter (typically 1.2 to 2.0)
132    pub k1: f64,
133    /// Length normalization parameter (typically 0.75)
134    pub b: f64,
135    /// Minimum IDF value
136    pub min_idf: f64,
137}
138
139impl Default for BM25Params {
140    fn default() -> Self {
141        Self {
142            k1: 1.5,
143            b: 0.75,
144            min_idf: 0.0,
145        }
146    }
147}
148
149/// Compute BM25 score for a document
150///
151/// # Arguments
152/// * `term_freq` - Term frequency in the document
153/// * `doc_length` - Length of the document
154/// * `avg_doc_length` - Average document length in the collection
155/// * `num_docs` - Total number of documents
156/// * `doc_freq` - Number of documents containing the term
157/// * `params` - BM25 parameters
158pub fn bm25_score(
159    term_freq: f64,
160    doc_length: f64,
161    avg_doc_length: f64,
162    num_docs: f64,
163    doc_freq: f64,
164    params: &BM25Params,
165) -> f64 {
166    // IDF component
167    let idf = ((num_docs - doc_freq + 0.5) / (doc_freq + 0.5) + 1.0)
168        .ln()
169        .max(params.min_idf);
170
171    // TF component with length normalization
172    let norm_length = 1.0 - params.b + params.b * (doc_length / avg_doc_length);
173    let tf = (term_freq * (params.k1 + 1.0)) / (term_freq + params.k1 * norm_length);
174
175    idf * tf
176}
177
178/// Compute TF-IDF score
179///
180/// # Arguments
181/// * `term_freq` - Term frequency in the document
182/// * `doc_freq` - Number of documents containing the term
183/// * `num_docs` - Total number of documents
184pub fn tfidf_score(term_freq: f64, doc_freq: f64, num_docs: f64) -> f64 {
185    let tf = term_freq;
186    let idf = (num_docs / (doc_freq + 1.0)).ln();
187    tf * idf
188}
189
190/// Combine multiple ranking scores using linear combination
191///
192/// # Arguments
193/// * `scores` - Vector of (score, weight) pairs
194pub fn linear_combination(scores: &[(f64, f64)]) -> f64 {
195    let total_weight: f64 = scores.iter().map(|(_, w)| w).sum();
196    if total_weight < 1e-10 {
197        return 0.0;
198    }
199
200    scores.iter().map(|(s, w)| s * w).sum::<f64>() / total_weight
201}
202
203/// Reciprocal rank fusion - combine multiple ranked lists
204///
205/// # Arguments
206/// * `ranked_lists` - Vector of ranked document IDs (highest rank first)
207/// * `k` - Constant (typically 60)
208pub fn reciprocal_rank_fusion(ranked_lists: &[Vec<String>], k: f64) -> Vec<(String, f64)> {
209    use std::collections::HashMap;
210
211    let mut scores: HashMap<String, f64> = HashMap::new();
212
213    for ranked_list in ranked_lists {
214        for (rank, doc_id) in ranked_list.iter().enumerate() {
215            let rrf_score = 1.0 / (k + (rank as f64 + 1.0));
216            *scores.entry(doc_id.clone()).or_insert(0.0) += rrf_score;
217        }
218    }
219
220    let mut result: Vec<(String, f64)> = scores.into_iter().collect();
221    result.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
222    result
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn test_bm25_score() {
231        let params = BM25Params::default();
232        let score = bm25_score(5.0, 100.0, 80.0, 1000.0, 10.0, &params);
233        assert!(score > 0.0);
234    }
235
236    #[test]
237    fn test_tfidf_score() {
238        let score = tfidf_score(3.0, 10.0, 100.0);
239        assert!(score > 0.0);
240    }
241
242    #[test]
243    fn test_linear_combination() {
244        let scores = vec![(0.8, 0.5), (0.6, 0.3), (0.9, 0.2)];
245        let combined = linear_combination(&scores);
246        assert!(combined > 0.0 && combined < 1.0);
247    }
248
249    #[test]
250    fn test_reciprocal_rank_fusion() {
251        let list1 = vec!["doc1".to_string(), "doc2".to_string(), "doc3".to_string()];
252        let list2 = vec!["doc2".to_string(), "doc1".to_string(), "doc4".to_string()];
253        let result = reciprocal_rank_fusion(&[list1, list2], 60.0);
254        assert!(!result.is_empty());
255        // doc1 and doc2 should have higher scores as they appear in both lists
256        assert!(result[0].1 > 0.0);
257    }
258
259    #[test]
260    fn test_ranking_score() {
261        let score = RankingScore::new(0.85, RankingAlgorithm::BM25)
262            .with_signal("term_match".to_string(), 0.9, 0.6)
263            .with_signal("semantic".to_string(), 0.8, 0.4)
264            .with_confidence(0.95);
265
266        assert_eq!(score.score, 0.85);
267        assert_eq!(score.signal_scores.len(), 2);
268        assert_eq!(score.confidence, 0.95);
269        assert!((score.weighted_score() - 0.8075).abs() < 1e-6);
270    }
271
272    #[test]
273    fn test_ranking_algorithm_name() {
274        assert_eq!(RankingAlgorithm::BM25.name(), "BM25");
275        assert_eq!(RankingAlgorithm::TFIDF.name(), "TF-IDF");
276    }
277}