File size: 19,405 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 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 |
//! The `loda-rust pattern` subcommand, identifies recurring patterns.
use crate::common::{find_asm_files_recursively, find_csv_files_recursively, oeis_id_from_path, parse_csv_file};
use crate::pattern::{Clusters, instruction_diff_between_constants, ProgramSimilarity, RecordSimilar};
use crate::config::Config;
use loda_rust_core::parser::{Instruction, InstructionId, ParsedProgram};
use std::time::Instant;
use std::path::{Path, PathBuf};
use std::fs;
use std::fs::File;
use std::io::prelude::*;
use std::collections::HashSet;
use std::collections::HashMap;
use std::error::Error;
use std::rc::Rc;
use std::iter::FromIterator;
const PROGRAM_LENGTH_MINIMUM: usize = 1;
const PROGRAM_LENGTH_MAXIMUM: usize = 80;
const MINIMUM_NUMBER_OF_SIMILAR_PROGRAMS_BEFORE_ITS_A_PATTERN: usize = 15;
const DISCARD_PATTERNS_WITHOUT_ANY_PARAMETERS: bool = true;
/// Identify recurring patterns among similar programs.
pub struct SubcommandPattern {
append_verbose_details: bool,
}
impl SubcommandPattern {
pub fn run(append_verbose_details: bool) {
let instance = Self {
append_verbose_details: append_verbose_details
};
instance.run_inner();
}
fn run_inner(&self) {
let start_time = Instant::now();
let config = Config::load();
let loda_programs_oeis_dir: PathBuf = config.loda_programs_oeis_dir();
let similar_programs: PathBuf = config.similar_programs();
let output_dir: PathBuf = config.loda_patterns_repository_simple_constant();
// Find all similarity CSV files.
let mut similarity_csv_paths: Vec<PathBuf> = find_csv_files_recursively(&similar_programs);
similarity_csv_paths.sort();
let number_of_similarity_csv_paths = similarity_csv_paths.len();
if number_of_similarity_csv_paths <= 0 {
error!("Expected 1 or more similarity csv files, but there are none to analyze");
return;
}
debug!("number of similarity csv files: {}", number_of_similarity_csv_paths);
let mut csv_vec = Vec::<Rc<SimilarityCSVFile>>::new();
for path in similarity_csv_paths {
let program_id: u32 = match oeis_id_from_path(&path) {
Some(oeis_id) => oeis_id.raw(),
None => { continue; }
};
let instance = SimilarityCSVFile::new(program_id, path);
csv_vec.push(Rc::new(instance));
}
let mut program_id_to_csv_hashmap = ProgramIdToSimilarityCSVFile::new();
for csv_item in csv_vec {
program_id_to_csv_hashmap.insert(csv_item.program_id, Rc::clone(&csv_item));
}
let number_of_items_in_csv_hashmap = program_id_to_csv_hashmap.len();
if number_of_items_in_csv_hashmap <= 0 {
error!("Expected 1 or more similarity csv files, but there are none to analyze");
return;
}
debug!("number of unique program_ids in csv hashmap: {:?}", number_of_items_in_csv_hashmap);
// Find all programs.
let mut program_asm_paths: Vec<PathBuf> = find_asm_files_recursively(&loda_programs_oeis_dir);
program_asm_paths.sort();
let number_of_program_asm_paths = program_asm_paths.len();
if number_of_program_asm_paths <= 0 {
error!("Expected 1 or more program asm files, but there are none to analyze");
return;
}
debug!("number of program asm files: {}", number_of_program_asm_paths);
// Parse all programs.
// Ignoring too short/long programs.
let mut program_meta_vec = Vec::<Rc<ProgramMeta>>::new();
for path in program_asm_paths {
let program_meta = match self.analyze_program(&path) {
Some(value) => value,
None => {
continue;
}
};
program_meta_vec.push(Rc::new(program_meta));
}
debug!("number of program_meta items: {}", program_meta_vec.len());
// Obtain the number of lines of all programs.
let mut line_count_set = HashSet::<u16>::new();
for program_meta in &program_meta_vec {
line_count_set.insert(program_meta.line_count);
}
let mut line_count_vec: Vec<u16> = line_count_set.into_iter().collect();
line_count_vec.sort();
debug!("line_count's: {:?}", line_count_vec);
self.traverse_by_line_count(
&line_count_vec,
&program_meta_vec,
&program_id_to_csv_hashmap,
&output_dir,
);
println!("elapsed: {:?} ms", start_time.elapsed().as_millis());
}
fn traverse_by_line_count(
&self,
line_count_vec: &Vec<u16>,
program_meta_vec: &Vec<Rc<ProgramMeta>>,
program_id_to_similarity_csv_file: &ProgramIdToSimilarityCSVFile,
output_dir: &Path,
) {
for line_count in line_count_vec {
let mut programs_with_same_length = Vec::<Rc<ProgramMeta>>::new();
for program_meta in program_meta_vec {
if program_meta.line_count != *line_count {
continue;
}
programs_with_same_length.push(Rc::clone(program_meta));
}
self.process_programs_with_same_length(
*line_count,
&programs_with_same_length,
program_id_to_similarity_csv_file,
output_dir,
);
}
}
fn process_programs_with_same_length(
&self,
line_count: u16,
program_meta_vec: &Vec<Rc<ProgramMeta>>,
program_id_to_similarity_csv_file: &ProgramIdToSimilarityCSVFile,
output_dir: &Path,
) {
println!("line count: {:?} number of programs: {:?}", line_count, program_meta_vec.len());
// Build a hashmap of programs with the same number of lines
let mut program_id_to_program_meta_hashmap = ProgramIdToProgramMeta::new();
for program_meta_item in program_meta_vec {
program_id_to_program_meta_hashmap.insert(program_meta_item.program_id, Rc::clone(&program_meta_item));
}
let mut number_of_similarity_records: usize = 0;
let mut clusters = Clusters::new();
for program_meta in program_meta_vec {
let program_id: u32 = program_meta.program_id;
// Find corresponding similarity csv file
let csv_file: Rc<SimilarityCSVFile> = match program_id_to_similarity_csv_file.get(&program_id) {
Some(value) => Rc::clone(value),
None => {
debug!("ignoring program_id: {}, because it's missing a similarity csv file", program_id);
continue;
}
};
// Parse the similarity csv file
let similarity_records: Vec<RecordSimilar> = match parse_csv_file(&csv_file.path) {
Ok(value) => value,
Err(error) => {
debug!("ignoring program_id: {}. cannot load csv file {:?}", program_id, error);
continue;
}
};
number_of_similarity_records += similarity_records.len();
// Compare this program with each rows in the csv file
self.find_patterns(
program_id,
&similarity_records,
&program_id_to_program_meta_hashmap,
&mut clusters
);
}
debug!("number of records: {}", number_of_similarity_records);
let mut clusters_of_programids: Vec<HashSet<u32>> = clusters.clusters_of_programids();
// Keep only the patterns that repeats a lot.
// Eliminate patterns that rarely occurs.
let number_of_all_clusters: usize = clusters_of_programids.len();
clusters_of_programids.retain(|program_id_set| program_id_set.len() >= MINIMUM_NUMBER_OF_SIMILAR_PROGRAMS_BEFORE_ITS_A_PATTERN);
let number_of_patterns: usize = clusters_of_programids.len();
debug!("number of clusters: {}", number_of_all_clusters);
println!("number of patterns: {}", number_of_patterns);
for program_id_set in clusters_of_programids {
let save_result = self.save_pattern(line_count, &program_id_set, &program_id_to_program_meta_hashmap, output_dir);
match save_result {
Ok(_) => {},
Err(error) => {
error!("Unable to save result. {:?}", error);
}
}
}
}
fn save_pattern(
&self,
line_count: u16,
program_id_set: &HashSet<u32>,
program_id_to_program_meta_hashmap: &ProgramIdToProgramMeta,
output_dir: &Path
) -> Result<(), Box<dyn Error>> {
let lowest_program_id: u32 = match Clusters::lowest_program_id_in_set(program_id_set) {
Some(value) => value,
None => {
error!("unable to find lowest program id.");
return Ok(());
}
};
let original_program_meta: Rc<ProgramMeta> = match program_id_to_program_meta_hashmap.get(&lowest_program_id) {
Some(value) => Rc::clone(value),
None => {
debug!("ignoring program: {}. there is no asm file.", lowest_program_id);
return Ok(());
}
};
let mut line_number_to_value_set = HashMap::<usize, HashSet<i64>>::new();
for program_id_item in program_id_set {
let similar_program_meta: Rc<ProgramMeta> = match program_id_to_program_meta_hashmap.get(&program_id_item) {
Some(value) => Rc::clone(value),
None => {
continue;
}
};
let instruction_vec0 = &original_program_meta.parsed_program.instruction_vec;
let instruction_vec1 = &similar_program_meta.parsed_program.instruction_vec;
// Reject if the number of instructions differs
if instruction_vec0.len() != instruction_vec1.len() {
continue;
}
// Reject if the instructions differs
for index in 0..instruction_vec0.len() {
if instruction_vec0[index].instruction_id != instruction_vec1[index].instruction_id {
continue;
}
}
for index in 0..instruction_vec0.len() {
let instruction0: &Instruction = &instruction_vec0[index];
let instruction1: &Instruction = &instruction_vec1[index];
// If the instructions have different constants
// then remember the line number and the constants.
let diff = instruction_diff_between_constants(instruction0, instruction1);
if let Some((constant0, constant1)) = diff {
let entry = line_number_to_value_set.entry(index).or_insert_with(|| HashSet::new());
entry.insert(constant0);
entry.insert(constant1);
}
}
}
let mut annotated_program = String::with_capacity(4000);
let instruction_vec = &original_program_meta.parsed_program.instruction_vec;
let mut indentation: usize = 0;
let mut pretty_parameters = Vec::<String>::new();
for index in 0..instruction_vec.len() {
let instruction: &Instruction = &instruction_vec[index];
if index > 0 {
annotated_program.push_str("\n");
}
// Indent nested loops
if instruction.instruction_id == InstructionId::LoopEnd {
if indentation > 0 {
indentation -= 1;
}
}
for _ in 0..indentation {
annotated_program.push_str(" ");
}
if instruction.instruction_id == InstructionId::LoopBegin {
indentation += 1;
}
// The instruction
annotated_program.push_str(&format!("{}", instruction));
let value_set: &HashSet<i64> = match line_number_to_value_set.get(&index) {
Some(value) => value,
None => {
continue;
}
};
// The parameter index
let parameter_index = pretty_parameters.len();
annotated_program.push_str(" ; ");
annotated_program.push_str(&format!("source=parameter {}", parameter_index));
// Format the parameter values
let mut value_vec: Vec<&i64> = Vec::from_iter(value_set);
value_vec.sort();
let value_strings: Vec<String> = value_vec.iter().map(|value| format!("{}", value) ).collect();
let mut formatted_parameter = String::with_capacity(1000);
formatted_parameter.push_str(&format!("; parameter {}\n", parameter_index));
formatted_parameter.push_str(&format!("; number of unique values: {}\n", value_set.len()));
formatted_parameter.push_str("; value: ");
formatted_parameter.push_str(&value_strings.join(","));
pretty_parameters.push(formatted_parameter);
}
let number_of_parameters: usize = line_number_to_value_set.len();
if DISCARD_PATTERNS_WITHOUT_ANY_PARAMETERS && number_of_parameters == 0 {
return Ok(());
}
// Convert program_ids to a formatted string
let mut program_ids: Vec<u32> = program_id_set.iter().map(|program_id| *program_id).collect();
program_ids.sort();
let program_id_strings: Vec<String> = program_ids.iter().map(|program_id| format!("{}", program_id)).collect();
let formatted_program_ids: String = program_id_strings.join(",");
// File content
let mut content = String::with_capacity(4000);
content += &annotated_program;
content += "\n";
if self.append_verbose_details {
content += "\n";
if !pretty_parameters.is_empty() {
content += &pretty_parameters.join("\n\n");
content += "\n\n";
}
content += "; programs with this pattern\n";
content += &format!("; number of programs: {:?}\n", program_id_set.len());
content += "; program id: ";
content += &formatted_program_ids;
content += "\n";
}
// Version control of the found patterns.
// Ideally pick a filename that stays the same, no matter how many programs follow the same pattern.
// The number of lines in the patterns doesn't change.
// The number of parameters changes, if new programs starts making creative parameter changes.
// The OEIS sequence id of the lowest program. This changes if it has started using another pattern.
let filename = format!("lines{}_parameters{}_A{}.asm", line_count, number_of_parameters, lowest_program_id);
let path: PathBuf = output_dir.join(Path::new(&filename));
let mut file = File::create(path)?;
file.write_all(content.as_bytes())?;
Ok(())
}
fn find_patterns(
&self,
program_id: u32,
similarity_records: &Vec<RecordSimilar>,
program_id_to_program_meta_hashmap: &ProgramIdToProgramMeta,
clusters: &mut Clusters,
) {
let original_program_meta: Rc<ProgramMeta> = match program_id_to_program_meta_hashmap.get(&program_id) {
Some(value) => Rc::clone(value),
None => {
debug!("ignoring program: {}. there is no asm file.", program_id);
return;
}
};
let mut highly_similar_programs = Vec::<Rc<ProgramMeta>>::with_capacity(26);
for record in similarity_records {
let similar_program_meta: Rc<ProgramMeta> = match program_id_to_program_meta_hashmap.get(&record.program_id) {
Some(value) => Rc::clone(value),
None => {
continue;
}
};
let similarity = ProgramSimilarity::measure_similarity(
&original_program_meta.parsed_program.instruction_vec,
&similar_program_meta.parsed_program.instruction_vec
);
match similarity {
ProgramSimilarity::NotSimilar => {
continue;
},
ProgramSimilarity::SimilarWithDifferentConstants(_) => {
highly_similar_programs.push(similar_program_meta);
}
}
}
highly_similar_programs.push(original_program_meta);
let highly_similar_program_ids: Vec<u32> = highly_similar_programs.iter().map(|pm|pm.program_id).collect();
// println!("program id: {} has many similar with minor diffs to constants: {:?}", program_id, highly_similar_program_ids);
clusters.insert(&highly_similar_program_ids);
}
fn analyze_program(
&self,
path: &Path,
) -> Option<ProgramMeta> {
let program_id: u32 = match oeis_id_from_path(path) {
Some(oeis_id) => oeis_id.raw(),
None => {
return None;
}
};
let parsed_program: ParsedProgram = match self.load_program(path) {
Some(value) => value,
None => {
return None;
}
};
let line_count_raw: usize = parsed_program.instruction_vec.len();
if line_count_raw < PROGRAM_LENGTH_MINIMUM {
return None;
}
if line_count_raw > PROGRAM_LENGTH_MAXIMUM {
error!("analyze_program. Skipping a program that is too long. path: {:?}", path);
return None;
}
Some(ProgramMeta::new(program_id, line_count_raw as u16, parsed_program))
}
fn load_program(
&self,
path: &Path
) -> Option<ParsedProgram> {
let contents: String = match fs::read_to_string(path) {
Ok(value) => value,
Err(error) => {
error!("load program, error: {:?} path: {:?}", error, path);
return None;
}
};
let parsed_program: ParsedProgram = match ParsedProgram::parse_program(&contents) {
Ok(value) => value,
Err(error) => {
error!("load program, error: {:?} path: {:?}", error, path);
return None;
}
};
Some(parsed_program)
}
}
struct ProgramMeta {
program_id: u32,
line_count: u16,
parsed_program: ParsedProgram,
}
impl ProgramMeta {
fn new(program_id: u32, line_count: u16, parsed_program: ParsedProgram) -> Self {
Self {
program_id: program_id,
line_count: line_count,
parsed_program: parsed_program,
}
}
}
type ProgramIdToProgramMeta = HashMap::<u32, Rc::<ProgramMeta>>;
struct SimilarityCSVFile {
program_id: u32,
path: PathBuf,
}
impl SimilarityCSVFile {
fn new(program_id: u32, path: PathBuf) -> Self {
Self {
program_id: program_id,
path: path
}
}
}
type ProgramIdToSimilarityCSVFile = HashMap::<u32, Rc::<SimilarityCSVFile>>;
|