File size: 13,791 Bytes
d5bfab8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
use super::{AnalyticsDirectory, AnalyticsMode, BatchProgramAnalyzerPlugin, BatchProgramAnalyzerContext};
use crate::common::create_csv_file;
use crate::common::RecordBigram;
use crate::common::RecordTrigram;
use crate::common::RecordSkipgram;
use crate::common::RecordUnigram;
use loda_rust_core;
use loda_rust_core::parser::ParameterType;
use loda_rust_core::parser::{InstructionId, ParsedProgram};
use std::path::PathBuf;
use std::error::Error;
use std::collections::HashMap;

type HistogramBigramKey = (String,String);
type HistogramTrigramKey = (String,String,String);
type HistogramSkipgramKey = (String,String);

/// Creates [N-gram] csv files with lines of LODA code.
/// 
/// Traverses all the programs inside the `loda-programs/oeis` dir.
/// It looks for all the LODA assembly programs there are.
/// Determines the most frequent combinations of LODA code lines.
/// 
/// ---
/// 
/// This outputs a `histogram_line_unigram.csv` file, with this format:
/// 
/// ```csv
/// count;word
/// 96597;STOP
/// 96597;START
/// 69080;lpe
/// 43970;lpb $0
/// 38553;mov $0,$1
/// 37459;add $0,1
/// 35716;sub $0,1
/// 21085;mov $1,$0
/// ```
///
/// Learnings from this unigram with LODA programs:
/// 
/// Learning A: Loop instructions are the most used instructions.
/// 
/// Learning B: As of 2022-oct-16 there are 102k LODA programs.
/// When ignoring values greater than 100, 
/// then there are 9k rows that 2 or more times and 12k rows that occurs once.
/// 
/// ---
/// 
/// This outputs a `histogram_line_bigram.csv` file, with this format:
/// 
/// ```csv
/// count;word0;word1
/// 25134;mov $0,$1;STOP
/// 20623;lpb $0;sub $0,1
/// 19807;lpe;mov $0,$1
/// 14278;START;mov $1,$0
/// 11410;add $0,1;STOP
/// 10803;START;add $0,1
/// 10034;START;mov $1,1
/// 8582;START;lpb $0
/// ```
/// 
/// Learnings from this bigram with LODA programs:
/// 
/// Learning A: Many programs ends with a `mov $0,$1` instruction.
/// Many programs starts with a `mov $1,$0` instruction, which is the opposite.
/// 
/// ---
/// 
/// This outputs a `histogram_line_trigram.csv` file, with this format:
/// 
/// ```csv
/// count;word0;word1;word2
/// 12576;lpe;mov $0,$1;STOP
/// 4255;mov $4,$0;max $4,0;cmp $4,$0
/// 4022;lpe;mov $0,$2;STOP
/// 3823;add $0,1;lpb $0;sub $0,1
/// 3607;max $4,0;cmp $4,$0;mul $2,$4
/// 3464;lpe;mov $0,$3;STOP
/// 3288;sub $2,1;lpe;mov $0,$1
/// 3197;mul $2,$4;sub $2,1;lpe
/// ```
/// 
/// ---
/// 
/// This outputs a `histogram_line_skipgram.csv` file, with this format:
/// 
/// ```csv
/// count;word0;word2
/// 27776;lpe;STOP
/// 11992;START;lpb $0
/// 9280;mov $0,$1;STOP
/// 5704;START;mov $2,$0
/// 5403;START;add $0,1
/// 5131;lpe;add $0,1
/// 4397;mov $4,$0;cmp $4,$0
/// 4249;add $0,1;sub $0,1
/// ```
/// 
/// [N-gram]: <https://en.wikipedia.org/wiki/N-gram>
pub struct AnalyzeLineNgram {
    analytics_directory: AnalyticsDirectory,
    limit_lower: i64,
    limit_upper: i64,
    histogram_unigram: HashMap<String,u32>,
    histogram_bigram: HashMap<HistogramBigramKey,u32>,
    histogram_trigram: HashMap<HistogramTrigramKey,u32>,
    histogram_skipgram: HashMap<HistogramSkipgramKey,u32>,
    ignore_count: usize,
}

