bool ArtificialBeeColony::onlookerBeesPhase(StateP state, DemeP deme)
{
// jednostavni odabir, uz selFitPropOp
/*	for( uint i = 0; i < deme->getSize(); i++ ) { // for each food source
		// choose a food source depending on its fitness value (better individuals are more likely to be chosen)
		IndividualP food = selFitOp->select(*deme);
		createNewFoodSource(food, state, deme);
	}
*/


// uz vjerojatnosti, jedinka po jedinka
	calculateProbabilities(state, deme);
	int demeSize = deme->getSize();
	int i = state->getRandomizer()->getRandomInteger(demeSize);
	int n = 0;
	while( n < demeSize) {
		int fact = i++ % demeSize;
		IndividualP food = deme->at(fact);
		
		if (state->getRandomizer()->getRandomDouble() < probability_[fact]){
			n++;
			createNewFoodSource(food, state, deme);
		}			
	}

	return true;
}
Пример #2
0
		bool initialize(StateP state)
		{		
			voidP lBound = state->getGenotypes()[0]->getParameterValue(state, "lbound");
			lbound = *((double*) lBound.get());

			voidP uBound = state->getGenotypes()[0]->getParameterValue(state, "ubound");
			ubound = *((double*) uBound.get());

			voidP dimension_ = state->getGenotypes()[0]->getParameterValue(state, "dimension");
			dimension = *((uint*) dimension_.get());

			voidP dup_ = getParameterValue(state, "dup");
			dup = *((uint*) dup_.get());
			if( *((int*) dup_.get()) <= 0 ) {
				ECF_LOG(state, 1, "Error: opt-IA requires parameter 'dup' to be an integer greater than 0");
				throw "";}

			voidP c_ = getParameterValue(state, "c");
			c = *((double*) c_.get());
			if( c <= 0 ) {
				ECF_LOG(state, 1, "Error: opt-IA requires parameter 'c' to be a double greater than 0");
				throw "";}

			voidP tauB_ = getParameterValue(state, "tauB");
			tauB = *((double*) tauB_.get());
			if( tauB < 0 ) {
				ECF_LOG(state, 1, "Error: opt-IA requires parameter 'tauB' to be a nonnegative double value");
				throw "";}

			voidP elitism_ = getParameterValue(state, "elitism");
			elitism = *((string*) elitism_.get());
			if( elitism != "true" && elitism != "false"  ) {
				ECF_LOG(state, 1,  "Error: opt-IA requires parameter 'elitism' to be either 'true' or 'false'");
				throw "";}


			// algorithm accepts a single FloatingPoint Genotype
			FloatingPointP flp (new FloatingPoint::FloatingPoint);
			if(state->getGenotypes()[0]->getName() != flp->getName()) {
				ECF_LOG_ERROR(state, "Error: opt-IA algorithm accepts only a FloatingPoint genotype!");
				throw ("");}

			// algorithm adds another FloatingPoint genotype (age)
			FloatingPointP flpoint[2];
			for(uint iGen = 1; iGen < 2; iGen++) {
				flpoint[iGen] = (FloatingPointP) new FloatingPoint::FloatingPoint;
				state->setGenotype(flpoint[iGen]);

				flpoint[iGen]->setParameterValue(state, "dimension", (voidP) new uint(1));					

				// initial value of age parameter should be (or as close as possible to) 0				
				flpoint[iGen]->setParameterValue(state, "lbound", (voidP) new double(0));
				flpoint[iGen]->setParameterValue(state, "ubound", (voidP) new double(0.01));
				
			}
			ECF_LOG(state, 1, "opt-IA algorithm: added 1 FloatingPoint genotype (antibody age)");
			
            return true;
		}
Пример #3
0
/**
 * \brief Register mutation related but Genotype unrelated parameters
 */
