Skip to main content

lindera_dependency/parser/
oracle.rs

1//! Training instances: the decisions of the parser on a sentence whose
2//! heads are known.
3//!
4//! The loop of the parser runs with the answer deciding in the place of a
5//! classifier, as CaboCha does in its training mode. Each decision it asks
6//! is one instance: the features the parser would have at that point, and
7//! whether the source depends on the target. The features of the children
8//! are those of the answer so far.
9
10use std::io::Write;
11use std::ops::Range;
12use std::rc::Rc;
13
14use super::features::{FeatureSet, Prepared};
15use super::shift_reduce::{self, Decision};
16use crate::error::{Error, Result};
17use crate::morpheme::Morpheme;
18use crate::schema::Schema;
19use crate::sentence::Sentence;
20
21/// One decision of the parser, with its answer.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct Instance {
24    /// Whether the source depends on the target.
25    pub label: bool,
26    /// The feature strings of the decision, sorted, each once.
27    pub features: Vec<String>,
28}
29
30/// The training instances of a sentence.
31///
32/// # Arguments
33///
34/// * `schema` - The schema of the dictionary of the morphemes.
35/// * `set` - The groups of features to make.
36/// * `sentence` - The sentence, with the head of every bunsetsu.
37///
38/// # Returns
39///
40/// The instances, in the order the parser asks the decisions; none for a
41/// sentence of two bunsetsu or fewer, where nothing is asked.
42/// [`Error::Structure`] when the sentence does not pass
43/// [`Sentence::check`], or when its tree is not one the parser can make
44/// ([`Sentence::violations`]); [`Error::Dictionary`] for a morpheme with
45/// fewer feature columns than the schema reads ([`Schema::check`]).
46pub fn instances<M: Morpheme>(
47    schema: &Schema,
48    set: &FeatureSet,
49    sentence: &Sentence<M>,
50) -> Result<Vec<Instance>> {
51    sentence.check()?;
52    schema.check(&sentence.morphemes)?;
53    if let Some(violation) = sentence.violations().first() {
54        return Err(Error::Structure(format!(
55            "the parser cannot make the tree of the sentence: {violation}"
56        )));
57    }
58    let ranges: Vec<Range<usize>> = sentence
59        .bunsetsu
60        .iter()
61        .map(|bunsetsu| bunsetsu.morphemes.clone())
62        .collect();
63    let answer: Vec<Option<usize>> = sentence
64        .bunsetsu
65        .iter()
66        .map(|bunsetsu| bunsetsu.head)
67        .collect();
68
69    let prepared: Prepared<Rc<str>> =
70        Prepared::new(schema, set, &sentence.morphemes, &ranges, |feature| {
71            Some(Rc::from(feature))
72        });
73    let mut instances = Vec::new();
74    let mut features = Vec::new();
75    let arcs = shift_reduce::parse(ranges.len(), |source, target, children| {
76        prepared.decision(source, target, children, &mut features);
77        let label = answer[source] == Some(target);
78        instances.push(Instance {
79            label,
80            features: features.iter().map(|feature| feature.to_string()).collect(),
81        });
82        Decision {
83            attach: label,
84            score: 0.0,
85        }
86    });
87    // A tree without a violation is given back as it is: anything else is a
88    // fault of the loop, and instances from it would teach the wrong
89    // decisions.
90    if arcs.heads != answer {
91        return Err(Error::Structure(
92            "the answer of the sentence did not give its tree back".to_string(),
93        ));
94    }
95    Ok(instances)
96}
97
98/// Writes the training instances of a sentence.
99///
100/// One line for each instance: `+1` when the source depends on the target
101/// and `-1` when it does not, then its feature strings, all separated by
102/// tabs. An empty line ends the sentence, so that a file can be cut into
103/// folds between sentences.
104///
105/// # Arguments
106///
107/// * `writer` - Where to write.
108/// * `instances` - The instances of one sentence.
109///
110/// # Returns
111///
112/// `Ok(())`, [`Error::Structure`] for a feature that holds a tab or a line
113/// break, or [`Error::Io`].
114pub fn write_instances<W: Write>(writer: &mut W, instances: &[Instance]) -> Result<()> {
115    for instance in instances {
116        write!(writer, "{}", if instance.label { "+1" } else { "-1" })?;
117        for feature in &instance.features {
118            if feature.contains(['\t', '\n', '\r']) {
119                return Err(Error::Structure(format!(
120                    "the feature {feature:?} holds a tab or a line break"
121                )));
122            }
123            write!(writer, "\t{feature}")?;
124        }
125        writeln!(writer)?;
126    }
127    writeln!(writer)?;
128    Ok(())
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134    use crate::lattice::LatticeMorpheme;
135    use crate::parser::fixtures;
136    use crate::sentence::Bunsetsu;
137
138    /// The sentence of the fixtures with heads.
139    fn sentence(heads: &[Option<usize>]) -> Sentence<LatticeMorpheme> {
140        let (morphemes, ranges) = fixtures::sentence();
141        Sentence {
142            comments: Vec::new(),
143            morphemes,
144            bunsetsu: ranges
145                .into_iter()
146                .zip(heads)
147                .map(|(range, head)| Bunsetsu::new(range, *head))
148                .collect(),
149        }
150    }
151
152    /// The instances of a sentence, with every group of features.
153    fn all(sentence: &Sentence<LatticeMorpheme>) -> Result<Vec<Instance>> {
154        instances(&Schema::ipadic(), &FeatureSet::cabocha(), sentence)
155    }
156
157    /// The features of an instance that start with a prefix.
158    fn starting<'a>(instance: &'a Instance, prefix: &str) -> Vec<&'a str> {
159        instance
160            .features
161            .iter()
162            .map(String::as_str)
163            .filter(|feature| feature.starts_with(prefix))
164            .collect()
165    }
166
167    #[test]
168    fn the_instances_are_the_decisions_of_the_answer() {
169        // 彼は -> 「本, 「本 -> 静かに、, 」を -> 静かに、, 静かに、 -> 読んだ。
170        let answer = sentence(&[Some(1), Some(3), Some(3), Some(4), None]);
171        let instances = all(&answer).unwrap();
172        // (0, 1), (1, 2), (2, 3), (1, 3): the source is named by the
173        // surface of its head, the target by the one of its first morpheme.
174        let decisions: Vec<(Vec<&str>, Vec<&str>, bool)> = instances
175            .iter()
176            .map(|one| (starting(one, "SHS:"), starting(one, "DLS:"), one.label))
177            .collect();
178        assert_eq!(
179            decisions,
180            [
181                (vec!["SHS:彼"], vec!["DLS:「"], true),
182                (vec!["SHS:本"], vec!["DLS:」"], false),
183                (vec!["SHS:」"], vec!["DLS:静か"], true),
184                (vec!["SHS:本"], vec!["DLS:静か"], true),
185            ]
186        );
187    }
188
189    #[test]
190    fn the_children_of_an_instance_are_those_of_the_answer_so_far() {
191        let answer = sentence(&[Some(1), Some(3), Some(3), Some(4), None]);
192        let instances = all(&answer).unwrap();
193        let children: Vec<Vec<&str>> = instances
194            .iter()
195            .map(|one| {
196                let mut children = starting(one, "a:");
197                children.extend(starting(one, "A:"));
198                children
199            })
200            .collect();
201        assert_eq!(
202            children,
203            [
204                vec![],
205                // 彼は is attached to the source 「本.
206                vec!["a:は"],
207                vec![],
208                // And 」を to the target 静かに、 by now.
209                vec!["a:は", "A:を"],
210            ]
211        );
212    }
213
214    #[test]
215    fn the_features_are_those_of_the_feature_set() {
216        let answer = sentence(&[Some(1), Some(3), Some(3), Some(4), None]);
217        let set = FeatureSet::parse("distance").unwrap();
218        let instances = instances(&Schema::ipadic(), &set, &answer).unwrap();
219        let features: Vec<&[String]> = instances
220            .iter()
221            .map(|one| one.features.as_slice())
222            .collect();
223        assert_eq!(features, [["DIST:1"], ["DIST:1"], ["DIST:1"], ["DIST:2-5"]]);
224    }
225
226    #[test]
227    fn nothing_is_asked_for_two_bunsetsu_or_fewer() {
228        let (morphemes, _) = fixtures::sentence();
229        let two = Sentence::new(
230            morphemes[..4].to_vec(),
231            vec![Bunsetsu::new(0..2, Some(1)), Bunsetsu::new(2..4, None)],
232        )
233        .unwrap();
234        assert_eq!(all(&two).unwrap(), []);
235        let none = Sentence::new(morphemes[..4].to_vec(), Vec::new()).unwrap();
236        assert_eq!(all(&none).unwrap(), []);
237    }
238
239    #[test]
240    fn a_tree_the_parser_cannot_make_is_refused() {
241        let refused = [
242            // Crossing arcs: 0 -> 2 and 1 -> 3.
243            (
244                "crossing",
245                sentence(&[Some(2), Some(3), Some(3), Some(4), None]),
246            ),
247            // A head to the left.
248            (
249                "left",
250                sentence(&[Some(1), Some(0), Some(3), Some(4), None]),
251            ),
252            // The root is not the last bunsetsu.
253            (
254                "root",
255                sentence(&[Some(1), Some(3), Some(3), None, Some(3)]),
256            ),
257            // A head that is no bunsetsu.
258            (
259                "range",
260                sentence(&[Some(1), Some(7), Some(3), Some(4), None]),
261            ),
262        ];
263        let accepted: Vec<&str> = refused
264            .iter()
265            .filter(|(_, sentence)| !matches!(all(sentence), Err(Error::Structure(_))))
266            .map(|(name, _)| *name)
267            .collect();
268        assert!(accepted.is_empty(), "not refused: {accepted:?}");
269
270        // The first three are refused for their tree, and the error says
271        // so.
272        let unnamed: Vec<&str> = refused[..3]
273            .iter()
274            .filter(|(_, sentence)| {
275                !all(sentence)
276                    .unwrap_err()
277                    .to_string()
278                    .contains("the parser cannot make the tree of the sentence")
279            })
280            .map(|(name, _)| *name)
281            .collect();
282        assert!(unnamed.is_empty(), "no reason given: {unnamed:?}");
283    }
284
285    #[test]
286    fn a_sentence_whose_bunsetsu_do_not_fit_is_refused() {
287        // The last bunsetsu ends past the morphemes.
288        let mut broken = sentence(&[Some(1), Some(3), Some(3), Some(4), None]);
289        broken.bunsetsu[4].morphemes = 9..13;
290        assert!(matches!(all(&broken), Err(Error::Structure(_))));
291    }
292
293    #[test]
294    fn instances_are_written_one_per_line() {
295        let written = |instances: &[Instance]| -> Result<String> {
296            let mut bytes = Vec::new();
297            write_instances(&mut bytes, instances)?;
298            Ok(String::from_utf8(bytes).unwrap())
299        };
300        let instance = |label: bool, features: &[&str]| Instance {
301            label,
302            features: features.iter().map(|feature| feature.to_string()).collect(),
303        };
304        assert_eq!(
305            written(&[
306                instance(true, &["DIST:1", "SFS:は"]),
307                instance(false, &["DIST:2-5"]),
308            ])
309            .unwrap(),
310            "+1\tDIST:1\tSFS:は\n-1\tDIST:2-5\n\n"
311        );
312        // A sentence without a decision is an empty line.
313        assert_eq!(written(&[]).unwrap(), "\n");
314        for feature in ["SHS:a\tb", "SHS:a\nb"] {
315            assert!(
316                matches!(
317                    written(&[instance(true, &[feature])]),
318                    Err(Error::Structure(_))
319                ),
320                "{feature:?}"
321            );
322        }
323    }
324
325    #[test]
326    fn a_morpheme_of_another_dictionary_is_refused() {
327        let mut sentence = sentence(&[Some(4), Some(2), Some(4), Some(4), None]);
328        sentence.morphemes[0] = LatticeMorpheme::new("彼", "名詞,代名詞");
329        let error = all(&sentence).unwrap_err();
330        assert!(matches!(error, Error::Dictionary(_)), "{error:?}");
331        assert!(
332            error.to_string().starts_with("the morpheme 1 (\"彼\")"),
333            "{error}"
334        );
335    }
336}