impl AnalyzeLineNgram {
    pub fn new(analytics_directory: AnalyticsDirectory, mode: AnalyticsMode) -> Self {
        match mode {
            AnalyticsMode::OEIS => {
                // When mining for OEIS sequences, then magic constants are unwanted.
                // Values like 3, or 7 are considered nice values.
                // However a values like 123456789 is considered huge and magic.
                let limit_lower: i64 = -100;
                let limit_upper: i64 = 100;
                return Self::create(analytics_directory, limit_lower, limit_upper);
            },
            AnalyticsMode::ARC => {
                // No particular preference about the lower limit.
                let limit_lower: i64 = -100;

                // It's a big memory layout of the ARC puzzles.
                // The input registers are between 100 and 200.
                // Thus the `magic_constant_upper_limit` is 200.
                let limit_upper: i64 = 200;
                return Self::create(analytics_directory, limit_lower, limit_upper);
            },
        }
    }

    fn create(analytics_directory: AnalyticsDirectory, limit_lower: i64, limit_upper: i64) -> Self {
        Self {
            analytics_directory,
            limit_lower,
            limit_upper,
            histogram_unigram: HashMap::new(),
            histogram_bigram: HashMap::new(),
            histogram_trigram: HashMap::new(),
            histogram_skipgram: HashMap::new(),
            ignore_count: 0,
        }
    }

    fn extract_words(&mut self, parsed_program: &ParsedProgram) -> Vec<String> {
        let mut words: Vec<String> = vec!();
        words.push("START".to_string());
        for instruction in &parsed_program.instruction_vec {
            // Ignore programs that serves as bad examples. Huge magic constants are unwanted.
            // When there is a huge magic constant, then ignore the program.
            // For the `seq` instruction allow huge constants.
            // For the unofficial `fxy` instructions allow huge constants.
            let should_reject_extreme_source_constant: bool = match instruction.instruction_id {
                InstructionId::EvalSequence | 
                InstructionId::UnofficialFunction { .. }  => false,
                _ => true
            };
            if should_reject_extreme_source_constant {
                if instruction.parameter_vec.len() == 2 {
                    if let Some(parameter) = instruction.parameter_vec.last() {
                        if parameter.parameter_type == ParameterType::Constant {
                            if parameter.parameter_value < self.limit_lower {
                                debug!("Encountered a magic value that is lower than {}. Ignoring program. Instruction: {}", self.limit_lower, instruction);
                                self.ignore_count += 1;
                                return vec!();
                            }
                            if parameter.parameter_value > self.limit_upper {
                                debug!("Encountered a magic value that is higher than {}. Ignoring program. Instruction: {}", self.limit_upper, instruction);
                                self.ignore_count += 1;
                                return vec!();
                            }
                        }
                    }
                }
            }
            // Data seems good, append it.
            let word: String = format!("{}", instruction);
            words.push(word);
        }
        words.push("STOP".to_string());
        words
    }

    fn populate_unigram(&mut self, words: &Vec<String>) {
        let keys: Vec<String> = words.clone();
        for key in keys {
            let counter = self.histogram_unigram.entry(key).or_insert(0);
            *counter += 1;
        }
    }

    fn populate_bigram(&mut self, words: &Vec<String>) {
        let mut keys = Vec::<HistogramBigramKey>::new();
        let mut prev_word = String::new();
        for (index, word1) in words.iter().enumerate() {
            let word0: String = prev_word;
            prev_word = word1.clone();
            if index == 0 {
                continue;
            }
            let key: HistogramBigramKey = (word0, word1.clone());
            keys.push(key);
        }
        for key in keys {
            let counter = self.histogram_bigram.entry(key).or_insert(0);
            *counter += 1;
        }
    }

    fn populate_trigram(&mut self, words: &Vec<String>) {
        let mut keys = Vec::<HistogramTrigramKey>::new();
        let mut prev_prev_word = String::new();
        let mut prev_word = String::new();
        for (index, word2) in words.iter().enumerate() {
            let word0: String = prev_prev_word;
            let word1: String = prev_word.clone();
            prev_prev_word = prev_word;
            prev_word = word2.clone();
            if index < 2 {
                continue;
            }
            let key: HistogramTrigramKey = (word0, word1, word2.clone());
            keys.push(key);
        }
        for key in keys {
            let counter = self.histogram_trigram.entry(key).or_insert(0);
            *counter += 1;
        }
    }

    fn populate_skipgram(&mut self, words: &Vec<String>) {
        let mut keys = Vec::<HistogramSkipgramKey>::new();
        let mut prev_prev_word = String::new();
        let mut prev_word = String::new();
        for (index, word2) in words.iter().enumerate() {
            let word0: String = prev_prev_word;
            prev_prev_word = prev_word;
            prev_word = word2.clone();
            if index < 2 {
                continue;
            }
            let key: HistogramSkipgramKey = (word0, word2.clone());
            keys.push(key);
        }
        for key in keys {
            let counter = self.histogram_skipgram.entry(key).or_insert(0);
            *counter += 1;
        }
    }

