Core Methods

run

Runs a genetic algorithm with the provided settings. Processing for each generation will be placed at the end of the event loop queue, allowing execution to be shared even if none of the algorithm's component operations are asynchronous.

run(settings: Object): Promise<Object>
Parameters
settings (Object) Algorithm settings object.
Name Description
settings.chromosomeClass Function? Chromosome class constructor. Must implement the ::create method.
settings.createChromosome Function? Alternative to chromosomeClass . A simple factory function which should return a chromosome object with each invocation.
settings.createArg any? Argument for the ::create method or createChromosome function.
settings.createArgs Array? Alternative to createArg which allows for multiple arguments.
settings.selector String (default 'tournament') Selection method. Uses the selector class registered for the provided key.
settings.selectorClass Function? Alternative to selector . Allows the selector class constructor to be provided directly.
settings.selectorSettings Object (default {}) Settings object which will be provided to selector class instances. See the documentation for the selector class you're using for more information.
settings.generationSize number Number of individuals per generation.
settings.generationLimit number (default Infinity) Maximum number of generations. If not set, the algorithm will continue until at least one individual's fitness meets or exceeds solutionFitness .
settings.solutionFitness (number | false) (default Infinity) When an individual's fitness meets or exceeds this number, it will be considered a solution, causing the algorithm to stop. To disable this behavior, set this to false.
settings.crossoverRate number (default 0) Fraction of individuals in each generation that should be produced through crossover operations, on average. If set, chromosome objects must implement the #crossover method.
settings.manualCrossoverCheck boolean (default false) Set to true to forgo gene-lib's crossover rate checks, allowing you to handle them manually in the #crossover method. This is similar to setting the crossoverRate to 1, though it allows the #crossover method to still receive a crossoverRate that isn't necessarily 1 as an argument.
settings.parentCount number (default 2) The number of parents to be selected for each crossover operation. It must be at least two. Any parents beyond the first two will appear as additional arguments to the #crossover method, before the final rate argument.
settings.childCount number (default 2) The number of children to be produced by each crossover operation. Your #crossover method must always return an array of children with length equal to this number. If you set it to 1, you may instead return a single child without needing to wrap it in an array.
settings.mutationRate number (default 0) Fractional rate of mutation. If set, your chromosome objects must implement the #mutate method. Unlike crossover, mutation rate-checking can only be handled manually in the #mutate method itself. This setting will simply be provided as an argument to that method.
settings.onGeneration Function? Will be invoked at the end of each generation. Receives an object argument detailing the current state of the algorithm, in the same format as the end result object.
settings.async Object? Used to specify asynchronous operations.
settings.async.create number? Maximum number of simultaneous chromosome creation operations. If set, your ::create method or createChromosome function must return a Promise.
settings.async.getFitness number? Maximum number of simultaneous fitness calculation operations. If set, your chromosome's #getFitness method must return a Promise.
settings.async.add number? Maximum number of simultaneous add-to-selector operations. If set, your selector's '#add' method must return a Promise.
settings.async.select number? Maximum number of simultaneous selection operations. If set, your selector's '#select' operation must return a Promise.
settings.async.crossover number? Maximum number of simultaneous crossover operations. If set, your chromosome's #crossover method must return a Promise.
settings.async.mutate number? Maximum number of simultaneous mutation operations. If set, your chromosome's #mutate method must return a Promise.
Returns
Promise<Object>: Will resolve with the an object containing the final state of the algorithm, with 'generationCount', 'best', and 'individuals' properties.

runSync

Runs a genetic algorithm with the provided settings, forcing all operations to take place in a single event loop. Use of this method is not recommended as part of an application that responds to requests, as it blocks execution completely until finished, preventing any other requests from being handled.

runSync(settings: Object): Object
Parameters
settings (Object) Algorithm settings object. These are the same as for ::run , except that settings.async is not supported and will cause this method to throw, if present.
Returns
Object: Contains the final state of the algorithm, with 'generationCount', 'best', and 'individuals' properties.

registerSelector

Registers a new class for use with the settings.selector ::run argument.

registerSelector(key: String, selectorClass: Function): undefined
Parameters
key (String) Selector setting value. Must not already be registered.
selectorClass (Function) Selector class constructor.
Returns
undefined:

Classes

Chromosome

Base class for chromosomes. It is not necessary for your chromosome objects to inherit from this class. They must, however, implement its instance methods.

new Chromosome()
Properties
async (Object?) : Set to specify asynchronous operations. Chromosome classes with this property set cannot be used with the ::runSync method.
  • async.getFitness (number | boolean)?

    Maximum concurrency of asynchronous #getFitness operations. true is interpeted as 1. If set, #getFitness must return a promise. Otherwise, it must return a number as normal.

  • async.crossover (number | boolean)?

    Maximum concurrency of asynchronous #crossover operations. true is interpeted as 1. If set, #crossover must return a promise. Otherwise, it must return a single child or array of children as normal.

  • async.mutate number?

    Maximum concurrency of asynchronous #mutate operations. true is interpeted as 1. If set, #mutate must return a promise. Otherwise, it must return a single mutant chromosome as normal.

