API

Description of all the CGP-Library functions and structures.

Summary
APIDescription of all the CGP-Library functions and structures.
StructuresDescription of all the structures used by CGP-Library.
Variables
parametersStores general evolutionary and chromosome parameters used by the CGP-Library.
chromosomeStores a CGP chromosome instances used by the CGP-Library.
dataSetStores a data set which can be used by fitness functions when calculating a chromosomes fitness.
resultsStores the best chromosome found on each run when using repeatCGP
Parameters FunctionsDescription of all the functions related to CGP-Library parameters
Functions
initialiseParametersInitialises a parameters structure used throughout the CGP-Library.
freeParametersFrees parameters structure instance.
printParametersPrints the given parameters to the screen in a human readable format.
addNodeFunctionAdds pre-defined node function(s) to the set of functions stored by a parameters structure.
addCustomNodeFunctionAdds custom node function to the set of functions stored by a parameters structure.
clearFunctionSetResets the function set stored by a parameters structure to contain no functions.
setNumInputsSets the number of chromosome inputs in the given parameters.
setNumNodesSets the number of chromosome nodes in the given parameters.
setNumOutputsSets the number of chromosome outputs in the given parameters.
setAritySets the arity of the chromosome nodes in the given parameters.
setMuSets the mu value in the given parameters.
setLambdaSets the lambda value in the given parameters.
setEvolutionaryStrategySets the evolutionary strategy in the given parameters.
setMutationRateSets the mutation rate in the given parameters.
setRecurrentConnectionProbabilitySets the recurrent connection probability in the given parameters.
setShortcutConnectionsSets whether shortcut connections are used in the given parameters.
setConnectionWeightRangeSets the connection weight range in the given parameters.
setCustomFitnessFunctionSet custom fitness function.
setCustomSelectionSchemeSets custom selection scheme.
setCustomReproductionSchemeSets custom reproduction scheme.
setTargetFitnessSets the target fitness used when running CGP.
setMutationTypeSets the mutation method used when mutating chromosomes.
setUpdateFrequencySets the frequency of the updates to the user when using runCGP.
setNumThreadsSets the number of threads in the given parameters.
Chromosome FunctionsDescription of all functions and structures relating to chromosomes
Functions
initialiseChromosomeInitialises a chromosome based on the given parameters.
initialiseChromosomeFromFileInitialises a chromosome from a given previously saved chromosome.
initialiseChromosomeFromChromosomeInitialises a chromosome from a given chromosome.
freeChromosomeFrees chromosome instance.
printChromosomeDisplays the given chromosome to the terminal / command prompt in a human readable format.
executeChromosomeExecutes the given chromosome.
getChromosomeOutputGets the outputs of the given chromosome after it has been executed using executeChromosome.
getChromosomeNodeValueGets the node value of the given chromosome and node after it has been executed using executeChromosome.
isNodeActiveReturns whether the given node in the given chromosome is active.
saveChromosomeSaves the given chromosome to a file which can used to initialise new chromosomes.
saveChromosomeDotSaves the given chromosome to a graphviz .dot file.
saveChromosomeLatexSaves the given chromosome to a latex .tex file for visulisation and inclusion in written workes.
mutateChromosomeMutate the given chromosome using the mutation method described in the given parameters.
removeInactiveNodesRemoves all of the inactive nodes from the given chromosome.
setChromosomeFitnessSets the fitness of the chromosome using the fitness function given in the parameters
resetChromosomeResets all of the chromosome nodes to output zero.
copyChromosomeCopies the contents of one chromoosme into the other.
getNumChromosomeInputsGets the number of chromosome inputs
getNumChromosomeNodesGets the number of chromosome nodes
getNumChromosomeActiveNodesGets the number of chromosome active nodes
getNumChromosomeOutputsGets the number of chromosome outputs
getChromosomeNodeArityGets the arity of the chromosome nodes
getChromosomeFitnessGets the fitness of the given chromosome
getNumChromosomeActiveConnectionsGets the number of active connections in the given chromosome
getChromosomeGenerationsGets the number of generations for which the given chromosome has been trained.
DataSet FunctionsDescription of all functions and structures relating to data sets
Functions
initialiseDataSetFromArraysInitialises a dataSet structures using the given input output pairs.
initialiseDataSetFromFileInitialises a dataSet structures using the given file.
freeDataSetFrees dataSet instance.
printDataSetPrints the input output pairs held by a dataSet structure to the terminal.
saveDataSetSaves the given dataSet to a file which can be read using initialiseDataSetFromFile.
getNumDataSetInputsGets the number of dataSet inputs.
getNumDataSetOutputsGets the number of dataSet outputs.
getNumDataSetSamplesGets the number of samples in the given dataSet.
getDataSetSampleInputsGets the dataSet inputs for the given sample index.
getDataSetSampleInputGets the dataSet input for the given sample index and input index.
getDataSetSampleOutputsGets the dataSet outputs for the given sample index.
getDataSetSampleOutputGets the dataSet output for the given sample index and output index.
Results Functions
Functions
freeResultsFrees results instance.
saveResultsSaves the given results to a csv file.
getChromosomeGets a copy of the best chromosome found on the given run in an initialised results structure.
getNumChromosomesGets number of chromosomes stored in the given results structure.
getAverageFitnessGets the average fitness of the best chromosome found for each run in results.
getMedianFitnessGets the median fitness of the best chromosome found for each run in results.
getAverageActiveNodesGets the average number of active nodes of the best chromosome found for each run in results.
getMedianActiveNodesGets the median number of active nodes of the best chromosome found for each run in results.
getAverageGenerationsGets the average number generations required to find the best best chromosome for each run in results.
getMedianGenerationsGets the median number generations required to find the best best chromosome for each run in results.
CGP Functions
Functions
runCGPApplies CGP to the given task.
repeatCGPRepeatedly applies CGP to the given task.
Other
Functions
setRandomNumberSeedSets the seed used by the random number generator in CGP-Library.

Structures

Description of all the structures used by CGP-Library.

Summary
Variables
parametersStores general evolutionary and chromosome parameters used by the CGP-Library.
chromosomeStores a CGP chromosome instances used by the CGP-Library.
dataSetStores a data set which can be used by fitness functions when calculating a chromosomes fitness.
resultsStores the best chromosome found on each run when using repeatCGP

Variables

parameters

struct parameters

Stores general evolutionary and chromosome parameters used by the CGP-Library.

The parameters structure is used extensively by the CGP-Library and controls every aspect of the evolutionary algorithm and solution structure.

The values stored in parameters are set to default values when initialised using initialiseParameters.  These default values can then be altered using provided setter functions.

Defaults

Default parameter values.

mu:                               1
lambda:                           4
evolutionary strategy:            +
mutation rate:                    0.05
Recurrent Connection Probability  0.00
Shortcut Connections              1
connection weight range:          1
update frequency:                 1
mutation type:                    probabilistic
fitness function:                 supervisedLearning
selection scheme:                 selectFittest
reproduction scheme:              mutateRandomParent
number of threads                 1
  • Mu, lambda and evolutionary strategy control the type and parameter values of the evolutionary strategy used.  See setMu, setLambda and setEvolutionaryStrategy.
  • The mutation rate controls the level of mutation when creating a child solution from a parent.  See setMutationRate.
  • The recurrent connection probability controls the probability of connections being made recurrent when mutating connection genes.  For regular acyclic feed-forward programs leave as zero.  For recurrent programs see setRecurrentConnectionProbability.
  • The shortcut connections controls whether program outputs can connect directly to program inputs.  1 (yes) and 0 (no).  See setShortcutConnections
  • The connection weight range controls the range of values which the connection weights can take.  Connection weights are only considered when the CGP-Library is used to evolve artificial neural networks.  See setConnectionWeightRange.
  • The update frequency controls the frequency of updates to the terminal when using runCGP.  The value is the number of generations between updates.  See setUpdateFrequency.
  • The mutation type stores the mutation method used when mutating chromosomes.  See setMutationType.
  • The fitness function stores the fitness function used when assigning a fitness to the chromosomes.  See setCustomFitnessFunction.
  • The selection scheme stores the selection scheme used when selecting the parents from the candidate chromosomes.  See setCustomSelectionScheme.
  • The reproduction scheme stores how children chromosomes are created from their parents.  See setCustomReproductionScheme.
  • The number of threads defines how many threads the CGP library will use internally.  See setNumThreads.

See Also

initialiseParameters, freeParameters, printParameters

chromosome

struct chromosome

