zkavtaskin / Darwin

Flexible genetic algorithm implementation in TypeScript.

Home Page:https://nathsou.github.io/Darwin/dist/SmartEaters/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Darwin

Flexible genetic algorithm implementation in TypeScript.

Installation

npm install charles.darwin

Darwin is compatible with ES6 modules

Demos

Usage

One must first choose a way of encoding the desired behavior as an array of some type (a chromosome) and of evaluating the fitness of any such chromosome.

For instance the 'Typing Monkeys' demo tries to evolve towards a target string, the fitness is simply the number of correct characters present in the randomly generated string.

On the other hand, the 'Smart Eaters' demo evolves the weights and biases of an artificial neural network, the fitness of an 'Eater' is the number of nutriments it eats in one generation (2000 ticks).

  const genetics = new Darwin<T>({
    population_size: number,
    chromosome_length: number,
    rand_gene: () => T,
    crossover_rate?: number,
    mutation_rate?: number,
    crossover_method?: CrossoverMethod | CustomCrossoverMethod<T>,
    mutation_method?: MutationMethod | CustomMutationMethod<T>,
    elite_count?: number,
    elite_copies?: number
  });

The constructor of the Darwin class initializes a population of random chromosomes, we can now assign a score (or fitness) to each of those chromosomes based on their genes represented by an array of the type returned by rand_gene :

  for (let chromo of genetics.getPopulation()) {
    chromo.setFitness(evalFitness(chromo.getGenes()));
  }

  // shorthand :
  genetics.updateFitness(genes => evalFitness(genes));

A new generation can then be generated by calling the mate() method:

  genetics.mate();

To observe the evolution of the population, one can call:

  const avg = genetics.getAverageFitness();
  const max = genetics.getFittest().getFitness();

About

Flexible genetic algorithm implementation in TypeScript.

https://nathsou.github.io/Darwin/dist/SmartEaters/


Languages

Language:JavaScript 51.4%Language:TypeScript 48.6%