Esempio n. 1
0
bool PhyloMOCHC::exist(Solution & s1, SolutionSet & set2) {
	for (int i = 0; i < set2.size(); i++) {
		if (equalsIndividuals(s1,*set2.get(i)))
			return true;
	}
	return false;
}
/**
* Performs the operation
* @param object Object representing a SolutionSet
* @return the selected solution
*/
void * BinaryTournament2::execute(void * object) {

  SolutionSet * population = (SolutionSet *)object;

  if (index_ == 0) //Create the permutation
  {
    PermutationUtility * permutationUtility = new PermutationUtility();
    delete [] a_;
    a_= permutationUtility->intPermutation(population->size());
    delete permutationUtility;
  }

  Solution * solution1;
  Solution * solution2;
  solution1 = population->get(a_[index_]);
  solution2 = population->get(a_[index_+1]);

  index_ = (index_ + 2) % population->size();

  int flag = dominance_->compare(solution1,solution2);
  if (flag == -1)
    return solution1;
  else if (flag == 1)
    return solution2;
  else if (solution1->getCrowdingDistance() > solution2->getCrowdingDistance())
    return solution1;
  else if (solution2->getCrowdingDistance() > solution1->getCrowdingDistance())
    return solution2;
  else
    if (PseudoRandom::randDouble()<0.5)
      return solution1;
    else
      return solution2;

} // execute 
Esempio n. 3
0
bool PhyloMOCHC::equals(SolutionSet & set1, SolutionSet & set2) {

	if (set1.size() != set2.size())
		return false;

	for (int i = 0; i < set1.size(); i++) {
		if (!exist(*set1.get(i),set2))
			return false;
	}
	return true;
} // returns the equal
Esempio n. 4
0
SolutionSet *MOCHC::rankingAndCrowdingSelection(SolutionSet * pop, int size) {


    SolutionSet *result = new SolutionSet(size);
    // Ranking the union
    Ranking * ranking = new Ranking(pop);    
    Distance * distance = new Distance();
    int remain = size;
    int index = 0;
    SolutionSet * front = NULL;

    // Obtain the next front
    front = ranking->getSubfront(index);

    while ((remain > 0) && (remain >= front->size())) {
      //Assign crowding distance to individuals
      distance->crowdingDistanceAssignment(front, problem_->getNumberOfObjectives());

      //Add the individuals of this front
      for (int k = 0; k < front->size(); k++) {
        result->add(new Solution(front->get(k)));
      } // for

      //Decrement remain
      remain = remain - front->size();

      //Obtain the next front
      index++;
      if (remain > 0) {
        front = ranking->getSubfront(index);
      } // if
      
    } // while

    // Remain is less than front(index).size, insert only the best one
    if (remain > 0) {  // front contains individuals to insert
      distance->crowdingDistanceAssignment(front, problem_->getNumberOfObjectives());
      Comparator * c = new CrowdingComparator();
      front->sort(c);
      delete c;
      for (int k = 0; k < remain; k++) {
        result->add(new Solution(front->get(k)));
      } // for

      remain = 0;
    } // if

    delete ranking;
    delete distance;

    return result;	
}
int main(int argc, char ** argv) {

  clock_t t_ini, t_fin;

  Problem   * problem   ; // The problem to solve
  Algorithm * algorithm ; // The algorithm to use
  //Operator  * mutation  ; // "Turbulence" operator

  if (argc>=2) {
    problem = ProblemFactory::getProblem(argc, argv);
    cout << "Selected problem: " << problem->getName() << endl;
  } else {
    cout << "No problem selected." << endl;
    cout << "Default problem will be used: Sphere" << endl;
    problem = ProblemFactory::getProblem(const_cast<char *>("Sphere"));
  }

  algorithm = new StandardPSO2007(problem);

  // Algorithm parameters
  int swarmSize = 10 + (int) (2 * sqrt(problem->getNumberOfVariables()));
  int maxIterations = 80000;
  int numberOfParticlesToInform = 3;
  algorithm->setInputParameter("swarmSize",&swarmSize);
  algorithm->setInputParameter("maxIterations",&maxIterations);
  algorithm->setInputParameter("numberOfParticlesToInform", &numberOfParticlesToInform);

  // Execute the Algorithm
  t_ini = clock();
  SolutionSet * population = algorithm->execute();
  t_fin = clock();
  double secs = (double) (t_fin - t_ini);
  secs = secs / CLOCKS_PER_SEC;

  // Result messages
  cout << "Total execution time: " << secs << "s" << endl;
  cout << "Variables values have been written to file VAR" << endl;
  population->printVariablesToFile("VAR");
  cout << "Objectives values have been written to file FUN" << endl;
  population->printObjectivesToFile("FUN");

  delete population;
  delete algorithm;

} // main
/**
 * Executes the operation
 * @param object An object containing the population and the position (index)
 *               of the current individual
 * @return An object containing the three selected parents
 */
