SlideShare a Scribd company logo
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GRAMMATICAL OPTIMIZATION
THE SOURCE CODE
Muhammad Adil Raja
Roaming Researchers, Inc.
cbna
April 27, 2015
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
OUTLINE I
1 INTRODUCTION
2 GE’S MAIN
3 INITIALIZER
4 GENOTYPE
5 GRAMMAR
6 PRODUCTION
7 RULE
8 MAPPER
9 SYMBOL
10 TREE
11 SUMMARY
12 REFERENCES
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
INTRODUCTION I
Grammatical optimization (GO) is an adaptation of
grammatical evolution (GE).
The algorithm is implemented in Java.
The algorithm is aimed at general optimization problems.
With slight modification it can also be used for other types
of problems such as classification.
The source code has many Java files.
In what follows you will find the source code of various
components of Java Beagle.
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE’S MAIN I
/∗
∗ GEsMain . java
∗
∗ Created on August 4 , 2007, 5:31 PM
∗
∗ To change t h i s template , choose Tools | Template Manager
∗ and open the template in the e d i t o r .
∗/
package GrammaticOptimization ;
/∗∗
∗
∗ @author a d i l r a j a
∗/
import java . u t i l . ∗ ;
public class GEsMain {
/∗∗ Creates a new instance of GEsMain ∗/
public GEsMain ( ) {
}
/∗∗
∗ @param args the command l i n e arguments
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE’S MAIN II
∗/
public static void main ( String [ ] args ) {
/ / TODO code a p p l i c a t i o n l o g i c here
Random rand=new Random ( ) ;
int [ ] newArray= new int [ 1 0 ] ;
newArray [ 0 ] = 0 ;
newArray [ 1 ] = 2 ;
newArray [ 2 ] = 1 ;
newArray [ 3 ] = 4 ;
newArray [ 4 ] = 4 ;
newArray [ 5 ] = 4 ;
newArray [ 6 ] = 4 ;
newArray [ 7 ] = 4 ;
newArray [ 8 ] = 4 ;
newArray [ 9 ] = 4 ;
ArrayList <Integer > a r r L i s t =new ArrayList ( ) ;
for ( int i =0; i <10; i ++){
a r r L i s t . add ( ( Integer ) newArray [ i ] ) ;
}
Genotype geno=new Genotype ( newArray , 10 , true , 1 0 ) ;
GEGrammar grammar=new GEGrammar( geno ) ;
grammar . setMaxWraps ( 9 ) ;
grammar . readBNFFile ( " / Users / a d i l r a j a / mywork / adils−java / GrammaticOptimization / d i s t / gram
/ / t r y {
/ / grammar . genotype2phenotype ( true ) ;
/ / }
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE’S MAIN III
/ / catch ( java . lang . Exception e ) {
/ / System . out . p r i n t l n ( e+" In Main " ) ;
/ / }
I t e r a t o r <Symbol> symbIt=grammar . getPhenotype ( ) . i t e r a t o r ( ) ;
I t e r a t o r <Rule> r u l e I t =grammar . i t e r a t o r ( ) ;
System . out . p r i n t l n ( " Here are the r e s u l t s : phenotype sizse= "+grammar . getPhenotype ( ) . si
while ( symbIt . hasNext ( ) ) {
System . out . p r i n t ( symbIt . next ( ) . getSymbol ( ) ) ;
}
i f ( grammar . phenotype . getValid ()== true )
System . out . p r i n t l n ( "  nThe above phenotype i s v a l i d " ) ;
else
System . out . p r i n t l n ( "  nThe above phenotype i s not v a l i d " ) ;
System . out . p r i n t l n ( "  n  nHere i s the grammar" ) ;
while ( r u l e I t . hasNext ( ) ) {
Rule tmpRule= r u l e I t . next ( ) ;
System . out . p r i n t ( "  n"+tmpRule . lhs . get ( 0 ) . getSymbol ()+ " : : = " ) ;
I t e r a t o r <Production > prodIt =tmpRule . i t e r a t o r ( ) ;
while ( prodIt . hasNext ( ) ) {
I t e r a t o r <Symbol> symbIt2= prodIt . next ( ) . i t e r a t o r ( ) ;
while ( symbIt2 . hasNext ( ) ) {
System . out . p r i n t ( symbIt2 . next ( ) . getSymbol ( ) ) ;
}
}
}
System . out . p r i n t l n ( "My name i s John Rambo "+grammar . size ( ) ) ;
System . out . p r i n t l n ( newArray . length ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE’S MAIN IV
String str1 =new String ( " Adil " ) ;
String str2 =new String ( " Adil " ) ;
i f ( str1 . equals ( str2 ) )
System . out . p r i n t l n ( " adilRaja " ) ;
Symbol symb=new Symbol ( ) ;
System . out . p r i n t l n (symb . getType ( ) . to Str in g ( ) ) ;
symb . setType ( SymbolType . NTSymbol ) ;
System . out . p r i n t l n (symb . getType ( ) . to Str in g ( ) ) ;
r u l e I t =grammar . i t e r a t o r ( ) ;
System . out . p r i n t l n ( "  n  nHere i s the grammar ’ s NT/ T i n f o " ) ;
while ( r u l e I t . hasNext ( ) ) {
Rule tmpRule= r u l e I t . next ( ) ;
System . out . p r i n t ( "  n"+tmpRule . lhs . get ( 0 ) . getType ( ) . to Str in g ()+ " : : = " ) ;
I t e r a t o r <Production > prodIt =tmpRule . i t e r a t o r ( ) ;
while ( prodIt . hasNext ( ) ) {
I t e r a t o r <Symbol> symbIt2= prodIt . next ( ) . i t e r a t o r ( ) ;
while ( symbIt2 . hasNext ( ) ) {
System . out . p r i n t ( symbIt2 . next ( ) . getType ( ) . to St rin g ()+ " " ) ;
}
}
}
}
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
INITIALIZER I
/∗
∗ I n i t i a l i s e r . java
∗
∗ Created on July 2 , 2007, 6:05 PM
∗
∗ To change t h i s template , choose Tools | Template Manager
∗ and open the template in the e d i t o r .
∗/
/∗∗
∗
∗ @author a d i l r a j a
∗
∗/
package GrammaticOptimization ;
public interface I n i t i a l i s e r {
public int getPopSize ( ) ;
public void setPopSize ( f i n a l int j ) ;
public int getIndex ( ) ;
public void setIndex ( f i n a l int i ) ;
public boolean i n i t ( f i n a l int i ) ;
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GENOTYPE I
/∗
∗ Genotype . java
∗
∗ Created on June 1 , 2007, 11:35 PM
∗
∗ To change t h i s template , choose Tools | Template Manager
∗ and open the template in the e d i t o r .
∗/
/∗∗
∗
∗ @author a d i l r a j a
∗/
package GrammaticOptimization ;
import java . u t i l . ∗ ;
import java . u t i l . ArrayList ;
/∗ Default Constructor . Creates a genotype s t r u c t u r e of length newLength , using the elements o
∗ i t s v a l i d f i e l d to newValid and i t s f i t n e s s to newFitness . Non−specified arguments are given
∗, as specified in the function prototype .
∗
∗/
public class Genotype extends ArrayList <Integer >{ / / codonType
private Vector genome ;
private boolean _libGE_Genotype_valid ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GENOTYPE II
private double _libGE_Genotype_fitness ;
private int _libGE_Genotype_maxCodonValue ;
private int _libGE_Genotype_effectiveSize ;
private int _libGE_Genotype_wraps ;
public Genotype ( ) {
}
/∗∗ Creates a new instance of Genotype ∗/
public Genotype ( f i n a l int [ ] newArray , f i n a l int newLength , f i n a l boolean newValid , f i n a l d
_libGE_Genotype_valid=newValid ;
_libGE_Genotype_fitness=newFitness ;
this . setMaxCodonValue (32767); / / INT_MAX
for ( int i i =0; i i <newLength ; i i ++){
this . add (new Integer ( newArray [ i i ] ) ) ;
}
setEffectiveSize ( 0 ) ;
setWraps ( 0 ) ;
}
/∗ Constructor . Creates a genotype s t r u c t u r e with the contents of newvector , and sets i t s
∗ f i e l d to newValid and i t s f i t n e s s to newFitness .
∗Non−specified arguments are given default values , as specified in he function prototype
∗/
public Genotype ( f i n a l ArrayList <Integer > newVector , f i n a l boolean newValid , f i n a l double n
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GENOTYPE III
_libGE_Genotype_valid=newValid ;
_libGE_Genotype_fitness=newFitness ;
this . addAll ( newVector ) ;
setMaxCodonValue (32767);
setEffectiveSize ( 0 ) ;
setWraps ( 0 ) ;
}
/∗ Constructor . Creates an empty genotype structure , and sets maCodonValue to the value
∗specified as argument
∗/
public Genotype ( f i n a l int maxCodonValue ) {
setMaxCodonValue ( maxCodonValue ) ;
setEffectiveSize ( 0 ) ;
setWraps ( 0 ) ;
}
/∗Copy constructor
∗/
public Genotype ( f i n a l Genotype copy ) {
setValid ( copy . getValid ( ) ) ;
setFitness ( copy . getFitness ( ) ) ;
setMaxCodonValue ( copy . getMaxCodonValue ( ) ) ;
setEffectiveSize ( copy . getEffectiveSize ( ) ) ;
setWraps ( copy . getWraps ( ) ) ;
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GENOTYPE IV
/∗ Returns the current v a l i d f i e l d
∗/
public f i n a l boolean getValid ( ) {
return _libGE_Genotype_valid ;
}
/∗ Set a new value f o r the v a l i d f i e l d
∗/
public void setValid ( f i n a l boolean newValid ) {
_libGE_Genotype_valid=newValid ;
}
/∗ Returns the current f i t n e s s score
∗/
public f i n a l double getFitness ( ) {
return _libGE_Genotype_fitness ;
}
/∗ Sets a new f i t n e s s score
∗/
public void setFitness ( f i n a l double newFitness ) {
_libGE_Genotype_fitness=newFitness ;
}
/∗ Returns the maximum containable value in a codon
∗/
public f i n a l int getMaxCodonValue ( ) {
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GENOTYPE V
return _libGE_Genotype_maxCodonValue ;
}
/∗ Sets the maximum containable value in a codon
∗/
public void setMaxCodonValue ( f i n a l int newMaxCodonValue ) {
_libGE_Genotype_maxCodonValue=newMaxCodonValue ;
}
/∗ Returns e f f e c t i v e length of Genotype
∗/
public f i n a l int getEffectiveSize ( ) {
return _libGE_Genotype_effectiveSize ;
}
/∗ Sets e f f e c t i v e length of genotype
∗/
public void setEffectiveSize ( f i n a l int newEffectiveSize ) {
_libGE_Genotype_effectiveSize=newEffectiveSize ;
}
/∗ Returns number of wrapping events
∗/
public f i n a l int getWraps ( ) {
return _libGE_Genotype_wraps ;
}
/∗ Sets the number of wrapping events
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GENOTYPE VI
∗/
public void setWraps ( f i n a l int newWraps ) {
_libGE_Genotype_wraps=newWraps ;
}
/∗Used to p r i n t the genome as a s t r i n g
∗/
public String printContents ( ) {
/ / String s=new String ( ) ;
return this . toArray ( ) . toS tr in g ( ) ;
}
}
/ / complete
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GRAMMAR I
/∗
∗ Grammar . java
∗
∗ Created on July 26 , 2007, 6:09 PM
∗
∗ To change t h i s template , choose Tools | Template Manager
∗ and open the template in the e d i t o r .
∗/
package GrammaticOptimization ;
/∗∗
∗
∗ @author a d i l r a j a
∗/
import java . u t i l . I t e r a t o r ;
public abstract class Grammar extends Mapper {
private boolean validGrammar ;
private int startSymbol ;
protected abstract boolean genotype2phenotype ( ) ;
protected abstract boolean phenotype2genotype ( ) ;
/∗∗
∗ Creates a new instance of Grammar
∗/
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GRAMMAR II
public Grammar ( ) {
super ( ) ;
setValidGrammar ( false ) ;
startSymbol =0;
}
/∗∗
∗Constructor s e t t i n g the genotype s t r u c t u r e of t h i s mapper to newGenotype .
∗/
public Grammar( f i n a l Genotype newGenotype ) {
super ( newGenotype ) ;
setValidGrammar ( false ) ;
startSymbol =0;
}
/∗∗
∗Constructor s e t t i n g the phenotype s t r u c t u r e of t h i s mapper to newPhenotype .
∗/
public Grammar( f i n a l Phenotype newPhenotype ) {
super ( newPhenotype ) ;
setValidGrammar ( false ) ;
startSymbol =0;
}
/∗∗
∗Copy Constructor
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GRAMMAR III
∗/
public Grammar( f i n a l Grammar copy ) {
super ( ) ;
setValidGrammar ( copy . getValidGrammar ( ) ) ;
startSymbol=copy . startSymbol ;
}
/∗∗
∗ Return the v a l i d i t y of the current grammar .
∗/
public f i n a l boolean getValidGrammar ( ) {
return validGrammar ;
}
/∗∗
∗Set the v a l i d i t y of the grammar .
∗/
protected void setValidGrammar ( f i n a l boolean newValidGrammar ) {
validGrammar=newValidGrammar ;
}
/∗∗
∗Return current s t a r t symbol .
∗/
public f i n a l Symbol getStartSymbol ( ) {
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GRAMMAR IV
/ / return f r o n t ( ) . lhs . f r o n t ( ) ;
/ / return (∗ t h i s ) [ startSymbol ] . lhs . f r o n t ( ) ;
Symbol symb=null ;
i f ( startSymbol <this . size ( ) )
{
symb=this . get ( startSymbol ) . lhs . get ( 0 ) ;
}
return symb ;
}
/∗∗
∗Change s t a r t symbol by index on Vector of rules .
∗/
public boolean setStartSymbol ( f i n a l int index ) {
i f ( index <this . size ( ) ) { / / Check boundaries .
startSymbol=index ;
genotype2phenotype ( ) ; / / Update phenotype .
return true ;
}
return false ;
}
/∗∗
∗Change s t a r t symbol by symbol pointer .
∗/
public boolean setStartSymbol ( f i n a l Symbol newStartSymbol ) {
int i i =0;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GRAMMAR V
I t e r a t o r <Rule> i t =this . i t e r a t o r ( ) ;
while ( i t . hasNext ( ) ) {
/ / Work by ∗pointer ∗.
i f ( i t . next ( ) . lhs . get ( 0 ) . getSymbol ( ) . compareTo ( newStartSymbol . getSymbol ( ) ) = = 0 ) {
startSymbol= i i ;
genotype2phenotype ( ) ; / / Update phenotype .
return true ;
}
i i ++;
}
return false ;
}
/∗∗
∗Change s t a r t symbol by s t r i n g .
∗/
public boolean setStartSymbol ( f i n a l String newStartSymbol ) {
int i i =0;
I t e r a t o r <Rule> i t =this . i t e r a t o r ( ) ;
while ( i t . hasNext ( ) ) {
/ / Work by ∗s t r i n g ∗.
String currentStartSymbol= i t . next ( ) . lhs . get ( 0 ) . getSymbol ( ) ;
i f ( currentStartSymbol . compareTo ( newStartSymbol )==0){
startSymbol= i i ;
genotype2phenotype ( ) ; / / Update phenotype .
return true ;
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GRAMMAR VI
i i ++;
}
return false ;
}
/∗∗
∗Return pointer to current s t a r t rule .
∗/
public f i n a l Rule getStartRule ( ) {
return this . get ( 0 ) ;
}
}
/ / complete
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR I
/∗
∗ CFGrammar. java
∗
∗ Created on July 26 , 2007, 12:21 PM
∗
∗ To change t h i s template , choose Tools | Template Manager
∗ and open the template in the e d i t o r .
∗/
package GrammaticOptimization ;
/∗∗
∗
∗ @author a d i l r a j a
∗/
import java . u t i l . ∗ ;
import java . u t i l . ArrayList ;
import java . u t i l . I t e r a t o r ;
import java . io . ∗ ;
public abstract class CFGrammar extends Grammar {
protected Tree derivationTree ;
protected abstract boolean genotype2phenotype ( ) ;
protected abstract boolean phenotype2genotype ( ) ;
/∗∗
∗ Creates a new instance of CFGrammar
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR II
∗/
public CFGrammar ( ) {
super ( ) ;
}
/∗∗
∗Constructor s e t t i n g the genotype s t r u c t u r e of t h i s mapper to newGenotype .
∗/
public CFGrammar( f i n a l Genotype newGenotype ) {
super ( newGenotype ) ;
}
/∗∗
∗ Constructor s e t t i n g the phenotype s t r u c t u r e of t h i s mapper to newPhenotype .
∗/
public CFGrammar( f i n a l Phenotype newPhenotype ) {
super ( newPhenotype ) ;
}
/∗∗
∗ Copy Constructor .
∗/
public CFGrammar( f i n a l CFGrammar copy ) {
super ( copy ) ;
/ / Now must go through the copied grammar , and replace references to
/ / the copy ’ s lhs symbols with references to the new lhs symbols .
I t e r a t o r r u l e I t =this . i t e r a t o r ( ) ; / / i t e r a t o r of Rule
I t e r a t o r <Rule> prodIt ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR III
I t e r a t o r <Production > symbIt ;
Rule r u l e P t r =null ;
int ruleCt =0 , prodCt =0 , symbCt=0;
while ( r u l e I t . hasNext ( ) ) {
prodIt = r u l e I t ;
while ( prodIt . hasNext ( ) ) {
symbIt= prodIt . next ( ) . i t e r a t o r ( ) ;
while ( symbIt . hasNext ( ) ) {
Symbol symb=symbIt . next ( ) . get ( 0 ) ;
i f (symb . getType ( ) . t oSt ri ng ( ) . compareTo ( "NTSymbol" )==0){
try {
r u l e P t r =findRule (symb ) ;
}
catch ( Exception e ) {
/ / do nothing
}
i f ( r u l e P t r ==null ) {
/∗ Undefined NTSymbol − create new symbol ∗/
symb=new Symbol (symb . getSymbol ( ) , null ) ;
}
else {
/∗ Point to symbol ’ s d e f i n i t i o n ∗/
symb= r u l e P t r . lhs . get ( r u l e P t r . lhs . size () −1);
}
this . get ( ruleCt ) . get ( prodCt ) . insertSymbol (symb , symbCt ) ;
}
symbIt . next ( ) ;
symbCt++;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR IV
}
prodIt . next ( ) ;
prodCt ++;
}
r u l e I t . next ( ) ;
ruleCt ++;
}
/ / I n v a l i d a t e phenotype − lower classes in hierarchy can always c a l l
/ / genotype2Phenotype ( ) to regenerate i t
phenotype . clear ( ) ;
phenotype . setValid ( false ) ;
/ / Don ’ t copy d e r i v a t i o n tree : procedure i s too complex and expensive .
/ / I f tree i s requested , i t w i l l be regenerated .
}
/∗∗
∗ Opens the f i l e whose name i s passed as an argument , reads i t s contents onto
∗a character string , and c a l l s readBNFString .
∗/
public boolean readBNFFile ( f i n a l String filename ) {
/∗
FILE ∗pFile ;
i f ( ! ( pFile=fopen ( filename , " r " ) ) ) {
cerr << " Could not open grammar f i l e " << filename << " .  nExecution aborted .  n
e x i t ( 1 ) ;
}
fseek ( pFile ,0 ,SEEK_END) ;
i n t size = f t e l l ( pFile ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR V
char program [ size +1];
strncpy ( program , " " , size ) ;
char l i n e [1024];
rewind ( pFile ) ;
while ( fgets ( line ,1024 , pFile ) )
s t r c a t ( program , l i n e ) ;
fclose ( pFile ) ;
s t r c a t ( program , "  n " ) ;
return readBNFString ( program ) ;
∗/
String program=new String ( ) ;
/ / t r y
/ / {
/ / Open the f i l e that i s the f i r s t
/ / command l i n e parameter
/ / FileInputStream fstream = new FileInputStream ( " a d i l . bnf " ) ;
/ / Convert our input stream to a
/ / DataInputStream
/ / BufferedReader in = new BufferedReader (new InputStreamReader ( fstream ) ) ;
/ / Continue to read l i n e s while
/ / there are s t i l l some l e f t to read
/ / DataInput s = new DataInputStream (new FileInputStream ( " ~ / mywork /GE/ libGE −0.26/E
/ / String th is Li ne ;
/ / while ( ( th is Li ne =s . readLine ( ) ) != n u l l )
/ / {
/ / program . concat ( th is Li ne ) ;
/ / }
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR VI
/ / s . close ( ) ;
/ / }
/ / catch ( Exception e )
/ / {
/ / System . out . p r i n t l n ( e+" F i l e input error " ) ;
/ / }
/ / program . concat ( "  n " ) ;
program="<expr > : : = (<expr > <op> <expr > )  n | DIV(<expr > , <expr > )  n | ABS(<expr > )  n | GT(
return readBNFString ( program ) ;
}
/∗∗
∗ Reads in the BNF grammar specified by i t s argument t e x t . Returns true i f
∗ loading of grammar was successful , false otherwise .
∗/
public boolean readBNFString ( String stream ) { / / the stream was f i n a l
/ / Delete the current grammar , i f any
this . clear ( ) ;
Rule newRule=new Rule ( 0 ) ; / / Used to create new rules f o r gramm
boolean insertRule=false ; / / I f newRule i s to be inserted onto grammar
Rule currentRule=null ; / / Used in pass 2 to add productions to current rule
Production newProduction=new Production ( 1 ) ;
newProduction . clear ( ) ; / / Used to create new productions f o r grammar
Symbol newSymbol=new Symbol ( ) ; / / Used to create new symbols f o r grammar
Symbol newTokenSeparator=new Symbol ( ) ; / / Used to create token separators f o r gramma
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR VII
int stream_size=stream . length ( ) ;
int i i , j j ; / / Working variables
char currentChar ; / / Current char of input
boolean skip=false ; / / SKip an i t e r a t i o n on parser ( f o r escaped newlines )
boolean quoted=false ; / / I f current char i s quoted
boolean non_terminal=false ; / / I f current t e x t i s a non−terminal symbol
char separated =0; / / I f there was a separator between previous token and
ArrayList <Symbol> nonTerminals=new ArrayList ( ) ;
nonTerminals . clear ( ) ; / / Contains pointers to a l l defined non−terminals
I t e r a t o r <Symbol> nonTerminalsIt ;
String currentBuffer =new String ( ) ; / / Buffer used to add new symbols to g
/ / States of parser
f i n a l int START = 0;
f i n a l int START_RULE = 1;
f i n a l int LHS_READ = 2;
f i n a l int PRODUCTION = 3;
f i n a l int START_OF_LINE = 4;
int state=START; / / Current state of parser
/ / #define libGE_DEBUG_CFGRAMMAR_PARSER
stream+="  n" ;
for ( int pass =1;pass <=2;pass ++){
i i = j j =0;
while ( i i <=stream_size ) {
i f ( i i <stream_size ) {
currentChar=stream . charAt ( i i ) ;
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR VIII
else {
/ / Simulate presence of endl at end of grammar
currentChar= ’  n ’ ;
}
System . out . p r i n t l n ( " I am here "+ i i ) ;
i f ( stream . charAt ( i i )== ’   ’ ) { / / Escape sequence
i i ++;
i f ( i i >=stream_size ) {
/ / Escape sequence as l a s t char i s i n v a l i d
ERROR_IN_GRAMMAR( ) ;
}
else i f ( ( non_terminal )&&( stream . charAt ( i i ) ! = ’  n ’ ) ) {
/ / Only escaped newline allowed inside non−terminal
System . out . p r i n t l n ( "ERROR: Escape sequence detected inside non−terminal s
ERROR_IN_GRAMMAR( ) ;
}
i f ( stream . charAt ( i i )== ’  ’ ’ ) { / / Single quote
currentChar= ’  ’ ’ ;
}
else i f ( stream . charAt ( i i )== ’  " ’ ) { / / Double quote
currentChar= ’  " ’ ;
}
else i f ( stream . charAt ( i i )== ’   ’ ) { / / Backslash
currentChar= ’   ’ ;
}
else i f ( stream . charAt ( i i )== ’0 ’ ) { / / Null character
currentChar= ’ 0 ’ ;
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR IX
/ / else i f ( stream . charAt ( i i )== ’a ’ ) { / / Audible b e l l
/ / currentChar = ’ a ’ ;
/ / }
else i f ( stream . charAt ( i i )== ’b ’ ) { / / Backspace
currentChar= ’  b ’ ;
}
else i f ( stream . charAt ( i i )== ’ f ’ ) { / / Formfeed
currentChar= ’  f ’ ;
}
else i f ( stream . charAt ( i i )== ’n ’ ) { / / Newline
currentChar= ’  n ’ ;
}
else i f ( stream . charAt ( i i )== ’ r ’ ) { / / Carriage return
currentChar= ’  r ’ ;
}
else i f ( stream . charAt ( i i )== ’ t ’ ) { / / Horizontal tab
currentChar= ’  t ’ ;
}
/ / else i f ( stream [ i i ]== ’ v ’ ) { / / V e r t i c a l tab
/ / currentChar = ’ v ’ ;
/ / }
else i f ( stream . charAt ( i i )== ’  n ’ ) { / / Escaped newline
/ / Ignore newline
skip=true ;
}
else i f ( stream . charAt ( i i )== ’  r ’ ) { / / Escaped DOS return
/ / Ignore newline
skip=true ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR X
i f ( stream . charAt (++ i i ) ! = ’  n ’ ) {
System . out . p r i n t l n ( "ERROR:   r character not followed by   n . " ) ;
ERROR_IN_GRAMMAR( ) ;
}
}
else { / / Normal character
currentChar=stream . charAt ( i i ) ;
}
i f ( ( ! skip )&&(pass >1)){
i f ( currentBuffer . length ()==0){
newSymbol . setType ( SymbolType . TSymbol ) ;
}
i f ( currentBuffer . length ()==0){
currentBuffer =Character . t oS tr ing ( currentChar ) ;
}
else {
/ / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ;
currentBuffer +=currentChar ;
}
}
}
else {
switch ( state ) {
case (START) :
i f ( currentChar== ’  r ’ ) {
break ; / / Ignore DOS newline f i r s t char
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XI
switch ( currentChar ) {
case ’ ’ : / / Ignore whitespaces
case ’  t ’ : / / Ignore tabs
case ’  n ’ : / / Ignore newlines
break ;
case ’< ’ : / / START OF RULE
newSymbol . setType ( SymbolType . NTSymbol ) ;
i f ( currentBuffer . length ()==0){
currentBuffer =Character . t oS tr in g ( currentChar ) ;
}
else {
/ / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ;
currentBuffer +=currentChar ;
}
state=START_RULE;
break ;
default : / / I l l i g a l
System . out . p r i n t l n ( "ERROR: Character "+ currentChar + " caused an erro
ERROR_IN_GRAMMAR( ) ;
}
break ;
case (START_RULE ) : / / Read the lhs Non−terminal symbol
i f ( currentChar== ’  r ’ ) {
break ; / / Ignore DOS newline f i r s t char
}
switch ( currentChar ) {
case ’  n ’ : / / Newlines are i l l i g a l here
System . out . p r i n t l n ( "ERROR: Newline inside non−terminal . " ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XII
ERROR_IN_GRAMMAR( ) ;
break ;
case ’> ’ : / / Possible end of non−terminal symbol
i f ( currentBuffer . length ()==0){
currentBuffer =Character . t oS tr ing ( currentChar ) ;
}
else {
/ / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ;
currentBuffer +=currentChar ;
}
newSymbol . setSymbol ( currentBuffer ) ;
/ / newSymbol . setType ( SymbolType . NTSymbol ) ; / / t h i s was added a d i l
i f ( pass ==1){
/ / F i r s t pass
/ / Check i f new symbol d e f i n i t i o n
/ / insertRule = ! ( findRule ( newSymbol ) ) ;
Rule tmpRulePtr=null ;
try {
tmpRulePtr=findRule ( newSymbol ) ;
}
catch ( Exception e ) {
/ / do nothing
}
i f ( tmpRulePtr==null )
insertRule=true ;
else
insertRule=false ;
i f ( insertRule ) {
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XIII
/ / Create new rule f o r symbol
newRule . clear ( ) ;
try {
newRule . lhs . add (new Symbol ( newSymbol ) ) ;
}
catch ( java . lang . Exception e ) {
System . out . p r i n t l n ( e + " newRule sucks " ) ;
}
/ / Add to grammar
try {
nonTerminals . add ( newRule . lhs . get ( newRule . lhs . size () −1));
}
catch ( java . lang . NullPointerException e ) {
System . out . p r i n t l n ( e+ " nonTerminals suck " ) ;
}
}
else { / / Existing symbol , do nothing
}
}
else {
/ / Second pass
/ / Point currentRule to previously defined rule
try {
i f ( ( currentRule=findRule ( newSymbol))== null ) {
System . out . p r i n t l n ( "ERROR: Grammar changed between parser pass
ERROR_IN_GRAMMAR( ) ;
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XIV
}
catch ( java . lang . NullPointerException e ) {
System . out . p r i n t l n ( e+"ERROR: Grammar changed between parser passes
ERROR_IN_GRAMMAR( ) ;
}
catch ( java . lang . Exception e ) {
System . out . p r i n t l n ( e+"ERROR: Grammar changed between parser passes
}
/ / i f ( ( currentRule=findRule ( newSymbol))== n u l l ) {
/ / System . out . p r i n t l n ( "ERROR: Grammar changed between parser pa
/ / ERROR_IN_GRAMMAR( ) ;
/ / }
}
/ / Reset the buffer
currentBuffer =" " ;
/ / lhs f o r t h i s rule has been read
state=LHS_READ;
break ;
default : / / Check f o r non−escaped special characters
i f ( ( ( currentChar== ’ " ’ ) | | ( currentChar== ’ | ’ ) | | ( currentChar== ’< ’ ) ) ) {
System . out . p r i n t l n ( "ERROR: I n v a l i d character ’ " + currentChar + "
ERROR_IN_GRAMMAR( ) ;
}
i f ( currentBuffer . length ()==0){
currentBuffer =Character . t oS tr ing ( currentChar ) ;
}
else {
/ / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XV
currentBuffer +=currentChar ;
}
}
break ;
case (LHS_READ) : / / Must read : : = token
i f ( currentChar== ’  r ’ ) {
break ; / / Ignore DOS newline f i r s t char
}
switch ( currentChar ) {
case ’ ’ : / / Ignore whitespaces
case ’  t ’ : / / Ignore tabs
case ’  n ’ : / / Ignore newlines
break ;
case ’ : ’ : / / Part of : : = token
i f ( currentBuffer . length ()==0){
currentBuffer =Character . t oS tr in g ( currentChar ) ;
}
else {
/ / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ;
currentBuffer +=currentChar ;
}
break ;
case ’= ’ : / / Should be end of : : = token
try {
i f ( currentBuffer . length ()==0){
currentBuffer =Character . t oS tr ing ( currentChar ) ;
}
else {
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XVI
/ / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ;
currentBuffer +=currentChar ;
}
/ / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ;
}
catch ( java . lang . NullPointerException e ) {
System . out . p r i n t l n ( e ) ;
}
i f ( currentBuffer . equals ( " : : = " )== false ) { / / Something other than : : = was
System . out . p r i n t l n ( "ERROR: Token ’ " + currentBuffer + " ’ cause
ERROR_IN_GRAMMAR( ) ;
}
/ / Reset the buffer
currentBuffer =" " ;
/ / START OF PRODUCTION
newProduction . clear ( ) ;
state=PRODUCTION;
break ;
default : / / I l l i g a l
System . out . p r i n t l n ( "ERROR: Character ’ " + currentChar + " ’ caused an e
ERROR_IN_GRAMMAR( ) ;
}
break ;
case (PRODUCTION) : / / Read everything u n t i l | token or  n , or EOL
i f ( currentChar== ’  r ’ ) {
break ; / / Ignore DOS newline f i r s t char
}
i f ( pass ==1){
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XVII
i f ( currentChar== ’  n ’ )
state=START_OF_LINE;
}
else switch ( currentChar ) {
case ’ | ’ : / / Possible end of production
i f ( quoted ) { / / Normal character
/ / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ;
i f ( currentBuffer . length ()==0){
currentBuffer =Character . t oS tr ing ( currentChar ) ;
}
else {
currentBuffer +=currentChar ;
}
break ;
}
case ’  n ’ : / / End of production ( and possibly rule )
/ / Reset separator marker
separated =0;
i f ( ( currentBuffer . length ( ) ! = 0 ) | | ( newProduction . size ( ) ! = 0 ) ) { / / The
System . out . p r i n t l n ( "A symbol ’ " + currentBuffer + " ’ " + newSym
i f ( currentBuffer . length ()==0){
/ / No symbol exists ; create terminal empty symbol
newSymbol . setType ( SymbolType . TSymbol ) ;
}
i f ( non_terminal ) { / / Current non−terminal symbol isn ’ t f in is hed
System . out . p r i n t l n ( "ERROR: Symbol ’ " + currentBuffer + " ’ caus
ERROR_IN_GRAMMAR( ) ;
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XVIII
newSymbol . setSymbol ( currentBuffer ) ;
i f ( newSymbol . getType ( ) . t oSt ri ng ( ) . equals ( "NTSymbol" ) ) {
/ / Find rule that defines t h i s symbol
Rule tempRule=null ;
try {
tempRule=findRule ( newSymbol ) ;
}
catch ( Exception e ) {
/ / do nothing again
}
i f ( tempRule != null ) {
newProduction . add (new Symbol ( tempRule . lhs . get ( tempRule . lhs
}
else {
/ / Undefined symbol , i n s e r t anyway
newProduction . add (new Symbol ( newSymbol ) ) ;
}
}
else { / / Add terminal symbol
newProduction . add (new Symbol ( newSymbol ) ) ;
}
/ / Reset the symbol
/ / newSymbol . clear ( ) ; / / t h i s i s not required , the garbage c o l l e c t o r does
newSymbol . clear ( ) ;
}
else { / / Empty token ; ignored
;
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XIX
/ / END OF PRODUCTION
/ / Add production to current rule
try {
currentRule . add (new Production ( newProduction ) ) ;
}
catch ( Exception e ) {
System . out . p r i n t l n ( e+" But the currentRule i s n u l l . . . i t sucks too "
}
/ / Reset the buffer
currentBuffer =" " ;
i f ( currentChar== ’  n ’ )
state=START_OF_LINE;
else {
/ / START OF PRODUCTION
newProduction . clear ( ) ;
}
break ;
case ’< ’ : / / Possible s t a r t of non−terminal symbol
case ’> ’ : / / Possible end of non−terminal symbol
case ’ ’ : / / Possible token separator
case ’  t ’ : / / Possible token separator
i f ( ( quoted ) / / Normal character
| | ( ( ( currentChar== ’ ’ ) | | ( currentChar== ’  t ’ ))&&( non_terminal ) ) ) { / / Spaces i
i f ( currentBuffer . length ()==0){
currentBuffer =Character . t oS tr in g ( currentChar ) ;
}
else {
/ / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XX
currentBuffer +=currentChar ;
}
i f ( ! non_terminal ) newSymbol . setType ( SymbolType . TSymbol ) ;
break ;
}
i f ( currentChar== ’> ’ ) { / / This i s also the end of a non−terminal symbol
i f ( currentBuffer . length ()==0){
currentBuffer =Character . t oS tr ing ( currentChar ) ;
}
else {
/ / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ;
currentBuffer +=currentChar ;
}
non_terminal=false ;
}
i f ( currentBuffer . length () >0){
i f ( non_terminal ) { / / Current non−terminal symbol isn ’ t f in is hed
System . out . p r i n t l n ( "ERROR: Symbol " + currentBuffer + " ’ caused an
ERROR_IN_GRAMMAR( ) ;
}
i f ( ( currentChar== ’ ’ ) | | ( currentChar== ’  t ’ ) ) { / / Token separator
separated =1;
}
newSymbol . setSymbol ( currentBuffer ) ;
i f ( newSymbol . getType ( ) . to St ri ng ( ) . equals ( "NTSymbol" ) ) {
/ / Find rule that defines t h i s symbol
Rule tempRule=null ;
try {
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XXI
tempRule=findRule ( newSymbol ) ;
}
catch ( java . lang . Exception e ) {
System . out . p r i n t l n ( e+" Finding the rule sucks . . . " ) ;
}
i f ( tempRule != null ) {
newProduction . add (new Symbol ( tempRule . lhs . get ( tempRule . lhs . siz
}
else {
/ / Undefined symbol , i n s e r t anyway
newProduction . add (new Symbol ( newSymbol ) ) ;
}
}
else { / / Add terminal symbol
newProduction . add (new Symbol ( newSymbol ) ) ;
}
/ / Reset the symbol
newSymbol . clear ( ) ;
}
else { / / Empty buffer
i f ( ( ( currentChar== ’ ’ ) | | ( currentChar== ’  t ’ ) ) / / Token separator
&&(newProduction . size ( ) > 0 ) ) {
/ / Probably a token separator a f t e r a non−terminal symbol
separated =1;
}
}
/ / Reset the buffer
currentBuffer =" " ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XXII
i f ( currentChar== ’< ’ ) { / / This i s also the s t a r t of a non−terminal symbol
/ / Special case ; must create new Symbol here
newSymbol . clear ( ) ;
newSymbol . setType ( SymbolType . NTSymbol ) ;
i f ( currentBuffer . length ()==0){
currentBuffer =Character . t oS tr ing ( currentChar ) ;
}
else {
/ / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ;
currentBuffer +=currentChar ;
}
non_terminal=true ; / / Now reading a non−terminal symbol
i f ( separated ! = 0 ) { / / I n s e r t a token separator
separated =0;
newTokenSeparator=new Symbol ( ) ;
newTokenSeparator . setSymbol ( " " ) ;
newTokenSeparator . setType ( SymbolType . TSymbol ) ;
newProduction . add (new Symbol ( newTokenSeparator ) ) ;
}
}
break ;
default : / / Add character to current buffer
i f ( separated ! = 0 ) { / / I n s e r t a token separator
separated =0;
newTokenSeparator=new Symbol ( ) ;
newTokenSeparator . setSymbol ( " " ) ;
newTokenSeparator . setType ( SymbolType . TSymbol ) ;
newProduction . add (new Symbol ( newTokenSeparator ) ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XXIII
}
i f ( currentChar== ’ " ’ ) { / / Start ( or end ) quoted section
quoted =! quoted ;
newSymbol . setType ( SymbolType . TSymbol ) ;
break ;
}
i f ( currentBuffer . length ()==0){
newSymbol . setType ( SymbolType . TSymbol ) ;
}
i f ( currentBuffer . length ()==0){
currentBuffer =Character . t oS tr ing ( currentChar ) ;
}
else {
/ / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ;
currentBuffer +=currentChar ;
}
}
break ;
case (START_OF_LINE ) :
i f ( currentChar== ’  r ’ ) {
break ; / / Ignore DOS newline f i r s t char
}
switch ( currentChar ) {
case ’ ’ : / / Ignore whitespaces
case ’  t ’ : / / Ignore tabs
case ’  n ’ : / / Ignore newlines
break ;
case ’ | ’ : / / Start of new production
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XXIV
state=PRODUCTION;
i f ( pass ==2){
/ / START OF PRODUCTION
newProduction . clear ( ) ;
}
break ;
case ’< ’ : / / Start of lhs non−terminal symbol
/ / END OF RULE
i f ( pass ==1){
/ / Add current rule
i f ( insertRule ) {
try {
this . add (new Rule ( newRule ) ) ;
}
catch ( java . lang . NullPointerException e ) {
System . out . p r i n t l n ( e ) ;
}
}
}
/ / START OF RULE
newSymbol . setType ( SymbolType . NTSymbol ) ;
i f ( currentBuffer . length ()==0){
currentBuffer =Character . t oS tr ing ( currentChar ) ;
}
else {
/ / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ;
currentBuffer +=currentChar ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XXV
}
state=START_RULE;
break ;
default : / / I l l i g a l
System . out . p r i n t l n ( "ERROR: Detected l i n e s t a r t i n g with terminal symbol . " ) ;
ERROR_IN_GRAMMAR( ) ;
}
break ;
default : / / Impossible error , q u i t the program now !
System . out . p r i n t l n ( " I n t e r n a l error .  nPlease report error ’ Impossible state in
System . e x i t ( 0 ) ;
}
}
skip=false ;
i i ++;
}
/ / END OF PASS
i f ( state !=START_OF_LINE ) { / / This must be the state of the parser
System . out . p r i n t l n ( " Parsing error reading grammar . " ) ;
ERROR_IN_GRAMMAR( ) ;
}
i f ( pass ==1){
/ / Add current rule
i f ( insertRule ) {
this . add (new Rule ( newRule ) ) ;
}
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XXVI
}
updateRuleFields ( ) ;
setValidGrammar ( true ) ;
genotype2phenotype ( ) ;
return true ;
}
/∗∗
∗ Reads in the BNF grammar−part specified by i t s argument text , and adds i t to
∗the current grammar . Returns true i f loading of new grammar part was
∗successful , false otherwise .
∗/
public boolean addBNFString ( f i n a l String stream ) {
/ / FIXME Slow implementation .
/ / Copy current grammar
ArrayList <Rule> grammarCopy=this ;
/ / Create appended grammar s t r i n g
String newGrammarStream=outputBNF ( ) ;
String newGrammar=new String ( newGrammarStream ) ;
newGrammar=stream ;
/ / Read new grammar
try {
i f ( ! readBNFString (newGrammar ) ) {
/ / Restore previous state of Mapper
readBNFString ( newGrammarStream ) ;
return false ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XXVII
}
return true ;
}
catch ( java . lang . Exception e ) {
return false ;
}
}
/∗∗
∗ Pretty p r i n t the current BNF grammar .
∗/
public String outputBNF ( ) {
String stream=null ;
i f ( ! getValidGrammar ( ) ) {
return null ;
}
I t e r a t o r <Rule> r _ i t =this . i t e r a t o r ( ) ;
while ( r _ i t . hasNext ( ) ) {
Rule tmp ;
tmp= r _ i t . next ( ) ;
stream . concat ( tmp . lhs . get ( tmp . lhs . size () −1). getSymbol ( ) + " : : = " ) ;
/ / go through productions
I t e r a t o r <Production > p _ i t =tmp . i t e r a t o r ( ) ;
while ( p _ i t . hasNext ( ) ) {
/ / go through symbols
I t e r a t o r <Symbol> s _ i t = p _ i t . next ( ) . i t e r a t o r ( ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XXVIII
while ( s _ i t . hasNext ( ) ) {
stream . concat ( s _ i t . next ( ) . getSymbol ( ) ) ;
}
stream . concat ( " | " ) ;
}
stream=stream . trim ( ) ;
stream . concat ( "  n" ) ;
/ / get next rule
}
return stream ;
}
/∗∗
∗ Returns the address of the rule defining the argument non−terminal symbol ,
∗ i f i t exists ; otherwise returns NULL.
∗/
public Rule findRule ( f i n a l Symbol nonterminal ) throws Exception {
I t e r a t o r <Rule> r u l e I t =this . i t e r a t o r ( ) ;
Rule tmp ;
while ( r u l e I t . hasNext ( ) ) {
tmp= r u l e I t . next ( ) ;
i f ( tmp . lhs . get ( tmp . lhs . size () −1).makeComparison ( nonterminal ) )
return tmp ;
}
return null ;
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XXIX
/∗∗
∗Returns the calculated recursive nature of the Rule passed as argument ,
∗and updates i t s minimum mapping depth ( minimumDepth )
∗/
private boolean isRecursive ( ArrayList <Symbol> visitedRules , Rule currentRule ) {
I t e r a t o r <Production > prodIt =currentRule . i t e r a t o r ( ) ;
I t e r a t o r <Symbol> symbIt ;
I t e r a t o r <Symbol> v i s i t e d R u l e s I t =visitedRules . i t e r a t o r ( ) ;
Rule r u l e P t r =null ;
boolean r e s u l t ;
/ / DON’T DO IT − otherwise minimumDepth i s not updated properly
/ / I f t h i s rule has already been labeled , e x i t
/ / i f ( currentRule−>getRecursive ( ) ! = SI_Undef ) {
/ / return currentRule−>getRecursive ( ) ;
/ / }
/ / Check i f t h i s i s a recursive c a l l to a previously v i s i t e d rule
while ( v i s i t e d R u l e s I t . hasNext ( ) ) {
i f ( v i s i t e d R u l e s I t . next ( ) . makeComparison ( currentRule . lhs . get ( currentRule . lhs . si
currentRule . setRecursive ( true ) ;
return true ;
}
}
/ / Go through each production in the rule
while ( prodIt . hasNext ( ) ) {
Production tmp_pd= prodIt . next ( ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XXX
tmp_pd . setMinimumDepth ( 0 ) ;
symbIt=tmp_pd . i t e r a t o r ( ) ;
/ / Go through each symbol in the production
while ( symbIt . hasNext ( ) ) {
Symbol tmp_symb=symbIt . next ( ) ;
i f ( tmp_symb . getType ( ) . to St ri ng ( ) . equals ( "NTSymbol" ) ) { / / Symbol i s non−
try {
r u l e P t r =findRule ( tmp_symb ) ; / / Find defining rule
}
catch ( java . lang . Exception e ) {
/ / do nothing
}
i f ( r u l e P t r != null ) { / / Symbol i s defined
/ / Recursive c a l l
visitedRules . add ( currentRule . lhs . get ( currentRule . lhs . s
r e s u l t =isRecursive ( visitedRules , r u l e P t r ) ;
visitedRules . remove ( visitedRules . size () −1);
i f ( r e s u l t ) { / / Production i s recursive
/ / Mark production as recursive
tmp_pd . setRecursive ( true ) ;
/ / Mark current rule also as recursive
currentRule . setRecursive ( true ) ;
}
i f ( tmp_pd . getMinimumDepth () <( r u l e P t r . getMinimumDepth ( )
tmp_pd . setMinimumDepth ( r u l e P t r . getMinimumDepth
}
}
else { / / Non−defined non−terminal symbols are considered term
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XXXI
i f ( tmp_pd . getMinimumDepth () <1){
tmp_pd . setMinimumDepth ( 1 ) ;
}
}
}
else { / / Terminal symbol
i f ( tmp_pd . getMinimumDepth () <1){
tmp_pd . setMinimumDepth ( 1 ) ;
}
}
}
/ / i f ( prodIt −>getRecursive ()== SI_Undef ) { / / Production i s not recursive
/ / prodIt −>setRecursive ( SI_NonRec ) ;
/ / }
i f ( currentRule . getMinimumDepth () >tmp_pd . getMinimumDepth ( ) ) { / / Update rule mini
currentRule . setMinimumDepth ( tmp_pd . getMinimumDepth ( ) ) ;
}
/ / prodIt ++;
}
/ / i f ( currentRule−>getRecursive ( ) ! = SI_Rec ) { / / Rule i s not recursive , as i t contains no
/ / currentRule−>setRecursive ( SI_NonRec ) ;
/ / return SI_NonRec ;
/ / }
/ / return SI_Rec ;
return currentRule . getRecursive ( ) ;
}
/∗∗
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XXXII
∗ Update recursive and minimumDepth f i e l d s f o r every Rule
∗/
/ / and Production in grammar .
private void updateRuleFields ( ) {
ArrayList <Symbol> visitedRules=new ArrayList ( ) ;
I t e r a t o r <Rule> r u l e I t =this . i t e r a t o r ( ) ;
clearRuleFields ( ) ;
/ / Go through each rule in the grammar
while ( r u l e I t . hasNext ( ) ) {
try {
visitedRules . clear ( ) ;
}
catch ( java . lang . NullPointerException e ) {
System . out . p r i n t l n ( e+" UpdateRuleFields sucks " ) ;
}
Rule tmp_rule= r u l e I t . next ( ) ;
tmp_rule . setRecursive ( isRecursive ( visitedRules , tmp_rule ) ) ;
}
/ / Second pass , to c o r r e c t l y update a l l recursive rules
r u l e I t =this . i t e r a t o r ( ) ;
while ( r u l e I t . hasNext ( ) ) {
try {
visitedRules . clear ( ) ;
}
catch ( java . lang . NullPointerException e ) {
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XXXIII
System . out . p r i n t l n ( e+" UpdateRuleFields sucks " ) ;
}
Rule tmp_rule= r u l e I t . next ( ) ;
tmp_rule . setRecursive ( isRecursive ( visitedRules , tmp_rule ) ) ;
}
}
/∗∗
∗ Update recursive and minimumDepth f i e l d s f o r every Rule
∗/
/ / and Production in grammar .
private void clearRuleFields ( ) {
I t e r a t o r <Rule> r u l e I t =this . i t e r a t o r ( ) ;
/ / Reset minimum depths and recursion f i e l d s
while ( r u l e I t . hasNext ( ) ) {
Rule tmp_rule= r u l e I t . next ( ) ;
tmp_rule . setMinimumDepth(32767 > >1);
tmp_rule . setRecursive ( false ) ;
}
}
/ / ERROR FUNCTION
private boolean ERROR_IN_GRAMMAR( ) {
System . out . p r i n t l n ( "Grammar not loaded ; " ) ;
try {
this . clear ( ) ;
}
catch ( java . lang . NullPointerException e ) {
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
CONTEXT-FREE GRAMMAR XXXIV
System . out . p r i n t l n ( e ) ;
}
setValidGrammar ( false ) ;
try {
phenotype . clear ( ) ;
phenotype . setValid ( false ) ;
}
catch ( java . lang . NullPointerException e ) {
System . out . p r i n t l n ( e ) ;
}
return false ;
}
}
/ / F i r s t implementation i s complete , t h i s f i l e may pose a l o t of bugs .
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR I
/∗
∗ GEGrammar. java
∗
∗ Created on August 2 , 2007, 12:22 AM
∗
∗ To change t h i s template , choose Tools | Template Manager
∗ and open the template in the e d i t o r .
∗/
package GrammaticOptimization ;
/∗∗
∗
∗ @author a d i l r a j a
∗/
import java . u t i l . ∗ ;
import java . u t i l . L i s t I t e r a t o r ;
public class GEGrammar extends CFGrammar {
private int maxWraps ;
protected ArrayList <Production > productions ;
/∗∗
∗ Creates a new instance of GEGrammar
∗/
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR II
public GEGrammar ( ) {
super ( ) ;
setMaxWraps ( 0 ) ;
}
/∗∗
∗Constructor s e t t i n g the genotype s t r u c t u r e of t h i s mapper to newGenotype .
∗/
public GEGrammar( f i n a l Genotype newGenotype ) {
super ( newGenotype ) ;
setMaxWraps ( 0 ) ;
productions=new ArrayList ( ) ;
}
/∗∗
∗Constructor s e t t i n g the phenotype s t r u c t u r e of t h i s mapper to newPhenotype .
∗/
public GEGrammar( f i n a l Phenotype newPhenotype ) {
super ( newPhenotype ) ;
setMaxWraps ( 0 ) ;
}
/∗∗
∗ Copy Constructor .
∗/
public GEGrammar( f i n a l GEGrammar copy ) throws Exception {
super ( copy ) ;
setMaxWraps ( copy . getMaxWraps ( ) ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR III
/ / Call genotype2Phenotype ( ) to regenerate phenotype structure ,
/ / and productions and derivationTree structures .
genotype2phenotype ( true ) ;
}
/∗∗
∗ Return number of maximum allowed wrapping events .
∗/
public f i n a l int getMaxWraps ( ) {
return maxWraps ;
}
/∗∗
∗ Set the new number of maximum allowed wrapping events .
∗/
public void setMaxWraps ( f i n a l int newMaxWraps ) {
maxWraps=newMaxWraps ;
}
/∗∗
∗ Builds the the current d e r i v a t i o n tree , and returns i t s address ;
∗ i f d e r i v a t i o n tree i s impossible to build , returns NULL.
∗/
public f i n a l Tree getTree ( ) throws Exception {
i f ( ( ! getValidGrammar ( ) ) | | ( ! genotype . getValid ( ) ) | | ( getGenotype ( ) . size ( ) ! = 0 ) ) {
return null ;
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR IV
genotype2phenotype ( true ) ;
return this . derivationTree ;
}
/∗∗
∗ Returns a vector of a l l productions used during the mapping process .
∗/
public f i n a l ArrayList <Production > getProductions ( ) throws Exception {
i f ( ( ! getValidGrammar ( ) ) | | ( ! genotype . getValid ( ) ) | | ( getGenotype ( ) . size ( ) ! = 0 ) ) {
return null ;
}
genotype2phenotype ( true ) ;
return productions ;
}
/∗∗
∗ S t r i c t implementation of genotype2Phenotype i n t e r f a c e . Calls l o c a l
∗ genotype2phenotype ( bool ) method , with bool= false .
∗/
public boolean genotype2phenotype ( ) {
/ / t r y {
return genotype2phenotype ( false ) ;
/ / }
/ / catch ( Exception e ) {
/ / System . out . p r i n t l n ( e+" genotype2phenotype ( ) " ) ;
/ / return false ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR V
/ / }
}
/∗∗
∗ Updates the contents of the phenotype structure , based on the current
∗ genotype and the current grammar , and according to the standard GE
∗ mapping process . Returns true upon a successful mapping , and false
∗ otherwise , and also updates the v a l i d f i e l d of the phenotype .
∗ With argument set to true , also updates derivationTree .
∗/
public boolean genotype2phenotype ( f i n a l boolean buildDerivationTree ) {
this . derivationTree=new Tree ( ) ; / / I n i t i a l i z e the tree
boolean returnValue=true ;
int newEffectiveSize =0;
/ / Start by s e t t i n g e f f e c t i v e S i z e to 0
genotype . setEffectiveSize ( newEffectiveSize ) ;
this . phenotype=new Phenotype ( true , 1 ) ;
i f ( ! phenotype . isEmpty ( ) )
phenotype . clear ( ) ;
i f ( buildDerivationTree ) {
this . productions . clear ( ) ;
}
/ / Quick safety checks
/ / i f ( ( ! getValidGrammar ( ) ) | | ( ! genotype . getValid ( ) ) | | ( ! getGenotype()−> size ( ) ) ) {
i f ( ! getValidGrammar ( ) ) {
phenotype . clear ( ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR VI
phenotype . setValid ( false ) ;
return false ;
}
/ / Wraps counter and nonterminals stack
int wraps =0;
Stack <Symbol> nonterminals=new Stack ( ) ;
/ / I t e r a t o r s
I t e r a t o r <Rule> r u l e I t ;
L i s t I t e r a t o r <Production > prodIt ;
I t e r a t o r <Integer > genoIt=genotype . i t e r a t o r ( ) ;
Integer tmpInt ; / / s h a l l contain the values in Genotype
/ / Start with the s t a r t symbol
nonterminals . push ( getStartSymbol ( ) ) ;
i f ( buildDerivationTree ) {
/ / Use s t a r t symbol as the derivationTree node
try {
derivationTree . setData ( getStartSymbol ( ) ) ;
}
catch ( java . lang . NullPointerException e ) {
System . out . p r i n t l n ( e+" The c a l l : derivationTree . setData ( getStartSymbol ( ) ) ; in
}
}
boolean gotToUseWrap=true ;
Integer codonGenoIt=new Integer ( genoIt . next ( ) . intValue ( ) ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR VII
/ / Get r i d of a l l non−terminal symbols
while ( ( ! nonterminals . empty ())&&( wraps<=getMaxWraps ( ) ) ) {
/ / Do a mapping step
switch ( genotype2phenotypeStep ( nonterminals , codonGenoIt , buildDerivationTree ) )
case −1:returnValue=false ;
break ;
case 0: ;
break ;
case 1: codonGenoIt=new Integer ( genoIt . next ( ) . intValue ( ) ) ;
/ / genoIt ++;
newEffectiveSize ++;
i f ( gotToUseWrap ) {
wraps++;
gotToUseWrap=false ;
}
/ / Check i f wrap i s needed
i f ( ! genoIt . hasNext ( ) ) {
/ / newEffectiveSize+=genotype . size ( ) ;
genoIt=genotype . i t e r a t o r ( ) ;
codonGenoIt=new Integer ( genoIt . next ( ) . intValue ( ) ) ;
gotToUseWrap=true ;
}
break ;
default : System . out . p r i n t l n ( " I n t e r n a l error in genotype2Phenotype ( ) " ) ;
System . out . p r i n t l n ( " Execution aborted . " ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR VIII
System . e x i t ( 0 ) ;
}
}
/ / newEffectiveSize +=( genoIt−genotype . begin ( ) ) ;
/ / Was the mapping successful?
i f ( ( wraps>getMaxWraps ( ) ) | | ( ! nonterminals . empty ( ) ) ) {
returnValue=false ;
/ / Add remaining symbols in nonterminals queue to phenotype
while ( ! nonterminals . empty ( ) ) {
phenotype . add ( nonterminals . pop ( ) ) ;
}
}
phenotype . setValid ( returnValue ) ;
genotype . setEffectiveSize ( newEffectiveSize ) ;
genotype . setWraps ( wraps ) ;
/ / Now build d e r i v a t i o n tree , based on productions vector
i f ( buildDerivationTree ) {
derivationTree . clear ( ) ;
derivationTree . setData ( getStartSymbol ( ) ) ;
derivationTree . setCurrentLevel ( 1 ) ;
derivationTree . setDepth ( 1 ) ;
prodIt =productions . l i s t I t e r a t o r ( ) ; / / something wrong here
buildDTree ( derivationTree , prodIt ) ;
}
return returnValue ;
}
/∗∗
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR IX
∗ Updates the contents of the genotype structure , based on the current
∗ phenotype and the current grammar , and according to a mapping process
∗ corresponding to the inverse of the standard GE mapping process .
∗ Returns true upon a successful inverse mapping , and false otherwise .
∗/
public boolean phenotype2genotype ( ) {
return false ;
/ / FIXME
}
/∗∗
∗ Performs one step of the mapping process , that is , maps the next
∗non−terminal symbol on the nonterminals stack passed as argument , using the
∗codon at the pos it io n pointed by genoIt .
∗Returns number of codons consumed , −1 i f not successful
∗/
public int genotype2phenotypeStep ( Stack <Symbol> nonterminals , Integer codonGenoIt , boolean bu
L i s t I t e r a t o r <Production > prodIt ;
int returnValue=−1;
/ / Find the rule f o r the current non−terminal
Rule r u l e P t r =null ;
try {
r u l e P t r =findRule ( nonterminals . peek ( ) ) ;
}
catch ( java . lang . Exception e ) {
System . out . p r i n t l n ( e+" genotype2phenotypeStep ( ) s r u l e P t r sucks " ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR X
}
/ / cerr << " mapping " << ∗( nonterminals . top ( ) ) << " with " << ∗genoIt << "  n " ;
i f ( r u l e P t r ==null ) { / / Undefined symbol − could be an extension symbol
try {
i f ( nonterminals . peek ( ) . getSymbol ( ) . startsWith ( "<GECodonValue" )&&( codonGenoIt !=
/ / I n s e r t codon value
/ / Extract range f o r value from non−terminal s p e c i f i c a t i o n
int low =0 , high=−1,pointer ="<GECodonValue" . length ( ) ;
/ / currentChar i s the f i r s t character a f t e r "<GECodonValue"
char currentChar=nonterminals . peek ( ) . getSymbol ( ) . substring ( pointer , po
/ / Look f o r range d e f i n i t i o n s
while ( Character . to St ri ng ( currentChar ) . compareTo ( ">" ) ! = 0 ) {
i f ( Character . t oSt ri ng ( currentChar ) . compareTo ( "−" )==0){
/ / Low range s p e c i f i c a t i o n
currentChar=nonterminals . peek ( ) . getSymbol ( ) . substring (
while ( Character . i s D i g i t ( currentChar ) ) {
low =( low ∗10)+( currentChar−’0 ’ ) ;
currentChar=nonterminals . peek ( ) . getSymbol ( ) . s
}
}
else i f ( Character . t oSt ri ng ( currentChar ) . compareTo ( "+" )==0){
/ / High range s p e c i f i c a t i o n
currentChar=nonterminals . peek ( ) . toS tr in g ( ) . substring (+
while ( Character . i s D i g i t ( currentChar ) ) {
i f ( high==−1){
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR XI
high =0;
}
high =( high ∗10)+( currentChar−’0 ’ ) ;
currentChar=nonterminals . peek ( ) . toS tr in g ( ) . su
}
}
else { / / Ignore errors
currentChar=nonterminals . peek ( ) . toS tr in g ( ) . substring (+
}
}
/ / High range was not specified , so set i t to maximum
i f ( high==−1){
high=genotype . getMaxCodonValue ( ) ;
}
/ / Remove non−terminal
nonterminals . pop ( ) ;
/ / P r i n t value onto " codon "
String codon ;
i f ( high==low ) {
/ / Catch d i v i s i o n by zero
codon=Integer . toS tr in g ( low ) ;
}
else {
codon=Integer . toS tr in g ( codonGenoIt . intValue ()%( high−low+1)+low
}
/ / I n s e r t symbol with value onto phenotype
phenotype . add (new Symbol ( codon , null ) ) ;
returnValue =1;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR XII
}
else {
/ / Unknown symbol or special symbol that requires non−empty genotype
/ / Include symbol on phenotype
phenotype . add ( nonterminals . pop ( ) ) ;
/ / Remove non−terminal
/ / nonterminals . pop ( ) ;
/ / I n v a l i d a t e mapping
returnValue=−1;
}
}
catch ( java . lang . NullPointerException e ) {
System . out . p r i n t l n ( e ) ;
}
}
/ / else i f ( rulePtr −>getMinimumDepth() >=INT_MAX> >1){// Stuck on recursive rule
/ / Allow recursive rules , but only i f they consume a codon
else i f ( ( r u l e P t r . getMinimumDepth() >=(32767 > >1)) / / Stuck on recursive rule
&&( r u l e P t r . size () <=1)){ / / No codon w i l l be consumed
/ / Include symbol on phenotype
phenotype . add ( nonterminals . pop ( ) ) ;
/ / Remove non−terminal
/ / nonterminals . pop ( ) ;
/ / I n v a l i d a t e mapping
returnValue=−1;
}
else {
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR XIII
/ / Remove non−terminal
nonterminals . pop ( ) ;
/ / Choose production
i f ( codonGenoIt==null&&r u l e P t r . size () >1){
/ / Empty genotype , but symbol requires choice
/ / Include symbol on phenotype
phenotype . add ( r u l e P t r . lhs . get ( 0 ) ) ;
/ / I n v a l i d a t e mapping
returnValue=−1;
}
else {
i f ( codonGenoIt==null ) { / / Empty genotype
prodIt = r u l e P t r . l i s t I t e r a t o r ( 0 ) ;
}
else {
prodIt = r u l e P t r . l i s t I t e r a t o r ( 0 ) ;
int tmp=0;
tmp=codonGenoIt . intValue ()% r u l e P t r . size ( ) ;
for ( int i =0; i <tmp ; i ++)
prodIt . next ( ) ;
/ / i f ( prodIt . hasPrevious ( ) )
/ / prodIt . previous ( ) ;
}
/ / Place production on productions vector
Production tmpProd= prodIt . next ( ) ;
i f ( buildDerivationTree ) {
productions . add ( tmpProd ) ; / / tmpProd i s also used l a t t e r
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR XIV
/ / Put a l l terminal symbols at s t a r t of production onto phenotype
int s_start =0;
int s_stop =0;
try {
s_stop=tmpProd . size ( ) ; / / Instead of prodIt . size ( ) ;
}
catch ( java . lang . NullPointerException e ) {
System . out . p r i n t l n ( e+" tmpProd i s n u l l in GEGrammar" ) ;
}
while ( ( s_start <s_stop)&&tmpProd . get ( s_start ) . getType ( ) . to Str in g ( ) . com
phenotype . add ( tmpProd . get ( s_start ++));
/ / s_start ++;
}
/ / Push a l l remaining symbols from production onto nonterminals queue
for ( ; s_stop > s_start ; s_stop−−){
nonterminals . push ( tmpProd . get ( s_stop −1));
}
/ / 0 or 1 choice f o r current rule , didn ’ t consume genotype codon
i f ( r u l e P t r . size () <=1){
returnValue =0;
}
else {
returnValue =1;
}
}
}
i f ( phenotype==null ) System . out . p r i n t l n ( " Phenotype i s messy" ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR XV
/ / Finally , pop a l l terminal symbols on top of stack and i n s e r t onto phenotype
/ / t r y {
while ( true ) {
try {
i f ( ( nonterminals . empty ( ) ) | | ( ! nonterminals . peek ( ) . getType ( ) . to St rin g ( ) . equals
break ;
}
phenotype . add ( nonterminals . pop ( ) ) ;
}
catch ( java . lang . NullPointerException e ) {
System . out . p r i n t l n ( e+" The whileloop at the end of genotype2phenotypeStep suck
System . e x i t ( 0 ) ;
}
catch ( java . u t i l . EmptyStackException e ) {
System . out . p r i n t l n ( e+" GEGrammar sucks . . . Stack i s empty " ) ;
System . e x i t ( 0 ) ;
}
}
/ / }
/ / catch ( java . lang . NullPointerException e ) {
/ / System . out . p r i n t l n ( e+" The whileloop at the end of genotype2phenotypeStep sucks
/ / }
return returnValue ;
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR XVI
/∗∗
∗ Builds the d e r i v a t i o n tree , based on the productions vector .
∗Arguments are current tree node , and i t e r a t o r on productions vector .
∗/
public void buildDTree ( Tree currentNode , L i s t I t e r a t o r <Production > prodIt ) {
/ / I f current symbol i s not a non−terminal , or i f a l l productions have been treated
i f ( currentNode . getData ( ) . getType ( ) . t oS tri ng ( ) . compareTo ( "NTSymbol" ) ! = 0 | | ! prodIt . hasNe
/ / Correct productions i t e r a t o r , as no production was read from i t
prodIt . previous ( ) ;
return ;
}
/ / Create new tree l e v e l
I t e r a t o r <Symbol> symbIt= prodIt . next ( ) . i t e r a t o r ( ) ; ;
while ( symbIt . hasNext ( ) ) {
currentNode . add (new Tree ( symbIt . next ( ) , currentNode . getCurrentLevel ()+1 , curre
/ / symbIt ++;
}
/ / Expand each c h i l d node
I t e r a t o r <Tree> t r e e I t =currentNode . i t e r a t o r ( ) ;
while ( t r e e I t . hasNext ( ) ) {
try {
buildDTree ( t r e e I t . next ( ) , prodIt ) ;
/ / prodIt . next ( ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
GE GRAMMAR XVII
}
catch ( java . u t i l . NoSuchElementException e ) {
System . out . p r i n t l n ( e+" The l a s t l i n e s of buildTree suck " ) ;
System . e x i t ( 0 ) ;
}
/ / t r e e I t ++;
}
}
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
BACKUS NAUR FORM I
<expr > : : = mymul(<expr > , <expr >) | mysub(<expr > , <expr >) | myadd(<expr > , <expr >) | pdiv (<expr >
| (<expr >)
| sin (<expr >) | cos(<expr >) | tan (<expr >) | exp(<expr >)
| x | y | 1.000 | <const> | −<const>
<const> : : = 0. < d i g i t >< d i g i t >< d i g i t >
< d i g i t > : : = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
PRODUCTION I
/∗
∗ Production . java
∗
∗ Created on June 3 , 2007, 12:24 AM
∗
∗ To change t h i s template , choose Tools | Template Manager
∗ and open the template in the e d i t o r .
∗/
/∗∗
∗
∗ @author a d i l r a j a
∗/
package GrammaticOptimization ;
import java . u t i l . ∗ ;
import java . u t i l . ArrayList ;
import java . u t i l . I t e r a t o r ;
public class Production extends ArrayList <Symbol >{
private boolean recursive ;
private int minimumDepth ;
/∗∗
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
PRODUCTION II
∗Creates a new production with newLength elements
∗/
public Production ( f i n a l int newLength ) {
super ( ) ;
this . ensureCapacity ( newLength ) ;
setRecursive ( false ) ;
setMinimumDepth(32767 > >1);
}
/∗∗
∗Copy constructor ; copy a l l symbols
∗/
public Production ( f i n a l Production copy ) {
I t e r a t o r <Symbol> i t r = copy . i t e r a t o r ( ) ;
while ( i t r . hasNext ( ) ) {
Symbol tmpsymb= i t r . next ( ) ;
i f ( tmpsymb . getType ( ) . to St ri ng ( ) . compareTo ( " TSymbol " )==0){
this . add (new Symbol ( tmpsymb ) ) ; / / Terminal symbol , create new one
}
else
this . add ( tmpsymb ) ;
}
setRecursive ( copy . recursive ) ;
setMinimumDepth ( copy . minimumDepth ) ;
}
/∗∗
∗Delete a l l terminal symbols and a l l symbol references
∗/
public void clearTerminals ( ) {
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
PRODUCTION III
I t e r a t o r <Symbol> i t r = this . i t e r a t o r ( ) ;
while ( i t r . hasNext ( ) ) {
Symbol tmpsymb= i t r . next ( ) ;
i f ( tmpsymb . getType ( ) . to St ri ng ( ) . compareTo ( " TSymbol " )==0){
this . remove ( tmpsymb ) ;
}
}
}
/∗∗
∗Return the recursive nature of t h i s production
∗/
public f i n a l boolean getRecursive ( ) {
return this . recursive ;
}
/∗∗
∗Update the recursive nature of t h i s production
∗/
public void setRecursive ( f i n a l boolean newRecursive ) {
this . recursive=newRecursive ;
}
/∗∗
∗Return the minimum mapping depth of t h i s production
∗/
public f i n a l int getMinimumDepth ( ) {
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
PRODUCTION IV
return this . minimumDepth ;
}
/∗∗
∗Update the minimum mapping depth of t h i s production
∗/
public void setMinimumDepth ( f i n a l int newMinimumDepth ) {
this . minimumDepth=newMinimumDepth ;
}
/∗∗
∗P r i n t the contents of t h i s production
∗/
/∗∗
∗This removes and adds a symbol at a p a r t i c u l a r l oc at io n in t h i s object . To be called l a
∗/
public void insertSymbol ( f i n a l Symbol symb , int pos ) {
this . remove ( pos ) ;
this . add ( pos , symb ) ;
}
}
/ / f i l e complete
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
RULE I
/∗
∗ Rule . java
∗
∗ Created on June 21 , 2007, 12:06 PM
∗
∗ To change t h i s template , choose Tools | Template Manager
∗ and open the template in the e d i t o r .
∗/
package GrammaticOptimization ;
/∗∗
∗
∗ @author a d i l r a j a
∗/
import java . u t i l . ∗ ;
import java . u t i l . ArrayList ; / / The l e f t −hand side of the rule
public class Rule extends ArrayList <Production >{
private boolean recursive ; / / Recursive nature of rule
private int minimumDepth ; / / Minimum depth of parse tree f o r production to map to termin
public ArrayList <Symbol> lhs ;
/∗∗
∗Creates a new rule with newLength elements .
∗/
public Rule ( f i n a l int newLength ) {
super ( newLength ) ;
this . ensureCapacity ( newLength ) ;
setRecursive ( false ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
RULE II
setMinimumDepth(32767 > >1);
lhs =new ArrayList ( ) ;
}
/∗∗
∗Copy constructor
∗/
public Rule ( f i n a l Rule copy ) {
super ( ) ;
lhs=new ArrayList ( ) ;
I t e r a t o r <Symbol> l h s I t =copy . lhs . i t e r a t o r ( ) ;
while ( l h s I t . hasNext ( ) ) {
Symbol tmpsymb= l h s I t . next ( ) ;
lhs . add (new Symbol ( tmpsymb ) ) ;
}
setRecursive ( copy . getRecursive ( ) ) ;
setMinimumDepth ( copy . getMinimumDepth ( ) ) ;
}
/∗∗
∗Delete a l l productions , and a l l symbols stored in lhs .
∗/
public void clear ( ) {
try {
lhs . clear ( ) ; / / clear the lhs vector
super . clear ( ) ; / / Clear production vector
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
RULE III
catch ( java . lang . Exception e ) {
System . out . p r i n t ( e ) ;
}
}
/∗∗
∗Return the recursive nature of t h i s rule .
∗/
public f i n a l boolean getRecursive ( ) {
return recursive ;
}
/∗∗
∗Update the recursive nature of t h i s rule .
∗/
public void setRecursive ( f i n a l boolean newRecursive ) {
recursive=newRecursive ;
}
/∗∗
∗Return the minimum mapping depth of t h i s rule .
∗/
public f i n a l int getMinimumDepth ( ) {
return minimumDepth ;
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
RULE IV
/∗∗
∗ Update the minimum mapping depth of t h i s Rule .
∗/
public void setMinimumDepth ( f i n a l int newMinimumDepth ) {
minimumDepth=newMinimumDepth ;
}
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
MAPPER I
/∗
∗ Mapper . java
∗
∗ Created on June 1 , 2007, 11:24 PM
∗
∗ To change t h i s template , choose Tools | Template Manager
∗ and open the template in the e d i t o r .
∗/
/∗∗
∗
∗ @author a d i l r a j a
∗/
package GrammaticOptimization ;
import java . u t i l . ∗ ;
import java . u t i l . ArrayList ;
public abstract class Mapper extends ArrayList <Rule> {
protected Genotype genotype ;
protected Phenotype phenotype ;
protected abstract boolean genotype2phenotype ( ) ;
protected abstract boolean phenotype2genotype ( ) ;
public Mapper ( ) {
super ( ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
MAPPER II
phenotype=new Phenotype ( ) ;
genotype=new Genotype ( ) ;
}
/∗∗
∗Constructor with genotype s t r u c t u r e . set to new newGenotype
∗/
public Mapper ( f i n a l Genotype newGenotype ) {
super ( ) ;
this . genotype=newGenotype ;
}
/∗∗
∗Constructor with phenotype s t r u c t o r . set phenotype to newPhenotype
∗/
public Mapper ( f i n a l Phenotype newPhenotype ) {
super ( ) ;
this . phenotype=new Phenotype ( newPhenotype ) ;
}
/∗∗
∗Copy Constructor
∗/
public Mapper ( f i n a l Mapper copy ) {
this . genotype=new Genotype ( copy . genotype ) ;
this . phenotype=new Phenotype ( copy . phenotype ) ;
}
/∗∗
∗returns the genotype s t r u c t u r e of t h i s mapper
∗/
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
MAPPER III
public f i n a l Genotype getGenotype ( ) {
return this . genotype ;
}
/∗∗
∗Sets t h i s mapper ’ s genotype s t r u c t u r e to be a copy of the argument , newgenotype ,
∗and c a l l s the genotype2phenotype private method .
∗/
public void setGenotype ( f i n a l Genotype newGenotype ) {
this . genotype=new Genotype ( newGenotype ) ;
genotype2phenotype ( ) ;
}
/∗∗
∗returns a pointer to the phenotype s t r u c t u r e of t h i s mapper
∗/
public f i n a l Phenotype getPhenotype ( ) {
return phenotype ;
}
/∗∗
∗Sets t h i s mapper ’ s phenotype s t r u c t u r e to be a copy of the argument phenotype
∗structure , and c a l l s the phenotype2genotype private method
∗/
public void setPhenotype ( f i n a l Phenotype newPhenotype ) {
phenotype=new Phenotype ( newPhenotype ) ;
phenotype2genotype ( ) ;
}
/∗∗
∗Sets the maximum codon value of the genotype s t r u c t u r e
∗/
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
MAPPER IV
public void setGenotypeMaxCodonValue ( f i n a l int newMaxCodonValue ) { / / CodonType= i n t
this . genotype . setMaxCodonValue ( newMaxCodonValue ) ;
}
/ / something l e f t here
}
/ / f i l e complete
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
SYMBOL I
/∗
∗ Symbol . java
∗
∗ Created on June 2 , 2007, 6:05 PM
∗
∗ To change t h i s template , choose Tools | Template Manager
∗ and open the template in the e d i t o r .
∗/
/∗∗
∗
∗ @author a d i l r a j a
∗
∗/
package GrammaticOptimization ;
import java . u t i l . ∗ ;
import java . lang . String ;
/ /
enum SymbolType {
NTSymbol , TSymbol
} ;
public class Symbol {
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
SYMBOL II
private SymbolType type ;
private String symbol ;
/∗∗ Creates a new instance of Symbol ∗/
/∗ Creat a new symbol object as a copy of newArry and with type newType , i f specified
∗/
public Symbol ( ) {
setType ( SymbolType . TSymbol ) ;
this . symbol=new String ( ) ;
}
public Symbol ( f i n a l String newArray , f i n a l SymbolType newType ) {
i f ( newArray != null )
this . symbol=new String ( newArray ) ;
else
this . symbol=new String ( " " ) ;
i f ( newType!= null )
setType ( newType ) ;
else
setType ( SymbolType . TSymbol ) ;
}
/∗∗
∗ Copy Constructor
∗/
public Symbol ( f i n a l Symbol copy ) {
try {
this . symbol=new String ( copy . getSymbol ( ) ) ;
}
catch ( java . lang . NullPointerException e ) {
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
SYMBOL III
System . out . p r i n t l n ( e ) ;
}
setType ( copy . getType ( ) ) ;
}
/∗∗
∗ Get the type of the symbol
∗/
public f i n a l SymbolType getType ( ) {
return this . type ;
}
/∗ Set the type of the symbol
∗/
public void setType ( f i n a l SymbolType newType ) {
this . type=newType ;
}
/∗∗
∗Returns the symbol
∗/
public f i n a l String getSymbol ( ) {
return this . symbol ;
}
/∗∗
∗Sets the symbol
∗/
public void setSymbol ( f i n a l String newSymbol ) {
this . symbol=newSymbol ;
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
SYMBOL IV
/∗∗
∗
∗/
public boolean makeComparison ( f i n a l Symbol newSymbol ) {
i f ( this . symbol . compareTo ( newSymbol . symbol)==0 && this . getType ( ) . t oS tr in g ( ) . compareTo ( n
return true ;
return false ;
}
public void clear ( ) {
this . symbol=" " ;
}
}
/ / under consideration
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
TREE I
/∗
∗ Tree . java
∗
∗ Created on July 27 , 2007, 3:53 PM
∗
∗ To change t h i s template , choose Tools | Template Manager
∗ and open the template in the e d i t o r .
∗/
package GrammaticOptimization ;
/∗∗
∗
∗ @author a d i l r a j a
∗/
import java . u t i l . ∗ ;
import java . u t i l . ArrayList ;
public class Tree extends ArrayList <Tree> {
private Symbol data ; / / Tree i s made of objects of type symbol as opposed to a r b i t r a r y type
private int depth ;
private int currentLevel ;
private boolean v a l i d ;
/∗∗ Creates a new instance of Tree ∗/
public Tree ( ) {
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
TREE II
/∗∗
∗ Constructor ; i n i t i a l i s e s depth and current l e v e l .
∗/
public Tree ( f i n a l int newDepth , f i n a l int newCurrentLevel ) {
depth=newDepth ;
currentLevel=newCurrentLevel ;
setValid ( false ) ;
}
/∗∗
∗Constructor ; i n i t i a l i s e s data to match arguments .
∗/
public Tree ( f i n a l Symbol newData , f i n a l int newCurrentLevel , f i n a l int newDepth ) {
data=newData ;
depth=newDepth ;
currentLevel=newCurrentLevel ;
setValid ( true ) ;
}
/∗∗
∗Copy constructor .
∗/
public Tree ( f i n a l Tree copy ) {
super ( copy ) ;
setData ( copy . getData ( ) ) ;
setDepth ( copy . getDepth ( ) ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
TREE III
setCurrentLevel ( copy . getCurrentLevel ( ) ) ;
setValid ( copy . getValid ( ) ) ;
}
/∗∗
∗ Return depth from t h i s node u n t i l the deepest l e a f .
∗/
/ / template <class T>
public f i n a l int getDepth ( ) {
return depth ;
}
/∗∗
∗Set new depth of t h i s node .
∗/
public void setDepth ( f i n a l int newDepth ) {
depth=newDepth ;
}
/∗∗
∗Return l e v e l of t h i s node .
∗/
public f i n a l int getCurrentLevel ( ) {
return currentLevel ;
}
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
TREE IV
/∗∗
∗Set new current l e v e l of t h i s node .
∗/
public void setCurrentLevel ( f i n a l int newCurrentLevel ) {
currentLevel=newCurrentLevel ;
}
/∗∗
∗Return data stored in t h i s node .
∗/
public f i n a l Symbol getData ( ) {
i f ( getValid ( ) ) {
return data ;
}
else {
return null ;
}
}
/∗∗
∗ Set data to store in t h i s node .
∗/
public void setData ( f i n a l Symbol newData ) {
data=new Symbol ( newData ) ;
setValid ( true ) ;
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
TREE V
}
/∗∗
∗Return v a l i d i t y of t h i s node .
∗/
public f i n a l boolean getValid ( ) {
return v a l i d ;
}
/∗∗
∗ Set v a l i d i t y of t h i s node .
∗/
public void setValid ( f i n a l boolean newValid ) {
v a l i d =newValid ;
}
}
/ / complete
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
SUMMARY
Java Beagle implements a simple genetic algorithm in
Java.
Implementation was focused at efficiency, ease of use and
simplicity.
Much of it is based on Beagle Puppy.
It is open source and can be found online.
Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen
REFERENCES
GO can be found online.
This presentation is developed with Beamer:
Darmstadt, crane.

More Related Content

PPS
Bdd: Tdd and beyond the infinite
ODP
JBoss Drools
PDF
OOP and FP - Become a Better Programmer
PDF
From object oriented to functional domain modeling
KEY
Test-driven development for TYPO3 (T3DD11)
PDF
Java Beagle
PPTX
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
PPT
Java Generics for Dummies
Bdd: Tdd and beyond the infinite
JBoss Drools
OOP and FP - Become a Better Programmer
From object oriented to functional domain modeling
Test-driven development for TYPO3 (T3DD11)
Java Beagle
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Java Generics for Dummies

What's hot (20)

PPTX
02 Java Language And OOP PART II
PPTX
Java Generics
PDF
FP in Java - Project Lambda and beyond
PPTX
Java 7, 8 & 9 - Moving the language forward
PDF
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
PDF
Coding Guidelines - Crafting Clean Code
PDF
Laziness, trampolines, monoids and other functional amenities: this is not yo...
PPTX
Use of Apache Commons and Utilities
PPTX
Java simple programs
PDF
Easy Going Groovy 2nd season on DevLOVE
PDF
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
PDF
The Ring programming language version 1.6 book - Part 34 of 189
PDF
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
PDF
The Ring programming language version 1.7 book - Part 36 of 196
PDF
The Ring programming language version 1.10 book - Part 42 of 212
PPT
Effective Java - Generics
KEY
JavaScript Classes and Inheritance
ODP
Java Generics
PPTX
Clean code slide
DOCX
Algoritmos sujei
02 Java Language And OOP PART II
Java Generics
FP in Java - Project Lambda and beyond
Java 7, 8 & 9 - Moving the language forward
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Coding Guidelines - Crafting Clean Code
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Use of Apache Commons and Utilities
Java simple programs
Easy Going Groovy 2nd season on DevLOVE
Beyond Java: 자바 8을 중심으로 본 자바의 혁신
The Ring programming language version 1.6 book - Part 34 of 189
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
The Ring programming language version 1.7 book - Part 36 of 196
The Ring programming language version 1.10 book - Part 42 of 212
Effective Java - Generics
JavaScript Classes and Inheritance
Java Generics
Clean code slide
Algoritmos sujei
Ad

Viewers also liked (10)

PDF
14 10 24 informe diário
PDF
Abolicionismooo
DOC
Mensagem
PDF
Manual Moodle
PDF
Relações Públicas 2.0
PPTX
Cosmo - Quick Devoxx09
PPSX
DOC
Apostila de html
PDF
Conectado em jesus
14 10 24 informe diário
Abolicionismooo
Mensagem
Manual Moodle
Relações Públicas 2.0
Cosmo - Quick Devoxx09
Apostila de html
Conectado em jesus
Ad

Similar to Grammatical Optimization (11)

PDF
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
PDF
Imagine that you want to keep track of your pet fish. Each fish is a.pdf
DOCX
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
PPT
Devnology Workshop Genpro 2 feb 2011
PPTX
Pattern Matching in Java 14
PDF
CFG Parsing
PDF
Java 5 New Feature
PPT
Lexical analysis, syntax analysis, semantic analysis. Ppt
PDF
A comparison between C# and Java
PDF
Compiler Construction | Lecture 14 | Interpreters
PDF
What can scala puzzlers teach us
Sum and Product Types - The Fruit Salad & Fruit Snack Example - From F# to Ha...
Imagine that you want to keep track of your pet fish. Each fish is a.pdf
Lab 1 Recursion  Introduction   Tracery (tracery.io.docx
Devnology Workshop Genpro 2 feb 2011
Pattern Matching in Java 14
CFG Parsing
Java 5 New Feature
Lexical analysis, syntax analysis, semantic analysis. Ppt
A comparison between C# and Java
Compiler Construction | Lecture 14 | Interpreters
What can scala puzzlers teach us

More from adil raja (20)

PDF
ANNs.pdf
PDF
A Software Requirements Specification
PDF
NUAV - A Testbed for Development of Autonomous Unmanned Aerial Vehicles
PDF
DevOps Demystified
PDF
On Research (And Development)
PDF
Simulators as Drivers of Cutting Edge Research
PDF
The Knock Knock Protocol
PDF
File Transfer Through Sockets
PDF
Remote Command Execution
PDF
Thesis
PDF
CMM Level 3 Assessment of Xavor Pakistan
PDF
Data Warehousing
PDF
Implementation of a Non-Intrusive Speech Quality Assessment Tool on a Mid-Net...
PDF
Implementation of a Non-Intrusive Speech Quality Assessment Tool on a Mid-Net...
PDF
Real-Time Non-Intrusive Speech Quality Estimation for VoIP
PDF
VoIP
PDF
ULMAN GUI Specifications
PDF
Modeling the Effect of Packet Loss on Speech Quality: Genetic Programming Bas...
PDF
ULMAN-GUI
PDF
Modeling the Effect of Packet Loss on Speech Quality: Genetic Programming Bas...
ANNs.pdf
A Software Requirements Specification
NUAV - A Testbed for Development of Autonomous Unmanned Aerial Vehicles
DevOps Demystified
On Research (And Development)
Simulators as Drivers of Cutting Edge Research
The Knock Knock Protocol
File Transfer Through Sockets
Remote Command Execution
Thesis
CMM Level 3 Assessment of Xavor Pakistan
Data Warehousing
Implementation of a Non-Intrusive Speech Quality Assessment Tool on a Mid-Net...
Implementation of a Non-Intrusive Speech Quality Assessment Tool on a Mid-Net...
Real-Time Non-Intrusive Speech Quality Estimation for VoIP
VoIP
ULMAN GUI Specifications
Modeling the Effect of Packet Loss on Speech Quality: Genetic Programming Bas...
ULMAN-GUI
Modeling the Effect of Packet Loss on Speech Quality: Genetic Programming Bas...

Recently uploaded (20)

PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Digital Strategies for Manufacturing Companies
PDF
System and Network Administraation Chapter 3
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Nekopoi APK 2025 free lastest update
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
assetexplorer- product-overview - presentation
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPT
Introduction Database Management System for Course Database
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PPTX
Introduction to Artificial Intelligence
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Softaken Excel to vCard Converter Software.pdf
Odoo Companies in India – Driving Business Transformation.pdf
Digital Strategies for Manufacturing Companies
System and Network Administraation Chapter 3
How to Migrate SBCGlobal Email to Yahoo Easily
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Wondershare Filmora 15 Crack With Activation Key [2025
Nekopoi APK 2025 free lastest update
PTS Company Brochure 2025 (1).pdf.......
assetexplorer- product-overview - presentation
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Introduction Database Management System for Course Database
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Introduction to Artificial Intelligence
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises

Grammatical Optimization

  • 1. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GRAMMATICAL OPTIMIZATION THE SOURCE CODE Muhammad Adil Raja Roaming Researchers, Inc. cbna April 27, 2015
  • 2. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen OUTLINE I 1 INTRODUCTION 2 GE’S MAIN 3 INITIALIZER 4 GENOTYPE 5 GRAMMAR 6 PRODUCTION 7 RULE 8 MAPPER 9 SYMBOL 10 TREE 11 SUMMARY 12 REFERENCES
  • 3. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen INTRODUCTION I Grammatical optimization (GO) is an adaptation of grammatical evolution (GE). The algorithm is implemented in Java. The algorithm is aimed at general optimization problems. With slight modification it can also be used for other types of problems such as classification. The source code has many Java files. In what follows you will find the source code of various components of Java Beagle.
  • 4. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE’S MAIN I /∗ ∗ GEsMain . java ∗ ∗ Created on August 4 , 2007, 5:31 PM ∗ ∗ To change t h i s template , choose Tools | Template Manager ∗ and open the template in the e d i t o r . ∗/ package GrammaticOptimization ; /∗∗ ∗ ∗ @author a d i l r a j a ∗/ import java . u t i l . ∗ ; public class GEsMain { /∗∗ Creates a new instance of GEsMain ∗/ public GEsMain ( ) { } /∗∗ ∗ @param args the command l i n e arguments
  • 5. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE’S MAIN II ∗/ public static void main ( String [ ] args ) { / / TODO code a p p l i c a t i o n l o g i c here Random rand=new Random ( ) ; int [ ] newArray= new int [ 1 0 ] ; newArray [ 0 ] = 0 ; newArray [ 1 ] = 2 ; newArray [ 2 ] = 1 ; newArray [ 3 ] = 4 ; newArray [ 4 ] = 4 ; newArray [ 5 ] = 4 ; newArray [ 6 ] = 4 ; newArray [ 7 ] = 4 ; newArray [ 8 ] = 4 ; newArray [ 9 ] = 4 ; ArrayList <Integer > a r r L i s t =new ArrayList ( ) ; for ( int i =0; i <10; i ++){ a r r L i s t . add ( ( Integer ) newArray [ i ] ) ; } Genotype geno=new Genotype ( newArray , 10 , true , 1 0 ) ; GEGrammar grammar=new GEGrammar( geno ) ; grammar . setMaxWraps ( 9 ) ; grammar . readBNFFile ( " / Users / a d i l r a j a / mywork / adils−java / GrammaticOptimization / d i s t / gram / / t r y { / / grammar . genotype2phenotype ( true ) ; / / }
  • 6. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE’S MAIN III / / catch ( java . lang . Exception e ) { / / System . out . p r i n t l n ( e+" In Main " ) ; / / } I t e r a t o r <Symbol> symbIt=grammar . getPhenotype ( ) . i t e r a t o r ( ) ; I t e r a t o r <Rule> r u l e I t =grammar . i t e r a t o r ( ) ; System . out . p r i n t l n ( " Here are the r e s u l t s : phenotype sizse= "+grammar . getPhenotype ( ) . si while ( symbIt . hasNext ( ) ) { System . out . p r i n t ( symbIt . next ( ) . getSymbol ( ) ) ; } i f ( grammar . phenotype . getValid ()== true ) System . out . p r i n t l n ( " nThe above phenotype i s v a l i d " ) ; else System . out . p r i n t l n ( " nThe above phenotype i s not v a l i d " ) ; System . out . p r i n t l n ( " n nHere i s the grammar" ) ; while ( r u l e I t . hasNext ( ) ) { Rule tmpRule= r u l e I t . next ( ) ; System . out . p r i n t ( " n"+tmpRule . lhs . get ( 0 ) . getSymbol ()+ " : : = " ) ; I t e r a t o r <Production > prodIt =tmpRule . i t e r a t o r ( ) ; while ( prodIt . hasNext ( ) ) { I t e r a t o r <Symbol> symbIt2= prodIt . next ( ) . i t e r a t o r ( ) ; while ( symbIt2 . hasNext ( ) ) { System . out . p r i n t ( symbIt2 . next ( ) . getSymbol ( ) ) ; } } } System . out . p r i n t l n ( "My name i s John Rambo "+grammar . size ( ) ) ; System . out . p r i n t l n ( newArray . length ) ;
  • 7. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE’S MAIN IV String str1 =new String ( " Adil " ) ; String str2 =new String ( " Adil " ) ; i f ( str1 . equals ( str2 ) ) System . out . p r i n t l n ( " adilRaja " ) ; Symbol symb=new Symbol ( ) ; System . out . p r i n t l n (symb . getType ( ) . to Str in g ( ) ) ; symb . setType ( SymbolType . NTSymbol ) ; System . out . p r i n t l n (symb . getType ( ) . to Str in g ( ) ) ; r u l e I t =grammar . i t e r a t o r ( ) ; System . out . p r i n t l n ( " n nHere i s the grammar ’ s NT/ T i n f o " ) ; while ( r u l e I t . hasNext ( ) ) { Rule tmpRule= r u l e I t . next ( ) ; System . out . p r i n t ( " n"+tmpRule . lhs . get ( 0 ) . getType ( ) . to Str in g ()+ " : : = " ) ; I t e r a t o r <Production > prodIt =tmpRule . i t e r a t o r ( ) ; while ( prodIt . hasNext ( ) ) { I t e r a t o r <Symbol> symbIt2= prodIt . next ( ) . i t e r a t o r ( ) ; while ( symbIt2 . hasNext ( ) ) { System . out . p r i n t ( symbIt2 . next ( ) . getType ( ) . to St rin g ()+ " " ) ; } } } } }
  • 8. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen INITIALIZER I /∗ ∗ I n i t i a l i s e r . java ∗ ∗ Created on July 2 , 2007, 6:05 PM ∗ ∗ To change t h i s template , choose Tools | Template Manager ∗ and open the template in the e d i t o r . ∗/ /∗∗ ∗ ∗ @author a d i l r a j a ∗ ∗/ package GrammaticOptimization ; public interface I n i t i a l i s e r { public int getPopSize ( ) ; public void setPopSize ( f i n a l int j ) ; public int getIndex ( ) ; public void setIndex ( f i n a l int i ) ; public boolean i n i t ( f i n a l int i ) ; }
  • 9. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GENOTYPE I /∗ ∗ Genotype . java ∗ ∗ Created on June 1 , 2007, 11:35 PM ∗ ∗ To change t h i s template , choose Tools | Template Manager ∗ and open the template in the e d i t o r . ∗/ /∗∗ ∗ ∗ @author a d i l r a j a ∗/ package GrammaticOptimization ; import java . u t i l . ∗ ; import java . u t i l . ArrayList ; /∗ Default Constructor . Creates a genotype s t r u c t u r e of length newLength , using the elements o ∗ i t s v a l i d f i e l d to newValid and i t s f i t n e s s to newFitness . Non−specified arguments are given ∗, as specified in the function prototype . ∗ ∗/ public class Genotype extends ArrayList <Integer >{ / / codonType private Vector genome ; private boolean _libGE_Genotype_valid ;
  • 10. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GENOTYPE II private double _libGE_Genotype_fitness ; private int _libGE_Genotype_maxCodonValue ; private int _libGE_Genotype_effectiveSize ; private int _libGE_Genotype_wraps ; public Genotype ( ) { } /∗∗ Creates a new instance of Genotype ∗/ public Genotype ( f i n a l int [ ] newArray , f i n a l int newLength , f i n a l boolean newValid , f i n a l d _libGE_Genotype_valid=newValid ; _libGE_Genotype_fitness=newFitness ; this . setMaxCodonValue (32767); / / INT_MAX for ( int i i =0; i i <newLength ; i i ++){ this . add (new Integer ( newArray [ i i ] ) ) ; } setEffectiveSize ( 0 ) ; setWraps ( 0 ) ; } /∗ Constructor . Creates a genotype s t r u c t u r e with the contents of newvector , and sets i t s ∗ f i e l d to newValid and i t s f i t n e s s to newFitness . ∗Non−specified arguments are given default values , as specified in he function prototype ∗/ public Genotype ( f i n a l ArrayList <Integer > newVector , f i n a l boolean newValid , f i n a l double n
  • 11. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GENOTYPE III _libGE_Genotype_valid=newValid ; _libGE_Genotype_fitness=newFitness ; this . addAll ( newVector ) ; setMaxCodonValue (32767); setEffectiveSize ( 0 ) ; setWraps ( 0 ) ; } /∗ Constructor . Creates an empty genotype structure , and sets maCodonValue to the value ∗specified as argument ∗/ public Genotype ( f i n a l int maxCodonValue ) { setMaxCodonValue ( maxCodonValue ) ; setEffectiveSize ( 0 ) ; setWraps ( 0 ) ; } /∗Copy constructor ∗/ public Genotype ( f i n a l Genotype copy ) { setValid ( copy . getValid ( ) ) ; setFitness ( copy . getFitness ( ) ) ; setMaxCodonValue ( copy . getMaxCodonValue ( ) ) ; setEffectiveSize ( copy . getEffectiveSize ( ) ) ; setWraps ( copy . getWraps ( ) ) ; }
  • 12. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GENOTYPE IV /∗ Returns the current v a l i d f i e l d ∗/ public f i n a l boolean getValid ( ) { return _libGE_Genotype_valid ; } /∗ Set a new value f o r the v a l i d f i e l d ∗/ public void setValid ( f i n a l boolean newValid ) { _libGE_Genotype_valid=newValid ; } /∗ Returns the current f i t n e s s score ∗/ public f i n a l double getFitness ( ) { return _libGE_Genotype_fitness ; } /∗ Sets a new f i t n e s s score ∗/ public void setFitness ( f i n a l double newFitness ) { _libGE_Genotype_fitness=newFitness ; } /∗ Returns the maximum containable value in a codon ∗/ public f i n a l int getMaxCodonValue ( ) {
  • 13. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GENOTYPE V return _libGE_Genotype_maxCodonValue ; } /∗ Sets the maximum containable value in a codon ∗/ public void setMaxCodonValue ( f i n a l int newMaxCodonValue ) { _libGE_Genotype_maxCodonValue=newMaxCodonValue ; } /∗ Returns e f f e c t i v e length of Genotype ∗/ public f i n a l int getEffectiveSize ( ) { return _libGE_Genotype_effectiveSize ; } /∗ Sets e f f e c t i v e length of genotype ∗/ public void setEffectiveSize ( f i n a l int newEffectiveSize ) { _libGE_Genotype_effectiveSize=newEffectiveSize ; } /∗ Returns number of wrapping events ∗/ public f i n a l int getWraps ( ) { return _libGE_Genotype_wraps ; } /∗ Sets the number of wrapping events
  • 14. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GENOTYPE VI ∗/ public void setWraps ( f i n a l int newWraps ) { _libGE_Genotype_wraps=newWraps ; } /∗Used to p r i n t the genome as a s t r i n g ∗/ public String printContents ( ) { / / String s=new String ( ) ; return this . toArray ( ) . toS tr in g ( ) ; } } / / complete
  • 15. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GRAMMAR I /∗ ∗ Grammar . java ∗ ∗ Created on July 26 , 2007, 6:09 PM ∗ ∗ To change t h i s template , choose Tools | Template Manager ∗ and open the template in the e d i t o r . ∗/ package GrammaticOptimization ; /∗∗ ∗ ∗ @author a d i l r a j a ∗/ import java . u t i l . I t e r a t o r ; public abstract class Grammar extends Mapper { private boolean validGrammar ; private int startSymbol ; protected abstract boolean genotype2phenotype ( ) ; protected abstract boolean phenotype2genotype ( ) ; /∗∗ ∗ Creates a new instance of Grammar ∗/
  • 16. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GRAMMAR II public Grammar ( ) { super ( ) ; setValidGrammar ( false ) ; startSymbol =0; } /∗∗ ∗Constructor s e t t i n g the genotype s t r u c t u r e of t h i s mapper to newGenotype . ∗/ public Grammar( f i n a l Genotype newGenotype ) { super ( newGenotype ) ; setValidGrammar ( false ) ; startSymbol =0; } /∗∗ ∗Constructor s e t t i n g the phenotype s t r u c t u r e of t h i s mapper to newPhenotype . ∗/ public Grammar( f i n a l Phenotype newPhenotype ) { super ( newPhenotype ) ; setValidGrammar ( false ) ; startSymbol =0; } /∗∗ ∗Copy Constructor
  • 17. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GRAMMAR III ∗/ public Grammar( f i n a l Grammar copy ) { super ( ) ; setValidGrammar ( copy . getValidGrammar ( ) ) ; startSymbol=copy . startSymbol ; } /∗∗ ∗ Return the v a l i d i t y of the current grammar . ∗/ public f i n a l boolean getValidGrammar ( ) { return validGrammar ; } /∗∗ ∗Set the v a l i d i t y of the grammar . ∗/ protected void setValidGrammar ( f i n a l boolean newValidGrammar ) { validGrammar=newValidGrammar ; } /∗∗ ∗Return current s t a r t symbol . ∗/ public f i n a l Symbol getStartSymbol ( ) {
  • 18. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GRAMMAR IV / / return f r o n t ( ) . lhs . f r o n t ( ) ; / / return (∗ t h i s ) [ startSymbol ] . lhs . f r o n t ( ) ; Symbol symb=null ; i f ( startSymbol <this . size ( ) ) { symb=this . get ( startSymbol ) . lhs . get ( 0 ) ; } return symb ; } /∗∗ ∗Change s t a r t symbol by index on Vector of rules . ∗/ public boolean setStartSymbol ( f i n a l int index ) { i f ( index <this . size ( ) ) { / / Check boundaries . startSymbol=index ; genotype2phenotype ( ) ; / / Update phenotype . return true ; } return false ; } /∗∗ ∗Change s t a r t symbol by symbol pointer . ∗/ public boolean setStartSymbol ( f i n a l Symbol newStartSymbol ) { int i i =0;
  • 19. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GRAMMAR V I t e r a t o r <Rule> i t =this . i t e r a t o r ( ) ; while ( i t . hasNext ( ) ) { / / Work by ∗pointer ∗. i f ( i t . next ( ) . lhs . get ( 0 ) . getSymbol ( ) . compareTo ( newStartSymbol . getSymbol ( ) ) = = 0 ) { startSymbol= i i ; genotype2phenotype ( ) ; / / Update phenotype . return true ; } i i ++; } return false ; } /∗∗ ∗Change s t a r t symbol by s t r i n g . ∗/ public boolean setStartSymbol ( f i n a l String newStartSymbol ) { int i i =0; I t e r a t o r <Rule> i t =this . i t e r a t o r ( ) ; while ( i t . hasNext ( ) ) { / / Work by ∗s t r i n g ∗. String currentStartSymbol= i t . next ( ) . lhs . get ( 0 ) . getSymbol ( ) ; i f ( currentStartSymbol . compareTo ( newStartSymbol )==0){ startSymbol= i i ; genotype2phenotype ( ) ; / / Update phenotype . return true ; }
  • 20. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GRAMMAR VI i i ++; } return false ; } /∗∗ ∗Return pointer to current s t a r t rule . ∗/ public f i n a l Rule getStartRule ( ) { return this . get ( 0 ) ; } } / / complete
  • 21. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR I /∗ ∗ CFGrammar. java ∗ ∗ Created on July 26 , 2007, 12:21 PM ∗ ∗ To change t h i s template , choose Tools | Template Manager ∗ and open the template in the e d i t o r . ∗/ package GrammaticOptimization ; /∗∗ ∗ ∗ @author a d i l r a j a ∗/ import java . u t i l . ∗ ; import java . u t i l . ArrayList ; import java . u t i l . I t e r a t o r ; import java . io . ∗ ; public abstract class CFGrammar extends Grammar { protected Tree derivationTree ; protected abstract boolean genotype2phenotype ( ) ; protected abstract boolean phenotype2genotype ( ) ; /∗∗ ∗ Creates a new instance of CFGrammar
  • 22. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR II ∗/ public CFGrammar ( ) { super ( ) ; } /∗∗ ∗Constructor s e t t i n g the genotype s t r u c t u r e of t h i s mapper to newGenotype . ∗/ public CFGrammar( f i n a l Genotype newGenotype ) { super ( newGenotype ) ; } /∗∗ ∗ Constructor s e t t i n g the phenotype s t r u c t u r e of t h i s mapper to newPhenotype . ∗/ public CFGrammar( f i n a l Phenotype newPhenotype ) { super ( newPhenotype ) ; } /∗∗ ∗ Copy Constructor . ∗/ public CFGrammar( f i n a l CFGrammar copy ) { super ( copy ) ; / / Now must go through the copied grammar , and replace references to / / the copy ’ s lhs symbols with references to the new lhs symbols . I t e r a t o r r u l e I t =this . i t e r a t o r ( ) ; / / i t e r a t o r of Rule I t e r a t o r <Rule> prodIt ;
  • 23. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR III I t e r a t o r <Production > symbIt ; Rule r u l e P t r =null ; int ruleCt =0 , prodCt =0 , symbCt=0; while ( r u l e I t . hasNext ( ) ) { prodIt = r u l e I t ; while ( prodIt . hasNext ( ) ) { symbIt= prodIt . next ( ) . i t e r a t o r ( ) ; while ( symbIt . hasNext ( ) ) { Symbol symb=symbIt . next ( ) . get ( 0 ) ; i f (symb . getType ( ) . t oSt ri ng ( ) . compareTo ( "NTSymbol" )==0){ try { r u l e P t r =findRule (symb ) ; } catch ( Exception e ) { / / do nothing } i f ( r u l e P t r ==null ) { /∗ Undefined NTSymbol − create new symbol ∗/ symb=new Symbol (symb . getSymbol ( ) , null ) ; } else { /∗ Point to symbol ’ s d e f i n i t i o n ∗/ symb= r u l e P t r . lhs . get ( r u l e P t r . lhs . size () −1); } this . get ( ruleCt ) . get ( prodCt ) . insertSymbol (symb , symbCt ) ; } symbIt . next ( ) ; symbCt++;
  • 24. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR IV } prodIt . next ( ) ; prodCt ++; } r u l e I t . next ( ) ; ruleCt ++; } / / I n v a l i d a t e phenotype − lower classes in hierarchy can always c a l l / / genotype2Phenotype ( ) to regenerate i t phenotype . clear ( ) ; phenotype . setValid ( false ) ; / / Don ’ t copy d e r i v a t i o n tree : procedure i s too complex and expensive . / / I f tree i s requested , i t w i l l be regenerated . } /∗∗ ∗ Opens the f i l e whose name i s passed as an argument , reads i t s contents onto ∗a character string , and c a l l s readBNFString . ∗/ public boolean readBNFFile ( f i n a l String filename ) { /∗ FILE ∗pFile ; i f ( ! ( pFile=fopen ( filename , " r " ) ) ) { cerr << " Could not open grammar f i l e " << filename << " . nExecution aborted . n e x i t ( 1 ) ; } fseek ( pFile ,0 ,SEEK_END) ; i n t size = f t e l l ( pFile ) ;
  • 25. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR V char program [ size +1]; strncpy ( program , " " , size ) ; char l i n e [1024]; rewind ( pFile ) ; while ( fgets ( line ,1024 , pFile ) ) s t r c a t ( program , l i n e ) ; fclose ( pFile ) ; s t r c a t ( program , " n " ) ; return readBNFString ( program ) ; ∗/ String program=new String ( ) ; / / t r y / / { / / Open the f i l e that i s the f i r s t / / command l i n e parameter / / FileInputStream fstream = new FileInputStream ( " a d i l . bnf " ) ; / / Convert our input stream to a / / DataInputStream / / BufferedReader in = new BufferedReader (new InputStreamReader ( fstream ) ) ; / / Continue to read l i n e s while / / there are s t i l l some l e f t to read / / DataInput s = new DataInputStream (new FileInputStream ( " ~ / mywork /GE/ libGE −0.26/E / / String th is Li ne ; / / while ( ( th is Li ne =s . readLine ( ) ) != n u l l ) / / { / / program . concat ( th is Li ne ) ; / / }
  • 26. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR VI / / s . close ( ) ; / / } / / catch ( Exception e ) / / { / / System . out . p r i n t l n ( e+" F i l e input error " ) ; / / } / / program . concat ( " n " ) ; program="<expr > : : = (<expr > <op> <expr > ) n | DIV(<expr > , <expr > ) n | ABS(<expr > ) n | GT( return readBNFString ( program ) ; } /∗∗ ∗ Reads in the BNF grammar specified by i t s argument t e x t . Returns true i f ∗ loading of grammar was successful , false otherwise . ∗/ public boolean readBNFString ( String stream ) { / / the stream was f i n a l / / Delete the current grammar , i f any this . clear ( ) ; Rule newRule=new Rule ( 0 ) ; / / Used to create new rules f o r gramm boolean insertRule=false ; / / I f newRule i s to be inserted onto grammar Rule currentRule=null ; / / Used in pass 2 to add productions to current rule Production newProduction=new Production ( 1 ) ; newProduction . clear ( ) ; / / Used to create new productions f o r grammar Symbol newSymbol=new Symbol ( ) ; / / Used to create new symbols f o r grammar Symbol newTokenSeparator=new Symbol ( ) ; / / Used to create token separators f o r gramma
  • 27. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR VII int stream_size=stream . length ( ) ; int i i , j j ; / / Working variables char currentChar ; / / Current char of input boolean skip=false ; / / SKip an i t e r a t i o n on parser ( f o r escaped newlines ) boolean quoted=false ; / / I f current char i s quoted boolean non_terminal=false ; / / I f current t e x t i s a non−terminal symbol char separated =0; / / I f there was a separator between previous token and ArrayList <Symbol> nonTerminals=new ArrayList ( ) ; nonTerminals . clear ( ) ; / / Contains pointers to a l l defined non−terminals I t e r a t o r <Symbol> nonTerminalsIt ; String currentBuffer =new String ( ) ; / / Buffer used to add new symbols to g / / States of parser f i n a l int START = 0; f i n a l int START_RULE = 1; f i n a l int LHS_READ = 2; f i n a l int PRODUCTION = 3; f i n a l int START_OF_LINE = 4; int state=START; / / Current state of parser / / #define libGE_DEBUG_CFGRAMMAR_PARSER stream+=" n" ; for ( int pass =1;pass <=2;pass ++){ i i = j j =0; while ( i i <=stream_size ) { i f ( i i <stream_size ) { currentChar=stream . charAt ( i i ) ; }
  • 28. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR VIII else { / / Simulate presence of endl at end of grammar currentChar= ’ n ’ ; } System . out . p r i n t l n ( " I am here "+ i i ) ; i f ( stream . charAt ( i i )== ’ ’ ) { / / Escape sequence i i ++; i f ( i i >=stream_size ) { / / Escape sequence as l a s t char i s i n v a l i d ERROR_IN_GRAMMAR( ) ; } else i f ( ( non_terminal )&&( stream . charAt ( i i ) ! = ’ n ’ ) ) { / / Only escaped newline allowed inside non−terminal System . out . p r i n t l n ( "ERROR: Escape sequence detected inside non−terminal s ERROR_IN_GRAMMAR( ) ; } i f ( stream . charAt ( i i )== ’ ’ ’ ) { / / Single quote currentChar= ’ ’ ’ ; } else i f ( stream . charAt ( i i )== ’ " ’ ) { / / Double quote currentChar= ’ " ’ ; } else i f ( stream . charAt ( i i )== ’ ’ ) { / / Backslash currentChar= ’ ’ ; } else i f ( stream . charAt ( i i )== ’0 ’ ) { / / Null character currentChar= ’ 0 ’ ; }
  • 29. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR IX / / else i f ( stream . charAt ( i i )== ’a ’ ) { / / Audible b e l l / / currentChar = ’ a ’ ; / / } else i f ( stream . charAt ( i i )== ’b ’ ) { / / Backspace currentChar= ’ b ’ ; } else i f ( stream . charAt ( i i )== ’ f ’ ) { / / Formfeed currentChar= ’ f ’ ; } else i f ( stream . charAt ( i i )== ’n ’ ) { / / Newline currentChar= ’ n ’ ; } else i f ( stream . charAt ( i i )== ’ r ’ ) { / / Carriage return currentChar= ’ r ’ ; } else i f ( stream . charAt ( i i )== ’ t ’ ) { / / Horizontal tab currentChar= ’ t ’ ; } / / else i f ( stream [ i i ]== ’ v ’ ) { / / V e r t i c a l tab / / currentChar = ’ v ’ ; / / } else i f ( stream . charAt ( i i )== ’ n ’ ) { / / Escaped newline / / Ignore newline skip=true ; } else i f ( stream . charAt ( i i )== ’ r ’ ) { / / Escaped DOS return / / Ignore newline skip=true ;
  • 30. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR X i f ( stream . charAt (++ i i ) ! = ’ n ’ ) { System . out . p r i n t l n ( "ERROR: r character not followed by n . " ) ; ERROR_IN_GRAMMAR( ) ; } } else { / / Normal character currentChar=stream . charAt ( i i ) ; } i f ( ( ! skip )&&(pass >1)){ i f ( currentBuffer . length ()==0){ newSymbol . setType ( SymbolType . TSymbol ) ; } i f ( currentBuffer . length ()==0){ currentBuffer =Character . t oS tr ing ( currentChar ) ; } else { / / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ; currentBuffer +=currentChar ; } } } else { switch ( state ) { case (START) : i f ( currentChar== ’ r ’ ) { break ; / / Ignore DOS newline f i r s t char }
  • 31. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XI switch ( currentChar ) { case ’ ’ : / / Ignore whitespaces case ’ t ’ : / / Ignore tabs case ’ n ’ : / / Ignore newlines break ; case ’< ’ : / / START OF RULE newSymbol . setType ( SymbolType . NTSymbol ) ; i f ( currentBuffer . length ()==0){ currentBuffer =Character . t oS tr in g ( currentChar ) ; } else { / / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ; currentBuffer +=currentChar ; } state=START_RULE; break ; default : / / I l l i g a l System . out . p r i n t l n ( "ERROR: Character "+ currentChar + " caused an erro ERROR_IN_GRAMMAR( ) ; } break ; case (START_RULE ) : / / Read the lhs Non−terminal symbol i f ( currentChar== ’ r ’ ) { break ; / / Ignore DOS newline f i r s t char } switch ( currentChar ) { case ’ n ’ : / / Newlines are i l l i g a l here System . out . p r i n t l n ( "ERROR: Newline inside non−terminal . " ) ;
  • 32. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XII ERROR_IN_GRAMMAR( ) ; break ; case ’> ’ : / / Possible end of non−terminal symbol i f ( currentBuffer . length ()==0){ currentBuffer =Character . t oS tr ing ( currentChar ) ; } else { / / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ; currentBuffer +=currentChar ; } newSymbol . setSymbol ( currentBuffer ) ; / / newSymbol . setType ( SymbolType . NTSymbol ) ; / / t h i s was added a d i l i f ( pass ==1){ / / F i r s t pass / / Check i f new symbol d e f i n i t i o n / / insertRule = ! ( findRule ( newSymbol ) ) ; Rule tmpRulePtr=null ; try { tmpRulePtr=findRule ( newSymbol ) ; } catch ( Exception e ) { / / do nothing } i f ( tmpRulePtr==null ) insertRule=true ; else insertRule=false ; i f ( insertRule ) {
  • 33. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XIII / / Create new rule f o r symbol newRule . clear ( ) ; try { newRule . lhs . add (new Symbol ( newSymbol ) ) ; } catch ( java . lang . Exception e ) { System . out . p r i n t l n ( e + " newRule sucks " ) ; } / / Add to grammar try { nonTerminals . add ( newRule . lhs . get ( newRule . lhs . size () −1)); } catch ( java . lang . NullPointerException e ) { System . out . p r i n t l n ( e+ " nonTerminals suck " ) ; } } else { / / Existing symbol , do nothing } } else { / / Second pass / / Point currentRule to previously defined rule try { i f ( ( currentRule=findRule ( newSymbol))== null ) { System . out . p r i n t l n ( "ERROR: Grammar changed between parser pass ERROR_IN_GRAMMAR( ) ; }
  • 34. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XIV } catch ( java . lang . NullPointerException e ) { System . out . p r i n t l n ( e+"ERROR: Grammar changed between parser passes ERROR_IN_GRAMMAR( ) ; } catch ( java . lang . Exception e ) { System . out . p r i n t l n ( e+"ERROR: Grammar changed between parser passes } / / i f ( ( currentRule=findRule ( newSymbol))== n u l l ) { / / System . out . p r i n t l n ( "ERROR: Grammar changed between parser pa / / ERROR_IN_GRAMMAR( ) ; / / } } / / Reset the buffer currentBuffer =" " ; / / lhs f o r t h i s rule has been read state=LHS_READ; break ; default : / / Check f o r non−escaped special characters i f ( ( ( currentChar== ’ " ’ ) | | ( currentChar== ’ | ’ ) | | ( currentChar== ’< ’ ) ) ) { System . out . p r i n t l n ( "ERROR: I n v a l i d character ’ " + currentChar + " ERROR_IN_GRAMMAR( ) ; } i f ( currentBuffer . length ()==0){ currentBuffer =Character . t oS tr ing ( currentChar ) ; } else { / / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ;
  • 35. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XV currentBuffer +=currentChar ; } } break ; case (LHS_READ) : / / Must read : : = token i f ( currentChar== ’ r ’ ) { break ; / / Ignore DOS newline f i r s t char } switch ( currentChar ) { case ’ ’ : / / Ignore whitespaces case ’ t ’ : / / Ignore tabs case ’ n ’ : / / Ignore newlines break ; case ’ : ’ : / / Part of : : = token i f ( currentBuffer . length ()==0){ currentBuffer =Character . t oS tr in g ( currentChar ) ; } else { / / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ; currentBuffer +=currentChar ; } break ; case ’= ’ : / / Should be end of : : = token try { i f ( currentBuffer . length ()==0){ currentBuffer =Character . t oS tr ing ( currentChar ) ; } else {
  • 36. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XVI / / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ; currentBuffer +=currentChar ; } / / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ; } catch ( java . lang . NullPointerException e ) { System . out . p r i n t l n ( e ) ; } i f ( currentBuffer . equals ( " : : = " )== false ) { / / Something other than : : = was System . out . p r i n t l n ( "ERROR: Token ’ " + currentBuffer + " ’ cause ERROR_IN_GRAMMAR( ) ; } / / Reset the buffer currentBuffer =" " ; / / START OF PRODUCTION newProduction . clear ( ) ; state=PRODUCTION; break ; default : / / I l l i g a l System . out . p r i n t l n ( "ERROR: Character ’ " + currentChar + " ’ caused an e ERROR_IN_GRAMMAR( ) ; } break ; case (PRODUCTION) : / / Read everything u n t i l | token or n , or EOL i f ( currentChar== ’ r ’ ) { break ; / / Ignore DOS newline f i r s t char } i f ( pass ==1){
  • 37. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XVII i f ( currentChar== ’ n ’ ) state=START_OF_LINE; } else switch ( currentChar ) { case ’ | ’ : / / Possible end of production i f ( quoted ) { / / Normal character / / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ; i f ( currentBuffer . length ()==0){ currentBuffer =Character . t oS tr ing ( currentChar ) ; } else { currentBuffer +=currentChar ; } break ; } case ’ n ’ : / / End of production ( and possibly rule ) / / Reset separator marker separated =0; i f ( ( currentBuffer . length ( ) ! = 0 ) | | ( newProduction . size ( ) ! = 0 ) ) { / / The System . out . p r i n t l n ( "A symbol ’ " + currentBuffer + " ’ " + newSym i f ( currentBuffer . length ()==0){ / / No symbol exists ; create terminal empty symbol newSymbol . setType ( SymbolType . TSymbol ) ; } i f ( non_terminal ) { / / Current non−terminal symbol isn ’ t f in is hed System . out . p r i n t l n ( "ERROR: Symbol ’ " + currentBuffer + " ’ caus ERROR_IN_GRAMMAR( ) ; }
  • 38. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XVIII newSymbol . setSymbol ( currentBuffer ) ; i f ( newSymbol . getType ( ) . t oSt ri ng ( ) . equals ( "NTSymbol" ) ) { / / Find rule that defines t h i s symbol Rule tempRule=null ; try { tempRule=findRule ( newSymbol ) ; } catch ( Exception e ) { / / do nothing again } i f ( tempRule != null ) { newProduction . add (new Symbol ( tempRule . lhs . get ( tempRule . lhs } else { / / Undefined symbol , i n s e r t anyway newProduction . add (new Symbol ( newSymbol ) ) ; } } else { / / Add terminal symbol newProduction . add (new Symbol ( newSymbol ) ) ; } / / Reset the symbol / / newSymbol . clear ( ) ; / / t h i s i s not required , the garbage c o l l e c t o r does newSymbol . clear ( ) ; } else { / / Empty token ; ignored ; }
  • 39. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XIX / / END OF PRODUCTION / / Add production to current rule try { currentRule . add (new Production ( newProduction ) ) ; } catch ( Exception e ) { System . out . p r i n t l n ( e+" But the currentRule i s n u l l . . . i t sucks too " } / / Reset the buffer currentBuffer =" " ; i f ( currentChar== ’ n ’ ) state=START_OF_LINE; else { / / START OF PRODUCTION newProduction . clear ( ) ; } break ; case ’< ’ : / / Possible s t a r t of non−terminal symbol case ’> ’ : / / Possible end of non−terminal symbol case ’ ’ : / / Possible token separator case ’ t ’ : / / Possible token separator i f ( ( quoted ) / / Normal character | | ( ( ( currentChar== ’ ’ ) | | ( currentChar== ’ t ’ ))&&( non_terminal ) ) ) { / / Spaces i i f ( currentBuffer . length ()==0){ currentBuffer =Character . t oS tr in g ( currentChar ) ; } else { / / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ;
  • 40. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XX currentBuffer +=currentChar ; } i f ( ! non_terminal ) newSymbol . setType ( SymbolType . TSymbol ) ; break ; } i f ( currentChar== ’> ’ ) { / / This i s also the end of a non−terminal symbol i f ( currentBuffer . length ()==0){ currentBuffer =Character . t oS tr ing ( currentChar ) ; } else { / / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ; currentBuffer +=currentChar ; } non_terminal=false ; } i f ( currentBuffer . length () >0){ i f ( non_terminal ) { / / Current non−terminal symbol isn ’ t f in is hed System . out . p r i n t l n ( "ERROR: Symbol " + currentBuffer + " ’ caused an ERROR_IN_GRAMMAR( ) ; } i f ( ( currentChar== ’ ’ ) | | ( currentChar== ’ t ’ ) ) { / / Token separator separated =1; } newSymbol . setSymbol ( currentBuffer ) ; i f ( newSymbol . getType ( ) . to St ri ng ( ) . equals ( "NTSymbol" ) ) { / / Find rule that defines t h i s symbol Rule tempRule=null ; try {
  • 41. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XXI tempRule=findRule ( newSymbol ) ; } catch ( java . lang . Exception e ) { System . out . p r i n t l n ( e+" Finding the rule sucks . . . " ) ; } i f ( tempRule != null ) { newProduction . add (new Symbol ( tempRule . lhs . get ( tempRule . lhs . siz } else { / / Undefined symbol , i n s e r t anyway newProduction . add (new Symbol ( newSymbol ) ) ; } } else { / / Add terminal symbol newProduction . add (new Symbol ( newSymbol ) ) ; } / / Reset the symbol newSymbol . clear ( ) ; } else { / / Empty buffer i f ( ( ( currentChar== ’ ’ ) | | ( currentChar== ’ t ’ ) ) / / Token separator &&(newProduction . size ( ) > 0 ) ) { / / Probably a token separator a f t e r a non−terminal symbol separated =1; } } / / Reset the buffer currentBuffer =" " ;
  • 42. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XXII i f ( currentChar== ’< ’ ) { / / This i s also the s t a r t of a non−terminal symbol / / Special case ; must create new Symbol here newSymbol . clear ( ) ; newSymbol . setType ( SymbolType . NTSymbol ) ; i f ( currentBuffer . length ()==0){ currentBuffer =Character . t oS tr ing ( currentChar ) ; } else { / / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ; currentBuffer +=currentChar ; } non_terminal=true ; / / Now reading a non−terminal symbol i f ( separated ! = 0 ) { / / I n s e r t a token separator separated =0; newTokenSeparator=new Symbol ( ) ; newTokenSeparator . setSymbol ( " " ) ; newTokenSeparator . setType ( SymbolType . TSymbol ) ; newProduction . add (new Symbol ( newTokenSeparator ) ) ; } } break ; default : / / Add character to current buffer i f ( separated ! = 0 ) { / / I n s e r t a token separator separated =0; newTokenSeparator=new Symbol ( ) ; newTokenSeparator . setSymbol ( " " ) ; newTokenSeparator . setType ( SymbolType . TSymbol ) ; newProduction . add (new Symbol ( newTokenSeparator ) ) ;
  • 43. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XXIII } i f ( currentChar== ’ " ’ ) { / / Start ( or end ) quoted section quoted =! quoted ; newSymbol . setType ( SymbolType . TSymbol ) ; break ; } i f ( currentBuffer . length ()==0){ newSymbol . setType ( SymbolType . TSymbol ) ; } i f ( currentBuffer . length ()==0){ currentBuffer =Character . t oS tr ing ( currentChar ) ; } else { / / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ; currentBuffer +=currentChar ; } } break ; case (START_OF_LINE ) : i f ( currentChar== ’ r ’ ) { break ; / / Ignore DOS newline f i r s t char } switch ( currentChar ) { case ’ ’ : / / Ignore whitespaces case ’ t ’ : / / Ignore tabs case ’ n ’ : / / Ignore newlines break ; case ’ | ’ : / / Start of new production
  • 44. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XXIV state=PRODUCTION; i f ( pass ==2){ / / START OF PRODUCTION newProduction . clear ( ) ; } break ; case ’< ’ : / / Start of lhs non−terminal symbol / / END OF RULE i f ( pass ==1){ / / Add current rule i f ( insertRule ) { try { this . add (new Rule ( newRule ) ) ; } catch ( java . lang . NullPointerException e ) { System . out . p r i n t l n ( e ) ; } } } / / START OF RULE newSymbol . setType ( SymbolType . NTSymbol ) ; i f ( currentBuffer . length ()==0){ currentBuffer =Character . t oS tr ing ( currentChar ) ; } else { / / currentBuffer . concat ( Character . to St ri ng ( currentChar ) ) ; currentBuffer +=currentChar ;
  • 45. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XXV } state=START_RULE; break ; default : / / I l l i g a l System . out . p r i n t l n ( "ERROR: Detected l i n e s t a r t i n g with terminal symbol . " ) ; ERROR_IN_GRAMMAR( ) ; } break ; default : / / Impossible error , q u i t the program now ! System . out . p r i n t l n ( " I n t e r n a l error . nPlease report error ’ Impossible state in System . e x i t ( 0 ) ; } } skip=false ; i i ++; } / / END OF PASS i f ( state !=START_OF_LINE ) { / / This must be the state of the parser System . out . p r i n t l n ( " Parsing error reading grammar . " ) ; ERROR_IN_GRAMMAR( ) ; } i f ( pass ==1){ / / Add current rule i f ( insertRule ) { this . add (new Rule ( newRule ) ) ; } }
  • 46. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XXVI } updateRuleFields ( ) ; setValidGrammar ( true ) ; genotype2phenotype ( ) ; return true ; } /∗∗ ∗ Reads in the BNF grammar−part specified by i t s argument text , and adds i t to ∗the current grammar . Returns true i f loading of new grammar part was ∗successful , false otherwise . ∗/ public boolean addBNFString ( f i n a l String stream ) { / / FIXME Slow implementation . / / Copy current grammar ArrayList <Rule> grammarCopy=this ; / / Create appended grammar s t r i n g String newGrammarStream=outputBNF ( ) ; String newGrammar=new String ( newGrammarStream ) ; newGrammar=stream ; / / Read new grammar try { i f ( ! readBNFString (newGrammar ) ) { / / Restore previous state of Mapper readBNFString ( newGrammarStream ) ; return false ;
  • 47. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XXVII } return true ; } catch ( java . lang . Exception e ) { return false ; } } /∗∗ ∗ Pretty p r i n t the current BNF grammar . ∗/ public String outputBNF ( ) { String stream=null ; i f ( ! getValidGrammar ( ) ) { return null ; } I t e r a t o r <Rule> r _ i t =this . i t e r a t o r ( ) ; while ( r _ i t . hasNext ( ) ) { Rule tmp ; tmp= r _ i t . next ( ) ; stream . concat ( tmp . lhs . get ( tmp . lhs . size () −1). getSymbol ( ) + " : : = " ) ; / / go through productions I t e r a t o r <Production > p _ i t =tmp . i t e r a t o r ( ) ; while ( p _ i t . hasNext ( ) ) { / / go through symbols I t e r a t o r <Symbol> s _ i t = p _ i t . next ( ) . i t e r a t o r ( ) ;
  • 48. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XXVIII while ( s _ i t . hasNext ( ) ) { stream . concat ( s _ i t . next ( ) . getSymbol ( ) ) ; } stream . concat ( " | " ) ; } stream=stream . trim ( ) ; stream . concat ( " n" ) ; / / get next rule } return stream ; } /∗∗ ∗ Returns the address of the rule defining the argument non−terminal symbol , ∗ i f i t exists ; otherwise returns NULL. ∗/ public Rule findRule ( f i n a l Symbol nonterminal ) throws Exception { I t e r a t o r <Rule> r u l e I t =this . i t e r a t o r ( ) ; Rule tmp ; while ( r u l e I t . hasNext ( ) ) { tmp= r u l e I t . next ( ) ; i f ( tmp . lhs . get ( tmp . lhs . size () −1).makeComparison ( nonterminal ) ) return tmp ; } return null ; }
  • 49. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XXIX /∗∗ ∗Returns the calculated recursive nature of the Rule passed as argument , ∗and updates i t s minimum mapping depth ( minimumDepth ) ∗/ private boolean isRecursive ( ArrayList <Symbol> visitedRules , Rule currentRule ) { I t e r a t o r <Production > prodIt =currentRule . i t e r a t o r ( ) ; I t e r a t o r <Symbol> symbIt ; I t e r a t o r <Symbol> v i s i t e d R u l e s I t =visitedRules . i t e r a t o r ( ) ; Rule r u l e P t r =null ; boolean r e s u l t ; / / DON’T DO IT − otherwise minimumDepth i s not updated properly / / I f t h i s rule has already been labeled , e x i t / / i f ( currentRule−>getRecursive ( ) ! = SI_Undef ) { / / return currentRule−>getRecursive ( ) ; / / } / / Check i f t h i s i s a recursive c a l l to a previously v i s i t e d rule while ( v i s i t e d R u l e s I t . hasNext ( ) ) { i f ( v i s i t e d R u l e s I t . next ( ) . makeComparison ( currentRule . lhs . get ( currentRule . lhs . si currentRule . setRecursive ( true ) ; return true ; } } / / Go through each production in the rule while ( prodIt . hasNext ( ) ) { Production tmp_pd= prodIt . next ( ) ;
  • 50. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XXX tmp_pd . setMinimumDepth ( 0 ) ; symbIt=tmp_pd . i t e r a t o r ( ) ; / / Go through each symbol in the production while ( symbIt . hasNext ( ) ) { Symbol tmp_symb=symbIt . next ( ) ; i f ( tmp_symb . getType ( ) . to St ri ng ( ) . equals ( "NTSymbol" ) ) { / / Symbol i s non− try { r u l e P t r =findRule ( tmp_symb ) ; / / Find defining rule } catch ( java . lang . Exception e ) { / / do nothing } i f ( r u l e P t r != null ) { / / Symbol i s defined / / Recursive c a l l visitedRules . add ( currentRule . lhs . get ( currentRule . lhs . s r e s u l t =isRecursive ( visitedRules , r u l e P t r ) ; visitedRules . remove ( visitedRules . size () −1); i f ( r e s u l t ) { / / Production i s recursive / / Mark production as recursive tmp_pd . setRecursive ( true ) ; / / Mark current rule also as recursive currentRule . setRecursive ( true ) ; } i f ( tmp_pd . getMinimumDepth () <( r u l e P t r . getMinimumDepth ( ) tmp_pd . setMinimumDepth ( r u l e P t r . getMinimumDepth } } else { / / Non−defined non−terminal symbols are considered term
  • 51. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XXXI i f ( tmp_pd . getMinimumDepth () <1){ tmp_pd . setMinimumDepth ( 1 ) ; } } } else { / / Terminal symbol i f ( tmp_pd . getMinimumDepth () <1){ tmp_pd . setMinimumDepth ( 1 ) ; } } } / / i f ( prodIt −>getRecursive ()== SI_Undef ) { / / Production i s not recursive / / prodIt −>setRecursive ( SI_NonRec ) ; / / } i f ( currentRule . getMinimumDepth () >tmp_pd . getMinimumDepth ( ) ) { / / Update rule mini currentRule . setMinimumDepth ( tmp_pd . getMinimumDepth ( ) ) ; } / / prodIt ++; } / / i f ( currentRule−>getRecursive ( ) ! = SI_Rec ) { / / Rule i s not recursive , as i t contains no / / currentRule−>setRecursive ( SI_NonRec ) ; / / return SI_NonRec ; / / } / / return SI_Rec ; return currentRule . getRecursive ( ) ; } /∗∗
  • 52. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XXXII ∗ Update recursive and minimumDepth f i e l d s f o r every Rule ∗/ / / and Production in grammar . private void updateRuleFields ( ) { ArrayList <Symbol> visitedRules=new ArrayList ( ) ; I t e r a t o r <Rule> r u l e I t =this . i t e r a t o r ( ) ; clearRuleFields ( ) ; / / Go through each rule in the grammar while ( r u l e I t . hasNext ( ) ) { try { visitedRules . clear ( ) ; } catch ( java . lang . NullPointerException e ) { System . out . p r i n t l n ( e+" UpdateRuleFields sucks " ) ; } Rule tmp_rule= r u l e I t . next ( ) ; tmp_rule . setRecursive ( isRecursive ( visitedRules , tmp_rule ) ) ; } / / Second pass , to c o r r e c t l y update a l l recursive rules r u l e I t =this . i t e r a t o r ( ) ; while ( r u l e I t . hasNext ( ) ) { try { visitedRules . clear ( ) ; } catch ( java . lang . NullPointerException e ) {
  • 53. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XXXIII System . out . p r i n t l n ( e+" UpdateRuleFields sucks " ) ; } Rule tmp_rule= r u l e I t . next ( ) ; tmp_rule . setRecursive ( isRecursive ( visitedRules , tmp_rule ) ) ; } } /∗∗ ∗ Update recursive and minimumDepth f i e l d s f o r every Rule ∗/ / / and Production in grammar . private void clearRuleFields ( ) { I t e r a t o r <Rule> r u l e I t =this . i t e r a t o r ( ) ; / / Reset minimum depths and recursion f i e l d s while ( r u l e I t . hasNext ( ) ) { Rule tmp_rule= r u l e I t . next ( ) ; tmp_rule . setMinimumDepth(32767 > >1); tmp_rule . setRecursive ( false ) ; } } / / ERROR FUNCTION private boolean ERROR_IN_GRAMMAR( ) { System . out . p r i n t l n ( "Grammar not loaded ; " ) ; try { this . clear ( ) ; } catch ( java . lang . NullPointerException e ) {
  • 54. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen CONTEXT-FREE GRAMMAR XXXIV System . out . p r i n t l n ( e ) ; } setValidGrammar ( false ) ; try { phenotype . clear ( ) ; phenotype . setValid ( false ) ; } catch ( java . lang . NullPointerException e ) { System . out . p r i n t l n ( e ) ; } return false ; } } / / F i r s t implementation i s complete , t h i s f i l e may pose a l o t of bugs .
  • 55. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR I /∗ ∗ GEGrammar. java ∗ ∗ Created on August 2 , 2007, 12:22 AM ∗ ∗ To change t h i s template , choose Tools | Template Manager ∗ and open the template in the e d i t o r . ∗/ package GrammaticOptimization ; /∗∗ ∗ ∗ @author a d i l r a j a ∗/ import java . u t i l . ∗ ; import java . u t i l . L i s t I t e r a t o r ; public class GEGrammar extends CFGrammar { private int maxWraps ; protected ArrayList <Production > productions ; /∗∗ ∗ Creates a new instance of GEGrammar ∗/
  • 56. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR II public GEGrammar ( ) { super ( ) ; setMaxWraps ( 0 ) ; } /∗∗ ∗Constructor s e t t i n g the genotype s t r u c t u r e of t h i s mapper to newGenotype . ∗/ public GEGrammar( f i n a l Genotype newGenotype ) { super ( newGenotype ) ; setMaxWraps ( 0 ) ; productions=new ArrayList ( ) ; } /∗∗ ∗Constructor s e t t i n g the phenotype s t r u c t u r e of t h i s mapper to newPhenotype . ∗/ public GEGrammar( f i n a l Phenotype newPhenotype ) { super ( newPhenotype ) ; setMaxWraps ( 0 ) ; } /∗∗ ∗ Copy Constructor . ∗/ public GEGrammar( f i n a l GEGrammar copy ) throws Exception { super ( copy ) ; setMaxWraps ( copy . getMaxWraps ( ) ) ;
  • 57. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR III / / Call genotype2Phenotype ( ) to regenerate phenotype structure , / / and productions and derivationTree structures . genotype2phenotype ( true ) ; } /∗∗ ∗ Return number of maximum allowed wrapping events . ∗/ public f i n a l int getMaxWraps ( ) { return maxWraps ; } /∗∗ ∗ Set the new number of maximum allowed wrapping events . ∗/ public void setMaxWraps ( f i n a l int newMaxWraps ) { maxWraps=newMaxWraps ; } /∗∗ ∗ Builds the the current d e r i v a t i o n tree , and returns i t s address ; ∗ i f d e r i v a t i o n tree i s impossible to build , returns NULL. ∗/ public f i n a l Tree getTree ( ) throws Exception { i f ( ( ! getValidGrammar ( ) ) | | ( ! genotype . getValid ( ) ) | | ( getGenotype ( ) . size ( ) ! = 0 ) ) { return null ; }
  • 58. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR IV genotype2phenotype ( true ) ; return this . derivationTree ; } /∗∗ ∗ Returns a vector of a l l productions used during the mapping process . ∗/ public f i n a l ArrayList <Production > getProductions ( ) throws Exception { i f ( ( ! getValidGrammar ( ) ) | | ( ! genotype . getValid ( ) ) | | ( getGenotype ( ) . size ( ) ! = 0 ) ) { return null ; } genotype2phenotype ( true ) ; return productions ; } /∗∗ ∗ S t r i c t implementation of genotype2Phenotype i n t e r f a c e . Calls l o c a l ∗ genotype2phenotype ( bool ) method , with bool= false . ∗/ public boolean genotype2phenotype ( ) { / / t r y { return genotype2phenotype ( false ) ; / / } / / catch ( Exception e ) { / / System . out . p r i n t l n ( e+" genotype2phenotype ( ) " ) ; / / return false ;
  • 59. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR V / / } } /∗∗ ∗ Updates the contents of the phenotype structure , based on the current ∗ genotype and the current grammar , and according to the standard GE ∗ mapping process . Returns true upon a successful mapping , and false ∗ otherwise , and also updates the v a l i d f i e l d of the phenotype . ∗ With argument set to true , also updates derivationTree . ∗/ public boolean genotype2phenotype ( f i n a l boolean buildDerivationTree ) { this . derivationTree=new Tree ( ) ; / / I n i t i a l i z e the tree boolean returnValue=true ; int newEffectiveSize =0; / / Start by s e t t i n g e f f e c t i v e S i z e to 0 genotype . setEffectiveSize ( newEffectiveSize ) ; this . phenotype=new Phenotype ( true , 1 ) ; i f ( ! phenotype . isEmpty ( ) ) phenotype . clear ( ) ; i f ( buildDerivationTree ) { this . productions . clear ( ) ; } / / Quick safety checks / / i f ( ( ! getValidGrammar ( ) ) | | ( ! genotype . getValid ( ) ) | | ( ! getGenotype()−> size ( ) ) ) { i f ( ! getValidGrammar ( ) ) { phenotype . clear ( ) ;
  • 60. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR VI phenotype . setValid ( false ) ; return false ; } / / Wraps counter and nonterminals stack int wraps =0; Stack <Symbol> nonterminals=new Stack ( ) ; / / I t e r a t o r s I t e r a t o r <Rule> r u l e I t ; L i s t I t e r a t o r <Production > prodIt ; I t e r a t o r <Integer > genoIt=genotype . i t e r a t o r ( ) ; Integer tmpInt ; / / s h a l l contain the values in Genotype / / Start with the s t a r t symbol nonterminals . push ( getStartSymbol ( ) ) ; i f ( buildDerivationTree ) { / / Use s t a r t symbol as the derivationTree node try { derivationTree . setData ( getStartSymbol ( ) ) ; } catch ( java . lang . NullPointerException e ) { System . out . p r i n t l n ( e+" The c a l l : derivationTree . setData ( getStartSymbol ( ) ) ; in } } boolean gotToUseWrap=true ; Integer codonGenoIt=new Integer ( genoIt . next ( ) . intValue ( ) ) ;
  • 61. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR VII / / Get r i d of a l l non−terminal symbols while ( ( ! nonterminals . empty ())&&( wraps<=getMaxWraps ( ) ) ) { / / Do a mapping step switch ( genotype2phenotypeStep ( nonterminals , codonGenoIt , buildDerivationTree ) ) case −1:returnValue=false ; break ; case 0: ; break ; case 1: codonGenoIt=new Integer ( genoIt . next ( ) . intValue ( ) ) ; / / genoIt ++; newEffectiveSize ++; i f ( gotToUseWrap ) { wraps++; gotToUseWrap=false ; } / / Check i f wrap i s needed i f ( ! genoIt . hasNext ( ) ) { / / newEffectiveSize+=genotype . size ( ) ; genoIt=genotype . i t e r a t o r ( ) ; codonGenoIt=new Integer ( genoIt . next ( ) . intValue ( ) ) ; gotToUseWrap=true ; } break ; default : System . out . p r i n t l n ( " I n t e r n a l error in genotype2Phenotype ( ) " ) ; System . out . p r i n t l n ( " Execution aborted . " ) ;
  • 62. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR VIII System . e x i t ( 0 ) ; } } / / newEffectiveSize +=( genoIt−genotype . begin ( ) ) ; / / Was the mapping successful? i f ( ( wraps>getMaxWraps ( ) ) | | ( ! nonterminals . empty ( ) ) ) { returnValue=false ; / / Add remaining symbols in nonterminals queue to phenotype while ( ! nonterminals . empty ( ) ) { phenotype . add ( nonterminals . pop ( ) ) ; } } phenotype . setValid ( returnValue ) ; genotype . setEffectiveSize ( newEffectiveSize ) ; genotype . setWraps ( wraps ) ; / / Now build d e r i v a t i o n tree , based on productions vector i f ( buildDerivationTree ) { derivationTree . clear ( ) ; derivationTree . setData ( getStartSymbol ( ) ) ; derivationTree . setCurrentLevel ( 1 ) ; derivationTree . setDepth ( 1 ) ; prodIt =productions . l i s t I t e r a t o r ( ) ; / / something wrong here buildDTree ( derivationTree , prodIt ) ; } return returnValue ; } /∗∗
  • 63. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR IX ∗ Updates the contents of the genotype structure , based on the current ∗ phenotype and the current grammar , and according to a mapping process ∗ corresponding to the inverse of the standard GE mapping process . ∗ Returns true upon a successful inverse mapping , and false otherwise . ∗/ public boolean phenotype2genotype ( ) { return false ; / / FIXME } /∗∗ ∗ Performs one step of the mapping process , that is , maps the next ∗non−terminal symbol on the nonterminals stack passed as argument , using the ∗codon at the pos it io n pointed by genoIt . ∗Returns number of codons consumed , −1 i f not successful ∗/ public int genotype2phenotypeStep ( Stack <Symbol> nonterminals , Integer codonGenoIt , boolean bu L i s t I t e r a t o r <Production > prodIt ; int returnValue=−1; / / Find the rule f o r the current non−terminal Rule r u l e P t r =null ; try { r u l e P t r =findRule ( nonterminals . peek ( ) ) ; } catch ( java . lang . Exception e ) { System . out . p r i n t l n ( e+" genotype2phenotypeStep ( ) s r u l e P t r sucks " ) ;
  • 64. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR X } / / cerr << " mapping " << ∗( nonterminals . top ( ) ) << " with " << ∗genoIt << " n " ; i f ( r u l e P t r ==null ) { / / Undefined symbol − could be an extension symbol try { i f ( nonterminals . peek ( ) . getSymbol ( ) . startsWith ( "<GECodonValue" )&&( codonGenoIt != / / I n s e r t codon value / / Extract range f o r value from non−terminal s p e c i f i c a t i o n int low =0 , high=−1,pointer ="<GECodonValue" . length ( ) ; / / currentChar i s the f i r s t character a f t e r "<GECodonValue" char currentChar=nonterminals . peek ( ) . getSymbol ( ) . substring ( pointer , po / / Look f o r range d e f i n i t i o n s while ( Character . to St ri ng ( currentChar ) . compareTo ( ">" ) ! = 0 ) { i f ( Character . t oSt ri ng ( currentChar ) . compareTo ( "−" )==0){ / / Low range s p e c i f i c a t i o n currentChar=nonterminals . peek ( ) . getSymbol ( ) . substring ( while ( Character . i s D i g i t ( currentChar ) ) { low =( low ∗10)+( currentChar−’0 ’ ) ; currentChar=nonterminals . peek ( ) . getSymbol ( ) . s } } else i f ( Character . t oSt ri ng ( currentChar ) . compareTo ( "+" )==0){ / / High range s p e c i f i c a t i o n currentChar=nonterminals . peek ( ) . toS tr in g ( ) . substring (+ while ( Character . i s D i g i t ( currentChar ) ) { i f ( high==−1){
  • 65. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR XI high =0; } high =( high ∗10)+( currentChar−’0 ’ ) ; currentChar=nonterminals . peek ( ) . toS tr in g ( ) . su } } else { / / Ignore errors currentChar=nonterminals . peek ( ) . toS tr in g ( ) . substring (+ } } / / High range was not specified , so set i t to maximum i f ( high==−1){ high=genotype . getMaxCodonValue ( ) ; } / / Remove non−terminal nonterminals . pop ( ) ; / / P r i n t value onto " codon " String codon ; i f ( high==low ) { / / Catch d i v i s i o n by zero codon=Integer . toS tr in g ( low ) ; } else { codon=Integer . toS tr in g ( codonGenoIt . intValue ()%( high−low+1)+low } / / I n s e r t symbol with value onto phenotype phenotype . add (new Symbol ( codon , null ) ) ; returnValue =1;
  • 66. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR XII } else { / / Unknown symbol or special symbol that requires non−empty genotype / / Include symbol on phenotype phenotype . add ( nonterminals . pop ( ) ) ; / / Remove non−terminal / / nonterminals . pop ( ) ; / / I n v a l i d a t e mapping returnValue=−1; } } catch ( java . lang . NullPointerException e ) { System . out . p r i n t l n ( e ) ; } } / / else i f ( rulePtr −>getMinimumDepth() >=INT_MAX> >1){// Stuck on recursive rule / / Allow recursive rules , but only i f they consume a codon else i f ( ( r u l e P t r . getMinimumDepth() >=(32767 > >1)) / / Stuck on recursive rule &&( r u l e P t r . size () <=1)){ / / No codon w i l l be consumed / / Include symbol on phenotype phenotype . add ( nonterminals . pop ( ) ) ; / / Remove non−terminal / / nonterminals . pop ( ) ; / / I n v a l i d a t e mapping returnValue=−1; } else {
  • 67. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR XIII / / Remove non−terminal nonterminals . pop ( ) ; / / Choose production i f ( codonGenoIt==null&&r u l e P t r . size () >1){ / / Empty genotype , but symbol requires choice / / Include symbol on phenotype phenotype . add ( r u l e P t r . lhs . get ( 0 ) ) ; / / I n v a l i d a t e mapping returnValue=−1; } else { i f ( codonGenoIt==null ) { / / Empty genotype prodIt = r u l e P t r . l i s t I t e r a t o r ( 0 ) ; } else { prodIt = r u l e P t r . l i s t I t e r a t o r ( 0 ) ; int tmp=0; tmp=codonGenoIt . intValue ()% r u l e P t r . size ( ) ; for ( int i =0; i <tmp ; i ++) prodIt . next ( ) ; / / i f ( prodIt . hasPrevious ( ) ) / / prodIt . previous ( ) ; } / / Place production on productions vector Production tmpProd= prodIt . next ( ) ; i f ( buildDerivationTree ) { productions . add ( tmpProd ) ; / / tmpProd i s also used l a t t e r }
  • 68. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR XIV / / Put a l l terminal symbols at s t a r t of production onto phenotype int s_start =0; int s_stop =0; try { s_stop=tmpProd . size ( ) ; / / Instead of prodIt . size ( ) ; } catch ( java . lang . NullPointerException e ) { System . out . p r i n t l n ( e+" tmpProd i s n u l l in GEGrammar" ) ; } while ( ( s_start <s_stop)&&tmpProd . get ( s_start ) . getType ( ) . to Str in g ( ) . com phenotype . add ( tmpProd . get ( s_start ++)); / / s_start ++; } / / Push a l l remaining symbols from production onto nonterminals queue for ( ; s_stop > s_start ; s_stop−−){ nonterminals . push ( tmpProd . get ( s_stop −1)); } / / 0 or 1 choice f o r current rule , didn ’ t consume genotype codon i f ( r u l e P t r . size () <=1){ returnValue =0; } else { returnValue =1; } } } i f ( phenotype==null ) System . out . p r i n t l n ( " Phenotype i s messy" ) ;
  • 69. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR XV / / Finally , pop a l l terminal symbols on top of stack and i n s e r t onto phenotype / / t r y { while ( true ) { try { i f ( ( nonterminals . empty ( ) ) | | ( ! nonterminals . peek ( ) . getType ( ) . to St rin g ( ) . equals break ; } phenotype . add ( nonterminals . pop ( ) ) ; } catch ( java . lang . NullPointerException e ) { System . out . p r i n t l n ( e+" The whileloop at the end of genotype2phenotypeStep suck System . e x i t ( 0 ) ; } catch ( java . u t i l . EmptyStackException e ) { System . out . p r i n t l n ( e+" GEGrammar sucks . . . Stack i s empty " ) ; System . e x i t ( 0 ) ; } } / / } / / catch ( java . lang . NullPointerException e ) { / / System . out . p r i n t l n ( e+" The whileloop at the end of genotype2phenotypeStep sucks / / } return returnValue ; }
  • 70. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR XVI /∗∗ ∗ Builds the d e r i v a t i o n tree , based on the productions vector . ∗Arguments are current tree node , and i t e r a t o r on productions vector . ∗/ public void buildDTree ( Tree currentNode , L i s t I t e r a t o r <Production > prodIt ) { / / I f current symbol i s not a non−terminal , or i f a l l productions have been treated i f ( currentNode . getData ( ) . getType ( ) . t oS tri ng ( ) . compareTo ( "NTSymbol" ) ! = 0 | | ! prodIt . hasNe / / Correct productions i t e r a t o r , as no production was read from i t prodIt . previous ( ) ; return ; } / / Create new tree l e v e l I t e r a t o r <Symbol> symbIt= prodIt . next ( ) . i t e r a t o r ( ) ; ; while ( symbIt . hasNext ( ) ) { currentNode . add (new Tree ( symbIt . next ( ) , currentNode . getCurrentLevel ()+1 , curre / / symbIt ++; } / / Expand each c h i l d node I t e r a t o r <Tree> t r e e I t =currentNode . i t e r a t o r ( ) ; while ( t r e e I t . hasNext ( ) ) { try { buildDTree ( t r e e I t . next ( ) , prodIt ) ; / / prodIt . next ( ) ;
  • 71. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen GE GRAMMAR XVII } catch ( java . u t i l . NoSuchElementException e ) { System . out . p r i n t l n ( e+" The l a s t l i n e s of buildTree suck " ) ; System . e x i t ( 0 ) ; } / / t r e e I t ++; } } }
  • 72. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen BACKUS NAUR FORM I <expr > : : = mymul(<expr > , <expr >) | mysub(<expr > , <expr >) | myadd(<expr > , <expr >) | pdiv (<expr > | (<expr >) | sin (<expr >) | cos(<expr >) | tan (<expr >) | exp(<expr >) | x | y | 1.000 | <const> | −<const> <const> : : = 0. < d i g i t >< d i g i t >< d i g i t > < d i g i t > : : = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
  • 73. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen PRODUCTION I /∗ ∗ Production . java ∗ ∗ Created on June 3 , 2007, 12:24 AM ∗ ∗ To change t h i s template , choose Tools | Template Manager ∗ and open the template in the e d i t o r . ∗/ /∗∗ ∗ ∗ @author a d i l r a j a ∗/ package GrammaticOptimization ; import java . u t i l . ∗ ; import java . u t i l . ArrayList ; import java . u t i l . I t e r a t o r ; public class Production extends ArrayList <Symbol >{ private boolean recursive ; private int minimumDepth ; /∗∗
  • 74. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen PRODUCTION II ∗Creates a new production with newLength elements ∗/ public Production ( f i n a l int newLength ) { super ( ) ; this . ensureCapacity ( newLength ) ; setRecursive ( false ) ; setMinimumDepth(32767 > >1); } /∗∗ ∗Copy constructor ; copy a l l symbols ∗/ public Production ( f i n a l Production copy ) { I t e r a t o r <Symbol> i t r = copy . i t e r a t o r ( ) ; while ( i t r . hasNext ( ) ) { Symbol tmpsymb= i t r . next ( ) ; i f ( tmpsymb . getType ( ) . to St ri ng ( ) . compareTo ( " TSymbol " )==0){ this . add (new Symbol ( tmpsymb ) ) ; / / Terminal symbol , create new one } else this . add ( tmpsymb ) ; } setRecursive ( copy . recursive ) ; setMinimumDepth ( copy . minimumDepth ) ; } /∗∗ ∗Delete a l l terminal symbols and a l l symbol references ∗/ public void clearTerminals ( ) {
  • 75. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen PRODUCTION III I t e r a t o r <Symbol> i t r = this . i t e r a t o r ( ) ; while ( i t r . hasNext ( ) ) { Symbol tmpsymb= i t r . next ( ) ; i f ( tmpsymb . getType ( ) . to St ri ng ( ) . compareTo ( " TSymbol " )==0){ this . remove ( tmpsymb ) ; } } } /∗∗ ∗Return the recursive nature of t h i s production ∗/ public f i n a l boolean getRecursive ( ) { return this . recursive ; } /∗∗ ∗Update the recursive nature of t h i s production ∗/ public void setRecursive ( f i n a l boolean newRecursive ) { this . recursive=newRecursive ; } /∗∗ ∗Return the minimum mapping depth of t h i s production ∗/ public f i n a l int getMinimumDepth ( ) {
  • 76. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen PRODUCTION IV return this . minimumDepth ; } /∗∗ ∗Update the minimum mapping depth of t h i s production ∗/ public void setMinimumDepth ( f i n a l int newMinimumDepth ) { this . minimumDepth=newMinimumDepth ; } /∗∗ ∗P r i n t the contents of t h i s production ∗/ /∗∗ ∗This removes and adds a symbol at a p a r t i c u l a r l oc at io n in t h i s object . To be called l a ∗/ public void insertSymbol ( f i n a l Symbol symb , int pos ) { this . remove ( pos ) ; this . add ( pos , symb ) ; } } / / f i l e complete
  • 77. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen RULE I /∗ ∗ Rule . java ∗ ∗ Created on June 21 , 2007, 12:06 PM ∗ ∗ To change t h i s template , choose Tools | Template Manager ∗ and open the template in the e d i t o r . ∗/ package GrammaticOptimization ; /∗∗ ∗ ∗ @author a d i l r a j a ∗/ import java . u t i l . ∗ ; import java . u t i l . ArrayList ; / / The l e f t −hand side of the rule public class Rule extends ArrayList <Production >{ private boolean recursive ; / / Recursive nature of rule private int minimumDepth ; / / Minimum depth of parse tree f o r production to map to termin public ArrayList <Symbol> lhs ; /∗∗ ∗Creates a new rule with newLength elements . ∗/ public Rule ( f i n a l int newLength ) { super ( newLength ) ; this . ensureCapacity ( newLength ) ; setRecursive ( false ) ;
  • 78. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen RULE II setMinimumDepth(32767 > >1); lhs =new ArrayList ( ) ; } /∗∗ ∗Copy constructor ∗/ public Rule ( f i n a l Rule copy ) { super ( ) ; lhs=new ArrayList ( ) ; I t e r a t o r <Symbol> l h s I t =copy . lhs . i t e r a t o r ( ) ; while ( l h s I t . hasNext ( ) ) { Symbol tmpsymb= l h s I t . next ( ) ; lhs . add (new Symbol ( tmpsymb ) ) ; } setRecursive ( copy . getRecursive ( ) ) ; setMinimumDepth ( copy . getMinimumDepth ( ) ) ; } /∗∗ ∗Delete a l l productions , and a l l symbols stored in lhs . ∗/ public void clear ( ) { try { lhs . clear ( ) ; / / clear the lhs vector super . clear ( ) ; / / Clear production vector }
  • 79. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen RULE III catch ( java . lang . Exception e ) { System . out . p r i n t ( e ) ; } } /∗∗ ∗Return the recursive nature of t h i s rule . ∗/ public f i n a l boolean getRecursive ( ) { return recursive ; } /∗∗ ∗Update the recursive nature of t h i s rule . ∗/ public void setRecursive ( f i n a l boolean newRecursive ) { recursive=newRecursive ; } /∗∗ ∗Return the minimum mapping depth of t h i s rule . ∗/ public f i n a l int getMinimumDepth ( ) { return minimumDepth ; }
  • 80. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen RULE IV /∗∗ ∗ Update the minimum mapping depth of t h i s Rule . ∗/ public void setMinimumDepth ( f i n a l int newMinimumDepth ) { minimumDepth=newMinimumDepth ; } }
  • 81. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen MAPPER I /∗ ∗ Mapper . java ∗ ∗ Created on June 1 , 2007, 11:24 PM ∗ ∗ To change t h i s template , choose Tools | Template Manager ∗ and open the template in the e d i t o r . ∗/ /∗∗ ∗ ∗ @author a d i l r a j a ∗/ package GrammaticOptimization ; import java . u t i l . ∗ ; import java . u t i l . ArrayList ; public abstract class Mapper extends ArrayList <Rule> { protected Genotype genotype ; protected Phenotype phenotype ; protected abstract boolean genotype2phenotype ( ) ; protected abstract boolean phenotype2genotype ( ) ; public Mapper ( ) { super ( ) ;
  • 82. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen MAPPER II phenotype=new Phenotype ( ) ; genotype=new Genotype ( ) ; } /∗∗ ∗Constructor with genotype s t r u c t u r e . set to new newGenotype ∗/ public Mapper ( f i n a l Genotype newGenotype ) { super ( ) ; this . genotype=newGenotype ; } /∗∗ ∗Constructor with phenotype s t r u c t o r . set phenotype to newPhenotype ∗/ public Mapper ( f i n a l Phenotype newPhenotype ) { super ( ) ; this . phenotype=new Phenotype ( newPhenotype ) ; } /∗∗ ∗Copy Constructor ∗/ public Mapper ( f i n a l Mapper copy ) { this . genotype=new Genotype ( copy . genotype ) ; this . phenotype=new Phenotype ( copy . phenotype ) ; } /∗∗ ∗returns the genotype s t r u c t u r e of t h i s mapper ∗/
  • 83. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen MAPPER III public f i n a l Genotype getGenotype ( ) { return this . genotype ; } /∗∗ ∗Sets t h i s mapper ’ s genotype s t r u c t u r e to be a copy of the argument , newgenotype , ∗and c a l l s the genotype2phenotype private method . ∗/ public void setGenotype ( f i n a l Genotype newGenotype ) { this . genotype=new Genotype ( newGenotype ) ; genotype2phenotype ( ) ; } /∗∗ ∗returns a pointer to the phenotype s t r u c t u r e of t h i s mapper ∗/ public f i n a l Phenotype getPhenotype ( ) { return phenotype ; } /∗∗ ∗Sets t h i s mapper ’ s phenotype s t r u c t u r e to be a copy of the argument phenotype ∗structure , and c a l l s the phenotype2genotype private method ∗/ public void setPhenotype ( f i n a l Phenotype newPhenotype ) { phenotype=new Phenotype ( newPhenotype ) ; phenotype2genotype ( ) ; } /∗∗ ∗Sets the maximum codon value of the genotype s t r u c t u r e ∗/
  • 84. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen MAPPER IV public void setGenotypeMaxCodonValue ( f i n a l int newMaxCodonValue ) { / / CodonType= i n t this . genotype . setMaxCodonValue ( newMaxCodonValue ) ; } / / something l e f t here } / / f i l e complete
  • 85. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen SYMBOL I /∗ ∗ Symbol . java ∗ ∗ Created on June 2 , 2007, 6:05 PM ∗ ∗ To change t h i s template , choose Tools | Template Manager ∗ and open the template in the e d i t o r . ∗/ /∗∗ ∗ ∗ @author a d i l r a j a ∗ ∗/ package GrammaticOptimization ; import java . u t i l . ∗ ; import java . lang . String ; / / enum SymbolType { NTSymbol , TSymbol } ; public class Symbol {
  • 86. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen SYMBOL II private SymbolType type ; private String symbol ; /∗∗ Creates a new instance of Symbol ∗/ /∗ Creat a new symbol object as a copy of newArry and with type newType , i f specified ∗/ public Symbol ( ) { setType ( SymbolType . TSymbol ) ; this . symbol=new String ( ) ; } public Symbol ( f i n a l String newArray , f i n a l SymbolType newType ) { i f ( newArray != null ) this . symbol=new String ( newArray ) ; else this . symbol=new String ( " " ) ; i f ( newType!= null ) setType ( newType ) ; else setType ( SymbolType . TSymbol ) ; } /∗∗ ∗ Copy Constructor ∗/ public Symbol ( f i n a l Symbol copy ) { try { this . symbol=new String ( copy . getSymbol ( ) ) ; } catch ( java . lang . NullPointerException e ) {
  • 87. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen SYMBOL III System . out . p r i n t l n ( e ) ; } setType ( copy . getType ( ) ) ; } /∗∗ ∗ Get the type of the symbol ∗/ public f i n a l SymbolType getType ( ) { return this . type ; } /∗ Set the type of the symbol ∗/ public void setType ( f i n a l SymbolType newType ) { this . type=newType ; } /∗∗ ∗Returns the symbol ∗/ public f i n a l String getSymbol ( ) { return this . symbol ; } /∗∗ ∗Sets the symbol ∗/ public void setSymbol ( f i n a l String newSymbol ) { this . symbol=newSymbol ; }
  • 88. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen SYMBOL IV /∗∗ ∗ ∗/ public boolean makeComparison ( f i n a l Symbol newSymbol ) { i f ( this . symbol . compareTo ( newSymbol . symbol)==0 && this . getType ( ) . t oS tr in g ( ) . compareTo ( n return true ; return false ; } public void clear ( ) { this . symbol=" " ; } } / / under consideration
  • 89. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen TREE I /∗ ∗ Tree . java ∗ ∗ Created on July 27 , 2007, 3:53 PM ∗ ∗ To change t h i s template , choose Tools | Template Manager ∗ and open the template in the e d i t o r . ∗/ package GrammaticOptimization ; /∗∗ ∗ ∗ @author a d i l r a j a ∗/ import java . u t i l . ∗ ; import java . u t i l . ArrayList ; public class Tree extends ArrayList <Tree> { private Symbol data ; / / Tree i s made of objects of type symbol as opposed to a r b i t r a r y type private int depth ; private int currentLevel ; private boolean v a l i d ; /∗∗ Creates a new instance of Tree ∗/ public Tree ( ) { }
  • 90. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen TREE II /∗∗ ∗ Constructor ; i n i t i a l i s e s depth and current l e v e l . ∗/ public Tree ( f i n a l int newDepth , f i n a l int newCurrentLevel ) { depth=newDepth ; currentLevel=newCurrentLevel ; setValid ( false ) ; } /∗∗ ∗Constructor ; i n i t i a l i s e s data to match arguments . ∗/ public Tree ( f i n a l Symbol newData , f i n a l int newCurrentLevel , f i n a l int newDepth ) { data=newData ; depth=newDepth ; currentLevel=newCurrentLevel ; setValid ( true ) ; } /∗∗ ∗Copy constructor . ∗/ public Tree ( f i n a l Tree copy ) { super ( copy ) ; setData ( copy . getData ( ) ) ; setDepth ( copy . getDepth ( ) ) ;
  • 91. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen TREE III setCurrentLevel ( copy . getCurrentLevel ( ) ) ; setValid ( copy . getValid ( ) ) ; } /∗∗ ∗ Return depth from t h i s node u n t i l the deepest l e a f . ∗/ / / template <class T> public f i n a l int getDepth ( ) { return depth ; } /∗∗ ∗Set new depth of t h i s node . ∗/ public void setDepth ( f i n a l int newDepth ) { depth=newDepth ; } /∗∗ ∗Return l e v e l of t h i s node . ∗/ public f i n a l int getCurrentLevel ( ) { return currentLevel ; }
  • 92. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen TREE IV /∗∗ ∗Set new current l e v e l of t h i s node . ∗/ public void setCurrentLevel ( f i n a l int newCurrentLevel ) { currentLevel=newCurrentLevel ; } /∗∗ ∗Return data stored in t h i s node . ∗/ public f i n a l Symbol getData ( ) { i f ( getValid ( ) ) { return data ; } else { return null ; } } /∗∗ ∗ Set data to store in t h i s node . ∗/ public void setData ( f i n a l Symbol newData ) { data=new Symbol ( newData ) ; setValid ( true ) ;
  • 93. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen TREE V } /∗∗ ∗Return v a l i d i t y of t h i s node . ∗/ public f i n a l boolean getValid ( ) { return v a l i d ; } /∗∗ ∗ Set v a l i d i t y of t h i s node . ∗/ public void setValid ( f i n a l boolean newValid ) { v a l i d =newValid ; } } / / complete
  • 94. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen SUMMARY Java Beagle implements a simple genetic algorithm in Java. Implementation was focused at efficiency, ease of use and simplicity. Much of it is based on Beagle Puppy. It is open source and can be found online.
  • 95. Introduction GE’s Main Initializer Genotype Grammar Production Rule Mapper Symbol Tree Summary Referen REFERENCES GO can be found online. This presentation is developed with Beamer: Darmstadt, crane.