Stores a CGP chromosome instances used by the CGP-Library.

See Also

initialiseChromosome, initialiseChromosomeFromFile freeChromosome, printChromosome, executeChromosome, mutateChromosome

dataSet

struct dataSet

Stores a data set which can be used by fitness functions when calculating a chromosomes fitness.

Typically contains input output pairs of data used when applying CGP to supervised learning tasks.

See Also

initialiseDataSetFromFile, initialiseDataSetFromArrays, freeDataSet, printDataSet

results

struct results

Stores the best chromosome found on each run when using repeatCGP

See Also

repeatCGP, freeResults, getChromosome, getAverageFitness, getAverageActiveNodes, getAverageGenerations

Parameters Functions

Description of all the functions related to CGP-Library parameters

Summary
Functions
initialiseParametersInitialises a parameters structure used throughout the CGP-Library.
freeParametersFrees parameters structure instance.
printParametersPrints the given parameters to the screen in a human readable format.
addNodeFunctionAdds pre-defined node function(s) to the set of functions stored by a parameters structure.
addCustomNodeFunctionAdds custom node function to the set of functions stored by a parameters structure.
clearFunctionSetResets the function set stored by a parameters structure to contain no functions.
setNumInputsSets the number of chromosome inputs in the given parameters.
setNumNodesSets the number of chromosome nodes in the given parameters.
setNumOutputsSets the number of chromosome outputs in the given parameters.
setAritySets the arity of the chromosome nodes in the given parameters.
setMuSets the mu value in the given parameters.
setLambdaSets the lambda value in the given parameters.
setEvolutionaryStrategySets the evolutionary strategy in the given parameters.
setMutationRateSets the mutation rate in the given parameters.
setRecurrentConnectionProbabilitySets the recurrent connection probability in the given parameters.
setShortcutConnectionsSets whether shortcut connections are used in the given parameters.
setConnectionWeightRangeSets the connection weight range in the given parameters.
setCustomFitnessFunctionSet custom fitness function.
setCustomSelectionSchemeSets custom selection scheme.
setCustomReproductionSchemeSets custom reproduction scheme.
setTargetFitnessSets the target fitness used when running CGP.
setMutationTypeSets the mutation method used when mutating chromosomes.
setUpdateFrequencySets the frequency of the updates to the user when using runCGP.
setNumThreadsSets the number of threads in the given parameters.

Functions

initialiseParameters

DLL_EXPORT struct parameters *initialiseParameters(const int numInputs,
const int numNodes,
const int numOutputs,
const int arity)

Initialises a parameters structure used throughout the CGP-Library.  The arguments describe the structure of the chromosomes created when using initialiseChromosome, runCGP or repeatCGP.

Parameters

numInputsthe number of chromosome inputs required.
numNodesthe number of chromosome nodes required.
numOutputsthe number of chromosome outputs required.
aritythe arity of each chromosome node required.

Returns

A pointer to an initialised parameters structure.

Example

Initialising parameters

struct parameters *params;

int numInputs = 3;
int numNodes = 10;
int numOutputs = 2;
int nodeArity = 2;

params = initialiseParameters(numInputs, numNodes, numOutputs, nodeArity);

See Also

freeParameters, printParameters

freeParameters

DLL_EXPORT void freeParameters(struct parameters *params)

Frees parameters structure instance.

Parameters

paramspointer to initialised parameters structure.

See Also

initialiseParameters

printParameters

DLL_EXPORT void printParameters(struct parameters *params)

Prints the given parameters to the screen in a human readable format.

Parameters

paramspointer to parameters structure.

Example

Typical parameters structure printed using printParameters.

---------------------------------------------------
       Parameters
---------------------------------------------------
Evolutionary Strategy:      (1+4)-ES
Inputs:                     1
Nodes:                      15
Outputs:                    1
Node Arity:                 2
Connection weights range:   +/- 1.000000
Mutation Type:              probabilistic
Mutation rate:              0.050000
Fitness Function:           supervisedLearning
Target Fitness:             0.100000
Selection scheme:           selectFittest
Reproduction scheme:        mutateRandomParent
Update frequency:           500
Function Set: add sub mul div sin (5)
---------------------------------------------------

addNodeFunction

DLL_EXPORT void addNodeFunction(struct parameters *params,
char const *functionNames)

Adds pre-defined node function(s) to the set of functions stored by a parameters structure.  These are the node functions available when using runCGP, repeatCGP and mutateChromosome.

If one function name is given that function is added to the function set.  If multiple node function names are given then each must be separated by a ‘,’.

If a node function name is given which is not recognised, a warning is given and that function is not added to the function set.

Parameters

paramspointer to parameters structure
functionNamesthe name(s) of the function(s) to be added to the function set

Node Functions

mathematical operations

  • add - summation over all inputs.
  • sub - subtracts all but the first input from the first input
  • mul - multiplies all of the inputs
  • div - divides the first input by the second and then the third etc
  • abs - the absolute of the first input
  • sqrt - the square root of the first input
  • sq - the square of the first input
  • cube - the cube of the first input
  • pow - the first input raised to the power of the second input
  • exp - the exponential of the first input
  • sin - the sine of the first input
  • cos - the cosine of the first input
  • tan - the tangent of the first input

logic gates

  • and - returns ‘1’ if all inputs are ‘1’, else ‘0’
  • nand - returns ‘0’ if all inputs are ‘1’, else, ‘1’
  • or - returns ‘0’ if all inputs are ‘0’, else, ‘1’
  • nor - returns ‘1’ if all inputs are ‘0’, else, ‘0’
  • xor - returns ‘1’ if only one of the inputs is ‘1’, else, ‘0’
  • xnor - returns ‘0’ if only one of the inputs is ‘1’, else, ‘1’
  • not - returns ‘1’ if first input is ‘0’, else ‘1’

neuron transfer/activation functions

  • sig - the logistic sigmoid of the weighted sum of inputs.  Output range [0,1]
  • gauss - the Gaussian of the weighted sum of inputs.  Output range [0,1]
  • step - the heaviside step function of the weighted sum of inputs.  Output range [0,1]
  • softsign - the softsign of the weighted sum of inputs.  Output range [-1,1]
  • tanh - the hyperbolic tangent of the weighted sum of inputs.  Output range [-1,1]

Other

  • rand - produces a different random number in the range [-1,1] each time it is called
  • pi - produces the constant pi
  • 1 - produces the constant one
  • 0 - produces the constant zero
  • wire - acts as a simple wire mapping the input to the output

Example

Add the node functions logical AND OR NAND NOR and XOR to the function set.

addNodeFunction(params, "and,or,nand,nor,xor");

See Also

clearFunctionSet, addCustomNodeFunction

addCustomNodeFunction

DLL_EXPORT void addCustomNodeFunction(
   struct parameters *params,
   double (*function)(const int numInputs, const double *inputs, const double *weights),
   char const *functionName,
   int maxNumInputs
)

Adds custom node function to the set of functions stored by a parameters structure.  See addNodeFunction.

The custom fitness function prototype must take the form

double nodeFunctionName(const int numInputs, const double *inputs, const double *weights);

where the user replaces ‘nodeFunctionName’ with their own function name.

Parameters

paramspointer to an initialised parameters structure
functionthe custom node function
functionNamethe name of the added function
maxNumInputsmaximum number of inputs to function (-1 is unlimited)

Example

Creating a custom node function ‘add’

double add(const int numInputs, const double *inputs, const double *connectionWeights){

    int i;
    double sum = 0;

    for(i=0; i<numInputs; i++){
        sum += inputs[i];
    }

    return sum;
}

Adding the new custom node function to the function set

addCustomNodeFunction(params, add, "add", -1);

Note

The connections weights are used for when creating custom node functions for Artificial Neural Networks.  If required they are accessed in the same way as the inputs.

See Also

clearFunctionSet, addNodeFunction

clearFunctionSet

DLL_EXPORT void clearFunctionSet(struct parameters *params)

Resets the function set stored by a parameters structure to contain no functions.

Parameters

paramspointer to an initialised parameters structure

See Also

addNodeFunction, addCustomNodeFunction

setNumInputs

DLL_EXPORT void setNumInputs(struct parameters *params,
int numInputs)

Sets the number of chromosome inputs in the given parameters.

The given number of chromosome inputs is also parsed to ensure a valid number of chromosome inputs.  A number of chromosome inputs <0 is invalid.  If an invalid number of chromosome inputs is give an error is displayed and CGP-Library terminates.

Parameters

