AI-Genetic

 view release on metacpan or  search on metacpan

Genetic.pm  view on Meta::CPAN

# -crossover:  set the crossover probability
# -mutation:   set the mutation probability
# -fitness:    set the fitness function
# -type:       set the genome type. See docs.
# -terminate:  set termination sub.

sub new {
  my ($class, %args) = @_;

  my $self = bless {
		    ADDSEL => {},   # user-defined selections
		    ADDCRS => {},   # user-defined crossovers
		    ADDMUT => {},   # user-defined mutations
		    ADDSTR => {},   # user-defined strategies
		   } => $class;

  $self->{FITFUNC}    = $args{-fitness}    || sub { 1 };
  $self->{CROSSRATE}  = $args{-crossover}  || 0.95;
  $self->{MUTPROB}    = $args{-mutation}   || 0.05;
  $self->{POPSIZE}    = $args{-population} || 100;
  $self->{TYPE}       = $args{-type}       || 'bitvector';

Genetic.pm  view on Meta::CPAN

=item B<1. Selection>

Here the performance of all the individuals is evaluated
based on the fitness function, and each is given a specific
fitness value. The higher the value, the bigger the chance
of an individual passing its genes on in future generations
through mating (crossover).

=item B<2. Crossover>

Here, individuals selected are randomly paired up for
crossover (aka I<sexual reproduction>). This is further
controlled by the crossover rate specified and may result in
a new offspring individual that contains genes common to
both parents. New individuals are injected into the current
population.

=item B<3. Mutation>

In this step, each individual is given the chance to mutate
based on the mutation probability specified. If an individual

Genetic.pm  view on Meta::CPAN

has to be chosen for crossover.

=head1 STRATEGIES

AI::Genetic comes with 9 predefined strategies. These are:

=over

=item rouletteSinglePoint

This strategy implements roulette-wheel selection and single-point crossover.

=item rouletteTwoPoint

This strategy implements roulette-wheel selection and two-point crossover.

=item rouletteUniform

This strategy implements roulette-wheel selection and uniform crossover.

=item tournamentSinglePoint

This strategy implements tournament selection and single-point crossover.

=item tournamentTwoPoint

This strategy implements tournament selection and two-point crossover.

=item tournamentUniform

This strategy implements tournament selection and uniform crossover.

=item randomSinglePoint

This strategy implements random selection and single-point crossover.

=item randomTwoPoint

This strategy implements random selection and two-point crossover.

=item randomUniform

This strategy implements random selection and uniform crossover.

=back

More detail on these strategies and how to call them in your own
custom strategies can be found in L<AI::Genetic::OpSelection>,
L<AI::Genetic::OpCrossover> and L<AI::Genetic::OpMutation>.

You can use the functions defined in the above modules in your
own custom-made strategy. Consult their manpages for more info.
A custom-made strategy can be defined using the I<strategy()>

Genetic/OpCrossover.pm  view on Meta::CPAN

  AI::Genetic::OpCrossover::MethodName(arguments)

=head1 CROSSOVER OPERATORS AND THEIR METHODS

The following crossover operators are defined:

=over

=item Single Point

In single point crossover, a point is selected along the choromosomes of both parents.
The chromosomes are then split at that point, and the head of one parent chromosome is
joined with the tail of the other and vice versa, creating two child chromosomes.
The following method is defined:

=over

=item B<vectorSinglePoint>(I<Xprob, parent1, parent2>)

The first argument is the crossover rate. The second and third arguments are anonymous
lists that define the B<genes>
of the parents (not AI::Genetic::Individual objects, but the return value of the I<genes()>
method in scalar context).
If mating occurs, two anonymous lists of genes are returned corresponding to the two
new children. If no mating occurs, 0 is returned.

=back

=item Two Point

In two point crossover, two points are selected along the choromosomes of both parents.
The chromosomes are then cut at those points, and the middle parts are swapped,
creating two child chromosomes. The following method is defined:

=over

=item B<vectorTwoPoint>(I<Xprob, parent1, parent2>)

The first argument is the crossover rate. The second and third arguments are anonymous
lists that define the B<genes>
of the parents (not AI::Genetic::Individual objects, but the return value of the I<genes()>
method in scalar context).
If mating occurs, two anonymous lists of genes are returned corresponding to the two
new children. If no mating occurs, 0 is returned.

=back

=item Uniform

In uniform crossover, two child chromosomes are created by looking at each gene in both
parents, and randomly selecting which one to go with each child.
The following method is defined:

=over

=item B<vectorUniform>(I<Xprob, parent1, parent2>)

The first argument is the crossover rate. The second and third arguments are anonymous
lists that define the B<genes>
of the parents (not AI::Genetic::Individual objects, but the return value of the I<genes()>
method in scalar context).

Genetic/OpSelection.pm  view on Meta::CPAN

# must be called whenever the population changes.
# only useful for roulette().

sub initWheel {
  my $pop = shift;

  my $tot = 0;
  $tot += $_->score for @$pop;

  # if all population has zero score, then none
  # deserves to be selected.
  $tot = 1 unless $tot;    # to avoid div by zero

  # normalize
  my @norms = map {$_->score / $tot} @$pop;

  @wheel = ();

  my $cur = 0;
  for my $i (@norms) {
    push @wheel => [$cur, $cur + $i];
    $cur += $i;
  }

  $wheelPop = $pop;
}

# sub roulette():
# Roulette Wheel selection.
# argument is number of individuals to select (def = 2).
# returns selected individuals.

sub roulette {
  my $num = shift || 2;

  my @selected;

  for my $j (1 .. $num) {
    my $rand = rand;
    for my $i (0 .. $#wheel) {
      if ($wheel[$i][0] <= $rand && $rand < $wheel[$i][1]) {
	push @selected => $wheelPop->[$i];
	last;
      }
    }
  }

  return @selected;
}

# same as roulette(), but returns unique individuals.
sub rouletteUnique {
  my $num = shift || 2;

  # make sure we select unique individuals.
  my %selected;

  while ($num > keys %selected) {
    my $rand = rand;

    for my $i (0 .. $#wheel) {
      if ($wheel[$i][0] <= $rand && $rand < $wheel[$i][1]) {
	$selected{$i} = 1;
	last;
      }
    }
  }

  return map $wheelPop->[$_], keys %selected;
}

# sub tournament():
# arguments are anon list of population, and number
# of individuals in tournament (def = 2).
# return 1 individual.

sub tournament {
  my ($pop, $num) = @_;

Genetic/OpSelection.pm  view on Meta::CPAN

  }

  return (sort {$b->score <=> $a->score}
	  map {$_->score; $_}  # This avoids a bug in Perl. See Genetic.pm.
	  map $pop->[$_], keys %s)[0];
}