void * DifferentialEvolutionSelection::execute(void * object) {

  void ** parameters = (void **)object ;
  SolutionSet * population = (SolutionSet *) parameters[0];
  int index = *(int *) parameters[1] ;

  Solution ** parents = new Solution*[3];
  int r1, r2, r3;

  if (population->size() < 4) {
    cerr << "DifferentialEvolutionSelection: the population has less than four solutions" << endl;
    exit(-1);
  }

  do {
    r1 = PseudoRandom::randInt(0,population->size()-1);
  } while ( r1==index );
  do {
    r2 = PseudoRandom::randInt(0,population->size()-1);
  } while ( r2==index || r2==r1 );
  do {
    r3 = PseudoRandom::randInt(0,population->size()-1);
  } while( r3==index || r3==r1 || r3==r2 );

  parents[0] = population->get(r1);
  parents[1] = population->get(r2);
  parents[2] = population->get(r3);

  return parents ;

} // execute
Esempio n. 7
0
bool MOCHC::equals(SolutionSet & set1, SolutionSet & set2) {
	for (int i = 0; i < set1.size(); i++) {
		for (int j = 0; j < set2.size(); j++) {
			Solution *s1 = set1.get(i);
			Solution *s2 = set2.get(j);
			for (int var = 0; var < s1->getNumberOfVariables(); var++) {
				Binary *b1, *b2;
				b1 = (Binary *)s1->getDecisionVariables()[var];
				b2 = (Binary *)s2->getDecisionVariables()[var];
				for (int bit = 0; bit < b1->getNumberOfBits(); bit++) {
					if (b1->getIth(bit)!=b2->getIth(bit)) {
						return false;
					}
				}
			}
		}
	}
	return true;
} // returns the equal
/**
* Performs the operation
* @param object Object representing a SolutionSet
* @return the worst solution found
*/
void * WorstSolutionSelection::execute(void * object) {

  SolutionSet * solutionSet = (SolutionSet *)object;

  if (solutionSet->size() == 0) {
    return NULL;
  }

  int worstSolution = 0;

  for (int i = 1; i < solutionSet->size(); i++) {
    if (comparator_->compare(solutionSet->get(i), solutionSet->get(worstSolution)) > 0) {
      worstSolution = i;
    }
  } // for

  int * intPtr = new int(worstSolution);
  return intPtr;

} // execute
Esempio n. 9
0
int main(int argc, char ** argv) {

  clock_t t_ini, t_fin;

  Problem   * problem;   // The problem to solve
  Algorithm * algorithm; // The algorithm to use
  Operator  * crossover; // Crossover operator
  Operator  * mutation;  // Mutation operator
  
  //QualityIndicator * indicators ; // Object to get quality indicators

  map<string, void *> parameters; // Operator parameters

  //TODO: QualityIndicator * indicators; // Object to get quality indicators

  if (argc>=2) {
    problem = ProblemFactory::getProblem(argc, argv);
    cout << "Selected problem: " << problem->getName() << endl;
  } else {
    cout << "No problem selected." << endl;
    cout << "Default problem will be used: Kursawe" << endl;
    problem = ProblemFactory::getProblem(const_cast<char *>("Kursawe"));
  }

  algorithm = new MOEAD(problem);

  // Algorithm parameters
  int populationSizeValue = 300;
  int maxEvaluationsValue = 150000;
  algorithm->setInputParameter("populationSize",&populationSizeValue);
  algorithm->setInputParameter("maxEvaluations",&maxEvaluationsValue);
  
  // Directory with the files containing the weight vectors used in 
  // Q. Zhang,  W. Liu,  and H Li, The Performance of a New Version of MOEA/D 
  // on CEC09 Unconstrained MOP Test Instances Working Report CES-491, School 
  // of CS & EE, University of Essex, 02/2009.
  // http://dces.essex.ac.uk/staff/qzhang/MOEAcompetition/CEC09final/code/ZhangMOEADcode/moead0305.rar
  string dataDirectoryValue =
          "../../data/Weight";
  algorithm->setInputParameter("dataDirectory", &dataDirectoryValue);

  // Crossover operator
  double crParameter = 1.0;
  double fParameter = 0.5;
  parameters["CR"] = &crParameter;
  parameters["F"] = &fParameter;
  crossover = new DifferentialEvolutionCrossover(parameters);
  
  // Mutation operator
  parameters.clear();
  double probabilityParameter = 1.0/(problem->getNumberOfVariables());
  double distributionIndexParameter = 20.0;
  parameters["probability"] =  &probabilityParameter;
  parameters["distributionIndex"] = &distributionIndexParameter;
  mutation = new PolynomialMutation(parameters);

  // Add the operators to the algorithm
  algorithm->addOperator("crossover",crossover);
  algorithm->addOperator("mutation",mutation);

  // Add the indicator object to the algorithm
  //algorithm->setInputParameter("indicators", indicators) ;

  // Execute the Algorithm
  t_ini = clock();
  SolutionSet * population = algorithm->execute();
  t_fin = clock();
  double secs = (double) (t_fin - t_ini);
  secs = secs / CLOCKS_PER_SEC;

  // Result messages
  cout << "Total execution time: " << secs << "s" << endl;
  cout << "Variables values have been written to file VAR" << endl;
  population->printVariablesToFile("VAR");
  cout << "Objectives values have been written to file FUN" << endl;
  population->printObjectivesToFile("FUN");

  delete mutation;
  delete crossover;
  delete population;
  delete algorithm;

} // main
Esempio n. 10
0
/**
 * Assigns crowding distances to all solutions in a <code>SolutionSet</code>.
 * @param solutionSet The <code>SolutionSet</code>.
 * @param nObjs Number of objectives.
 */
