lindera-dependency 7.1.0

Japanese bunsetsu dependency analysis for Lindera.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! From the word dependencies of UD to bunsetsu dependencies.
//!
//! UD Japanese-GSD was annotated by bunsetsu and converted to words by head
//! rules; this undoes the conversion.
//!
//! 1. A word with `BunsetuBILabel=B` starts a bunsetsu.
//! 2. In each bunsetsu, the word whose head is outside the bunsetsu gives
//!    the head of the bunsetsu: the bunsetsu of that head.
//! 3. The bunsetsu with the word whose head is the root is the root.
//! 4. Coordination is put back. UD attaches every later conjunct to the
//!    first one, with an arc to the left; the Kyoto corpus and CaboCha make
//!    each conjunct depend on the next, and the last one on the head of the
//!    whole.
//! 5. A sentence that is not the tree the parsers assume is dropped.

use std::ops::Range;

use super::DropCause;
use super::conllu::UdSentence;
use crate::sentence::{ArcType, Violation, tree_violations};

/// The relation of a conjunct to the first conjunct in UD.
const CONJ: &str = "conj";

/// A bunsetsu over the words of a UD sentence.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UdBunsetsu {
    /// The words of the bunsetsu, as a range of indices into the words of
    /// the sentence.
    pub words: Range<usize>,
    /// The index of the bunsetsu this one depends on, or `None` for the
    /// root.
    pub head: Option<usize>,
    /// The type of the arc to the head: [`ArcType::Parallel`] between
    /// conjuncts, [`ArcType::Dependency`] elsewhere.
    pub arc_type: ArcType,
    /// The content head of the bunsetsu, as an index into the words of the
    /// sentence: its one word with `BunsetuPositionType=SEM_HEAD` or
    /// `ROOT`. `None` when the bunsetsu has no such word or more than one.
    pub content_head: Option<usize>,
}

/// The bunsetsu dependencies of a UD sentence: a tree as the parsers assume.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BunsetsuTree {
    /// The bunsetsu, from left to right.
    pub bunsetsu: Vec<UdBunsetsu>,
    /// The number of bunsetsu with more than one word whose head is outside
    /// the bunsetsu. The last such word gave the head.
    pub ambiguous_heads: usize,
}

/// Converts the word dependencies of a UD sentence to bunsetsu dependencies.
///
/// # Arguments
///
/// * `sentence` - The sentence.
///
/// # Returns
///
/// The tree, or the causes for which the sentence is dropped, each once:
/// [`DropCause::Bunsetsu`] when the first word does not start a bunsetsu or
/// a bunsetsu has no word whose head is outside it, and otherwise every way
/// the result is not a tree ([`DropCause::Root`],
/// [`DropCause::HeadToTheLeft`], [`DropCause::CrossingArcs`]).
pub fn to_bunsetsu(sentence: &UdSentence) -> Result<BunsetsuTree, Vec<DropCause>> {
    let words = &sentence.words;

    // Step 1: the bunsetsu, and the bunsetsu of each word.
    if !words.first().is_some_and(|word| word.starts_bunsetsu) {
        return Err(vec![DropCause::Bunsetsu]);
    }
    let mut ranges: Vec<Range<usize>> = Vec::new();
    let mut bunsetsu_of = Vec::with_capacity(words.len());
    for (index, word) in words.iter().enumerate() {
        if word.starts_bunsetsu {
            if let Some(last) = ranges.last_mut() {
                last.end = index;
            }
            ranges.push(index..words.len());
        }
        bunsetsu_of.push(ranges.len() - 1);
    }
    let count = ranges.len();

    // Steps 2 and 3: the head of each bunsetsu, and the relation of the word
    // that gives it. `Some(None)` is the root.
    let mut heads: Vec<Option<Option<usize>>> = vec![None; count];
    let mut conjunct = vec![false; count];
    let mut ambiguous_heads = 0;
    for (index, word) in words.iter().enumerate() {
        let bunsetsu = bunsetsu_of[index];
        let head = match word.head {
            0 => None,
            head => Some(bunsetsu_of[head - 1]),
        };
        if head == Some(bunsetsu) {
            continue;
        }
        if heads[bunsetsu].is_some() {
            ambiguous_heads += 1;
        }
        heads[bunsetsu] = Some(head);
        conjunct[bunsetsu] = head.is_some() && word.deprel == CONJ;
    }
    let Some(heads) = heads.into_iter().collect::<Option<Vec<Option<usize>>>>() else {
        return Err(vec![DropCause::Bunsetsu]);
    };

    // Step 4.
    let (heads, arc_types) = restore_coordination(&heads, &conjunct);

    // Step 5.
    let causes = drop_causes(&heads);
    if !causes.is_empty() {
        return Err(causes);
    }

    let bunsetsu = ranges
        .into_iter()
        .zip(heads)
        .zip(arc_types)
        .map(|((range, head), arc_type)| {
            let mut content_heads = range.clone().filter(|&index| words[index].content_head);
            let content_head = match (content_heads.next(), content_heads.next()) {
                (Some(index), None) => Some(index),
                _ => None,
            };
            UdBunsetsu {
                words: range,
                head,
                arc_type,
                content_head,
            }
        })
        .collect();
    Ok(BunsetsuTree {
        bunsetsu,
        ambiguous_heads,
    })
}

