Random mutations

This commit is contained in:
Rendo 2025-11-09 15:43:03 +05:00
commit 35d186cf05
2 changed files with 22 additions and 2 deletions

View file

@ -22,11 +22,13 @@ impl Formula {
} }
outputs outputs
} }
pub fn mutate(&mut self) {}
pub fn modify_tree(&mut self) -> NodeModifier { pub fn modify_tree(&mut self) -> NodeModifier {
self.tree.modify_tree() self.tree.modify_tree()
} }
pub fn modify_random_node(&mut self) -> NodeModifier {
self.tree.modify_node()
}
pub fn display_tree(&self) { pub fn display_tree(&self) {
self.display_recursion(0, vec![&self.tree]); self.display_recursion(0, vec![&self.tree]);
} }

View file

@ -1,4 +1,10 @@
use crate::formula::Formula; use crate::formula::Formula;
use rand::random_range;
const ACTION_ADD: u8 = 0;
const ACTION_REMOVE: u8 = 1;
const ACTION_INSERT: u8 = 2;
const ACTION_MUTATE: u8 = 3;
pub struct Learner { pub struct Learner {
best_algorithm: Formula, best_algorithm: Formula,
@ -49,7 +55,19 @@ impl Learner {
.0 .0
.clone() .clone()
} }
fn mutate_formula_randomly(formula: &mut Formula) {} fn mutate_formula_randomly(formula: &mut Formula) {
let mut editor = formula.modify_random_node();
let decided_action = random_range(0..3);
if decided_action == ACTION_ADD {
editor.add_node(editor.get_random_node());
} else if decided_action == ACTION_REMOVE {
editor.remove_node(None);
} else if decided_action == ACTION_INSERT {
editor.insert_node(editor.get_random_node(), None);
} else if decided_action == ACTION_MUTATE {
editor.mutate_node();
}
}
fn get_similarity(expected_output: &Vec<f64>, real_output: &Vec<f64>) -> Result<f64, ()> { fn get_similarity(expected_output: &Vec<f64>, real_output: &Vec<f64>) -> Result<f64, ()> {
if expected_output.len() != real_output.len() { if expected_output.len() != real_output.len() {
return Err(()); return Err(());