aboutsummaryrefslogtreecommitdiff
path: root/srchr/src/layout.rs
blob: e6ac86276f43dbdd558ccca3962a6acb376636ec (plain)
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
use crate::config::*;
use crate::corpus::*;
use crate::output::*;
use rand::prelude::*;
use std::fmt;

#[derive(Copy, Clone)]
pub struct Prelayout {
    standard_columns: [[u8; 3]; 6],
    index_columns: [[u8; 6]; 2],
}

impl Prelayout {
    pub fn get_standard_column(&self, index: usize) -> &[u8; 3] {
        &self.standard_columns[index]
    }

    pub fn get_index_column(&self, index: usize) -> &[u8; 6] {
        &self.index_columns[index]
    }

    pub fn new_random_from<R: RngCore>(pl: &Prelayout, rng: &mut R) -> Prelayout {
        let mut standard_columns = pl.standard_columns.clone();
        let mut index_columns = pl.index_columns.clone();

        let mut count = rng.gen_range(1..=MAX_NUM_TRANSPOSITIONS);
        while count > 0 {
            let source_index: bool = rng.gen();
            let target_index: bool = rng.gen();

            let saved;
            let target_col: usize;
            let target_idx: usize;
            if target_index {
                target_col = rng.gen_range(0..2);
                target_idx = rng.gen_range(0..6);
                saved = index_columns[target_col][target_idx];
            } else {
                target_col = rng.gen_range(0..6);
                target_idx = rng.gen_range(0..3);
                saved = standard_columns[target_col][target_idx];
            }

            let source_col: usize;
            let source_idx: usize;
            if source_index {
                source_col = rng.gen_range(0..2);
                source_idx = rng.gen_range(0..6);
                if target_index {
                    index_columns[target_col][target_idx] = index_columns[source_col][source_idx];
                } else {
                    standard_columns[target_col][target_idx] =
                        index_columns[source_col][source_idx];
                }
                index_columns[source_col][source_idx] = saved;
            } else {
                source_col = rng.gen_range(0..6);
                source_idx = rng.gen_range(0..3);
                if target_index {
                    index_columns[target_col][target_idx] =
                        standard_columns[source_col][source_idx];
                } else {
                    standard_columns[target_col][target_idx] =
                        standard_columns[source_col][source_idx];
                }
                standard_columns[source_col][source_idx] = saved;
            }
            count -= 1;
        }
        Prelayout {
            standard_columns,
            index_columns,
        }
    }

    fn from_char_array(ca: &[char; NUM_KEYS]) -> Prelayout {
        let mut standard_columns = [[0; 3]; 6];
        let mut index_columns = [[0; 6]; 2];

        for i in 0..6 {
            let ind = if i < 3 { i } else { i + 4 };
            for j in 0..3 {
                standard_columns[i][j] = ca[ind + j * ROW_LENGTH] as u8;
            }
        }

        for j in 0..3 {
            index_columns[0][j] = ca[3 + j * ROW_LENGTH] as u8;
            index_columns[1][j] = ca[6 + j * ROW_LENGTH] as u8;
            index_columns[0][j + 3] = ca[4 + j * ROW_LENGTH] as u8;
            index_columns[1][j + 3] = ca[5 + j * ROW_LENGTH] as u8;
        }

        Prelayout {
            standard_columns,
            index_columns,
        }
    }
}

#[derive(Copy, Clone)]
pub struct Layout {
    keys: [char; NUM_KEYS],
}

impl Layout {
    pub fn as_prelayout(&self) -> Prelayout {
        Prelayout::from_char_array(&self.keys)
    }