void Mutation::registerParameters(StateP state)
{
	state->getRegistry()->registerEntry("mutation.indprob", (voidP) new double(0.3), ECF::DOUBLE,
		"individual mutation probability (unless the algorithm overrides it) (default: 0.3)");
//	state->getRegistry()->registerEntry("mutation.geneprob", (voidP) new double(0.01), ECF::DOUBLE);
	state->getRegistry()->registerEntry("mutation.genotypes", (voidP) new std::string("random"), ECF::STRING,
		"if there are multiple genotypes, which to mutate? 'random': a random one, all: mutate all (default: random)");
	state->getRegistry()->registerEntry("mutation.protected", (voidP) new std::string(""), ECF::STRING,
		"indexes of genotypes (separated by spaces) that are excluded (protected) from mutation (default: none)");
}
Пример #4
0
bool TermStagnationOp::operate(StateP state)
{
	uint currentGen = state->getGenerationNo();
	if(currentGen - state->getPopulation()->getHof()->getLastChange() > termStagnation_) {
		state->setTerminateCond();
		ECF_LOG(state, 1, "Termination: maximum number of generations without improvement ("
			+ uint2str(termStagnation_) + ") reached");
	}

	return true;
}
Пример #5
0
void RegEvalOp::registerParameters(StateP state) {

    state->getRegistry()->registerEntry("inputfile", (voidP)(new std::string("learning.txt")), ECF::STRING);

    state->getRegistry()->registerEntry("testfile", (voidP)(new std::string("test.txt")), ECF::STRING);

    state->getRegistry()->registerEntry("classesfile", (voidP)(new std::string("classes.txt")), ECF::STRING);

    state->getRegistry()->registerEntry("resultsfile", (voidP)(new std::string("results.txt")), ECF::STRING);

    state->getRegistry()->registerEntry("classesNum", (voidP)(new uint(2)), ECF::UINT);
}
bool ArtificialBeeColony::initialize(StateP state)
{
	// initialize all operators
	selFitOp->initialize(state);
	selFitOp->setSelPressure(2);
	selBestOp->initialize(state);
	selWorstOp->initialize(state);
	selRandomOp->initialize(state);

	voidP sptr = state->getRegistry()->getEntry("population.size");
	uint size = *((uint*) sptr.get());
	probability_.resize(size);

	// this algorithm accepts a single FloatingPoint Genotype
	FloatingPointP flp (new FloatingPoint::FloatingPoint);
	if(state->getGenotypes()[0]->getName() != flp->getName()) {
		ECF_LOG_ERROR(state, "Error: ABC algorithm accepts only a single FloatingPoint genotype!");
		throw ("");
	}

	voidP limitp = getParameterValue(state, "limit");
	limit_ = *((uint*) limitp.get());

	voidP lBound = state->getGenotypes()[0]->getParameterValue(state, "lbound");
	lbound_ = *((double*) lBound.get());
	voidP uBound = state->getGenotypes()[0]->getParameterValue(state, "ubound");
	ubound_ = *((double*) uBound.get());

	// batch run check
	if(isTrialAdded_)
		return true;

	FloatingPointP flpoint[2];
	for(uint iGen = 1; iGen < 2; iGen++) {

		flpoint[iGen] = (FloatingPointP) new FloatingPoint::FloatingPoint;
		state->setGenotype(flpoint[iGen]);

		flpoint[iGen]->setParameterValue(state, "dimension", (voidP) new uint(1));					

		// initial value of trial parameter should be (as close as possible to) 0				
		flpoint[iGen]->setParameterValue(state, "lbound", (voidP) new double(0));
		flpoint[iGen]->setParameterValue(state, "ubound", (voidP) new double(0.01));
	}
	ECF_LOG(state, 1, "ABC algorithm: added 1 FloatingPoint genotype (trial)");

	// mark adding of trial genotype
	isTrialAdded_ = true;

    return true;
}
		 bool createNewFoodSource(IndividualP food, StateP state, DemeP deme)
		 {  
			 //for each food source find a neighbour 
			IndividualP neighbour;
			do{
				neighbour = selRandomOp->select(*deme);
			}while(food->index == neighbour->index);

			//potential new food source
			IndividualP newFood = copy(food);

			FloatingPointP flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (food->getGenotype(0));
			std::vector< double > &foodVars = flp->realValue;
			flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (neighbour->getGenotype(0));
			std::vector< double > &neighbourVars = flp->realValue;
			flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (newFood->getGenotype(0));
			std::vector< double > &newFoodVars = flp->realValue;


			uint param = state->getRandomizer()->getRandomInteger((int)foodVars.size());
			double factor = state->getRandomizer()->getRandomDouble();
			double value = foodVars[param] * (1-2*factor)*(foodVars[param]-neighbourVars[param]);
			if (value > ubound)
				value = ubound;
			else if (value <lbound)
				value = lbound;

			//produce a modification on the food source (discover a new food source)
			newFoodVars[param] = value;
			evaluate(newFood);

			flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (food->getGenotype(1));
			double &foodTrial = flp->realValue[0];

//			d)	if the fitness value of the new food source is better than that of the original source,
//					memorize the new source, forget the old one and set trial to 0
//					otherwise keep the old one and increment trial
			if(newFood->fitness->isBetterThan( food->fitness) )
			{
				foodVars[param] = value;
				evaluate(food);
				foodTrial = 0;
			}
			else {
				foodTrial +=1;
			}
			return true;
		}
