Skip to main content

lindera_core/
mode.rs

1use std::str::FromStr;
2
3use serde::{Deserialize, Serialize};
4
5use crate::dictionary::viterbi::Edge;
6use crate::error::{LinderaError, LinderaErrorKind};
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    pub fn penalty_cost(&self, edge: &Edge) -> i32 {
61        match self {
62            Mode::Normal => 0i32,
63            Mode::Decompose(penalty) => penalty.penalty(edge),
64        }
65    }
66}
67
68impl FromStr for Mode {
69    type Err = LinderaError;
70    fn from_str(mode: &str) -> Result<Mode, Self::Err> {
71        match mode {
72            "normal" => Ok(Mode::Normal),
73            "decompose" => Ok(Mode::Decompose(Penalty::default())),
74            _ => {
75                Err(LinderaErrorKind::ModeError
76                    .with_error(anyhow::anyhow!("Invalid mode: {}", mode)))
77            }
78        }
79    }
80}