Skip to content

Commit

Permalink
Merge pull request #49 from inflectrix/41-write-more-tests
Browse files Browse the repository at this point in the history
write more tests
  • Loading branch information
HyperCodec authored Apr 18, 2024
2 parents e6d1215 + cc88ebf commit 66391cc
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,68 @@ pub use topology::*;

#[cfg(feature = "serde")]
pub use nnt_serde::*;

#[cfg(test)]
mod tests {
use super::*;
use rand::prelude::*;

#[derive(RandomlyMutable, DivisionReproduction, Clone)]
struct AgentDNA {
network: NeuralNetworkTopology<2, 1>,
}

impl Prunable for AgentDNA {}

impl GenerateRandom for AgentDNA {
fn gen_random(rng: &mut impl Rng) -> Self {
Self {
network: NeuralNetworkTopology::new(0.01, 3, rng),
}
}
}

#[test]
fn basic_test() {
let fitness = |g: &AgentDNA| {
let network = NeuralNetwork::from(&g.network);
let mut fitness = 0.;
let mut rng = rand::thread_rng();

for _ in 0..100 {
let n = rng.gen::<f32>() * 10000.;
let base = rng.gen::<f32>() * 10.;
let expected = n.log(base);

let [answer] = network.predict([n, base]);
network.flush_state();

fitness += 5. / (answer - expected).abs();
}

fitness
};

#[cfg(not(feature = "rayon"))]
let mut rng = rand::thread_rng();

let mut sim = GeneticSim::new(
#[cfg(not(feature = "rayon"))]
Vec::gen_random(&mut rng, 100),
#[cfg(feature = "rayon")]
Vec::gen_random(100),
fitness,
division_pruning_nextgen,
);

for _ in 0..100 {
sim.next_generation();
}

let mut fits: Vec<_> = sim.genomes.iter().map(fitness).collect();

fits.sort_by(|a, b| a.partial_cmp(&b).unwrap());

dbg!(fits);
}
}

0 comments on commit 66391cc

Please sign in to comment.