Skip to main content

Crate neat

Crate neat 

Source
Expand description

§neat

github crates.io docs.rs

Implementation of the NEAT algorithm using genetic-rs.

§Features

  • serde - Implements Serialize and Deserialize on most of the types in this crate.

Do you like this crate and want to support it? If so, leave a ⭐

§How To Use

The NeuralNetwork<I, O> struct is the main type exported by this crate. The I is the number of input neurons, and O is the number of output neurons. It implements GenerateRandom, RandomlyMutable, Mitosis, and Crossover, with a lot of customizability. This means that you can use it standalone as your organism’s entire genome:

use neat::*;

fn fitness(net: &NeuralNetwork<5, 6>) -> f32 {
    // ideally you'd test multiple times for consistency,
    // but this is just a simple example.
    // it's also generally good practice to normalize your inputs between -1..1,
    // but NEAT is usually flexible enough to still work anyways
    let inputs = [1.0, 2.0, 3.0, 4.0, 5.0];
    let outputs = net.predict(inputs);

    // simple fitness: sum of outputs
    // you should replace this with a real fitness test
    outputs.iter().sum()
}

fn main() {
    let mut rng = rand::rng();
    let mut sim = GeneticSim::new(
        Vec::gen_random(&mut rng, 100),
        FitnessEliminator::new_without_observer(fitness),
        CrossoverRepopulator::new(0.25, ReproductionSettings::default()),
    );

    sim.perform_generations(100);
}

Or just a part of a more complex genome:

use neat::*;

#[derive(Clone, Debug)]
struct PhysicalStats {
    strength: f32,
    speed: f32,
    // ...
}

// ... implement `RandomlyMutable`, `GenerateRandom`, `Crossover`, `Default`, etc.

#[derive(Clone, Debug, GenerateRandom, RandomlyMutable, Mitosis, Crossover)]
#[randmut(create_context(name = MyGenomeMutate, derive(Default, Clone, Debug)))]
#[mitosis(create_context(name = MyGenomeReproduce, derive(Default, Clone, Debug)))]
#[crossover(with_context = MyGenomeReproduce)]
struct MyGenome {
    brain: NeuralNetwork<4, 2>,
    stats: PhysicalStats,
}

fn fitness(genome: &MyGenome) -> f32 {
    let inputs = [1.0, 2.0, 3.0, 4.0];
    let outputs = genome.brain.predict(inputs);
    // fitness uses both brain output and stats
    outputs.iter().sum::<f32>() + genome.stats.strength + genome.stats.speed
}

// main is the exact same as before
fn main() {
    let mut rng = rand::rng();
    let mut sim = GeneticSim::new(
        Vec::gen_random(&mut rng, 100),
        FitnessEliminator::new_without_observer(fitness),
        CrossoverRepopulator::new(0.25, MyGenomeReproduce::default()),
    );

    sim.perform_generations(100);
}

If you want more in-depth examples, look at the examples. You can also check out the genetic-rs docs to see what other options you have to customize your genetic simulation.

§License

This crate falls under the MIT license

Re-exports§

pub use genetic_rs;
pub use neuralnet::*;

Modules§

activation
Contains the types surrounding activation functions.
genetic_rs_common
The crate containing the core traits and structs of genetic-rs.
neuralnet
Contains the NeuralNetwork and related types.

Macros§

activation_fn
Creates an ActivationFn object from a function

Structs§

CrossoverRepopulator
Repopulator that uses crossover reproduction to create new genomes.
FitnessEliminator
A fitness-based eliminator that eliminates genomes based on their fitness scores.
FitnessEliminatorBuilder
A builder for FitnessEliminator to make it easier to construct with default parameters.
FitnessKnockoutFn
A knockout function that uses a fitness function to determine the winner.
GeneticSim
This struct is the main entry point for the simulation. It handles the state and evolution of the genomes based on what eliminator and repopulator it receives.
KnockoutEliminator
Eliminator that pits genomes against each other and eliminates the weaker ones.
LayeredObserver
An observer that calls two observers in sequence. Created by FitnessObserver::layer.
MitosisRepopulator
Repopulator that uses division reproduction to create new genomes.
SmallRng
A small-state, fast, non-crypto, non-portable PRNG
SpeciatedCrossoverRepopulator
Repopulator that uses crossover reproduction to create new genomes, but only between genomes of the same species.
StdRng
A strong, fast (amortized), non-portable RNG
ThreadRng
A reference to the thread-local generator

Enums§

ActionIfOdd
The action a knockout eliminator should take if the number of genomes is odd.
KnockoutWinner
A distinct type to help clarify the result of a knockout function.

Traits§

Crossover
Used in crossover-reproducing Repopulators
CryptoRng
A marker trait for securely unpredictable infallible RNGs
Distribution
Types (distributions) that can be used to create a random instance of T.
Eliminator
Tests and eliminates the unfit from the simulation.
FitnessFn
A trait for fitness functions. This allows for more flexibility in defining fitness functions. Any Fn(&G) -> f32 can be used as a fitness function.
FitnessObserver
A trait for observing fitness scores. This can be used to implement things like logging or statistics collection.
GenerateRandom
Helper trait used in the generation of random starting populations
GenerateRandomCollection
Blanket trait used on collections that contain objects implementing GenerateRandom
GenerateRandomCollectionParallel
Rayon version of the GenerateRandomCollection trait
IndexedMutRandom
Extension trait on indexable lists, providing random sampling methods.
IndexedRandom
Extension trait on indexable lists, providing random sampling methods.
IteratorRandom
Extension trait on iterators, providing random sampling methods.
KnockoutFn
A function that pits two genomes against each other and determines a winner.
MaxIndex
A trait for getting the index of the maximum element.
Mitosis
Used in dividually-reproducing Repopulators
RandomlyMutable
Used in other traits to randomly mutate genomes a given amount
Repopulator
Refills the population of the simulation based on survivors.
Rng
Trait for infallible random number generators
RngExt
User-level interface for RNGs
SeedableRng
A random number generator that can be explicitly seeded.
SliceRandom
Extension trait on slices, providing shuffling methods.
Speciated
Used in speciated crossover nextgens. Allows for genomes to avoid crossover with ones that are too different.