1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum RankingAlgorithm {
9 BM25,
11 TFIDF,
13 CosineSimilarity,
15 LinearCombination,
17 LearningToRank,
19 ReciprocalRankFusion,
21}
22
23impl RankingAlgorithm {
24 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 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#[derive(Debug, Clone)]
59pub struct RankingScore {
60 pub score: f64,
62 pub algorithm: RankingAlgorithm,
64 pub signal_scores: Vec<SignalScore>,
66 pub confidence: f64,
68 pub explanation: Option<String>,
70}
71
72impl RankingScore {
73 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 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 pub fn with_confidence(mut self, confidence: f64) -> Self {
96 self.confidence = confidence;
97 self
98 }
99
100 pub fn with_explanation(mut self, explanation: String) -> Self {
102 self.explanation = Some(explanation);
103 self
104 }
105
106 pub fn weighted_score(&self) -> f64 {
108 self.score * self.confidence
109 }
110
111 pub fn is_relevant(&self, threshold: f64) -> bool {
113 self.score >= threshold
114 }
115}
116
117#[derive(Debug, Clone)]
119pub struct SignalScore {
120 pub name: String,
122 pub score: f64,
124 pub weight: f64,
126}
127
128#[derive(Debug, Clone)]
130pub struct BM25Params {
131 pub k1: f64,
133 pub b: f64,
135 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
149pub 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 let idf = ((num_docs - doc_freq + 0.5) / (doc_freq + 0.5) + 1.0)
168 .ln()
169 .max(params.min_idf);
170
171 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
178pub 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
190pub 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
203pub 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, ¶ms);
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 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}