Skip to main content

lindera_dependency/
parser.rs

1//! Parsing: finding, for each bunsetsu of a sentence, the bunsetsu it
2//! depends on.
3//!
4//! The parser goes through the bunsetsu from left to right with a stack
5//! (shift-reduce), and asks one question at a time: does this bunsetsu, the
6//! source, depend on that one, the target? It is what CaboCha and J.DepP
7//! do. Every head is to the right of its bunsetsu, no two arcs cross, and
8//! the last bunsetsu is the root; the time is linear in the number of
9//! bunsetsu.
10//!
11//! It is in three parts, so that each can be replaced:
12//!
13//! - **The features of a decision** are strings, with the names CaboCha
14//!   gives them. They are made from the head and the function word of each
15//!   bunsetsu, through the [`Schema`] of the dictionary. A [`FeatureSet`]
16//!   says which [`Group`]s of features are made.
17//! - **The classifier** ([`Classifier`]) scores the features of a decision:
18//!   the source depends on the target when the score is above 0. Every
19//!   classifier here adds the weights of the features and of their pairs:
20//!   [`ParserPart`] reads them on the bytes of a model file,
21//!   [`ParserModel`] holds them in memory as training gives them, and
22//!   [`LinearClassifier`] takes weights made by hand.
23//! - **The loop** asks the decisions. With a classifier it parses
24//!   ([`Parser::parse`]); with the answer of a sentence it gives the
25//!   training instances of a classifier ([`instances`]).
26//!
27//! Parsing needs nothing but this crate. Training, behind the `train`
28//! feature, is `train`: dual coordinate descent as CaboCha does it, or
29//! passive-aggressive as J.DepP does.
30//!
31//! The parser of a model file comes from
32//! [`Model::parser`](crate::model::Model::parser).
33//!
34//! # Examples
35//!
36//! A classifier made by hand: a bunsetsu that ends in を depends on the
37//! next one, and nothing else is attached before the end of the sentence.
38//!
39//! ```
40//! use std::collections::HashMap;
41//!
42//! use lindera_dependency::lattice::LatticeMorpheme;
43//! use lindera_dependency::parser::{FeatureSet, LinearClassifier, Parser};
44//! use lindera_dependency::Schema;
45//!
46//! // SFS is the surface of the function word of the source, and DIST:1
47//! // says that the target is the next bunsetsu.
48//! let pairs = HashMap::from([(("SFS:を".to_string(), "DIST:1".to_string()), 2.0)]);
49//! let classifier = LinearClassifier::new(-1.0, HashMap::new(), pairs)?;
50//! let parser = Parser::new(Schema::ipadic(), FeatureSet::cabocha(), classifier);
51//!
52//! // 彼 は / 本 を / 読ん だ / と / 言う
53//! let morphemes = [
54//!     LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*,彼,カレ,カレ"),
55//!     LatticeMorpheme::new("は", "助詞,係助詞,*,*,*,*,は,ハ,ワ"),
56//!     LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
57//!     LatticeMorpheme::new("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ"),
58//!     LatticeMorpheme::new("読ん", "動詞,自立,*,*,五段・マ行,連用タ接続,読む,ヨン,ヨン"),
59//!     LatticeMorpheme::new("だ", "助動詞,*,*,*,特殊・タ,基本形,だ,ダ,ダ"),
60//!     LatticeMorpheme::new("と", "助詞,格助詞,引用,*,*,*,と,ト,ト"),
61//!     LatticeMorpheme::new("言う", "動詞,自立,*,*,五段・ワ行促音便,基本形,言う,イウ,イウ"),
62//! ];
63//! let bunsetsu = parser.parse(&morphemes, &[0..2, 2..4, 4..7, 7..8])?;
64//!
65//! let heads: Vec<Option<usize>> = bunsetsu.iter().map(|one| one.head).collect();
66//! assert_eq!(heads, [Some(3), Some(2), Some(3), None]);
67//! // 本 を: the head word is 本, the function word を, and the score is
68//! // the bias and the weight of the pair.
69//! assert_eq!(bunsetsu[1].positions, Some((0, 1)));
70//! assert_eq!(bunsetsu[1].score, Some(1.0));
71//! # Ok::<(), lindera_dependency::Error>(())
72//! ```
73
74mod classifier;
75mod features;
76pub(crate) mod model;
77mod oracle;
78mod shift_reduce;
79#[cfg(feature = "train")]
80mod train;
81
82use std::ops::Range;
83
84pub use classifier::{Classifier, LinearClassifier};
85pub use features::{FeatureSet, Group};
86pub use model::{PairWeights, ParserModel, ParserPart, Quantization};
87pub use oracle::{Instance, instances, write_instances};
88#[cfg(feature = "train")]
89pub use train::{Algorithm, Pairs, TrainOptions, Trained, train};
90
91use crate::error::Result;
92use crate::morpheme::Morpheme;
93use crate::schema::Schema;
94use crate::sentence::{Bunsetsu, check_bunsetsu};
95use features::Prepared;
96use shift_reduce::Decision;
97
98/// Finds the head of each bunsetsu of a sentence.
99///
100/// A parser is made once and used from any number of threads: parsing takes
101/// `&self` and keeps no state.
102#[derive(Debug, Clone, PartialEq)]
103pub struct Parser<C> {
104    /// The schema of the dictionary of the morphemes.
105    schema: Schema,
106    /// The groups of features the classifier was trained on.
107    features: FeatureSet,
108    /// The classifier.
109    classifier: C,
110}
111
112impl<C: Classifier> Parser<C> {
113    /// Makes a parser.
114    ///
115    /// # Arguments
116    ///
117    /// * `schema` - The schema of the dictionary of the morphemes.
118    /// * `features` - The groups of features the classifier was trained on.
119    /// * `classifier` - The classifier.
120    ///
121    /// # Returns
122    ///
123    /// The parser.
124    pub fn new(schema: Schema, features: FeatureSet, classifier: C) -> Self {
125        Self {
126            schema,
127            features,
128            classifier,
129        }
130    }
131
132    /// The schema of the parser.
133    ///
134    /// # Returns
135    ///
136    /// The schema.
137    pub fn schema(&self) -> &Schema {
138        &self.schema
139    }
140
141    /// The feature set of the parser.
142    ///
143    /// # Returns
144    ///
145    /// The feature set.
146    pub fn feature_set(&self) -> &FeatureSet {
147        &self.features
148    }
149
150    /// The classifier of the parser.
151    ///
152    /// # Returns
153    ///
154    /// The classifier.
155    pub fn classifier(&self) -> &C {
156        &self.classifier
157    }
158
159    /// Parses a sentence.
160    ///
161    /// # Arguments
162    ///
163    /// * `morphemes` - The morphemes of the sentence.
164    /// * `bunsetsu` - Its bunsetsu from left to right, as ranges of indices
165    ///   into `morphemes`: what
166    ///   [`Chunker::chunk`](crate::chunker::Chunker::chunk) gives.
167    ///
168    /// # Returns
169    ///
170    /// The bunsetsu with their heads; the last one is the root. Each has
171    /// the positions of its head word and of its function word, from the
172    /// schema, and the score of the decision that attached it: 0 for the
173    /// root and for a bunsetsu attached to the root, which is not asked.
174    /// The result can be given to [`Sentence::new`](crate::Sentence::new).
175    ///
176    /// [`Error::Structure`](crate::Error::Structure) when the bunsetsu do
177    /// not cover the morphemes from the first to the last without a gap, or
178    /// one of them is empty. [`Error::Dictionary`](crate::Error::Dictionary)
179    /// for a morpheme with fewer feature columns than the schema reads
180    /// ([`Schema::check`]).
181    pub fn parse<M: Morpheme>(
182        &self,
183        morphemes: &[M],
184        bunsetsu: &[Range<usize>],
185    ) -> Result<Vec<Bunsetsu>> {
186        let mut parsed: Vec<Bunsetsu> = bunsetsu
187            .iter()
188            .map(|range| Bunsetsu::new(range.clone(), None))
189            .collect();
190        check_bunsetsu(morphemes.len(), &parsed)?;
191        self.schema.check(morphemes)?;
192
193        let prepared: Prepared<u32> = Prepared::new(
194            &self.schema,
195            &self.features,
196            morphemes,
197            bunsetsu,
198            |feature| self.classifier.id(feature),
199        );
200        let mut features = Vec::new();
201        let arcs = shift_reduce::parse(bunsetsu.len(), |source, target, children| {
202            prepared.decision(source, target, children, &mut features);
203            let score = self.classifier.score(&features);
204            Decision {
205                attach: score > 0.0,
206                score,
207            }
208        });
209
210        for (index, one) in parsed.iter_mut().enumerate() {
211            one.head = arcs.heads[index];
212            one.positions = self.schema.positions(&morphemes[one.morphemes.clone()]);
213            one.score = one.positions.map(|_| arcs.scores[index]);
214        }
215        Ok(parsed)
216    }
217}
218
219/// Sentences for the tests of the parser.
220#[cfg(test)]
221pub(crate) mod fixtures {
222    use std::ops::Range;
223
224    use crate::lattice::LatticeMorpheme;
225
226    /// 彼 は / 「 本 / 」 を / 静か に 、 / 読ん だ 。
227    ///
228    /// The brackets are cut apart on purpose: one bunsetsu opens, the next
229    /// closes.
230    pub(crate) fn sentence() -> (Vec<LatticeMorpheme>, Vec<Range<usize>>) {
231        let morphemes = [
232            ("彼", "名詞,代名詞,一般,*,*,*,彼,カレ,カレ"),
233            ("は", "助詞,係助詞,*,*,*,*,は,ハ,ワ"),
234            ("「", "記号,括弧開,*,*,*,*,「,「,「"),
235            ("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
236            ("」", "記号,括弧閉,*,*,*,*,」,」,」"),
237            ("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ"),
238            ("静か", "名詞,形容動詞語幹,*,*,*,*,静か,シズカ,シズカ"),
239            ("に", "助詞,副詞化,*,*,*,*,に,ニ,ニ"),
240            ("、", "記号,読点,*,*,*,*,、,、,、"),
241            ("読ん", "動詞,自立,*,*,五段・マ行,連用タ接続,読む,ヨン,ヨン"),
242            ("だ", "助動詞,*,*,*,特殊・タ,基本形,だ,ダ,ダ"),
243            ("。", "記号,句点,*,*,*,*,。,。,。"),
244        ]
245        .iter()
246        .map(|(surface, features)| LatticeMorpheme::new(*surface, *features))
247        .collect();
248        (morphemes, vec![0..2, 2..4, 4..6, 6..9, 9..12])
249    }
250
251    /// A sentence of `count` bunsetsu, each 本 / を.
252    pub(crate) fn repeated(count: usize) -> (Vec<LatticeMorpheme>, Vec<Range<usize>>) {
253        let mut morphemes = Vec::new();
254        let mut ranges = Vec::new();
255        for index in 0..count {
256            morphemes.push(LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン"));
257            morphemes.push(LatticeMorpheme::new(
258                "を",
259                "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ",
260            ));
261            ranges.push(2 * index..2 * index + 2);
262        }
263        (morphemes, ranges)
264    }
265}
266
267#[cfg(test)]
268mod tests {
269    use std::cell::Cell;
270    use std::collections::HashMap;
271
272    use super::*;
273    use crate::error::Error;
274    use crate::lattice::LatticeMorpheme;
275    use crate::sentence::Sentence;
276
277    /// A classifier that knows every feature and counts its calls.
278    struct Counting {
279        /// The score it gives.
280        score: f64,
281        /// The number of decisions it scored.
282        scores: Cell<usize>,
283    }
284
285    impl Counting {
286        /// A classifier that gives one score to every decision.
287        fn new(score: f64) -> Self {
288            Self {
289                score,
290                scores: Cell::new(0),
291            }
292        }
293    }
294
295    impl Classifier for Counting {
296        fn id(&self, _: &str) -> Option<u32> {
297            Some(0)
298        }
299
300        fn score(&self, _: &[u32]) -> f64 {
301            self.scores.set(self.scores.get() + 1);
302            self.score
303        }
304    }
305
306    /// A parser for IPADIC with every group of features.
307    fn parser<C: Classifier>(classifier: C) -> Parser<C> {
308        Parser::new(Schema::ipadic(), FeatureSet::cabocha(), classifier)
309    }
310
311    /// The heads of bunsetsu.
312    fn heads(bunsetsu: &[Bunsetsu]) -> Vec<Option<usize>> {
313        bunsetsu.iter().map(|one| one.head).collect()
314    }
315
316    #[test]
317    fn a_pair_of_features_decides() {
318        // A source that ends in を depends on the next bunsetsu, and on no
319        // other: neither feature is enough alone.
320        let pairs = HashMap::from([(("SFS:を".to_string(), "DIST:1".to_string()), 2.0)]);
321        let classifier = LinearClassifier::new(-1.0, HashMap::new(), pairs).unwrap();
322        let (morphemes, ranges) = fixtures::sentence();
323        let parsed = parser(classifier).parse(&morphemes, &ranges).unwrap();
324        // 彼は and 「本 are refused by the next bunsetsu; 」を is attached to
325        // 静かに、; then 「本 is two bunsetsu from it, and refused.
326        assert_eq!(heads(&parsed), [Some(4), Some(4), Some(3), Some(4), None]);
327        let scores: Vec<Option<f64>> = parsed.iter().map(|one| one.score).collect();
328        assert_eq!(
329            scores,
330            [Some(0.0), Some(0.0), Some(1.0), Some(0.0), Some(0.0)]
331        );
332    }
333
334    #[test]
335    fn the_result_is_a_sentence_without_violations() {
336        let (morphemes, ranges) = fixtures::sentence();
337        for score in [-1.0, 1.0] {
338            let parsed = parser(Counting::new(score))
339                .parse(&morphemes, &ranges)
340                .unwrap();
341            let sentence = Sentence::new(morphemes.clone(), parsed).unwrap();
342            assert_eq!(sentence.violations(), [], "score {score}");
343        }
344    }
345
346    #[test]
347    fn a_score_above_zero_attaches() {
348        let (morphemes, ranges) = fixtures::sentence();
349        let attached = parser(Counting::new(0.25))
350            .parse(&morphemes, &ranges)
351            .unwrap();
352        assert_eq!(heads(&attached), [Some(1), Some(2), Some(3), Some(4), None]);
353        // A score of 0 does not.
354        let refused = parser(Counting::new(0.0))
355            .parse(&morphemes, &ranges)
356            .unwrap();
357        assert_eq!(heads(&refused), [Some(4), Some(4), Some(4), Some(4), None]);
358    }
359
360    #[test]
361    fn the_positions_are_those_of_the_schema() {
362        let (morphemes, ranges) = fixtures::sentence();
363        let parsed = parser(Counting::new(1.0))
364            .parse(&morphemes, &ranges)
365            .unwrap();
366        let positions: Vec<Option<(usize, usize)>> =
367            parsed.iter().map(|one| one.positions).collect();
368        assert_eq!(
369            positions,
370            [
371                Some((0, 1)),
372                Some((1, 1)),
373                Some((0, 1)),
374                Some((0, 1)),
375                Some((0, 1))
376            ]
377        );
378    }
379
380    #[test]
381    fn the_classifier_is_not_called_for_two_bunsetsu_or_fewer() {
382        let (morphemes, _) = fixtures::sentence();
383        let classifier = Counting::new(-1.0);
384        let none = parser(&classifier)
385            .parse::<LatticeMorpheme>(&[], &[])
386            .unwrap();
387        assert_eq!(none, []);
388
389        #[allow(clippy::single_range_in_vec_init)]
390        let one = parser(&classifier).parse(&morphemes[..2], &[0..2]).unwrap();
391        assert_eq!(heads(&one), [None]);
392        assert_eq!(one[0].score, Some(0.0));
393
394        let two = parser(&classifier)
395            .parse(&morphemes[..4], &[0..2, 2..4])
396            .unwrap();
397        assert_eq!(heads(&two), [Some(1), None]);
398        assert_eq!(classifier.scores.get(), 0);
399    }
400
401    #[test]
402    fn bunsetsu_that_do_not_cover_the_morphemes_are_refused() {
403        let (morphemes, _) = fixtures::sentence();
404        let classifier = Counting::new(1.0);
405        // A gap, an end past the morphemes, an empty bunsetsu, and
406        // morphemes left over.
407        #[allow(clippy::single_range_in_vec_init)]
408        let wrong: [Vec<Range<usize>>; 4] = [
409            vec![0..2, 3..12],
410            vec![0..2, 2..13],
411            vec![0..2, 2..2, 2..12],
412            vec![0..2],
413        ];
414        let accepted: Vec<usize> = wrong
415            .iter()
416            .enumerate()
417            .filter(|(_, ranges)| {
418                !matches!(
419                    parser(&classifier).parse(&morphemes, ranges),
420                    Err(Error::Structure(_))
421                )
422            })
423            .map(|(index, _)| index)
424            .collect();
425        assert!(accepted.is_empty(), "not refused: {accepted:?}");
426    }
427
428    #[test]
429    fn a_feature_the_classifier_does_not_know_is_left_out() {
430        // The classifier knows the distance only: with a weight on DIST:1,
431        // every bunsetsu depends on the next.
432        let features = HashMap::from([("DIST:1".to_string(), 1.0)]);
433        let classifier = LinearClassifier::new(-0.5, features, HashMap::new()).unwrap();
434        let (morphemes, ranges) = fixtures::sentence();
435        let parsed = parser(classifier).parse(&morphemes, &ranges).unwrap();
436        assert_eq!(heads(&parsed), [Some(1), Some(2), Some(3), Some(4), None]);
437    }
438
439    #[test]
440    fn a_group_left_out_of_the_set_is_not_made() {
441        // Without the distance, the weight on DIST:1 is never reached.
442        let features = HashMap::from([("DIST:1".to_string(), 1.0)]);
443        let classifier = LinearClassifier::new(-0.5, features, HashMap::new()).unwrap();
444        let set = FeatureSet::parse("source,target").unwrap();
445        let (morphemes, ranges) = fixtures::sentence();
446        let parsed = Parser::new(Schema::ipadic(), set, classifier)
447            .parse(&morphemes, &ranges)
448            .unwrap();
449        assert_eq!(heads(&parsed), [Some(4), Some(4), Some(4), Some(4), None]);
450    }
451
452    #[test]
453    fn a_morpheme_of_another_dictionary_is_refused() {
454        let (mut morphemes, ranges) = fixtures::sentence();
455        morphemes[1] = LatticeMorpheme::new("は", "助詞,係助詞");
456        let classifier = LinearClassifier::new(1.0, HashMap::new(), HashMap::new()).unwrap();
457        let error = parser(classifier).parse(&morphemes, &ranges).unwrap_err();
458        assert!(matches!(error, crate::Error::Dictionary(_)), "{error:?}");
459        assert!(
460            error.to_string().starts_with("the morpheme 2 (\"は\")"),
461            "{error}"
462        );
463    }
464}