2 releases

new 0.1.1 Apr 27, 2025
0.1.0 Apr 23, 2025

#346 in Compression

Download history 113/week @ 2025-04-20

114 downloads per month

Apache-2.0

37KB
380 lines

rs-genetics

Latest version License

rs-genetics is a genetic algorithm library written entirely in Rust.

Get started

  • define a fitness function which inputs a Population and outputs an f64 (F:Fn(Population)->f64)
    fn fitness(weights: Population) -> f64 {
        let inputs = vec![4.0, -2.0, 3.5, 5.0, -11.0, -4.7];
        let target = 44.0;
        match weights {
            Population::F64(vec) => {
                let distance: f64 = inputs.iter()
                    .zip(&vec[0])
                    .map(|(x, y)| x * y)
                    .sum();
                let result = 1.0 / ((target - distance).abs()+0.000000001);
                result
            }
            _ => panic!("Expected Population::F64"),
        }
    }
  • choose an InitializationStrategy
  • use the default configuration or change it
    let init_strategy = InitializationStrategy::F64(Box::new(RandomInitialization));
    let mut config = Config::default();
        config.num_individuals = 1000;
  • define your Genetic Algorithm and evolve it
  let mut ga = GA::new(init_strategy,fitness, config)
  let hist = ga.evolve(100);
  • print the solution
    let hist = ga.evolve(100);
    let inputs = vec![4.0, -2.0, 3.5, 5.0, -11.0, -4.7];
    let distance: f64 = inputs.iter()
        .zip(&ga.population.get_individual(0).unwrap())
        .map(|(x, y)| x * y)
        .sum();
    println!("Solution = {}",distance);
  • plot the fitness curve
    draw_fitness(hist, "fitness_curve.png");

Dependencies

~5.5–7.5MB
~132K SLoC