lindera-dependency 7.2.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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! Chunking: segmenting the morphemes of a sentence into bunsetsu.
//!
//! The chunker decides, for every morpheme, whether it starts a bunsetsu
//! (`B`) or continues one (`I`), with a conditional random field over the
//! two labels, as CaboCha does.
//!
//! It is in three parts, so that each can be replaced:
//!
//! - **The features of a position** are strings. The [`Column`]s of each
//!   morpheme (its surface, its part of speech, ...) are taken through the
//!   [`Schema`] of the dictionary, and a [`Template`] in the
//!   format of CRF++ expands them ([`Chunker::features`]).
//! - **The model** is a table from feature string to the weights of `B` and
//!   `I`, and the weights of the transitions, with the schema, the columns
//!   and the template it was trained with ([`ChunkerData`]). A
//!   [`ChunkerModel`] holds it in memory; a model file
//!   ([`Model`](crate::model::Model)) is read where it is.
//! - **Decoding** ([`Chunker::labels`]) finds the best labels for feature
//!   strings, by Viterbi. It does not know where the strings come from.
//!
//! Inference needs nothing but this crate. Training, behind the `train`
//! feature, uses `lindera-crf`.
//!
//! # Examples
//!
//! A model made by hand, with one weight: a morpheme after a particle
//! starts a bunsetsu.
//!
//! ```
//! use std::collections::HashMap;
//!
//! use lindera_dependency::chunker::{Chunker, ChunkerModel, Column, Template};
//! use lindera_dependency::lattice::LatticeMorpheme;
//! use lindera_dependency::Schema;
//!
//! // U11 is the part of speech of the morpheme before: `B` gets 1.0.
//! let mut features = HashMap::new();
//! features.insert("U11:助詞-係助詞".to_string(), [1.0, 0.0]);
//! features.insert("U11:助詞-格助詞-一般".to_string(), [1.0, 0.0]);
//! // Without a feature for `B`, a morpheme continues the bunsetsu: `I`
//! // after anything gets 0.5.
//! let transitions = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.5], [0.0, 0.0, 0.5]];
//! let model = ChunkerModel::new(
//!     Schema::ipadic(),
//!     vec![Column::Surface, Column::PartOfSpeech],
//!     Template::cabocha(),
//!     transitions,
//!     features,
//! )?;
//! let chunker = Chunker::new(model);
//!
//! let morphemes = [
//!     LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*,彼,カレ,カレ"),
//!     LatticeMorpheme::new("は", "助詞,係助詞,*,*,*,*,は,ハ,ワ"),
//!     LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
//!     LatticeMorpheme::new("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ"),
//!     LatticeMorpheme::new("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム"),
//! ];
//! assert_eq!(chunker.chunk(&morphemes)?, [0..2, 2..4, 4..5]);
//! # Ok::<(), lindera_dependency::Error>(())
//! ```

pub mod columns;
mod decode;
pub mod model;
pub mod template;
#[cfg(feature = "train")]
pub mod train;

use std::ops::Range;

pub use columns::{Column, parse_columns};
pub use model::{ChunkerData, ChunkerModel, Label};
pub use template::Template;
#[cfg(feature = "train")]
pub use train::{Regularization, TrainOptions, Trained, train};

use crate::error::Result;
use crate::morpheme::{Morpheme, is_space};
use crate::schema::Schema;

/// The feature strings of each morpheme of a sentence.
///
/// # Arguments
///
/// * `schema` - The schema of the dictionary of the morphemes.
/// * `columns` - The columns the template reads.
/// * `template` - The template.
/// * `morphemes` - The morphemes of the sentence.
///
/// # Returns
///
/// For each morpheme, one string per unigram line of the template.
pub(crate) fn extract<M: Morpheme>(
    schema: &Schema,
    columns: &[Column],
    template: &Template,
    morphemes: &[M],
) -> Vec<Vec<String>> {
    let rows = columns::rows(schema, columns, morphemes);
    (0..rows.len())
        .map(|position| template.expand(&rows, position))
        .collect()
}