void Distance::crowdingDistanceAssignment(SolutionSet * solutionSet, int nObjs) {
  int size = solutionSet->size();

  if (size == 0)
    return;

  if (size == 1) {
    solutionSet->get(0)->setCrowdingDistance(std::numeric_limits<double>::max());
    return;
  } // if

  if (size == 2) {
    solutionSet->get(0)->setCrowdingDistance(std::numeric_limits<double>::max());
    solutionSet->get(1)->setCrowdingDistance(std::numeric_limits<double>::max());
    return;
  } // if

  //Use a new SolutionSet to evite alter original solutionSet
  SolutionSet * front = new SolutionSet(size);
  for (int i = 0; i < size; i++){
    front->add(solutionSet->get(i));
  }

  for (int i = 0; i < size; i++)
    front->get(i)->setCrowdingDistance(0.0);

  double objetiveMaxn;
  double objetiveMinn;
  double distance;

  for (int i = 0; i<nObjs; i++) {
    // Sort the population by Obj n
    Comparator * c = new ObjectiveComparator(i);
    front->sort(c);
    delete c;
    objetiveMinn = front->get(0)->getObjective(i);
    objetiveMaxn = front->get(front->size()-1)->getObjective(i);

    //Set de crowding distance
    front->get(0)->setCrowdingDistance(std::numeric_limits<double>::max());
    front->get(size-1)->setCrowdingDistance(std::numeric_limits<double>::max());

    for (int j = 1; j < size-1; j++) {
      distance = front->get(j+1)->getObjective(i) - front->get(j-1)->getObjective(i);
      distance = distance / (objetiveMaxn - objetiveMinn);
      distance += front->get(j)->getCrowdingDistance();
      front->get(j)->setCrowdingDistance(distance);
    } // for
  } // for

  front->clear();
  delete front;

} // crowdingDistanceAssignment
Esempio n. 11
0
SolutionSet *MOCHC::execute() {
	
  int populationSize;
  int iterations;
  int maxEvaluations;
  int convergenceValue;
  int minimumDistance;
  int evaluations;

  double preservedPopulation;
  double initialConvergenceCount;
  bool condition = false;
  SolutionSet *solutionSet, *offSpringPopulation, *newPopulation; 

  Comparator * crowdingComparator = new CrowdingComparator();

  SolutionSet * population;
  SolutionSet * offspringPopulation;
  SolutionSet * unionSolution;

  Operator * cataclysmicMutation;
  Operator * crossover;
  Operator * parentSelection;


  //Read the parameters
  populationSize = *(int *) getInputParameter("populationSize");
  maxEvaluations = *(int *) getInputParameter("maxEvaluations");
  convergenceValue = *(int *) getInputParameter("convergenceValue");
  initialConvergenceCount = *(double *)getInputParameter("initialConvergenceCount");
  preservedPopulation = *(double *)getInputParameter("preservedPopulation");
  

  //Read the operators
  cataclysmicMutation = operators_["mutation"];
  crossover	      = operators_["crossover"];
  parentSelection     = operators_["parentSelection"];
  
  iterations  = 0;
  evaluations = 0;

  // calculating the maximum problem sizes .... 
  Solution * sol = new Solution(problem_);
  int size = 0;
  for (int var = 0; var < problem_->getNumberOfVariables(); var++) {
	Binary *binaryVar;
        binaryVar  = (Binary *)sol->getDecisionVariables()[var];
	size += binaryVar->getNumberOfBits();
  } 
  minimumDistance = (int) std::floor(initialConvergenceCount*size);

  // Create the initial solutionSet
  Solution * newSolution;
  population = new SolutionSet(populationSize);
  for (int i = 0; i < populationSize; i++) {
    newSolution = new Solution(problem_);
    problem_->evaluate(newSolution);
    problem_->evaluateConstraints(newSolution);
    evaluations++;
    population->add(newSolution);
  } //for


  while (!condition) {
	offSpringPopulation = new SolutionSet(populationSize);
 	Solution **parents = new Solution*[2];
	
	for (int i = 0; i < population->size()/2; i++) {
  		parents[0] = (Solution *) (parentSelection->execute(population));
		parents[1] = (Solution *) (parentSelection->execute(population));

		if (hammingDistance(*parents[0],*parents[1])>= minimumDistance) {
		   Solution ** offSpring = (Solution **) (crossover->execute(parents));
		   problem_->evaluate(offSpring[0]);
		   problem_->evaluateConstraints(offSpring[0]);
	           problem_->evaluate(offSpring[1]);
		   problem_->evaluateConstraints(offSpring[1]);
		   evaluations+=2;
		   offSpringPopulation->add(offSpring[0]);
		   offSpringPopulation->add(offSpring[1]);
		}		
	}  
	SolutionSet *join = population->join(offSpringPopulation);
 	delete offSpringPopulation;

	newPopulation = rankingAndCrowdingSelection(join,populationSize);
	delete join;
        if (equals(*population,*newPopulation)) {
		minimumDistance--;
	}   

	if (minimumDistance <= -convergenceValue) {
		minimumDistance = (int) (1.0/size * (1-1.0/size) * size);
		int preserve = (int) std::floor(preservedPopulation*populationSize);
		newPopulation->clear(); //do the new in c++ really hurts me(juanjo)
		population->sort(crowdingComparator);
		for (int i = 0; i < preserve; i++) {
			newPopulation->add(new Solution(population->get(i)));
		}
		for (int i = preserve; i < populationSize; i++) {
			Solution * solution = new Solution(population->get(i));
			cataclysmicMutation->execute(solution);
			problem_->evaluate(solution);
			problem_->evaluateConstraints(solution);	
			newPopulation->add(solution);
		}
		
	}

	iterations++;
	delete population;
	population = newPopulation;
	if (evaluations >= maxEvaluations) {
		condition = true;		
	}
  }

  return population;

}
Esempio n. 12
0
SolutionSet *PhyloMOCHC::execute() {
	
  int populationSize;
  int iterations;
  int maxEvaluations;
  int convergenceValue;
  int minimumDistance;
  int evaluations;
  int IntervalOptSubsModel;
   

  double preservedPopulation;
  double initialConvergenceCount;
  bool condition = false;
  SolutionSet *solutionSet, *offSpringPopulation, *newPopulation; 

  Comparator * crowdingComparator = new CrowdingComparator();

  SolutionSet * population;
  SolutionSet * offspringPopulation;
  SolutionSet * unionSolution;

  Operator * cataclysmicMutation;
  Operator * crossover;
  Operator * parentSelection;


  //Read the parameters
  populationSize = *(int *) getInputParameter("populationSize");
  maxEvaluations = *(int *) getInputParameter("maxEvaluations");
  IntervalOptSubsModel = *(int *) getInputParameter("intervalupdateparameters");
   
  convergenceValue = *(int *) getInputParameter("convergenceValue");
  initialConvergenceCount = *(double *)getInputParameter("initialConvergenceCount");
  preservedPopulation = *(double *)getInputParameter("preservedPopulation");
  
  //Read the operators
  cataclysmicMutation = operators_["mutation"];
  crossover	      = operators_["crossover"];
  parentSelection     = operators_["selection"];
  
  iterations  = 0;
  evaluations = 0;

   // calculating the maximum problem sizes .... 
   int size = 0;

    Solution * sol = new Solution(problem_);
    PhyloTree *Pt1 = (PhyloTree *)sol->getDecisionVariables()[0];
    TreeTemplate<Node> * tree1 = Pt1->getTree();
    BipartitionList* bipL1 = new BipartitionList(*tree1, true);
    bipL1->removeTrivialBipartitions();
    
    size = bipL1->getNumberOfBipartitions() * 2;
    

    delete bipL1;
    delete sol;
  
  minimumDistance = (int) std::floor(initialConvergenceCount*size);

  cout << "Minimun Distance " << minimumDistance << endl;
  
  // Create the initial solutionSet
  Solution * newSolution;
  
  ApplicationTools::displayTask("Initial Population", true);
   
  population = new SolutionSet(populationSize);
  Phylogeny * p = (Phylogeny *) problem_;
  
  for (int i = 0; i < populationSize; i++) {
    
      newSolution = new Solution(problem_);
     
      if(p->StartingOptRamas){
        p->BranchLengthOptimization(newSolution,p->StartingMetodoOptRamas,p->StartingNumIterOptRamas,p->StartingTolerenciaOptRamas);
      }
    
      if(p->OptimizacionSubstModel){
          p->OptimizarParamModeloSust(newSolution);
      }

    problem_->evaluate(newSolution);
    problem_->evaluateConstraints(newSolution);
    
    evaluations++;
    population->add(newSolution);
  } //for

  ApplicationTools::displayTaskDone();

  
  while (!condition) {
      
        cout << "Evaluating  " <<  evaluations << endl;
       
	offSpringPopulation = new SolutionSet(populationSize);
 	Solution **parents = new Solution*[2];
	
	for (int i = 0; i < population->size()/2; i++) {
               
  		parents[0] = (Solution *) (parentSelection->execute(population));
		parents[1] = (Solution *) (parentSelection->execute(population));

		if (RFDistance(parents[0],parents[1])>= minimumDistance) {
                    
		   Solution ** offSpring = (Solution **) (crossover->execute(parents));
                   
                   ((Phylogeny *)problem_)->Optimization(offSpring[0]); //Optimize and update the scores (Evaluate OffSpring)
                   ((Phylogeny *)problem_)->Optimization(offSpring[1]);
        
		   /*problem_->evaluate(offSpring[0]);
		   problem_->evaluateConstraints(offSpring[0]);
	           problem_->evaluate(offSpring[1]);
		   problem_->evaluateConstraints(offSpring[1]);*/
                   
		   evaluations+=2;
                   
		   offSpringPopulation->add(offSpring[0]);
		   offSpringPopulation->add(offSpring[1]);
                   delete[] offSpring;
		}		
	}  
        
	SolutionSet *join = population->join(offSpringPopulation);
 	delete offSpringPopulation;

	newPopulation = rankingAndCrowdingSelection(join,populationSize);
	delete join;
        if (equals(*population,*newPopulation)) {
		minimumDistance--;
	}   

	if (minimumDistance <= -convergenceValue) {
		minimumDistance = (int) (1.0/size * (1-1.0/size) * size);
		int preserve = (int) std::floor(preservedPopulation*populationSize);
		newPopulation->clear(); 
		population->sort(crowdingComparator);
		for (int i = 0; i < preserve; i++) {
			newPopulation->add(new Solution(population->get(i)));
		}
		for (int i = preserve; i < populationSize; i++) {
			Solution * solution = new Solution(population->get(i));
			cataclysmicMutation->execute(solution);
			problem_->evaluate(solution);
			problem_->evaluateConstraints(solution);	
			newPopulation->add(solution);
		}
		
	}

        //Update Interval
     if(evaluations%IntervalOptSubsModel==0 and IntervalOptSubsModel > 0){ 
        Solution * sol;  double Lk;
        Phylogeny * p = (Phylogeny*) problem_;
        cout << "Updating and Optimizing Parameters.." << endl;
        for(int i=0; i<newPopulation->size(); i++){
            sol =  newPopulation->get(i);
            Lk=  p->BranchLengthOptimization(sol,p->OptimizationMetodoOptRamas,p->OptimizationNumIterOptRamas,p->OptimizationTolerenciaOptRamas);
            sol->setObjective(1,Lk*-1);
        }
        cout << "Update Interval Done!!" << endl;
      }
        
	iterations++;
	delete population;
	population = newPopulation;
	if (evaluations >= maxEvaluations) {
		condition = true;		
	}
  }

  return population;

}
/*
 * Runs the ssNSGA-II algorithm.
 * @return a <code>SolutionSet</code> that is a set of non dominated solutions
 * as a result of the algorithm execution
 */
