gap
Class GPProgram

java.lang.Object
  |
  +--gap.GPProgram
All Implemented Interfaces:
java.lang.Cloneable, Executable, java.io.Serializable

public class GPProgram
extends java.lang.Object
implements Executable, java.lang.Cloneable, java.io.Serializable

The GPProgram class contains a program tree and methods to execute and manipulate it.

Author:
Pietro Berkes, Samuele Pedroni
See Also:
Serialized Form

Field Summary
protected  gap.GPProgramArray adf
          "Array" containing the automatically defined functions.
static int ADF_EXCL
          Used in methods with a "mask" argument.
static int ADF_ONLY
          Used in methods with a "mask" argument.
static java.lang.String ADF_PFX
          This token marks the beginning of an ADF program tree in a string representation.
static java.lang.String ADFLINK_PFX
          This token represent an ADF in a string representation.
static java.lang.String ARG_PFX
          This token represent a program argument in a string representation.
static int EMPTY_MASK
          Used in methods with a "mask" argument.
protected static int ERROR
          Error value.
static int NO_TYPE
          In methods with a "type" argument, use this to indicate that you don't care about the type.
protected  GPParams params
          The parameters.
protected  GPFunction root
          Root of the program tree.
static int ROOT_EXCL
          Used in methods with a "mask" argument.
protected static Ref ROOT_REF
          Constant reference which represents any reference to the root.
static java.lang.String ROOT_TOKEN
          This token marks the beginning of the main program tree in a string representation.
static int TERMINALS_EXCL
          Used in methods with a "mask" argument.
 
Constructor Summary
  GPProgram(GPParams params)
          Create a random GPProgram.
  GPProgram(GPParams params, java.io.File progrFile)
          Create a GPProgram by parsing a LISP-style string.
protected GPProgram(GPParams params, gap.GPProgramArray linkedADFs)
          Constructor for ADFs with linked ADFs.
protected GPProgram(GPParams params, int internal)
          Construct a void program (without root and ADFs).
  GPProgram(GPParams params, java.lang.String progr)
          Create a GPProgram by parsing a LISP-style string.
 
Method Summary
protected  javax.swing.tree.MutableTreeNode asJTree(GPFunction tree)
          Represent a subtree as a part of a JTree.
 javax.swing.JTree asJTree(java.lang.String name)
          Return a graphical representation of the program tree.
 java.lang.Object clone()
          Clone the program.
 void compile(java.lang.String name, java.io.File f)
          Compile the GPProgram to an independent Java class.
 void compile(java.lang.String name, java.lang.String filename)
          Compile the GPProgram to an independent Java class.
protected  GPFunction constructTree(int[] n, java.lang.String[] tokens, Ref father, GPParams params, java.util.HashMap fnames, java.util.HashMap tnames)
          Recursively construct a program subtree by parsing a list of tokens.
protected  int countPoints(GPFunction tree, int type, int mask)
          Count a subset of the nodes in a subtree.
 int countProgramPoints(int type, int mask)
          Count a subset of the nodes.
 float exec(java.lang.Object o, float[] args)
          Execute this program.
protected  int extractSuffixNr(java.lang.String str, java.lang.String pfx)
          extractSuffixNr( "pfx5" ) == 5
 boolean find(java.lang.Class[] fcl, java.util.ArrayList refs)
          Get all the references to functions of specified classes in the main program.
 boolean find(java.lang.Class[] fcl, java.util.ArrayList refs, java.util.ArrayList adfRefList, boolean upmostOnly)
          Get all the references to functions of specified classes in the main program and in the ADFs.
protected  boolean find(GPFunction tree, java.lang.Class[] fcl, java.util.ArrayList refs, boolean upmostOnly)
          Get all the references to functions of specified classes in a subtree.
protected  boolean find(GPFunction tree, int[] fidx, java.util.ArrayList refs, boolean upmostOnly)
          Get all the references to special functions of specified index in a (sub)tree.
 boolean find(int[] fidx, java.util.ArrayList refs, java.util.ArrayList adfRefList, boolean upmostOnly)
          Get all the references to special functions of specified index in the main program and in the ADFs.
protected  int getMaxDepth(GPFunction tree)
          Compute the maximal depth of a tree.
 GPParams getParams()
          Return the parameters.
protected  int getRefTo(GPFunction tree, int n, int type, int mask, Ref r)
          Get a reference to a function by the number in a subtree.
protected  Ref getRefTo(GPProgram progr, int n, int type, int mask)
          Get a reference to a function by its number in the program tree.
static GPProgram load(java.io.File f)
          Load a program.