    pub fn from_prelayout(pl: &Prelayout, corpus: &Corpus) -> Layout {
        fn my_f32_compare(r: f32, l: f32) -> std::cmp::Ordering {
            if r < l {
                std::cmp::Ordering::Less
            } else {
                std::cmp::Ordering::Greater
            }
        }
        fn weight_function<const N: usize, const M: usize>(
            columns: &[[u8; N]; M],
            corpus: &Corpus,
        ) -> Vec<(Vec<u8>, f32)> {
            let mut result = columns
                .iter()
                .map(|col| {
                    let mut weight = 0.0;
                    let mut wcol: Vec<(u8, f32)> = col
                        .iter()
                        .map(|&c| {
                            let w = corpus.get_character_perc(c);
                            weight += w;
                            (c, w)
                        })
                        .collect();
                    wcol.sort_by(|(_, l), (_, r)| my_f32_compare(*r, *l));
                    wcol.swap(0, 1);
                    if N == 6 {
                        wcol.swap(0, 2);
                        wcol.swap(3, 4);
                        wcol.swap(3, 5);
                    }
                    (wcol.into_iter().map(|(k, _)| k as u8).collect(), weight)
                })
                .collect::<Vec<(Vec<u8>, f32)>>();
            result.sort_by(|(_, l), (_, r)| my_f32_compare(*r, *l));
            result
        }

        let mut balance: f32 = 0.0;
        let mut left_col: usize = 0;
        let mut right_col: usize = 9;
        let mut keys = ['x'; NUM_KEYS];

        let mut w_standard_columns = weight_function(&pl.standard_columns, corpus);
        while let Some((col, weight)) = w_standard_columns.pop() {
            let left: bool = ((balance >= 0.0) && (left_col <= 2)) || (right_col <= 6);
            let ind = if left { left_col } else { right_col };
            for i in 0..3 {
                keys[ind + i * ROW_LENGTH] = col[i] as char;
            }
            if left {
                left_col += 1;
            } else {
                right_col -= 1;
            }
            balance += if left { -weight } else { weight };
        }

        let w_index_columns = weight_function(&pl.index_columns, corpus);
        // Choose index order to minimise LSB (middle-index only) even though we
        // don't directly optimise for this parameter
        let mut lsbs = [0.0; 2];
        for option in [0, 1] {
            for left in [true, false] {
                let mind = if left { 2 } else { 7 };
                let side = if left { option } else { 1 - option };
                let m1 = keys[mind + 10 * 0] as u8;
                let m2 = keys[mind + 10 * 1] as u8;
                let m3 = keys[mind + 10 * 2] as u8;
                let i1 = w_index_columns[side].0[3];
                let i2 = w_index_columns[side].0[4];
                let i3 = w_index_columns[side].0[5];
                lsbs[option] += corpus.get_bigram_perc(m1, i1)
                    + corpus.get_bigram_perc(m1, i2)
                    + corpus.get_bigram_perc(m1, i3)
                    + corpus.get_bigram_perc(m2, i1)
                    + corpus.get_bigram_perc(m2, i2)
                    + corpus.get_bigram_perc(m2, i3)
                    + corpus.get_bigram_perc(m3, i1)
                    + corpus.get_bigram_perc(m3, i2)
                    + corpus.get_bigram_perc(m3, i3);
            }
        }
        let (left_ind, right_ind) = if lsbs[0] < lsbs[1] { (0, 1) } else { (1, 0) };
        for j in 0..3 {
            keys[3 + j * ROW_LENGTH] = w_index_columns[left_ind].0[j] as char;
            keys[6 + j * ROW_LENGTH] = w_index_columns[right_ind].0[j] as char;
            keys[4 + j * ROW_LENGTH] = w_index_columns[left_ind].0[j + 3] as char;
            keys[5 + j * ROW_LENGTH] = w_index_columns[right_ind].0[j + 3] as char;
        }

        Layout { keys }
    }

    pub fn get_keys(&self) -> &[char] {
        &self.keys
    }

    fn char_array_to_layout(keys: [char; NUM_KEYS]) -> Layout {
        return Layout { keys };
    }

    pub fn get_key(&self, index: usize) -> u8 {
        self.keys[index] as u8
    }

    pub fn from_verbose(inp: &str) -> Option<Layout> {
        let mut layout: [char; NUM_KEYS] = ['x'; NUM_KEYS];

        let mut k: usize = 0;
        for c in inp.chars() {
            if let Some(c) = canonicalise(c) {
                layout[k] = c as char;
                k += 1;
            }
            if k > NUM_KEYS {
                return None;
            }
        }

        return Some(Layout::char_array_to_layout(layout));
    }
}

impl fmt::Display for Layout {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str(&format_block_output(self.keys.into_iter()))
    }
}