Algorithm-Evolutionary
view release on metacpan or search on metacpan
lib/Algorithm/Evolutionary/Op/GeneralGeneration.pm view on Meta::CPAN
input
=cut
sub set {
my $self = shift;
my $hashref = shift || croak "No params here";
my $codehash = shift || croak "No code here";
my $opshash = shift || croak "No ops here";
$self->{_selrate} = $hashref->{selrate};
for ( keys %$codehash ) {
$self->{"_$_"} = eval "sub { $codehash->{$_} } ";
}
$self->{_ops} =();
for ( keys %$opshash ) {
push @{$self->{_ops}},
Algorithm::Evolutionary::Op::Base::fromXML( $_, $opshash->{$_}->[1], $opshash->{$_}->[0] ) ;
}
}
=head2 apply( $population )
Applies the algorithm to the population, which should have
been evaluated first; checks that it receives a
ref-to-array as input, croaks if it does not. Returns a sorted,
culled, evaluated population for next generation.
=cut
sub apply ($) {
my $self = shift;
my $pop = shift || croak "No population here";
croak "Incorrect type ".(ref $pop) if ref( $pop ) ne $APPLIESTO;
#Evaluate only the new ones
my $eval = $self->{_eval};
my @ops = @{$self->{_ops}};
#Breed
my $selector = $self->{_selector};
my @genitors = $selector->apply( @$pop );
#Reproduce
my $totRate = 0;
my @rates;
for ( @ops ) {
push( @rates, $_->{rate});
}
my $opWheel = new Algorithm::Evolutionary::Wheel @rates;
my @newpop;
my $pringaos = @$pop * $self->{'_replacementRate'} ;
for ( my $i = 0; $i < $pringaos; $i++ ) {
my @offspring;
my $selectedOp = $ops[ $opWheel->spin()];
# print $selectedOp->asXML;
for ( my $j = 0; $j < $selectedOp->arity(); $j ++ ) {
my $chosen = $genitors[ rand( @genitors )];
# print "Elegido ", $chosen->asString(), "\n";
push( @offspring, $chosen->clone() );
}
my $mutante = $selectedOp->apply( @offspring );
push( @newpop, $mutante );
}
#Eliminate and substitute
splice( @$pop, -$pringaos );
for ( @newpop ) {
$_->evaluate( $eval );
}
push @$pop, @newpop;
my @sortPop = sort { $b->{'_fitness'} <=> $a->{'_fitness'}; } @$pop;
@$pop = @sortPop;
}
=head1 SEE ALSO
=over 4
=item *
A more modern and flexible version: L<Algorithm::Evolutionary::Op::Generation_Skeleton>.
=item *
L<Algorithm::Evolutionary::Op::CanonicalGA>.
=item *
L<Algorithm::Evolutionary::Op::FullAlgorithm>.
=back
=head1 Copyright
This file is released under the GPL. See the LICENSE file included in this distribution,
or go to http://www.fsf.org/licenses/gpl.txt
=cut
"The truth is out there";
( run in 0.417 second using v1.01-cache-2.11-cpan-5735350b133 )