SolutionSet * ssNSGAII::execute() {

  int populationSize;
  int maxEvaluations;
  int evaluations;
  
  int IntervalOptSubsModel;

  // TODO: QualityIndicator indicators; // QualityIndicator object
  int requiredEvaluations; // Use in the example of use of the
                           // indicators object (see below)

  SolutionSet * population;
  SolutionSet * offspringPopulation;
  SolutionSet * unionSolution;

  Operator * mutationOperator;
  Operator * crossoverOperator;
  Operator * selectionOperator;

  Distance * distance = new Distance();

  //Read the parameters
  populationSize = *(int *) getInputParameter("populationSize");
  maxEvaluations = *(int *) getInputParameter("maxEvaluations");
  IntervalOptSubsModel = *(int *) getInputParameter("intervalupdateparameters");
  // TODO: indicators = (QualityIndicator) getInputParameter("indicators");

  //Initialize the variables
  population = new SolutionSet(populationSize);
  evaluations = 0;

  requiredEvaluations = 0;

  //Read the operators
  mutationOperator = operators_["mutation"];
  crossoverOperator = operators_["crossover"];
  selectionOperator = operators_["selection"];
  
  ApplicationTools::displayTask("Initial Population", true);
  
  // Create the initial solutionSet
  Solution * newSolution;
  Phylogeny * p = (Phylogeny *) problem_;
  
  
  for (int i = 0; i < populationSize; i++) {
    newSolution = new Solution(problem_);
    
    if(p->StartingOptRamas){
        p->BranchLengthOptimization(newSolution,p->StartingMetodoOptRamas,p->StartingNumIterOptRamas,p->StartingTolerenciaOptRamas);
    }
    
    if(p->OptimizacionSubstModel)
        p->OptimizarParamModeloSust(newSolution);
       
    
    problem_->evaluate(newSolution);
    problem_->evaluateConstraints(newSolution);
    evaluations++;
    population->add(newSolution);
  } //for
   ApplicationTools::displayTaskDone();
   
   
  // Generations
  while (evaluations < maxEvaluations) {
    
    // Create the offSpring solutionSet
    offspringPopulation = new SolutionSet(populationSize);
    Solution ** parents = new Solution*[2];
    
     if(evaluations%100==0){ 
         cout << "Evaluating  " <<  evaluations << endl;
     }
     
     
    //obtain parents
    parents[0] = (Solution *) (selectionOperator->execute(population));
    parents[1] = (Solution *) (selectionOperator->execute(population));
    
    // crossover
    Solution ** offSpring = (Solution **) (crossoverOperator->execute(parents));
    
    // mutation
    mutationOperator->execute(offSpring[0]);
    
    ((Phylogeny *)problem_)->Optimization(offSpring[0]); //Optimize and update the scores (Evaluate OffSpring)
    
    // evaluation
    //problem_->evaluate(offSpring[0]);
    //problem_->evaluateConstraints(offSpring[0]);
    
    // insert child into the offspring population
    offspringPopulation->add(offSpring[0]);
    
    evaluations ++;
    delete[] offSpring;
    delete[] parents;
    
    // Create the solutionSet union of solutionSet and offSpring
    unionSolution = population->join(offspringPopulation);
    delete offspringPopulation;

    // Ranking the union
    Ranking * ranking = new Ranking(unionSolution);

    int remain = populationSize;
    int index = 0;
    SolutionSet * front = NULL;
    for (int i=0;i<population->size();i++) {
      delete population->get(i);
    }
    population->clear();

    // Obtain the next front
    front = ranking->getSubfront(index);

    while ((remain > 0) && (remain >= front->size())) {
      //Assign crowding distance to individuals
      distance->crowdingDistanceAssignment(front, problem_->getNumberOfObjectives());
      //Add the individuals of this front
      for (int k = 0; k < front->size(); k++) {
        population->add(new Solution(front->get(k)));
      } // for
      
      //Decrement remain
      remain = remain - front->size();
      
      //Obtain the next front
      index++;
      if (remain > 0) {
        front = ranking->getSubfront(index);
      } // if
    } // while

    // Remain is less than front(index).size, insert only the best one
    if (remain > 0) {  // front contains individuals to insert
      distance->crowdingDistanceAssignment(front, problem_->getNumberOfObjectives());
      Comparator * c = new CrowdingComparator();
      front->sort(c);
      delete c;
      for (int k = 0; k < remain; k++) {
        population->add(new Solution(front->get(k)));
      } // for

      remain = 0;
    } // if

    delete ranking;
    delete unionSolution;

       //Update Interval
    if(evaluations%IntervalOptSubsModel==0 and IntervalOptSubsModel > 0){ 
        Solution * sol;  double Lk;
        Phylogeny * p = (Phylogeny*) problem_;
        //cout << "Updating and Optimizing Parameters.." << endl;
        for(int i=0; i<population->size(); i++){
            sol =  population->get(i);
            Lk=  p->BranchLengthOptimization(sol,p->OptimizationMetodoOptRamas,p->OptimizationNumIterOptRamas,p->OptimizationTolerenciaOptRamas);
            sol->setObjective(1,Lk*-1);
        }
        //cout << "Update Interval Done!!" << endl;
    }
    
    // This piece of code shows how to use the indicator object into the code
    // of NSGA-II. In particular, it finds the number of evaluations required
    // by the algorithm to obtain a Pareto front with a hypervolume higher
    // than the hypervolume of the true Pareto front.
// TODO:
//    if ((indicators != NULL) &&
//      (requiredEvaluations == 0)) {
//      double HV = indicators.getHypervolume(population);
//      if (HV >= (0.98 * indicators.getTrueParetoFrontHypervolume())) {
//        requiredEvaluations = evaluations;
//      } // if
//    } // if

  } // while

  delete distance;

  // Return as output parameter the required evaluations
  // TODO:
  //setOutputParameter("evaluations", requiredEvaluations);

  // Return the first non-dominated front
  Ranking * ranking = new Ranking(population);
  SolutionSet * result = new SolutionSet(ranking->getSubfront(0)->size());
  for (int i=0;i<ranking->getSubfront(0)->size();i++) {
    result->add(new Solution(ranking->getSubfront(0)->get(i)));
  }
  delete ranking;
  delete population;

  return result;

} // execute
Esempio n. 14
0
/*
 * Runs the ssNSGA-II algorithm.
 * @return a <code>SolutionSet</code> that is a set of non dominated solutions
 * as a result of the algorithm execution
 */
