Listing 2: Sample code is provided for (a) the evaluation operator and (b) the main program in OpenBeagle.
class SymbRegEvalOp : public GP:: EvaluationOp
{
public:
SymbRegEvalOp() { }
virtual Fitness:: Handle evaluate(
GP:: Individual& inIndividual, GP::Context& ioContext)
{
InitialData &id = dynamic_cast<InitialData&>(
*( ioContext.getSystem().getComponent(“InitialData”)));
std:: vector<Double> X = id. X;
std:: vector<Double> Y = id. Y;
double lQErr = 0.; // square error
for(unsigned int i=0; i< X.size(); i++)
{
setValue(“x”,X[i],ioContext);
Double lResult;
inIndividual.run(lResult,ioContext);
double lError = Y[i]-lResult;
lQErr += (lError*lError);
}
return new FitnessSimple( 1.0/
(std::sqrt(lQErr/ X.size())+ 1.0));
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <cmath>
#include <vector>
#include <beagle/GP.hpp>
using namespace Beagle;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
ba
int main(int argc, char *argv[]) {
GP::System:: Handle lSystem = create_system();
InitialData:: Handle id = new InitialData( 20);
lSystem->addComponent(id);
SymbRegEvalOp:: Handle lEvalOp = new SymbRegEvalOp;
GP::Evolver:: Handle lEvolver = new GP:: Evolver(lEvalOp);
GP::Vivarium:: Handle lVivarium = new GP:: Vivarium;
lEvolver->initialize(lSystem,argc,argv);
lEvolver->evolve(lVivarium);
return 0;
}
I have used the formula
for this example. So in fact we will be
approximating a trigonometric function by
a rational one.
The next step is to define the fitness
function which measures how close an
individual I is to a perfect match. In our
case, a good choice will be to calculate the
deviation
and then set the fitness to be the
normalized value (the algorithm
maximizes the fitness, so a perfect match
would have the maximal fitness)
In OpenBeagle, the fitness calculation
is encapsulated by objects of type
GP::EvaluationOp. Ours would be
coded as shown in Listing 2a.
Having defined these essential
components of a GP system, now we
only need to combine everything. There
are two additional objects we need to be
familiar with. The first is GP::Vivarium,
which encapsulates all the individuals of
all the generations throughout the whole
evolution process, as well as statistical
data. For example, it has a member of
type Beagle::HallOfFame that holds
the best individual. Finally, the entire
process is controlled by a GP::Evolver.
{CON TINUED ON P. 51}
Figure 1: The best individual is shown, including: (a) its complete genotype and (b) how well it approximates the initial data.