Genetic
NAME
Algorithm::Genetic - A basic genetic algorithm implementation for Perl6!
Use the Algorithm::Genetic distribution to implement your own evolutionary searches.
This library was written primarily for learning so there likely are some rough edges. Feel to report any issues and contributions are welcome!
SYNOPSIS
use Algorithm::Genetic;
use Algorithm::Genetic::Genotype;
use Algorithm::Genetic::Selection::Roulette;
my $target = 42;
# First implement the is-finished method for our specific application.
# Note that we compose in our selection behaviour of the Roulette role.
class FindMeaning does Algorithm::Genetic does Algorithm::Genetic::Selection::Roulette {
has int $.target;
method is-finished() returns Bool {
#say "Gen{ self.generation } - pop. size: { @!population.elems }";
self.population.tail[0].result == $!target;
}
}
# Create our Genotype
class Equation does Algorithm::Genetic::Genotype {
our $eq-target = $target;
our @options = 1, 9;
# Note that we use the custom is mutable trait to provide a routine to mutate our attribute.
has Int $.a is mutable( -> $v { (-1, 1).pick + $v } ) = @options.pick;
has Int $.b is mutable( -> $v { (-1, 1).pick + $v } ) = @options.pick;
method result() { $!a * $!b }
# A scoring method is required for our genotype :)
method !calc-score() returns Numeric {
(self.result() - $eq-target) ** 2
}
}
# Instantiate our search
my FindMeaning $ga .= new(
:genotype(Equation.new)
:mutation-probability(4/5)
:$target
);
# Go!
$ga.evolve(:generations(1000), :size(16));
say "stopped at generation { $ga.generation } with result: { .a } x { .b } = { .result } and a score of { .score }" given $ga.population.tail[0];
DESCRIPTION
Algorithm::Genetic distribution currently provides the following classes:
Algorithm::Genetic
Algorithm::Genetic::Crossoverable
Algorithm::Genetic::Genotype
Algorithm::Genetic::Selection
Algorithm::Genetic::Selection::Roulette
AUTHOR
Sam Gillespie <[email protected]>
COPYRIGHT AND LICENSE
Copyright 2016 Sam Gillespie
This library is free software; you can redistribute it and/or modify it under the Artistic License 2.0.
Reference
NAME
Algorithm::Genetic - A role for genetic algorithms.
unit role Algorithm::Genetic does Algorithm::Genetic::Selection
METHODS
method new(
Int:D :$population-size = 100,
Rat:D :$crossover-probability = 7/10,
Rat:D :$mutation-probability = 1/100,
Algorithm::Genetic::Genotype :$genotype is required
)
Probability values are expected to be between 0 and 1.