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 Agree,
78}
79
80impl Group {
81 const ALL: [(Group, &'static str); 9] = [
84 (Group::Distance, "distance"),
85 (Group::Source, "source"),
86 (Group::Target, "target"),
87 (Group::Left, "left"),
88 (Group::Right, "right"),
89 (Group::Children, "children"),
90 (Group::Gap, "gap"),
91 (Group::AfterHead, "after"),
92 (Group::Agree, "agree"),
93 ];
94
95 pub fn name(self) -> &'static str {
102 Self::ALL
103 .iter()
104 .find(|(group, _)| *group == self)
105 .map_or("", |(_, name)| name)
106 }
107
108 pub fn from_name(name: &str) -> Option<Self> {
118 Self::ALL
119 .iter()
120 .find(|(_, other)| *other == name)
121 .map(|(group, _)| *group)
122 }
123}
124
125#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct FeatureSet {
138 groups: Vec<Group>,
140 part_of_speech_levels: Option<usize>,
143}
144
145const LEVELS_KEY: &str = "pos-levels=";
148
149impl FeatureSet {
150 pub fn new(groups: &[Group]) -> Result<Self> {
160 if groups.is_empty() {
161 return Err(Error::Parser("a feature set needs a group".to_string()));
162 }
163 for (index, group) in groups.iter().enumerate() {
164 if groups[..index].contains(group) {
165 return Err(Error::Parser(format!(
166 "the group {} is given twice",
167 group.name()
168 )));
169 }
170 }
171 Ok(Self {
172 groups: Group::ALL
173 .iter()
174 .map(|(group, _)| *group)
175 .filter(|group| groups.contains(group))
176 .collect(),
177 part_of_speech_levels: None,
178 })
179 }
180
181 pub fn with_part_of_speech_levels(mut self, levels: usize) -> Result<Self> {
214 if levels == 0 {
215 return Err(Error::Parser(
216 "the features need a level of the part of speech: pos-levels is 1 or more"
217 .to_string(),
218 ));
219 }
220 self.part_of_speech_levels = Some(levels);
221 Ok(self)
222 }
223
224 pub fn part_of_speech_levels(&self) -> Option<usize> {
231 self.part_of_speech_levels
232 }
233
234 fn levels(&self, schema: &Schema) -> Range<usize> {
244 let all = schema.part_of_speech.clone();
245 match self.part_of_speech_levels {
246 Some(levels) => all.start..all.end.min(all.start.saturating_add(levels)),
247 None => all,
248 }
249 }
250
251 pub fn cabocha() -> Self {
258 Self {
259 groups: Group::ALL
260 .iter()
261 .map(|(group, _)| *group)
262 .filter(|group| !matches!(group, Group::AfterHead | Group::Agree))
263 .collect(),
264 part_of_speech_levels: None,
265 }
266 }
267
268 pub fn parse(text: &str) -> Result<Self> {
282 let mut groups = Vec::new();
283 let mut levels = None;
284 for name in text.split(',') {
285 let name = name.trim();
286 if let Some(value) = name.strip_prefix(LEVELS_KEY) {
287 if levels.is_some() {
288 return Err(Error::Parser(format!("{LEVELS_KEY} is given twice")));
289 }
290 levels = Some(value.parse::<usize>().map_err(|_| {
291 Error::Parser(format!(
292 "{name:?} is not a number of levels of the part of speech"
293 ))
294 })?);
295 continue;
296 }
297 groups
298 .push(Group::from_name(name).ok_or_else(|| {
299 Error::Parser(format!("{name:?} is not a group of features"))
300 })?);
301 }
302 let set = Self::new(&groups)?;
303 match levels {
304 Some(levels) => set.with_part_of_speech_levels(levels),
305 None => Ok(set),
306 }
307 }
308
309 pub fn groups(&self) -> &[Group] {
316 &self.groups
317 }
318
319 pub fn has(&self, group: Group) -> bool {
329 self.groups.contains(&group)
330 }
331}
332
333impl Default for FeatureSet {
334 fn default() -> Self {
338 Self {
339 groups: Group::ALL
340 .iter()
341 .map(|(group, _)| *group)
342 .filter(|group| *group != Group::Agree)
343 .collect(),
344 part_of_speech_levels: None,
345 }
346 }
347}
348
349impl fmt::Display for FeatureSet {
350 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
354 for (index, group) in self.groups.iter().enumerate() {
355 if index > 0 {
356 write!(f, ",")?;
357 }
358 write!(f, "{}", group.name())?;
359 }
360 if let Some(levels) = self.part_of_speech_levels {
361 write!(f, ",{LEVELS_KEY}{levels}")?;
362 }
363 Ok(())
364 }
365}
366
367#[derive(Debug, Clone, PartialEq)]
373struct Roles<T> {
374 source: Vec<T>,
376 target: Vec<T>,
378 left: Vec<T>,
380 right: Vec<T>,
382 gap: Vec<T>,
385 after_source: Vec<T>,
387 after_target: Vec<T>,
389 child_of_source: Option<T>,
391 child_of_target: Option<T>,
393 opens: bool,
395 closes: bool,
397 head: Vec<String>,
401}
402
403#[derive(Debug, Clone, PartialEq)]
406pub(crate) struct Prepared<T> {
407 bunsetsu: Vec<Roles<T>>,
409 distance: [Option<T>; 3],
411 brackets: [Option<T>; 4],
414 agree_surface: Option<T>,
416 agree_levels: Vec<Option<T>>,
419}
420
421impl<T: Clone + Ord> Prepared<T> {
422 pub(crate) fn new<M: Morpheme>(
438 schema: &Schema,
439 set: &FeatureSet,
440 morphemes: &[M],
441 bunsetsu: &[Range<usize>],
442 mut intern: impl FnMut(&str) -> Option<T>,
443 ) -> Self {
444 let last = bunsetsu.len().saturating_sub(1);
445 let roles = bunsetsu
446 .iter()
447 .enumerate()
448 .map(|(index, range)| {
449 let strings = Strings::new(
450 schema,
451 set.levels(schema),
452 &morphemes[range.clone()],
453 index == 0,
454 index == last,
455 );
456 let mut role = |group: Group, prefix: &str, names: &[String]| -> Vec<T> {
457 if !set.has(group) {
458 return Vec::new();
459 }
460 names
461 .iter()
462 .filter_map(|name| intern(&format!("{prefix}{name}")))
463 .collect()
464 };
465 let source = role(Group::Source, "S", &strings.statics);
466 let target = role(Group::Target, "D", &strings.statics);
467 let left = role(Group::Left, "", &strings.left);
468 let right = role(Group::Right, "", &strings.right);
469 let gap = role(Group::Gap, "", &strings.gap);
470 let after_source = role(Group::AfterHead, "S", &strings.after);
471 let after_target = role(Group::AfterHead, "D", &strings.after);
472 let child = std::slice::from_ref(&strings.child);
473 let child_of_source = role(Group::Children, "a:", child).pop();
474 let child_of_target = role(Group::Children, "A:", child).pop();
475 Roles {
476 source,
477 target,
478 left,
479 right,
480 gap,
481 after_source,
482 after_target,
483 child_of_source,
484 child_of_target,
485 opens: strings.opens,
486 closes: strings.closes,
487 head: if set.has(Group::Agree) {
488 strings.head
489 } else {
490 Vec::new()
491 },
492 }
493 })
494 .collect();
495 let mut named = |group: Group, name: &str| {
496 if set.has(group) { intern(name) } else { None }
497 };
498 Self {
499 bunsetsu: roles,
500 distance: [
501 named(Group::Distance, "DIST:1"),
502 named(Group::Distance, "DIST:2-5"),
503 named(Group::Distance, "DIST:6-"),
504 ],
505 brackets: [
506 named(Group::Gap, "GNB:1"),
507 named(Group::Gap, "GOB:1"),
508 named(Group::Gap, "GCB:1"),
509 named(Group::Gap, "GBB:1"),
510 ],
511 agree_surface: named(Group::Agree, "AGS:1"),
512 agree_levels: (0..set.levels(schema).len())
513 .map(|level| named(Group::Agree, &format!("AGP{level}:1")))
514 .collect(),
515 }
516 }
517
518 pub(crate) fn decision(
528 &self,
529 source: usize,
530 target: usize,
531 children: &[Vec<usize>],
532 features: &mut Vec<T>,
533 ) {
534 features.clear();
535 let class = match target - source {
536 1 => 0,
537 2..=5 => 1,
538 _ => 2,
539 };
540 features.extend(self.distance[class].clone());
541 features.extend_from_slice(&self.bunsetsu[source].source);
542 features.extend_from_slice(&self.bunsetsu[target].target);
543 features.extend_from_slice(&self.bunsetsu[source].after_source);
544 features.extend_from_slice(&self.bunsetsu[target].after_target);
545 if source > 0 {
546 features.extend_from_slice(&self.bunsetsu[source - 1].left);
547 }
548 if let Some(after) = self.bunsetsu.get(target + 1) {
549 features.extend_from_slice(&after.right);
550 }
551 for &child in &children[source] {
554 features.extend(self.bunsetsu[child].child_of_source.clone());
555 }
556 for &child in &children[target] {
557 features.extend(self.bunsetsu[child].child_of_target.clone());
558 }
559 let mut opens = false;
560 let mut closes = false;
561 for between in &self.bunsetsu[source + 1..target] {
562 features.extend_from_slice(&between.gap);
563 opens |= between.opens;
564 closes |= between.closes;
565 }
566 let state = usize::from(opens) + 2 * usize::from(closes);
567 features.extend(self.brackets[state].clone());
568 let (first, second) = (&self.bunsetsu[source].head, &self.bunsetsu[target].head);
570 if let (Some(one), Some(other)) = (first.first(), second.first())
571 && one == other
572 {
573 features.extend(self.agree_surface.clone());
574 }
575 let levels = first.iter().skip(1).zip(second.iter().skip(1));
576 for (feature, (one, other)) in self.agree_levels.iter().zip(levels) {
577 if one != other {
578 break;
579 }
580 features.extend(feature.clone());
581 }
582 features.sort_unstable();
583 features.dedup();
584 }
585}
586
587#[derive(Debug, Clone, PartialEq, Eq)]
589struct Strings {
590 statics: Vec<String>,
593 left: Vec<String>,
595 right: Vec<String>,
597 gap: Vec<String>,
599 after: Vec<String>,
602 child: String,
604 opens: bool,
606 closes: bool,
608 head: Vec<String>,
611}
612
613impl Strings {
614 fn new<M: Morpheme>(
627 schema: &Schema,
628 levels: Range<usize>,
629 morphemes: &[M],
630 first: bool,
631 last: bool,
632 ) -> Self {
633 let words: Vec<&M> = morphemes
638 .iter()
639 .filter(|morpheme| !is_space(*morpheme))
640 .collect();
641 if words.is_empty() || words.len() == morphemes.len() {
642 Self::of_words(schema, levels, morphemes, first, last)
643 } else {
644 Self::of_words(schema, levels, &words, first, last)
645 }
646 }
647
648 fn of_words<M: Morpheme>(
663 schema: &Schema,
664 levels: Range<usize>,
665 morphemes: &[M],
666 first: bool,
667 last: bool,
668 ) -> Self {
669 let mut statics = Vec::new();
670 let mut gap = Vec::new();
671 let mut opens = false;
672 let mut closes = false;
673 for (index, morpheme) in morphemes.iter().enumerate() {
674 let surface = schema.surface_of(morpheme);
675 if schema.is_comma(morpheme) || schema.is_period(morpheme) {
676 gap.push(format!("GPUNC:{surface}"));
677 statics.push(format!("PUNC:{surface}"));
678 }
679 if schema.is_open_bracket(morpheme) {
680 gap.push(format!("GOB:{surface}"));
681 statics.push(format!("OB:{surface}"));
682 statics.push("OB:1".to_string());
683 opens = true;
684 }
685 if schema.is_close_bracket(morpheme) {
686 gap.push(format!("GCB:{surface}"));
687 statics.push(format!("CB:{surface}"));
688 statics.push("CB:1".to_string());
689 closes = true;
690 }
691 if schema.is_particle(morphemes, index) {
692 statics.push(format!("CASE:{surface}"));
693 }
694 }
695
696 let (head, function) = schema.positions(morphemes).unwrap_or((0, 0));
697 let end = morphemes.len().saturating_sub(1);
698 for (role, index) in [('H', head), ('F', function), ('L', 0), ('R', end)] {
699 if let Some(morpheme) = morphemes.get(index) {
700 push_morpheme(schema, levels.clone(), role, morpheme, &mut statics);
701 }
702 }
703 let mut after = Vec::new();
704 if let Some(morpheme) = morphemes.get(head + 1) {
705 push_morpheme(schema, levels.clone(), 'N', morpheme, &mut after);
706 }
707 let head_values = morphemes.get(head).map_or_else(Vec::new, |morpheme| {
708 std::iter::once(schema.surface_of(morpheme).into_owned())
709 .chain(
710 levels
711 .clone()
712 .map_while(|index| morpheme.feature(index).filter(|value| *value != EMPTY))
713 .map(str::to_string),
714 )
715 .collect()
716 });
717 if first {
718 statics.push("BOS:1".to_string());
719 }
720 if last {
721 statics.push("EOS:1".to_string());
722 }
723
724 let surface = |index: usize| {
725 morphemes
726 .get(index)
727 .map_or(Cow::Borrowed(""), |morpheme| schema.surface_of(morpheme))
728 };
729 let left = vec![format!("LF:{}", surface(function))];
730 let right = vec![
731 format!("RL:{}", surface(0)),
732 format!("RH:{}", surface(head)),
733 format!("RF:{}", surface(function)),
734 ];
735 if schema.is_particle(morphemes, function) {
736 gap.push(format!("GCASE:{}", surface(function)));
737 }
738
739 let child = if schema.is_lexicalized(morphemes, function) {
740 surface(function).to_string()
741 } else {
742 morphemes
743 .get(function)
744 .and_then(|morpheme| conjugation_form(schema, morpheme))
745 .map(str::to_string)
746 .or_else(|| {
747 morphemes
748 .get(function)
749 .map(|morpheme| schema.levels_of(morpheme, levels.clone()))
750 })
751 .unwrap_or_default()
752 };
753
754 Self {
755 statics,
756 left,
757 right,
758 gap,
759 after,
760 child,
761 opens,
762 closes,
763 head: head_values,
764 }
765 }
766}
767
768fn conjugation_form<'a, M: Morpheme>(schema: &Schema, morpheme: &'a M) -> Option<&'a str> {
780 schema
781 .conjugation_form
782 .and_then(|index| morpheme.feature(index))
783 .filter(|form| *form != EMPTY)
784}
785
786fn push_morpheme<M: Morpheme>(
800 schema: &Schema,
801 levels: Range<usize>,
802 role: char,
803 morpheme: &M,
804 features: &mut Vec<String>,
805) {
806 features.push(format!("{role}S:{}", schema.surface_of(morpheme)));
807 for (level, index) in levels.enumerate() {
808 match morpheme.feature(index) {
809 Some(value) if value != EMPTY => features.push(format!("{role}P{level}:{value}")),
810 _ => break,
811 }
812 }
813 if let Some(form) = conjugation_form(schema, morpheme) {
814 features.push(format!("{role}F:{form}"));
815 }
816}
817
818#[cfg(test)]
819#[allow(clippy::single_range_in_vec_init)]
822mod tests {
823 use super::*;
824 use crate::lattice::LatticeMorpheme;
825 use crate::parser::fixtures;
826
827 fn prepared(
829 set: &FeatureSet,
830 sentence: &(Vec<LatticeMorpheme>, Vec<Range<usize>>),
831 ) -> Prepared<String> {
832 Prepared::new(
833 &Schema::ipadic(),
834 set,
835 &sentence.0,
836 &sentence.1,
837 |feature| Some(feature.to_string()),
838 )
839 }
840
841 fn decision(
843 prepared: &Prepared<String>,
844 source: usize,
845 target: usize,
846 children: &[Vec<usize>],
847 ) -> Vec<String> {
848 let mut features = Vec::new();
849 prepared.decision(source, target, children, &mut features);
850 features
851 }
852
853 fn no_children(count: usize) -> Vec<Vec<usize>> {
855 vec![Vec::new(); count]
856 }
857
858 fn is_of(group: Group, feature: &str) -> bool {
860 match group {
861 Group::Distance => feature.starts_with("DIST:"),
862 Group::Source => feature.starts_with('S') && !feature.starts_with("SN"),
863 Group::Target => {
864 feature.starts_with('D')
865 && !feature.starts_with("DIST:")
866 && !feature.starts_with("DN")
867 }
868 Group::Left => feature.starts_with("LF:"),
869 Group::Right => feature.starts_with('R'),
870 Group::Children => feature.starts_with("a:") || feature.starts_with("A:"),
871 Group::Gap => feature.starts_with('G'),
872 Group::AfterHead => feature.starts_with("SN") || feature.starts_with("DN"),
873 Group::Agree => feature.starts_with("AG"),
874 }
875 }
876
877 fn every() -> FeatureSet {
879 let all: Vec<Group> = Group::ALL.iter().map(|(group, _)| *group).collect();
880 FeatureSet::new(&all).unwrap()
881 }
882
883 #[test]
884 fn the_surfaces_of_the_features_are_the_normalized_ones_of_the_schema() {
885 let noun = "名詞,一般,*,*,*,*,*";
888 let particle = "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ";
889 let morphemes = vec![
890 LatticeMorpheme::new("A", noun),
891 LatticeMorpheme::new("ヲ", particle),
892 LatticeMorpheme::new("B", noun),
893 LatticeMorpheme::new("(", "名詞,サ変接続,*,*,*,*,*"),
894 LatticeMorpheme::new("ヲ", particle),
895 LatticeMorpheme::new("C", noun),
896 LatticeMorpheme::new("ヲ", particle),
897 LatticeMorpheme::new("D", noun),
898 LatticeMorpheme::new("ヲ", particle),
899 LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
900 ];
901 let ranges = vec![0..2, 2..5, 5..7, 7..9, 9..10];
902 let mut children = no_children(5);
904 children[1].push(0);
905 let features = |schema: &Schema, source: usize, target: usize| -> Vec<String> {
906 let prepared = Prepared::new(
907 schema,
908 &FeatureSet::cabocha(),
909 &morphemes,
910 &ranges,
911 |feature| Some(feature.to_string()),
912 );
913 decision(&prepared, source, target, &children)
914 };
915 let schema = Schema {
916 normalization: crate::schema::Normalization::new(&[
917 ("A", "A"),
918 ("B", "B"),
919 ("C", "C"),
920 ("D", "D"),
921 ("(", "("),
922 ("ヲ", "ヲ"),
923 ])
924 .unwrap(),
925 ..Schema::ipadic()
926 };
927 let normalized = features(&schema, 1, 3);
929 for feature in [
930 "SHS:B",
932 "SLS:B",
933 "SFS:ヲ",
934 "SRS:ヲ",
935 "SOB:(",
936 "SOB:1",
937 "SCASE:ヲ",
938 "DHS:D",
939 "DCASE:ヲ",
940 "LF:ヲ",
942 "a:ヲ",
943 "GCASE:ヲ",
945 ] {
946 assert!(
947 normalized.iter().any(|one| one == feature),
948 "{feature}: {normalized:?}"
949 );
950 }
951 let first = features(&schema, 0, 1);
954 for feature in ["RL:C", "RH:C", "RF:ヲ", "DOB:("] {
955 assert!(
956 first.iter().any(|one| one == feature),
957 "{feature}: {first:?}"
958 );
959 }
960 let over = features(&schema, 0, 2);
961 assert!(over.iter().any(|one| one == "GOB:("), "{over:?}");
962 for all in [&normalized, &first, &over] {
963 assert!(
964 !all.iter()
965 .any(|one| "ABCD(ヲ".chars().any(|wide| one.contains(wide))),
966 "{all:?}"
967 );
968 }
969 let plain = features(&Schema::ipadic(), 1, 3);
971 for feature in [
972 "SHS:B",
973 "SFS:ヲ",
974 "SOB:(",
975 "SCASE:ヲ",
976 "DHS:D",
977 "LF:ヲ",
978 "a:ヲ",
979 "GCASE:ヲ",
980 ] {
981 assert!(
982 plain.iter().any(|one| one == feature),
983 "{feature}: {plain:?}"
984 );
985 }
986 }
987
988 #[test]
989 fn a_decision_has_the_features_of_cabocha() {
990 let prepared = prepared(&FeatureSet::cabocha(), &fixtures::sentence());
991 let mut expected = vec![
993 "DIST:1",
994 "SHS:彼",
997 "SHP0:名詞",
998 "SHP1:代名詞",
999 "SHP2:一般",
1000 "SFS:は",
1001 "SFP0:助詞",
1002 "SFP1:係助詞",
1003 "SLS:彼",
1004 "SLP0:名詞",
1005 "SLP1:代名詞",
1006 "SLP2:一般",
1007 "SRS:は",
1008 "SRP0:助詞",
1009 "SRP1:係助詞",
1010 "SCASE:は",
1011 "SBOS:1",
1012 "DHS:本",
1015 "DHP0:名詞",
1016 "DHP1:一般",
1017 "DFS:本",
1018 "DFP0:名詞",
1019 "DFP1:一般",
1020 "DLS:「",
1021 "DLP0:記号",
1022 "DLP1:括弧開",
1023 "DRS:本",
1024 "DRP0:名詞",
1025 "DRP1:一般",
1026 "DOB:「",
1027 "DOB:1",
1028 "RL:」",
1031 "RH:」",
1032 "RF:を",
1033 "GNB:1",
1035 ];
1036 expected.sort_unstable();
1037 assert_eq!(decision(&prepared, 0, 1, &no_children(5)), expected);
1038 }
1039
1040 #[test]
1041 fn the_conjugation_form_and_the_marks_of_a_bunsetsu_are_features() {
1042 let prepared = prepared(&FeatureSet::cabocha(), &fixtures::sentence());
1043 let features = decision(&prepared, 3, 4, &no_children(5));
1045 let missing: Vec<&str> = [
1046 "SPUNC:、",
1047 "SCASE:に",
1048 "LF:を",
1049 "DHF:連用タ接続",
1050 "DFF:基本形",
1051 "DPUNC:。",
1052 "DEOS:1",
1053 ]
1054 .into_iter()
1055 .filter(|expected| !features.iter().any(|feature| feature == expected))
1056 .collect();
1057 assert!(missing.is_empty(), "{missing:?} not in {features:?}");
1058 let present: Vec<&str> = ["RL:", "RH:", "RF:", "SBOS:", "SEOS:", "DBOS:"]
1061 .into_iter()
1062 .filter(|absent| features.iter().any(|feature| feature.starts_with(absent)))
1063 .collect();
1064 assert!(present.is_empty(), "{present:?} in {features:?}");
1065 let features = decision(&prepared, 2, 3, &no_children(5));
1067 let missing: Vec<&str> = ["SCB:」", "SCB:1"]
1068 .into_iter()
1069 .filter(|expected| !features.iter().any(|feature| feature == expected))
1070 .collect();
1071 assert!(missing.is_empty(), "{missing:?} not in {features:?}");
1072 }
1073
1074 #[test]
1075 fn the_levels_of_the_part_of_speech_stop_at_the_first_empty_one() {
1076 let morphemes = [LatticeMorpheme::new("語", "名詞,*,一般,*,*,*,語,ゴ,ゴ")];
1078 let strings = Strings::new(&Schema::ipadic(), 0..4, &morphemes, false, false);
1079 let levels: Vec<&str> = strings
1080 .statics
1081 .iter()
1082 .map(String::as_str)
1083 .filter(|feature| feature.starts_with("HP"))
1084 .collect();
1085 assert_eq!(levels, ["HP0:名詞"]);
1086 }
1087
1088 #[test]
1089 fn a_limit_holds_the_features_to_that_many_levels_of_the_part_of_speech() {
1090 let schema = Schema {
1092 part_of_speech: 0..4,
1093 conjugation_form: Some(5),
1094 ..Schema::default()
1095 };
1096 let all = FeatureSet::cabocha();
1097 let two = FeatureSet::cabocha().with_part_of_speech_levels(2).unwrap();
1098 assert_eq!(all.levels(&schema), 0..4);
1099 assert_eq!(two.levels(&schema), 0..2);
1100 let nine = FeatureSet::cabocha().with_part_of_speech_levels(9).unwrap();
1102 assert_eq!(nine.levels(&schema), 0..4);
1103 let later = Schema {
1105 part_of_speech: 3..7,
1106 ..Schema::default()
1107 };
1108 assert_eq!(two.levels(&later), 3..5);
1109
1110 let morphemes = [LatticeMorpheme::new(
1112 "太郎",
1113 "名詞,固有名詞,人名,名,*,*,タロウ,タロウ",
1114 )];
1115 let levels = |set: &FeatureSet| -> (Vec<String>, String) {
1116 let strings = Strings::new(&schema, set.levels(&schema), &morphemes, false, false);
1117 let names = strings
1118 .statics
1119 .iter()
1120 .filter(|feature| feature.starts_with("HP"))
1121 .cloned()
1122 .collect();
1123 (names, strings.child)
1124 };
1125 assert_eq!(
1128 levels(&all),
1129 (
1130 vec![
1131 "HP0:名詞".to_string(),
1132 "HP1:固有名詞".to_string(),
1133 "HP2:人名".to_string(),
1134 "HP3:名".to_string()
1135 ],
1136 "名詞-固有名詞-人名-名".to_string()
1137 )
1138 );
1139 assert_eq!(
1140 levels(&two),
1141 (
1142 vec!["HP0:名詞".to_string(), "HP1:固有名詞".to_string()],
1143 "名詞-固有名詞".to_string()
1144 )
1145 );
1146 let pair = [morphemes[0].clone(), morphemes[0].clone()];
1148 let decisions = |set: &FeatureSet| -> Vec<String> {
1149 let prepared = Prepared::new(&schema, set, &pair, &[0..1, 1..2], |feature| {
1150 Some(feature.to_string())
1151 });
1152 decision(&prepared, 0, 1, &no_children(2))
1153 };
1154 assert!(decisions(&all).iter().any(|one| one == "SHP3:名"));
1155 assert!(!decisions(&two).iter().any(|one| one == "SHP2:人名"));
1156 assert!(decisions(&two).iter().any(|one| one == "SHP1:固有名詞"));
1157 }
1158
1159 #[test]
1160 fn the_limit_of_the_levels_is_part_of_the_text_of_a_set() {
1161 let set = FeatureSet::parse("gap, pos-levels=2 ,source").unwrap();
1162 assert_eq!(set.groups(), [Group::Source, Group::Gap]);
1163 assert_eq!(set.part_of_speech_levels(), Some(2));
1164 assert_eq!(set.to_string(), "source,gap,pos-levels=2");
1166 assert_eq!(FeatureSet::parse(&set.to_string()).unwrap(), set);
1167 let plain = FeatureSet::parse("source,gap").unwrap();
1169 assert_eq!(plain.part_of_speech_levels(), None);
1170 assert_eq!(plain.to_string(), "source,gap");
1171 assert_ne!(plain, set);
1172 assert_eq!(FeatureSet::cabocha().part_of_speech_levels(), None);
1173 assert_eq!(FeatureSet::default().part_of_speech_levels(), None);
1174
1175 let message = |text: &str| FeatureSet::parse(text).unwrap_err().to_string();
1176 assert_eq!(
1177 message("source,pos-levels=0"),
1178 "the features need a level of the part of speech: pos-levels is 1 or more"
1179 );
1180 assert_eq!(
1181 message("source,pos-levels=two"),
1182 "\"pos-levels=two\" is not a number of levels of the part of speech"
1183 );
1184 assert_eq!(
1185 message("source,pos-levels="),
1186 "\"pos-levels=\" is not a number of levels of the part of speech"
1187 );
1188 assert_eq!(
1189 message("pos-levels=2,source,pos-levels=3"),
1190 "pos-levels= is given twice"
1191 );
1192 assert_eq!(message("pos-levels=2"), "a feature set needs a group");
1194 assert!(matches!(
1195 FeatureSet::cabocha().with_part_of_speech_levels(0),
1196 Err(Error::Parser(_))
1197 ));
1198 }
1199
1200 #[test]
1201 fn the_distance_has_three_classes() {
1202 let prepared = prepared(&FeatureSet::cabocha(), &fixtures::repeated(8));
1203 let classes: Vec<String> = [1, 2, 5, 6, 7]
1204 .iter()
1205 .map(|&target| {
1206 decision(&prepared, 0, target, &no_children(8))
1207 .into_iter()
1208 .find(|feature| feature.starts_with("DIST:"))
1209 .unwrap_or_default()
1210 })
1211 .collect();
1212 assert_eq!(
1213 classes,
1214 ["DIST:1", "DIST:2-5", "DIST:2-5", "DIST:6-", "DIST:6-"]
1215 );
1216 }
1217
1218 #[test]
1219 fn the_gap_has_the_marks_in_between_and_the_state_of_the_brackets() {
1220 let prepared = prepared(&FeatureSet::cabocha(), &fixtures::sentence());
1221 let gap = |source: usize, target: usize| -> Vec<String> {
1222 decision(&prepared, source, target, &no_children(5))
1223 .into_iter()
1224 .filter(|feature| feature.starts_with('G'))
1225 .collect()
1226 };
1227 assert_eq!(gap(1, 2), ["GNB:1"]);
1230 assert_eq!(gap(0, 2), ["GOB:1", "GOB:「"]);
1232 assert_eq!(gap(1, 3), ["GCASE:を", "GCB:1", "GCB:」"]);
1234 assert_eq!(
1236 gap(0, 4),
1237 [
1238 "GBB:1",
1239 "GCASE:に",
1240 "GCASE:を",
1241 "GCB:」",
1242 "GOB:「",
1243 "GPUNC:、"
1244 ]
1245 );
1246 }
1247
1248 #[test]
1249 fn the_children_are_named_by_their_function_word() {
1250 let prepared = prepared(&FeatureSet::cabocha(), &fixtures::sentence());
1251 let children = |features: Vec<String>| -> Vec<String> {
1252 features
1253 .into_iter()
1254 .filter(|feature| is_of(Group::Children, feature))
1255 .collect()
1256 };
1257 assert_eq!(
1259 children(decision(&prepared, 1, 3, &no_children(5))),
1260 [""; 0]
1261 );
1262 let attached = vec![vec![], vec![0], vec![], vec![2], vec![]];
1265 assert_eq!(
1266 children(decision(&prepared, 1, 3, &attached)),
1267 ["A:を", "a:は"]
1268 );
1269 let attached = vec![vec![], vec![], vec![1], vec![4], vec![]];
1272 assert_eq!(
1273 children(decision(&prepared, 2, 3, &attached)),
1274 ["A:基本形", "a:名詞-一般"]
1275 );
1276 }
1277
1278 #[test]
1279 fn a_feature_is_in_a_decision_once() {
1280 let prepared = prepared(&FeatureSet::cabocha(), &fixtures::repeated(4));
1282 let features = decision(&prepared, 0, 3, &no_children(4));
1283 let particles = features
1284 .iter()
1285 .filter(|feature| *feature == "GCASE:を")
1286 .count();
1287 assert_eq!(particles, 1);
1288 let mut sorted = features.clone();
1289 sorted.sort_unstable();
1290 sorted.dedup();
1291 assert_eq!(features, sorted);
1292 }
1293
1294 #[test]
1295 fn a_feature_that_is_not_interned_is_left_out() {
1296 let (morphemes, ranges) = fixtures::sentence();
1297 let known = ["GNB:1", "RF:を", "SFS:は", "DIST:1"];
1298 let prepared: Prepared<u32> = Prepared::new(
1299 &Schema::ipadic(),
1300 &FeatureSet::cabocha(),
1301 &morphemes,
1302 &ranges,
1303 |feature| {
1304 known
1305 .iter()
1306 .position(|one| *one == feature)
1307 .map(|index| index as u32)
1308 },
1309 );
1310 let mut features = Vec::new();
1311 prepared.decision(0, 1, &no_children(5), &mut features);
1312 assert_eq!(features, [0, 1, 2, 3]);
1314 }
1315
1316 #[test]
1317 fn a_group_left_out_gives_none_of_its_features() {
1318 let sentence = fixtures::sentence();
1319 let attached = vec![vec![], vec![0], vec![], vec![2], vec![]];
1320 let all = decision(&prepared(&every(), &sentence), 1, 3, &attached);
1321 let mut failures = Vec::new();
1322 for (group, name) in Group::ALL {
1323 if !all.iter().any(|feature| is_of(group, feature)) {
1325 failures.push(format!("the decision has no feature of {name}"));
1326 }
1327 let others: Vec<Group> = Group::ALL
1328 .iter()
1329 .map(|(other, _)| *other)
1330 .filter(|other| *other != group)
1331 .collect();
1332 let without = decision(
1333 &prepared(&FeatureSet::new(&others).unwrap(), &sentence),
1334 1,
1335 3,
1336 &attached,
1337 );
1338 let expected: Vec<String> = all
1339 .iter()
1340 .filter(|feature| !is_of(group, feature))
1341 .cloned()
1342 .collect();
1343 if without != expected {
1344 failures.push(format!("without {name}: {without:?}"));
1345 }
1346 }
1347 assert!(failures.is_empty(), "{failures:#?}");
1348 }
1349
1350 fn agreement(
1352 set: &FeatureSet,
1353 morphemes: &[(&str, &str)],
1354 bunsetsu: &[Range<usize>],
1355 source: usize,
1356 target: usize,
1357 ) -> Vec<String> {
1358 let sentence = (
1359 morphemes
1360 .iter()
1361 .map(|(surface, features)| LatticeMorpheme::new(*surface, *features))
1362 .collect(),
1363 bunsetsu.to_vec(),
1364 );
1365 let attached = vec![Vec::new(); bunsetsu.len()];
1366 decision(&prepared(set, &sentence), source, target, &attached)
1367 .into_iter()
1368 .filter(|feature| is_of(Group::Agree, feature))
1369 .collect()
1370 }
1371
1372 #[test]
1373 fn agree_compares_the_heads_of_the_source_and_of_the_target() {
1374 let places = [
1376 (
1377 "東京",
1378 "名詞,固有名詞,地域,一般,*,*,東京,トウキョウ,トーキョー",
1379 ),
1380 ("と", "助詞,並立助詞,*,*,*,*,と,ト,ト"),
1381 ("京都", "名詞,固有名詞,地域,一般,*,*,京都,キョウト,キョート"),
1382 ("の", "助詞,連体化,*,*,*,*,の,ノ,ノ"),
1383 ("寺", "名詞,一般,*,*,*,*,寺,テラ,テラ"),
1384 ("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ"),
1385 ("訪ね", "動詞,自立,*,*,一段,連用形,訪ねる,タズネ,タズネ"),
1386 ("た", "助動詞,*,*,*,特殊・タ,基本形,た,タ,タ"),
1387 ("。", "記号,句点,*,*,*,*,。,。,。"),
1388 ];
1389 let ranges = [0..2, 2..4, 4..6, 6..9];
1390 let set = every();
1391 assert_eq!(
1394 agreement(&set, &places, &ranges, 0, 1),
1395 ["AGP0:1", "AGP1:1", "AGP2:1", "AGP3:1"]
1396 );
1397 assert_eq!(agreement(&set, &places, &ranges, 0, 2), ["AGP0:1"]);
1399 assert!(agreement(&set, &places, &ranges, 0, 3).is_empty());
1401 let two = every().with_part_of_speech_levels(2).unwrap();
1403 assert_eq!(
1404 agreement(&two, &places, &ranges, 0, 1),
1405 ["AGP0:1", "AGP1:1"]
1406 );
1407 assert!(agreement(&FeatureSet::default(), &places, &ranges, 0, 1).is_empty());
1409
1410 let books = [
1413 ("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
1414 ("と", "助詞,並立助詞,*,*,*,*,と,ト,ト"),
1415 ("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
1416 ("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ"),
1417 ("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム"),
1418 ];
1419 assert_eq!(
1420 agreement(&set, &books, &[0..2, 2..4, 4..5], 0, 1),
1421 ["AGP0:1", "AGP1:1", "AGS:1"]
1422 );
1423 }
1424
1425 #[test]
1426 fn the_morpheme_after_the_head_is_a_feature_of_the_source_and_of_the_target() {
1427 let morphemes: Vec<LatticeMorpheme> = [
1430 ("利用", "名詞,サ変接続,*,*,*,*,利用,リヨウ,リヨー"),
1431 ("し", "動詞,自立,*,*,サ変・スル,連用形,する,シ,シ"),
1432 ("た", "助動詞,*,*,*,特殊・タ,基本形,た,タ,タ"),
1433 ("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム"),
1434 ("こと", "名詞,非自立,一般,*,*,*,こと,コト,コト"),
1435 ("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ"),
1436 ("知っ", "動詞,自立,*,*,五段・ラ行,連用タ接続,知る,シッ,シッ"),
1437 ("た", "助動詞,*,*,*,特殊・タ,基本形,た,タ,タ"),
1438 ]
1439 .iter()
1440 .map(|(surface, features)| LatticeMorpheme::new(*surface, *features))
1441 .collect();
1442 let sentence = (morphemes, vec![0..3, 3..6, 6..8]);
1443 let after = |set: &FeatureSet, source: usize, target: usize| -> Vec<String> {
1444 decision(&prepared(set, &sentence), source, target, &no_children(3))
1445 .into_iter()
1446 .filter(|feature| is_of(Group::AfterHead, feature))
1447 .collect()
1448 };
1449 assert_eq!(
1450 after(&FeatureSet::default(), 0, 1),
1451 [
1452 "DNP0:名詞",
1453 "DNP1:非自立",
1454 "DNP2:一般",
1455 "DNS:こと",
1456 "SNF:連用形",
1457 "SNP0:動詞",
1458 "SNP1:自立",
1459 "SNS:し"
1460 ]
1461 );
1462 assert_eq!(
1464 after(&FeatureSet::default(), 1, 2),
1465 [
1466 "DNF:基本形",
1467 "DNP0:助動詞",
1468 "DNS:た",
1469 "SNP0:名詞",
1470 "SNP1:非自立",
1471 "SNP2:一般",
1472 "SNS:こと"
1473 ]
1474 );
1475 assert!(after(&FeatureSet::cabocha(), 0, 1).is_empty());
1478 let (morphemes, _) = &sentence;
1479 let alone = (morphemes[3..4].to_vec(), vec![0..1]);
1480 let prepared = prepared(&FeatureSet::default(), &alone);
1481 assert!(prepared.bunsetsu[0].after_source.is_empty());
1482 assert!(prepared.bunsetsu[0].after_target.is_empty());
1483 }
1484
1485 #[test]
1486 fn a_feature_set_is_read_from_its_text_and_written_back() {
1487 assert_eq!(
1488 FeatureSet::cabocha().to_string(),
1489 "distance,source,target,left,right,children,gap"
1490 );
1491 assert_eq!(
1493 FeatureSet::default().to_string(),
1494 "distance,source,target,left,right,children,gap,after"
1495 );
1496 assert!(!FeatureSet::cabocha().has(Group::AfterHead));
1497 assert!(!FeatureSet::default().has(Group::Agree));
1499 assert!(!FeatureSet::cabocha().has(Group::Agree));
1500 assert_eq!(Group::ALL.len(), 9);
1501 let set = FeatureSet::parse("gap, source ,distance").unwrap();
1503 assert_eq!(set.groups(), [Group::Distance, Group::Source, Group::Gap]);
1504 assert_eq!(set.to_string(), "distance,source,gap");
1505 assert_eq!(FeatureSet::parse(&set.to_string()).unwrap(), set);
1506 assert!(set.has(Group::Gap));
1507 assert!(!set.has(Group::Children));
1508 for (group, name) in Group::ALL {
1509 assert_eq!(group.name(), name);
1510 assert_eq!(Group::from_name(name), Some(group));
1511 }
1512 }
1513
1514 #[test]
1515 fn a_feature_set_that_cannot_be_read_is_refused() {
1516 let accepted: Vec<&str> = ["", "distance,", "distance,head", "gap,distance,gap"]
1517 .into_iter()
1518 .filter(|text| !matches!(FeatureSet::parse(text), Err(Error::Parser(_))))
1519 .collect();
1520 assert!(accepted.is_empty(), "not refused: {accepted:?}");
1521 assert!(matches!(FeatureSet::new(&[]), Err(Error::Parser(_))));
1522 }
1523
1524 #[test]
1525 fn the_features_of_a_bunsetsu_are_those_of_its_words() {
1526 let schema = Schema::ipadic();
1527 let space =
1528 LatticeMorpheme::new("\u{3000}", "記号,空白,*,*,*,*,\u{3000},\u{3000},\u{3000}");
1529 let hon = LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン");
1530 let wo = LatticeMorpheme::new("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ");
1531 let levels = FeatureSet::default().levels(&schema);
1532 let strings = |morphemes: &[LatticeMorpheme]| {
1533 Strings::new(&schema, levels.clone(), morphemes, false, false)
1534 };
1535 let plain = strings(&[hon.clone(), wo.clone()]);
1536 for spaced in [
1539 vec![space.clone(), hon.clone(), wo.clone()],
1540 vec![hon.clone(), space.clone(), wo.clone()],
1541 vec![hon.clone(), wo.clone(), space.clone()],
1542 vec![
1543 space.clone(),
1544 hon.clone(),
1545 space.clone(),
1546 wo.clone(),
1547 space.clone(),
1548 ],
1549 ] {
1550 assert_eq!(strings(&spaced), plain);
1551 }
1552 assert!(plain.statics.contains(&"LS:本".to_string()));
1553 assert!(plain.statics.contains(&"RS:を".to_string()));
1554 assert_eq!(plain.after, ["NS:を", "NP0:助詞", "NP1:格助詞", "NP2:一般"]);
1555
1556 let spaces = strings(&[space.clone(), space]);
1558 assert!(spaces.statics.contains(&"HS:\u{3000}".to_string()));
1559 }
1560}