ECF 1.5
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 = boost::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 boost::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#include <boost/property_tree/ptree.hpp>
183#include <boost/property_tree/xml_parser.hpp>
184#include <boost/foreach.hpp>
185namespace pt = boost::property_tree;
186
187// 2. primjer: GA minimizacija funkcije
188/*
189#include "examples/GAFunctionMin/FunctionMinEvalOp.h"
190int main(int argc, char **argv)
191{
192 argc = 2;
193 argv[1] = "./examples/GAFunctionMin/parametri.txt";
194
195 StateP state (new State);
196 state->setEvalOp(new FunctionMinEvalOp);
197
198 state->initialize(argc, argv);
199 state->run();
200
201
202 try {
203 pt::ptree tree;
204 pt::read_xml("./examples/GAFunctionMin/parametri.txt", tree);
205 pt::ptree ecf = tree.get_child("ECF");
206 pt::ptree genotype = ecf.get_child("Genotype");
207
208 // BOOST_FOREACH(pt::ptree::value_type &v, genotype.get_child("")) {
209 for(pt::ptree::iterator it = genotype.begin(); it != genotype.end(); it++) {
210 pt::ptree::value_type &v = *it;
211 if(v.first == "FloatingPoint")
212 ;
213 }
214 }
215 catch(const pt::ptree_error& er){
216 std::cout << er.what() << std::endl;
217 }
218
219
220
221
222
223 return 0;
224
225//
226// ispis populacije u txt fajl, za potrebe landscape analysis
227//
228 ofstream fajl("popis.txt");
229 for(uint i = 0; i < state->getPopulation()->getLocalDeme()->getSize(); i++) {
230 IndividualP ind = state->getPopulation()->getLocalDeme()->at(i);
231 fajl << ind->fitness->getValue() << "\t";
232 FloatingPointP fp = boost::static_pointer_cast<FloatingPoint::FloatingPoint> (ind->getGenotype());
233 for(uint dim = 0; dim < fp->realValue.size(); dim++)
234 fajl << fp->realValue[dim] << "\t";
235 fp = boost::static_pointer_cast<FloatingPoint::FloatingPoint> (ind->getGenotype(2));
236 fajl << fp->realValue[0];
237 fajl << "\n";
238 }
239
240 return 0;
241}
242*/
243
244
245// 2a. primjer: MO NSGA minimizacija funkcije
246/*
247#include "examples/MOFunctionMin/MOFunctionMinEvalOp.h"
248int main(int argc, char **argv)
249{
250 argc = 2;
251 argv[1] = "./examples/MOFunctionMin/parameters.txt";
252
253 StateP state (new State);
254 state->setEvalOp(new MOEvalOp);
255
256 state->initialize(argc, argv);
257 state->run();
258
259 // ispis populacije na kraju
260 std::ofstream myfile;
261 myfile.open ("paretoFront.txt");
262 DemeP deme = state->getPopulation()->getLocalDeme();
263 for (uint i = 0; i<deme->size(); i++) {
264 MOFitnessP fitness = boost::static_pointer_cast<MOFitness> (deme->at(i)->fitness);
265 for (uint f = 0; f < fitness->size(); f++)
266 myfile << fitness->at(f)->getValue() << "\t";
267 myfile << "\n";
268 }
269 myfile.close();
270
271 return 0;
272}
273*/
274
275
276
277namespace Tree {
278
279// primjer tipa podataka
281{
282 double v;
283 bool b;
284};
285
286// terminal za doticni tip
288{
289public:
290 my_type value_;
291
292 MyTerminal()
293 {
294 nArguments_ = 0;
295 }
296 void execute(void* result, Tree& tree)
297 {
298 my_type& res = *(my_type*)result;
299 res = value_;
300 }
301 void setValue(void* value)
302 {
303 value_ = *(my_type*)value;
304 }
305 ~MyTerminal()
306 { }
307};
308
309// primjer funkcije za korisnicki tip podataka
311{
312public:
313 MyFunc()
314 {
315 nArguments_ = 2;
316 name_ = "func";
317 }
318 void execute(void* result, Tree& tree)
319 {
320 my_type first, second;
321 my_type& func = *(my_type*)result;
322
323 getNextArgument(&first, tree);
324 getNextArgument(&second, tree);
325
326 func.b = first.b && second.b;
327 func.v = first.v + second.v;
328 }
329 ~MyFunc()
330 { }
331};
332
333}
334
335
336
337// 3. primjer: GP simbolicka regresija
338
339#include "examples/GPSymbReg/SymbRegEvalOp.h"
340#include "examples/GPSymbReg/zbr.h"
341int main(int argc, char **argv)
342{
343// argc = 2;
344// argv[1] = "./examples/GPSymbReg/parametri.txt";
345
346 StateP state = static_cast<StateP> (new State);
347
348 state->setEvalOp(static_cast<EvaluateOpP> (new SymbRegEvalOp));
349
350 // primjer: dodavanje korisnickog operatora
351// MyOpP myOp = (MyOpP) (new MyOp);
352// state->addOperator(myOp);
353
354 // primjer: dodavanje korisnickog algoritma
355// MyAlgP myAlg = (MyAlgP) (new MyAlg);
356// state->addAlgorithm(myAlg);
357
358 // primjer: dodavanje korisnickog genotipa
359// MyGenotypeP myGenotype = (MyGenotypeP) (new MyGenotype);
360// state->addGenotype(myGenotype);
361
362 // primjer: dodavanje korisnicke funkcije za stablo
363 TreeP tree = (TreeP) new Tree::Tree;
364 Tree::PrimitiveP zbr = (Tree::PrimitiveP) new Tree::Ad;
365 tree->addFunction(zbr);
366
367Tree::PrimitiveP myFunc = (Tree::PrimitiveP) new Tree::MyFunc;
368tree->addFunction(myFunc);
369
370Tree::PrimitiveP myTerm = (Tree::PrimitiveP) new Tree::MyTerminal;
371myTerm->setName("term");
372tree->addTerminal(myTerm);
373
374
375 state->addGenotype(tree);
376
377 if (!state->initialize(argc, argv))
378 return 1;
379 state->run();
380
381 //std::vector<IndividualP> vec = state->getPopulation()->hof_->getBest();
382 //IndividualP ind = vec[0];
383 //state->getAlgorithm()->evaluate(ind);
384 //XMLNode out;
385 //ind->write(out);
386 //std::cout << out.createXMLString() << std::endl;
387
388 std::vector<IndividualP> vec = state->getPopulation()->getHof()->getBest();
389 IndividualP ind = vec[0];
390 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");
391 ind->read(xml2);
392 state->getAlgorithm()->evaluate(ind);
393 std::cout << ind->toString();
394
395 return 0;
396}
397
398
399
400//4. primjer: GA problem trgovackog putnika, 29 gradova
401/*
402#include "examples/GATSP/TSPEvalOp.h"
403int main(int argc, char **argv)
404{
405// argc = 2;
406// argv[1] = "./examples/GATSP/parameters.txt";
407
408 StateP state = static_cast<StateP> (new State);
409
410 state->setEvalOp(static_cast<EvaluateOpP> (new TSPEvalOp));
411
412 state->initialize(argc, argv);
413 //state->getFitnessObject();
414
415 state->run();
416
417 return 0;
418}
419*/
420
421
422
423//5. primjer: GA problem aproksimacije funkcije
424/*
425#include "examples/GAApprox/ApproxEvalOp.h"
426int main(int argc, char **argv)
427{
428// argc = 2;
429// argv[1] = "./examples/GAApprox/parameters.txt";
430
431 StateP state(new State);
432
433 state->setEvalOp(EvaluateOpP (new AproxEvalOp));
434
435 state->initialize(argc, argv);
436 state->run();
437
438 return 0;
439}
440*/
441
442
443
444//6. primjer: GP evolucija pravila rasporedjivanja
445/*
446#include "examples/GPScheduling/SchedulingEvalOp.h"
447int main(int argc, char **argv)
448{
449 argc = 2;
450 //argv[1] = "./examples/GPScheduling/parameters.txt";
451 argv[1] = "./parameters.txt";
452
453 StateP state = static_cast<StateP> (new State);
454
455 state->setEvalOp(static_cast<EvaluateOpP> (new SchedulingEvalOp));
456
457 state->initialize(argc, argv);
458 state->run();
459
460// XMLNode xInd = XMLNode::parseFile("./ind.txt", "Individual");
461// IndividualP ind = (IndividualP) new Individual(state);
462// ind->read(xInd);
463// state->getAlgorithm()->evaluate(ind);
464// std::cout << ind->toString();
465
466 return 0;
467}
468*/
469
470
471//7. primjer: XCS
472/*
473#include "examples/XCSmux/MuxEvalOp.h"
474#include "examples/XCSmaze/SingleObjMazeEnv.h"
475#include "examples/XCSmaze/SeqObjMazeEnv.h"
476#include "examples/XCSmaze/TwoObjMazeEnv.h"
477#include "examples/XCSmaze/ThreeObjMazeEnv.h"
478
479int main(int argc, char **argv)
480{
481 argc = 2;
482 StateP state = static_cast<StateP> (new State);
483 MazeEnvP maze;
484
485 //Multistep:
486
487 // - sigle-objective maze:
488 //argv[1] = "examples/XCSmaze/single-obj params.txt";
489 //maze = static_cast<MazeEnvP> (new SingleObjMazeEnv(state));
490 //maze->setMazeFile("examples/XCSmaze/Environments/single-objective/Maze1.txt");
491
492 // - multi-objective maze:
493 //argv[1] = "examples/XCSmaze/seq-obj params.txt";
494 //maze = static_cast<MazeEnvP> (new SeqObjMazeEnv(state));
495 //maze->setMazeFile("examples/XCSmaze/Environments/multi-objective/Maze1k.txt");
496
497 argv[1] = "examples/XCSmaze/three-obj params.txt";
498 maze = static_cast<MazeEnvP> (new ThreeObjMazeEnv(state,0));
499 maze->setMazeFile("examples/XCSmaze/Environments/multi-objective/Maze1em.txt");
500
501 maze->setResultsFile("examples/XCSmaze/Maze1k results.txt");
502 state->setEvalOp(maze);
503
504 //Singlestep:
505
506 // - 6-multiplexor problem:
507 // argv[1] = "./examples/XCSmux/parametri.txt";
508 // state->setEvalOp(static_cast<EvaluateOpP> (new MuxEvalOp(state)));
509
510 state->initialize(argc, argv);
511
512 state->run();
513
514 int a;
515 cin >> a;
516 return 0;
517}
518*/
519
520
521
522//8. primjer: Kartezijski GP - feedforward
523/*
524#include "examples/CGPFeedForward/FeedForwardEvalOp.h"
525#include "examples/CGPFeedForward/CGPEvalOp.h"
526#include "cartesian/Cartesian.h"
527using namespace cart;
528
529int main(int argc, char **argv)
530{
531 argc = 2;
532 argv[1] = "./examples/CGPFeedForward/parameters.txt";
533
534 StateP state (new State);
535
536 CartesianP cart (new Cartesian);
537
538 state->addGenotype(cart);
539
540 state->setEvalOp(new FunctionMinEvalOp);
541
542
543 // izabrati koji tip
544 //state->setEvalOp(new cart::FeedForwardEvalOpInt);
545 //state->setEvalOp(static_cast<EvaluateOpP> (new cart::FeedForwardEvalOpDouble));
546 //state->setEvalOp(static_cast<EvaluateOpP> (new cart::CircuitEvalOpUint));
547
548 state->initialize(argc, argv);
549 state->run();
550
551 return 0;
552}
553*/
Algorithm base class.
Definition: Algorithm.h:20
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.
Definition: FloatingPoint.h:39
Definition: main.cpp:15
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
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:39
Symbolic regression evaluation operator (using AP genotype).
Definition: SymbRegEvalOp.h:29
void execute(void *result, Tree &tree)
Execute the primitive.
Definition: main.cpp:318
void execute(void *result, Tree &tree)
Execute the primitive.
Definition: main.cpp:296
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
void setName(std::string name)
Set primitive's name.
Definition: Primitive.cpp:100
Tree class - implements genotype as a tree.
Definition: Tree_c.h:29
bool addFunction(PrimitiveP)
Add user defined function primitive. Must be called prior to initialization (no impact otherwise).
Definition: Tree.cpp:80