Static Members
isChromosome(obj)
create(args)
Instance Members
getFitness()
crossover(others, rate)
mutate(rate)

CachingChromosome

Another base class for chromosomes which caches the results of fitness calculations internally. Use this class if you need to call #getFitness in the other chromsome methods. See the Chromsome class for more information.

new CachingChromosome()

Extends Chromosome

Instance Members
calculateFitness()
getFitness()

Selector

Base Selector class. Extend this to implement a custom selection method.

new Selector(settings: Object)
Parameters
settings (Object = {}) Selector configuration object. Will be passed from the ::run or '::runSync' method's settings.selectorSettings argument, if any.
Properties
defaults (Object?) : Set to provide default values for the selector settings object.
async (Object?) : Set to specify asynchronous operations. Selector classes with this property set cannot be used with the ::runSync method.
  • async.add (number | boolean)?

    Maximum concurrency of asynchronous #add operations. true is interpeted as 1. If set, #add must return a promise to signify when the operation is complete.

  • async.select (number | boolean)?

    Maximum concurrency of asynchronous #select operations. true is interpeted as 1. If set, #select must return a promise. Otherwise, it must return a single individual as normal.

Static Members
validateSettings(settings)
Instance Members
add(individual)
select()

ArraySelector

Base class for selectors that store individuals in an array, which will be available at this.individuals. See the Selector class for more information.

new ArraySelector(settings: Object)

Extends Selector

Parameters
settings (Object = {}) Selector configuration object. Will be passed from the ::run method's settings.selectorSettings argument, if any.
Instance Members
add(individual)

TournamentSelector

Selector class for tournament selection.

new TournamentSelector(settings: Object)

Extends ArraySelector

Parameters
settings (Object = {}) Selector configuration object.
Name Description
settings.tournamentSize Number? Number of individuals (k) to be selected at random from the population for each tournament.
settings.baseWeight Number? Probability (p) of selecting the most fit individual from a tournament. Lower-fitness individuals will be selected with probabilities equal to p*((1-p))^n, where n is the number of ranks below first. To avoid unexpected behavior, this number should never be lower than 0.5.
Static Members
getWeights(base, count)
Instance Members
getTournament()
getSortedTournament()
selectDeterministic()
selectWeighted()
select()

RouletteSelector

Selector class for fitness-proportional (roulette) selection.

new RouletteSelector(settings: Object)

Extends ArraySelector

Parameters
settings (Object = {}) Selector configuration object. Will be passed from the ::run method's settings.selectorSettings argument, if any.
Instance Members
add(individual)
spin()
select()

Utility Methods

getRandomIndex

Gets a random chromosome index between zero and length.

getRandomIndex(length: number): number
Parameters
length (number) Length of the chromosome.
Returns
number: A random integer in [0, length]

getRandomRange

Gets two random chromosome indices, a start and an end.

getRandomRange(length: number): Array<number>
Parameters
length (number) Length of the chromosome.
Returns
Array<number>: Contains two random integers in [0, length] . For convenience, the lesser of the two will always be the first.

getRandomIndices

Gets an array of random chromosome indices.

getRandomIndices(length: number, pick: boolean, ratio: number): Arrray<number>
Parameters
length (number) Length of the chromosome.
pick (boolean = false) Set to true to pick a set number of possible indices based on the provided ratio.
ratio (number = 0.5) Probability of an individual index being selected, or ratio of possible indices that will be selected (rounded down).
Returns
Arrray<number>: Contains a random set of integers in [0, length] .

singlePointCrossover

Performs a single-point crossover between two arrays or strings.

singlePointCrossover(left: (Array | String), right: (Array | String)): Array<(Array | String)>
Parameters
left ((Array | String)) Left parent.
right ((Array | String)) Right parent.
Returns
Array<(Array | String)>: Will contain two children, of the same type as left .

twoPointCrossover

Performs a two-point crossover between two arrays or strings.

twoPointCrossover(left: (Array | String), right: (Array | String)): Array<(Array | String)>
Parameters
left ((Array | String)) Left parent.
right ((Array | String)) Right parent.
Returns
Array<(Array | String)>: Will contain two children, of the same type as left .

uniformCrossover

Performs a uniform crossover between two arrays or strings.

uniformCrossover(left: (Array | String), right: (Array | String), pick: boolean, ratio: number): Array<(Array | String)>
Parameters
left ((Array | String)) Left parent.
right ((Array | String)) Right parent.
pick (boolean = false) Set to true to pick a set number of possible crossover indices based on the provided ratio.
ratio (number = 0.5) Probability of an individual index being selected for crossover, or ratio of possible indices that will be selected (rounded down).
Returns
Array<(Array | String)>: Will contain two children, of the same type as left .

pmx

Performs a partially-matched crossover between two arrays or strings. Note that '===' is used for equality comparisons in this operation, so if your parent arrays contain objects, make sure they're references to the same objects.

pmx(left: (Array | String), right: (Array | String)): Arrray<(Array | String)>
Parameters
left ((Array | String)) Left parent.
right ((Array | String)) Right parent.
Returns
Arrray<(Array | String)>: Will contain two children, of the same type as left .