Algorithm-Evolutionary
view release on metacpan or search on metacpan
lib/Algorithm/Evolutionary/Op/Easy.pm view on Meta::CPAN
Sets the instance variables. Takes a ref-to-hash (for options), codehash (for fitness) and opshash (for operators)
=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->{$_} } " || carp "Error compiling fitness function: $! => $@";
}
$self->{_ops} =();
for ( keys %$opshash ) {
#First element of the array contains the content, second the rate.
push @{$self->{_ops}},
Algorithm::Evolutionary::Op::Base::fromXML( $_, $opshash->{$_}->[1], $opshash->{$_}->[0] );
}
}
=head2 apply( $population )
Applies the algorithm to the population; 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";
#Evaluate
my $eval = $self->{_eval};
my @ops = @{$self->{_ops}};
my @popEval;
for ( @$pop ) {
my $fitness; #Evaluates only those that have no fitness
if ( !defined ($_->Fitness() ) ) {
$_->evaluate( $eval );
}
push @popEval, $_;
}
#Sort by fitness
my @popsort = sort { $b->{_fitness} <=> $a->{_fitness}; }
@popEval ;
#Cull
my $pringaos = int(($#popsort+1)*$self->{_selrate}); #+1 gives you size
splice @popsort, -$pringaos;
#Reproduce
my @rates = map( $_->{'rate'}, @ops );
my $opWheel = new Algorithm::Evolutionary::Wheel @rates;
#Generate offpring;
my $originalSize = $#popsort; # Just for random choice
for ( my $i = 0; $i < $pringaos; $i ++ ) {
my @offspring;
my $selectedOp = $ops[ $opWheel->spin()];
croak "Problems with selected operator" if !$selectedOp;
for ( my $j = 0; $j < $selectedOp->arity(); $j ++ ) {
my $chosen = $popsort[ int ( rand( $originalSize ) )];
push( @offspring, $chosen ); #No need to clone, it's not changed in ops
}
# p rint "Op ", ref $selectedOp, "\n";
# if ( (ref $selectedOp ) =~ /ssover/ ) {
# print map( $_->{'_str'}."\n", @offspring );
# }
my $mutante = $selectedOp->apply( @offspring );
croak "Error aplying operator" if !$mutante;
# print "Mutante ", $mutante->{'_str'}, "\n";
push( @popsort, $mutante );
}
#Return
@$pop = @popsort;
}
=head1 SEE ALSO
L<Algorithm::Evolutionary::Op::CanonicalGA>.
L<Algorithm::Evolutionary::Op::FullAlgorithm>.
=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.725 second using v1.01-cache-2.11-cpan-98e64b0badf )