Exemplo n.º 1
0
int main(int argc, char **argv) 
{
    MPI_Init(&argc, &argv); 
    atexit([]{ MPI_Finalize(); }); 

    const std::size_t population = 100; 
    const std::size_t generations = 200; 
    const std::size_t variables = 5; 
    const std::size_t max_crossover_attempts = 100; 
    const float       migration_prob = .2f;
    const float       elite_percentage = .3f;

    std::vector< float > min_constraints(variables); 
    std::vector< float > max_constraints(variables); 
    fill(begin(min_constraints), end(min_constraints), -5.12f); 
    fill(begin(max_constraints), end(max_constraints), +5.12f); 

    libga_mpi::sga< float > sga(population, elite_percentage
        , min_constraints, max_constraints); 
    libga_mpi::island_model< libga_mpi::sga< float >> im(sga, migration_prob); 

    const bool success 
	= sga.start(rastrigin, libga_mpi::xover::blxa<float>()
	      , [generations](std::size_t g) { return g == generations; }
		, [&](const float *x, std::size_t n) 
		{ return is_within_constraints(x, n
		       , min_constraints, max_constraints); }
		, libga_mpi::mutation::mutate_none<float>()
		, max_crossover_attempts); 
    
    if(success) 
    {
	int rank;
	MPI_Comm_rank(MPI_COMM_WORLD, &rank); 
	const std::size_t f = fittest(sga);
	std::ofstream stream("rastrigin_data_" + std::to_string(rank)); 
	for(std::size_t i=0; i < variables; ++i) 
	    stream << im.island().genome()[f*variables + i] << " "; 
	stream << im.island().ospace()[f]; 
    }
    else
    {
	std::cout << "Algorithm stalled. " << std::endl; 
	return 1; 
    }
    return 0; 
}
Exemplo n.º 2
0
bool COptMethodEP::optimise()
{
  if (!initialize())
    {
      if (mpCallBack)
        mpCallBack->finishItem(mhGenerations);

      return false;
    }

  bool Continue = true;

  // Initialize the population
  Continue = creation();

  // get the index of the fittest
  mBestIndex = fittest();

  if (mBestIndex != C_INVALID_INDEX)
    {
      // and store that value
      mBestValue = mValue[mBestIndex];
      Continue = mpOptProblem->setSolution(mBestValue, *mIndividual[mBestIndex]);

      // We found a new best value lets report it.
      mpParentTask->output(COutputInterface::DURING);
    }

  if (!Continue)
    {
      if (mpCallBack)
        mpCallBack->finishItem(mhGenerations);

      cleanup();
      return true;
    }

  // iterate over Generations
  for (mGeneration = 2; mGeneration <= mGenerations && Continue; mGeneration++)
    {
      // replicate the individuals
      Continue = replicate();

      // select the most fit
      Continue = select();

      // get the index of the fittest
      mBestIndex = fittest();

      if (mBestIndex != C_INVALID_INDEX &&
          mValue[mBestIndex] < mBestValue)
        {
          mBestValue = mValue[mBestIndex];

          Continue = mpOptProblem->setSolution(mBestValue, *mIndividual[mBestIndex]);

          // We found a new best value lets report it.
          //if (mpReport) mpReport->printBody();
          mpParentTask->output(COutputInterface::DURING);
        }

      if (mpCallBack)
        Continue = mpCallBack->progressItem(mhGenerations);
    }

  if (mpCallBack)
    mpCallBack->finishItem(mhGenerations);

  cleanup();

  return true;
}
Exemplo n.º 3
0
bool COptMethodDE::optimise()
{
  bool Continue = true;

  if (!initialize())
    {
      if (mpCallBack)
        mpCallBack->finishItem(mhGenerations);

      return false;
    }

  size_t i;

  // initialise the population
  // first individual is the initial guess
  for (i = 0; i < mVariableSize; i++)
    {
      C_FLOAT64 & mut = (*mIndividuals[0])[i];
      COptItem & OptItem = *(*mpOptItem)[i];

      mut = OptItem.getStartValue();

      // force it to be within the bounds
      switch (OptItem.checkConstraint(mut))
        {
          case - 1:
            mut = *OptItem.getLowerBoundValue();
            break;

          case 1:
            mut = *OptItem.getUpperBoundValue();
            break;
        }

      // We need to set the value here so that further checks take
      // account of the value.
      *mContainerVariables[i] = mut;
    }

  Continue &= evaluate(*mIndividuals[0]);
  mValues[0] = mEvaluationValue;

  if (!isnan(mEvaluationValue))
    {
      // and store that value
      mBestValue = mValues[0];
      Continue &= mpOptProblem->setSolution(mBestValue, *mIndividuals[0]);

      // We found a new best value lets report it.
      mpParentTask->output(COutputInterface::DURING);
    }

  // the others are random
  Continue &= creation(1, mPopulationSize);

  mBestIndex = fittest();

  if (mBestIndex != C_INVALID_INDEX &&
      mValues[mBestIndex] < mBestValue)
    {
      // and store that value
      mBestValue = mValues[mBestIndex];
      Continue = mpOptProblem->setSolution(mBestValue, *mIndividuals[mBestIndex]);

      // We found a new best value lets report it.
      mpParentTask->output(COutputInterface::DURING);
    }

  if (!Continue)
    {
      if (mpCallBack)
        mpCallBack->finishItem(mhGenerations);

      cleanup();
      return true;
    }

  size_t Stalled = 0;

  // ITERATE FOR gener GENERATIONS
  for (mCurrentGeneration = 2;
    mCurrentGeneration <= mGenerations && Continue;
    mCurrentGeneration++, Stalled++)
    {
      if (Stalled > 10)
        {
          Continue &= creation((size_t) 0.4 * mPopulationSize, (size_t) 0.8 * mPopulationSize);
        }

      // perturb the population a bit
      Continue &= creation((size_t)(mPopulationSize * 0.9), mPopulationSize);

      Continue &= replicate();

      // get the index of the fittest
      mBestIndex = fittest();

      if (mBestIndex != C_INVALID_INDEX &&
          mValues[mBestIndex] < mBestValue)
        {
          Stalled = 0;
          mBestValue = mValues[mBestIndex];

          Continue &= mpOptProblem->setSolution(mBestValue, *mIndividuals[mBestIndex]);

          // We found a new best value lets report it.
          //if (mpReport) mpReport->printBody();
          mpParentTask->output(COutputInterface::DURING);
        }

      if (mpCallBack)
        Continue &= mpCallBack->progressItem(mhGenerations);
    }

  if (mpCallBack)
    mpCallBack->finishItem(mhGenerations);

  cleanup();

  return true;
}
Exemplo n.º 4
0
bool COptMethodGA::optimise()
{
  bool Continue = true;

  if (!initialize())
    {
      if (mpCallBack)
        mpCallBack->finishItem(mhGenerations);

      return false;
    }

  // Counters to determine whether the optimization process has stalled
  // They count the number of generations without advances.
  unsigned C_INT32 Stalled, Stalled10, Stalled30, Stalled50;
  Stalled = Stalled10 = Stalled30 = Stalled50 = 0;

  unsigned C_INT32 i;

  // initialise the population
  // first individual is the initial guess
  for (i = 0; i < mVariableSize; i++)
    {
      C_FLOAT64 & mut = (*mIndividual[0])[i];
      COptItem & OptItem = *(*mpOptItem)[i];

      mut = OptItem.getStartValue();

      // force it to be within the bounds
      switch (OptItem.checkConstraint(mut))
        {
          case - 1:
            mut = *OptItem.getLowerBoundValue();
            break;

          case 1:
            mut = *OptItem.getUpperBoundValue();
            break;
        }

      // We need to set the value here so that further checks take
      // account of the value.
      (*(*mpSetCalculateVariable)[i])(mut);
    }

  Continue &= evaluate(*mIndividual[0]);
  mValue[0] = mEvaluationValue;

  if (!isnan(mEvaluationValue))
    {
      // and store that value
      mBestValue = mValue[0];
      Continue &= mpOptProblem->setSolution(mBestValue, *mIndividual[0]);

      // We found a new best value lets report it.
      mpParentTask->output(COutputInterface::DURING);
    }

  // the others are random
  Continue &= creation(1, mPopulationSize);

  Continue &= select();
  mBestIndex = fittest();

  if (mBestIndex != C_INVALID_INDEX &&
      mValue[mBestIndex] < mBestValue)
    {
      // and store that value
      mBestValue = mValue[mBestIndex];
      Continue = mpOptProblem->setSolution(mBestValue, *mIndividual[mBestIndex]);

      // We found a new best value lets report it.
      mpParentTask->output(COutputInterface::DURING);
    }

  if (!Continue)
    {
      if (mpCallBack)
        mpCallBack->finishItem(mhGenerations);

      cleanup();
      return false;
    }

  // ITERATE FOR gener GENERATIONS
  for (mGeneration = 2;
       mGeneration <= mGenerations && Continue;
       mGeneration++, Stalled++, Stalled10++, Stalled30++, Stalled50++)
    {
      // perturb the population if we have stalled for a while
      if (Stalled > 50 && Stalled50 > 50)
        {
          Continue &= creation((unsigned C_INT32)(mPopulationSize / 2),
                               mPopulationSize);
          Stalled10 = Stalled30 = Stalled50 = 0;
        }
      else if (Stalled > 30 && Stalled30 > 30)
        {
          Continue &= creation((unsigned C_INT32)(mPopulationSize * 0.7),
                               mPopulationSize);
          Stalled10 = Stalled30 = 0;
        }
      else if (Stalled > 10 && Stalled10 > 10)
        {
          Continue &= creation((unsigned C_INT32)(mPopulationSize * 0.9),
                               mPopulationSize);
          Stalled10 = 0;
        }
      // replicate the individuals
      else
        Continue &= replicate();

      // select the most fit
      Continue &= select();

      // get the index of the fittest
      mBestIndex = fittest();

      if (mBestIndex != C_INVALID_INDEX &&
          mValue[mBestIndex] < mBestValue)
        {
          Stalled = Stalled10 = Stalled30 = Stalled50 = 0;
          mBestValue = mValue[mBestIndex];

          Continue &= mpOptProblem->setSolution(mBestValue, *mIndividual[mBestIndex]);

          // We found a new best value lets report it.
          //if (mpReport) mpReport->printBody();
          mpParentTask->output(COutputInterface::DURING);
        }

      if (mpCallBack)
        Continue &= mpCallBack->progressItem(mhGenerations);
    }

  if (mpCallBack)
    mpCallBack->finishItem(mhGenerations);

  cleanup();

  return Continue;
}
Exemplo n.º 5
0
bool COptMethodSRES::optimise()
{
  bool Continue = true;
  size_t BestIndex = C_INVALID_INDEX;

  size_t Stalled = 0;
#ifdef RANDOMIZE
  // Counters to determine whether the optimization process has stalled
  // They count the number of generations without advances.
  size_t Stalled10, Stalled20, Stalled40, Stalled80;
  Stalled10 = Stalled20 = Stalled40 = Stalled80 = 0;
#endif // RANDOMIZE

  if (!initialize())
    {
      if (mpCallBack)
        mpCallBack->finishItem(mhGenerations);

      return false;
    }

  if (mLogVerbosity > 0)
    mMethodLog.enterLogEntry(
      COptLogEntry(
        "Algorithm started",
        "For more information about this method see: http://copasi.org/Support/User_Manual/Methods/Optimization_Methods/Evolutionary_Strategy_SRES/"
      )
    );

  // initialise the population
  Continue = creation(0);
  mpOptProblem->setSolution(mValues[0], *mIndividuals[0]);

  // get the index of the fittest
  BestIndex = fittest();

  if (BestIndex != C_INVALID_INDEX)
    {
      // and store that value
      mBestValue = mValues[BestIndex];
      Continue = mpOptProblem->setSolution(mBestValue, *mIndividuals[BestIndex]);

      // We found a new best value lets report it.
      mpParentTask->output(COutputInterface::DURING);
    }

  if (!Continue)
    {
      if (mLogVerbosity > 0)
        mMethodLog.enterLogEntry(COptLogEntry("Algorithm was terminated by user."));

      if (mpCallBack)
        mpCallBack->finishItem(mhGenerations);

      cleanup();
      return true;
    }

  // ITERATE FOR gener GENERATIONS
#ifdef RANDOMIZE

  for (mCurrentGeneration = 2;
       mCurrentGeneration <= mGenerations && Continue;
       mCurrentGeneration++, Stalled++, Stalled10++, Stalled20++, Stalled40++, Stalled80++)
    {
      // perturb the population if we have stalled for a while
      if (Stalled80 > 80)
        {
          if (mLogVerbosity > 0)
            mMethodLog.enterLogEntry(
              COptLogEntry(
                "Generation " + std::to_string(mCurrentGeneration) +
                "generations: Fittest individual has not changed for the last " + std::to_string(Stalled80 - 1) +
                ". 80% of individuals randomized."
              ));

          Continue = creation((size_t)(mPopulationSize * 0.2));
          Stalled10 = Stalled20 = Stalled40 = Stalled80 = 0;
        }
      else if (Stalled40 > 40)
        {
          if (mLogVerbosity > 0)
            mMethodLog.enterLogEntry(
              COptLogEntry(
                "Generation " + std::to_string(mCurrentGeneration) +
                "generations: Fittest individual has not changed for the last " + std::to_string(Stalled40 - 1) +
                ". 40% of individuals randomized."
              ));

          Continue = creation((size_t)(mPopulationSize * 0.6));
          Stalled10 = Stalled20 = Stalled40 = 0;
        }
      else if (Stalled20 > 20)
        {
          if (mLogVerbosity > 0)
            mMethodLog.enterLogEntry(
              COptLogEntry(
                "Generation " + std::to_string(mCurrentGeneration) +
                "generations: Fittest individual has not changed for the last " + std::to_string(Stalled20 - 1) +
                ". 20% of individuals randomized."
              ));

          Continue = creation((size_t)(mPopulationSize * 0.8));
          Stalled10 = Stalled20 = 0;
        }
      else if (Stalled10 > 10)
        {
          if (mLogVerbosity > 0)
            mMethodLog.enterLogEntry(
              COptLogEntry(
                "Generation " + std::to_string(mCurrentGeneration) +
                "generations: Fittest individual has not changed for the last " + std::to_string(Stalled10 - 1) +
                ". 10% of individuals randomized."
              ));

          Continue = creation((size_t)(mPopulationSize * 0.9));
          Stalled10 = 0;
        }

#else

  for (mCurrentGeneration = 2;
       mCurrentGeneration <= mGenerations && Continue;
       mCurrentGeneration++, Stalled++)
    {
#endif // RANDOMIZE

      if (mStopAfterStalledGenerations != 0 && Stalled > mStopAfterStalledGenerations)
        break;

      Continue = replicate();

      // select the most fit
      select();

      // get the index of the fittest
      BestIndex = fittest();

      if (BestIndex != C_INVALID_INDEX &&
          mValues[BestIndex] < mBestValue)
        {
#ifdef RANDOMIZE
          Stalled = Stalled10 = Stalled20 = Stalled40 = Stalled80 = 0;
#else
          Stalled = 0;
#endif // RANDOMIZE

          mBestValue = mValues[BestIndex];

          Continue = mpOptProblem->setSolution(mBestValue, *mIndividuals[BestIndex]);

          // We found a new best value lets report it.
          mpParentTask->output(COutputInterface::DURING);
        }

      if (mpCallBack)
        Continue = mpCallBack->progressItem(mhGenerations);

      //use a different output channel. It will later get a proper enum name
      mpParentTask->output(COutputInterface::MONITORING);
    }

  if (mLogVerbosity > 0)
    mMethodLog.enterLogEntry(
      COptLogEntry("Algorithm finished.",
                   "Terminated after " + std::to_string(mCurrentGeneration - 1) + " of " +
                   std::to_string(mGenerations) + " generations."));

  if (mpCallBack)
    mpCallBack->finishItem(mhGenerations);

  return true;
}

unsigned C_INT32 COptMethodSRES::getMaxLogVerbosity() const
{
  return 1;
}
Exemplo n.º 6
0
/**
 * GA Optimizer Function:
 * Returns: nothing
 */
C_INT32 COptMethodEP2::optimise()
{
  NumGeneration = (C_INT32) getValue("EvolutionaryProgram2.Iterations");
  PopulationSize = (C_INT32) getValue("EvolutionaryProgram2.PopulationSize");
  NumParameter = mpOptProblem->getVariableSize();

  /* Create a random number generator */
  CRandom::Type Type;
  Type = (CRandom::Type)(C_INT32) getValue("EvolutionaryProgram2.RandomGenerator.Type");
  C_INT32 Seed;
  Seed = (C_INT32) getValue("EvolutionaryProgram2.RandomGenerator.Seed");
  CRandom * pRand = CRandom::createGenerator(Type, Seed);

  assert(pRand);

  const double ** Minimum = mpOptProblem->getParameterMin().array();
  const double ** Maximum = mpOptProblem->getParameterMax().array();

  std::vector< UpdateMethod * > & Parameter = mpOptProblem->getCalculateVariableUpdateMethods();

  double current_best_value, la;
  int i, j, last_update, u10, u30, u50;
  bool linear;

  // create array for function value of candidate
  CandidateValue = new double[2 * PopulationSize];

  // create array for function value rate of candidate
  CandidateValueRate = new double[PopulationSize];

  // create array for tournament competition strategy
  WinScore = new int[2 * PopulationSize];

  // create array for crossover points
  CrossPoint = new int[NumParameter];

  // create the population array
  individual.resize(2 * PopulationSize);

  // create the individuals
  for (i = 0; i < 2*PopulationSize; i++)
    individual[i].resize(NumParameter);

  // Prepare inital population
  //Generate the initial population at random
  for (i = 0; i < PopulationSize; i++)
    {
      for (j = 0; j < NumParameter; j++)
        {
          try
            {
              // determine if linear or log scale
              linear = FALSE; la = 1.0;

              if ((*Maximum[j] <= 0.0) || (*Minimum[j] < 0.0)) linear = TRUE;
              else
                {
                  la = log10(*Maximum[j]) - log10(std::min(*Minimum[j], std::numeric_limits< C_FLOAT64 >::epsilon()));

                  if (la < 1.8) linear = TRUE;
                }

              // set it to a random value within the interval
              if (linear)
                individual[i][j] = *Minimum[j] + pRand->getRandomCC() * (*Maximum[j] - *Minimum[j]);
              else
                individual[i][j] = *Minimum[j] * pow(10.0, la * pRand->getRandomCC());
            }
          catch (int)
            {
              individual[i][j] = (*Maximum[j] - *Minimum[j]) * 0.5 + *Minimum[j];
            }
        }

      try
        {
          // calculate its fitness value
          for (int kk = 0; kk < NumParameter; kk++)
            (*Parameter[kk])(individual[i][kk]);

          CandidateValue[i] = mpOptProblem->calculate();
        }
      catch (int)
        {
          CandidateValue[i] = std::numeric_limits< C_FLOAT64 >::max();
        }
    } // initialization ends

  //Set fitness map rate
  // double q=0.8;
  // double constant1=100;
  double constant1 = 100;
  // double constant2=20;
  double constant2 = 10;
  /* for (i=0; i<PopulationSize; i++)
   {
    CandidateValueRate[i]=1-q*pow((1-q),i);
   }
  */
  // get the index of the fittest
  BestFoundSoFar = fittest();

  // initialise the update registers
  last_update = 0;
  u10 = u30 = u50 = 0;

  // store that value
  current_best_value = Get_BestFoundSoFar_candidate();

  std::ofstream finalout("debugopt.dat");

  if (!finalout)
    {
      std::cout << "debugopt.dat cannot be opened!" << std::endl;
      exit(1);
    }

  finalout << "----------------------------- the best result at each generation---------------------" << std::endl;
  finalout << "Generation\t" << "Best candidate value for object function\t" << "Display " << NumParameter << " parameters" << std::endl;
  finalout << std::endl;
  finalout.close();

  srand(time(NULL)); rand();

  // Iterations of GA
  for (i = 0; i < NumGeneration; i++)
    {
      std::cout << std::endl;
      std::cout << "EP2 is processing at generation " << i << std::endl;

      TrackDataFile(i);

      select(5);

      //Mutating all parents
      for (int nn = PopulationSize; nn < 2*PopulationSize; nn++)
        {
          double mut;

          // mutate the parameters
          for (int j = 0; j < NumParameter; j++)
            {
              if (floor(10*rand() / RAND_MAX) > 5)
                {
                  //  if(i<NumGeneration*0.5) mut = individual[nn-PopulationSize][j]*(1 + pRand->getRandomCC());
                  if (i < NumGeneration*0.5) mut = individual[nn - PopulationSize][j] * (1 + sqrt(constant1 * CandidateValueRate[nn] + constant2) * pRand->getRandomCC());
                  else
                    {
                      if (i < NumGeneration*0.6) mut = individual[nn - PopulationSize][j] * (1 + sqrt(constant1 * CandidateValueRate[nn] + constant2) * 0.5 * pRand->getRandomCC());
                      else
                        {
                          if (i < NumGeneration*0.7) mut = individual[nn - PopulationSize][j] * (1 + sqrt(constant1 * CandidateValueRate[nn] + constant2) * 0.25 * pRand->getRandomCC());
                          else
                            {
                              if (i < NumGeneration*0.8) mut = individual[nn - PopulationSize][j] * (1 + sqrt(constant1 * CandidateValueRate[nn] + constant2) * 0.1 * pRand->getRandomCC());
                              else
                                {
                                  if (i < NumGeneration*0.9) mut = individual[nn - PopulationSize][j] * (1 + sqrt(constant1 * CandidateValueRate[nn] + constant2) * 0.01 * pRand->getRandomCC());
                                  else
                                    {
                                      if (i < NumGeneration*0.95) mut = individual[nn - PopulationSize][j] * (1 + sqrt(constant1 * CandidateValueRate[nn] + constant2) * 0.001 * pRand->getRandomCC());
                                      else mut = individual[nn - PopulationSize][j] * (1 + sqrt(constant1 * CandidateValueRate[nn] + constant2) * 0.0001 * pRand->getRandomCC());
                                    }
                                }
                            }
                        }
                    }
                }
              else
                {
                  if (i < NumGeneration*0.5) mut = individual[nn - PopulationSize][j] * (1 - sqrt(constant1 * CandidateValueRate[nn] + constant2) * pRand->getRandomCC());
                  else
                    {
                      if (i < NumGeneration*0.6) mut = individual[nn - PopulationSize][j] * (1 - sqrt(constant1 * CandidateValueRate[nn] + constant2) * 0.5 * pRand->getRandomCC());
                      else
                        {
                          if (i < NumGeneration*0.7) mut = individual[nn - PopulationSize][j] * (1 - sqrt(constant1 * CandidateValueRate[nn] + constant2) * 0.25 * pRand->getRandomCC());
                          else
                            {
                              if (i < NumGeneration*0.8) mut = individual[nn - PopulationSize][j] * (1 - sqrt(constant1 * CandidateValueRate[nn] + constant2) * 0.1 * pRand->getRandomCC());
                              else
                                {
                                  if (i < NumGeneration*0.9) mut = individual[nn - PopulationSize][j] * (1 - sqrt(constant1 * CandidateValueRate[nn] + constant2) * 0.01 * pRand->getRandomCC());
                                  else
                                    {
                                      if (i < NumGeneration*0.95) mut = individual[nn - PopulationSize][j] * (1 - sqrt(constant1 * CandidateValueRate[nn] + constant2) * 0.001 * pRand->getRandomCC());
                                      else mut = individual[nn - PopulationSize][j] * (1 - sqrt(constant1 * CandidateValueRate[nn] + constant2) * 0.0001 * pRand->getRandomCC());
                                    }
                                }
                            }
                        }
                    }
                }

              // check boundary and force it to be within the bounds
              if (mut <= *Minimum[j]) mut = *Minimum[j] + std::numeric_limits< C_FLOAT64 >::epsilon();
              else
                {
                  if (mut < *Minimum[j]) mut = *Minimum[j];
                }

              if (mut >= *Maximum[j]) mut = *Maximum[j] - std::numeric_limits< C_FLOAT64 >::epsilon();
              else
                {
                  if (mut > *Maximum[j]) mut = *Maximum[j];
                }

              // store it
              individual[nn][j] = mut;
            }

          // evaluate the fitness
          for (int kk = 0; kk < NumParameter; kk++)
            (*Parameter[kk])(individual[nn][kk]);

          CandidateValue[nn] = mpOptProblem->calculate();
        }

      // select approprate individuals as new population
      select(2);

      // get the index of the fittest
      BestFoundSoFar = fittest();

      if (Get_BestFoundSoFar_candidate() != current_best_value)
        {
          last_update = i;
          current_best_value = Get_BestFoundSoFar_candidate();
        }

      if (u10) u10--;

      if (u30) u30--;

      if (u50) u50--;

      if ((u50 == 0) && (i - last_update > 50))
        {
          for (int mm = PopulationSize / 2; mm < PopulationSize; mm++)
            {
              for (int jj = 0; jj < NumParameter; jj++)
                {
                  try
                    {
                      // determine if linear or log scale
                      linear = FALSE; la = 1.0;

                      if ((*Maximum[jj] <= 0.0) || (*Minimum[jj] < 0.0)) linear = TRUE;
                      else
                        {
                          la = log10(*Maximum[jj]) - log10(std::min(*Minimum[jj], std::numeric_limits< C_FLOAT64 >::epsilon()));

                          if (la < 1.8) linear = TRUE;
                        }

                      // set it to a random value within the interval
                      if (linear)
                        individual[mm][jj] = *Minimum[jj] + pRand->getRandomCC() * (*Maximum[jj] - *Minimum[jj]);
                      else
                        individual[mm][jj] = *Minimum[jj] * pow(10.0, la * pRand->getRandomCC());
                    }
                  catch (int)
                    {
                      individual[mm][jj] = (*Maximum[jj] - *Minimum[jj]) * 0.5 + *Minimum[jj];
                    }
                }

              try
                {
                  // calculate its fitness
                  for (int kk = 0; kk < NumParameter; kk++)
                    (*Parameter[kk])(individual[mm][kk]);

                  CandidateValue[mm] = mpOptProblem->calculate();
                }
              catch (int)
                {
                  CandidateValue[mm] = std::numeric_limits< C_FLOAT64 >::max();
                }
            }

          //end external for loop
          BestFoundSoFar = fittest();
          u50 = 50; u30 = 30; u10 = 10;
        }
      else
        {
          if ((u30 == 0) && (i - last_update > 30))
            {
              for (int mm = (int)floor(PopulationSize * 0.7); mm < PopulationSize; mm++)
                {
                  for (int jj = 0; jj < NumParameter; jj++)
                    {
                      try
                        {
                          // determine if linear or log scale
                          linear = FALSE; la = 1.0;

                          if ((*Maximum[jj] <= 0.0) || (*Minimum[jj] < 0.0)) linear = TRUE;
                          else
                            {
                              la = log10(*Maximum[jj]) - log10(std::min(*Minimum[jj], std::numeric_limits< C_FLOAT64 >::epsilon()));

                              if (la < 1.8) linear = TRUE;
                            }

                          // set it to a random value within the interval
                          if (linear)
                            individual[mm][jj] = *Minimum[jj] + pRand->getRandomCC() * (*Maximum[jj] - *Minimum[jj]);
                          else
                            individual[mm][jj] = *Minimum[jj] * pow(10.0, la * pRand->getRandomCC());
                        }
                      catch (int)
                        {
                          individual[mm][jj] = (*Maximum[jj] - *Minimum[jj]) * 0.5 + *Minimum[jj];
                        }
                    }

                  try
                    {
                      // calculate its fitness
                      for (int kk = 0; kk < NumParameter; kk++)
                        (*Parameter[kk])(individual[mm][kk]);

                      CandidateValue[mm] = mpOptProblem->calculate();
                    }
                  catch (int)
                    {
                      CandidateValue[mm] = std::numeric_limits< C_FLOAT64 >::max();
                    }
                }

              //end external for loop
              BestFoundSoFar = fittest();
              u30 = 30; u10 = 10;
            }
          else
            {
              if ((u10 == 0) && (i - last_update > 10))
                {
                  for (int mm = (int) floor(PopulationSize * 0.9); mm < PopulationSize; mm++)
                    {
                      for (int jj = 0; jj < NumParameter; jj++)
                        {
                          try
                            {
                              // determine if linear or log scale
                              linear = FALSE; la = 1.0;

                              if ((*Maximum[jj] <= 0.0) || (*Minimum[jj] < 0.0)) linear = TRUE;
                              else
                                {
                                  la = log10(*Maximum[jj]) - log10(std::min(*Minimum[jj], std::numeric_limits< C_FLOAT64 >::epsilon()));

                                  if (la < 1.8) linear = TRUE;
                                }

                              // set it to a random value within the interval
                              if (linear)
                                individual[mm][jj] = *Minimum[jj] + pRand->getRandomCC() * (*Maximum[jj] - *Minimum[jj]);
                              else
                                individual[mm][jj] = *Minimum[jj] * pow(10.0, la * pRand->getRandomCC());
                            }
                          catch (int)
                            {
                              individual[mm][jj] = (*Maximum[jj] - *Minimum[jj]) * 0.5 + *Minimum[jj];
                            }
                        }

                      try
                        {
                          // calculate its fitness
                          for (int kk = 0; kk < NumParameter; kk++)
                            (*Parameter[kk])(individual[mm][kk]);

                          CandidateValue[mm] = mpOptProblem->calculate();
                        }
                      catch (int)
                        {
                          CandidateValue[mm] = std::numeric_limits< C_FLOAT64 >::max();
                        }
                    }

                  //end external for loop
                  BestFoundSoFar = fittest();
                  u10 = 10;
                  //u10=50;
                }
            }
        }
    } // end iteration of generations

  //store the combination of the BestFoundSoFar parameter values found so far
  mpOptProblem->setSolutionVariables(individual[BestFoundSoFar]);

  //set the  BestFoundSoFar function value
  mpOptProblem->setSolutionValue(CandidateValue[BestFoundSoFar]);

  //free memory space
  delete CrossPoint;
  delete WinScore;
  delete CandidateValue;

  std::cout << std::endl;
  std::cout << "GA has successfully done!" << std::endl;

  return 0;
}
Exemplo n.º 7
0
bool COptMethodSRES::optimise()
{
  bool Continue = true;
  size_t BestIndex = C_INVALID_INDEX;

#ifdef RANDOMIZE
  // Counters to determine whether the optimization process has stalled
  // They count the number of generations without advances.
  size_t Stalled10, Stalled20, Stalled40, Stalled80;
  Stalled10 = Stalled20 = Stalled40 = Stalled80 = 0;
#endif // RANDOMIZE

  if (!initialize())
    {
      if (mpCallBack)
        mpCallBack->finishItem(mhGenerations);

      return false;
    }

  // initialise the population
  Continue = creation(0);

  // get the index of the fittest
  BestIndex = fittest();

  if (BestIndex != C_INVALID_INDEX)
    {
      // and store that value
      mBestValue = mValue[BestIndex];
      Continue = mpOptProblem->setSolution(mBestValue, *mIndividual[BestIndex]);

      // We found a new best value lets report it.
      mpParentTask->output(COutputInterface::DURING);
    }

  if (!Continue)
    {
      if (mpCallBack)
        mpCallBack->finishItem(mhGenerations);

      cleanup();
      return true;
    }

  // ITERATE FOR gener GENERATIONS
#ifdef RANDOMIZE

  for (mGeneration = 2;
       mGeneration <= mGenerations && Continue;
       mGeneration++, Stalled10++, Stalled20++, Stalled40++, Stalled80++)
    {
      // perturb the population if we have stalled for a while
      if (Stalled80 > 80)
        {
          Continue = creation((size_t)(mPopulationSize * 0.2));
          Stalled10 = Stalled20 = Stalled40 = Stalled80 = 0;
        }
      else if (Stalled40 > 40)
        {
          Continue = creation((size_t)(mPopulationSize * 0.6));
          Stalled10 = Stalled20 = Stalled40 = 0;
        }
      else if (Stalled20 > 20)
        {
          Continue = creation((size_t)(mPopulationSize * 0.8));
          Stalled10 = Stalled20 = 0;
        }
      else if (Stalled10 > 10)
        {
          Continue = creation((size_t)(mPopulationSize * 0.9));
          Stalled10 = 0;
        }

#else

  for (mGeneration = 2;
       mGeneration <= mGenerations && Continue;
       mGeneration++)
    {
#endif // RANDOMIZE
      Continue = replicate();

      // select the most fit
      select();

      // get the index of the fittest
      BestIndex = fittest();

      if (BestIndex != C_INVALID_INDEX &&
          mValue[BestIndex] < mBestValue)
        {
#ifdef RANDOMIZE
          Stalled10 = Stalled20 = Stalled40 = Stalled80 = 0;
#endif // RANDOMIZE
          mBestValue = mValue[BestIndex];

          Continue = mpOptProblem->setSolution(mBestValue, *mIndividual[BestIndex]);

          // We found a new best value lets report it.
          mpParentTask->output(COutputInterface::DURING);
        }

      if (mpCallBack)
        Continue = mpCallBack->progressItem(mhGenerations);
    }

  if (mpCallBack)
    mpCallBack->finishItem(mhGenerations);

  return true;
}