Rust library for genetic algorithms

Overview

Spiril

Spiril is an implementation of a genetic algorithm for obtaining optimum variables (genetics) for a task through mutation and natural selection.

The API allows you to specify an initial group of units, which will act as the original parents of all subsequent units. Unit types implement a fitness function and a breed function for introducing new genetic combinations and mutations into subsequent generations.

Fitnesses can be calculated across a population using parallel threads.

Sudoku example

extern crate spiril;
extern crate rand;

use spiril::unit::Unit;
use spiril::population::Population;
use rand::{StdRng, SeedableRng, Rng};

struct SudokuUnit {
    sudoku: Vec<usize>, // 9x9 grid
    answer: Vec<usize>, // 9x9 grid
}

impl Unit for SudokuUnit {
    fn fitness(&self) -> f64 {
        let mut score = 1.0_f64;

        for i in 0..9 {
            let mut seen_row: [usize; 9] = [0, 0, 0, 0, 0, 0, 0, 0, 0];
            let mut seen_col: [usize; 9] = [0, 0, 0, 0, 0, 0, 0, 0, 0];
            let mut seen_sqr: [usize; 9] = [0, 0, 0, 0, 0, 0, 0, 0, 0];

            for j in 0..9 {
                seen_row[self.answer[i * 9 + j] - 1] += 1;
                seen_col[self.answer[i + 9 * j] - 1] += 1;

                let sqr_index = ((i % 3) * 3) + (((i / 3) % 3) * 27) + (9 * (j / 3)) + j % 3;
                seen_sqr[self.answer[sqr_index] - 1] += 1;
            }

            seen_row
                .iter()
                .chain(seen_col.iter())
                .chain(seen_sqr.iter())
                .map(|x| if *x == 0 {
                    // score -= (1.0 / 729.0);
                    score *= 0.9;
                })
                .last();
        }

        score
    }

    fn breed_with(&self, other: &SudokuUnit) -> SudokuUnit {
        // Even rows taken from self, odd rows taken from other.
        // Mutations applied at random.
        let mut new_unit: SudokuUnit = SudokuUnit {
            sudoku: self.sudoku.clone(),
            answer: self.answer.clone(),
        };

        (0_usize..81_usize)
            .filter(|x| self.sudoku[*x] == 0)
            .map(|x| {
                if rand::thread_rng().gen_range(0, 1) == 1 {
                    new_unit.answer[x] = other.answer[x];
                }
                new_unit.answer[x]
            })
            .last();

        loop {
            let i = rand::thread_rng().gen_range(0, 81);
            if self.sudoku[i] == 0 {
                new_unit.answer[i] = rand::thread_rng().gen_range(1, 10);
                break;
            }
        }

        new_unit
    }
}

fn main() {
    let test_doku: Vec<usize> = vec![
        7, 2, 6,   0, 9, 3,   8, 1, 5,
        3, 0, 5,   7, 2, 8,   9, 0, 6,
        4, 8, 0,   6, 0, 1,   2, 3, 7,

        8, 5, 2,   1, 4, 0,   6, 9, 3,
        0, 7, 3,   9, 8, 5,   1, 2, 4,
        9, 4, 1,   0, 6, 2,   0, 5, 8,

        1, 9, 0,   8, 3, 0,   5, 7, 2,
        5, 6, 7,   2, 1, 4,   3, 8, 0,
        2, 0, 8,   5, 0, 9,   4, 6, 1,
    ];

    let seed: &[_] = &[0];
    let mut init_rng: StdRng = SeedableRng::from_seed(seed);
    let units: Vec<SudokuUnit> = (0..1000)
        .map(|_| {
            SudokuUnit {
                sudoku: test_doku.clone(),
                answer: test_doku
                    .clone()
                    .iter()
                    .map(|x| if *x == 0 {
                        init_rng.gen_range(1, 10)
                    } else {
                        *x
                    })
                    .collect(),
            }
        })
        .collect();

    assert_eq!(Population::new(units)
        .set_size(1000)
        .set_breed_factor(0.3)
        .set_survival_factor(0.5)
        .epochs_parallel(5000, 4) // 4 CPU cores
        .finish()
        .first()
        .unwrap()
        .fitness(), 1.0);
}
You might also like...
Rust library for Self Organising Maps (SOM).
Rust library for Self Organising Maps (SOM).

