1use std::borrow::Cow;
14use std::fmt;
15use std::ops::Range;
16
17use crate::error::{Error, Result};
18use crate::morpheme::{Morpheme, is_space};
19use crate::schema::Schema;
20
21const EMPTY: &str = "*";
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29#[non_exhaustive]
30pub enum Group {
31 Distance,
34 Source,
42 Target,
45 Left,
48 Right,
51 Children,
57 Gap,
63 AfterHead,
71}
72
73impl Group {
74 const ALL: [(Group, &'static str); 8] = [
77 (Group::Distance, "distance"),
78 (Group::Source, "source"),
79 (Group::Target, "target"),
80 (Group::Left, "left"),
81 (Group::Right, "right"),
82 (Group::Children, "children"),
83 (Group::Gap, "gap"),
84 (Group::AfterHead, "after"),
85 ];
86
87 pub fn name(self) -> &'static str {
94 Self::ALL
95 .iter()
96 .find(|(group, _)| *group == self)
97 .map_or("", |(_, name)| name)
98 }
99
100 pub fn from_name(name: &str) -> Option<Self> {
110 Self::ALL
111 .iter()
112 .find(|(_, other)| *other == name)
113 .map(|(group, _)| *group)
114 }
115}
116
117#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct FeatureSet {
130 groups: Vec<Group>,
132 part_of_speech_levels: Option<usize>,
135}
136
137const LEVELS_KEY: &str = "pos-levels=";
140
141impl FeatureSet {
142 pub fn new(groups: &[Group]) -> Result<Self> {
152 if groups.is_empty() {
153 return Err(Error::Parser("a feature set needs a group".to_string()));
154 }
155 for (index, group) in groups.iter().enumerate() {
156 if groups[..index].contains(group) {
157 return Err(Error::Parser(format!(
158 "the group {} is given twice",
159 group.name()
160 )));
161 }
162 }
163 Ok(Self {
164 groups: Group::ALL
165 .iter()
166 .map(|(group, _)| *group)
167 .filter(|group| groups.contains(group))
168 .collect(),
169 part_of_speech_levels: None,
170 })
171 }
172
173 pub fn with_part_of_speech_levels(mut self, levels: usize) -> Result<Self> {
206 if levels == 0 {
207 return Err(Error::Parser(
208 "the features need a level of the part of speech: pos-levels is 1 or more"
209 .to_string(),
210 ));
211 }
212 self.part_of_speech_levels = Some(levels);
213 Ok(self)
214 }
215
216 pub fn part_of_speech_levels(&self) -> Option<usize> {
223 self.part_of_speech_levels
224 }
225
226 fn levels(&self, schema: &Schema) -> Range<usize> {
236 let all = schema.part_of_speech.clone();
237 match self.part_of_speech_levels {
238 Some(levels) => all.start..all.end.min(all.start.saturating_add(levels)),
239 None => all,
240 }
241 }
242
243 pub fn cabocha() -> Self {
249 Self {
250 groups: Group::ALL
251 .iter()
252 .map(|(group, _)| *group)
253 .filter(|group| *group != Group::AfterHead)
254 .collect(),
255 part_of_speech_levels: None,
256 }
257 }
258
259 pub fn parse(text: &str) -> Result<Self> {
273 let mut groups = Vec::new();
274 let mut levels = None;
275 for name in text.split(',') {
276 let name = name.trim();
277 if let Some(value) = name.strip_prefix(LEVELS_KEY) {
278 if levels.is_some() {
279 return Err(Error::Parser(format!("{LEVELS_KEY} is given twice")));
280 }
281 levels = Some(value.parse::<usize>().map_err(|_| {
282 Error::Parser(format!(
283 "{name:?} is not a number of levels of the part of speech"
284 ))
285 })?);
286 continue;
287 }
288 groups
289 .push(Group::from_name(name).ok_or_else(|| {
290 Error::Parser(format!("{name:?} is not a group of features"))
291 })?);
292 }
293 let set = Self::new(&groups)?;
294 match levels {
295 Some(levels) => set.with_part_of_speech_levels(levels),
296 None => Ok(set),
297 }
298 }
299
300 pub fn groups(&self) -> &[Group] {
307 &self.groups
308 }
309
310 pub fn has(&self, group: Group) -> bool {
320 self.groups.contains(&group)
321 }
322}
323
324impl Default for FeatureSet {
325 fn default() -> Self {
328 Self {
329 groups: Group::ALL.iter().map(|(group, _)| *group).collect(),
330 part_of_speech_levels: None,
331 }
332 }
333}
334
335impl fmt::Display for FeatureSet {
336 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
340 for (index, group) in self.groups.iter().enumerate() {
341 if index > 0 {
342 write!(f, ",")?;
343 }
344 write!(f, "{}", group.name())?;
345 }
346 if let Some(levels) = self.part_of_speech_levels {
347 write!(f, ",{LEVELS_KEY}{levels}")?;
348 }
349 Ok(())
350 }
351}
352
353#[derive(Debug, Clone, PartialEq)]
359struct Roles<T> {
360 source: Vec<T>,
362 target: Vec<T>,
364 left: Vec<T>,
366 right: Vec<T>,
368 gap: Vec<T>,
371 after_source: Vec<T>,
373 after_target: Vec<T>,
375 child_of_source: Option<T>,
377 child_of_target: Option<T>,
379 opens: bool,
381 closes: bool,
383}
384
385#[derive(Debug, Clone, PartialEq)]
388pub(crate) struct Prepared<T> {
389 bunsetsu: Vec<Roles<T>>,
391 distance: [Option<T>; 3],
393 brackets: [Option<T>; 4],
396}
397
398impl<T: Clone + Ord> Prepared<T> {
399 pub(crate) fn new<M: Morpheme>(
415 schema: &Schema,
416 set: &FeatureSet,
417 morphemes: &[M],
418 bunsetsu: &[Range<usize>],
419 mut intern: impl FnMut(&str) -> Option<T>,
420 ) -> Self {
421 let last = bunsetsu.len().saturating_sub(1);
422 let roles = bunsetsu
423 .iter()
424 .enumerate()
425 .map(|(index, range)| {
426 let strings = Strings::new(
427 schema,
428 set.levels(schema),
429 &morphemes[range.clone()],
430 index == 0,
431 index == last,
432 );
433 let mut role = |group: Group, prefix: &str, names: &[String]| -> Vec<T> {
434 if !set.has(group) {
435 return Vec::new();
436 }
437 names
438 .iter()
439 .filter_map(|name| intern(&format!("{prefix}{name}")))
440 .collect()
441 };
442 let source = role(Group::Source, "S", &strings.statics);
443 let target = role(Group::Target, "D", &strings.statics);
444 let left = role(Group::Left, "", &strings.left);
445 let right = role(Group::Right, "", &strings.right);
446 let gap = role(Group::Gap, "", &strings.gap);
447 let after_source = role(Group::AfterHead, "S", &strings.after);
448 let after_target = role(Group::AfterHead, "D", &strings.after);
449 let child = std::slice::from_ref(&strings.child);
450 let child_of_source = role(Group::Children, "a:", child).pop();
451 let child_of_target = role(Group::Children, "A:", child).pop();
452 Roles {
453 source,
454 target,
455 left,
456 right,
457 gap,
458 after_source,
459 after_target,
460 child_of_source,
461 child_of_target,
462 opens: strings.opens,
463 closes: strings.closes,
464 }
465 })
466 .collect();
467 let mut named = |group: Group, name: &str| {
468 if set.has(group) { intern(name) } else { None }
469 };
470 Self {
471 bunsetsu: roles,
472 distance: [
473 named(Group::Distance, "DIST:1"),
474 named(Group::Distance, "DIST:2-5"),
475 named(Group::Distance, "DIST:6-"),
476 ],
477 brackets: [
478 named(Group::Gap, "GNB:1"),
479 named(Group::Gap, "GOB:1"),
480 named(Group::Gap, "GCB:1"),
481 named(Group::Gap, "GBB:1"),
482 ],
483 }
484 }
485
486 pub(crate) fn decision(
496 &self,
497 source: usize,
498 target: usize,
499 children: &[Vec<usize>],
500 features: &mut Vec<T>,
501 ) {
502 features.clear();
503 let class = match target - source {
504 1 => 0,
505 2..=5 => 1,
506 _ => 2,
507 };
508 features.extend(self.distance[class].clone());
509 features.extend_from_slice(&self.bunsetsu[source].source);
510 features.extend_from_slice(&self.bunsetsu[target].target);
511 features.extend_from_slice(&self.bunsetsu[source].after_source);
512 features.extend_from_slice(&self.bunsetsu[target].after_target);
513 if source > 0 {
514 features.extend_from_slice(&self.bunsetsu[source - 1].left);
515 }
516 if let Some(after) = self.bunsetsu.get(target + 1) {
517 features.extend_from_slice(&after.right);
518 }
519 for &child in &children[source] {
522 features.extend(self.bunsetsu[child].child_of_source.clone());
523 }
524 for &child in &children[target] {
525 features.extend(self.bunsetsu[child].child_of_target.clone());
526 }
527 let mut opens = false;
528 let mut closes = false;
529 for between in &self.bunsetsu[source + 1..target] {
530 features.extend_from_slice(&between.gap);
531 opens |= between.opens;
532 closes |= between.closes;
533 }
534 let state = usize::from(opens) + 2 * usize::from(closes);
535 features.extend(self.brackets[state].clone());
536 features.sort_unstable();
537 features.dedup();
538 }
539}
540
541#[derive(Debug, Clone, PartialEq, Eq)]
543struct Strings {
544 statics: Vec<String>,
547 left: Vec<String>,
549 right: Vec<String>,
551 gap: Vec<String>,
553 after: Vec<String>,
556 child: String,
558 opens: bool,
560 closes: bool,
562}
563
564impl Strings {
565 fn new<M: Morpheme>(
578 schema: &Schema,
579 levels: Range<usize>,
580 morphemes: &[M],
581 first: bool,
582 last: bool,
583 ) -> Self {
584 let words: Vec<&M> = morphemes
589 .iter()
590 .filter(|morpheme| !is_space(*morpheme))
591 .collect();
592 if words.is_empty() || words.len() == morphemes.len() {
593 Self::of_words(schema, levels, morphemes, first, last)
594 } else {
595 Self::of_words(schema, levels, &words, first, last)
596 }
597 }
598
599 fn of_words<M: Morpheme>(
614 schema: &Schema,
615 levels: Range<usize>,
616 morphemes: &[M],
617 first: bool,
618 last: bool,
619 ) -> Self {
620 let mut statics = Vec::new();
621 let mut gap = Vec::new();
622 let mut opens = false;
623 let mut closes = false;
624 for (index, morpheme) in morphemes.iter().enumerate() {
625 let surface = schema.surface_of(morpheme);
626 if schema.is_comma(morpheme) || schema.is_period(morpheme) {
627 gap.push(format!("GPUNC:{surface}"));
628 statics.push(format!("PUNC:{surface}"));
629 }
630 if schema.is_open_bracket(morpheme) {
631 gap.push(format!("GOB:{surface}"));
632 statics.push(format!("OB:{surface}"));
633 statics.push("OB:1".to_string());
634 opens = true;
635 }
636 if schema.is_close_bracket(morpheme) {
637 gap.push(format!("GCB:{surface}"));
638 statics.push(format!("CB:{surface}"));
639 statics.push("CB:1".to_string());
640 closes = true;
641 }
642 if schema.is_particle(morphemes, index) {
643 statics.push(format!("CASE:{surface}"));
644 }
645 }
646
647 let (head, function) = schema.positions(morphemes).unwrap_or((0, 0));
648 let end = morphemes.len().saturating_sub(1);
649 for (role, index) in [('H', head), ('F', function), ('L', 0), ('R', end)] {
650 if let Some(morpheme) = morphemes.get(index) {
651 push_morpheme(schema, levels.clone(), role, morpheme, &mut statics);
652 }
653 }
654 let mut after = Vec::new();
655 if let Some(morpheme) = morphemes.get(head + 1) {
656 push_morpheme(schema, levels.clone(), 'N', morpheme, &mut after);
657 }
658 if first {
659 statics.push("BOS:1".to_string());
660 }
661 if last {
662 statics.push("EOS:1".to_string());
663 }
664
665 let surface = |index: usize| {
666 morphemes
667 .get(index)
668 .map_or(Cow::Borrowed(""), |morpheme| schema.surface_of(morpheme))
669 };
670 let left = vec![format!("LF:{}", surface(function))];
671 let right = vec![
672 format!("RL:{}", surface(0)),
673 format!("RH:{}", surface(head)),
674 format!("RF:{}", surface(function)),
675 ];
676 if schema.is_particle(morphemes, function) {
677 gap.push(format!("GCASE:{}", surface(function)));
678 }
679
680 let child = if schema.is_lexicalized(morphemes, function) {
681 surface(function).to_string()
682 } else {
683 morphemes
684 .get(function)
685 .and_then(|morpheme| conjugation_form(schema, morpheme))
686 .map(str::to_string)
687 .or_else(|| {
688 morphemes
689 .get(function)
690 .map(|morpheme| schema.levels_of(morpheme, levels.clone()))
691 })
692 .unwrap_or_default()
693 };
694
695 Self {
696 statics,
697 left,
698 right,
699 gap,
700 after,
701 child,
702 opens,
703 closes,
704 }
705 }
706}
707
708fn conjugation_form<'a, M: Morpheme>(schema: &Schema, morpheme: &'a M) -> Option<&'a str> {
720 schema
721 .conjugation_form
722 .and_then(|index| morpheme.feature(index))
723 .filter(|form| *form != EMPTY)
724}
725
726fn push_morpheme<M: Morpheme>(
740 schema: &Schema,
741 levels: Range<usize>,
742 role: char,
743 morpheme: &M,
744 features: &mut Vec<String>,
745) {
746 features.push(format!("{role}S:{}", schema.surface_of(morpheme)));
747 for (level, index) in levels.enumerate() {
748 match morpheme.feature(index) {
749 Some(value) if value != EMPTY => features.push(format!("{role}P{level}:{value}")),
750 _ => break,
751 }
752 }
753 if let Some(form) = conjugation_form(schema, morpheme) {
754 features.push(format!("{role}F:{form}"));
755 }
756}
757
758#[cfg(test)]
759#[allow(clippy::single_range_in_vec_init)]
762mod tests {
763 use super::*;
764 use crate::lattice::LatticeMorpheme;
765 use crate::parser::fixtures;
766
767 fn prepared(
769 set: &FeatureSet,
770 sentence: &(Vec<LatticeMorpheme>, Vec<Range<usize>>),
771 ) -> Prepared<String> {
772 Prepared::new(
773 &Schema::ipadic(),
774 set,
775 &sentence.0,
776 &sentence.1,
777 |feature| Some(feature.to_string()),
778 )
779 }
780
781 fn decision(
783 prepared: &Prepared<String>,
784 source: usize,
785 target: usize,
786 children: &[Vec<usize>],
787 ) -> Vec<String> {
788 let mut features = Vec::new();
789 prepared.decision(source, target, children, &mut features);
790 features
791 }
792
793 fn no_children(count: usize) -> Vec<Vec<usize>> {
795 vec![Vec::new(); count]
796 }
797
798 fn is_of(group: Group, feature: &str) -> bool {
800 match group {
801 Group::Distance => feature.starts_with("DIST:"),
802 Group::Source => feature.starts_with('S') && !feature.starts_with("SN"),
803 Group::Target => {
804 feature.starts_with('D')
805 && !feature.starts_with("DIST:")
806 && !feature.starts_with("DN")
807 }
808 Group::Left => feature.starts_with("LF:"),
809 Group::Right => feature.starts_with('R'),
810 Group::Children => feature.starts_with("a:") || feature.starts_with("A:"),
811 Group::Gap => feature.starts_with('G'),
812 Group::AfterHead => feature.starts_with("SN") || feature.starts_with("DN"),
813 }
814 }
815
816 #[test]
817 fn the_surfaces_of_the_features_are_the_normalized_ones_of_the_schema() {
818 let noun = "名詞,一般,*,*,*,*,*";
821 let particle = "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ";
822 let morphemes = vec![
823 LatticeMorpheme::new("A", noun),
824 LatticeMorpheme::new("ヲ", particle),
825 LatticeMorpheme::new("B", noun),
826 LatticeMorpheme::new("(", "名詞,サ変接続,*,*,*,*,*"),
827 LatticeMorpheme::new("ヲ", particle),
828 LatticeMorpheme::new("C", noun),
829 LatticeMorpheme::new("ヲ", particle),
830 LatticeMorpheme::new("D", noun),
831 LatticeMorpheme::new("ヲ", particle),
832 LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
833 ];
834 let ranges = vec![0..2, 2..5, 5..7, 7..9, 9..10];
835 let mut children = no_children(5);
837 children[1].push(0);
838 let features = |schema: &Schema, source: usize, target: usize| -> Vec<String> {
839 let prepared = Prepared::new(
840 schema,
841 &FeatureSet::cabocha(),
842 &morphemes,
843 &ranges,
844 |feature| Some(feature.to_string()),
845 );
846 decision(&prepared, source, target, &children)
847 };
848 let schema = Schema {
849 normalization: crate::schema::Normalization::new(&[
850 ("A", "A"),
851 ("B", "B"),
852 ("C", "C"),
853 ("D", "D"),
854 ("(", "("),
855 ("ヲ", "ヲ"),
856 ])
857 .unwrap(),
858 ..Schema::ipadic()
859 };
860 let normalized = features(&schema, 1, 3);
862 for feature in [
863 "SHS:B",
865 "SLS:B",
866 "SFS:ヲ",
867 "SRS:ヲ",
868 "SOB:(",
869 "SOB:1",
870 "SCASE:ヲ",
871 "DHS:D",
872 "DCASE:ヲ",
873 "LF:ヲ",
875 "a:ヲ",
876 "GCASE:ヲ",
878 ] {
879 assert!(
880 normalized.iter().any(|one| one == feature),
881 "{feature}: {normalized:?}"
882 );
883 }
884 let first = features(&schema, 0, 1);
887 for feature in ["RL:C", "RH:C", "RF:ヲ", "DOB:("] {
888 assert!(
889 first.iter().any(|one| one == feature),
890 "{feature}: {first:?}"
891 );
892 }
893 let over = features(&schema, 0, 2);
894 assert!(over.iter().any(|one| one == "GOB:("), "{over:?}");
895 for all in [&normalized, &first, &over] {
896 assert!(
897 !all.iter()
898 .any(|one| "ABCD(ヲ".chars().any(|wide| one.contains(wide))),
899 "{all:?}"
900 );
901 }
902 let plain = features(&Schema::ipadic(), 1, 3);
904 for feature in [
905 "SHS:B",
906 "SFS:ヲ",
907 "SOB:(",
908 "SCASE:ヲ",
909 "DHS:D",
910 "LF:ヲ",
911 "a:ヲ",
912 "GCASE:ヲ",
913 ] {
914 assert!(
915 plain.iter().any(|one| one == feature),
916 "{feature}: {plain:?}"
917 );
918 }
919 }
920
921 #[test]
922 fn a_decision_has_the_features_of_cabocha() {
923 let prepared = prepared(&FeatureSet::cabocha(), &fixtures::sentence());
924 let mut expected = vec![
926 "DIST:1",
927 "SHS:彼",
930 "SHP0:名詞",
931 "SHP1:代名詞",
932 "SHP2:一般",
933 "SFS:は",
934 "SFP0:助詞",
935 "SFP1:係助詞",
936 "SLS:彼",
937 "SLP0:名詞",
938 "SLP1:代名詞",
939 "SLP2:一般",
940 "SRS:は",
941 "SRP0:助詞",
942 "SRP1:係助詞",
943 "SCASE:は",
944 "SBOS:1",
945 "DHS:本",
948 "DHP0:名詞",
949 "DHP1:一般",
950 "DFS:本",
951 "DFP0:名詞",
952 "DFP1:一般",
953 "DLS:「",
954 "DLP0:記号",
955 "DLP1:括弧開",
956 "DRS:本",
957 "DRP0:名詞",
958 "DRP1:一般",
959 "DOB:「",
960 "DOB:1",
961 "RL:」",
964 "RH:」",
965 "RF:を",
966 "GNB:1",
968 ];
969 expected.sort_unstable();
970 assert_eq!(decision(&prepared, 0, 1, &no_children(5)), expected);
971 }
972
973 #[test]
974 fn the_conjugation_form_and_the_marks_of_a_bunsetsu_are_features() {
975 let prepared = prepared(&FeatureSet::cabocha(), &fixtures::sentence());
976 let features = decision(&prepared, 3, 4, &no_children(5));
978 let missing: Vec<&str> = [
979 "SPUNC:、",
980 "SCASE:に",
981 "LF:を",
982 "DHF:連用タ接続",
983 "DFF:基本形",
984 "DPUNC:。",
985 "DEOS:1",
986 ]
987 .into_iter()
988 .filter(|expected| !features.iter().any(|feature| feature == expected))
989 .collect();
990 assert!(missing.is_empty(), "{missing:?} not in {features:?}");
991 let present: Vec<&str> = ["RL:", "RH:", "RF:", "SBOS:", "SEOS:", "DBOS:"]
994 .into_iter()
995 .filter(|absent| features.iter().any(|feature| feature.starts_with(absent)))
996 .collect();
997 assert!(present.is_empty(), "{present:?} in {features:?}");
998 let features = decision(&prepared, 2, 3, &no_children(5));
1000 let missing: Vec<&str> = ["SCB:」", "SCB:1"]
1001 .into_iter()
1002 .filter(|expected| !features.iter().any(|feature| feature == expected))
1003 .collect();
1004 assert!(missing.is_empty(), "{missing:?} not in {features:?}");
1005 }
1006
1007 #[test]
1008 fn the_levels_of_the_part_of_speech_stop_at_the_first_empty_one() {
1009 let morphemes = [LatticeMorpheme::new("語", "名詞,*,一般,*,*,*,語,ゴ,ゴ")];
1011 let strings = Strings::new(&Schema::ipadic(), 0..4, &morphemes, false, false);
1012 let levels: Vec<&str> = strings
1013 .statics
1014 .iter()
1015 .map(String::as_str)
1016 .filter(|feature| feature.starts_with("HP"))
1017 .collect();
1018 assert_eq!(levels, ["HP0:名詞"]);
1019 }
1020
1021 #[test]
1022 fn a_limit_holds_the_features_to_that_many_levels_of_the_part_of_speech() {
1023 let schema = Schema {
1025 part_of_speech: 0..4,
1026 conjugation_form: Some(5),
1027 ..Schema::default()
1028 };
1029 let all = FeatureSet::cabocha();
1030 let two = FeatureSet::cabocha().with_part_of_speech_levels(2).unwrap();
1031 assert_eq!(all.levels(&schema), 0..4);
1032 assert_eq!(two.levels(&schema), 0..2);
1033 let nine = FeatureSet::cabocha().with_part_of_speech_levels(9).unwrap();
1035 assert_eq!(nine.levels(&schema), 0..4);
1036 let later = Schema {
1038 part_of_speech: 3..7,
1039 ..Schema::default()
1040 };
1041 assert_eq!(two.levels(&later), 3..5);
1042
1043 let morphemes = [LatticeMorpheme::new(
1045 "太郎",
1046 "名詞,固有名詞,人名,名,*,*,タロウ,タロウ",
1047 )];
1048 let levels = |set: &FeatureSet| -> (Vec<String>, String) {
1049 let strings = Strings::new(&schema, set.levels(&schema), &morphemes, false, false);
1050 let names = strings
1051 .statics
1052 .iter()
1053 .filter(|feature| feature.starts_with("HP"))
1054 .cloned()
1055 .collect();
1056 (names, strings.child)
1057 };
1058 assert_eq!(
1061 levels(&all),
1062 (
1063 vec![
1064 "HP0:名詞".to_string(),
1065 "HP1:固有名詞".to_string(),
1066 "HP2:人名".to_string(),
1067 "HP3:名".to_string()
1068 ],
1069 "名詞-固有名詞-人名-名".to_string()
1070 )
1071 );
1072 assert_eq!(
1073 levels(&two),
1074 (
1075 vec!["HP0:名詞".to_string(), "HP1:固有名詞".to_string()],
1076 "名詞-固有名詞".to_string()
1077 )
1078 );
1079 let pair = [morphemes[0].clone(), morphemes[0].clone()];
1081 let decisions = |set: &FeatureSet| -> Vec<String> {
1082 let prepared = Prepared::new(&schema, set, &pair, &[0..1, 1..2], |feature| {
1083 Some(feature.to_string())
1084 });
1085 decision(&prepared, 0, 1, &no_children(2))
1086 };
1087 assert!(decisions(&all).iter().any(|one| one == "SHP3:名"));
1088 assert!(!decisions(&two).iter().any(|one| one == "SHP2:人名"));
1089 assert!(decisions(&two).iter().any(|one| one == "SHP1:固有名詞"));
1090 }
1091
1092 #[test]
1093 fn the_limit_of_the_levels_is_part_of_the_text_of_a_set() {
1094 let set = FeatureSet::parse("gap, pos-levels=2 ,source").unwrap();
1095 assert_eq!(set.groups(), [Group::Source, Group::Gap]);
1096 assert_eq!(set.part_of_speech_levels(), Some(2));
1097 assert_eq!(set.to_string(), "source,gap,pos-levels=2");
1099 assert_eq!(FeatureSet::parse(&set.to_string()).unwrap(), set);
1100 let plain = FeatureSet::parse("source,gap").unwrap();
1102 assert_eq!(plain.part_of_speech_levels(), None);
1103 assert_eq!(plain.to_string(), "source,gap");
1104 assert_ne!(plain, set);
1105 assert_eq!(FeatureSet::cabocha().part_of_speech_levels(), None);
1106 assert_eq!(FeatureSet::default().part_of_speech_levels(), None);
1107
1108 let message = |text: &str| FeatureSet::parse(text).unwrap_err().to_string();
1109 assert_eq!(
1110 message("source,pos-levels=0"),
1111 "the features need a level of the part of speech: pos-levels is 1 or more"
1112 );
1113 assert_eq!(
1114 message("source,pos-levels=two"),
1115 "\"pos-levels=two\" is not a number of levels of the part of speech"
1116 );
1117 assert_eq!(
1118 message("source,pos-levels="),
1119 "\"pos-levels=\" is not a number of levels of the part of speech"
1120 );
1121 assert_eq!(
1122 message("pos-levels=2,source,pos-levels=3"),
1123 "pos-levels= is given twice"
1124 );
1125 assert_eq!(message("pos-levels=2"), "a feature set needs a group");
1127 assert!(matches!(
1128 FeatureSet::cabocha().with_part_of_speech_levels(0),
1129 Err(Error::Parser(_))
1130 ));
1131 }
1132
1133 #[test]
1134 fn the_distance_has_three_classes() {
1135 let prepared = prepared(&FeatureSet::cabocha(), &fixtures::repeated(8));
1136 let classes: Vec<String> = [1, 2, 5, 6, 7]
1137 .iter()
1138 .map(|&target| {
1139 decision(&prepared, 0, target, &no_children(8))
1140 .into_iter()
1141 .find(|feature| feature.starts_with("DIST:"))
1142 .unwrap_or_default()
1143 })
1144 .collect();
1145 assert_eq!(
1146 classes,
1147 ["DIST:1", "DIST:2-5", "DIST:2-5", "DIST:6-", "DIST:6-"]
1148 );
1149 }
1150
1151 #[test]
1152 fn the_gap_has_the_marks_in_between_and_the_state_of_the_brackets() {
1153 let prepared = prepared(&FeatureSet::cabocha(), &fixtures::sentence());
1154 let gap = |source: usize, target: usize| -> Vec<String> {
1155 decision(&prepared, source, target, &no_children(5))
1156 .into_iter()
1157 .filter(|feature| feature.starts_with('G'))
1158 .collect()
1159 };
1160 assert_eq!(gap(1, 2), ["GNB:1"]);
1163 assert_eq!(gap(0, 2), ["GOB:1", "GOB:「"]);
1165 assert_eq!(gap(1, 3), ["GCASE:を", "GCB:1", "GCB:」"]);
1167 assert_eq!(
1169 gap(0, 4),
1170 [
1171 "GBB:1",
1172 "GCASE:に",
1173 "GCASE:を",
1174 "GCB:」",
1175 "GOB:「",
1176 "GPUNC:、"
1177 ]
1178 );
1179 }
1180
1181 #[test]
1182 fn the_children_are_named_by_their_function_word() {
1183 let prepared = prepared(&FeatureSet::cabocha(), &fixtures::sentence());
1184 let children = |features: Vec<String>| -> Vec<String> {
1185 features
1186 .into_iter()
1187 .filter(|feature| is_of(Group::Children, feature))
1188 .collect()
1189 };
1190 assert_eq!(
1192 children(decision(&prepared, 1, 3, &no_children(5))),
1193 [""; 0]
1194 );
1195 let attached = vec![vec![], vec![0], vec![], vec![2], vec![]];
1198 assert_eq!(
1199 children(decision(&prepared, 1, 3, &attached)),
1200 ["A:を", "a:は"]
1201 );
1202 let attached = vec![vec![], vec![], vec![1], vec![4], vec![]];
1205 assert_eq!(
1206 children(decision(&prepared, 2, 3, &attached)),
1207 ["A:基本形", "a:名詞-一般"]
1208 );
1209 }
1210
1211 #[test]
1212 fn a_feature_is_in_a_decision_once() {
1213 let prepared = prepared(&FeatureSet::cabocha(), &fixtures::repeated(4));
1215 let features = decision(&prepared, 0, 3, &no_children(4));
1216 let particles = features
1217 .iter()
1218 .filter(|feature| *feature == "GCASE:を")
1219 .count();
1220 assert_eq!(particles, 1);
1221 let mut sorted = features.clone();
1222 sorted.sort_unstable();
1223 sorted.dedup();
1224 assert_eq!(features, sorted);
1225 }
1226
1227 #[test]
1228 fn a_feature_that_is_not_interned_is_left_out() {
1229 let (morphemes, ranges) = fixtures::sentence();
1230 let known = ["GNB:1", "RF:を", "SFS:は", "DIST:1"];
1231 let prepared: Prepared<u32> = Prepared::new(
1232 &Schema::ipadic(),
1233 &FeatureSet::cabocha(),
1234 &morphemes,
1235 &ranges,
1236 |feature| {
1237 known
1238 .iter()
1239 .position(|one| *one == feature)
1240 .map(|index| index as u32)
1241 },
1242 );
1243 let mut features = Vec::new();
1244 prepared.decision(0, 1, &no_children(5), &mut features);
1245 assert_eq!(features, [0, 1, 2, 3]);
1247 }
1248
1249 #[test]
1250 fn a_group_left_out_gives_none_of_its_features() {
1251 let sentence = fixtures::sentence();
1252 let attached = vec![vec![], vec![0], vec![], vec![2], vec![]];
1253 let all = decision(
1254 &prepared(&FeatureSet::default(), &sentence),
1255 1,
1256 3,
1257 &attached,
1258 );
1259 let mut failures = Vec::new();
1260 for (group, name) in Group::ALL {
1261 if !all.iter().any(|feature| is_of(group, feature)) {
1263 failures.push(format!("the decision has no feature of {name}"));
1264 }
1265 let others: Vec<Group> = Group::ALL
1266 .iter()
1267 .map(|(other, _)| *other)
1268 .filter(|other| *other != group)
1269 .collect();
1270 let without = decision(
1271 &prepared(&FeatureSet::new(&others).unwrap(), &sentence),
1272 1,
1273 3,
1274 &attached,
1275 );
1276 let expected: Vec<String> = all
1277 .iter()
1278 .filter(|feature| !is_of(group, feature))
1279 .cloned()
1280 .collect();
1281 if without != expected {
1282 failures.push(format!("without {name}: {without:?}"));
1283 }
1284 }
1285 assert!(failures.is_empty(), "{failures:#?}");
1286 }
1287
1288 #[test]
1289 fn the_morpheme_after_the_head_is_a_feature_of_the_source_and_of_the_target() {
1290 let morphemes: Vec<LatticeMorpheme> = [
1293 ("利用", "名詞,サ変接続,*,*,*,*,利用,リヨウ,リヨー"),
1294 ("し", "動詞,自立,*,*,サ変・スル,連用形,する,シ,シ"),
1295 ("た", "助動詞,*,*,*,特殊・タ,基本形,た,タ,タ"),
1296 ("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム"),
1297 ("こと", "名詞,非自立,一般,*,*,*,こと,コト,コト"),
1298 ("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ"),
1299 ("知っ", "動詞,自立,*,*,五段・ラ行,連用タ接続,知る,シッ,シッ"),
1300 ("た", "助動詞,*,*,*,特殊・タ,基本形,た,タ,タ"),
1301 ]
1302 .iter()
1303 .map(|(surface, features)| LatticeMorpheme::new(*surface, *features))
1304 .collect();
1305 let sentence = (morphemes, vec![0..3, 3..6, 6..8]);
1306 let after = |set: &FeatureSet, source: usize, target: usize| -> Vec<String> {
1307 decision(&prepared(set, &sentence), source, target, &no_children(3))
1308 .into_iter()
1309 .filter(|feature| is_of(Group::AfterHead, feature))
1310 .collect()
1311 };
1312 assert_eq!(
1313 after(&FeatureSet::default(), 0, 1),
1314 [
1315 "DNP0:名詞",
1316 "DNP1:非自立",
1317 "DNP2:一般",
1318 "DNS:こと",
1319 "SNF:連用形",
1320 "SNP0:動詞",
1321 "SNP1:自立",
1322 "SNS:し"
1323 ]
1324 );
1325 assert_eq!(
1327 after(&FeatureSet::default(), 1, 2),
1328 [
1329 "DNF:基本形",
1330 "DNP0:助動詞",
1331 "DNS:た",
1332 "SNP0:名詞",
1333 "SNP1:非自立",
1334 "SNP2:一般",
1335 "SNS:こと"
1336 ]
1337 );
1338 assert!(after(&FeatureSet::cabocha(), 0, 1).is_empty());
1341 let (morphemes, _) = &sentence;
1342 let alone = (morphemes[3..4].to_vec(), vec![0..1]);
1343 let prepared = prepared(&FeatureSet::default(), &alone);
1344 assert!(prepared.bunsetsu[0].after_source.is_empty());
1345 assert!(prepared.bunsetsu[0].after_target.is_empty());
1346 }
1347
1348 #[test]
1349 fn a_feature_set_is_read_from_its_text_and_written_back() {
1350 assert_eq!(
1351 FeatureSet::cabocha().to_string(),
1352 "distance,source,target,left,right,children,gap"
1353 );
1354 assert_eq!(
1356 FeatureSet::default().to_string(),
1357 "distance,source,target,left,right,children,gap,after"
1358 );
1359 assert!(!FeatureSet::cabocha().has(Group::AfterHead));
1360 assert_eq!(Group::ALL.len(), 8);
1361 let set = FeatureSet::parse("gap, source ,distance").unwrap();
1363 assert_eq!(set.groups(), [Group::Distance, Group::Source, Group::Gap]);
1364 assert_eq!(set.to_string(), "distance,source,gap");
1365 assert_eq!(FeatureSet::parse(&set.to_string()).unwrap(), set);
1366 assert!(set.has(Group::Gap));
1367 assert!(!set.has(Group::Children));
1368 for (group, name) in Group::ALL {
1369 assert_eq!(group.name(), name);
1370 assert_eq!(Group::from_name(name), Some(group));
1371 }
1372 }
1373
1374 #[test]
1375 fn a_feature_set_that_cannot_be_read_is_refused() {
1376 let accepted: Vec<&str> = ["", "distance,", "distance,head", "gap,distance,gap"]
1377 .into_iter()
1378 .filter(|text| !matches!(FeatureSet::parse(text), Err(Error::Parser(_))))
1379 .collect();
1380 assert!(accepted.is_empty(), "not refused: {accepted:?}");
1381 assert!(matches!(FeatureSet::new(&[]), Err(Error::Parser(_))));
1382 }
1383
1384 #[test]
1385 fn the_features_of_a_bunsetsu_are_those_of_its_words() {
1386 let schema = Schema::ipadic();
1387 let space =
1388 LatticeMorpheme::new("\u{3000}", "記号,空白,*,*,*,*,\u{3000},\u{3000},\u{3000}");
1389 let hon = LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン");
1390 let wo = LatticeMorpheme::new("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ");
1391 let levels = FeatureSet::default().levels(&schema);
1392 let strings = |morphemes: &[LatticeMorpheme]| {
1393 Strings::new(&schema, levels.clone(), morphemes, false, false)
1394 };
1395 let plain = strings(&[hon.clone(), wo.clone()]);
1396 for spaced in [
1399 vec![space.clone(), hon.clone(), wo.clone()],
1400 vec![hon.clone(), space.clone(), wo.clone()],
1401 vec![hon.clone(), wo.clone(), space.clone()],
1402 vec![
1403 space.clone(),
1404 hon.clone(),
1405 space.clone(),
1406 wo.clone(),
1407 space.clone(),
1408 ],
1409 ] {
1410 assert_eq!(strings(&spaced), plain);
1411 }
1412 assert!(plain.statics.contains(&"LS:本".to_string()));
1413 assert!(plain.statics.contains(&"RS:を".to_string()));
1414 assert_eq!(plain.after, ["NS:を", "NP0:助詞", "NP1:格助詞", "NP2:一般"]);
1415
1416 let spaces = strings(&[space.clone(), space]);
1418 assert!(spaces.statics.contains(&"HS:\u{3000}".to_string()));
1419 }
1420}