1#include "../ECF_base.h"
2#include "../SelRandomOp.h"
3#include "../SelFitnessProportionalOp.h"
4#include "../SelWorstOp.h"
5#include "../ECF_macro.h"
17#pragma region Intro comments
31bool cmp (ClassifierP a, ClassifierP b){
32 return a->ind->fitness->getValue() > b->ind->fitness->getValue();
41 selRandomOp =
static_cast<SelectionOperatorP
> (
new SelRandomOp);
42 selFitPropOp =
static_cast<SelectionOperatorP
> (
new SelFitnessProportionalOp);
43 selWorstOp =
static_cast<SelectionOperatorP
> (
new SelWorstOp);
45 params =
static_cast<XCSParamsP
> (
new XCSParams(
name_));
52 params->registerParams(state->getRegistry());
55 ClassifierParamsP params =
static_cast<ClassifierParamsP
> (
new ClassifierParams(0,0,0));
56 state->addGenotype(params);
61 if (!Classifier::checkState(state)) {
65 selRandomOp->initialize(state);
66 selWorstOp->initialize(state);
67 selFitPropOp->initialize(state);
69 params->readParams(state->getRegistry());
73 ClassifierParamsP clParams =
static_cast<ClassifierParamsP
> (
new ClassifierParams(0,0,0));
74 clParams->setGenotypeId(3);
75 clParams->initialize(state);
76 params->initF_ = clParams->F_;
79 environment = std::dynamic_pointer_cast<Environment> (
evalOp_);
81 if (!environment->checkState(state)) {
86 if (!environment->initialize()){
87 throw (std::string(
"failed to initialize"));
89 }
catch (std::string text){
90 ECF_LOG_ERROR(state,
"Environment error: "+text);
96void XCS::printPopulation(){
98 for (uint i = 0; i < populationSet.size(); i++)
99 populationSet[i]->print();
104 if (state->getGenerationNo() == 0){
108 PopulationP pop = state->getPopulation();
110 for (uint i = 0; i < pop->size(); i++){
111 for (uint j = 0; j < pop->at(i)->size(); j++){
112 classP =
static_cast<ClassifierP
>
113 (
new Classifier(params, time, pop->at(i)->at(j), state));
114 populationSet.push_back(classP);
118 for (uint i = 0; i < deme->size(); i++)
119 deme->at(i)->fitness->setValue(params->initF_);
120 environment->reset();
123 std::vector<ClassifierP> lastActionSet;
124 double lastReward = 0;
131 std::cout <<
"Press any key to continue..." << std::endl;
135 std::vector<ClassifierP> matchSet;
136 std::vector<ClassifierP> actionSet;
139 GenotypeP input = environment->getInput();
142 std::cout <<
"Input value: ";
143 Classifier::printBitString(std::dynamic_pointer_cast<BitString::BitString> (input));
144 std::cout << std::endl;
147 matchSet = generateMatchSet(state, deme, input);
150 std::cout <<
"Match set [M]: "<< std::endl;
151 for (uint i = 0; i < matchSet.size(); i++)
152 matchSet[i]->print();
156 std::map<int, double> PA = generatePA(matchSet);
159 int actionId = selectActionId(state, PA);
161 std::cout <<
"action id = " << actionId<< std::endl;
165 actionSet = generateActionSet(matchSet, actionId);
168 std::cout <<
"\nAction set [A]: "<< std::endl;
169 for (uint i = 0; i < actionSet.size(); i++)
170 actionSet[i]->print();
174 IndividualP ind =
static_cast<IndividualP
> (
new Individual);
175 ind->push_back(input);
176 ind->push_back(actionSet[0]->getAction());
180 double reward = ind->fitness->getValue();
183 std::cout <<
"Reward: " << reward << std::endl;
186 if (!lastActionSet.empty()){
187 double P = lastReward + params->gama_ * getMaxFromPA(PA).second;
189 updateActionSet(lastActionSet, deme, P, state);
190 if (!environment->isExploit()) {
191 runGA(lastActionSet, lastInput, deme, state);
194 if (environment->isOver()) {
196 if (!environment->isExploit()) {
197 updateActionSet(actionSet, deme, reward, state);
199 runGA(actionSet, input, deme, state);
200 lastActionSet.clear();
204 lastActionSet = actionSet;
208 }
while (!environment->isOver());
210 environment->nextTrial();
213 std::cout <<
"Classifiers:" << std::endl;
215 std::cout <<
" ===== advanceGeneration end ====="<< std::endl;
221std::vector<ClassifierP> XCS::generateMatchSet(StateP state, DemeP deme, GenotypeP input) {
224 std::vector<ClassifierP> matchSet;
226 while(matchSet.empty()){
228 for (uint i = 0; i < populationSet.size(); ++i){
229 if (populationSet[i]->doesMatch(input))
230 matchSet.push_back(populationSet[i]);
233 uint noDiffActions = (uint) getActionsFromMs(matchSet).size();
234 if (noDiffActions < params->mna_){
236 ClassifierP coverCl = cover(state, deme, input, matchSet);
237 deleteFromPopulation(state, deme);
245std::set<int> XCS::getActionsFromMs (std::vector<ClassifierP> matchSet){
247 std::set<int> actions;
248 for (uint i = 0; i < matchSet.size(); ++i){
249 actions.insert(matchSet[i]->getActionId());
256ClassifierP XCS::cover (StateP state, DemeP deme, GenotypeP input, std::vector<ClassifierP> matchSet){
258 IndividualP newInd =
static_cast<IndividualP
> (
new Individual(state));
260 ClassifierP newClassifier =
static_cast<ClassifierP
> (
new
261 Classifier (params,time, newInd, state));
264 newClassifier->cover(getActionsFromMs(matchSet), input, state);
265 newInd->index = (uint)deme->size();
267 populationSet.push_back(newClassifier);
268 deme->push_back(newInd);
270 assert(deme->size() == populationSet.size());
272 return newClassifier;
276std::map<int, double> XCS::generatePA(std::vector<ClassifierP> matchSet){
277 std::map<int, double> PA;
278 std::map<int, double> fsa;
280 for (uint i = 0; i < matchSet.size(); ++i){
282 ClassifierP cl = matchSet[i];
283 double fitness = cl->getFitness();
284 int action = cl->getActionId();
286 if(PA[action] == NULL) {
287 PA[action] = cl->getPrediction() * fitness;
290 PA[action] += cl->getPrediction() * fitness;
291 fsa[action] += fitness;
293 for (std::map<int, double>::iterator it = PA.begin(); it != PA.end(); ++it){
294 PA[it->first] /= (fsa[it->first] == 0 ? 1 : fsa[it->first]);
300int XCS:: selectActionId(StateP state, std::map<int, double> PA){
301 double rnd = state->getRandomizer()->getRandomDouble();
302 int actionId = PA.begin()->first;
305 if (environment->isExploit())
306 return getMaxFromPA(PA).first;
308 if (rnd < params->p_explore_) {
310 rnd = state->getRandomizer()->getRandomDouble();
312 for (std::map<int, double>::const_iterator it = PA.begin(); it != PA.end(); ++it){
313 if (i > PA.size() * rnd){
314 actionId = it->first;
321 actionId = getMaxFromPA(PA).first;
326std::vector<ClassifierP> XCS::generateActionSet(std::vector<ClassifierP> matchSet,
int actionId){
327 std::vector<ClassifierP> actionSet;
328 for (uint i = 0; i < matchSet.size(); i++)
329 if (matchSet[i]->getActionId() == actionId)
330 actionSet.push_back(matchSet[i]);
334void XCS::updateActionSet(std::vector<ClassifierP> actionSet, DemeP deme,
double reward, StateP state){
338 std::vector<double> accuracy;
341 for (uint i = 0; i < actionSet.size(); ++i)
342 numSum += actionSet[i]->getNumerosity();
345 for (uint i = 0; i < actionSet.size(); ++i){
348 double exp = cl->getExperience() + 1;
349 cl->setExperience(exp);
351 double eps = cl->getError();
352 double p = cl->getPrediction();
353 double as = cl->getActSetSize();
355 if (exp < 1 / params->beta_) {
356 p += (reward - p) / exp;
357 eps += (fabs(reward - p) - eps) / exp;
358 as += (numSum - as) / exp;
360 p += params->beta_ * (reward - p);
361 eps += params->beta_ * (fabs(reward - p) - eps);
362 as += params->beta_ * (numSum - as);
365 if (eps < params->eps0_)
366 accuracy.push_back(1);
368 accuracy.push_back( params->alpha_ * pow(eps / params->eps0_, -params->accExp_) );
370 sum += accuracy[i] * cl->getNumerosity();
372 cl->setPrediction(p);
374 cl->setActSetSize(as);
378 for (uint i = 0; i < actionSet.size(); ++i){
382 double F = cl->getFitness();
383 F += params->beta_ * (accuracy[i] * cl->getNumerosity() / sum - F) ;
387 actionSetSubsumption(&actionSet, deme, state);
391double XCS::getAsTimeSum(std::vector<ClassifierP> as) {
393 double sumNum = 0, sumTsNum = 0;
394 for (uint i = 0; i < as.size(); ++i){
395 sumTsNum += as[i]->getTimeStamp() * as[i]->getNumerosity();
396 sumNum += as[i]->getNumerosity();
399 return sumTsNum / sumNum;
402void XCS::runGA(std::vector<ClassifierP> actionSet, GenotypeP genInput, DemeP deme, StateP state){
404 if (time - getAsTimeSum(actionSet) < params->thresholdGA_)
return;
406 std::vector<IndividualP> tournament, vActionSet;
408 for (uint i = 0; i < actionSet.size(); i++) {
409 if (!actionSet[i]->valid)
continue;
410 vActionSet.push_back(actionSet[i]->ind);
411 actionSet[i]->setTimeStamp(time);
413 if (vActionSet.size() < 1)
return;
415 IndividualP parent[2];
416 parent[0] = selFitPropOp->select(vActionSet);
417 parent[1] = selFitPropOp->select(vActionSet);
419 ClassifierP clParent[2];
420 clParent[0] = populationSet[parent[0]->index];
421 clParent[1] = populationSet[parent[1]->index];
423 assert(clParent[0]->getActionId() == clParent[1]->getActionId());
424 ClassifierP clChild[2];
426 for (
int i = 0; i < 2; ++i) {
428 clChild[i] =
static_cast<ClassifierP
> (
new Classifier(clParent[i]));
430 clChild[i]->setNumerosity(1);
431 clChild[i]->setExperience(0);
433 double f = clChild[i]->getFitness();
435 if (state->getRandomizer()->getRandomDouble() < params->pCrossover_) {
436 mate(parent[0], parent[1], clChild[i]->ind);
438 clChild[i]->setAction(clParent[0]->getAction());
440 assert(clChild[i]->getActionId() == clParent[i]->getActionId());
442 clChild[i]->setPrediction((clParent[0]->getPrediction() + clParent[1]->getPrediction()) / 2);
443 clChild[i]->setError((clParent[0]->getError() + clParent[1]->getError()) / 2);
445 f = (clParent[0]->getFitness() + clParent[1]->getFitness()) / 2;
448 clChild[i]->setFitness( 0.1 * f);
450 clChild[i]->mutateRule(genInput, state);
451 clChild[i]->mutateAction(state);
453 if (clParent[0]->doesSubsume(clChild[i])) {
454 clParent[0]->setNumerosity(clParent[0]->getNumerosity() + 1);
455 }
else if (clParent[1]->doesSubsume(clChild[i])) {
456 clParent[1]->setNumerosity(clParent[1]->getNumerosity() + 1);
458 clChild[i]->ind->index = (uint)deme->size();
459 populationSet.push_back(clChild[i]);
460 deme->push_back(clChild[i]->ind);
462 assert(deme->size() == populationSet.size());
464 deleteFromPopulation(state, deme);
468std::pair<int, double> XCS::getMaxFromPA(std::map<int, double> PA){
470 if (PA.empty())
return std::make_pair(-1, -1.);
472 std::pair<int, double> maxPA = *PA.begin();
473 for (std::map<int, double>::iterator it = PA.begin(); it != PA.end(); ++it){
474 if (it->second > maxPA.second)
480void XCS::deleteFromPopulation(StateP state, DemeP deme) {
485 for ( uint i = 0; i < populationSet.size(); ++i) {
486 sumNum += populationSet[i]->getNumerosity();
487 sumFit += populationSet[i]->getFitness();
489 if (sumNum <= (
int) params->popSize_)
return;
491 double avFitInPop = sumFit / sumNum;
494 for ( uint i = 0; i < populationSet.size(); ++i) {
495 sumVote += populationSet[i]->getDeletionVote(avFitInPop);
497 double choicePoint = state->getRandomizer()->getRandomDouble() * sumVote;
499 for ( uint i = 0; i < populationSet.size(); ++i) {
500 ClassifierP cl = populationSet[i];
501 sumVote += cl->getDeletionVote(avFitInPop);
502 if (sumVote > choicePoint) {
503 int n = cl->getNumerosity();
505 cl->setNumerosity(n-1);
507 removeFromPopSet(cl, deme);
512 assert(deme->size() == populationSet.size());
516void XCS::removeFromPopSet(ClassifierP cl, DemeP deme){
518 IndividualP lastInd = deme->at(deme->size()-1);
519 ClassifierP lastCl = populationSet[populationSet.size()-1];
521 lastInd->index = cl->ind->index;
523 populationSet[cl->ind->index] = lastCl;
524 populationSet.erase(populationSet.begin() + populationSet.size() - 1);
526 deme->at(cl->ind->index) = lastInd;
527 deme->erase(deme->begin() + deme->size() - 1);
529 assert(deme->size() == populationSet.size());
533void XCS::actionSetSubsumption(std::vector<ClassifierP> *actionSet, DemeP deme, StateP state){
537 for (uint i = 0; i < actionSet->size(); ++i){
539 ClassifierP c = actionSet->at(i);
540 if (c->couldSubsume()){
542 int clDcb = c->numOfDCBits();
543 double rnd = state->getRandomizer()->getRandomDouble();
544 if (!clSet || clDcb > cl->numOfDCBits() || (clDcb == cl->numOfDCBits() && rnd < 0.5 )) {
551 for (uint i = 0; i < actionSet->size(); ++i){
552 ClassifierP c = actionSet->at(i);
553 if (cl->isMoreGeneral(c)){
554 cl->setNumerosity(cl->getNumerosity() + c->getNumerosity());
555 actionSet->erase(actionSet->begin() + i);
556 removeFromPopSet(c,deme);
EvaluateOpP evalOp_
sptr to evaluation operator (set by the system)
std::string name_
algorithm name
bool mate(IndividualP p1, IndividualP p2, IndividualP child)
Helper function: crossover two individuals.
void evaluate(IndividualP ind)
Helper function: evaluate an individual.
Classifier class that holds all parameters and pointer to individual to which the parameters belong.
Classifier data structure in XCS algorithm.
Individual class - inherits a vector of Genotype objects.
bool advanceGeneration(StateP state, DemeP deme)
Perform a single generation on a single deme.
bool initialize(StateP state)
Initialize the algorithm, read parameters from the system, do a sanity check.
void registerParameters(StateP state)
Register algorithm's parameters (if any).