1use crate::bitmap::Postings;
18use crate::index::InfonIndex;
19use serde::Serialize;
20use std::collections::BTreeMap;
21
22#[derive(Debug, Clone, Serialize)]
23pub struct FacetScore {
24 pub facet: String,
25 pub tokens: usize,
27 pub coverage: f64,
29 pub maxcos: f64,
31 pub nearest: String,
33 pub gain: f64,
35}
36
37#[derive(Debug, Clone, Serialize)]
38pub struct MeceReport {
39 pub situations: u32,
40 pub facets: Vec<FacetScore>,
41 pub mean_coverage: f64,
43 pub mean_maxcos: f64,
45 pub mean_gain: f64,
46}
47
48impl MeceReport {
49 pub fn failing(&self, threshold: f64) -> Vec<&FacetScore> {
51 self.facets.iter().filter(|f| f.gain < threshold).collect()
52 }
53}
54
55fn facet_incidence<B: Postings>(ix: &InfonIndex<B>, facet: &str) -> B {
57 let mut acc = B::empty();
58 for tok in facet_tokens(ix, facet) {
59 acc.or_inplace(&ix.post(&tok));
60 }
61 acc
62}
63
64fn facet_tokens<B: Postings>(ix: &InfonIndex<B>, facet: &str) -> Vec<String> {
66 let prefix = format!("{facet}/");
67 ix.tokens().filter(|t| *t == facet || t.starts_with(&prefix)).cloned().collect()
68}
69
70pub const MIN_SUPPORT: usize = 3;
79
80fn facet_maxcos<B: Postings>(ix: &InfonIndex<B>, a: &[String], b: &[String], cap: usize) -> f64 {
81 let mut best = 0.0f64;
82 for ta in a.iter().take(cap) {
83 let pa = ix.post(ta);
84 let la = pa.len() as f64;
85 if pa.len() < MIN_SUPPORT {
86 continue; }
88 for tb in b.iter().take(cap) {
89 let pb = ix.post(tb);
90 let lb = pb.len() as f64;
91 if pb.len() < MIN_SUPPORT {
92 continue;
93 }
94 let cos = pa.and(&pb).len() as f64 / (la * lb).sqrt();
95 if cos > best {
96 best = cos;
97 }
98 }
99 }
100 best
101}
102
103pub fn report<B: Postings>(ix: &InfonIndex<B>, skip: &[&str]) -> MeceReport {
106 let n = ix.situations();
107 let mut counts: BTreeMap<String, usize> = BTreeMap::new();
109 for tok in ix.tokens() {
110 let f = tok.split('/').next().unwrap_or(tok).to_string();
111 *counts.entry(f).or_default() += 1;
112 }
113 let names: Vec<String> = counts.keys().filter(|f| !skip.contains(&f.as_str())).cloned().collect();
114 let inc: Vec<B> = names.iter().map(|f| facet_incidence(ix, f)).collect();
115 let lens: Vec<f64> = inc.iter().map(|b| b.len() as f64).collect();
116 let toks: Vec<Vec<String>> = names.iter().map(|f| facet_tokens(ix, f)).collect();
117
118 let mut facets = Vec::with_capacity(names.len());
119 for i in 0..names.len() {
120 let mut maxcos = 0.0f64;
121 let mut nearest = String::new();
122 for j in 0..names.len() {
123 if i == j || lens[i] == 0.0 || lens[j] == 0.0 {
124 continue;
125 }
126 let cos = facet_maxcos(ix, &toks[i], &toks[j], 64);
127 if cos > maxcos {
128 maxcos = cos;
129 nearest = names[j].clone();
130 }
131 }
132 let coverage = if n == 0 { 0.0 } else { lens[i] / n as f64 };
133 facets.push(FacetScore {
134 facet: names[i].clone(),
135 tokens: counts.get(&names[i]).copied().unwrap_or(0),
136 coverage: round3(coverage),
137 maxcos: round3(maxcos),
138 nearest,
139 gain: round3(coverage * (1.0 - maxcos)),
140 });
141 }
142 facets.sort_by(|a, b| b.gain.partial_cmp(&a.gain).unwrap_or(std::cmp::Ordering::Equal));
143 let k = facets.len().max(1) as f64;
144 let mean_coverage = round3(facets.iter().map(|f| f.coverage).sum::<f64>() / k);
145 let mean_maxcos = round3(facets.iter().map(|f| f.maxcos).sum::<f64>() / k);
146 let mean_gain = round3(facets.iter().map(|f| f.gain).sum::<f64>() / k);
147 MeceReport { situations: n, facets, mean_coverage, mean_maxcos, mean_gain }
148}
149
150fn round3(v: f64) -> f64 {
151 (v * 1000.0).round() / 1000.0
152}
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157 use crate::RoarPostings;
158 use std::collections::HashMap;
159
160 #[test]
161 fn rare_terms_cannot_fake_perfect_redundancy() {
162 let raw = HashMap::from([
164 ("alpha/rare".to_string(), vec![0u32]),
165 ("beta/rare".to_string(), vec![0u32]),
166 ("alpha/common".to_string(), vec![0u32, 1, 2, 3]),
168 ("beta/common".to_string(), vec![4, 5, 6, 7]),
169 ]);
170 let ix: InfonIndex<RoarPostings> = InfonIndex::from_postings(raw, 8);
171 let r = report(&ix, &["src"]);
172 let by = |n: &str| r.facets.iter().find(|f| f.facet == n).unwrap().clone();
173 assert!(by("alpha").maxcos < 1.0, "rare overlap must not saturate: {:?}", by("alpha"));
175 assert!(by("alpha").gain > 0.0, "both facets earn gain: {:?}", by("alpha"));
176 assert!(by("beta").gain > 0.0);
177 }
178
179 #[test]
180 fn gain_rewards_coverage_and_punishes_redundancy() {
181 let raw = HashMap::from([
184 ("country/japan".to_string(), vec![0u32, 1, 2, 3]),
185 ("nation/japan".to_string(), vec![0u32, 1, 2, 3]),
186 ("powertrain/electric".to_string(), vec![0, 2]),
187 ("powertrain/diesel".to_string(), vec![1, 3]),
188 ("rare/thing".to_string(), vec![0]),
189 ]);
190 let ix: InfonIndex<RoarPostings> = InfonIndex::from_postings(raw, 4);
191 let r = report(&ix, &["src"]);
192 eprintln!("{}", serde_json::to_string_pretty(&r).unwrap());
193 let by = |n: &str| r.facets.iter().find(|f| f.facet == n).unwrap().clone();
194 assert_eq!(by("country").maxcos, 1.0);
196 assert_eq!(by("country").nearest, "nation");
197 assert_eq!(by("country").gain, 0.0);
198 assert_eq!(by("powertrain").coverage, 1.0);
200 assert!(by("powertrain").gain > 0.0, "disjoint well-covered facet must earn gain");
201 assert_eq!(r.facets[0].facet, "powertrain", "best gain = broad coverage + low redundancy");
202 assert!(by("powertrain").maxcos < 1.0, "term-space cosine must not saturate for co-extensive facets");
203 assert!(by("rare").coverage <= 0.25);
205 assert!(by("rare").gain < by("powertrain").gain);
206 let failing: Vec<&str> = r.failing(0.1).iter().map(|f| f.facet.as_str()).collect();
208 assert!(failing.contains(&"country") && failing.contains(&"nation"));
209 }
210}