static GPProgram load(java.lang.String filename)
          Load a program.
 GPProgram mutate()
          Mutate.
protected  GPProgram mutate(int mask)
          Mutate.
protected  GPFunction newTree(int depth, Ref father)
          Create a new program tree.
protected  void parse(java.lang.String progr)
          Parse a program string.
protected  boolean sameType(int type, GPFunction f)
          Compare a type with the type of a GPFunction.
 void save(java.io.File f)
          Save the program.
 void save(java.lang.String filename)
          Save the program.
 int size()
          Compute the size of the program tree.
 java.lang.String toString()
          Pretty print the program tree and the ADFs.
 GPProgram xover(GPProgram partner)
          Crossover.
protected  GPProgram xover(GPProgram partner, int mask)
          Crossover.
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

root

protected GPFunction root
Root of the program tree.

adf

protected gap.GPProgramArray adf
"Array" containing the automatically defined functions.

params

protected GPParams params
The parameters.

ROOT_REF

protected static final Ref ROOT_REF
Constant reference which represents any reference to the root.

ROOT_TOKEN

public static final java.lang.String ROOT_TOKEN
This token marks the beginning of the main program tree in a string representation.
See Also:
GPProgram(GPParams, String), toString()

ADF_PFX

public static final java.lang.String ADF_PFX
This token marks the beginning of an ADF program tree in a string representation.
See Also:
GPProgram(GPParams, String), toString()

ADFLINK_PFX

public static final java.lang.String ADFLINK_PFX
This token represent an ADF in a string representation.
See Also:
GPProgram(GPParams, String), toString()

ARG_PFX

public static final java.lang.String ARG_PFX
This token represent a program argument in a string representation.
See Also:
GPProgram(GPParams, String), toString()

ERROR

protected static final int ERROR
Error value.

NO_TYPE

public static final int NO_TYPE
In methods with a "type" argument, use this to indicate that you don't care about the type.

EMPTY_MASK

public static final int EMPTY_MASK
Used in methods with a "mask" argument. No special modifiers.

ROOT_EXCL

public static final int ROOT_EXCL
Used in methods with a "mask" argument. The root is excluded from the computation.

TERMINALS_EXCL

public static final int TERMINALS_EXCL
Used in methods with a "mask" argument. The terminals are excluded from the computation.

ADF_EXCL

public static final int ADF_EXCL
Used in methods with a "mask" argument. The ADF are excluded from the computation.

ADF_ONLY

public static final int ADF_ONLY
Used in methods with a "mask" argument. Only the ADF are used in the computations.
Constructor Detail

GPProgram

public GPProgram(GPParams params)
          throws ParametersNotProperlySetException
Create a random GPProgram.
Parameters:
params - The parameters from which to create the program.
Throws:
ParametersNotProperlySetException - If the parameters definition is inconsistent.

GPProgram

protected GPProgram(GPParams params,
                    gap.GPProgramArray linkedADFs)
             throws java.lang.InstantiationException
Constructor for ADFs with linked ADFs.

GPProgram

public GPProgram(GPParams params,
                 java.io.File progrFile)
          throws InvalidProgramStringException,
                 ParametersNotProperlySetException
Create a GPProgram by parsing a LISP-style string.

The program string is read from the specified file and parsed as in GPProgram(GPParams, String)

Parameters:
params - The parameters of the program.
progrFile - An ASCII file from which to read the program string.
Throws:
InvalidProgramStringException - If a syntax error is found or if the program string is not compatible with the parameters.
ParametersNotProperlySetException - If the parameters definition is inconsistent.
See Also:
GPProgram(GPParams, String)

GPProgram

public GPProgram(GPParams params,
                 java.lang.String progr)
          throws InvalidProgramStringException,
                 ParametersNotProperlySetException
Create a GPProgram by parsing a LISP-style string.

The string format is closed with respect to the toString() output: the result of the toString() method can be used as input for this constructor. Schema of a program string :

 root:
 RootFunction( Func1(Term1, Term2), ADF0(Term3, Arg0) )
 adf_root0:
 ADF0RootFunction( ... )
 adf_root1:
 ADF1RootFunction( ... )
 

The string can also set random constants in terminals, if the name of the corresponding field in the terminal class is randInt or randFloat (as in the automatically generated classes). The value has to be specified after the terminal name, in the toString() format:

 Sum( IntegerNumber<5>, FloatNumber<4.32> )
 

Parenthesis and commas are ignored, so that the followting expressions are equivalent:

 (Sum(Arg0 Arg1))
 Sum( Arg0, Arg1 )
 Sum Arg0 Arg1
 
