/*
 * MultimodalAlgorithm.cpp
 *
 *  Created on: Jul 29, 2015
 *      Author: jjpalacios
 */

#include "MultimodalAlgorithm.h"

namespace clbDEB {

//=============================================================================
//
//	Abstract class MultimodalAlgorithm
//
//=============================================================================
//=============================================================================
//		CONSTRUCTORS / INITIALIZERS
//=============================================================================
//-----  Main constructor  ----------------------------------------------------
MultimodalAlgorithm::MultimodalAlgorithm(const char * setupFile) {
	this->sharedVariables = new SharedVars();
	this->sharedVariables->parameters = new ParameterDB(setupFile);
	this->sharedVariables->rng = new Random();
	finished = false;
	evaluator = NULL;
	ready = false;
}


//-----  ClearAll  ------------------------------------------------------------
void MultimodalAlgorithm::clearAll() {
	delete this->evaluator;
}



//=========================================================================
//		METHODS
//=========================================================================
//-----  prepareToRun  ----------------------------------------------------
void MultimodalAlgorithm::prepareToRun() {
	std::string paramName;

	if(this->ready)
		clearAll();

	// Checks if the algorithm needs to maximize/minimize
	paramName = MMA_FITNESS_MAX;
	this->sharedVariables->maximize = this->sharedVariables->parameters->
			getBoolean(paramName, false);

	// Reads the number of parameters to tune
	paramName = MMA_INDIVIDUAL_LENGTH;
	int nParams;
	nParams = this->sharedVariables->parameters
			->getInteger(paramName, -1);
	if(nParams < 0) {
		std::string err = "Invalid number of parameters to tune. ";
		err += "Incorrect value or missing parameter";
		throw ClbException(err);
	}
	this->sharedVariables->numElements = nParams;

	// Load the bounds for each parameter
	double min, max;
	this->sharedVariables->minGene.clear();
	this->sharedVariables->maxGene.clear();
	for(int i=0; i < nParams; i++) {
		paramName = MMA_BOUNDS_MIN + valueToString(i);
		min = this->sharedVariables->parameters->getDouble(paramName, -Infd);
		paramName = MMA_BOUNDS_MAX + valueToString(i);
		max = this->sharedVariables->parameters->getDouble(paramName, Infd);
		this->sharedVariables->minGene.push_back(min);
		this->sharedVariables->maxGene.push_back(max);
	}

	// Loads the evaluation function to use
	paramName = EVAL_FUNCTION;
	std::string evalName = this->sharedVariables->parameters
			->getString(paramName);

	this->evaluator = ClassRegister::getEvaluatorObject(evalName);

	if(this->evaluator == NULL) {
		std::string err = "Invalid evaluation function. Incorrect name ";
		err += "or missing parameter";
		throw ClbException(err);
	}
	this->evaluator->setup(this->sharedVariables->parameters);

	this->ready = true;
	this->finished = false;
}

}



