lindera_dictionary/
mode.rs1use std::str::FromStr;
2
3use serde::{Deserialize, Serialize};
4
5use crate::error::{LinderaError, LinderaErrorKind};
6use crate::viterbi::Edge;
7
8#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
9pub struct Penalty {
10 pub kanji_penalty_length_threshold: usize,
11 pub kanji_penalty_length_penalty: i32,
12 pub other_penalty_length_threshold: usize,
13 pub other_penalty_length_penalty: i32,
14}
15
16impl Default for Penalty {
17 fn default() -> Self {
18 Penalty {
19 kanji_penalty_length_threshold: 2,
20 kanji_penalty_length_penalty: 3000,
21 other_penalty_length_threshold: 7,
22 other_penalty_length_penalty: 1700,
23 }
24 }
25}
26
27impl Penalty {
28 pub fn penalty(&self, edge: &Edge) -> i32 {
29 let num_chars = edge.num_chars();
30 if num_chars <= self.kanji_penalty_length_threshold {
31 return 0;
32 }
33 if edge.kanji_only {
34 ((num_chars - self.kanji_penalty_length_threshold) as i32)
35 * self.kanji_penalty_length_penalty
36 } else if num_chars > self.other_penalty_length_threshold {
37 ((num_chars - self.other_penalty_length_threshold) as i32)
38 * self.other_penalty_length_penalty
39 } else {
40 0
41 }
42 }
43}
44
45#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
46pub enum Mode {
47 #[serde(rename = "normal")]
48 Normal,
49 #[serde(rename = "decompose")]
50 Decompose(Penalty),
51}
52
53impl Mode {
54 pub fn is_search(&self) -> bool {
55 match self {
56 Mode::Normal => false,
57 Mode::Decompose(_penalty) => true,
58 }
59 }
60
61 pub fn penalty_cost(&self, edge: &Edge) -> i32 {
62 match self {
63 Mode::Normal => 0i32,
64 Mode::Decompose(penalty) => penalty.penalty(edge),
65 }
66 }
67
68 pub fn as_str(&self) -> &str {
69 match self {
70 Mode::Normal => "normal",
71 Mode::Decompose(_penalty) => "decompose",
72 }
73 }
74}
75
76impl FromStr for Mode {
77 type Err = LinderaError;
78 fn from_str(mode: &str) -> Result<Mode, Self::Err> {
79 match mode {
80 "normal" => Ok(Mode::Normal),
81 "decompose" => Ok(Mode::Decompose(Penalty::default())),
82 _ => Err(LinderaErrorKind::Mode.with_error(anyhow::anyhow!("Invalid mode: {}", mode))),
83 }
84 }
85}