Пример #8
0
bool Individual::initialize(StateP state)
{
	state_ = state;
	this->clear();

	// copy genotypes from State
	for(uint i = 0; i < state->getGenotypes().size(); i++) {
		this->push_back(static_cast<GenotypeP> (state->getGenotypes()[i]->copy()));
		(*this)[i]->setGenotypeId(i);
	}

	// init genotypes
	for(uint i = 0; i < this->size(); i++)
		(*this)[i]->initialize(state);

	return true;
}
//! cross donor vectors with population members to create trial vectors
void DifferentialEvolution::crossover(DemeP deme, uint index, StateP state)
{
	// get population member and corresponding donor vector
	FloatingPoint::FloatingPoint* flp1 = (FloatingPoint::FloatingPoint*) (deme->at(index)->getGenotype().get());
	int dim = (int) flp1->realValue.size();
	FloatingPoint::FloatingPoint* flp2 = (FloatingPoint::FloatingPoint*) donor_vector[index]->getGenotype().get();

	// crossover their elements (keep the result in donor_vector)
	for(uint i = 0; i < flp1->realValue.size(); i++) {
		if (state->getRandomizer()->getRandomDouble() <= CR_ || i == state->getRandomizer()->getRandomInteger(dim)) {
		}
		else {
			flp2->realValue[i] = flp1->realValue[i];
	    }
	}

}
Пример #10
0
		bool hypermutationPhase(StateP state, DemeP deme, std::vector<IndividualP> &clones)
		{	
			uint M;	// M - number of mutations of a single antibody 
			uint k;

			//sort 
			std::sort (clones.begin(), clones.end(), sortPopulationByFitness);

			for( uint i = 0; i < clones.size(); i++ ){ // for each antibody in vector clones
				IndividualP antibody = clones.at(i);
				
				FloatingPointP flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (antibody->getGenotype(0));
			    std::vector< double > &antibodyVars = flp->realValue;
				
				k = 1 + i/(dup+1);
				M =(int) ((1- 1/(double)(k)) * (c*dimension) + (c*dimension));
				
				// mutate M times
				for (uint j = 0; j < M; j++){
					uint param = state->getRandomizer()->getRandomInteger((int)antibodyVars.size());
					
					double randDouble1 = state->getRandomizer()->getRandomDouble();
					double randDouble2 = state->getRandomizer()->getRandomDouble();
					double value = antibodyVars[param] + (1-2*randDouble1)* 0.2 *  (ubound - lbound) * pow(2, -16*randDouble2 );
					
					if (value > ubound)
						value = ubound;
					else if (value <lbound)
						value = lbound;

					//produce a mutation on the antibody 
					antibodyVars[param] = value;
				}
				FitnessP parentFitness = antibody->fitness;
				evaluate(antibody);

				// if the clone is better than its parent, reset clone's age
				if(antibody-> fitness->isBetterThan(parentFitness)){					
					flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (antibody->getGenotype(1));
					double &age = flp->realValue[0];
					age = 0;
				} 
			}
			return true;
		}
