1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
use crate::{file_model::FileModel, fraction::Fraction};
use ahash::AHashMap;
use fraction::GenericFraction;
#[derive(Debug)]
pub(crate) struct TrainingModel<'t> {
pub(crate) absolute_frequencies: AHashMap<&'t [char], usize>,
}
impl<'t> TrainingModel<'t> {
pub(crate) fn new(words_chars: &'t [Vec<char>]) -> Self {
let mut absolute_frequencies = AHashMap::new();
for chars in words_chars.iter() {
*absolute_frequencies.entry(chars.as_ref()).or_default() += 1;
}
Self {
absolute_frequencies,
}
}
pub(crate) fn new_windows(words_chars: &'t [Vec<char>], ngram_length: usize) -> Self {
let mut absolute_frequencies = AHashMap::new();
for chars in words_chars.iter() {
for ngram in chars.windows(ngram_length) {
*absolute_frequencies.entry(ngram).or_default() += 1;
}
}
// let min_count = absolute_frequencies.values().sum::<usize>() / 10_000_000;
// absolute_frequencies.retain(|_, c| *c > min_count);
Self {
absolute_frequencies,
}
}
fn compute_relative_frequencies(
&self,
lower_ngram_absolute_frequencies: AHashMap<&'t [char], usize>,
) -> AHashMap<GenericFraction<usize>, Vec<&'t [char]>> {
let total_count = self.absolute_frequencies.values().sum::<usize>();
let mut ngram_probabilities: AHashMap<GenericFraction<usize>, Vec<_>> = AHashMap::new();
for (&ngram, &frequency) in self.absolute_frequencies.iter() {
let denominator = if lower_ngram_absolute_frequencies.is_empty() {
total_count
} else {
let Some(&start_ngram_abs_fr) =
lower_ngram_absolute_frequencies.get(&ngram[..ngram.len() - 1])
else {
continue;
};
let Some(&end_ngram_abs_fr) = lower_ngram_absolute_frequencies.get(&ngram[1..])
else {
continue;
};
start_ngram_abs_fr.min(end_ngram_abs_fr)
};
let fract = GenericFraction::<usize>::new(frequency, denominator);
ngram_probabilities.entry(fract).or_default().push(ngram);
}
ngram_probabilities
}
pub(crate) fn to_file_model(
&self,
lower_ngram_absolute_frequencies: AHashMap<&'t [char], usize>,
join: &[char],
) -> FileModel {
let relative_frequencies =
self.compute_relative_frequencies(lower_ngram_absolute_frequencies);
let mut sorted: Vec<_> = relative_frequencies.into_iter().collect();
sorted.sort_unstable_by(|a, b| b.0.cmp(&a.0));
let mut lang_model: FileModel = (self.absolute_frequencies.len(), Default::default());
for (gf, mut ngrams) in sorted {
ngrams.sort_unstable();
lang_model.1.insert_unchecked(
Fraction::from(gf),
// ngrams.into_iter().flat_map(|v| v.iter()).collect(),
itertools::Itertools::intersperse(ngrams.into_iter(), join)
.flat_map(|v| v.iter())
.collect(),
);
}
lang_model
}
/*pub(crate) fn to_match(self, file_path: &Path) -> io::Result<()> {
let mut sorted: Vec<_> = self.relative_frequencies.unwrap().into_iter().collect();
sorted.sort_unstable_by(|a, b| b.0.cmp(&a.0));
if let Some(parent) = file_path.parent() {
create_dir_all(parent)?;
}
let mut file = File::create(file_path)?;
file.write_all(b"#![cfg_attr(rustfmt,rustfmt_skip)]\n")?;
if self.ngram_length == 1 {
file.write_all(b"pub(super) fn prob(c:char) -> f64 {\nmatch c {\n")?;
} else {
file.write_all(b"pub(super) fn prob(g:&[char;")?;
file.write_all(self.ngram_length.to_string().as_bytes())?;
file.write_all(b"]) -> f64 {\nmatch g {\n")?;
}
for (fraction, ngrams) in sorted {
if self.ngram_length == 1 {
file.write_all(b"'")?;
file.write_all(
ngrams
.into_iter()
.map(|n| {
n.chars()
.map(|c| {
if c == '\'' {
"\\'".to_owned()
} else {
c.to_string()
}
})
.next()
.unwrap()
})
.join("'|'")
.as_bytes(),
)?;
file.write_all(b"'=>")?;
} else {
file.write_all(b"&['")?;
file.write_all(
ngrams
.into_iter()
.map(|n| {
n.chars()
.map(|c| {
if c == '\'' {
"\\'".to_owned()
} else {
c.to_string()
}
})
.join("','")
})
.join("']|&['")
.as_bytes(),
)?;
file.write_all(b"']=>")?;
}
let numer = fraction.numer().unwrap();
let denom = fraction.denom().unwrap();
if numer == denom {
file.write_all(b"1.0,\n")?;
} else {
file.write_all(numer.to_string().as_bytes())?;
file.write_all(b".0/")?;
file.write_all(denom.to_string().as_bytes())?;
file.write_all(b".0,\n")?;
}
}
file.write_all(b"_=>0.0,\n}\n}")
}*/
}