File size: 9,188 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 |
use super::random_indexes_with_distance;
use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::collections::{HashMap, HashSet};
use std::iter::FromIterator;
use serde::Deserialize;
use rand::Rng;
use rand::seq::SliceRandom;
use rand::SeedableRng;
use rand::rngs::StdRng;
use loda_rust_core::parser::{InstructionId, ParseInstructionId};
use crate::common::parse_csv_data;
type ValueAndWeight = (i32,u32);
type ValueAndWeightVector = Vec<ValueAndWeight>;
/// Instructions that takes a constant value.
///
/// The most used combo: `add $0,1` (addition by 1)
///
/// Almost as popular combo: `sub $0,1` (subtract by 1)
///
/// Usecase:
/// During mining, when mutating an `add` instruction.
///
/// It's a time waster making poor choices of constants.
/// The miner originally picked random integers, but it was excruciating slow.
///
/// Time can be saved this way.
///
/// Before mining: analyze all programs and build a histogram.
///
/// During mining: make weighted choices from the histogram.
#[derive(Clone, Debug)]
pub struct HistogramInstructionConstant {
instruction_and_valueweightvector: HashMap<InstructionId, ValueAndWeightVector>
}
impl HistogramInstructionConstant {
pub fn number_of_items(&self) -> usize {
self.instruction_and_valueweightvector.len()
}
#[allow(dead_code)]
pub fn load_csv_file(path: &Path) -> Result<HistogramInstructionConstant, Box<dyn Error>> {
let file = File::open(path)?;
let mut reader = BufReader::new(file);
Self::create(&mut reader)
}
const SHUFFLE_COUNT: usize = 0;
fn create(reader: &mut dyn BufRead) -> Result<HistogramInstructionConstant, Box<dyn Error>> {
let records_original: Vec<Record> = parse_csv_data::<Record>(reader)?;
// Shuffle the items slightly
let mut records: Vec<Record> = records_original.clone();
let seed: u64 = 1;
let mut rng = StdRng::seed_from_u64(seed);
let indexes: Vec<usize> = random_indexes_with_distance(&mut rng, records.len(), Self::SHUFFLE_COUNT);
for index in indexes {
records[index].count = records_original[index].count;
}
let instruction_and_valueweightvector: HashMap<InstructionId, ValueAndWeightVector> =
Record::instruction_and_valueweightvector(&records);
let result = Self {
instruction_and_valueweightvector: instruction_and_valueweightvector
};
Ok(result)
}
pub fn choose_weighted<R: Rng + ?Sized>(&self, rng: &mut R, instruction_id: InstructionId) -> Option<i32> {
let value_and_weight_vec: &ValueAndWeightVector =
match self.instruction_and_valueweightvector.get(&instruction_id) {
Some(value) => value,
None => {
return None;
}
};
let value: i32 = value_and_weight_vec.choose_weighted(rng, |item| item.1).unwrap().0;
Some(value)
}
}
#[derive(Clone, Debug, Deserialize)]
struct Record {
count: u32,
instruction: String,
constant: i32,
}
impl Record {
fn unique_instruction_ids(records: &Vec<Record>) -> HashSet<InstructionId> {
let mut instruction_ids = Vec::<InstructionId>::new();
for record in records {
match InstructionId::parse(&record.instruction, 0) {
Ok(instruction_id) => {
instruction_ids.push(instruction_id);
},
Err(_) => {}
}
}
HashSet::from_iter(instruction_ids.iter().cloned())
}
fn value_and_weight_vec(records: &Vec<Record>, instruction_id: InstructionId) -> ValueAndWeightVector {
let mut value_and_weight_vec: ValueAndWeightVector = vec!();
let needle: String = instruction_id.to_string();
let mut already_known = HashSet::<i32>::new();
for record in records {
if record.instruction != needle {
continue;
}
if already_known.contains(&record.constant) {
// Keep only the first value. Ignore following duplicates.
continue;
}
let value = (record.constant, record.count);
value_and_weight_vec.push(value);
already_known.insert(record.constant);
}
value_and_weight_vec
}
fn instruction_and_valueweightvector(records: &Vec<Record>) -> HashMap<InstructionId, ValueAndWeightVector> {
let instruction_ids: HashSet<InstructionId> = Record::unique_instruction_ids(&records);
let mut result: HashMap<InstructionId, ValueAndWeightVector> = HashMap::new();
for instruction_id in instruction_ids {
let value_and_weight_vec: ValueAndWeightVector =
Record::value_and_weight_vec(&records, instruction_id);
if value_and_weight_vec.is_empty() {
continue;
}
result.insert(instruction_id, value_and_weight_vec);
}
result
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::SeedableRng;
use rand::rngs::StdRng;
#[test]
fn test_10000_parse_csv_data() {
let data = "\
count;instruction;constant
36545;add;1
33648;sub;1
17147;mul;-2
";
let mut input: &[u8] = data.as_bytes();
let records: Vec<Record> = parse_csv_data(&mut input).unwrap();
let strings: Vec<String> = records.iter().map(|record| {
format!("{} {} {}", record.count, record.instruction, record.constant)
}).collect();
let strings_joined: String = strings.join(",");
assert_eq!(strings_joined, "36545 add 1,33648 sub 1,17147 mul -2");
}
#[test]
fn test_10001_unique_instruction_ids() {
let data = "\
count;instruction;constant
36545;add;1
9232;add;2
666;unknown;23
555;sub;1
171;mul;-2
92;add;3
";
let mut input: &[u8] = data.as_bytes();
let records: Vec<Record> = parse_csv_data(&mut input).unwrap();
let actual: HashSet<InstructionId> = Record::unique_instruction_ids(&records);
let v = vec![InstructionId::Add, InstructionId::Subtract, InstructionId::Multiply];
let expected: HashSet<InstructionId> = HashSet::from_iter(v);
assert_eq!(actual, expected);
}
#[test]
fn test_10002_value_and_weight_vec_typical_data() {
let data = "\
count;instruction;constant
36545;add;1
92;add;2
9232;add;3
100;add;4
";
let mut input: &[u8] = data.as_bytes();
let records: Vec<Record> = parse_csv_data(&mut input).unwrap();
let actual: ValueAndWeightVector = Record::value_and_weight_vec(&records, InstructionId::Add);
let expected: ValueAndWeightVector = vec![(1,36545),(2,92),(3,9232),(4,100)];
assert_eq!(actual, expected);
}
#[test]
fn test_10003_value_and_weight_vec_without_duplicates() {
let data = "\
count;instruction;constant
1000;add;1
1000;add;2
1000;add;1
1000;add;3
1001;add;1
";
let mut input: &[u8] = data.as_bytes();
let records: Vec<Record> = parse_csv_data(&mut input).unwrap();
let actual: ValueAndWeightVector = Record::value_and_weight_vec(&records, InstructionId::Add);
let expected: ValueAndWeightVector = vec![(1,1000),(2,1000),(3,1000)];
assert_eq!(actual, expected);
}
#[test]
fn test_10004_instruction_and_valueweightvector() {
let data = "\
count;instruction;constant
1001;add;1
1002;add;2
999;div;2
998;mul;-1
";
let mut input: &[u8] = data.as_bytes();
let records: Vec<Record> = parse_csv_data(&mut input).unwrap();
let actual: HashMap<InstructionId, ValueAndWeightVector> = Record::instruction_and_valueweightvector(&records);
assert_eq!(actual.len(), 3);
}
#[test]
fn test_20000_instruction_and_valueweightvector_add() {
let data = "\
count;instruction;constant
1000;add;1984
1000;mul;-1
";
let mut input: &[u8] = data.as_bytes();
let instance = HistogramInstructionConstant::create(&mut input).unwrap();
let mut rng = StdRng::seed_from_u64(0);
let actual = instance.choose_weighted(&mut rng, InstructionId::Add);
assert_eq!(actual, Some(1984));
}
#[test]
fn test_20001_instruction_and_valueweightvector_multiply() {
let data = "\
count;instruction;constant
1000;add;1984
1000;mul;-1
";
let mut input: &[u8] = data.as_bytes();
let instance = HistogramInstructionConstant::create(&mut input).unwrap();
let mut rng = StdRng::seed_from_u64(0);
let actual = instance.choose_weighted(&mut rng, InstructionId::Multiply);
assert_eq!(actual, Some(-1));
}
#[test]
fn test_20002_instruction_and_valueweightvector_no_such_instruction() {
let data = "\
count;instruction;constant
1000;add;1984
1000;mul;-1
";
let mut input: &[u8] = data.as_bytes();
let instance = HistogramInstructionConstant::create(&mut input).unwrap();
let mut rng = StdRng::seed_from_u64(0);
let actual = instance.choose_weighted(&mut rng, InstructionId::GCD);
assert_eq!(actual, None);
}
}
|