use super::Emitted;
use crate::types::{AggregateTriple, Conflict, ConflictKind, Polarity, TripleCandidate};
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, HashMap};
pub fn aggregate(candidates: Vec<Emitted>) -> (Vec<AggregateTriple>, Vec<bool>) {
struct Evidence {
confidence: f32,
spans: Vec<[usize; 2]>,
rules: Vec<String>,
single_filler: bool,
}
let mut merged: BTreeMap<(String, String, String, Polarity), Evidence> = BTreeMap::new();
for Emitted {
candidate,
polarity,
single_filler,
} in candidates
{
let TripleCandidate {
subject,
relation,
object,
confidence,
span,
rule,
} = candidate;
match merged.entry((subject, relation, object, polarity)) {
Entry::Occupied(mut entry) => {
let entry = entry.get_mut();
entry.confidence = entry.confidence.max(confidence);
entry.spans.push(span);
entry.single_filler &= single_filler;
if !entry.rules.contains(&rule) {
entry.rules.push(rule);
}
}
Entry::Vacant(entry) => {
entry.insert(Evidence {
confidence,
spans: vec![span],
rules: vec![rule],
single_filler,
});
}
}
}
let mut aggregates: Vec<(AggregateTriple, bool)> = merged
.into_iter()
.map(|((subject, relation, object, polarity), evidence)| {
(
AggregateTriple {
subject,
relation,
object,
polarity,
confidence: evidence.confidence,
spans: evidence.spans,
rules: evidence.rules,
},
evidence.single_filler,
)
})
.collect();
sort_by_first_span(&mut aggregates);
aggregates.into_iter().unzip()
}
pub fn find_conflicts(aggregates: &[AggregateTriple], single_filler: &[bool]) -> Vec<Conflict> {
debug_assert_eq!(aggregates.len(), single_filler.len());
let mut by_fact: HashMap<(&str, &str, &str), Vec<usize>> = HashMap::new();
let mut by_slot: HashMap<(&str, &str), Vec<usize>> = HashMap::new();
for (i, a) in aggregates.iter().enumerate() {
by_fact
.entry((&a.subject, &a.relation, &a.object))
.or_default()
.push(i);
if a.polarity == Polarity::Asserted && single_filler[i] {
by_slot.entry((&a.relation, &a.object)).or_default().push(i);
}
}
let mut pairs: Vec<(usize, usize, ConflictKind)> = Vec::new();
for group in by_fact.values() {
for (n, &i) in group.iter().enumerate() {
for &j in &group[n + 1..] {
if aggregates[i].polarity != aggregates[j].polarity {
pairs.push((i, j, ConflictKind::Denial));
}
}
}
}
for group in by_slot.values() {
for (n, &i) in group.iter().enumerate() {
for &j in &group[n + 1..] {
pairs.push((i, j, ConflictKind::Cardinality));
}
}
}
pairs.sort_unstable_by_key(|&(i, j, _)| (i, j));
pairs
.into_iter()
.map(|(i, j, kind)| Conflict {
kind,
left: aggregates[i].clone(),
right: aggregates[j].clone(),
})
.collect()
}
fn sort_by_first_span(aggregates: &mut [(AggregateTriple, bool)]) {
aggregates.sort_by(|(a, _), (b, _)| {
a.spans[0].cmp(&b.spans[0]).then_with(|| {
(&a.subject, &a.relation, &a.object, a.polarity).cmp(&(
&b.subject,
&b.relation,
&b.object,
b.polarity,
))
})
});
}