Algorithm-Evolutionary
view release on metacpan or search on metacpan
lib/Algorithm/Evolutionary/Individual/Base.pm view on Meta::CPAN
use Algorithm::Evolutionary::Individual::Base;
my $indi = Algorithm::Evolutionary::Individual::Base->fromParam( $param_hashref ); #From parametric description
$binIndi2->Fitness( 3.5 ); #Sets or gets fitness
print $binIndi2->Fitness();
my $emptyIndi = new Algorithm::Evolutionary::Individual::Base;
=head1 DESCRIPTION
Base class for individuals, that is, "chromosomes" in evolutionary
computation algorithms. However, chromosomes needn't be bitstrings, so
the name is a bit misleading. This is, however, an "empty" base class,
that acts as a boilerplate for deriving others.
=cut
package Algorithm::Evolutionary::Individual::Base;
use YAML qw(Dump Load LoadFile);
use Carp;
our $VERSION = '3.3';
use constant MY_OPERATORS => qw(None);
=head1 METHODS
=head2 AUTOLOAD
Creates methods for instance variables automatically
=cut
sub AUTOLOAD {
my $self = shift;
my $attr = our $AUTOLOAD;
$attr =~ s/.*:://;
return unless $attr =~ /[^A-Z]/; # skip DESTROY and all-cap methods
my $instance_variable = "_$attr";
$self->{$instance_variable} = shift if @_;
return $self->{$instance_variable};
}
=head2 new( $options )
Creates a new Base individual of the required class, with a fitness, and sets fitnes to undef.
Takes as params a hash to the options of the individual, that will be passed
on to the object of the class when it iss initialized.
=cut
sub new {
my $class = shift;
if ( $class !~ /Algorithm::Evolutionary/ ) {
$class = "Algorithm::Evolutionary::Individual::$class";
}
my $options = shift;
my $self = { _fitness => undef }; # Avoid error
bless $self, $class; # And bless it
#If the class is not loaded, we load it.
if ( !$INC{"$class\.pm"} ) {
eval "require $class" || croak "Can't find $class Module";
}
if ( $options ) {
$self->set( $options );
}
return $self;
}
=head2 create( $ref_to_hash )
Creates a new individual, but uses a different interface: takes a
ref-to-hash, with named parameters, which gives it a common interface
to all the hierarchy. The main difference with respect to new is that
after creation, it is initialized with random values.
=cut
sub create {
my $class = shift;
my $ref = shift || croak "Can't find the parameters hash";
my $self = Algorithm::Evolutionary::Individual::Base::new( $class, $ref );
$self->randomize();
return $self;
}
=head2 set( $ref_to_hash )
Sets values of an individual; takes a hash as input. Keys are prepended an
underscore and turn into instance variables
=cut
sub set {
my $self = shift;
my $hash = shift || croak "No params here";
for ( keys %{$hash} ) {
$self->{"_$_"} = $hash->{$_};
}
}
=head2 as_yaml()
Prints it as YAML.
=cut
sub as_yaml {
my $self = shift;
return Dump($self);
}
=head2 as_string()
Prints it as a string in the most meaningful representation possible
( run in 0.513 second using v1.01-cache-2.11-cpan-4991d5b9bd9 )