    fn save_unigram(&self) -> Result<(), Box<dyn Error>> {
        // Convert from dictionary to array
        let mut records = Vec::<RecordUnigram>::new();
        for (histogram_key, histogram_count) in &self.histogram_unigram {
            let record = RecordUnigram {
                count: *histogram_count,
                word: histogram_key.clone(),
            };
            records.push(record);
        }

        // Move the most frequently occuring items to the top
        // Move the lesser used items to the bottom
        records.sort_unstable_by_key(|item| (item.count, item.word.clone()));
        records.reverse();

        // Save as a CSV file
        let output_path: PathBuf = self.analytics_directory.histogram_line_unigram_file();
        create_csv_file(&records, &output_path)
    }

    fn save_bigram(&self) -> Result<(), Box<dyn Error>> {
        // Convert from dictionary to array
        let mut records = Vec::<RecordBigram>::new();
        for (histogram_key, histogram_count) in &self.histogram_bigram {
            let record = RecordBigram {
                count: *histogram_count,
                word0: histogram_key.0.clone(),
                word1: histogram_key.1.clone()
            };
            records.push(record);
        }

        // Move the most frequently occuring items to the top
        // Move the lesser used items to the bottom
        records.sort_unstable_by_key(|item| (item.count, item.word0.clone(), item.word1.clone()));
        records.reverse();

        // Save as a CSV file
        let output_path: PathBuf = self.analytics_directory.histogram_line_bigram_file();
        create_csv_file(&records, &output_path)
    }

    fn save_trigram(&self) -> Result<(), Box<dyn Error>> {
        // Convert from dictionary to array
        let mut records = Vec::<RecordTrigram>::new();
        for (histogram_key, histogram_count) in &self.histogram_trigram {
            let record = RecordTrigram {
                count: *histogram_count,
                word0: histogram_key.0.clone(),
                word1: histogram_key.1.clone(),
                word2: histogram_key.2.clone()
            };
            records.push(record);
        }

        // Move the most frequently occuring items to the top
        // Move the lesser used items to the bottom
        records.sort_unstable_by_key(|item| (item.count, item.word0.clone(), item.word1.clone(), item.word2.clone()));
        records.reverse();

        // Save as a CSV file
        let output_path: PathBuf = self.analytics_directory.histogram_line_trigram_file();
        create_csv_file(&records, &output_path)
    }

    fn save_skipgram(&self) -> Result<(), Box<dyn Error>> {
        // Convert from dictionary to array
        let mut records = Vec::<RecordSkipgram>::new();
        for (histogram_key, histogram_count) in &self.histogram_skipgram {
            let record = RecordSkipgram {
                count: *histogram_count,
                word0: histogram_key.0.clone(),
                word2: histogram_key.1.clone()
            };
            records.push(record);
        }

        // Move the most frequently occuring items to the top
        // Move the lesser used items to the bottom
        records.sort_unstable_by_key(|item| (item.count, item.word0.clone(), item.word2.clone()));
        records.reverse();

        // Save as a CSV file
        let output_path: PathBuf = self.analytics_directory.histogram_line_skipgram_file();
        create_csv_file(&records, &output_path)
    }
}

impl BatchProgramAnalyzerPlugin for AnalyzeLineNgram {
    fn plugin_name(&self) -> &'static str {
        "AnalyzeLineNgram"
    }
    
    fn analyze(&mut self, context: &BatchProgramAnalyzerContext) -> Result<(), Box<dyn Error>> {
        let words: Vec<String> = self.extract_words(&context.parsed_program);
        self.populate_unigram(&words);
        self.populate_bigram(&words);
        self.populate_trigram(&words);
        self.populate_skipgram(&words);
        Ok(())
    }

    fn save(&self) -> Result<(), Box<dyn Error>> {
        self.save_unigram()?;
        self.save_bigram()?;
        self.save_trigram()?;
        self.save_skipgram()?;
        Ok(())
    }

    fn human_readable_summary(&self) -> String {
        let items: Vec<String> = vec![
            format!("unigram: {:?}", self.histogram_unigram.len()),
            format!("bigram: {:?}", self.histogram_bigram.len()),
            format!("trigram: {:?}", self.histogram_trigram.len()),
            format!("skipgram: {:?}", self.histogram_skipgram.len()),
            format!("ignore count: {:?}", self.ignore_count),
        ];
        items.join(", ")
    }
}