# sub random():
# pure random choice of individuals.
# arguments are anon list of population, and number
# of individuals to select (def = 1).
# returns selected individual(s).

sub random {
  my ($pop, $num) = @_;

  $num ||= 1;

  my %s;
  while ($num > keys %s) {
    my $i = int rand @$pop;
    $s{$i} = 1;

Genetic/OpSelection.pm  view on Meta::CPAN

	   map {$_->score; $_}  # This avoids a bug in Perl. See Genetic.pm.
	   @$pop)[0 .. $N-1]];
}

1;

__END__

=head1 NAME

AI::Genetic::OpSelection - A class that implements various selection operators.

=head1 SYNOPSIS

See L<AI::Genetic>.

=head1 DESCRIPTION

This package implements a few selection mechanisms that can be used in user-defined
strategies. The methods in this class are to be called as static class methods,
rather than instance methods, which means you must call them as such:

  AI::Genetic::OpSelection::MethodName(arguments)

=head1 SELECTION OPERATORS AND THEIR METHODS

The following selection operators are defined:

=over

=item Roulette Wheel

Here, the probability of an individual being selected is proportional to its fitness
score. The following methods are defined:

=over

=item B<initWheel>(I<population>)

This method initializes the roulette wheel. It expects an anonymous list of individuals,
as returned by the I<people()> method as described in L<AI::Genetic/CLASS METHODS>.
This B<must> be called only once.

=item B<roulette>(?I<N>?)

This method selects I<N> individuals. I<N> defaults to 2. Note that the same individual
can be selected multiple times.

=item B<rouletteUnique>(?I<N>?)

This method selects I<N> unique individuals. I<N> defaults to 2. Any individual
can be selected only once per call to this method.

=back

=item Tournament

Here, I<N> individuals are randomly selected, and the fittest one of
them is returned. The following method is defined:

=over

=item B<tournament>(?I<N>?)

I<N> defaults to 2. Note that only one individual is returned per call to this
method.

=back

=item Random

Here, I<N> individuals are randomly selected and returned.
The following method is defined:

=over

=item B<random>(?I<N>?)

I<N> defaults to 1.

=back

README  view on Meta::CPAN

    for more info). Typically, a variation of the following happens at each
    generation:

    1. Selection
        Here the performance of all the individuals is evaluated based on
        the fitness function, and each is given a specific fitness value.
        The higher the value, the bigger the chance of an individual passing
        its genes on in future generations through mating (crossover).

    2. Crossover
        Here, individuals selected are randomly paired up for crossover (aka
        *sexual reproduction*). This is further controlled by the crossover
        rate specified and may result in a new offspring individual that
        contains genes common to both parents. New individuals are injected
        into the current population.

    3. Mutation
        In this step, each individual is given the chance to mutate based on
        the mutation probability specified. If an individual is to mutate,
        each of its genes is given the chance to randomly switch its value
        to some other state.

README  view on Meta::CPAN

    The fitness function should expect only one argument, an anonymous list
    of genes, corresponding to the individual being analyzed. It is expected
    to return a number which defines the fitness score of the said
    individual. The higher the score, the more fit the individual, the more
    the chance it has to be chosen for crossover.

STRATEGIES
    AI::Genetic comes with 9 predefined strategies. These are:

    rouletteSinglePoint
        This strategy implements roulette-wheel selection and single-point
        crossover.

    rouletteTwoPoint
        This strategy implements roulette-wheel selection and two-point
        crossover.

    rouletteUniform
        This strategy implements roulette-wheel selection and uniform
        crossover.

    tournamentSinglePoint
        This strategy implements tournament selection and single-point
        crossover.

    tournamentTwoPoint
        This strategy implements tournament selection and two-point
        crossover.

    tournamentUniform
        This strategy implements tournament selection and uniform crossover.

    randomSinglePoint
        This strategy implements random selection and single-point
        crossover.

    randomTwoPoint
        This strategy implements random selection and two-point crossover.

    randomUniform
        This strategy implements random selection and uniform crossover.

    More detail on these strategies and how to call them in your own custom
    strategies can be found in the AI::Genetic::OpSelection manpage, the
    AI::Genetic::OpCrossover manpage and the AI::Genetic::OpMutation
    manpage.

    You can use the functions defined in the above modules in your own
    custom-made strategy. Consult their manpages for more info. A
    custom-made strategy can be defined using the *strategy()* method and is
    called at the beginning of each generation. The only argument to it is



( run in 0.576 second using v1.01-cache-2.11-cpan-49f99fa48dc )