SolutionSet * ssNSGAII::execute() {

  int populationSize;
  int maxEvaluations;
  int evaluations;

  // TODO: QualityIndicator indicators; // QualityIndicator object
  int requiredEvaluations; // Use in the example of use of the
                           // indicators object (see below)

  SolutionSet * population;
  SolutionSet * offspringPopulation;
  SolutionSet * unionSolution;

  Operator * mutationOperator;
  Operator * crossoverOperator;
  Operator * selectionOperator;

  Distance * distance = new Distance();

  //Read the parameters
  populationSize = *(int *) getInputParameter("populationSize");
  maxEvaluations = *(int *) getInputParameter("maxEvaluations");
  // TODO: indicators = (QualityIndicator) getInputParameter("indicators");

  //Initialize the variables
  population = new SolutionSet(populationSize);
  evaluations = 0;

  requiredEvaluations = 0;

  //Read the operators
  mutationOperator = operators_["mutation"];
  crossoverOperator = operators_["crossover"];
  selectionOperator = operators_["selection"];
  
  // Create the initial solutionSet
  Solution * newSolution;
  for (int i = 0; i < populationSize; i++) {
    newSolution = new Solution(problem_);
    problem_->evaluate(newSolution);
    problem_->evaluateConstraints(newSolution);
    evaluations++;
    population->add(newSolution);
  } //for
  
  // Generations
  while (evaluations < maxEvaluations) {
    
    // Create the offSpring solutionSet
    offspringPopulation = new SolutionSet(populationSize);
    Solution ** parents = new Solution*[2];
    
    //obtain parents
    parents[0] = (Solution *) (selectionOperator->execute(population));
    parents[1] = (Solution *) (selectionOperator->execute(population));
    
    // crossover
    Solution ** offSpring = (Solution **) (crossoverOperator->execute(parents));
    
    // mutation
    mutationOperator->execute(offSpring[0]);
    
    // evaluation
    problem_->evaluate(offSpring[0]);
    problem_->evaluateConstraints(offSpring[0]);
    
    // insert child into the offspring population
    offspringPopulation->add(offSpring[0]);
    
    evaluations ++;
    delete[] offSpring;
    delete[] parents;
    
    // Create the solutionSet union of solutionSet and offSpring
    unionSolution = population->join(offspringPopulation);
    delete offspringPopulation;

    // Ranking the union
    Ranking * ranking = new Ranking(unionSolution);

    int remain = populationSize;
    int index = 0;
    SolutionSet * front = NULL;
    for (int i=0;i<population->size();i++) {
      delete population->get(i);
    }
    population->clear();

    // Obtain the next front
    front = ranking->getSubfront(index);

    while ((remain > 0) && (remain >= front->size())) {
      //Assign crowding distance to individuals
      distance->crowdingDistanceAssignment(front, problem_->getNumberOfObjectives());
      //Add the individuals of this front
      for (int k = 0; k < front->size(); k++) {
        population->add(new Solution(front->get(k)));
      } // for
      
      //Decrement remain
      remain = remain - front->size();
      
      //Obtain the next front
      index++;
      if (remain > 0) {
        front = ranking->getSubfront(index);
      } // if
    } // while

    // Remain is less than front(index).size, insert only the best one
    if (remain > 0) {  // front contains individuals to insert
      distance->crowdingDistanceAssignment(front, problem_->getNumberOfObjectives());
      Comparator * c = new CrowdingComparator();
      front->sort(c);
      delete c;
      for (int k = 0; k < remain; k++) {
        population->add(new Solution(front->get(k)));
      } // for

      remain = 0;
    } // if

    delete ranking;
    delete unionSolution;

    // This piece of code shows how to use the indicator object into the code
    // of NSGA-II. In particular, it finds the number of evaluations required
    // by the algorithm to obtain a Pareto front with a hypervolume higher
    // than the hypervolume of the true Pareto front.
// TODO:
//    if ((indicators != NULL) &&
//      (requiredEvaluations == 0)) {
//      double HV = indicators.getHypervolume(population);
//      if (HV >= (0.98 * indicators.getTrueParetoFrontHypervolume())) {
//        requiredEvaluations = evaluations;
//      } // if
//    } // if

  } // while

  delete distance;

  // Return as output parameter the required evaluations
  // TODO:
  //setOutputParameter("evaluations", requiredEvaluations);

  // Return the first non-dominated front
  Ranking * ranking = new Ranking(population);
  SolutionSet * result = new SolutionSet(ranking->getSubfront(0)->size());
  for (int i=0;i<ranking->getSubfront(0)->size();i++) {
    result->add(new Solution(ranking->getSubfront(0)->get(i)));
  }
  delete ranking;
  delete population;

  return result;

} // execute
Esempio n. 15
0
File: PSO.cpp Progetto: wkoder/mocde
/**
 * Runs of the SMPSO algorithm.
 * @return a <code>SolutionSet</code> that is a set of non dominated solutions
 * as a result of the algorithm execution
 */
