Skip to content

Commit

Permalink
Cargo fmt and remove the 'can solve xor' test for now
Browse files Browse the repository at this point in the history
  • Loading branch information
Ploppz committed Feb 2, 2020
1 parent 9cf2576 commit 9be47b5
Show file tree
Hide file tree
Showing 12 changed files with 146 additions and 132 deletions.
40 changes: 22 additions & 18 deletions examples/function_approximation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,34 +8,34 @@ extern crate rusty_dashed;
#[cfg(feature = "telemetry")]
mod telemetry_helper;

use rustneat::{Environment, Organism, Population, NeuralNetwork};
use rustneat::{Environment, NeuralNetwork, Organism, Population};

static mut BEST_FITNESS: f64 = 0.0;
struct FunctionApproximation;

impl Environment<NeuralNetwork> for FunctionApproximation {
fn test(&self, organism: &mut NeuralNetwork) -> f64 {
let mut output = vec![0f64];
let mut distance = 0f64;
fn test(&self, organism: &mut NeuralNetwork) -> f64 {
let mut output = vec![0f64];
let mut distance = 0f64;

let mut outputs = Vec::new();
let mut outputs = Vec::new();

for x in -10..11 {
organism.activate(vec![x as f64 / 10f64], &mut output);
distance += ((x as f64).powf(2f64) - (output[0] * 100f64)).abs();
outputs.push([x, (output[0] * 100f64) as i64]);
}
for x in -10..11 {
organism.activate(vec![x as f64 / 10f64], &mut output);
distance += ((x as f64).powf(2f64) - (output[0] * 100f64)).abs();
outputs.push([x, (output[0] * 100f64) as i64]);
}

let fitness = 100f64 / (1f64 + (distance / 1000.0));
unsafe {
let fitness = 100f64 / (1f64 + (distance / 1000.0));
unsafe {
if fitness > BEST_FITNESS {
BEST_FITNESS = fitness;
#[cfg(feature = "telemetry")]
telemetry!("approximation1", 1.0, format!("{:?}", outputs));
#[cfg(feature = "telemetry")]
telemetry!("approximation1", 1.0, format!("{:?}", outputs));
}
}
fitness
}
}
fitness
}
}

fn main() {
Expand All @@ -50,7 +50,11 @@ fn main() {
std::thread::sleep(std::time::Duration::from_millis(2000));

#[cfg(feature = "telemetry")]
telemetry!("approximation1", 1.0, format!("{:?}", (-10..11).map(|x| [x, x * x]).collect::<Vec<_>>()));
telemetry!(
"approximation1",
1.0,
format!("{:?}", (-10..11).map(|x| [x, x * x]).collect::<Vec<_>>())
);

#[cfg(feature = "telemetry")]
std::thread::sleep(std::time::Duration::from_millis(2000));
Expand Down
2 changes: 1 addition & 1 deletion examples/simple_sample.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
extern crate rand;
extern crate rustneat;

use rustneat::{Environment, Organism, Population, NeuralNetwork};
use rustneat::{Environment, NeuralNetwork, Organism, Population};

#[cfg(feature = "telemetry")]
mod telemetry_helper;
Expand Down
2 changes: 1 addition & 1 deletion examples/telemetry_helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ extern crate rusty_dashed;
use self::rusty_dashed::Dashboard;

#[allow(dead_code)]
pub fn main(){}
pub fn main() {}

#[cfg(feature = "telemetry")]
pub fn enable_telemetry(query_string: &str, open: bool) {
Expand Down
19 changes: 10 additions & 9 deletions src/genome.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
const COMPATIBILITY_THRESHOLD: f64 = 3.0; //used to speciate organisms
const COMPATIBILITY_THRESHOLD: f64 = 3.0; // used to speciate organisms

/// Implementing `Genome` conceptually means that the implementor "has a genome", and the
/// implementor can be called an "organism".
/// Implementing `Genome` conceptually means that the implementor "has a
/// genome", and the implementor can be called an "organism".
// (TODO: remove Default?)
pub trait Genome: Clone + Default + Send {
/// Returns a new organism which is a clone of `&self` apart from possible mutations
/// Returns a new organism which is a clone of `&self` apart from possible
/// mutations
fn mutate(&self) -> Self;

/// `fittest` is true if `other` is more fit.
Expand All @@ -13,16 +14,15 @@ pub trait Genome: Clone + Default + Send {
/// TODO: how should it be implemented for e.g. a composed organism?
fn distance(&self, other: &Self) -> f64;


/// Compare another Genome for species equality
// TODO This should be impl Eq
fn is_same_specie(&self, other: &Self) -> bool {
self.distance(other) < COMPATIBILITY_THRESHOLD
}
}

/// Used in algorithm just to group an organism (genome) with its fitness, and also in the
/// interface to get the fitness of organisms
/// Used in algorithm just to group an organism (genome) with its fitness, and
/// also in the interface to get the fitness of organisms
#[derive(Default, Clone, Debug)]
pub struct Organism<G> {
/// The genome of this organism
Expand All @@ -48,9 +48,10 @@ impl<G: Genome> Organism<G> {
pub fn mate(&self, other: &Self) -> Organism<G> {
Organism::new(
self.genome
.mate(&other.genome, self.fitness < other.fitness))
.mate(&other.genome, self.fitness < other.fitness),
)
}
///
///
pub fn distance(&self, other: &Self) -> f64 {
self.genome.distance(&other.genome)
}
Expand Down
21 changes: 14 additions & 7 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
#![deny(
missing_docs, trivial_casts, trivial_numeric_casts, unsafe_code, unused_import_braces,
missing_docs,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unused_import_braces,
unused_qualifications
)]
#![cfg_attr(feature = "clippy", feature(plugin))]
#![cfg_attr(feature = "clippy", plugin(clippy))]
#![cfg_attr(feature = "clippy", deny(clippy, unicode_not_nfc, wrong_pub_self_convention))]
#![cfg_attr(
feature = "clippy",
deny(clippy, unicode_not_nfc, wrong_pub_self_convention)
)]
#![cfg_attr(feature = "clippy", allow(use_debug, too_many_arguments))]

//! Implementation of `NeuroEvolution` of Augmenting Topologies [NEAT]
Expand All @@ -23,20 +30,20 @@ extern crate serde_derive;
#[cfg(feature = "telemetry")]
extern crate serde_json;

pub use self::genome::*;
pub use self::environment::Environment;
pub use self::genome::*;
pub use self::nn::{Gene, NeuralNetwork};
pub use self::population::Population;
pub use self::specie::Specie;
pub use self::species_evaluator::SpeciesEvaluator;
pub use self::nn::{NeuralNetwork, Gene};

/// Contains the definition of the genome of neural networks, which is the basic building block of
/// an organism (and in many cases, the only building block).
pub mod nn;
/// Trait to define test parameter
mod environment;
/// A collection of genes
mod genome;
/// Contains the definition of the genome of neural networks, which is the basic
/// building block of an organism (and in many cases, the only building block).
pub mod nn;
/// A collection of species with champion
mod population;
mod specie;
Expand Down
18 changes: 8 additions & 10 deletions src/nn/ctrnn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@ use rulinalg::matrix::{BaseMatrix, BaseMatrixMut, Matrix};
pub struct Ctrnn<'a> {
pub y: &'a [f64],
pub delta_t: f64,
pub tau: &'a [f64], //time constant
pub wij: &'a [f64], //weights
pub theta: &'a [f64], //bias
pub i: &'a [f64], //sensors
pub tau: &'a [f64], // time constant
pub wij: &'a [f64], // weights
pub theta: &'a [f64], // bias
pub i: &'a [f64], // sensors
}


