use std::fmt;
use std::num::NonZeroUsize;
use std::ops::Range;
use crate::error::{Error, Result};
use crate::morpheme::Morpheme;
use crate::sentence::Sentence;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Count {
pub correct: usize,
pub total: usize,
}
impl Count {
fn add(&mut self, correct: bool) {
self.total += 1;
if correct {
self.correct += 1;
}
}
pub fn ratio(&self) -> Option<f64> {
ratio(self.correct, self.total)
}
}
impl fmt::Display for Count {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} ({}/{})",
Percent(self.ratio()),
self.correct,
self.total
)
}
}
fn ratio(part: usize, whole: usize) -> Option<f64> {
(whole > 0).then(|| part as f64 / whole as f64)
}
struct Percent(Option<f64>);
impl fmt::Display for Percent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
Some(ratio) => write!(f, "{:.2}%", 100.0 * ratio),
None => f.write_str("n/a"),
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Chunking {
pub correct: usize,
pub system: usize,
pub gold: usize,
pub sentences: Count,
}
impl Chunking {
pub fn precision(&self) -> Option<f64> {
ratio(self.correct, self.system)
}
pub fn recall(&self) -> Option<f64> {
ratio(self.correct, self.gold)
}
pub fn f_score(&self) -> Option<f64> {
let precision = self.precision()?;
let recall = self.recall()?;
if precision + recall == 0.0 {
Some(0.0)
} else {
Some(2.0 * precision * recall / (precision + recall))
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Dependency {
pub level0: Count,
pub level1: Count,
pub level2: Count,
pub sentences: Count,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct EndToEnd {
pub arcs: Count,
pub sentences: Count,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Evaluation {
pub sentences: usize,
pub different: Vec<usize>,
pub without_bunsetsu: usize,
pub chunking: Chunking,
pub dependency: Dependency,
pub end_to_end: EndToEnd,
}
impl fmt::Display for Evaluation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "sentences: {}", self.sentences)?;
writeln!(
f,
"left out, different morphemes: {}{}",
self.different.len(),
Numbers(&self.different)
)?;
writeln!(f, "not counted, no bunsetsu: {}", self.without_bunsetsu)?;
let chunking = &self.chunking;
writeln!(
f,
"chunking precision: {} ({}/{})",
Percent(chunking.precision()),
chunking.correct,
chunking.system
)?;
writeln!(
f,
"chunking recall: {} ({}/{})",
Percent(chunking.recall()),
chunking.correct,
chunking.gold
)?;
writeln!(f, "chunking F: {}", Percent(chunking.f_score()))?;
writeln!(f, "chunking sentences: {}", chunking.sentences)?;
writeln!(f, "dependency level 0: {}", self.dependency.level0)?;
writeln!(f, "dependency level 1: {}", self.dependency.level1)?;
writeln!(f, "dependency level 2: {}", self.dependency.level2)?;
writeln!(f, "dependency sentences: {}", self.dependency.sentences)?;
writeln!(f, "end to end: {}", self.end_to_end.arcs)?;
write!(f, "end to end sentences: {}", self.end_to_end.sentences)
}
}
struct Numbers<'a>(&'a [usize]);
impl fmt::Display for Numbers<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
const SHOWN: usize = 10;
if self.0.is_empty() {
return Ok(());
}
f.write_str(" (sentences ")?;
for (index, number) in self.0.iter().take(SHOWN).enumerate() {
if index > 0 {
f.write_str(", ")?;
}
write!(f, "{number}")?;
}
if self.0.len() > SHOWN {
write!(f, " and {} more", self.0.len() - SHOWN)?;
}
f.write_str(")")
}
}
struct Outcome {
arcs: Vec<bool>,
segmentation: bool,
sentence: bool,
}
pub fn evaluate<G: Morpheme, S: Morpheme>(
gold: &[Sentence<G>],
system: &[Sentence<S>],
) -> Result<Evaluation> {
let mut evaluation = Evaluation::default();
evaluate_into(&mut evaluation, gold, system)?;
Ok(evaluation)
}
fn evaluate_into<G: Morpheme, S: Morpheme>(
evaluation: &mut Evaluation,
gold: &[Sentence<G>],
system: &[Sentence<S>],
) -> Result<Vec<Option<Outcome>>> {
if gold.len() != system.len() {
return Err(Error::Evaluation(format!(
"the answer has {} sentences and the output {}",
gold.len(),
system.len()
)));
}
let mut outcomes = Vec::with_capacity(gold.len());
for (index, (gold, system)) in gold.iter().zip(system).enumerate() {
gold.check()?;
system.check()?;
evaluation.sentences += 1;
if !same_morphemes(gold, system) {
evaluation.different.push(index + 1);
outcomes.push(None);
continue;
}
if gold.bunsetsu.is_empty() {
evaluation.without_bunsetsu += 1;
outcomes.push(None);
continue;
}
outcomes.push(Some(evaluate_sentence(evaluation, gold, system)));
}
Ok(outcomes)
}
fn same_morphemes<G: Morpheme, S: Morpheme>(gold: &Sentence<G>, system: &Sentence<S>) -> bool {
gold.morphemes.len() == system.morphemes.len()
&& gold
.morphemes
.iter()
.zip(&system.morphemes)
.all(|(gold, system)| gold.surface() == system.surface())
}
fn evaluate_sentence<G, S>(
evaluation: &mut Evaluation,
gold: &Sentence<G>,
system: &Sentence<S>,
) -> Outcome {
let gold = &gold.bunsetsu;
let system = &system.bunsetsu;
let chunking = &mut evaluation.chunking;
chunking.system += system.len();
chunking.gold += gold.len();
let (mut system_index, mut gold_index) = (0, 0);
let mut correct = 0;
while system_index < system.len() && gold_index < gold.len() {
let system_span = &system[system_index].morphemes;
let gold_span = &gold[gold_index].morphemes;
if system_span.start == gold_span.start {
if system_span.end == gold_span.end {
correct += 1;
}
system_index += 1;
gold_index += 1;
} else if system_span.start < gold_span.start {
system_index += 1;
} else {
gold_index += 1;
}
}
chunking.correct += correct;
let same_segmentation = correct == gold.len();
chunking.sentences.add(same_segmentation);
let mut every_head = same_segmentation;
if same_segmentation {
let dependency = &mut evaluation.dependency;
let count = gold.len();
for (index, (gold, system)) in gold.iter().zip(system).enumerate() {
let right = gold.head == system.head;
every_head &= right;
dependency.level0.add(right);
if index + 1 < count {
dependency.level1.add(right);
}
if index + 2 < count {
dependency.level2.add(right);
}
}
dependency.sentences.add(every_head);
}
let span_of_head = |bunsetsu: &[crate::Bunsetsu], index: usize| -> Option<Range<usize>> {
bunsetsu[index]
.head
.map(|head| bunsetsu[head].morphemes.clone())
};
let mut arcs = Vec::with_capacity(gold.len().saturating_sub(1));
for (index, bunsetsu) in gold.iter().enumerate().take(gold.len() - 1) {
let right = system
.binary_search_by_key(&bunsetsu.morphemes.start, |other| other.morphemes.start)
.is_ok_and(|found| {
system[found].morphemes == bunsetsu.morphemes
&& span_of_head(system, found) == span_of_head(gold, index)
});
evaluation.end_to_end.arcs.add(right);
arcs.push(right);
}
evaluation.end_to_end.sentences.add(every_head);
Outcome {
arcs,
segmentation: same_segmentation,
sentence: every_head,
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Pairs {
pub both: usize,
pub first_only: usize,
pub second_only: usize,
pub neither: usize,
}
impl Pairs {
fn add(&mut self, first: bool, second: bool) {
match (first, second) {
(true, true) => self.both += 1,
(true, false) => self.first_only += 1,
(false, true) => self.second_only += 1,
(false, false) => self.neither += 1,
}
}
pub fn p_value(&self) -> f64 {
mcnemar_exact(self.first_only, self.second_only)
}
}
impl fmt::Display for Pairs {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"both {}, first only {}, second only {}, neither {}, McNemar p = {:.4}",
self.both,
self.first_only,
self.second_only,
self.neither,
self.p_value()
)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Comparison {
pub first: Evaluation,
pub second: Evaluation,
pub segmentations: Pairs,
pub arcs: Pairs,
pub sentences: Pairs,
}
impl fmt::Display for Comparison {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "first output\n{}\n", self.first)?;
writeln!(f, "second output\n{}\n", self.second)?;
writeln!(f, "paired segmentations: {}", self.segmentations)?;
writeln!(f, "paired arcs: {}", self.arcs)?;
write!(f, "paired sentences: {}", self.sentences)
}
}
pub fn compare<G: Morpheme, A: Morpheme, B: Morpheme>(
gold: &[Sentence<G>],
first: &[Sentence<A>],
second: &[Sentence<B>],
) -> Result<Comparison> {
let mut comparison = Comparison::default();
let first = evaluate_into(&mut comparison.first, gold, first)?;
let second = evaluate_into(&mut comparison.second, gold, second)?;
for (first, second) in first.iter().zip(&second) {
let (Some(first), Some(second)) = (first, second) else {
continue;
};
for (&first, &second) in first.arcs.iter().zip(&second.arcs) {
comparison.arcs.add(first, second);
}
comparison
.segmentations
.add(first.segmentation, second.segmentation);
comparison.sentences.add(first.sentence, second.sentence);
}
Ok(comparison)
}
pub fn mcnemar_exact(first_only: usize, second_only: usize) -> f64 {
let pairs = first_only + second_only;
let smaller = first_only.min(second_only);
let mut term = -(pairs as f64) * std::f64::consts::LN_2;
let mut tail = 0.0;
for index in 0..=smaller {
tail += term.exp();
term += ((pairs - index) as f64).ln() - ((index + 1) as f64).ln();
}
(2.0 * tail).min(1.0)
}
pub fn fold_of(index: usize, folds: NonZeroUsize) -> usize {
index % folds
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sentence::Bunsetsu;
struct Word(&'static str);
impl Morpheme for Word {
fn surface(&self) -> &str {
self.0
}
fn feature(&self, _index: usize) -> Option<&str> {
None
}
}
fn sentence(surfaces: &[&'static str], bunsetsu: &[(usize, Option<usize>)]) -> Sentence<Word> {
let mut start = 0;
let bunsetsu = bunsetsu
.iter()
.map(|&(length, head)| {
let bunsetsu = Bunsetsu::new(start..start + length, head);
start += length;
bunsetsu
})
.collect();
Sentence::new(
surfaces.iter().map(|&surface| Word(surface)).collect(),
bunsetsu,
)
.unwrap()
}
fn count(correct: usize, total: usize) -> Count {
Count { correct, total }
}
const ABCD: &[&str] = &["a", "b", "c", "d"];
fn one(gold: Sentence<Word>, system: Sentence<Word>) -> Evaluation {
evaluate(&[gold], &[system]).unwrap()
}
#[test]
fn an_output_equal_to_the_answer_is_right_everywhere() {
let heads = [(1, Some(1)), (1, Some(3)), (1, Some(3)), (1, None)];
let evaluation = one(sentence(ABCD, &heads), sentence(ABCD, &heads));
assert_eq!(
evaluation,
Evaluation {
sentences: 1,
different: Vec::new(),
without_bunsetsu: 0,
chunking: Chunking {
correct: 4,
system: 4,
gold: 4,
sentences: count(1, 1),
},
dependency: Dependency {
level0: count(4, 4),
level1: count(3, 3),
level2: count(2, 2),
sentences: count(1, 1),
},
end_to_end: EndToEnd {
arcs: count(3, 3),
sentences: count(1, 1),
},
}
);
assert_eq!(evaluation.chunking.precision(), Some(1.0));
assert_eq!(evaluation.chunking.recall(), Some(1.0));
assert_eq!(evaluation.chunking.f_score(), Some(1.0));
}
#[test]
fn a_bunsetsu_split_in_two() {
let gold = sentence(ABCD, &[(1, Some(1)), (2, Some(2)), (1, None)]);
let system = sentence(ABCD, &[(1, Some(1)), (1, Some(2)), (1, Some(3)), (1, None)]);
let evaluation = one(gold, system);
assert_eq!(
evaluation.chunking,
Chunking {
correct: 2,
system: 4,
gold: 3,
sentences: count(0, 1),
}
);
assert_eq!(evaluation.chunking.precision(), Some(0.5));
assert_eq!(evaluation.chunking.recall(), Some(2.0 / 3.0));
let f_score = evaluation.chunking.f_score().unwrap();
assert!((f_score - 4.0 / 7.0).abs() < 1e-12, "{f_score}");
assert_eq!(evaluation.dependency, Dependency::default());
assert_eq!(
evaluation.end_to_end,
EndToEnd {
arcs: count(0, 2),
sentences: count(0, 1),
}
);
}
#[test]
fn as_many_bunsetsu_with_other_boundaries() {
let gold = sentence(ABCD, &[(1, Some(1)), (2, Some(2)), (1, None)]);
let system = sentence(ABCD, &[(2, Some(1)), (1, Some(2)), (1, None)]);
let evaluation = one(gold, system);
assert_eq!(
evaluation.chunking,
Chunking {
correct: 1,
system: 3,
gold: 3,
sentences: count(0, 1),
}
);
assert_eq!(evaluation.dependency, Dependency::default());
assert_eq!(
evaluation.end_to_end,
EndToEnd {
arcs: count(0, 2),
sentences: count(0, 1),
}
);
}
#[test]
fn a_bunsetsu_of_another_length_is_wrong_even_with_the_right_head() {
let gold = sentence(ABCD, &[(1, Some(2)), (2, Some(2)), (1, None)]);
let system = sentence(ABCD, &[(1, Some(3)), (1, Some(3)), (1, Some(3)), (1, None)]);
let evaluation = one(gold, system);
assert_eq!(
evaluation.end_to_end,
EndToEnd {
arcs: count(1, 2),
sentences: count(0, 1),
}
);
}
#[test]
fn two_bunsetsu_merged_into_one() {
let gold = sentence(ABCD, &[(1, Some(3)), (1, Some(2)), (1, Some(3)), (1, None)]);
let system = sentence(ABCD, &[(1, Some(2)), (2, Some(2)), (1, None)]);
let evaluation = one(gold, system);
assert_eq!(
evaluation.chunking,
Chunking {
correct: 2,
system: 3,
gold: 4,
sentences: count(0, 1),
}
);
assert_eq!(evaluation.dependency, Dependency::default());
assert_eq!(
evaluation.end_to_end,
EndToEnd {
arcs: count(1, 3),
sentences: count(0, 1),
}
);
}
#[test]
fn a_wrong_head_with_the_same_segmentation() {
let gold = sentence(ABCD, &[(1, Some(1)), (1, Some(3)), (1, Some(3)), (1, None)]);
let system = sentence(ABCD, &[(1, Some(1)), (1, Some(2)), (1, Some(3)), (1, None)]);
let evaluation = one(gold, system);
assert_eq!(evaluation.chunking.correct, 4);
assert_eq!(evaluation.chunking.sentences, count(1, 1));
assert_eq!(
evaluation.dependency,
Dependency {
level0: count(3, 4),
level1: count(2, 3),
level2: count(1, 2),
sentences: count(0, 1),
}
);
assert_eq!(
evaluation.end_to_end,
EndToEnd {
arcs: count(2, 3),
sentences: count(0, 1),
}
);
}
#[test]
fn the_last_and_the_last_but_one_bunsetsu_at_each_level() {
let gold = || sentence(ABCD, &[(1, Some(1)), (1, Some(3)), (1, Some(3)), (1, None)]);
let system = sentence(ABCD, &[(1, Some(1)), (1, Some(3)), (1, None), (1, None)]);
let evaluation = one(gold(), system);
assert_eq!(
evaluation.dependency,
Dependency {
level0: count(3, 4),
level1: count(2, 3),
level2: count(2, 2),
sentences: count(0, 1),
}
);
assert_eq!(evaluation.end_to_end.arcs, count(2, 3));
let system = sentence(
ABCD,
&[(1, Some(1)), (1, Some(3)), (1, Some(3)), (1, Some(0))],
);
let evaluation = one(gold(), system);
assert_eq!(
evaluation.dependency,
Dependency {
level0: count(3, 4),
level1: count(3, 3),
level2: count(2, 2),
sentences: count(0, 1),
}
);
assert_eq!(
evaluation.end_to_end,
EndToEnd {
arcs: count(3, 3),
sentences: count(0, 1),
}
);
}
#[test]
fn a_sentence_of_one_bunsetsu() {
let evaluation = one(
sentence(&["a", "b"], &[(2, None)]),
sentence(&["a", "b"], &[(2, None)]),
);
assert_eq!(
evaluation.chunking,
Chunking {
correct: 1,
system: 1,
gold: 1,
sentences: count(1, 1),
}
);
assert_eq!(
evaluation.dependency,
Dependency {
level0: count(1, 1),
level1: count(0, 0),
level2: count(0, 0),
sentences: count(1, 1),
}
);
assert_eq!(
evaluation.end_to_end,
EndToEnd {
arcs: count(0, 0),
sentences: count(1, 1),
}
);
assert_eq!(evaluation.dependency.level1.ratio(), None);
let evaluation = one(
sentence(&["a", "b"], &[(2, None)]),
sentence(&["a", "b"], &[(1, Some(1)), (1, None)]),
);
assert_eq!(
evaluation.chunking,
Chunking {
correct: 0,
system: 2,
gold: 1,
sentences: count(0, 1),
}
);
assert_eq!(evaluation.chunking.f_score(), Some(0.0));
assert_eq!(evaluation.dependency, Dependency::default());
assert_eq!(
evaluation.end_to_end,
EndToEnd {
arcs: count(0, 0),
sentences: count(0, 1),
}
);
}
#[test]
fn a_sentence_of_two_bunsetsu_is_at_level_1_and_not_at_level_2() {
let evaluation = one(
sentence(&["a", "b"], &[(1, Some(1)), (1, None)]),
sentence(&["a", "b"], &[(1, Some(1)), (1, None)]),
);
assert_eq!(
evaluation.dependency,
Dependency {
level0: count(2, 2),
level1: count(1, 1),
level2: count(0, 0),
sentences: count(1, 1),
}
);
}
#[test]
fn sentences_add_up() {
let gold = [
sentence(ABCD, &[(1, Some(1)), (1, Some(3)), (1, Some(3)), (1, None)]),
sentence(&["a", "b"], &[(1, Some(1)), (1, None)]),
];
let system = [
sentence(ABCD, &[(1, Some(1)), (1, Some(2)), (1, Some(3)), (1, None)]),
sentence(&["a", "b"], &[(1, Some(1)), (1, None)]),
];
let evaluation = evaluate(&gold, &system).unwrap();
assert_eq!(evaluation.sentences, 2);
assert_eq!(
evaluation.dependency,
Dependency {
level0: count(5, 6),
level1: count(3, 4),
level2: count(1, 2),
sentences: count(1, 2),
}
);
assert_eq!(
evaluation.end_to_end,
EndToEnd {
arcs: count(3, 4),
sentences: count(1, 2),
}
);
assert_eq!(evaluation.chunking.sentences, count(2, 2));
}
#[test]
fn a_sentence_with_different_morphemes_is_reported_and_not_counted() {
let gold = [
sentence(&["a", "b"], &[(1, Some(1)), (1, None)]),
sentence(&["a", "b"], &[(1, Some(1)), (1, None)]),
sentence(&["a", "b"], &[(1, Some(1)), (1, None)]),
sentence(&["a", "b"], &[(1, Some(1)), (1, None)]),
];
let system = [
sentence(&["a", "b"], &[(1, Some(1)), (1, None)]),
sentence(&["a", "x"], &[(1, Some(1)), (1, None)]),
sentence(&["ab"], &[(1, None)]),
sentence(&["a", "b", "c"], &[(1, Some(1)), (2, None)]),
];
let evaluation = evaluate(&gold, &system).unwrap();
assert_eq!(evaluation.sentences, 4);
assert_eq!(evaluation.different, [2, 3, 4]);
assert_eq!(evaluation.chunking.gold, 2);
assert_eq!(evaluation.chunking.system, 2);
assert_eq!(evaluation.chunking.sentences, count(1, 1));
assert_eq!(evaluation.dependency.level0, count(2, 2));
assert_eq!(evaluation.end_to_end.sentences, count(1, 1));
}
#[test]
fn a_sentence_without_bunsetsu_in_the_answer_is_not_counted() {
let gold = [sentence(&["a", "b"], &[])];
let system = [sentence(&["a", "b"], &[(1, Some(1)), (1, None)])];
let evaluation = evaluate(&gold, &system).unwrap();
assert_eq!(
evaluation,
Evaluation {
sentences: 1,
without_bunsetsu: 1,
..Evaluation::default()
}
);
let evaluation = one(
sentence(&["a", "b"], &[(1, Some(1)), (1, None)]),
sentence(&["a", "b"], &[]),
);
assert_eq!(
evaluation.chunking,
Chunking {
correct: 0,
system: 0,
gold: 2,
sentences: count(0, 1),
}
);
assert_eq!(evaluation.chunking.precision(), None);
assert_eq!(evaluation.chunking.f_score(), None);
assert_eq!(evaluation.end_to_end.arcs, count(0, 1));
}
#[test]
fn files_of_different_lengths_and_broken_sentences_are_errors() {
let gold = [sentence(&["a"], &[(1, None)])];
let system: [Sentence<Word>; 0] = [];
let error = evaluate(&gold, &system).unwrap_err();
assert_eq!(
error.to_string(),
"the answer has 1 sentences and the output 0"
);
let mut broken = sentence(&["a"], &[(1, None)]);
broken.bunsetsu[0].head = Some(5);
let error = evaluate(&gold, std::slice::from_ref(&broken)).unwrap_err();
assert!(matches!(error, Error::Structure(_)), "{error}");
let error = evaluate(std::slice::from_ref(&broken), &gold).unwrap_err();
assert!(matches!(error, Error::Structure(_)), "{error}");
}
#[test]
fn two_outputs_are_paired_arc_by_arc_and_sentence_by_sentence() {
let chain = [(1, Some(1)), (1, Some(2)), (1, Some(3)), (1, None)];
let gold = [
sentence(ABCD, &chain),
sentence(ABCD, &chain),
sentence(&["a"], &[(1, None)]),
sentence(&["a", "b"], &[(1, Some(1)), (1, None)]),
sentence(&["a", "b"], &[(1, Some(1)), (1, None)]),
];
let first = [
sentence(ABCD, &[(1, Some(1)), (1, Some(3)), (1, Some(3)), (1, None)]),
sentence(ABCD, &[(1, Some(2)), (1, Some(3)), (1, Some(3)), (1, None)]),
sentence(&["a"], &[(1, None)]),
sentence(&["a", "b"], &[(1, Some(1)), (1, None)]),
sentence(&["a", "b"], &[(1, Some(1)), (1, None)]),
];
let second = [
sentence(ABCD, &[(1, Some(2)), (1, Some(2)), (1, Some(3)), (1, None)]),
sentence(ABCD, &[(1, Some(3)), (1, Some(3)), (1, Some(3)), (1, None)]),
sentence(&["a"], &[(1, None)]),
sentence(&["a", "b"], &[(1, None), (1, None)]),
sentence(&["a", "x"], &[(1, Some(1)), (1, None)]),
];
let comparison = compare(&gold, &first, &second).unwrap();
assert_eq!(
comparison.arcs,
Pairs {
both: 2,
first_only: 2,
second_only: 1,
neither: 2,
}
);
assert_eq!(
comparison.sentences,
Pairs {
both: 1,
first_only: 1,
second_only: 0,
neither: 2,
}
);
assert_eq!(
comparison.segmentations,
Pairs {
both: 4,
..Pairs::default()
}
);
assert_eq!(comparison.first.different, Vec::<usize>::new());
assert_eq!(comparison.second.different, [5]);
assert_eq!(comparison.first.end_to_end.arcs, count(5, 8));
assert_eq!(comparison.second.end_to_end.arcs, count(3, 7));
assert_eq!(comparison.first, evaluate(&gold, &first).unwrap());
assert_eq!(comparison.second, evaluate(&gold, &second).unwrap());
assert!((comparison.arcs.p_value() - 1.0).abs() < 1e-12);
assert!((comparison.sentences.p_value() - 1.0).abs() < 1e-12);
}
#[test]
fn segmentations_are_paired_whatever_the_heads() {
let chain = [(1, Some(1)), (1, Some(2)), (1, Some(3)), (1, None)];
let merged = [(1, Some(1)), (2, Some(2)), (1, None)];
let other_heads = [(1, Some(3)), (1, Some(3)), (1, Some(3)), (1, None)];
let gold = [
sentence(ABCD, &chain),
sentence(ABCD, &chain),
sentence(ABCD, &chain),
sentence(ABCD, &chain),
];
let first = [
sentence(ABCD, &other_heads),
sentence(ABCD, &chain),
sentence(ABCD, &merged),
sentence(ABCD, &merged),
];
let second = [
sentence(ABCD, &chain),
sentence(ABCD, &merged),
sentence(ABCD, &other_heads),
sentence(ABCD, &merged),
];
let comparison = compare(&gold, &first, &second).unwrap();
assert_eq!(
comparison.segmentations,
Pairs {
both: 1,
first_only: 1,
second_only: 1,
neither: 1,
}
);
assert_eq!(
comparison.sentences,
Pairs {
both: 0,
first_only: 1,
second_only: 1,
neither: 2,
}
);
}
#[test]
fn mcnemar_exact_gives_the_values_computed_by_hand() {
let close = |value: f64, expected: f64| (value - expected).abs() < 1e-12;
assert_eq!(mcnemar_exact(0, 0), 1.0);
assert!(close(mcnemar_exact(1, 0), 1.0));
assert_eq!(mcnemar_exact(3, 3), 1.0);
assert!(close(mcnemar_exact(5, 0), 0.0625));
assert!(close(mcnemar_exact(0, 5), 0.0625));
assert!(close(mcnemar_exact(10, 2), 158.0 / 4096.0));
assert!(close(mcnemar_exact(2, 10), 158.0 / 4096.0));
assert!(close(mcnemar_exact(7, 1), 18.0 / 256.0));
}
#[test]
fn mcnemar_exact_holds_for_large_counts() {
assert_eq!(mcnemar_exact(20_000, 20_000), 1.0);
let p_value = mcnemar_exact(30_000, 10_000);
assert!((0.0..1e-300).contains(&p_value), "{p_value}");
let p_value = mcnemar_exact(5_100, 4_900);
assert!((0.044..0.049).contains(&p_value), "{p_value}");
}
#[test]
fn folds_take_the_sentences_in_turn() {
let three = NonZeroUsize::new(3).unwrap();
let folds: Vec<usize> = (0..7).map(|index| fold_of(index, three)).collect();
assert_eq!(folds, [0, 1, 2, 0, 1, 2, 0]);
let one = NonZeroUsize::new(1).unwrap();
assert_eq!(fold_of(41, one), 0);
}
#[test]
fn an_evaluation_is_written_line_by_line() {
let evaluation = Evaluation {
sentences: 14,
different: (1..=12).collect(),
without_bunsetsu: 1,
chunking: Chunking {
correct: 9,
system: 10,
gold: 12,
sentences: count(0, 1),
},
dependency: Dependency {
level0: count(3, 4),
level1: count(2, 3),
level2: count(1, 2),
sentences: count(0, 0),
},
end_to_end: EndToEnd {
arcs: count(1, 8),
sentences: count(0, 1),
},
};
assert_eq!(
evaluation.to_string(),
"\
sentences: 14
left out, different morphemes: 12 (sentences 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 and 2 more)
not counted, no bunsetsu: 1
chunking precision: 90.00% (9/10)
chunking recall: 75.00% (9/12)
chunking F: 81.82%
chunking sentences: 0.00% (0/1)
dependency level 0: 75.00% (3/4)
dependency level 1: 66.67% (2/3)
dependency level 2: 50.00% (1/2)
dependency sentences: n/a (0/0)
end to end: 12.50% (1/8)
end to end sentences: 0.00% (0/1)"
);
assert_eq!(
Evaluation::default().to_string().lines().nth(1),
Some("left out, different morphemes: 0")
);
}
#[test]
fn a_comparison_is_written_with_its_pairs() {
let comparison = Comparison {
segmentations: Pairs {
both: 7,
first_only: 1,
second_only: 3,
neither: 0,
},
arcs: Pairs {
both: 80,
first_only: 10,
second_only: 2,
neither: 8,
},
sentences: Pairs {
both: 5,
first_only: 5,
second_only: 0,
neither: 1,
},
..Comparison::default()
};
let text = comparison.to_string();
assert!(text.starts_with("first output\nsentences: 0\n"), "{text}");
assert!(text.contains("\n\nsecond output\nsentences: 0\n"), "{text}");
assert!(
text.ends_with(
"paired segmentations: both 7, first only 1, second only 3, neither 0, McNemar p = 0.6250\n\
paired arcs: both 80, first only 10, second only 2, neither 8, McNemar p = 0.0386\n\
paired sentences: both 5, first only 5, second only 0, neither 1, McNemar p = 0.0625"
),
"{text}"
);
}
}