SolutionSet * PSO::execute() {

  initParams();

  success_ = false;
  globalBest_ =  NULL;

  //->Step 1 (and 3) Create the initial population and evaluate
  for (int i = 0; i < particlesSize_; i++) {
    Solution * particle = new Solution(problem_);
    problem_->evaluate(particle);
    evaluations_ ++;
    particles_->add(particle);
    if ((globalBest_ == NULL) || (particle->getObjective(0) < globalBest_->getObjective(0))) {
      if (globalBest_!= NULL) {
        delete globalBest_;
      }
      globalBest_ = new Solution(particle);
    }
  }

  //-> Step2. Initialize the speed_ of each particle to 0
  for (int i = 0; i < particlesSize_; i++) {
    speed_[i] = new double[problem_->getNumberOfVariables()];
    for (int j = 0; j < problem_->getNumberOfVariables(); j++) {
    speed_[i][j] = 0.0;
    }
  }

  //-> Step 6. Initialize the memory of each particle
  for (int i = 0; i < particles_->size(); i++) {
    Solution * particle = new Solution(particles_->get(i));
    localBest_[i] = particle;
  }

  //-> Step 7. Iterations ..
  while (iteration_ < maxIterations_) {
    int * bestIndividualPtr = (int*)findBestSolution_->execute(particles_);
    int bestIndividual = *bestIndividualPtr;
    delete bestIndividualPtr;
    computeSpeed(iteration_, maxIterations_);

    //Compute the new positions for the particles_
    computeNewPositions();

    //Mutate the particles_
    //mopsoMutation(iteration_, maxIterations_);

    //Evaluate the new particles_ in new positions
    for (int i = 0; i < particles_->size(); i++) {
      Solution * particle = particles_->get(i);
      problem_->evaluate(particle);
      evaluations_ ++;
    }

    //Actualize the memory of this particle
    for (int i = 0; i < particles_->size(); i++) {
     //int flag = comparator_.compare(particles_.get(i), localBest_[i]);
     //if (flag < 0) { // the new particle is best_ than the older remember
     if ((particles_->get(i)->getObjective(0) < localBest_[i]->getObjective(0))) {
       Solution * particle = new Solution(particles_->get(i));
       delete localBest_[i];
       localBest_[i] = particle;
     } // if
     if ((particles_->get(i)->getObjective(0) < globalBest_->getObjective(0))) {
       Solution * particle = new Solution(particles_->get(i));
       delete globalBest_;
       globalBest_ = particle;
     } // if

    }
    iteration_++;
  }

  // Return a population with the best individual
  SolutionSet * resultPopulation = new SolutionSet(1);
  int * bestIndexPtr = (int *)findBestSolution_->execute(particles_);
  int bestIndex = *bestIndexPtr;
  delete bestIndexPtr;
  cout << "Best index = " << bestIndex << endl;
  Solution * s = particles_->get(bestIndex);
  resultPopulation->add(new Solution(s));

  // Free memory
  deleteParams();

  return resultPopulation;
} // execute
Esempio n. 16
0
/**
 * Runs of the SMPSO algorithm.
 * @return a <code>SolutionSet</code> that is a set of non dominated solutions
 * as a result of the algorithm execution
 */
SolutionSet *SMPSOhv::execute() {

  initParams();

  success = false;
  //->Step 1 (and 3) Create the initial population and evaluate
  for (int i = 0; i < swarmSize; i++){
    Solution *particle = new Solution(problem_);
    problem_->evaluate(particle);
    problem_->evaluateConstraints(particle);
    particles->add(particle);
  }

  //-> Step2. Initialize the speed of each particle to 0
  for (int i = 0; i < swarmSize; i++) {
    speed[i] = new double[problem_->getNumberOfVariables()];
    for (int j = 0; j < problem_->getNumberOfVariables(); j++) {
      speed[i][j] = 0.0;
    }
  }

  // Step4 and 5
  for (int i = 0; i < particles->size(); i++){
    Solution *particle = new Solution(particles->get(i));
    if (leaders->add(particle) == false){
      delete particle;
    }
  }

  //-> Step 6. Initialize the memory of each particle
  for (int i = 0; i < particles->size(); i++){
    Solution *particle = new Solution(particles->get(i));
    best[i] = particle;
  }

  //Crowding the leaders_
  //distance->crowdingDistanceAssignment(leaders, problem_->getNumberOfObjectives());
  leaders->computeHVContribution();

  //-> Step 7. Iterations ..
  while (iteration < maxIterations) {
    //Compute the speed_
    computeSpeed(iteration, maxIterations);

    //Compute the new positions for the particles_
    computeNewPositions();

    //Mutate the particles_
    mopsoMutation(iteration,maxIterations);

    //Evaluate the new particles in new positions
    for (int i = 0; i < particles->size(); i++){
      Solution *particle = particles->get(i);
      problem_->evaluate(particle);
      problem_->evaluateConstraints(particle);
    }

    //Update the archive
    for (int i = 0; i < particles->size(); i++) {
      Solution *particle = new Solution(particles->get(i));
      if (leaders->add(particle) == false) {
        delete particle;
      }
    }

    //Update the memory of this particle
    for (int i = 0; i < particles->size(); i++) {
      int flag = dominance->compare(particles->get(i), best[i]);
      if (flag != 1) { // the new particle is best_ than the older remembered
        Solution *particle = new Solution(particles->get(i));
        delete best[i];
        best[i] = particle;
      }
    }

    iteration++;
  }

  // Build the solution set result
  SolutionSet * result = new SolutionSet(leaders->size());
  for (int i=0;i<leaders->size();i++) {
    result->add(new Solution(leaders->get(i)));
  }

  // Free memory
  deleteParams();

  return result;
} // execute
Esempio n. 17
0
/*
 * Runs the GDE3 algorithm.
 * @return a <code>SolutionSet</code> that is a set of non dominated solutions
 * as a result of the algorithm execution
 */