bool DifferentialEvolution::initialize(StateP state)
{	
	selRandomOp->initialize(state);
	donor_vector.clear();

	// read parameters, check defined genotype (only a single FloatingPoint is allowed)
	voidP F = getParameterValue(state, "F");
	Fconst_ = *((double*) F.get());
	voidP CR = getParameterValue(state, "CR");
	CR_ = *((double*) CR.get());
	FloatingPointP flp (new FloatingPoint::FloatingPoint);
	if(state->getGenotypes()[0]->getName() != flp->getName() || state->getGenotypes().size() != 1) {
		state->getLogger()->log(1, "Error: DE algorithm accepts only a single FloatingPoint genotype!");
		throw ("");
	}

	return true;
}
void ModularRobotEvalOp::registerParameters(StateP state)
{
    state->getRegistry()->registerEntry("robot.modules", (voidP) (new uint(1)), ECF::UINT, "Number of modules" );
    state->getRegistry()->registerEntry("robot.runtime", (voidP) (new uint(10000)), ECF::UINT, "Max robot runtime (ms)" );
    state->getRegistry()->registerEntry("robot.timestep", (voidP) (new float(1.0)), ECF::FLOAT, "Time step (ms)" );
    state->getRegistry()->registerEntry("robot.configfile", (voidP) (new std::string()), ECF::STRING, "Robot description file");

    state->getRegistry()->registerEntry("osc.maxamplitude", (voidP) (new uint(90)), ECF::UINT, "Max amplitude of oscillators");
    state->getRegistry()->registerEntry("osc.maxoffset", (voidP) (new uint(90)), ECF::UINT, "Max offset of oscillators");
    state->getRegistry()->registerEntry("osc.maxphase", (voidP) (new uint(360)), ECF::UINT, "Max phase of oscillators");
    state->getRegistry()->registerEntry("osc.maxfrequency", (voidP) (new float(1.0f)), ECF::FLOAT, "Max frequency of oscillators");
}
Пример #13
0
bool SymbRegEvalOp::initialize(StateP state)
{
	domain.clear();
	codomain.clear();

	double datum;
	std::stringstream ss;

	// check if the parameters are defined in the conf. file
	// if not, we return false so the initialization fails
	if(!state->getRegistry()->isModified("domain") ||
		!state->getRegistry()->isModified("codomain"))
		return false;

	voidP sptr = state->getRegistry()->getEntry("domain"); // get parameter value
	ss << *((std::string*) sptr.get()); // convert from voidP to user defined type
	while(ss >> datum) {	// read all the data from string
		domain.push_back(datum);
	}
	ss.str("");
	ss.clear();	// reset stringstream object
	sptr = state->getRegistry()->getEntry("codomain");	// get codomain parameter
	ss << *((std::string*) sptr.get());
	while(ss >> datum) {	// read values
		codomain.push_back(datum);
	}

	if(domain.size() != codomain.size())	// if the parameters are ill defined, return false
		return false;
	nSamples = (uint) domain.size();

	return true;

	//nSamples = 10;
	//double x = -10;
	//for(uint i = 0; i < nSamples; i++) {
	//	domain.push_back(x);
	//	codomain.push_back(x + sin(x));
	//	x += 2;
	//}
	//return true;
}
Пример #14
0
int main(int argc, char **argv)
{
//	argc = 2;
//	argv[1] = "./examples/GAFunctionMin/parametri.txt";

	// PSO algoritam:
	//argv[1] = "./examples/GAFunctionMin/parameters_DE.txt";

	GenHookeJeevesP alg (new GenHookeJeeves);

	StateP state (new State);
	state->addAlgorithm(alg);

	state->setEvalOp(static_cast<EvaluateOpP> (new FunctionMinEvalOp));

	state->initialize(argc, argv);
	state->run();

	return 0;
}
Пример #15
0
bool TermStagnationOp::initialize(StateP state)
{
	voidP sptr = state->getRegistry()->getEntry("term.stagnation");
	termStagnation_ = *((uint*) sptr.get());

	// define the default criterion
	if(termStagnation_ == 0) {
		voidP sptr = state->getRegistry()->getEntry("population.size");
		uint demeSize = *((uint*) sptr.get());
		termStagnation_ = 5000 / demeSize;
		if(termStagnation_ < 10)
			termStagnation_ = 5;
		if(termStagnation_ > 200)
			termStagnation_ = 200;
	}

	if(!state->getRegistry()->isModified("term.stagnation"))
		return false;

	return true;
}
        bool initialize(StateP state)
		{		
			// initialize all operators
			selFitOp->initialize(state);
			selBestOp->initialize(state);
			selRandomOp->initialize(state);
			
			voidP limit_ = getParameterValue(state, "limit");
			limit = *((uint*) limit_.get());

			voidP lBound = state->getGenotypes()[0]->getParameterValue(state, "lbound");
			lbound = *((double*) lBound.get());
			voidP uBound = state->getGenotypes()[0]->getParameterValue(state, "ubound");
			ubound = *((double*) uBound.get());

		// algorithm accepts a single FloatingPoint Genotype
			FloatingPointP flp (new FloatingPoint::FloatingPoint);
			if(state->getGenotypes()[0]->getName() != flp->getName()) {
				ECF_LOG_ERROR(state, "Error: ABC algorithm accepts only a FloatingPoint genotype!");
				throw ("");
			}

			FloatingPointP flpoint[2];
			for(uint iGen = 1; iGen < 2; iGen++) {

				flpoint[iGen] = (FloatingPointP) new FloatingPoint::FloatingPoint;
				state->setGenotype(flpoint[iGen]);

				flpoint[iGen]->setParameterValue(state, "dimension", (voidP) new uint(1));					

				// initial value of trial parameter should be (as close as possible to) 0				
				flpoint[iGen]->setParameterValue(state, "lbound", (voidP) new double(0));
				flpoint[iGen]->setParameterValue(state, "ubound", (voidP) new double(0.01));
				
			}
			ECF_LOG(state, 1, "ABC algorithm: added 1 FloatingPoint genotype (trial)");
 
            return true;
        }