There are no ambiguities, as the number of argument of each function are fixed and the arguments are assigned in a depth-first way.
Parameters:
params - The parameters of the program.
progr - The program string.
Throws:
InvalidProgramStringException - If a syntax error is found or if the program string is not compatible with the parameters.
ParametersNotProperlySetException - If the parameters definition is inconsistent.

GPProgram

protected GPProgram(GPParams params,
                    int internal)
Construct a void program (without root and ADFs).
Parameters:
internal - Ignored.
Method Detail

getParams

public GPParams getParams()
Return the parameters.

newTree

protected GPFunction newTree(int depth,
                             Ref father)
                      throws java.lang.InstantiationException
Create a new program tree.

The "grow" method is used.

Parameters:
depth - Maximal depth.
father - The father of the subtree to be created. ROOT_REF if root.
Returns:
The root function.
Throws:
java.lang.InstantiationException - If it coldn't create an instance of a GPFunction or GPTerminal of the function set.
See Also:
ROOT_REF

extractSuffixNr

protected int extractSuffixNr(java.lang.String str,
                              java.lang.String pfx)
extractSuffixNr( "pfx5" ) == 5
Parameters:
pfx - String prefix.
Returns:
The number after the prefix, ERROR if error.

parse

protected void parse(java.lang.String progr)
              throws InvalidProgramStringException,
                     java.lang.InstantiationException
Parse a program string.
Throws:
InvalidProgramStringException - If a syntax error is found or if the program string is not compatible with the parameters.
See Also:
GPProgram(GPParams, String)

constructTree

protected GPFunction constructTree(int[] n,
                                   java.lang.String[] tokens,
                                   Ref father,
                                   GPParams params,
                                   java.util.HashMap fnames,
                                   java.util.HashMap tnames)
                            throws InvalidProgramStringException,
                                   java.lang.InstantiationException
Recursively construct a program subtree by parsing a list of tokens.
Parameters:
n - Position in the tokens array.
tokens - Array of tokens extracted from the program string.
father - Reference to the father of the subtree. ROOT_REF if root.
fnames - Names of the functions in the function set.
tnames - Names of the terminals in the terminal set.
See Also:
parse(String)

exec

public float exec(java.lang.Object o,
                  float[] args)
Execute this program.

The object passed can be used for example to implement side effects of the functions or to store internal variables.

Specified by:
exec in interface Executable
Parameters:
o - An object that your GPFunctions may want to use.
args - The arguments of the main function.
Returns:
The return value of the root function.

clone

public java.lang.Object clone()
Clone the program.

Make a deep clone of the program tree and of the ADFs. The parameters of the program are not cloned.

Overrides:
clone in class java.lang.Object

toString

public java.lang.String toString()
Pretty print the program tree and the ADFs.

The returned string could be quite large.

Overrides:
toString in class java.lang.Object

mutate

public GPProgram mutate()
                 throws ParametersNotProperlySetException
Mutate.

If the created program is too large, ths function returns a clone of this program.


mutate

protected GPProgram mutate(int mask)
                    throws ParametersNotProperlySetException
Mutate.
Parameters:
mask - EMPTY_MASK, ROOT_EXCL and ADF_EXCL allowed.

xover

public GPProgram xover(GPProgram partner)
Crossover.

Assumed: this program and his partner share the same parameters.

First the function decides if the crossover point is going to be choosed in an ADF (if defined) according to the geneticOpInADFFreq variable in the parameters. Then a random xover point (1) is chosen from this program tree. A random compatible point (2) in the partner is then chosen and inserted at point (1).

Neither this program nor the partner are modified. A clone is returned if the result is too large or il no compatible point is found.


xover

protected GPProgram xover(GPProgram partner,
                          int mask)
Crossover.
Parameters:
mask - EMPTY_MASK and ADF_EXCL allowed.
See Also:
xover(GPProgram)

size

public int size()
Compute the size of the program tree.
Returns:
The number of functions and terminals in the main program tree and in the ADFs.

countProgramPoints

public int countProgramPoints(int type,
                              int mask)
Count a subset of the nodes.
Parameters:
type - Count the nodes of this type.
mask - EMPTY_MASK, ROOT_EXCL, TERMINALS_EXCL, ADF_EXCL and ADF_ONLY (or a combination) allowed.
Returns:
The number of functions and terminals in the main program and in the ADFs compatible with type and with the mask.
See Also:
NO_TYPE

countPoints

protected int countPoints(GPFunction tree,
                          int type,
                          int mask)