SolutionSet * GDE3::execute() {

  int populationSize;
  int maxIterations;
  int evaluations;
  int iterations;

  SolutionSet * population;
  SolutionSet * offspringPopulation;

  Distance * distance;
  Comparator * dominance;

  Operator * crossoverOperator;
  Operator * selectionOperator;

  distance  = new Distance();
  dominance = new DominanceComparator();

  Solution ** parent;

  //Read the parameters
  populationSize = *(int *) getInputParameter("populationSize");
  maxIterations  = *(int *) getInputParameter("maxIterations");

  //Initialize the variables
  population  = new SolutionSet(populationSize);
  evaluations = 0;
  iterations  = 0;

  //Read the operators
  crossoverOperator = operators_["crossover"];
  selectionOperator = operators_["selection"];

  // Create the initial solutionSet
  Solution * newSolution;
  for (int i = 0; i < populationSize; i++) {
    newSolution = new Solution(problem_);
    problem_->evaluate(newSolution);
    problem_->evaluateConstraints(newSolution);
    evaluations++;
    population->add(newSolution);
  } //for

  // Generations ...
  while (iterations < maxIterations) {
    // Create the offSpring solutionSet
    offspringPopulation  = new SolutionSet(populationSize * 2);

    for (int i = 0; i < populationSize; i++){
      // Obtain parents. Two parameters are required: the population and the
      //                 index of the current individual
      void ** object1 = new void*[2];
      object1[0] = population;
      object1[1] = &i;
      parent = (Solution **) (selectionOperator->execute(object1));
      delete[] object1;

      Solution * child ;
      // Crossover. Two parameters are required: the current individual and the
      //            array of parents
      void ** object2 = new void*[2];
      object2[0] = population->get(i);
      object2[1] = parent;
      child = (Solution *) (crossoverOperator->execute(object2));
      delete[] object2;
      delete[] parent;

      problem_->evaluate(child) ;
      problem_->evaluateConstraints(child);
      evaluations++ ;

      // Dominance test
      int result  ;
      result = dominance->compare(population->get(i), child) ;
      if (result == -1) { // Solution i dominates child
        offspringPopulation->add(new Solution(population->get(i)));
        delete child;
      } // if
      else if (result == 1) { // child dominates
        offspringPopulation->add(child) ;
      } // else if
      else { // the two solutions are non-dominated
        offspringPopulation->add(child) ;
        offspringPopulation->add(new Solution(population->get(i)));
      } // else
    } // for

    // Ranking the offspring population
    Ranking * ranking = new Ranking(offspringPopulation);

    int remain = populationSize;
    int index  = 0;
    SolutionSet * front = NULL;
    for (int i = 0; i < populationSize; i++) {
      delete population->get(i);
    }
    population->clear();

    // Obtain the next front
    front = ranking->getSubfront(index);

    while ((remain > 0) && (remain >= front->size())){
      //Assign crowding distance to individuals
      distance->crowdingDistanceAssignment(front,problem_->getNumberOfObjectives());
      //Add the individuals of this front
      for (int k = 0; k < front->size(); k++ ) {
        population->add(new Solution(front->get(k)));
      } // for

      //Decrement remain
      remain = remain - front->size();

      //Obtain the next front
      index++;
      if (remain > 0) {
        front = ranking->getSubfront(index);
      } // if
    } // while

    // remain is less than front(index).size, insert only the best one
    if (remain > 0) {  // front contains individuals to insert
      while (front->size() > remain) {
         distance->crowdingDistanceAssignment(front,problem_->getNumberOfObjectives());
         Comparator * crowdingComparator = new CrowdingComparator();
         int indexWorst = front->indexWorst(crowdingComparator);
         delete crowdingComparator;
         delete front->get(indexWorst);
         front->remove(indexWorst);
      }
      for (int k = 0; k < front->size(); k++) {
        population->add(new Solution(front->get(k)));
      }

      remain = 0;
    } // if

    delete ranking;
    delete offspringPopulation;

    iterations ++ ;
  } // while

  delete dominance;
  delete distance;

  // Return the first non-dominated front
  Ranking * ranking = new Ranking(population);
  SolutionSet * result = new SolutionSet(ranking->getSubfront(0)->size());
  for (int i=0;i<ranking->getSubfront(0)->size();i++) {
    result->add(new Solution(ranking->getSubfront(0)->get(i)));
  }
  delete ranking;
  delete population;

  return result;

} // execute
Esempio n. 18
0
void enumerate(int limit,
               int timeLimit,
               int threads,
               int state_tree_limit,
               std::ifstream& inFile,
               const std::string& intervalFile,
               int lowerbound,
               bool monoclonal,
               const std::string& purityString,
               bool writeCliqueFile,
               bool readCliqueFile,
               const std::string& cliqueFile,
               int offset,
               const IntSet& whiteList,
               SolutionSet& sols)
{
  CharacterMatrix M;
  
  try
  {
    g_lineNumber = 0;
    inFile >> M;
  }
  catch (std::runtime_error& e)
  {
    std::cerr << "Character matrix file. " << e.what() << std::endl;
    exit(1);
  }
  
  if (!intervalFile.empty())
  {
    std::ifstream inFile2(intervalFile.c_str());
    if (inFile2.good())
    {
      try
      {
        M.setIntervals(inFile2);
      }
      catch (std::runtime_error& e)
      {
        std::cerr << "Interval file. " << e.what() << std::endl;
        exit(1);
      }
    }
  }
  
  StlDoubleVector purityValues;
  if (purityString != "" && !parse_purity_vector(purityString, M.m(), purityValues))
  {
    return;
  }
//  if (monoclonal && purityString == "")
//  {
//    std::cerr << "Expected purity values" << std::endl;
//    return;
//  }
  
  if (g_verbosity >= VERBOSE_ESSENTIAL)
  {
    std::cerr << "Intializing copy-state matrix ..." << std::endl;
  }
  M.init();
  
  if (monoclonal)
  {
    M.applyHeuristic();
  }
  
  CompatibilityGraph* pComp = NULL;
  if (!readCliqueFile)
  {
    if (g_verbosity >= VERBOSE_ESSENTIAL)
    {
      std::cerr << std::endl << "Initializing compatibility graph ..." << std::endl;
    }
    pComp = new CompatibilityGraph(M);
    pComp->init(IntPairSet(), -1);
  }
  else
  {
    std::ifstream inFile(cliqueFile);
    pComp = new CompatibilityGraph(M);
    pComp->init(inFile);
  }
  
  if (writeCliqueFile)
  {
    std::ofstream outFile(cliqueFile);
    if (outFile.good())
    {
      pComp->write(outFile);
    }
  }
  
  NoisyCnaEnumerate alg(M, purityValues, *pComp, lowerbound);
  alg.init(state_tree_limit);
  alg.enumerate(limit, timeLimit, threads, state_tree_limit, monoclonal, offset, whiteList);

  sols = alg.sols();
  delete pComp;
  
  if (g_verbosity >= VERBOSE_ESSENTIAL)
  {
    std::cerr << "Generated " << sols.solutionCount() << " solutions" << std::endl;
  }
  inFile.close();
}
Esempio n. 19
0
int main(int argc, char ** argv) {

  clock_t t_ini, t_fin;

  Problem   * problem   ; // The problem to solve
  Algorithm * algorithm ; // The algorithm to use
  Operator  * crossover ; // Crossover operator
  Operator  * selection ; // Selection operator

  map<string, void *> parameters;
  
  //TODO: QualityIndicator * indicators;

  if (argc>=2) {
    problem = ProblemFactory::getProblem(argc, argv);
    cout << "Selected problem: " << problem->getName() << endl;
  } else {
    cout << "No problem selected." << endl;
    cout << "Default problem will be used: Fonseca" << endl;
    problem = ProblemFactory::getProblem(const_cast<char *>("Fonseca"));
  }

  algorithm = new GDE3(problem);

  // Algorithm parameters
  int populationSizeValue = 100;
  int maxIterationsValue = 250;
  algorithm->setInputParameter("populationSize",&populationSizeValue);
  algorithm->setInputParameter("maxIterations",&maxIterationsValue);

  // Crossover operator
  double crParameter = 0.5;
  double fParameter  = 0.5;
  parameters["CR"] =  &crParameter;
  parameters["F"] = &fParameter;
  crossover = new DifferentialEvolutionCrossover(parameters);

  // Selection operator
  parameters.clear();
  selection = new DifferentialEvolutionSelection(parameters) ;

  // Add the operators to the algorithm
  algorithm->addOperator("crossover",crossover);
  algorithm->addOperator("selection",selection);

  // Add the indicator object to the algorithm
  //algorithm->setInputParameter("indicators", indicators) ;

  // Execute the Algorithm
  t_ini = clock();
  SolutionSet * population = algorithm->execute();
  t_fin = clock();
  double secs = (double) (t_fin - t_ini);
  secs = secs / CLOCKS_PER_SEC;

  // Result messages
  cout << "Total execution time: " << secs << "s" << endl;
  cout << "Variables values have been written to file VAR" << endl;
  population->printVariablesToFile("VAR");
  cout << "Objectives values have been written to file FUN" << endl;
  population->printObjectivesToFile("FUN");

  delete selection;
  delete crossover;
  delete population;
  delete algorithm;

} // main
Esempio n. 20
0
/**
 * Class implementing the NSGA-II algorithm.
 * This implementation of NSGA-II makes use of a QualityIndicator object
 *  to obtained the convergence speed of the algorithm. This version is used
 *  in the paper:
 *     A.J. Nebro, J.J. Durillo, C.A. Coello Coello, F. Luna, E. Alba
 *     "A Study of Convergence Speed in Multi-Objective Metaheuristics."
 *     To be presented in: PPSN'08. Dortmund. September 2008.
 *
 *   Besides the classic NSGA-II, a steady-state version (ssNSGAII) is also
 *   included (See: J.J. Durillo, A.J. Nebro, F. Luna and E. Alba
 *                  "On the Effect of the Steady-State Selection Scheme in
 *                  Multi-Objective Genetic Algorithms"
 *                  5th International Conference, EMO 2009, pp: 183-197.
 *                  April 2009)
 */
