ECF 1.7
main.cpp
1#include "ECF.h"
2
3// Za svaki primjer je potrebno:
4// a) definirati odgovarajuci EvaluateOp objekt koji se primjenjuje za evaluaciju jedinke
5// b) definirati genotip (po zelji i druge parametre) u konf fajlu
6//
7// Svaki primjer ima posebnu funkciju main() - otkomentirati
8
9
10
11//
12// primjer dodavanja novog algoritma
13//
14class MyAlg : public Algorithm
15{
16protected:
17
18 // declare all available selection operators (not all get used)
19 SelFitnessProportionalOpP selFitOp_;
20 SelRandomOpP selRandomOp_;
21 SelBestOpP selBestOp_;
22 SelWorstOpP selWorstOp_;
23 // what individual to replace (worst or random)
24 bool replaceWorst_;
25
26public:
27
28 // mandatory: define name, construct selection operators
29 MyAlg()
30 {
31 // the algorithm name will be used in config file (see below)
32 name_ = "MyAlg";
33 selFitOp_ = (SelFitnessProportionalOpP) (new SelFitnessProportionalOp);
34 selRandomOp_ = (SelRandomOpP) (new SelRandomOp);
35 selBestOp_ = (SelBestOpP) (new SelBestOp);
36 selWorstOp_ = (SelWorstOpP) (new SelWorstOp);
37 }
38
39
40 // optional: register any parameters
41 void registerParameters(StateP state)
42 {
43 // HOW TO: define a parameter
44 // string parameter, options: random, worst
45 registerParameter(state, "replace", (voidP) (new std::string("random")), ECF::STRING);
46 }
47
48
49 // optional: initialize components, read parameters
50 bool initialize(StateP state)
51 {
52 // selection operators must be initialized if used!
53 selFitOp_->initialize(state);
54 // optional: set ratio between the best and the worst individual's selection probability
55 selFitOp_->setSelPressure(10);
56 // if the ratio is < 1, the selection favours worse over better individuals
57 //selFitOp_->setSelPressure(0.1);
58 selRandomOp_->initialize(state);
59 selBestOp_->initialize(state);
60 selWorstOp_->initialize(state);
61
62 // HOW TO: read a parameter value
63 // get parameter, decide what to replace
64 voidP par = getParameterValue(state, "replace");
65 std::string replace = *((std::string*) par.get());
66 replaceWorst_ = false;
67 if(replace == "worst")
68 replaceWorst_ = true;
69
70 // HOW TO: check if genotype is of a specific kind
71 // suppose we only accept FloatingPoint
72 FloatingPointP flp (new FloatingPoint::FloatingPoint);
73 if(state->getGenotypes()[0]->getName() != flp->getName()) {
74 ECF_LOG_ERROR(state, "Error: this algorithm accepts only a single FloatingPoint genotype!");
75 throw ("");
76 }
77
78 // HOW TO: read the dimension and domain boundaries
79 voidP sptr = state->getGenotypes()[0]->getParameterValue(state, "dimension");
80 uint numDimension = *((uint*) sptr.get());
81 voidP lBound = state->getGenotypes()[0]->getParameterValue(state, "lbound");
82 double lbound = *((double*) lBound.get());
83 voidP uBound = state->getGenotypes()[0]->getParameterValue(state, "ubound");
84 double ubound = *((double*) uBound.get());
85
86 // HOW TO: add another genotype in all individuals (if algorithm requires)
87 // new FloatingPoint genotype with same parameters
88 FloatingPointP fp (static_cast<FloatingPoint::FloatingPoint*> (state->getGenotypes()[0]->copy()));
89 //state->setGenotype(fp);
90 fp->setParameterValue(state, "dimension", (voidP) new uint(numDimension));
91 fp->setParameterValue(state, "lbound", (voidP) new double(lbound));
92 fp->setParameterValue(state, "ubound", (voidP) new double(ubound));
93
94 // HOW TO: read population (local deme) size
95 uint popSize = state->getPopulation()->getLocalDeme()->getSize();
96
97 return true;
98 }
99
100
101 // mandatory: perform single 'generation' (however the algorithm defines it)
102 bool advanceGeneration(StateP state, DemeP deme)
103 {
104 // HOW TO: select parents
105 IndividualP first = selFitOp_->select(*deme);
106 IndividualP second = selBestOp_->select(*deme);
107
108 // select child (random or worst)
109 IndividualP child;
110 if(replaceWorst_)
111 child = selWorstOp_->select(*deme);
112 else
113 child = selRandomOp_->select(*deme);
114
115 // HOW TO: cross two individuals
116 mate(first, second, child);
117
118 // HOW TO: mutate an individual
119 // mutation probability defined in Registry!
120 mutate(child);
121 // to explicitly mutate an individual:
122 //mutation_->mutate(child);
123
124 // HOW TO: evaluate an individual
125 evaluate(child);
126
127 // HOW TO: create a trial individual (e.g. a copy of an existing individual)
128 IndividualP trial = (IndividualP) deme->at(0)->copy();
129
130 // HOW TO: access individual data
131 // get FloatingPoint genotype from individual
132 FloatingPointP fp = std::static_pointer_cast<FloatingPoint::FloatingPoint> (trial->getGenotype(0));
133 // or use ordinary pointers:
134 //FloatingPoint::FloatingPoint* fp = static_cast<FloatingPoint::FloatingPoint*> (trial->getGenotype().get());
135
136 // HOW TO: change individual data
137 fp->realValue[0] = 3.14;
138
139 // HOW TO: replace an individual in deme
140 // evaluate and compare with another individual
141 evaluate(trial);
142 if(trial->fitness->isBetterThan(child->fitness))
143 // replace first with second:
144 replaceWith(child, trial);
145
146 // some other helper functions (see existing algorithms):
147 // copy, replaceWith, removeFrom, isMember
148
149 return true;
150 }
151};
152typedef std::shared_ptr<MyAlg> MyAlgP;
153
154
155
156
157
158
159
160
161// 1. primjer: GA OneMax problem
162
163#include "examples/GAonemax/OneMaxEvalOp.h"
164int main(int argc, char **argv)
165{
166 argc = 2; // hard coded za lakse isprobavanje :)
167 //argv[1] = "./examples/GAOneMax/parametri.txt";
168
169 StateP state (new State);
170
171 //state->setEvalOp(static_cast<EvaluateOpP> (new OneMaxEvalOp));
172 state->setEvalOp(new OneMaxEvalOp);
173
174 state->initialize(argc, argv);
175 state->run();
176
177 return 0;
178}
179
180
181
182// 2. primjer: GA minimizacija funkcije
183/*
184#include "examples/GAFunctionMin/FunctionMinEvalOp.h"
185int main(int argc, char **argv)
186{
187 argc = 2;
188 argv[1] = "./examples/GAFunctionMin/parametri.txt";
189
190 StateP state (new State);
191 state->setEvalOp(new FunctionMinEvalOp);
192
193 state->initialize(argc, argv);
194 state->run();
195
196
197 try {
198 pt::ptree tree;
199 pt::read_xml("./examples/GAFunctionMin/parametri.txt", tree);
200 pt::ptree ecf = tree.get_child("ECF");
201 pt::ptree genotype = ecf.get_child("Genotype");
202
203 // BOOST_FOREACH(pt::ptree::value_type &v, genotype.get_child("")) {
204 for(pt::ptree::iterator it = genotype.begin(); it != genotype.end(); it++) {
205 pt::ptree::value_type &v = *it;
206 if(v.first == "FloatingPoint")
207 ;
208 }
209 }
210 catch(const pt::ptree_error& er){
211 std::cout << er.what() << std::endl;
212 }
213
214
215
216
217
218 return 0;
219
220//
221// ispis populacije u txt fajl, za potrebe landscape analysis
222//
223 ofstream fajl("popis.txt");
224 for(uint i = 0; i < state->getPopulation()->getLocalDeme()->getSize(); i++) {
225 IndividualP ind = state->getPopulation()->getLocalDeme()->at(i);
226 fajl << ind->fitness->getValue() << "\t";
227 FloatingPointP fp = boost::static_pointer_cast<FloatingPoint::FloatingPoint> (ind->getGenotype());
228 for(uint dim = 0; dim < fp->realValue.size(); dim++)
229 fajl << fp->realValue[dim] << "\t";
230 fp = boost::static_pointer_cast<FloatingPoint::FloatingPoint> (ind->getGenotype(2));
231 fajl << fp->realValue[0];
232 fajl << "\n";
233 }
234
235 return 0;
236}
237*/
238
239
240// 2a. primjer: MO NSGA minimizacija funkcije
241/*
242#include "examples/MOFunctionMin/MOFunctionMinEvalOp.h"
243int main(int argc, char **argv)
244{
245 argc = 2;
246 argv[1] = "./examples/MOFunctionMin/parameters.txt";
247
248 StateP state (new State);
249 state->setEvalOp(new MOEvalOp);
250
251 state->initialize(argc, argv);
252 state->run();
253
254 // ispis populacije na kraju
255 std::ofstream myfile;
256 myfile.open ("paretoFront.txt");
257 DemeP deme = state->getPopulation()->getLocalDeme();
258 for (uint i = 0; i<deme->size(); i++) {
259 MOFitnessP fitness = boost::static_pointer_cast<MOFitness> (deme->at(i)->fitness);
260 for (uint f = 0; f < fitness->size(); f++)
261 myfile << fitness->at(f)->getValue() << "\t";
262 myfile << "\n";
263 }
264 myfile.close();
265
266 return 0;
267}
268*/
269
270
271
272namespace Tree {
273
274// primjer tipa podataka
276{
277 double v;
278 bool b;
279};
280
281// terminal za doticni tip
282class MyTerminal : public Primitives::Primitive
283{
284public:
285 my_type value_;
286
287 MyTerminal()
288 {
289 nArguments_ = 0;
290 }
291 void execute(void* result, Tree& tree)
292 {
293 my_type& res = *(my_type*)result;
294 res = value_;
295 }
296 void setValue(void* value)
297 {
298 value_ = *(my_type*)value;
299 }
300 ~MyTerminal()
301 { }
302};
303
304// primjer funkcije za korisnicki tip podataka
305class MyFunc : public Primitives::Primitive
306{
307public:
308 MyFunc()
309 {
310 nArguments_ = 2;
311 name_ = "func";
312 }
313 void execute(void* result, Tree& tree)
314 {
315 my_type first, second;
316 my_type& func = *(my_type*)result;
317
318 getNextArgument(&first, tree);
319 getNextArgument(&second, tree);
320
321 func.b = first.b && second.b;
322 func.v = first.v + second.v;
323 }
324 ~MyFunc()
325 { }
326};
327
328}
329
330
331
332// 3. primjer: GP simbolicka regresija
333/*
334#include "examples/GPSymbReg/SymbRegEvalOp.h"
335#include "examples/GPSymbReg/zbr.h"
336int main(int argc, char **argv)
337{
338// argc = 2;
339// argv[1] = "./examples/GPSymbReg/parametri.txt";
340
341 StateP state = static_cast<StateP> (new State);
342
343 state->setEvalOp(static_cast<EvaluateOpP> (new SymbRegEvalOp));
344
345 // primjer: dodavanje korisnickog operatora
346// MyOpP myOp = (MyOpP) (new MyOp);
347// state->addOperator(myOp);
348
349 // primjer: dodavanje korisnickog algoritma
350// MyAlgP myAlg = (MyAlgP) (new MyAlg);
351// state->addAlgorithm(myAlg);
352
353 // primjer: dodavanje korisnickog genotipa
354// MyGenotypeP myGenotype = (MyGenotypeP) (new MyGenotype);
355// state->addGenotype(myGenotype);
356
357 // primjer: dodavanje korisnicke funkcije za stablo
358 TreeP tree = (TreeP) new Tree::Tree;
359 Tree::PrimitiveP zbr = (Tree::PrimitiveP) new Tree::Ad;
360 tree->addFunction(zbr);
361
362Tree::PrimitiveP myFunc = (Tree::PrimitiveP) new Tree::MyFunc;
363tree->addFunction(myFunc);
364
365Tree::PrimitiveP myTerm = (Tree::PrimitiveP) new Tree::MyTerminal;
366myTerm->setName("term");
367tree->addTerminal(myTerm);
368
369
370 state->addGenotype(tree);
371
372 if (!state->initialize(argc, argv))
373 return 1;
374 state->run();
375
376 //std::vector<IndividualP> vec = state->getPopulation()->hof_->getBest();
377 //IndividualP ind = vec[0];
378 //state->getAlgorithm()->evaluate(ind);
379 //XMLNode out;
380 //ind->write(out);
381 //std::cout << out.createXMLString() << std::endl;
382
383 std::vector<IndividualP> vec = state->getPopulation()->getHof()->getBest();
384 IndividualP ind = vec[0];
385 XMLNode xml2 = XMLNode::parseString("<Individual size=""1"" gen=""77""><FitnessMin value=""4.26326e-14""/><Tree size=""36"">+ + * * X * X X - * X X + X X + sin X * X * X X / - * X X X / / X X + X X </Tree></Individual>", "Individual");
386 ind->read(xml2);
387 state->getAlgorithm()->evaluate(ind);
388 std::cout << ind->toString();
389
390 return 0;
391}
392*/
393
394
395//4. primjer: GA problem trgovackog putnika, 29 gradova
396/*
397#include "examples/GATSP/TSPEvalOp.h"
398int main(int argc, char **argv)
399{
400// argc = 2;
401// argv[1] = "./examples/GATSP/parameters.txt";
402
403 StateP state = static_cast<StateP> (new State);
404
405 state->setEvalOp(static_cast<EvaluateOpP> (new TSPEvalOp));
406
407 state->initialize(argc, argv);
408 //state->getFitnessObject();
409
410 state->run();
411
412 return 0;
413}
414*/
415
416
417
418//5. primjer: GA problem aproksimacije funkcije
419/*
420#include "examples/GAApprox/ApproxEvalOp.h"
421int main(int argc, char **argv)
422{
423// argc = 2;
424// argv[1] = "./examples/GAApprox/parameters.txt";
425
426 StateP state(new State);
427
428 state->setEvalOp(EvaluateOpP (new AproxEvalOp));
429
430 state->initialize(argc, argv);
431 state->run();
432
433 return 0;
434}
435*/
436
437
438
439//6. primjer: GP evolucija pravila rasporedjivanja
440/*
441#include "examples/GPScheduling/SchedulingEvalOp.h"
442int main(int argc, char **argv)
443{
444 argc = 2;
445 //argv[1] = "./examples/GPScheduling/parameters.txt";
446 argv[1] = "./parameters.txt";
447
448 StateP state = static_cast<StateP> (new State);
449
450 state->setEvalOp(static_cast<EvaluateOpP> (new SchedulingEvalOp));
451
452 state->initialize(argc, argv);
453 state->run();
454
455// XMLNode xInd = XMLNode::parseFile("./ind.txt", "Individual");
456// IndividualP ind = (IndividualP) new Individual(state);
457// ind->read(xInd);
458// state->getAlgorithm()->evaluate(ind);
459// std::cout << ind->toString();
460
461 return 0;
462}
463*/
464
465
466//7. primjer: XCS
467/*
468#include "examples/XCSmux/MuxEvalOp.h"
469#include "examples/XCSmaze/SingleObjMazeEnv.h"
470#include "examples/XCSmaze/SeqObjMazeEnv.h"
471#include "examples/XCSmaze/TwoObjMazeEnv.h"
472#include "examples/XCSmaze/ThreeObjMazeEnv.h"
473
474int main(int argc, char **argv)
475{
476 argc = 2;
477 StateP state = static_cast<StateP> (new State);
478 MazeEnvP maze;
479
480 //Multistep:
481
482 // - sigle-objective maze:
483 //argv[1] = "examples/XCSmaze/single-obj params.txt";
484 //maze = static_cast<MazeEnvP> (new SingleObjMazeEnv(state));
485 //maze->setMazeFile("examples/XCSmaze/Environments/single-objective/Maze1.txt");
486
487 // - multi-objective maze:
488 //argv[1] = "examples/XCSmaze/seq-obj params.txt";
489 //maze = static_cast<MazeEnvP> (new SeqObjMazeEnv(state));
490 //maze->setMazeFile("examples/XCSmaze/Environments/multi-objective/Maze1k.txt");
491
492 argv[1] = "examples/XCSmaze/three-obj params.txt";
493 maze = static_cast<MazeEnvP> (new ThreeObjMazeEnv(state,0));
494 maze->setMazeFile("examples/XCSmaze/Environments/multi-objective/Maze1em.txt");
495
496 maze->setResultsFile("examples/XCSmaze/Maze1k results.txt");
497 state->setEvalOp(maze);
498
499 //Singlestep:
500
501 // - 6-multiplexor problem:
502 // argv[1] = "./examples/XCSmux/parametri.txt";
503 // state->setEvalOp(static_cast<EvaluateOpP> (new MuxEvalOp(state)));
504
505 state->initialize(argc, argv);
506
507 state->run();
508
509 int a;
510 cin >> a;
511 return 0;
512}
513*/
514
515
516
517//8. primjer: Kartezijski GP - feedforward
518/*
519#include "examples/CGPFeedForward/FeedForwardEvalOp.h"
520#include "examples/CGPFeedForward/CGPEvalOp.h"
521#include "cartesian/Cartesian.h"
522using namespace cart;
523
524int main(int argc, char **argv)
525{
526 argc = 2;
527 argv[1] = "./examples/CGPFeedForward/parameters.txt";
528
529 StateP state (new State);
530
531 CartesianP cart (new Cartesian);
532
533 state->addGenotype(cart);
534
535 state->setEvalOp(new FunctionMinEvalOp);
536
537
538 // izabrati koji tip
539 //state->setEvalOp(new cart::FeedForwardEvalOpInt);
540 //state->setEvalOp(static_cast<EvaluateOpP> (new cart::FeedForwardEvalOpDouble));
541 //state->setEvalOp(static_cast<EvaluateOpP> (new cart::CircuitEvalOpUint));
542
543 state->initialize(argc, argv);
544 state->run();
545
546 return 0;
547}
548*/
uint mutate(const std::vector< IndividualP > &pool)
Helper function: send a vector of individuals to mutation.
Definition Algorithm.h:169
std::string name_
algorithm name
Definition Algorithm.h:23
bool registerParameter(StateP state, std::string name, voidP value, enum ECF::type T, std::string description="")
Helper function: register a single parameter with the system.
Definition Algorithm.h:35
voidP getParameterValue(StateP state, std::string name)
Helper function: get parameter value from the system.
Definition Algorithm.h:46
bool mate(IndividualP p1, IndividualP p2, IndividualP child)
Helper function: crossover two individuals.
Definition Algorithm.h:285
void replaceWith(IndividualP oldInd, IndividualP newInd)
Helper function: replace an individual in current deme.
Definition Algorithm.h:187
void evaluate(IndividualP ind)
Helper function: evaluate an individual.
Definition Algorithm.h:157
FloatingPoint class - implements genotype as a vector of floating point values.
bool advanceGeneration(StateP state, DemeP deme)
Perform a single generation on a single deme.
Definition main.cpp:102
void registerParameters(StateP state)
Register algorithm's parameters (if any).
Definition main.cpp:41
bool initialize(StateP state)
Initialize the algorithm, read parameters from the system, do a sanity check.
Definition main.cpp:50
OneMax problem evaluation class.
Best individual selection operator.
Definition SelBestOp.h:10
Fitness proportional (and inverse proportional) individual selection operator.
Random individual selection operator.
Definition SelRandomOp.h:12
Worst individual selection operator.
Definition SelWorstOp.h:11
State class - backbone of the framework.
Definition State.h:38
void execute(void *result, Tree &tree)
Execute the primitive.
Definition main.cpp:313
void execute(void *result, Tree &tree)
Execute the primitive.
Definition main.cpp:291
Base primitive class (Tree genotype).
Definition Primitive.h:37
void getNextArgument(void *result, Tree &tree)
Execute next child node's primitive (execute next subtree).
Definition Primitive.cpp:71
Tree class - implements genotype as a tree.
Definition Tree_c.h:29