Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add serde derives #48

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ ctrlc = { version = "3.1.4", optional = true }
[features]
default = []
telemetry = ["rusty_dashed", "open", "serde", "serde_derive", "serde_json"]
with_serde = ["serde", "serde_derive"]
openai = ["cpython", "python3-sys", "ctrlc"]
ctrnn_telemetry = []

Expand All @@ -41,8 +42,15 @@ required-features = ["cpython"]
[[example]]
name = "simple_sample"

[[example]]
name = "serde_sample"

[[example]]
name = "function_approximation"

[[example]]
name = "ctrnn"

[dev-dependencies]
ctrlc = "3.1.4"
serde_json = "1.0"
106 changes: 106 additions & 0 deletions examples/serde_sample.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
extern crate rand;
extern crate rustneat;

use std::fs::File;
use std::io::{BufReader, BufWriter};
use std::sync::{Arc, Mutex};

use rustneat::Environment;
use rustneat::Organism;
use rustneat::Population;

#[cfg(feature = "telemetry")]
mod telemetry_helper;

struct XORClassification;

impl Environment for XORClassification {
fn test(&self, organism: &mut Organism) -> f64 {
let mut output = vec![0f64];
let mut distance: f64;
organism.activate(vec![0f64, 0f64], &mut output);
distance = (0f64 - output[0]).powi(2);
organism.activate(vec![0f64, 1f64], &mut output);
distance += (1f64 - output[0]).powi(2);
organism.activate(vec![1f64, 0f64], &mut output);
distance += (1f64 - output[0]).powi(2);
organism.activate(vec![1f64, 1f64], &mut output);
distance += (0f64 - output[0]).powi(2);

let fitness = 16f64 / (1f64 + distance);

fitness
}
}

const POPULATION_PATH: &str = "population.json";

fn main() {
let lock = Arc::new(Mutex::new(()));
{
let lock = Arc::clone(&lock);
ctrlc::set_handler(move || {
let _guard = lock.lock().unwrap();
std::process::exit(0);
})
.unwrap();
}

#[cfg(feature = "telemetry")]
telemetry_helper::enable_telemetry("?max_fitness=18", true);

#[cfg(feature = "telemetry")]
std::thread::sleep(std::time::Duration::from_millis(2000));

let mut population = match File::open(POPULATION_PATH) {
Ok(file) => match serde_json::from_reader(BufReader::new(file)) {
Ok(population) => {
println!("Loaded population from {}", POPULATION_PATH);
population
}
Err(err) => {
eprintln!("Error parsing {}: {}", POPULATION_PATH, err);
return;
}
},
Err(err) => {
if err.kind() == std::io::ErrorKind::NotFound {
Population::create_population(150)
} else {
eprintln!("Error reading {}: {}", POPULATION_PATH, err);
return;
}
}
};

let mut environment = XORClassification;
let mut champion: Option<Organism> = None;
while champion.is_none() {
population.evolve();
population.evaluate_in(&mut environment);
{
let _guard = lock.lock().unwrap();
match File::create(POPULATION_PATH) {
Ok(file) => {
if let Err(err) = serde_json::to_writer(BufWriter::new(file), &population) {
eprintln!("Error serializing to {}: {}", POPULATION_PATH, err);
return;
}
}
Err(err) => {
eprintln!("Error writing to {}: {}", POPULATION_PATH, err);
return;
}
}
}
for organism in &population.get_organisms() {
if organism.fitness > 15.5f64 {
champion = Some(organism.clone());
}
}
}
println!(
"{}",
serde_json::to_string_pretty(&champion.unwrap()).unwrap()
);
}
3 changes: 2 additions & 1 deletion src/gene.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ use std::cmp::Ordering;

/// A connection Gene
#[derive(Debug, Copy, Clone)]
#[cfg_attr(feature = "telemetry", derive(Serialize))]
#[cfg_attr(any(feature = "telemetry", feature = "with_serde"), derive(Serialize))]
#[cfg_attr(feature = "with_serde", derive(Deserialize))]
pub struct Gene {
in_neuron_id: usize,
out_neuron_id: usize,
Expand Down
1 change: 1 addition & 0 deletions src/genome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::cmp;
/// Vector of Genes
/// Holds a count of last neuron added, similar to Innovation number
#[derive(Default, Debug, Clone)]
#[cfg_attr(feature = "with_serde", derive(Serialize, Deserialize))]
pub struct Genome {
genes: Vec<Gene>,
last_neuron_id: usize,
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ extern crate num_cpus;
extern crate rand;
extern crate rulinalg;

#[cfg(feature = "telemetry")]
#[cfg(any(feature = "telemetry", feature = "with_serde"))]
#[macro_use]
extern crate serde_derive;

Expand Down
1 change: 1 addition & 0 deletions src/organism.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::cmp;
/// Also maitain a fitenss measure of the organism
#[allow(missing_docs)]
#[derive(Debug, Clone)]
#[cfg_attr(feature = "with_serde", derive(Serialize, Deserialize))]
pub struct Organism {
pub genome: Genome,
pub fitness: f64,
Expand Down
1 change: 1 addition & 0 deletions src/population.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use species_evaluator::SpeciesEvaluator;

/// All species in the network
#[derive(Debug)]
#[cfg_attr(feature = "with_serde", derive(Serialize, Deserialize))]
pub struct Population {
/// container of species
pub species: Vec<Specie>,
Expand Down
1 change: 1 addition & 0 deletions src/specie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use rand::Rng;

/// A species (several organisms) and associated fitnesses
#[derive(Debug, Clone)]
#[cfg_attr(feature = "with_serde", derive(Serialize, Deserialize))]
pub struct Specie {
representative: Genome,
average_fitness: f64,
Expand Down