Count a subset of the nodes in a subtree.
Parameters:
tree - The subtree.
type - Count the nodes of this type.
mask - EMPTY_MASK and TERMINALS_EXCL allowed.
See Also:
NO_TYPE, countProgramPoints(int, int)

getMaxDepth

protected int getMaxDepth(GPFunction tree)
Compute the maximal depth of a tree.
Parameters:
tree - The root of a program tree.

getRefTo

protected Ref getRefTo(GPProgram progr,
                       int n,
                       int type,
                       int mask)
Get a reference to a function by its number in the program tree.

Used to choose a random function in the program tree.

Parameters:
mask - EMPTY_MASK, ROOT_EXCL and TERMINALS_EXCL allowed.

getRefTo

protected int getRefTo(GPFunction tree,
                       int n,
                       int type,
                       int mask,
                       Ref r)
Get a reference to a function by the number in a subtree.
Parameters:
mask - EMPTY_MASK, ROOT_EXCL and TERMINALS_EXCL allowed.

sameType

protected boolean sameType(int type,
                           GPFunction f)
Compare a type with the type of a GPFunction.

The GPFunction could be an ADF or an Argument...


find

public boolean find(java.lang.Class[] fcl,
                    java.util.ArrayList refs)
Get all the references to functions of specified classes in the main program.
Parameters:
fcl - Array of subclasses of GPFunction, to find in the program.
refs - The references are stored here. Set to null if you don't care about them.
Returns:
true if found at least one reference, false otherwise.
See Also:
Ref

find

public boolean find(java.lang.Class[] fcl,
                    java.util.ArrayList refs,
                    java.util.ArrayList adfRefList,
                    boolean upmostOnly)
Get all the references to functions of specified classes in the main program and in the ADFs.

Note: a changement in the function- OR terminal- set in an ADF (with respect to the corresponding sets in the main program tree) will stop this method from searching into that ADF.

Parameters:
fcl - Array of subclasses of GPFunction, to find in the program.
refs - List of Refs in the main program. Set to null if you don't care about them.
adfRefList - List (a list for each ADF) of lists of Refs in the ADFs. Set to null if you don't care about them.
upmostOnly - If true return references only to the upmost functions.
Returns:
true if found at least one reference, false otherwise.
See Also:
Ref

find

protected boolean find(GPFunction tree,
                       java.lang.Class[] fcl,
                       java.util.ArrayList refs,
                       boolean upmostOnly)
Get all the references to functions of specified classes in a subtree.
Returns:
true if found at least one reference, false otherwise.

find

public boolean find(int[] fidx,
                    java.util.ArrayList refs,
                    java.util.ArrayList adfRefList,
                    boolean upmostOnly)
Get all the references to special functions of specified index in the main program and in the ADFs.

The indices of ADFunctions must be specified by their (positive) value, while those of arguments must be specified by the negative-1 of their value. E.g.: "find ADF #2 and argument #0": int[] fidx = {2,-1};

Returns:
true if found at least one reference, false otherwise.

find

protected boolean find(GPFunction tree,
                       int[] fidx,
                       java.util.ArrayList refs,
                       boolean upmostOnly)
Get all the references to special functions of specified index in a (sub)tree.
Returns:
true if found at least one reference, false otherwise.

compile

public void compile(java.lang.String name,
                    java.lang.String filename)
             throws CompileFailureException,
                    java.io.IOException
Compile the GPProgram to an independent Java class.
Parameters:
name - The name of the new class, package name included (e.g. 'ant.BestProgram').
filename - The name of the file in which the compiled class is written.

compile

public void compile(java.lang.String name,
                    java.io.File f)
             throws CompileFailureException,
                    java.io.IOException
Compile the GPProgram to an independent Java class.
Parameters:
name - The name of the new class, package name included (e.g. 'ant.BestProgram').
f - The file in which the new class is written.

asJTree

public javax.swing.JTree asJTree(java.lang.String name)
Return a graphical representation of the program tree.
Parameters:
name - The name of the root node of the JTree.

asJTree

protected javax.swing.tree.MutableTreeNode asJTree(GPFunction tree)
Represent a subtree as a part of a JTree.

save

public void save(java.lang.String filename)
          throws java.io.IOException
Save the program.

save

public void save(java.io.File f)
          throws java.io.IOException
Save the program.

load

public static GPProgram load(java.lang.String filename)
                      throws java.io.IOException,
                             java.lang.ClassNotFoundException
Load a program.

load

public static GPProgram load(java.io.File f)
                      throws java.io.IOException,
                             java.lang.ClassNotFoundException
Load a program.