int main(int argc, char ** argv) {

    clock_t t_ini, t_fin;

    Problem   * problem   ; // The problem to solve
    Algorithm * algorithm ; // The algorithm to use
    HUXCrossover  * crossover ; // Crossover operator
    BitFlipMutation  * mutation  ; // Mutation operator
    BinaryTournament  * selection ; // Selection operator

    if (argc>=2) {
        problem = ProblemFactory::getProblem(argc, argv);
        cout << "Selected problem: " << problem->getName() << endl;
    } else {
        cout << "No problem selected." << endl;
        cout << "Default problem will be used: Fonseca" << endl;
        problem = ProblemFactory::getProblem(const_cast<char *>("ZDT5"));
    }

//  QualityIndicator * indicators ; // Object to get quality indicators
//	indicators = NULL ;

    algorithm = new MOCHC(problem);

    // Algorithm parameters
    int populationSize = 100;
    int maxEvaluations = 25000;
    double initialConvergenceCount = 0.25;
    double preservedPopulation = 0.05;
    int convergenceValue = 3;
    algorithm->setInputParameter("populationSize",&populationSize);
    algorithm->setInputParameter("maxEvaluations",&maxEvaluations);
    algorithm->setInputParameter("initialConvergenceCount",&initialConvergenceCount);
    algorithm->setInputParameter("preservedPopulation",&preservedPopulation);
    algorithm->setInputParameter("convergenceValue",&convergenceValue);

    // Mutation and Crossover for Real codification
    map<string, void *> parameters;

    double crossoverProbability = 1.0;
    double crossoverDistributionIndex = 20.0;
    parameters["probability"] =  &crossoverProbability;
    crossover = new HUXCrossover(parameters);

    parameters.clear();
    double mutationProbability = 0.35;
    parameters["probability"] = &mutationProbability;

    mutation = new BitFlipMutation(parameters);

    // Selection Operator
    parameters.clear();
    selection = new BinaryTournament(parameters);

    // Add the operators to the algorithm
    algorithm->addOperator("crossover",crossover);
    algorithm->addOperator("mutation",mutation);
    algorithm->addOperator("parentSelection",selection);

    // Add the indicator object to the algorithm
//	algorithm->setInputParameter("indicators", indicators) ;

    // Execute the Algorithm
    t_ini = clock();
    SolutionSet * population = algorithm->execute();
    t_fin = clock();
    double secs = (double) (t_fin - t_ini);
    secs = secs / CLOCKS_PER_SEC;

    // Result messages
    cout << "Total execution time: " << secs << "s" << endl;
    cout << "Variables values have been written to file VAR" << endl;
    population->printVariablesToFile("VAR");
    cout << "Objectives values have been written to file FUN" << endl;
    population->printObjectivesToFile("FUN");


    delete selection;
    delete mutation;
    delete crossover;
    delete population;
    delete algorithm;

} // main
Esempio n. 21
0
int main(int argc, char ** argv) {

  clock_t t_ini, t_fin;

  Problem   * problem;   // The problem to solve
  Algorithm * algorithm; // The algorithm to use
  Operator  * mutation;  // "Turbulence" operator

  map<string, void *> parameters; // Operator parameters

  //TODO: QualityIndicator * indicators; // Object to get quality indicators

  if (argc>=2) {
    problem = ProblemFactory::getProblem(argc, argv);
    cout << "Selected problem: " << problem->getName() << endl;
  } else {
    cout << "No problem selected." << endl;
    cout << "Default problem will be used: Kursawe" << endl;
    problem = ProblemFactory::getProblem(const_cast<char *>("Kursawe"));
  }

  algorithm = new SMPSO(problem);

  // Algorithm parameters
  int swarmSizeValue = 100;
  int archiveSizeValue = 100;
  int maxIterationsValue = 250;
  algorithm->setInputParameter("swarmSize",&swarmSizeValue);
  algorithm->setInputParameter("archiveSize",&archiveSizeValue);
  algorithm->setInputParameter("maxIterations",&maxIterationsValue);

  // Mutation operator
  double probabilityParameter = 1.0/(problem->getNumberOfVariables());
  double distributionIndexParameter = 20.0;
  parameters["probability"] =  &probabilityParameter;
  parameters["distributionIndex"] = &distributionIndexParameter;
  mutation = new PolynomialMutation(parameters);

  // Add the operators to the algorithm
  algorithm->addOperator("mutation",mutation);

  // Add the indicator object to the algorithm
  //algorithm->setInputParameter("indicators", indicators) ;

  // Execute the Algorithm
  t_ini = clock();
  SolutionSet * population = algorithm->execute();
  t_fin = clock();
  double secs = (double) (t_fin - t_ini);
  secs = secs / CLOCKS_PER_SEC;

  // Result messages
  cout << "Total execution time: " << secs << "s" << endl;
  cout << "Variables values have been written to file VAR" << endl;
  population->printVariablesToFile("VAR");
  cout << "Objectives values have been written to file FUN" << endl;
  population->printObjectivesToFile("FUN");

  delete mutation;
  delete population;
  delete algorithm;

} // main