/// Puts coordination back in the form of the Kyoto corpus.
///
/// For a bunsetsu `a` with the conjuncts `b` and `c`, in this order, and the
/// head `h`, the arcs `a → h`, `b → a`, `c → a` of UD become `a → b`,
/// `b → c`, `c → h`; a conjunct with conjuncts of its own is treated the
/// same way, before the next conjunct. The arcs between conjuncts get the
/// type [`ArcType::Parallel`].
///
/// # Arguments
///
/// * `heads` - The head of each bunsetsu, `None` for the root.
/// * `conjunct` - Whether each bunsetsu is a conjunct of its head.
///
/// # Returns
///
/// The new head and the arc type of each bunsetsu.
fn restore_coordination(
    heads: &[Option<usize>],
    conjunct: &[bool],
) -> (Vec<Option<usize>>, Vec<ArcType>) {
    let count = heads.len();
    let mut conjuncts: Vec<Vec<usize>> = vec![Vec::new(); count];
    for index in 0..count {
        if conjunct[index]
            && let Some(head) = heads[index]
        {
            conjuncts[head].push(index);
        }
    }

    let mut new_heads = heads.to_vec();
    let mut arc_types = vec![ArcType::Dependency; count];
    let mut seen = vec![false; count];
    // A stack instead of recursion: (bunsetsu, the head it gets when it has
    // no conjunct of its own, the type of that arc).
    let mut stack: Vec<(usize, Option<usize>, ArcType)> = (0..count)
        .rev()
        .filter(|&index| !conjunct[index])
        .map(|index| (index, heads[index], ArcType::Dependency))
        .collect();
    while let Some((index, target, arc_type)) = stack.pop() {
        // A conjunct is reached once, from its head. Conjuncts that depend
        // on each other in a cycle are never reached, and keep their heads.
        if seen[index] {
            continue;
        }
        seen[index] = true;
        let chain = &conjuncts[index];
        let Some(&first) = chain.first() else {
            new_heads[index] = target;
            arc_types[index] = arc_type;
            continue;
        };
        new_heads[index] = Some(first);
        arc_types[index] = ArcType::Parallel;
        for (position, &conjunct) in chain.iter().enumerate() {
            match chain.get(position + 1) {
                Some(&next) => stack.push((conjunct, Some(next), ArcType::Parallel)),
                None => stack.push((conjunct, target, arc_type)),
            }
        }
    }
    (new_heads, arc_types)
}

