<?xml version="1.0" encoding="windows-1252"?>
<node id="81679" title="Re: Algorithm::Genetic" created="2001-05-19 03:17:01" updated="2005-07-26 23:52:49">
<type id="11">
note</type>
<author id="53423">
Masem</author>
<data>
<field name="doctext">
As an addition test case that I'm using, I've taken the concepts in [id://31147], and used them to develop the following code:
&lt;CODE&gt;
#!/usr/bin/perl -w

use strict;

use Algorithm::Genetic;
use Data::Dumper;

my @genes = qw{
    $x+=1; $x=$y; $y=$x; $x|=$y; $x+=$y;
};

my $target = 100;

my $algo = new Algorithm::Genetic( {
    FITNESS =&gt; \&amp;fitness,
    MUTATOR =&gt; \&amp;mutate,
    REAP_CRITERIA =&gt; sub { $_[ 0 ]-&gt;{ FITNESS } },
    MUTATE_CRITERIA =&gt; sub { (10000-$_[ 0 ]-&gt;{ FITNESS } )**2 }
} );


my @initcode;
foreach ( 0..10 ) { 
    my @bits = map {  int rand @genes } ( 0..10 );
    $initcode[ $_ ] = \@bits;
};


$algo-&gt;init_population( @initcode );

for (1..100) {
    print "GENERATION $_\n";
    print "-------------\n";
    print join "\n", map { eval_code( get_code( @$_ ) ).' : '.get_code( @$_ ) } reverse $algo-&gt;get_population();
    print "\n";
    $algo-&gt;process_generation();
    print "\n";
}


sub mutate {
    my @clone = @{ $_[0]-&gt;{ DATA } };

    if ( int( rand() + 0.5 ) ) { 
	# mutate by switching a new op in
	my $pos = int rand @clone;
	my $newop = int rand @genes;
	while ( $newop == $clone[ $pos ] ) {
	    $newop = int rand @genes;
	}
	$clone[ $pos ] = $newop;	
    } else {
	# mutate by adding a new op in
	push @clone, $genes[ int rand @genes ];
    }
    return \@clone;
}

sub fitness {
    my $code = $_[0]-&gt;{ DATA };
   
    # Calculate the fitness;
    my $string = get_code( @$code );
    my $calc = eval_code( $string );
    return ( $calc - $target )**2;
}

sub get_code { 
    my $string = 'my $x = 1; my $y = 1; ';
    $string = join '', $string, map { $genes[ $_ ] } @_;
    return $string;
}    

sub eval_code {
    return eval( $_[0] );
}
&lt;/CODE&gt;
&lt;P&gt;While probably not as robust as the original entry, the solutions I'm getting are converging to the target value even after 100 generations, so something is working right...
&lt;P&gt;
&lt;HR&gt;
&lt;I&gt;
Dr. Michael K. Neylon - &lt;a href="mailto:mneylon-pm@masemware.com"&gt;mneylon-pm@masemware.com&lt;/a&gt;
||
"You've left the lens cap of your mind on again, Pinky" - The Brain
&lt;/I&gt;</field>
<field name="root_node">
81678</field>
<field name="parent_node">
81678</field>
</data>
</node>