paramspointer to parameters structure.
numInputsThe number of chromosome inputs to be set.

See Also

setNumNodes, setNumOutputs, setArity

setNumNodes

DLL_EXPORT void setNumNodes(struct parameters *params,
int numNodes)

Sets the number of chromosome nodes in the given parameters.

The given number of chromosome nodes is also parsed to ensure a valid number of chromosome nodes.  A number of chromosome nodes <0 is invalid.  If an invalid number of chromosome nodes is give an error is displayed and CGP-Library terminates.

Parameters

paramspointer to parameters structure.
nodesThe number of chromosome nodes to be set.

See Also

setNumInputs, setNumOutputs, setArity

setNumOutputs

DLL_EXPORT void setNumOutputs(struct parameters *params,
int numOutputs)

Sets the number of chromosome outputs in the given parameters.

The given number of chromosome outputs is also parsed to ensure a valid number of chromosome outputs.  A number of chromosome outputs <1 is invalid.  If an invalid number of chromosome outputs is give an error is displayed and CGP-Library terminates.

Parameters

paramspointer to parameters structure.
numOutputsThe number of chromosome outputs to be set.

See Also

setNumInputs, setNumNodes, setArity

setArity

DLL_EXPORT void setArity(struct parameters *params,
int arity)

Sets the arity of the chromosome nodes in the given parameters.

The given arity for each chromosome node is also parsed to ensure a valid chromosome node arity.  A chromosome node arity <1 is invalid.  If an invalid chromosome node arity is give an error is displayed and CGP-Library terminates.

Parameters

paramspointer to parameters structure.
arityThe chromosome node arity to be set.

See Also

setNumInputs, setNumNodes, setNumOutputs

setMu

DLL_EXPORT void setMu(struct parameters *params,
int mu)

Sets the mu value in the given parameters.

The given mu value is also parsed to ensure a valid mu value. mu values <1 are invalid.  If an invalid mu value is give a warning is displayed and the mu value is left unchanged.

Parameters

paramspointer to parameters structure.
muThe value of mu to be set.

setLambda

DLL_EXPORT void setLambda(struct parameters *params,
int lambda)

Sets the lambda value in the given parameters.

The given lambda value is also parsed to ensure a valid lambda value. lambda values <1 are invalid.  If an invalid lambda value is give a warning is displayed and the lambda value is left unchanged.

Parameters

paramspointer to parameters structure.
lambdaThe value of lambda to be set.

setEvolutionaryStrategy

DLL_EXPORT void setEvolutionaryStrategy(struct parameters *params,
char evolutionaryStrategy)

Sets the evolutionary strategy in the given parameters.

The given evolutionary strategy is also parsed to ensure a valid evolutionary strategy.  Evolutionary strategies other than ‘+’ and ‘,’ are invalid.  If an invalid evolutionary strategy is give a warning is displayed and the evolutionary strategy is left unchanged.

Parameters

paramspointer to parameters structure.
evolutionaryStrategyThe evolutionary strategy to be set.

setMutationRate

DLL_EXPORT void setMutationRate(struct parameters *params,
double mutationRate)

Sets the mutation rate in the given parameters.

The given mutation rate is also parsed to ensure a valid mutation rate.  Mutation rate <0 or >1 are invalid.  If an invalid mutation rate is give a warning is displayed and the mutation rate is left unchanged.

Parameters

paramspointer to parameters structure.
mutationRateThe value of the mutation rate to be set.

setRecurrentConnectionProbability

DLL_EXPORT void setRecurrentConnectionProbability(
   struct parameters *params,
   double recurrentConnectionProbability
)

Sets the recurrent connection probability in the given parameters.

The recurrent connection probability specifies the probability that a mutation to a connection gene will create a recurrent connection; otherwise a standard feed forward connection is made.  The given recurrent connection probability is also parsed to ensure a valid recurrent connection probability.  Recurrent connection probability <0 or >1 are invalid.  If an invalid recurrent connection probability is give a warning is displayed and the recurrent connection probability is left unchanged.

Parameters

paramspointer to parameters structure.
recurrentConnectionProbabilityThe value of the recurrent connection probability to be set.

setShortcutConnections

DLL_EXPORT void setShortcutConnections(struct parameters *params,
int shortcutConnections)

Sets whether shortcut connections are used in the given parameters.

Shortcut Connections specifies whether an output can connect directly to an input.  Only Shortcut Connections of values 0 (no) and 1 (yes) are valid.  If an invalid value is given, a warning is displayed and the shortcut connections value is left unchanged.

Parameters

paramspointer to parameters structure.
shortcutConnectionswhether shortcut connections are used

setConnectionWeightRange

DLL_EXPORT void setConnectionWeightRange(struct parameters *params,
double weightRange)

Sets the connection weight range in the given parameters.  (only used by NeuroEvolution)

Parameters

paramspointer to parameters structure.
weightRangeThe connection weight range to be set.  (the range is +/- weightRange)

setCustomFitnessFunction

DLL_EXPORT void setCustomFitnessFunction(
   struct parameters *params,
   double (*fitnessFunction)(struct parameters *params, struct chromosome *chromo, struct dataSet *data),
   char const *fitnessFunctionName
)

Set custom fitness function.

By default the CGP-Library used a generic supervised learning fitness function where the fitness assigned to each chromosome is the sum of the absolute differences between the actual and target outputs defined in the given dataSetsetCustomFitnessFunction is used to redefine the fitness function to be one of the users design.

All custom fitness function prototype must take the following form.  Where params is a parameters structure, chromo is the chromosome to be assigned a fitness and data is a dataSet which may be used by the custom fitness function.

double functionName(struct parameters *params, struct chromosome *chromo, struct dataSet *data);

Parameters

paramspointer to parameters structure.
fitnessFunctionthe custom fitness function
fitnessFunctionNamename of custom fitness function

If the fitnessFunction parameter is set as NULL, the fitness function will be reset to the default supervised learning fitness function.

Example

Defining a custom fitness function, full adder.  Note that the dataSet does not have to be used.

double fullAdder(struct parameters *params, struct chromosome *chromo, struct data *dat){

int i;
double error = 0;

// full adder truth table
double inputs[8][3] = {{0,0,0},{0,0,1},{0,1,0},{0,1,1},{1,0,0},{1,0,1},{1,1,0},{1,1,1}};
double outputs[8][2] = {{0,0},{1,0},{1,0},{0,1},{1,0},{0,1},{0,1},{1,1}};

    //for each line in the truth table
    for(i=0; i<8; i++){

        // calculate the chromosome outputs for each set of inputs
        executeChromosome(chromo, inputs[i]);

        // If the first chromosome outputs differ from the correct outputs increment the error
        if(outputs[i][0] != getChromosomeOutput(chromo, 0) ){
            error++;
        }

        // If the second chromosome outputs differ from the correct outputs increment the error
        if(outputs[i][1] != getChromosomeOutput(chromo, 1) ){
            error++;
        }
    }

    return error;
}

Setting the new custom fitness function as the fitness function to be used

setCustomFitnessFunction(params, fullAdder, "fullAdder");

setCustomSelectionScheme

DLL_EXPORT void setCustomSelectionScheme(
   struct parameters *params,
   void (*selectionScheme)(struct parameters *params, struct chromosome **parents, struct chromosome **candidateChromos, int numParents, int numCandidateChromos),
   char const *selectionSchemeName
)

Sets custom selection scheme.

By default the selection scheme used by CGP-Library is select fittest, where the fittest members of the candidate chromosomes are always selected as the parents.  This type of selection scheme is commonly used by CGP.  setCustomSelectionScheme is used to redefine the selection scheme to be one of the users design.

The custom selection scheme prototype must take the following form.  Where params is a parameters structure, parents is an array of chromosomes used to store the selected parents, candidateChromos is an array of chromosomes containing the pool of chromosomes to select the parent from, numParents is the number of parents to be selected and numCandidateChromos is the number of candidate chromosomes.

void selectionSchemeNmes(struct parameters *params, struct chromosome **parents, struct chromosome **candidateChromos, int numParents, int numCandidateChromos);

Note

The ordering of the candidateChromos is children followed by parents.

Parameters

paramspointer to parameters structure
selectionSchemethe custom selection scheme
selectionSchemeNamename of custom selection scheme

If the selectionScheme parameter is set as NULL, the selection scheme will be reset to the default select fittest selection scheme.

Example

Defining a custom selection scheme, tournament selection.