RusticSOM Rust library for Self Organising Maps (SOM). Using this Crate Add rusticsom as a dependency in Cargo.toml [dependencies] rusticsom = "1.1.0"

Rust numeric library with R, MATLAB & Python syntax

Peroxide Rust numeric library contains linear algebra, numerical analysis, statistics and machine learning tools with R, MATLAB, Python like macros. W

A deep learning library for rust

Alumina An experimental deep learning library written in pure rust. Breakage expected on each release in the short term. See mnist.rs in examples or R

Machine Learning Library for Rust

autograph Machine Learning Library for Rust undergoing maintenance Features Portable accelerated compute Run SPIR-V shaders on GPU's that support Vulk

Simple neural network library for classification written in Rust.

Cogent A note I continue working on GPU stuff, I've made some interesting things there, but ultimately it made me realise this is far too monumental a

Rust wrapper for the Fast Artificial Neural Network library

fann-rs Rust wrapper for the Fast Artificial Neural Network (FANN) library. This crate provides a safe interface to FANN on top of the low-level bindi

RustFFT is a high-performance FFT library written in pure Rust.

RustFFT is a high-performance FFT library written in pure Rust. It can compute FFTs of any size, including prime-number sizes, in O(nlogn) time.

Rust crate to create Anki decks. Based on the python library genanki

genanki-rs: A Rust Crate for Generating Anki Decks With genanki-rs you can easily generate decks for the popular open source flashcard platform Anki.

Generic Automatic Differentiation library for Rust (aka "autograd")

GAD: Generic Automatic Differentiation for Rust This project aims to provide a general and extensible framework for tape-based automatic differentiati

Owner
Ashley Jeffs
If you want to get in touch please find me in person I'm not good with computers.
Ashley Jeffs
NEATeRS is a library for training a genetic neural net through reinforcement learning.

NEATeRS NEATeRS is a library for training a genetic neural net through reinforcement learning. It uses the NEAT algorithm developed by Ken Stanley whi

TecTrixer 3 Nov 28, 2022
Execute genetic algorithm (GA) simulations in a customizable and extensible way.

genevo genevo provides building blocks to run simulations of optimization and search problems using genetic algorithms (GA). The vision for genevo is

Innoave 110 Dec 21, 2022
darwin-rs, evolutionary algorithms with rust

darwin-rs This library allows you to write evolutionary algorithms (EA) using the Rust programming language. Written by Willi Kappler, License: MIT -

Willi Kappler 95 Jan 1, 2023
🧮 alphatensor matrix breakthrough algorithms + simd + rust.

simd-alphatensor-rs tldr; alphatensor matrix breakthrough algorithims + simd + rust. This repo contains the cutting edge matrix multiplication algorit

drbh 50 Feb 11, 2023
DBSCAN and OPTICS clustering algorithms.

petal-clustering A collection of clustering algorithms. Currently this crate provides DBSCAN and OPTICS. Examples The following example shows how to c

Petabi 15 Dec 15, 2022
Nearest neighbor search algorithms including a ball tree and a vantage point tree.

petal-neighbors Nearest neighbor search algorithms including a ball tree and a vantage point tree. Examples The following example shows how to find tw

Petabi 6 Oct 19, 2022
A suite of benchmarks to test e-graph extraction algorithms

Extraction Gym A suite of benchmarks to test e-graph extraction algorithms. Add your algorithm in src/extract and then add a line in src/main.rs. To r

null 7 Jul 1, 2023
Msgpack serialization/deserialization library for Python, written in Rust using PyO3, and rust-msgpack. Reboot of orjson. msgpack.org[Python]

ormsgpack ormsgpack is a fast msgpack library for Python. It is a fork/reboot of orjson It serializes faster than msgpack-python and deserializes a bi

Aviram Hassan 139 Dec 30, 2022
A Rust library with homemade machine learning models to classify the MNIST dataset. Built in an attempt to get familiar with advanced Rust concepts.

mnist-classifier Ideas UPDATED: Finish CLI Flags Parallelize conputationally intensive functions Class-based naive bayes README Image parsing Confusio

Neil Kaushikkar 0 Sep 2, 2021
Machine Learning library for Rust

rusty-machine This library is no longer actively maintained. The crate is currently on version 0.5.4. Read the API Documentation to learn more. And he

James Lucas 1.2k Dec 31, 2022