/// Segments the morphemes of a sentence into bunsetsu.
///
/// A chunker is made from a model once and used from any number of threads:
/// chunking takes `&self` and keeps no state.
///
/// `D` is where the model is: a [`ChunkerModel`] in memory, or the chunker
/// part of a model file, which [`Model::chunker`](crate::model::Model::chunker)
/// gives.
#[derive(Debug, Clone, PartialEq)]
pub struct Chunker<D = ChunkerModel> {
    /// The model.
    model: D,
}

impl<D: ChunkerData> Chunker<D> {
    /// Makes a chunker.
    ///
    /// # Arguments
    ///
    /// * `model` - The model.
    ///
    /// # Returns
    ///
    /// The chunker.
    pub fn new(model: D) -> Self {
        Self { model }
    }

    /// The model of the chunker.
    ///
    /// # Returns
    ///
    /// The model.
    pub fn model(&self) -> &D {
        &self.model
    }

    /// The feature strings of each morpheme of a sentence, made with the
    /// schema, the columns and the template of the model.
    ///
    /// # Arguments
    ///
    /// * `morphemes` - The morphemes of the sentence.
    ///
    /// # Returns
    ///
    /// For each morpheme, one string per unigram line of the template.
    pub fn features<M: Morpheme>(&self, morphemes: &[M]) -> Vec<Vec<String>> {
        extract(
            self.model.schema(),
            self.model.columns(),
            self.model.template(),
            morphemes,
        )
    }

    /// The best labels for the feature strings of a sentence.
    ///
    /// This is the decoder alone: the strings can come from
    /// [`Chunker::features`] or from another extractor that makes the
    /// strings the model was trained on.
    ///
    /// # Arguments
    ///
    /// * `features` - The feature strings of each position.
    ///
    /// # Returns
    ///
    /// One label per position, the first always [`Label::Begin`]; none for
    /// an empty sentence.
    pub fn labels(&self, features: &[Vec<String>]) -> Vec<Label> {
        decode::decode(&self.model, features)
    }

    /// Segments the morphemes of a sentence into bunsetsu.
    ///
    /// # Arguments
    ///
    /// * `morphemes` - The morphemes of the sentence.
    ///
    /// # Returns
    ///
    /// The bunsetsu from left to right, each as a range of indices into
    /// `morphemes`. They cover the morphemes without a gap: the first
    /// morpheme always starts a bunsetsu. An empty sentence has none.
    ///
    /// A space (a morpheme whose surface is of white space alone, such as
    /// the full-width space a tokenizer gives as a token) is no word, and
    /// the model does not see it: the bunsetsu are those of the sentence
    /// without its spaces. A space is then in the bunsetsu of the word
    /// after it, and the spaces at the end of the sentence in the last
    /// bunsetsu. A sentence of spaces alone is one bunsetsu.
    ///
    /// A text of several sentences is cut after each sentence end when the
    /// schema of the model says so ([`Schema::sentence_starts`]), and each
    /// part is given to the model on its own: a word after a `。` starts a
    /// bunsetsu, inside brackets as outside. The model was trained on
    /// sentences, and has seen no word after a period.
    ///
    /// [`Error::Dictionary`](crate::Error::Dictionary) for a morpheme with
    /// fewer feature columns than the schema of the model reads
    /// ([`Schema::check`]): it is not of the dictionary of the model.
    pub fn chunk<M: Morpheme>(&self, morphemes: &[M]) -> Result<Vec<Range<usize>>> {
        self.model.schema().check(morphemes)?;
        let words = words(morphemes);
        let labels = if words.len() == morphemes.len() {
            self.labels_of_sentences(morphemes)
        } else {
            let kept: Vec<&M> = words.iter().map(|&index| &morphemes[index]).collect();
            self.labels_of_sentences(&kept)
        };
        let mut bunsetsu: Vec<Range<usize>> = Vec::new();
        for (position, label) in labels.iter().enumerate() {
            // A bunsetsu starts right after the word before it: the spaces
            // in between are at its start.
            let start = position
                .checked_sub(1)
                .map_or(0, |before| words[before] + 1);
            let end = words[position] + 1;
            match (label, bunsetsu.last_mut()) {
                (Label::Inside, Some(last)) => last.end = end,
                _ => bunsetsu.push(start..end),
            }
        }
        match bunsetsu.last_mut() {
            // The spaces after the last word.
            Some(last) => last.end = morphemes.len(),
            // No word: the spaces, when there are any, are one bunsetsu.
            None if !morphemes.is_empty() => bunsetsu.push(0..morphemes.len()),
            None => {}
        }
        Ok(bunsetsu)
    }
}