Пример #17
0
bool StatCalc::initialize(StateP state)
{
	state_ = state;
	average_.clear();
	stdDev_.clear();
	max_.clear();
	min_.clear();
	time_.clear();
	sampleSize_.clear();
	evaluations_.clear();
	nEvaluations_ = 0;
	lowest_ = highest_ = 0;

	if(state->getRegistry()->isModified("stats.file")) {
		voidP sptr = state->getRegistry()->getEntry("stats.file");
		statsFileName_ = *((std::string*) sptr.get());

		statsFile_.open(statsFileName_.c_str());
		if(!statsFile_) {
			throw std::string("Error: can't open stats file (") + statsFileName_ + ")";
		}
	}
	return true;
}
Пример #18
0
void SymbRegEvalOp::registerParameters(StateP state)
{
	state->getRegistry()->registerEntry("domain", (voidP) (new std::string), ECF::STRING);
	state->getRegistry()->registerEntry("codomain", (voidP) (new std::string), ECF::STRING);
}
bool PSOInheritance::initialize(StateP state)
{
	// initialize all operators
	selBestOp->initialize(state);

	voidP weightType = getParameterValue(state, "weightType");
	m_weightType = *((InertiaWeightType*) weightType.get());

	voidP weight = getParameterValue(state, "weight");
	m_weight = *((double*) weight.get());

	voidP maxV = getParameterValue(state, "maxVelocity");
	m_maxV = *((double*) maxV.get());

	// test if inertia weight type is time variant and if so, check if max iterations specified
	if(m_weightType == TIME_VARIANT) {
		if(state->getRegistry()->isModified("term.maxgen")) {
			// read maxgen parameter
			m_maxIter = *(boost::static_pointer_cast<int>( state->getRegistry()->getEntry("term.maxgen") ));
		}
		else {
			ECF_LOG_ERROR(state, "Error: term.maxgen has to be specified in order to use time variant inertia eight in PSO algorithm");
			throw("");
		}
	}

	// algorithm accepts a single FloatingPoint Genotype
	FloatingPointP flp (new FloatingPoint::FloatingPoint);
	if(state->getGenotypes()[0]->getName() != flp->getName()) {
		ECF_LOG_ERROR(state, "Error: PSO algorithm accepts only a single FloatingPoint genotype!");
		throw ("");
	}

	voidP sptr = state->getGenotypes()[0]->getParameterValue(state, "dimension");
	uint numDimension = *((uint*) sptr.get());

	voidP bounded = getParameterValue(state, "bounded");
	bounded_ = *((bool*) bounded.get());

	sptr = state->getGenotypes()[0]->getParameterValue(state, "lbound");
	lbound_ = *((double*) sptr.get());

	sptr = state->getGenotypes()[0]->getParameterValue(state, "ubound");
	ubound_ = *((double*) sptr.get());

	// batch run check
	if(areGenotypesAdded_)
		return true;

	FloatingPointP flpoint[4];
	for(uint iGen = 1; iGen < 4; iGen++) {

		flpoint[iGen] = (FloatingPointP) new FloatingPoint::FloatingPoint;
		state->setGenotype(flpoint[iGen]);

		if(iGen == 3)
			flpoint[iGen]->setParameterValue(state, "dimension", (voidP) new uint(1));
		else
			flpoint[iGen]->setParameterValue(state, "dimension", (voidP) new uint(numDimension));

		// other parameters are proprietary (ignored by the algorithm)
		flpoint[iGen]->setParameterValue(state, "lbound", (voidP) new double(0));
		flpoint[iGen]->setParameterValue(state, "ubound", (voidP) new double(1));
	}
	ECF_LOG(state, 1, "PSO algorithm: added 3 FloatingPoint genotypes (particle velocity, best-so-far postition, best-so-far fitness value)");

	// mark adding of genotypes
	areGenotypesAdded_ = true;

	return true;
}
Пример #20
0
bool RegEvalOp::initialize(StateP state) {

    state->getContext()->environment = this;
    
    voidP sptr = state->getRegistry()->getEntry("classesNum");
    classesNum = *((uint *) sptr.get());

    std::string outputPath = *((std::string*) state->getRegistry()->getEntry("resultsfile").get());
    
    std::ofstream outfile;
    outfile.open(outputPath.c_str());
   
    if (!outfile.is_open()) {
        ECF_LOG_ERROR(state, "Error: Can't open output file " + outputPath);
        return false;
    }
    
    outfile << "Gen_No,Training,Test" << std::endl;
    outfile.close();

    sptr = state->getRegistry()->getEntry("inputfile");
    std::string filePath = *((std::string *) sptr.get());

    ifstream file;
    file.open(filePath.c_str());

    if (!file.is_open()) {
        ECF_LOG_ERROR(state, "Error: Can't open input file " + filePath);
        return false;
    }

    parseFile(domain, codomain, file);
    file.close();


    sptr = state->getRegistry()->getEntry("testfile");
    filePath = *((std::string *) sptr.get());
    file.open(filePath.c_str());

    if (!file.is_open()) {
        ECF_LOG_ERROR(state, "Error: Can't open test file " + filePath);
        return false; 
    }

    parseFile(testDomain, testCodomain, file);
    file.close();
    
    sptr = state->getRegistry()->getEntry("classesfile");
    filePath = *((std::string *) sptr.get());

    file.open(filePath.c_str());

    if (!file.is_open()) {
        generateDefaultClasses();
    } else {
        generateParsedClasses(file);
    }

    file.close();

    for (auto& entry: classes) {
        f1Score.insert(std::make_pair(entry.first, std::vector<uint>(3, 0)));
    }
    
    return true;
}
Пример #21
0
void TermStagnationOp::registerParameters(StateP state)
{
	uint *value = new uint(50);
	state->getRegistry()->registerEntry("term.stagnation", (voidP) value, ECF::UINT,
		"max number of consecutive generations without improvement (default: 5000 / pop_size)");
}
Пример #22
0
/**
 * \brief Initialize all mutation operators of all active genotypes
 */