void tournament(struct parameters *params, struct chromosome **parents, struct chromosome **candidateChromos, int numParents, int numCandidateChromos){

    int i;

    // two chromosome pointers to point to the chromosomes in the torment
    struct chromosome *candidateA;
    struct chromosome *candidateB;

    // for the number of required parents
    for(i=0; i<numParents; i++){

        // randomly select chromosomes for tournament
        candidateA = candidateChromos[rand() % numCandidateChromos];
        candidateB = candidateChromos[rand() % numCandidateChromos];

        // choose the fittest chromosome to become a parent
        if(getChromosomeFitness(candidateA) <= getChromosomeFitness(candidateB)){
            copyChromosome(parents[i], candidateA);
        }
        else{
            copyChromosome(parents[i], candidateB);
        }
    }
}

Setting the new custom selection scheme as the selection scheme to be used

setCustomSelectionScheme(params, tournament, "tournament");

See Also

setCustomFitnessFunction

setCustomReproductionScheme

DLL_EXPORT void setCustomReproductionScheme(
   struct parameters *params,
   void (*reproductionScheme)(struct parameters *params, struct chromosome **parents, struct chromosome **children, int numParents, int numChildren),
   char const *reproductionSchemeName
)

Sets custom reproduction scheme.

By default the reproduction scheme used by CGP-Library is to create each child as a mutated version of a randomly selected parent.  This type of reproduction scheme is commonly used by CGP.  setCustomReproductionScheme is used to redefine the reproduction scheme to be one of the users design.

The custom reproduction scheme prototype must take the following form.  Where params is a parameters structure, parents is an array of chromosomes which store the parents to select from, children is an array of chromosomes which will contain the children after reproduction, numParents is the number of parents available for reproduction and numChildren is the number of children to be created.

void reproductionScheme(struct parameters *params, struct chromosome **parents, struct chromosome **children, int numParents, int numChildren);

If the reproductionScheme parameter is set as NULL, the reproduction scheme will be reset to the default mutate random parent reproduction scheme.

Example

Defining a custom reproduction scheme, ...

Setting the new custom reproduction scheme as the reproduction scheme to be used

setCustomReproductionScheme(params, ..., "...");

See Also

setCustomFitnessFunction, setCustomSelectionScheme

setTargetFitness

DLL_EXPORT void setTargetFitness(struct parameters *params,
double targetFitness)

Sets the target fitness used when running CGP.

In all cases lower fitness values are used to represent fitter chromosomes.

Parameters

paramspointer to parameters structure.
targetFitnessThe target fitness to be set.

setMutationType

DLL_EXPORT void setMutationType(struct parameters *params,
char const *mutationType)

Sets the mutation method used when mutating chromosomes.

Used to set the mutation method used when running runCGP and repeatCGP or when mutating an individual chromosome using mutateChromosome.  The type of mutation used is set the parameters structure.

If an invalid mutation type is given a warning is displayed and the mutation type is left unchanged.

Mutation Methods

These are the mutation methods which can be selected from.

  • ”probabilistic”.  The default mutation method.  Mutates each chromosome gene with a given probability; set with setMutationRate.
  • ”point”.  Always mutates the same number of randomly selected genes.  The number of mutated genes is the total number of genes times the mutation rate.  Note: does not mutate weight genes, see pointANN.
  • ”pointANN”.  Point mutation when evolving artificial neural networks; includes mutations to weight genes.
  • ”onlyActive”.  Conducts probabilistic mutation on active nodes only.  Genes belonging to inactive nodes are not mutated.
  • ”single”.  Keeps mutating randomly selected genes until an active gene is mutated to a new allele.  Note: this is independent of the mutation rate set.  Note: this does not mutate weight genes.

Parameters

paramspointer to parameters structure.
mutationTypechar array specifying the mutation type.

Example

struct parameters *params = NULL;

params = initialiseParameters(1,10,1,2);
setMutationType(params, "point");

setMutationType()

See Also

setMutationRate

setUpdateFrequency

DLL_EXPORT void setUpdateFrequency(struct parameters *params,
int updateFrequency)

Sets the frequency of the updates to the user when using runCGP.

The update frequency represents the number of generations which elapse between showing the user the current best fitness.

Note

A value of ‘0’ is a special case which causes not updates to be shown.

Parameters

paramspointer to parameters structure.
updateFrequencyupdate frequency in generations.

setNumThreads

DLL_EXPORT void setNumThreads(struct parameters *params,
int numThreads)

Sets the number of threads in the given parameters.

The given number of threads is also parsed to ensure a valid value.  Values <1 are invalid.  If an invalid value is give a warning is displayed and the value is left unchanged.

Note

In order for the CGP-Library to use multiple threads it must be compiled with openMP flag set (-fopenmp for gcc/mingw).

Note

The CGP-Library ignores the OMP_NUM_THREADS environment variable.  The only method for setting the number of threads is using setNumThreads.

Parameters

paramspointer to parameters structure.
numThreadsThe number of threads to be set.

Chromosome Functions

Description of all functions and structures relating to chromosomes

Summary
Functions
initialiseChromosomeInitialises a chromosome based on the given parameters.
initialiseChromosomeFromFileInitialises a chromosome from a given previously saved chromosome.
initialiseChromosomeFromChromosomeInitialises a chromosome from a given chromosome.
freeChromosomeFrees chromosome instance.
printChromosomeDisplays the given chromosome to the terminal / command prompt in a human readable format.
executeChromosomeExecutes the given chromosome.
getChromosomeOutputGets the outputs of the given chromosome after it has been executed using executeChromosome.
getChromosomeNodeValueGets the node value of the given chromosome and node after it has been executed using executeChromosome.
isNodeActiveReturns whether the given node in the given chromosome is active.
saveChromosomeSaves the given chromosome to a file which can used to initialise new chromosomes.
saveChromosomeDotSaves the given chromosome to a graphviz .dot file.
saveChromosomeLatexSaves the given chromosome to a latex .tex file for visulisation and inclusion in written workes.
mutateChromosomeMutate the given chromosome using the mutation method described in the given parameters.
removeInactiveNodesRemoves all of the inactive nodes from the given chromosome.
setChromosomeFitnessSets the fitness of the chromosome using the fitness function given in the parameters
resetChromosomeResets all of the chromosome nodes to output zero.
copyChromosomeCopies the contents of one chromoosme into the other.
getNumChromosomeInputsGets the number of chromosome inputs
getNumChromosomeNodesGets the number of chromosome nodes
getNumChromosomeActiveNodesGets the number of chromosome active nodes
getNumChromosomeOutputsGets the number of chromosome outputs
getChromosomeNodeArityGets the arity of the chromosome nodes
getChromosomeFitnessGets the fitness of the given chromosome
getNumChromosomeActiveConnectionsGets the number of active connections in the given chromosome
getChromosomeGenerationsGets the number of generations for which the given chromosome has been trained.

Functions

initialiseChromosome

DLL_EXPORT struct chromosome *initialiseChromosome(struct parameters *params)

Initialises a chromosome based on the given parameters.

Parameters

paramspointer to parameters structure

Returns

A pointer to an initialised chromosome structure.

See Also

freeChromosome, initialiseChromosomeFromFile, initialiseChromosomeFromChromosome

initialiseChromosomeFromFile

DLL_EXPORT struct chromosome* initialiseChromosomeFromFile(char const *file)

Initialises a chromosome from a given previously saved chromosome.

Note

Only chromosomes which use node functions defined by the CGP-library can be loaded.  Chromosomes which use custom node functions cannot be loaded.

Parameters

filechar array giving the location of the chromosome to be loaded.

Returns

A pointer to an initialised chromosome structure.

Example

struct Chromosome *chromo;
char *chromoFile = "location of Chromosome";

chromo = loadChromosome(chromoFile);

See Also

freeChromosome, initialiseChromosome, initialiseChromosomeFromChromosome,

initialiseChromosomeFromChromosome

DLL_EXPORT struct chromosome *initialiseChromosomeFromChromosome(
   struct chromosome *chromo
)

Initialises a chromosome from a given chromosome.

This functions can be used to create a copy of a chromosome.

Parameters

chromopointer to an initialised chromosome structure.

Returns

A pointer to an initialised chromosome structure.

See Also

freeChromosome, initialiseChromosome, initialiseChromosomeFromFile

freeChromosome

DLL_EXPORT void freeChromosome(struct chromosome *chromo)

Frees chromosome instance.

Parameters

chromopointer to an initialised chromosome structure.

See Also

initialiseChromosome, initialiseChromosomeFromFile

printChromosome