impl<D: ChunkerData> Chunker<D> {
    /// The labels of the words of a text, each sentence of it decoded on
    /// its own.
    ///
    /// # Arguments
    ///
    /// * `words` - The words of the text: its morphemes without the spaces.
    ///
    /// # Returns
    ///
    /// One label per word. The first word of each sentence
    /// ([`Schema::sentence_starts`]) has [`Label::Begin`].
    fn labels_of_sentences<M: Morpheme>(&self, words: &[M]) -> Vec<Label> {
        let starts = self.model.schema().sentence_starts(words);
        if starts.is_empty() {
            return self.labels(&self.features(words));
        }
        let mut labels = Vec::with_capacity(words.len());
        let mut from = 0;
        for to in starts.into_iter().chain([words.len()]) {
            labels.extend(self.labels(&self.features(&words[from..to])));
            from = to;
        }
        labels
    }
}

/// The words of a sentence: its morphemes that are not spaces.
///
/// # Arguments
///
/// * `morphemes` - The morphemes of the sentence.
///
/// # Returns
///
/// The indices of the morphemes the chunker reads, in order.
pub(crate) fn words<M: Morpheme>(morphemes: &[M]) -> Vec<usize> {
    (0..morphemes.len())
        .filter(|&index| !is_space(&morphemes[index]))
        .collect()
}

#[cfg(test)]
// A sentence that is one bunsetsu is compared with `[0..n]`: an array of one
// range, which is what is meant.
#[allow(clippy::single_range_in_vec_init)]
mod tests {
    use super::*;
    use crate::chunker::model::tests::model;
    use crate::lattice::LatticeMorpheme;

    /// 彼 は 本 を 読む, with the features of IPADIC.
    fn morphemes() -> Vec<LatticeMorpheme> {
        vec![
            LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*,彼,カレ,カレ"),
            LatticeMorpheme::new("は", "助詞,係助詞,*,*,*,*,は,ハ,ワ"),
            LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
            LatticeMorpheme::new("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ"),
            LatticeMorpheme::new("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム"),
        ]
    }

    /// A chunker for which a particle continues a bunsetsu and anything
    /// else starts one.
    fn chunker() -> Chunker {
        Chunker::new(model(
            &[
                ("U12:助詞-係助詞", [0.0, 1.0]),
                ("U12:助詞-格助詞-一般", [0.0, 1.0]),
            ],
            [[0.0; 3]; 3],
        ))
    }

    #[test]
    fn chunks_a_sentence() {
        let chunker = chunker();
        let morphemes = morphemes();
        assert_eq!(chunker.chunk(&morphemes).unwrap(), [0..2, 2..4, 4..5]);
        assert_eq!(
            chunker.labels(&chunker.features(&morphemes)),
            [
                Label::Begin,
                Label::Inside,
                Label::Begin,
                Label::Inside,
                Label::Begin
            ]
        );
    }