/// The causes for which bunsetsu with these heads are dropped.
///
/// # Arguments
///
/// * `heads` - The head of each bunsetsu, `None` for a root.
///
/// # Returns
///
/// [`DropCause::Root`], [`DropCause::HeadToTheLeft`] and
/// [`DropCause::CrossingArcs`], each at most once and in this order; none
/// for a tree as the parsers assume.
pub(super) fn drop_causes(heads: &[Option<usize>]) -> Vec<DropCause> {
    let mut causes = Vec::new();
    for violation in tree_violations(heads) {
        let cause = match violation {
            Violation::NoRoot | Violation::MultipleRoots { .. } | Violation::RootNotLast { .. } => {
                DropCause::Root
            }
            Violation::HeadNotToTheRight { .. } => DropCause::HeadToTheLeft,
            Violation::CrossingArcs { .. } => DropCause::CrossingArcs,
        };
        if !causes.contains(&cause) {
            causes.push(cause);
        }
    }
    causes.sort();
    causes
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::corpus::tests::{ud_sentence, with_content_heads};

    /// The heads and the arc types of the bunsetsu of a converted sentence,
    /// as `(head, letter)`.
    fn arcs(tree: &BunsetsuTree) -> Vec<(Option<usize>, char)> {
        tree.bunsetsu
            .iter()
            .map(|bunsetsu| (bunsetsu.head, bunsetsu.arc_type.as_char()))
            .collect()
    }

    #[test]
    fn groups_words_into_bunsetsu_and_takes_the_head_from_the_word_that_leaves() {
        // 彼 は | 本 を | 読ん だ
        let sentence = ud_sentence(&[
            ("彼", 5, "nsubj", true),
            ("は", 1, "case", false),
            ("本", 5, "obj", true),
            ("を", 3, "case", false),
            ("読ん", 0, "root", true),
            ("だ", 5, "aux", false),
        ]);
        let tree = to_bunsetsu(&sentence).unwrap();
        let words: Vec<Range<usize>> = tree
            .bunsetsu
            .iter()
            .map(|bunsetsu| bunsetsu.words.clone())
            .collect();
        assert_eq!(words, [0..2, 2..4, 4..6]);
        assert_eq!(arcs(&tree), [(Some(2), 'D'), (Some(2), 'D'), (None, 'D')]);
        assert_eq!(tree.ambiguous_heads, 0);
    }

    #[test]
    fn the_content_head_is_the_one_word_marked_in_the_bunsetsu() {
        // 彼 は | 本 を | 読ん だ
        let words = [
            ("彼", 5, "nsubj", true),
            ("は", 1, "case", false),
            ("本", 5, "obj", true),
            ("を", 3, "case", false),
            ("読ん", 0, "root", true),
            ("だ", 5, "aux", false),
        ];
        let content_heads = |marked: &[usize]| -> Vec<Option<usize>> {
            let sentence = with_content_heads(ud_sentence(&words), marked);
            to_bunsetsu(&sentence)
                .unwrap()
                .bunsetsu
                .iter()
                .map(|bunsetsu| bunsetsu.content_head)
                .collect()
        };
        // One word each: its index in the sentence, the first of the
        // bunsetsu or not.
        assert_eq!(content_heads(&[0, 3, 4]), [Some(0), Some(3), Some(4)]);
        // None in the second bunsetsu, two in the third.
        assert_eq!(content_heads(&[0, 4, 5]), [Some(0), None, None]);
        assert_eq!(content_heads(&[]), [None, None, None]);
    }

    #[test]
    fn two_conjuncts_become_a_chain() {
        // a と b を 読む: UD has b → a (conj) and a → 読む.
        let sentence = ud_sentence(&[
            ("a", 3, "obj", true),
            ("b", 1, "conj", true),
            ("読む", 0, "root", true),
        ]);
        let tree = to_bunsetsu(&sentence).unwrap();
        assert_eq!(arcs(&tree), [(Some(1), 'P'), (Some(2), 'D'), (None, 'D')]);
    }

    #[test]
    fn three_conjuncts_become_a_chain() {
        let sentence = ud_sentence(&[
            ("a", 4, "obj", true),
            ("b", 1, "conj", true),
            ("c", 1, "conj", true),
            ("読む", 0, "root", true),
        ]);
        let tree = to_bunsetsu(&sentence).unwrap();
        assert_eq!(
            arcs(&tree),
            [(Some(1), 'P'), (Some(2), 'P'), (Some(3), 'D'), (None, 'D')]
        );
    }

    #[test]
    fn nested_conjuncts_are_chained_before_the_next_conjunct() {
        // b and d are conjuncts of a; c is a conjunct of b:
        // a → b, b → c, c → d, d → 読む.
        let sentence = ud_sentence(&[
            ("a", 5, "obj", true),
            ("b", 1, "conj", true),
            ("c", 2, "conj", true),
            ("d", 1, "conj", true),
            ("読む", 0, "root", true),
        ]);
        let tree = to_bunsetsu(&sentence).unwrap();
        assert_eq!(
            arcs(&tree),
            [
                (Some(1), 'P'),
                (Some(2), 'P'),
                (Some(3), 'P'),
                (Some(4), 'D'),
                (None, 'D')
            ]
        );
    }

    #[test]
    fn the_last_conjunct_of_the_root_is_the_root() {
        // 読み、書く: UD has the first verb as the root.
        let sentence = ud_sentence(&[("読み", 0, "root", true), ("書く", 1, "conj", true)]);
        let tree = to_bunsetsu(&sentence).unwrap();
        assert_eq!(arcs(&tree), [(Some(1), 'P'), (None, 'D')]);
    }

    #[test]
    fn the_last_word_that_leaves_the_bunsetsu_gives_the_head() {
        // ( 細かい | 字 | 読む: both words of the first bunsetsu leave it.
        let sentence = ud_sentence(&[
            ("(", 4, "punct", true),
            ("細かい", 3, "acl", false),
            ("字", 4, "obj", true),
            ("読む", 0, "root", true),
        ]);
        let tree = to_bunsetsu(&sentence).unwrap();
        assert_eq!(arcs(&tree), [(Some(1), 'D'), (Some(2), 'D'), (None, 'D')]);
        assert_eq!(tree.ambiguous_heads, 1);
    }

    #[test]
    fn drops_a_sentence_whose_first_word_starts_no_bunsetsu() {
        let sentence = ud_sentence(&[("彼", 2, "nsubj", false), ("読む", 0, "root", true)]);
        assert_eq!(to_bunsetsu(&sentence), Err(vec![DropCause::Bunsetsu]));
        assert_eq!(
            to_bunsetsu(&ud_sentence(&[])),
            Err(vec![DropCause::Bunsetsu])
        );
    }

    #[test]
    fn drops_a_sentence_with_a_bunsetsu_no_word_leaves() {
        // The two words of the first bunsetsu depend on each other.
        let sentence = ud_sentence(&[
            ("彼", 2, "dep", true),
            ("は", 1, "dep", false),
            ("読む", 0, "root", true),
        ]);
        assert_eq!(to_bunsetsu(&sentence), Err(vec![DropCause::Bunsetsu]));
    }

    #[test]
    fn drops_a_sentence_whose_root_is_not_the_last_bunsetsu() {
        let sentence = ud_sentence(&[("読む", 0, "root", true), ("彼", 1, "nsubj", true)]);
        assert_eq!(
            to_bunsetsu(&sentence),
            Err(vec![DropCause::Root, DropCause::HeadToTheLeft])
        );
        // Two roots, the last bunsetsu among them.
        let sentence = ud_sentence(&[("はい", 0, "root", true), ("読む", 0, "root", true)]);
        assert_eq!(to_bunsetsu(&sentence), Err(vec![DropCause::Root]));
    }

    #[test]
    fn drops_a_sentence_with_a_head_to_the_left() {
        // An arc to the left that is not a conjunct stays one.
        let sentence = ud_sentence(&[
            ("彼", 3, "nsubj", true),
            ("本", 1, "dislocated", true),
            ("読む", 0, "root", true),
        ]);
        assert_eq!(to_bunsetsu(&sentence), Err(vec![DropCause::HeadToTheLeft]));
    }

    #[test]
    fn drops_a_sentence_with_crossing_arcs() {
        // a → c and b → d cross.
        let sentence = ud_sentence(&[
            ("a", 3, "dep", true),
            ("b", 4, "dep", true),
            ("c", 4, "dep", true),
            ("d", 0, "root", true),
        ]);
        assert_eq!(to_bunsetsu(&sentence), Err(vec![DropCause::CrossingArcs]));
    }

    #[test]
    fn conjuncts_in_a_cycle_keep_their_heads_and_drop_the_sentence() {
        // a and b are conjuncts of each other: neither is reached.
        let sentence = ud_sentence(&[
            ("a", 2, "conj", true),
            ("b", 1, "conj", true),
            ("読む", 0, "root", true),
        ]);
        assert_eq!(to_bunsetsu(&sentence), Err(vec![DropCause::HeadToTheLeft]));
    }
}