DLL_EXPORT void printChromosome(struct chromosome *chromo,
int weights)

Displays the given chromosome to the terminal / command prompt in a human readable format.

Parameters

chromopointer to chromosome structure.
weightsif set as 1 display connections weights

Example

Typical output from printChromosome.

Each input and functioning node is labelled with its index in the chromosome.  There is a textual description of the node e.g.  input for input nodes or the operation for the function nodes.  Function node operations are followed by space separated values describing each nodes inputs.  Active nodes are also labelled with an *.  Finally the last line gives the nodes used as chromosome outputs.

(0):    input
(1):    mul 0 0 *
(2):    add 0 1 *
(3):    sub 2 0 *
(4):    mul 0 1 *
(5):    add 4 3 *
(6):    sub 4 2 *
(7):    mul 6 5 *
(8):    add 5 7 *
(9):    mul 1 6
(10):   mul 5 3
(11):   add 4 1
(12):   add 10 3
(13):   add 5 11
(14):   sub 3 6
(15):   div 5 13
outputs: 8

executeChromosome

DLL_EXPORT void executeChromosome(struct chromosome *chromo,
const double *inputs)

Executes the given chromosome.

Executes the given chromosome with the given inputs.  The dimensions of the inputs arrays must match the dimensions of the chromosome inputs.  The chromosome outputs are then accessed using getChromosomeOutput.

Parameters

chromopointer to an initialised chromosome structure.
inputsarray of doubles used as inputs to the chromosome

Example

for a chromosome with three inputs and one outputs.

struct parameters *params = NULL;
struct chromosome *chromo = NULL;

double chromoInputs[] = {1, 2};
double chromoOutput;

params = initialiseParameters(2, 10, 1, 2);
addNodeFunction(params, "add,sub,mul,sq,cube,sin");

chromo = initialiseChromosome(params);

executeChromosome(chromo, chromoInputs);

chromoOutput = getChromosomeOutput(chromo, 0);

freeParameters(params);
freeChromosome(chromo);

(end)

See Also

getChromosomeOutput

getChromosomeOutput

DLL_EXPORT double getChromosomeOutput(struct chromosome *chromo,
int output)

Gets the outputs of the given chromosome after it has been executed using executeChromosome.

After a given chromosome has been executed using executeChromosome the chromosome outputs are made available using getChromosomeOutput.

Parameters

chromopointer to an initialised chromosome structure.
outputThe index of the output to be retrieved

Example

See executeChromosome

See Also

executeChromosome

getChromosomeNodeValue

DLL_EXPORT double getChromosomeNodeValue(struct chromosome *chromo,
int node)

Gets the node value of the given chromosome and node after it has been executed using executeChromosome.

After a given chromosome has been executed using executeChromosome the chromosome node values are made available using getChromosomeNodeValue.

Parameters

chromopointer to an initialised chromosome structure.
outputThe index of the node value to be retrieved

See Also

executeChromosome, getChromosomeOutput

isNodeActive

DLL_EXPORT int isNodeActive(struct chromosome *chromo,
int node)

Returns whether the given node in the given chromosome is active.  1-active, 0-inactive

If the given node index is less than zero or greater then the number of nodes in the given chromosome and error message is displayed and the program will terminate.

Parameters

chromopointer to an initialised chromosome structure.
nodeThe index of the node

saveChromosome

DLL_EXPORT void saveChromosome(struct chromosome *chromo,
char const *fileName)

Saves the given chromosome to a file which can used to initialise new chromosomes.

New chromosomes can be initialised using the saved chromosomes by calling initialiseChromosomeFromFile.

Node

Only chromosome which use node functions defined by the CGP-library can be loaded.  Chromosomes which use custom node functions cannot be loaded.

Parameters

chromopointer to chromosome structure.
fileNamechar array giving the location of the chromosome to be saved.

See Also

initialiseChromosomeFromFile, saveChromosomeDot saveChromosomeLatex

saveChromosomeDot

DLL_EXPORT void saveChromosomeDot(struct chromosome *chromo,
int weights,
char const *fileName)

Saves the given chromosome to a graphviz .dot file.

graphviz (www.graphviz.org) is a free open source graph drawing tool.  Once installed graphviz can be used to draw the chromosomes saved using saveChromosomeDot with the following command.

dot -Tsvg chromosome.dot -o chromosome.svg

Parameters

chromopointer to chromosome structure.
weightswhether or not to include connection weights, 0 - without weights, 1 - with weights.
fileNamechar array giving the location of the chromosome dot file to be saved.

See Also

saveChromosome saveChromosomeLatex

saveChromosomeLatex

DLL_EXPORT void saveChromosomeLatex(struct chromosome *chromo,
int weights,
char const *fileName)

Saves the given chromosome to a latex .tex file for visulisation and inclusion in written workes.