    #[test]
    fn the_features_are_those_of_the_template_on_the_columns() {
        let chunker = chunker();
        let features = chunker.features(&morphemes());
        assert_eq!(features.len(), 5);
        assert_eq!(features[1].len(), 19);
        assert_eq!(features[1][2], "U02:は");
        assert_eq!(features[1][9], "U12:助詞-係助詞");
        assert_eq!(
            features[1][17],
            "U21:名詞-代名詞-一般/助詞-係助詞/名詞-一般"
        );
        assert_eq!(features[4][11], "U14:_B+2");
    }

    #[test]
    fn an_empty_sentence_and_a_sentence_of_one_morpheme() {
        let chunker = chunker();
        let none: [LatticeMorpheme; 0] = [];
        assert!(chunker.chunk(&none).unwrap().is_empty());
        assert_eq!(chunker.chunk(&morphemes()[..1]).unwrap(), [0..1]);
        // A particle alone is a bunsetsu: the first morpheme starts one.
        assert_eq!(chunker.chunk(&morphemes()[1..2]).unwrap(), [0..1]);
        assert_eq!(chunker.chunk(&morphemes()[1..4]).unwrap(), [0..1, 1..3]);
    }

    #[test]
    fn the_bunsetsu_cover_the_morphemes() {
        // Everything continues: one bunsetsu.
        let chunker = Chunker::new(model(&[], [[0.0; 3], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]]));
        assert_eq!(chunker.chunk(&morphemes()).unwrap(), [0..5]);
        // Everything starts: one bunsetsu per morpheme.
        let chunker = Chunker::new(model(&[], [[0.0; 3]; 3]));
        assert_eq!(
            chunker.chunk(&morphemes()).unwrap(),
            [0..1, 1..2, 2..3, 3..4, 4..5]
        );
    }

    /// A full-width space, as IPADIC gives it.
    fn space() -> LatticeMorpheme {
        LatticeMorpheme::new("\u{3000}", "記号,空白,*,*,*,*,\u{3000},\u{3000},\u{3000}")
    }

    #[test]
    fn a_space_is_not_read_and_is_in_the_bunsetsu_of_the_word_after_it() {
        let chunker = chunker();
        let words = morphemes();
        // A half-width space, which a tokenizer gives when it keeps them.
        let narrow = LatticeMorpheme::new(" ", "記号,空白,*,*,*,*,*,*,*");
        // 彼は / 本を / 読む, with spaces at the start, between two
        // bunsetsu, inside one and at the end.
        let sentence = vec![
            space(),
            words[0].clone(),
            words[1].clone(),
            space(),
            narrow,
            words[2].clone(),
            space(),
            words[3].clone(),
            words[4].clone(),
            space(),
        ];
        assert_eq!(super::words(&sentence), [1, 2, 5, 7, 8]);
        // The bunsetsu of the sentence without its spaces, with each space
        // in the bunsetsu of the word after it, and the last one in the
        // last bunsetsu.
        assert_eq!(chunker.chunk(&sentence).unwrap(), [0..3, 3..8, 8..10]);

        // A space where the model would start a bunsetsu changes nothing:
        // with a model in which everything continues, there is one bunsetsu.
        let chunker = Chunker::new(model(&[], [[0.0; 3], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]]));
        assert_eq!(chunker.chunk(&sentence).unwrap(), [0..10]);
    }

    #[test]
    fn a_sentence_of_spaces_alone_is_one_bunsetsu() {
        let chunker = chunker();
        assert_eq!(chunker.chunk(&[space()]).unwrap(), [0..1]);
        assert_eq!(chunker.chunk(&[space(), space()]).unwrap(), [0..2]);
        assert!(super::words(&[space(), space()]).is_empty());
    }

    #[test]
    fn a_chunker_is_shared_between_threads() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<Chunker>();
        assert_send_sync::<ChunkerModel>();

        let chunker = chunker();
        let morphemes = morphemes();
        std::thread::scope(|scope| {
            for _ in 0..2 {
                scope.spawn(|| assert_eq!(chunker.chunk(&morphemes).unwrap(), [0..2, 2..4, 4..5]));
            }
        });
        assert_eq!(chunker.model().feature_count(), 2);
    }

    #[test]
    fn a_morpheme_of_another_dictionary_is_refused() {
        let chunker = chunker();
        let mut morphemes = morphemes();
        morphemes[3] = LatticeMorpheme::new("を", "助詞,格助詞,一般");
        let error = chunker.chunk(&morphemes).unwrap_err();
        assert!(matches!(error, crate::Error::Dictionary(_)), "{error:?}");
        assert!(
            error.to_string().starts_with("the morpheme 4 (\"を\")"),
            "{error}"
        );
    }

    /// 。 as IPADIC gives it.
    fn period() -> LatticeMorpheme {
        LatticeMorpheme::new("。", "記号,句点,*,*,*,*,。,。,。")
    }

    /// A chunker that never starts a bunsetsu but at the first word: with
    /// it, a bunsetsu that starts elsewhere is the work of the cut.
    fn continues() -> Chunker {
        Chunker::new(model(&[], [[0.0; 3], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]]))
    }

    #[test]
    fn a_text_of_two_sentences_is_cut_after_the_period() {
        let chunker = continues();
        let words = morphemes();
        // 彼は本を読む。彼は。
        let text = vec![
            words[0].clone(),
            words[1].clone(),
            words[2].clone(),
            words[3].clone(),
            words[4].clone(),
            period(),
            words[0].clone(),
            words[1].clone(),
            period(),
        ];
        assert_eq!(chunker.model().schema().sentence_starts(&text), [6]);
        // The model continues everywhere: one bunsetsu per sentence.
        assert_eq!(chunker.chunk(&text).unwrap(), [0..6, 6..9]);
        // One sentence is one bunsetsu, as before.
        assert_eq!(chunker.chunk(&text[..6]).unwrap(), [0..6]);

        // Each sentence is decoded as a sentence of its own: the labels of
        // the text are those of its sentences, one after the other.
        let chunker = self::chunker();
        let first = chunker.chunk(&text[..6]).unwrap();
        let second = chunker.chunk(&text[6..]).unwrap();
        let mut expected = first.clone();
        expected.extend(second.iter().map(|range| range.start + 6..range.end + 6));
        assert_eq!(chunker.chunk(&text).unwrap(), expected);
        assert_eq!(first.last().unwrap().end, 6);
    }

    #[test]
    fn a_model_whose_schema_does_not_cut_gives_the_text_to_the_model_whole() {
        use crate::schema::SentenceSplit;

        let whole = |split: SentenceSplit| {
            let cut = continues();
            let model = cut.model();
            Chunker::new(
                ChunkerModel::new(
                    Schema {
                        sentence_split: split,
                        ..model.schema().clone()
                    },
                    model.columns().to_vec(),
                    model.template().clone(),
                    [[0.0; 3], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0]],
                    Default::default(),
                )
                .unwrap(),
            )
        };
        let words = morphemes();
        let text = vec![words[0].clone(), period(), words[2].clone(), period()];
        assert_eq!(whole(SentenceSplit::None).chunk(&text).unwrap(), [0..4]);
        assert_eq!(
            whole(SentenceSplit::AfterEnds).chunk(&text).unwrap(),
            [0..2, 2..4]
        );
    }

    #[test]
    fn the_spaces_of_a_text_of_two_sentences_go_to_the_word_after_them() {
        let chunker = continues();
        let words = morphemes();
        // 彼 。 ␣ 本 。 ␣: the space after the first period is at the start
        // of the second sentence, and the last one in the last bunsetsu.
        let text = vec![
            words[0].clone(),
            period(),
            space(),
            words[2].clone(),
            period(),
            space(),
        ];
        assert_eq!(chunker.chunk(&text).unwrap(), [0..2, 2..6]);
        // A space before the period changes nothing.
        let text = vec![words[0].clone(), space(), period(), words[2].clone()];
        assert_eq!(chunker.chunk(&text).unwrap(), [0..3, 3..4]);
    }
}