bool Mutation::initialize(StateP state)
{
	state_ = state;
	protectedGenotypes_.clear();
	protectedGenotypes_.insert(protectedGenotypes_.begin(), operators.size(), false);
	opProb.clear();

	voidP sptr = state->getRegistry()->getEntry("mutation.indprob");
	indMutProb_ = *((double*)sptr.get());

	sptr = state->getRegistry()->getEntry("mutation.geneprob");
//	geneMutProb_ = *((double*)sptr.get());
//	if(state->getRegistry()->isModified("mutation.geneprob") == false)
//		geneMutProb_ = 0;

	sptr = state->getRegistry()->getEntry("mutation.genotypes");
	std::string mutGen = *((std::string*)sptr.get());

	mutateGenotypes_ = RANDOM_GENOTYPE;
	if(mutGen == "random")
		mutateGenotypes_ = RANDOM_GENOTYPE;
	else if(mutGen == "all")
		mutateGenotypes_ = ALL_GENOTYPES;
	else
		ECF_LOG_ERROR(state, "Warning: invalid parameter value (key: mutation.genotypes)");

	// read protected genotypes
	std::stringstream ss;
	sptr = state->getRegistry()->getEntry("mutation.protected");
	ss << *((std::string*) sptr.get());
	uint genId;
	while(ss >> genId) {	// read all the data from string
		if(genId >= protectedGenotypes_.size()) {
			ECF_LOG_ERROR(state, "Error: invalid genotype index (key: mutation.protected)!");
			throw("");
		}
		protectedGenotypes_[genId] = true;
	}

	// initialize operators for all genotypes
	for(uint gen = 0; gen < operators.size(); gen++) {
		uint nOps = (uint) operators[gen].size();
		// if the genotype doesn't define mutation operators
		if(nOps == 0) {
			protectedGenotypes_[gen] = true;
			std::vector<double> empty;
			opProb.push_back(empty);
			break;
		}
		for(uint i = 0; i < nOps; i++) {
			operators[gen][i]->state_ = state;
			operators[gen][i]->initialize(state);
		}
		// calculate cumulative operator probabilities
		std::vector<double> probs(nOps);
		probs[0] = operators[gen][0]->probability_;
		for(uint i = 1; i < nOps; i++) {
			probs[i] = probs[i - 1] + operators[gen][i]->probability_;
		}
		if(probs[nOps - 1] == 0) {
			std::vector<double> none(1);
			none[0] = -1;
			opProb.push_back(none);
		} else {
			if(probs[nOps - 1] != 1) {
				double normal = probs[nOps - 1];
				ECF_LOG_ERROR(state, "Warning: " + operators[gen][0]->myGenotype_->getName() +
					" mutation operators: cumulative probability not equal to 1 (sum = " + dbl2str(normal) + ")");
				for(uint i = 0; i < probs.size(); i++)
					probs[i] /= normal;
			}
			opProb.push_back(probs);
		}
	}
	return true;
}
void CgdaPaintFitnessFunction::registerParameters(StateP state) {
	state->getRegistry()->registerEntry("function", (voidP) (new uint(1)), ECF::UINT);
}
Пример #24
0
void StatCalc::registerParameters(StateP state)
{
	state->getRegistry()->registerEntry("stats.file", (voidP) (new std::string("")), ECF::STRING);
}
bool CgdaPaintFitnessFunction::initialize(StateP state) {

    voidP sptr = state->getRegistry()->getEntry("function"); // get parameter value

	return true;
}
bool PSOInheritance::advanceGeneration(StateP state, DemeP deme)
{
//       a) For each particle:
//          1) If the fitness value is better than the best fitness value (pBest) in  history
//          2) Set current value as the new pBest
//          3) Put particle in the ranking array using the fitness value
//          End
//       b) For the p best particles in the ranking arrayºº
//          1) Find, in the particle neighborhood, the particle with the best fitness
//          2) Calculate particle velocity according to the velocity equation (1)
//          3) Apply the velocity constriction
//          4) Update particle position according to the position equation (2)
//          5) Apply the position constriction
//       c) Inherit // Evaluate
//          1) Get the fitness value via evaluation or inheritance.
//          End

	for( uint i = 0; i < deme->getSize(); i++ ) { // for each particle 
        IndividualP particle = deme->at(i);                                                                             //Read "i" particle

		// the whole point of this section is to compare fitness and pbest
        FloatingPointP flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (particle->getGenotype(3));
        double &particlePbestFitness = flp->realValue[0];
        double fitness = particle->fitness->getValue();

        //There is a problem with the particlePbestFitness initialization in this algorithm. The following lines take care of this.
        //TODO: Find a way to do this in the ¿initialize fuction?.
        if(state->getGenerationNo()==1){
            //std::cout<<"INCIALIZADOOOOOOOOOOOOO!!!!!!!!!!!!!!!!!"<<std::endl;
            particlePbestFitness=fitness;
        }
        else{
            //std::cout<<"FITNESS"<<fitness<<std::endl;

            flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (particle->getGenotype(0));
            std::vector< double > &positions = flp->realValue;

            flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (particle->getGenotype(2));
            std::vector< double > &pbestx = flp->realValue;

            // set particle pbestx-es
            if( /*iter == 0 ||*/ fitness < particlePbestFitness ) { // minimize error
                particlePbestFitness = fitness; //Update particle personal fitness

                // set pbestx-es
                for( uint j = 0;j<pbestx.size();j++ ) {
                    pbestx[j] = positions[j];
                }
            }
        }

		// NOTE store best particle index?
        //std::cout<<"THE PBEST OF THIS PARTICLE IS!!!!!!!!!!!!:"<<particlePbestFitness<<std::endl;
	}

	// b)
	for( uint i = 0; i < deme->getSize(); i++ ) { // for each particle
		IndividualP particle = deme->at(i);

		IndividualP bestParticle = selBestOp->select( *deme );

		FloatingPointP flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (particle->getGenotype(0));
		std::vector< double > &positions = flp->realValue;

		flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (particle->getGenotype(1));
		std::vector< double > &velocities = flp->realValue;

		flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (particle->getGenotype(2));
        std::vector< double > &pbestx = flp->realValue;

        double R1=rand()/(float)RAND_MAX, R2=rand()/(float)RAND_MAX, vf;
        int C1=2, C2=2;



        double weight_up;

		switch( m_weightType )
		{
			//time variant weight, linear from weight to 0.4
			case TIME_VARIANT:
			weight_up = ( m_weight - 0.4 ) * ( m_maxIter - state->getGenerationNo() ) / m_maxIter + 0.4;
			break;

			// constant inertia weight
			case CONSTANT:
            default:
			weight_up = m_weight;
			break;
		}
		// calculate particle velocity according to the velocity equation (1)
		flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (bestParticle->getGenotype(2));
		std::vector< double > &bestParticlesPbestx = flp->realValue;
		for( uint j = 0; j < velocities.size(); j++ ) {
			double velocity;

			velocity = weight_up * velocities[j] +
               2 * R1 * (pbestx[j] - positions[j]) +
               2 * R2 * (bestParticlesPbestx[j] - positions[j]);

			if( velocity > m_maxV ) velocity = m_maxV;
            if( velocity < -m_maxV) velocity = -m_maxV;
			velocities[j] = velocity;

            positions[j] += velocities[j];      //Updated positions with velocitites X(t+1)=X(t)+velocities(t);
			// TODO apply position constriction

			// check for bounds
            if(bounded_) {
				if(positions[j] < lbound_)
					positions[j] = lbound_;
				if(positions[j] > ubound_)
					positions[j] = ubound_;
			}

            //std::cout<<"LA VELOCIDAD ES::::"<<velocity<<std::endl;
		}

        int proportion=55;
        if(rand()%100>=proportion){
            //Initial PSO inheritance algorithm -> 100%inheritance no evaluations.
            //determine new particle fitness

            //Particle best personal fitness
//            flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (particle->getGenotype(3));
//            double &particlePbestFitness = flp->realValue[0];

            //Best particle fitness
//            flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (bestParticle->getGenotype(3));
//            double &bestparticlePbestFitness = flp->realValue[0];

//            vf=(C1*R1*(particlePbestFitness-particle->fitness->getValue())+C2*R2*(bestparticlePbestFitness-particle->fitness->getValue()))
//                    /(1+C1*R1+C2*R2);

//            vf=vf+particle->fitness->getValue();



            evaluate( particle );

            //std::cout<< " Inherited: " << vf<< " -> Evaluated "<< particle->fitness->getValue() <<std::endl ;

        }
        else{
            //Particle best personal fitness
            flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (particle->getGenotype(3));
            double &particlePbestFitness = flp->realValue[0];

            //Best particle fitness
            flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (bestParticle->getGenotype(3));
            double &bestparticlePbestFitness = flp->realValue[0];

            //std::cout<<std::endl<<"The EverPersonalBEST of this particle is:"<<particlePbestFitness<<std::endl;
            //std::cout<<std::endl<<"THE present LEADER(Allbes) of this particle fitness is:"<<bestparticlePbestFitness<<std::endl;

            //Inheritance based on flight formula
            std::cout<<"Particle Fitness"<<particle->fitness->getValue()<<" "<<std::endl;


            //Fitness inheritance
            vf=(C1*R1*(particlePbestFitness-particle->fitness->getValue())+C2*R2*(bestparticlePbestFitness-particle->fitness->getValue()))
                    /(1+C1*R1+C2*R2);
            particle->fitness->setValue(vf+particle->fitness->getValue());

            std::cout<< " Inherited: " << particle->fitness->getValue()<< " "<< std::endl ;
        }

	}

    //std::cout<<std::endl<<"THE NUMBER OF THIS GENERATION IS:"<<state->getGenerationNo() <<std::endl;
    std::cout<<std::endl<<"THE NUMBER OF EVALUATIONS ARE:"<<state->getEvaluations() <<std::endl;
    std::cout<<std::endl<<"THE TIME TAKEN TO DO THIS IS:"<<state->getElapsedTime() <<std::endl;

    //*******************FILE OUTPUT FOR DEBUGGING***********************************************//
    IndividualP bestParticle = selBestOp->select( *deme );

    FloatingPointP flp = boost::dynamic_pointer_cast<FloatingPoint::FloatingPoint> (bestParticle->getGenotype(3));

    double &bestparticlePbestFitness = flp->realValue[0];
    std::ofstream myfile1;
    myfile1.open("FitnessvsEvaluations.txt", std::ios_base::app);
    if (myfile1.is_open()){
        myfile1<<bestparticlePbestFitness<<" ";
        myfile1<<state->getEvaluations()<<std::endl;
    }
    //*******************************************************************************************//

	return true;
}
bool ModularRobotEvalOp::initialize(StateP state)
{
    //-- Get the robot values from the registry:
    //-----------------------------------------------------------------------------------------
    //-- Number of modules:
    voidP sptr = state->getRegistry()->getEntry("robot.modules");
    n_modules = *((uint*) sptr.get() );
    std::cout << "[Evolve] Info: Loaded \"robot.modules\"="<< n_modules << std::endl;

    //-- Max runtime:
    sptr = state->getRegistry()->getEntry("robot.runtime");
    max_runtime =(unsigned long) *((uint*) sptr.get() );
    std::cout << "[Evolve] Info: Loaded \"robot.runtime\"="<< max_runtime << std::endl;

    //-- Time step:
    sptr = state->getRegistry()->getEntry("robot.timestep");
    timestep = *((float*) sptr.get() );
    std::cout << "[Evolve] Info: Loaded \"robot.timestep\"="<< timestep << std::endl;

    //-- Gait table file:
    sptr = state->getRegistry()->getEntry("robot.configfile");
    config_file = *((std::string*) sptr.get() );
    std::cout << "[Evolve] Info: Loaded \"robot.configfile\"="<< config_file << std::endl;

    //-- Get the oscillator parameters from the registry:
    //---------------------------------------------------------------------------------------
    //-- Max amplitude:
    sptr = state->getRegistry()->getEntry("osc.maxamplitude");
    int max_amplitude = *((uint*) sptr.get());
    max_amp_0_5 = max_amplitude / 2.0;
    std::cout << "[Evolve] Info: Loaded \"osc.maxamplitude\"="<< max_amplitude << std::endl;

    //-- Max offset:
    sptr = state->getRegistry()->getEntry("osc.maxoffset");
    max_offset = *((uint*) sptr.get());
    std::cout << "[Evolve] Info: Loaded \"osc.maxoffset\"="<< max_offset << std::endl;

    //-- Max phase:
    sptr = state->getRegistry()->getEntry("osc.maxphase");
    int max_phase = *((uint*) sptr.get());
    max_pha_0_5 = max_phase / 2.0;
    std::cout << "[Evolve] Info: Loaded \"osc.maxphase\"="<< max_phase << std::endl;

    //-- Max frequency:
    sptr = state->getRegistry()->getEntry("osc.maxfrequency");
    float max_frequency = *((float*) sptr.get());
    max_freq_0_5 = max_frequency / 2.0;
    std::cout << "[Evolve] Info: Loaded \"osc.maxfrequency\"="<< max_frequency << std::endl;

    //-- Create and configure the robot parts
    //---------------------------------------------------------------------------------------
    //-- Read test data
    if ( configParser.parse(config_file) != 0)
    {
        std::cerr << "[Evolve] Error: error parsing xml config file!" << std::endl;
        return false;
    }

    if ( configParser.getNumModules() != n_modules )
    {
        std::cerr << "[Evolve] Error: number of modules not consitent between config file and "
                  << "robot model." << std::endl;
        return false;
    }
    //-- Create robot, simulated type
    robotInterface = createModularRobotInterface( "simulated", configParser);

    //-- Create sinusoidal oscillators with the test parameters
    oscillators.clear();
    for ( int i = 0; i < configParser.getNumModules(); i++)
        oscillators.push_back(new SinusoidalOscillator( 0, 0, 0, 4000));

    robotInterface->reset();

    return true;
}
int main(int argc, char **argv)
{
	// run for selected COCO functions
	for(uint function = 1; function < 25; function++) {

		// read XML config
		std::ifstream fin(argv[1]);
		if (!fin) {
			throw std::string("Error opening file! ");
		}

		std::string xmlFile, temp;
		while (!fin.eof()) {
			getline(fin, temp);
			xmlFile += "\n" + temp;
		}
		fin.close();

		// set log and stats parameters
		std::string funcName = uint2str(function);
		std::string logName = "log", statsName = "stats";
		if(function < 10) {
			logName += "0";
			statsName += "0";
		}
		logName += uint2str(function) + ".txt";
		statsName += uint2str(function) + ".txt";

		// update in XML
		XMLResults results;
		XMLNode xConfig = XMLNode::parseString(xmlFile.c_str(), "ECF", &results);
		XMLNode registry = xConfig.getChildNode("Registry");

		XMLNode func = registry.getChildNodeWithAttribute("Entry", "key", "coco.function");
		func.updateText(funcName.c_str());
		XMLNode log = registry.getChildNodeWithAttribute("Entry", "key", "log.filename");
		log.updateText(logName.c_str());
		XMLNode stats = registry.getChildNodeWithAttribute("Entry", "key", "batch.statsfile");
		stats.updateText(statsName.c_str());

		// write back
		std::ofstream fout(argv[1]);
		fout << xConfig.createXMLString(true);
		fout.close();


		// finally, run ECF on single function
		StateP state (new State);

		//set newAlg
		MyAlgP alg = (MyAlgP) new MyAlg;
		state->addAlgorithm(alg);
		// set the evaluation operator
		state->setEvalOp(new FunctionMinEvalOp);

		state->initialize(argc, argv);
		state->run();
	}

	return 0;
}