LaTeX (www.http://latex-project.org/intro.html) is a free open source document preparation system.  Once installed LaTeX can be used to draw the chromosomes saved using saveChromosomeLatex with the following command.

latex chromosome.tex

or

pdflatex chromosome.tex

Parameters

chromopointer to chromosome structure.
weightswhether or not to include connection weights, 0 - without weights, 1 - with weights.
fileNamechar array giving the location of the chromosome dot file to be saved.

See Also

saveChromosome saveChromosomeLatex

mutateChromosome

DLL_EXPORT void mutateChromosome(struct parameters *params,
struct chromosome *chromo)

Mutate the given chromosome using the mutation method described in the given parameters.

Parameters

paramspointer to parameters structure
chromopointer to chromosome structure.

Example

struct parameters *params;
struct chromosome *chromo;

params = initialiseParameters(3,10,2,2);
chromo = initialiseChromosome(params);

mutateChromosome(params, chromo);

removeInactiveNodes

DLL_EXPORT void removeInactiveNodes(struct chromosome *chromo)

Removes all of the inactive nodes from the given chromosome.

Note

This operation causes the number of nodes in the chromosome to change.

Parameters

chromopointer to chromosome structure.

setChromosomeFitness

DLL_EXPORT void setChromosomeFitness(struct parameters *params,
struct chromosome *chromo,
struct dataSet *data)

Sets the fitness of the chromosome using the fitness function given in the parameters

Parameters

paramspointer to parameters structure
chromopointer to chromosome structure.
datapointer to the data used by the fitness function (NULL if not used)

See Also

getChromosomeFitness

resetChromosome

DLL_EXPORT void resetChromosome(struct chromosome *chromo)

Resets all of the chromosome nodes to output zero.

Note

This is useful when using recurrent connections where you do not want the output to be a function of the current state of the chromosome.

copyChromosome

DLL_EXPORT void copyChromosome(struct chromosome *chromoDest,
struct chromosome *chromoSrc)

Copies the contents of one chromoosme into the other.

In order for copy chromosome to opperate correctly the dimensions of the chromosomes must match i.e. the number of inputs, nodes, outputs and node arity must be the same.

Parameters

chromoDestpointer to an initialised chromosome to be copied too
chromoSrcpointer to an initialised chromosome to be copied from

See Also

initialiseChromosome

getNumChromosomeInputs

DLL_EXPORT int getNumChromosomeInputs(struct chromosome *chromo)

Gets the number of chromosome inputs

Parameters

chromopointer to an initialised chromosome structure.

Returns

Number number of chromosome inputs

See Also

initialiseChromosome

getNumChromosomeNodes

DLL_EXPORT int getNumChromosomeNodes(struct chromosome *chromo)

Gets the number of chromosome nodes

Parameters

chromopointer to an initialised chromosome structure.

Returns

Number number of chromosome nodes

See Also

initialiseChromosome

getNumChromosomeActiveNodes

DLL_EXPORT int getNumChromosomeActiveNodes(struct chromosome *chromo)

Gets the number of chromosome active nodes

Parameters

chromopointer to an initialised chromosome structure.

Returns

Number number of chromosome active nodes

See Also

initialiseChromosome

getNumChromosomeOutputs

DLL_EXPORT int getNumChromosomeOutputs(struct chromosome *chromo)

Gets the number of chromosome outputs

Parameters

chromopointer to an initialised chromosome structure.

Returns

Number number of chromosome outputs

See Also

initialiseChromosome

getChromosomeNodeArity

DLL_EXPORT int getChromosomeNodeArity(struct chromosome *chromo,
int index)

Gets the arity of the chromosome nodes

Parameters

chromopointer to an initialised chromosome structure.
indexindex of chromosome node

Returns

Arity of chromosome nodes

See Also

initialiseChromosome

getChromosomeFitness

DLL_EXPORT double getChromosomeFitness(struct chromosome *chromo)

Gets the fitness of the given chromosome

Parameters

chromopointer to initialised chromosome structure.

Returns

The fitness of the given chromosome

See Also

setChromosomeFitness getChromosomeGenerations getNumChromosomeActiveNodes

getNumChromosomeActiveConnections

DLL_EXPORT int getNumChromosomeActiveConnections(struct chromosome *chromo)

Gets the number of active connections in the given chromosome

Parameters

chromopointer to initialised chromosome structure.

Returns

The number of active connections

See Also

getNumChromosomeActiveNodes

getChromosomeGenerations

DLL_EXPORT int getChromosomeGenerations(struct chromosome *chromo)

Gets the number of generations for which the given chromosome has been trained.

If the chromosome has not been trained then -1 is returned.

Parameters

chromopointer to initialised chromosome structure.

Returns

Number of generations for which the given chromosome has been trained

See Also

getChromosomeFitness getNumChromosomeActiveNodes

DataSet Functions

Description of all functions and structures relating to data sets

Summary
Functions
initialiseDataSetFromArraysInitialises a dataSet structures using the given input output pairs.
initialiseDataSetFromFileInitialises a dataSet structures using the given file.
freeDataSetFrees dataSet instance.
printDataSetPrints the input output pairs held by a dataSet structure to the terminal.
saveDataSetSaves the given dataSet to a file which can be read using initialiseDataSetFromFile.
getNumDataSetInputsGets the number of dataSet inputs.
getNumDataSetOutputsGets the number of dataSet outputs.
getNumDataSetSamplesGets the number of samples in the given dataSet.
getDataSetSampleInputsGets the dataSet inputs for the given sample index.
getDataSetSampleInputGets the dataSet input for the given sample index and input index.
getDataSetSampleOutputsGets the dataSet outputs for the given sample index.
getDataSetSampleOutputGets the dataSet output for the given sample index and output index.

Functions

initialiseDataSetFromArrays

DLL_EXPORT struct dataSet *initialiseDataSetFromArrays(int numInputs,
int numOutputs,
int numSamples,
double *inputs,
double *outputs)

Initialises a dataSet structures using the given input output pairs.

The given arrays containing the input output pairs must take the form

double inputs[numSamples][numInputs]
double outputs[numSamples][numOutputs]

Where the numInputs and numOutputs are the number of inputs and outputs per sample.

Parameters

numInputsnumber of inputs per data sample
numOutputsnumber of outputs per data sample
numSamplesnumber of data samples
inputspointer to the first element in the inputs to be stored to the data structure
outputspointer to the first element in outputs to be stored to the data structure

Returns

A pointer to an initialised dataSet structure.

Example

Initialising a dataSet to contain the input output pairs for a full adder truth table.

struct data *trainingData;

int numInputs = 3;
int numOutputs = 2;
int numSamples = 8;

// full adder input output pairs
double inputs[8][3] = {{0,0,0},{0,0,1},{0,1,0},{0,1,1},{1,0,0},{1,0,1},{1,1,0},{1,1,1}};
double outputs[8][2] = {{0,0},{1,0},{1,0},{0,1},{1,0},{0,1},{0,1},{1,1}};

trainingData = initialiseDataFromArrays(numInputs, numOutputs, numSamples, inputs[0], outputs[0]);

See Also

freeDataSet, initialiseDataSetFromFile, printDataSet

initialiseDataSetFromFile

DLL_EXPORT struct dataSet *initialiseDataSetFromFile(char const *file)

Initialises a dataSet structures using the given file.

Parameters

filethe location of the file to be loaded into the dataSet structure

Returns

A pointer to an initialised dataSet structure.

Example

The file containing the dataSet must take the form

2,3,4
1,2,3,4,5
6,7,8,9,10
11,12,13,14,15
16,17,18,19,20

Where the header describes the number of inputs, number of outputs and the number of samples.  The rest of the file gives the inputs and then the outputs of each sample on a new line.  All values are comma separated.

The file can then be used to initialise a dataSet structure.

struct dataSet *trainingData;

trainingData = initialiseDataFromFile("file");

See Also

freeDataSet, initialiseDataSetFromArrays, printDataSet

freeDataSet

DLL_EXPORT void freeDataSet(struct dataSet *data)

Frees dataSet instance.

Parameters

datapointer to dataSet structure.

See Also

initialiseDataSetFromArrays, initialiseDataSetFromFile

printDataSet

DLL_EXPORT void printDataSet(struct dataSet *data)

Prints the input output pairs held by a dataSet structure to the terminal.

Parameters

datapointer to dataSet structure.

See Also

initialiseDataSetFromArrays, initialiseDataSetFromFile, freeDataSet

saveDataSet

DLL_EXPORT void saveDataSet(struct dataSet *data,
char const *fileName)

Saves the given dataSet to a file which can be read using initialiseDataSetFromFile.

Parameters

datapointer to dataSet structure.
fileNamechar array giving the location of the dataSet to be saved.

See Also

initialiseDataSetFromFile, freeDataSet

getNumDataSetInputs

DLL_EXPORT int getNumDataSetInputs(struct dataSet *data)

Gets the number of dataSet inputs.

Parameters

datapointer to an initialised dataSet structure.

Returns

Number number of dataSet inputs

See Also

getNumDataSetOutputs, getNumDataSetSamples

getNumDataSetOutputs

DLL_EXPORT int getNumDataSetOutputs(struct dataSet *data)

Gets the number of dataSet outputs.

Parameters

datapointer to an initialised dataSet structure.

Returns

Number number of dataSet outputs

See Also

getNumDataSetInputs, getNumDataSetSamples

getNumDataSetSamples

DLL_EXPORT int getNumDataSetSamples(struct dataSet *data)

Gets the number of samples in the given dataSet.

Parameters

datapointer to an initialised dataSet structure.

Returns

Number number of dataSet samples

See Also

getNumDataSetInputs, getNumDataSetOutputs

getDataSetSampleInputs

DLL_EXPORT double *getDataSetSampleInputs(struct dataSet *data,
int sample)

Gets the dataSet inputs for the given sample index.

Parameters

datapointer to an initialised dataSet structure.
sampleindex of the sample inputs

Returns

Pointer to an array containing the sample inputs.

See Also

getDataSetSampleInput, getDataSetSampleOutputs, getDataSetSampleOutput

getDataSetSampleInput

DLL_EXPORT double getDataSetSampleInput(struct dataSet *data,
int sample,
int input)

Gets the dataSet input for the given sample index and input index.

Parameters

datapointer to an initialised dataSet structure
sampleindex of the sample inputs
inputindex of the input for the given sample

Returns

The input value for the given input of the given sample.

See Also

getDataSetSampleInputs, getDataSetSampleOutput, getDataSetSampleOutputs

getDataSetSampleOutputs

DLL_EXPORT double *getDataSetSampleOutputs(struct dataSet *data,
int sample)

Gets the dataSet outputs for the given sample index.

Parameters

datapointer to an initialised dataSet structure
sampleindex of the sample outputs

Returns

Pointer to an array containing the sample outputs.

See Also

getDataSetSampleOutput, getDataSetSampleInputs, getDataSetSampleInput

getDataSetSampleOutput

DLL_EXPORT double getDataSetSampleOutput(struct dataSet *data,
int sample,
int output)

Gets the dataSet output for the given sample index and output index.

Parameters

datapointer to an initialised dataSet structure.
sampleindex of the sample inputs
outputindex of the output for the given sample

Returns

The output value for the given output for the given sample.

See Also

getDataSetSampleOutputs, getDataSetSampleInput, getDataSetSampleInputs

Results Functions

Summary
Functions
freeResultsFrees results instance.
saveResultsSaves the given results to a csv file.
getChromosomeGets a copy of the best chromosome found on the given run in an initialised results structure.
getNumChromosomesGets number of chromosomes stored in the given results structure.
getAverageFitnessGets the average fitness of the best chromosome found for each run in results.
getMedianFitnessGets the median fitness of the best chromosome found for each run in results.
getAverageActiveNodesGets the average number of active nodes of the best chromosome found for each run in results.
getMedianActiveNodesGets the median number of active nodes of the best chromosome found for each run in results.
getAverageGenerationsGets the average number generations required to find the best best chromosome for each run in results.
getMedianGenerationsGets the median number generations required to find the best best chromosome for each run in results.

Functions

freeResults

DLL_EXPORT void freeResults(struct results *rels)

Frees results instance.

An initialised results structure is returned from repeatCGP when applied CGP to a task multiple times in order to assess average behaviour.

Parameters

relspointer to results structure.

See Also

repeatCGP

saveResults

DLL_EXPORT void saveResults(struct results *rels,
char const *fileName)

Saves the given results to a csv file.

Parameters

elspointer to an initialised results structure.
fileNamechar array giving the location of the results to be saved.

getChromosome

DLL_EXPORT struct chromosome* getChromosome(struct results *rels,
int run)

Gets a copy of the best chromosome found on the given run in an initialised results structure.

Parameters

relspointer to an initialised results structure.
runthe run for which the chromosome is got

Returns

Pointer to an initialised chromosome structure.

See Also

repeatCGP, getAverageFitness, getAverageActiveNodes, getAverageGenerations

getNumChromosomes

DLL_EXPORT int getNumChromosomes(struct results *rels)

Gets number of chromosomes stored in the given results structure.

Parameters

relspointer to an initialised results structure.

Returns

The number of chromosomes stored in the given results structure

See Also

repeatCGP, getAverageFitness, getAverageActiveNodes, getAverageGenerations

getAverageFitness

DLL_EXPORT double getAverageFitness(struct results *rels)

Gets the average fitness of the best chromosome found for each run in results.

Parameters

relspointer to an initialised results structure.

Returns

The average fitness of the best chromosome found for each run in results.

See Also

repeatCGP, getAverageActiveNodes, getAverageGenerations

getMedianFitness

DLL_EXPORT double getMedianFitness(struct results *rels)

Gets the median fitness of the best chromosome found for each run in results.

Parameters

relspointer to an initialised results structure.

Returns

The median fitness of the best chromosome found for each run in results.

See Also

repeatCGP, getMedianActiveNodes, getMedianGenerations

getAverageActiveNodes

DLL_EXPORT double getAverageActiveNodes(struct results *rels)

Gets the average number of active nodes of the best chromosome found for each run in results.

Parameters

relspointer to an initialised results structure.

Returns

The average number of active nodes of the best chromosome found for each run in results.

See Also

repeatCGP, getAverageFitness, getAverageGenerations

getMedianActiveNodes

DLL_EXPORT double getMedianActiveNodes(struct results *rels)

Gets the median number of active nodes of the best chromosome found for each run in results.

Parameters

relspointer to an initialised results structure.

Returns

The median number of active nodes of the best chromosome found for each run in results.

See Also

repeatCGP, getMedianFitness, getMedianGenerations

getAverageGenerations

DLL_EXPORT double getAverageGenerations(struct results *rels)

Gets the average number generations required to find the best best chromosome for each run in results.

Parameters

relspointer to an initialised results structure.

Returns

The average number generations required to find the best chromosome found for each run in results.

See Also

repeatCGP, getAverageFitness, getAverageActiveNodes

getMedianGenerations

DLL_EXPORT double getMedianGenerations(struct results *rels)

Gets the median number generations required to find the best best chromosome for each run in results.

Parameters

relspointer to an initialised results structure.

Returns

The median number generations required to find the best chromosome found for each run in results.

See Also

repeatCGP, getMedianFitness, getMedianActiveNodes

CGP Functions

Summary
Functions
runCGPApplies CGP to the given task.
repeatCGPRepeatedly applies CGP to the given task.

Functions

runCGP

DLL_EXPORT struct chromosome* runCGP(struct parameters *params,
struct dataSet *data,
int numGens)

Applies CGP to the given task.

Returns the best chromosome found after applying CGP to a given task using the specified parameters.  Depending upon the update frequency given in parameters (setUpdateFrequency) the progress made by CGP will be displayed in the terminal.

Note

As runCGP returns an initialised chromosome this should later be free’d using freeChromosome.

Parameters

paramspointer to parameters structure.
datapointer to dataSet structure.
gensthe number of allowed generations before terminating the search.

Returns

A pointer to an initialised chromosome.

Example

struct parameters *params;
struct dataSet *data;
struct chromosome *chromo;

params = initialiseParameters(a,b,c,d);
addNodeFunction(params, "aaa,bbb,ccc");

data = initialiseDataSetFromFile("file");

chromo = runCGP(params, data, 100);

freeParameters(params);
freeDataSet(data);
freeChromosome(chromo);

See Also

repeatCGP, initialiseParameters, initialiseDataSetFromFile, freeChromosome

repeatCGP

DLL_EXPORT struct results* repeatCGP(struct parameters *params,
struct dataSet *data,
int numGens,
int numRuns)

Repeatedly applies CGP to the given task.

Returns a results structure containing the results of applying CGP to the given task multiple times.

Note

As repeatCGP returns an initialised results structure this should later be free’d using freeResults.

Parameters

paramspointer to parameters structure.
datapointer to dataSet structure.
numGensthe number of allowed generations before terminating the search.
numRunsthe number of times CGP will be applied to the given task

Returns

A pointer to an initialised results structure.

Example

struct parameters *params;
struct dataSet *data;
struct results *rels;

params = initialiseParameters(a,b,c,d);
addNodeFunction(params, "aaa,bbb,ccc");

data = initialiseDataSetFromFile("file");

rels = repeatCGP(params, data, 100, 50);

freeParameters(params);
freeDataSet(data);
freeResults(rels);

See Also

runCGP, initialiseParameters, initialiseDataSetFromFile, freeResults

Other

Summary
Functions
setRandomNumberSeedSets the seed used by the random number generator in CGP-Library.

Functions

setRandomNumberSeed

DLL_EXPORT void setRandomNumberSeed(unsigned int seed)

Sets the seed used by the random number generator in CGP-Library.

By default the current time is used as the random number seed.  When a random number seed is specified the CGP-Library will produce the same results if used in the same way.

Note

setRandomNumberSeed must be called after initialiseParameters otherwise the time will be used as the random number seed.

Parameters

seedthe random number seed to be used

See Also

initialiseParameters

struct parameters
Stores general evolutionary and chromosome parameters used by the CGP-Library.
struct chromosome
Stores a CGP chromosome instances used by the CGP-Library.
struct dataSet
Stores a data set which can be used by fitness functions when calculating a chromosomes fitness.
struct results
Stores the best chromosome found on each run when using repeatCGP
DLL_EXPORT struct results* repeatCGP(struct parameters *params,
struct dataSet *data,
int numGens,
int numRuns)
Repeatedly applies CGP to the given task.
DLL_EXPORT struct parameters *initialiseParameters(const int numInputs,
const int numNodes,
const int numOutputs,
const int arity)
Initialises a parameters structure used throughout the CGP-Library.
DLL_EXPORT void freeParameters(struct parameters *params)
Frees parameters structure instance.
DLL_EXPORT void printParameters(struct parameters *params)
Prints the given parameters to the screen in a human readable format.
DLL_EXPORT void addNodeFunction(struct parameters *params,
char const *functionNames)
Adds pre-defined node function(s) to the set of functions stored by a parameters structure.
DLL_EXPORT void addCustomNodeFunction(
   struct parameters *params,
   double (*function)(const int numInputs, const double *inputs, const double *weights),
   char const *functionName,
   int maxNumInputs
)
Adds custom node function to the set of functions stored by a parameters structure.
DLL_EXPORT void clearFunctionSet(struct parameters *params)
Resets the function set stored by a parameters structure to contain no functions.
DLL_EXPORT void setNumInputs(struct parameters *params,
int numInputs)
Sets the number of chromosome inputs in the given parameters.
DLL_EXPORT void setNumNodes(struct parameters *params,
int numNodes)
Sets the number of chromosome nodes in the given parameters.
DLL_EXPORT void setNumOutputs(struct parameters *params,
int numOutputs)
Sets the number of chromosome outputs in the given parameters.
DLL_EXPORT void setArity(struct parameters *params,
int arity)
Sets the arity of the chromosome nodes in the given parameters.
DLL_EXPORT void setMu(struct parameters *params,
int mu)
Sets the mu value in the given parameters.
DLL_EXPORT void setLambda(struct parameters *params,
int lambda)
Sets the lambda value in the given parameters.
DLL_EXPORT void setEvolutionaryStrategy(struct parameters *params,
char evolutionaryStrategy)
Sets the evolutionary strategy in the given parameters.
DLL_EXPORT void setMutationRate(struct parameters *params,
double mutationRate)
Sets the mutation rate in the given parameters.
DLL_EXPORT void setRecurrentConnectionProbability(
   struct parameters *params,
   double recurrentConnectionProbability
)
Sets the recurrent connection probability in the given parameters.
DLL_EXPORT void setShortcutConnections(struct parameters *params,
int shortcutConnections)
Sets whether shortcut connections are used in the given parameters.
DLL_EXPORT void setConnectionWeightRange(struct parameters *params,
double weightRange)
Sets the connection weight range in the given parameters.
DLL_EXPORT void setCustomFitnessFunction(
   struct parameters *params,
   double (*fitnessFunction)(struct parameters *params, struct chromosome *chromo, struct dataSet *data),
   char const *fitnessFunctionName
)
Set custom fitness function.
DLL_EXPORT void setCustomSelectionScheme(
   struct parameters *params,
   void (*selectionScheme)(struct parameters *params, struct chromosome **parents, struct chromosome **candidateChromos, int numParents, int numCandidateChromos),
   char const *selectionSchemeName
)
Sets custom selection scheme.
DLL_EXPORT void setCustomReproductionScheme(
   struct parameters *params,
   void (*reproductionScheme)(struct parameters *params, struct chromosome **parents, struct chromosome **children, int numParents, int numChildren),
   char const *reproductionSchemeName
)
Sets custom reproduction scheme.
DLL_EXPORT void setTargetFitness(struct parameters *params,
double targetFitness)
Sets the target fitness used when running CGP.
DLL_EXPORT void setMutationType(struct parameters *params,
char const *mutationType)
Sets the mutation method used when mutating chromosomes.
DLL_EXPORT void setUpdateFrequency(struct parameters *params,
int updateFrequency)
Sets the frequency of the updates to the user when using runCGP.
DLL_EXPORT struct chromosome* runCGP(struct parameters *params,
struct dataSet *data,
int numGens)
Applies CGP to the given task.
DLL_EXPORT void setNumThreads(struct parameters *params,
int numThreads)
Sets the number of threads in the given parameters.
DLL_EXPORT struct chromosome *initialiseChromosome(struct parameters *params)
Initialises a chromosome based on the given parameters.
DLL_EXPORT struct chromosome* initialiseChromosomeFromFile(char const *file)
Initialises a chromosome from a given previously saved chromosome.
DLL_EXPORT struct chromosome *initialiseChromosomeFromChromosome(
   struct chromosome *chromo
)
Initialises a chromosome from a given chromosome.
DLL_EXPORT void freeChromosome(struct chromosome *chromo)
Frees chromosome instance.
DLL_EXPORT void printChromosome(struct chromosome *chromo,
int weights)
Displays the given chromosome to the terminal / command prompt in a human readable format.
DLL_EXPORT void executeChromosome(struct chromosome *chromo,
const double *inputs)
Executes the given chromosome.
DLL_EXPORT double getChromosomeOutput(struct chromosome *chromo,
int output)
Gets the outputs of the given chromosome after it has been executed using executeChromosome.
DLL_EXPORT double getChromosomeNodeValue(struct chromosome *chromo,
int node)
Gets the node value of the given chromosome and node after it has been executed using executeChromosome.
DLL_EXPORT int isNodeActive(struct chromosome *chromo,
int node)
Returns whether the given node in the given chromosome is active.
DLL_EXPORT void saveChromosome(struct chromosome *chromo,
char const *fileName)
Saves the given chromosome to a file which can used to initialise new chromosomes.
DLL_EXPORT void saveChromosomeDot(struct chromosome *chromo,
int weights,
char const *fileName)
Saves the given chromosome to a graphviz .dot file.
DLL_EXPORT void saveChromosomeLatex(struct chromosome *chromo,
int weights,
char const *fileName)
Saves the given chromosome to a latex .tex file for visulisation and inclusion in written workes.
DLL_EXPORT void mutateChromosome(struct parameters *params,
struct chromosome *chromo)
Mutate the given chromosome using the mutation method described in the given parameters.
DLL_EXPORT void removeInactiveNodes(struct chromosome *chromo)
Removes all of the inactive nodes from the given chromosome.
DLL_EXPORT void setChromosomeFitness(struct parameters *params,
struct chromosome *chromo,
struct dataSet *data)
Sets the fitness of the chromosome using the fitness function given in the parameters
DLL_EXPORT void resetChromosome(struct chromosome *chromo)
Resets all of the chromosome nodes to output zero.
DLL_EXPORT void copyChromosome(struct chromosome *chromoDest,
struct chromosome *chromoSrc)
Copies the contents of one chromoosme into the other.
DLL_EXPORT int getNumChromosomeInputs(struct chromosome *chromo)
Gets the number of chromosome inputs
DLL_EXPORT int getNumChromosomeNodes(struct chromosome *chromo)
Gets the number of chromosome nodes
DLL_EXPORT int getNumChromosomeActiveNodes(struct chromosome *chromo)
Gets the number of chromosome active nodes
DLL_EXPORT int getNumChromosomeOutputs(struct chromosome *chromo)
Gets the number of chromosome outputs
DLL_EXPORT int getChromosomeNodeArity(struct chromosome *chromo,
int index)
Gets the arity of the chromosome nodes
DLL_EXPORT double getChromosomeFitness(struct chromosome *chromo)
Gets the fitness of the given chromosome
DLL_EXPORT int getNumChromosomeActiveConnections(struct chromosome *chromo)
Gets the number of active connections in the given chromosome
DLL_EXPORT int getChromosomeGenerations(struct chromosome *chromo)
Gets the number of generations for which the given chromosome has been trained.
DLL_EXPORT struct dataSet *initialiseDataSetFromArrays(int numInputs,
int numOutputs,
int numSamples,
double *inputs,
double *outputs)
Initialises a dataSet structures using the given input output pairs.
DLL_EXPORT struct dataSet *initialiseDataSetFromFile(char const *file)
Initialises a dataSet structures using the given file.
DLL_EXPORT void freeDataSet(struct dataSet *data)
Frees dataSet instance.
DLL_EXPORT void printDataSet(struct dataSet *data)
Prints the input output pairs held by a dataSet structure to the terminal.
DLL_EXPORT void saveDataSet(struct dataSet *data,
char const *fileName)
Saves the given dataSet to a file which can be read using initialiseDataSetFromFile.
DLL_EXPORT int getNumDataSetInputs(struct dataSet *data)
Gets the number of dataSet inputs.
DLL_EXPORT int getNumDataSetOutputs(struct dataSet *data)
Gets the number of dataSet outputs.
DLL_EXPORT int getNumDataSetSamples(struct dataSet *data)
Gets the number of samples in the given dataSet.
DLL_EXPORT double *getDataSetSampleInputs(struct dataSet *data,
int sample)
Gets the dataSet inputs for the given sample index.
DLL_EXPORT double getDataSetSampleInput(struct dataSet *data,
int sample,
int input)
Gets the dataSet input for the given sample index and input index.
DLL_EXPORT double *getDataSetSampleOutputs(struct dataSet *data,
int sample)
Gets the dataSet outputs for the given sample index.
DLL_EXPORT double getDataSetSampleOutput(struct dataSet *data,
int sample,
int output)
Gets the dataSet output for the given sample index and output index.
DLL_EXPORT void freeResults(struct results *rels)
Frees results instance.
DLL_EXPORT void saveResults(struct results *rels,
char const *fileName)
Saves the given results to a csv file.
DLL_EXPORT struct chromosome* getChromosome(struct results *rels,
int run)
Gets a copy of the best chromosome found on the given run in an initialised results structure.
DLL_EXPORT int getNumChromosomes(struct results *rels)
Gets number of chromosomes stored in the given results structure.
DLL_EXPORT double getAverageFitness(struct results *rels)
Gets the average fitness of the best chromosome found for each run in results.
DLL_EXPORT double getMedianFitness(struct results *rels)
Gets the median fitness of the best chromosome found for each run in results.
DLL_EXPORT double getAverageActiveNodes(struct results *rels)
Gets the average number of active nodes of the best chromosome found for each run in results.
DLL_EXPORT double getMedianActiveNodes(struct results *rels)
Gets the median number of active nodes of the best chromosome found for each run in results.
DLL_EXPORT double getAverageGenerations(struct results *rels)
Gets the average number generations required to find the best best chromosome for each run in results.
DLL_EXPORT double getMedianGenerations(struct results *rels)
Gets the median number generations required to find the best best chromosome for each run in results.
DLL_EXPORT void setRandomNumberSeed(unsigned int seed)
Sets the seed used by the random number generator in CGP-Library.
Close