#[allow(missing_docs)]
impl<'a> Ctrnn<'a> {
pub fn activate_nn(&self, steps: usize) -> Vec<f64> {
Expand All @@ -23,10 +22,8 @@ impl<'a> Ctrnn<'a> {
let delta_t_tau = tau.apply(&(|x| 1.0 / x)) * self.delta_t;
for _ in 0..steps {
let activations = (&y - &theta).apply(&Ctrnn::sigmoid);
y = &y + delta_t_tau.elemul(
&((&wij * activations) - &y + &i)
);
};
y = &y + delta_t_tau.elemul(&((&wij * activations) - &y + &i));
}
y.into_vec()
}

Expand Down Expand Up @@ -64,6 +61,7 @@ mod tests {
#[test]
fn neural_network_activation_stability() {
// TODO
// This test should just ensure that a stable neural network implementation doesn't change
// This test should just ensure that a stable neural network
// implementation doesn't change
}
}
14 changes: 10 additions & 4 deletions src/nn/gene.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub struct Gene {
/// Whether the expression of a gene is enabled.
pub enabled: bool,
/// Whether this gene functions as a bias in the neural network.
pub is_bias: bool
pub is_bias: bool,
}

impl Eq for Gene {}
Expand Down Expand Up @@ -49,13 +49,19 @@ impl PartialOrd for Gene {

impl Gene {
/// Create a new gene
pub fn new(in_neuron_id: usize, out_neuron_id: usize, weight: f64, enabled: bool, is_bias: bool) -> Gene {
pub fn new(
in_neuron_id: usize,
out_neuron_id: usize,
weight: f64,
enabled: bool,
is_bias: bool,
) -> Gene {
Gene {
in_neuron_id: in_neuron_id,
out_neuron_id: out_neuron_id,
weight: weight,
enabled: enabled,
is_bias: is_bias
is_bias: is_bias,
}
}
/// Generate a weight
Expand All @@ -79,7 +85,7 @@ impl Default for Gene {
out_neuron_id: 1,
weight: Gene::generate_weight(),
enabled: true,
is_bias: false
is_bias: false,
}
}
}
Expand Down
Loading

0 comments on commit 9be47b5

Please sign in to comment.