コード例 #1
0
ファイル: Tribes.java プロジェクト: cernoiu-theo/Eva2-AL
  public void init() {
    //		System.out.println("TRIBES.init()");
    // Generate a swarm
    swarm =
        new TribesSwarm(
            this, range, initRange); // TODO initRange is hard coded equal to problem range
    // swarm.generateSwarm(initExplorerNb, initType, m_problem);

    //   swarm.displaySwarm(swarm,out);
    //  print("\n Best after init: "+swarm.Best.position.fitness,out);

    iter = 0;
    adapt = 0;
    informOption = -1;
    //        Hard coded option
    //        -1 = absolute best informant
    //        1 = relative (pseudo-gradient) best informant. For "niching"
    //       See also moveExplorer, which can be modified in order to avoid this parameter

    population.clear();
    population.addAll(swarm.toPopulation());
    population.init(); // necessary to allow for multi-runs

    if (m_Show) show();
  }
コード例 #2
0
ファイル: Tribes.java プロジェクト: cernoiu-theo/Eva2-AL
 public void incEvalCnt() {
   population.incrFunctionCalls();
   if (notifyAfter(population.getFunctionCalls())) {
     //			System.out.println("Notifying after " + population.getFunctionCalls());
     firePropertyChangedEvent(Population.nextGenerationPerformed);
   }
 }
コード例 #3
0
ファイル: Tribes.java プロジェクト: cernoiu-theo/Eva2-AL
  private void plotAll(Population pop) {
    // TODO
    double pos[], vel[];

    for (int i = 0; i < pop.size(); i++) {
      pos = ((TribesExplorer) pop.getEAIndividual(i)).getDoubleData();
      vel = ((TribesExplorer) pop.getEAIndividual(i)).getVelocity();
      plotIndy(pos, vel, i);
      //			hier weiter!
    }
  }
コード例 #4
0
ファイル: Tribes.java プロジェクト: cernoiu-theo/Eva2-AL
 /**
  * As TRIBES manages an own structured set of particles (the list of Tribes containing explorers
  * and memories), the setPopulation method is only telling Tribes the range of the indiviuals in
  * the beginning of the run, the individuals will be discarded.
  */
 public void setPopulation(Population pop) {
   if (pop == null) return;
   population = pop;
   if (population.get(0) instanceof InterfaceDataTypeDouble) {
     range = ((InterfaceDataTypeDouble) population.get(0)).getDoubleRange();
     setDimension(range.length);
   } else {
     System.err.println(
         "warning, TRIBES requires InterfaceESIndidivual instead of "
             + population.get(0).getClass()
             + ". Couldnt correctly init the problem range.");
   }
 }
コード例 #5
0
 /** Expects newPop to have correct number of generations set. */
 public void adaptGenerational(
     Population oldPop, Population selectedPop, Population newPop, boolean updateSelected) {
   // nothing to do? Oh yes, we can easily transfer the cma-params from the old to the new
   // population.
   if (!newPop.hasData(cmaParamsKey)) {
     if (!oldPop.hasData(cmaParamsKey))
       System.err.println("warning: no cma param set found (MutateESRankMuCMA!");
     else newPop.putData(cmaParamsKey, oldPop.getData(cmaParamsKey));
   }
   // newPop.addData(cmaParamsKey, oldPop.getData(cmaParamsKey));
   // newPop.addPopulationChangedEventListener(this); // listen to every population to be informed
   // about reinit events
 }
コード例 #6
0
  /**
   * Requires selected population to be sorted by fitness.
   *
   * @param params refering parameter set
   * @param iterations number of iterations performed
   * @param selected selected population
   * @return true if the parameters seem ok or were corrected, false if new parameters must be
   *     produced
   */
  private boolean testAndCorrectNumerics(
      CMAParamSet params, int iterations, Population selected) { // not much left here
    boolean corrected = true;
    /* Flat Fitness, Test if function values are identical */
    if (iterations > 1 && (selected.size() > 1)) {
      // selected pop is sorted
      if (nearlySame(
          selected.getEAIndividual(0).getFitness(),
          selected.getEAIndividual(selected.size() - 1).getFitness())) {
        if (TRACE_1)
          System.err.println(
              "flat fitness landscape, consider reformulation of fitness, step-size increased");
        params.sigma *= Math.exp(0.2 + params.c_sig / params.d_sig);
        //    			sigma=0.1;
      }
    }

    if (!checkValidDouble(params.sigma)) {
      System.err.println("Error, unstable sigma!");
      corrected = false;
      //        	params.sigma=params.firstSigma; // MK TODO
      //        	System.err.println(
    }

    /* Align (renormalize) scale C (and consequently sigma) */
    /* e.g. for infinite stationary state simulations (noise
     * handling needs to be introduced for that) */
    double fac = 1.;
    double minEig = 1e-12;
    double maxEig = 1e8;
    if (Mathematics.max(params.eigenvalues) < minEig)
      fac = 1. / Math.sqrt(Mathematics.max(params.eigenvalues));
    else if (Mathematics.min(params.eigenvalues) > maxEig)
      fac = 1. / Math.sqrt(Mathematics.min(params.eigenvalues));

    if (fac != 1.) {
      //    		System.err.println("Scaling by " + fac);
      params.sigma /= fac;
      for (int i = 0; i < params.meanX.length; ++i) {
        params.pathC[i] *= fac;
        params.eigenvalues[i] *= fac * fac;
        for (int j = 0; j <= i; ++j) {
          params.mC.set(i, j, params.mC.get(i, j) * fac * fac);
          if (i != j) params.mC.set(j, i, params.mC.get(i, j));
        }
      }
    }
    return corrected;
  } // Test...
コード例 #7
0
 public void initByPopulation(Population pop, boolean reset) {
   this.m_Population = (Population) pop.clone();
   if (reset) {
     this.m_Population.init();
     this.m_Problem.evaluate(this.m_Population);
     this.firePropertyChangedEvent(Population.nextGenerationPerformed);
   }
 }
コード例 #8
0
ファイル: Tribes.java プロジェクト: cernoiu-theo/Eva2-AL
 protected TribesExplorer positionToExplorer(TribesPosition pos) {
   TribesExplorer tmp = (TribesExplorer) population.get(0);
   if (tmp == null) System.err.println("Error in Tribes::positionToExplorer!");
   TribesExplorer indy = tmp.clone();
   indy.clearPosVel();
   indy.SetDoubleGenotype(pos.getPos());
   indy.SetFitness(pos.getFitness());
   return indy;
 }
コード例 #9
0
ファイル: Tribes.java プロジェクト: cernoiu-theo/Eva2-AL
 public AbstractEAIndividual getBestInd() {
   TribesPosition bestMemPos = swarm.getBestMemory().getPos();
   AbstractEAIndividual bestExp = population.getBestEAIndividual();
   if (bestMemPos.firstIsBetter(bestMemPos.getFitness(), bestExp.getFitness())) {
     AbstractEAIndividual indy = (AbstractEAIndividual) bestExp.clone();
     indy.SetFitness(bestMemPos.getFitness());
     ((InterfaceDataTypeDouble) indy).SetDoubleGenotype(bestMemPos.getPos());
     return indy;
   } else return bestExp;
 }
コード例 #10
0
 /**
  * Test condition of C (Auger&Hansen, CEC '05, stopping criterion conditioncov). Return true, if a
  * diagonal entry is <= 0 or >= d.
  *
  * @param d
  * @return true, if a diagonal entry is <= 0 or >= d, else false
  */
 public boolean testCCondition(Population pop, double d) {
   //	    if (min(diag(D)) <= 0) || (max(diag(D)) > 1e14*min(diag(D)))
   //		  stopflag(end+1) = {'warnconditioncov'};
   CMAParamSet params = (CMAParamSet) pop.getData(cmaParamsKey);
   Pair<Double, Double> minMax = params.mC.getMinMaxDiag();
   if ((minMax.head <= 0) || (minMax.tail >= d)) {
     if (TRACE_TEST) System.out.println("testCCondition hit");
     return true;
   } else return false;
 }
コード例 #11
0
  /** This method will optimize */
  public void optimize() {
    AbstractEAIndividual indy;
    Population original = (Population) this.m_Population.clone();
    double tmpD;
    InterfaceMutation tmpMut;

    for (int i = 0; i < this.m_Population.size(); i++) {
      indy = ((AbstractEAIndividual) this.m_Population.get(i));
      tmpD = indy.getMutationProbability();
      indy.setMutationProbability(1.0);
      if (mutator == null) indy.mutate();
      else mutator.mutate(indy);
      indy.setMutationProbability(tmpD);
    }
    this.m_Problem.evaluate(this.m_Population);
    for (int i = 0; i < this.m_Population.size(); i++) {
      if (((AbstractEAIndividual) original.get(i))
          .isDominatingDebConstraints(((AbstractEAIndividual) this.m_Population.get(i)))) {
        this.m_Population.remove(i);
        this.m_Population.add(i, original.get(i));
      } else {
        // else: mutation improved the individual
      }
    }
    this.m_Population.incrGeneration();
    //        for (int i = 0; i < this.m_Population.size(); i++) {
    //            indy1 = (AbstractEAIndividual) this.m_Population.get(i);
    //            indy2 = (AbstractEAIndividual)(indy1).clone();
    //            indy2.mutate();
    //            this.m_Problem.evaluate((AbstractEAIndividual) indy2);
    //            //indy2.SetFitness(0, indy2.evaulateAsMiniBits());
    //            this.m_Population.incrFunctionCalls();
    //            //if (indy2.getFitness(0) < indy1.getFitness(0)) {
    //            if (indy2.isDominating(indy1)) {
    //                this.m_Population.remove(i);
    //                this.m_Population.add(i, indy2);
    //            }
    //        }
    //        this.m_Population.incrGeneration();
    this.firePropertyChangedEvent(Population.nextGenerationPerformed);
  }
コード例 #12
0
ファイル: Tribes.java プロジェクト: cernoiu-theo/Eva2-AL
 /** This method is simply for debugging. */
 protected void show() {
   if (this.m_Plot == null) {
     //			InterfaceDataTypeDouble indy = (InterfaceDataTypeDouble)this.population.get(0);
     //			double[][] range = indy.getDoubleRange();
     //			double[] tmpD = new double[2];
     //			tmpD[0] = 0;
     //			tmpD[1] = 0;
     this.m_Plot =
         new eva2.gui.Plot("TRIBES " + population.getGeneration(), "x1", "x2", range[0], range[1]);
     //			this.m_Plot.setCornerPoints(range, 0);
   }
 }
コード例 #13
0
ファイル: Tribes.java プロジェクト: cernoiu-theo/Eva2-AL
 /**
  * Return a SolutionSet of TribesExplorers (AbstractEAIndividuals) of which some where memory
  * particles, thus the returned population is larger than the current population.
  *
  * @return a population of possible solutions.
  */
 public InterfaceSolutionSet getAllSolutions() {
   // return population and memories?
   Population all = (Population) population.clone();
   List<TribesPosition> mems = swarm.collectMem();
   for (Iterator<TribesPosition> iterator = mems.iterator(); iterator.hasNext(); ) {
     TribesPosition tp = iterator.next();
     all.add(positionToExplorer(tp));
   }
   all.SetFunctionCalls(population.getFunctionCalls());
   all.setGenerationTo(population.getGeneration());
   // all.addPopulation(pop);
   return new SolutionSet(population, all);
 }
コード例 #14
0
 /**
  * From Auger&Hansen, CEC '05, stopping criterion noeffectcoord.
  *
  * @param d
  * @return
  */
 public boolean testNoEffectCoord(Population pop, double d) {
   //		if any(xmean == xmean + 0.2*sigma*sqrt(diag(C)))
   //		stopflag(end+1) = {'warnnoeffectcoord'};
   boolean ret = false;
   CMAParamSet params = (CMAParamSet) pop.getData(cmaParamsKey);
   int i = 0;
   while ((i < params.meanX.length) && !ret) {
     ret =
         ret
             || (params.meanX[i]
                 == (params.meanX[i] + d * getSigma(params, i) * Math.sqrt(params.mC.get(i, i))));
     i++;
   }
   if (TRACE_TEST) if (ret) System.out.println("testNoEffectCoord hit");
   return ret;
 }
コード例 #15
0
 /**
  * From Auger&Hansen, CEC '05, stopping criterion TolX.
  *
  * @param tolX
  * @return
  */
 public boolean testAllDistBelow(Population pop, double tolX) {
   //		if all(sigma*(max(abs(pc), sqrt(diag(C)))) < stopTolX)
   boolean res = true;
   CMAParamSet params = (CMAParamSet) pop.getData(cmaParamsKey);
   int i = 0;
   while (res && i < params.meanX.length) {
     res =
         res
             && (getSigma(params, i)
                     * Math.max(Math.abs(params.pathC[i]), Math.sqrt(params.mC.get(i, i)))
                 < tolX);
     i++;
   }
   if (TRACE_TEST) if (res) System.out.println("testAllDistBelow hit");
   return res;
 }
コード例 #16
0
  /**
   * This method allows you to merge to populations into an archive. This method will add elements
   * from pop to the archive but will also remove elements from the archive if the archive target
   * size is exceeded.
   *
   * @param pop The population that may add Individuals to the archive.
   */
  public void addElementsToArchive(Population pop) {

    if (pop.getArchive() == null) pop.SetArchive(new Population());

    // test for each element in population if it
    // is dominating a element in the archive
    for (int i = 0; i < pop.size(); i++) {
      if (this.isDominant((AbstractEAIndividual) pop.get(i), pop.getArchive())) {
        this.addIndividualToArchive(
            (AbstractEAIndividual) ((AbstractEAIndividual) pop.get(i)).clone(), pop.getArchive());
      }
    }

    // Now clear the archive of surplus individuals
    Population archive = pop.getArchive();

    this.m_Cleaner.removeSurplusIndividuals(archive);
  }
コード例 #17
0
 /**
  * Retrieve the initial sigma for the given population and the user defined method. For the
  * halfRange case, -1 is returned, as the range is not available here but set in initializing the
  * CMAParams.
  *
  * @param initGen
  * @return
  */
 private double getInitSigma(Population initGen) {
   switch (initializeSig) {
     case avgInitialDistance:
       // scaled by average range as the measures are normed
       // return initGen.getPopulationMeasures(null)[0]*getAvgRange();
       // use euclidian measures without normation and scaling
       return initGen
           .getPopulationMeasures(new EuclideanMetric())[
           0]; // use euclidean metric which is not normed by range instead of phenotype metric
       // case halfRange: return getAvgRange(range)/2.;
     case userDefined:
       return userDefInitSig;
     case halfRange:
       return -0.5;
     case quarterRange:
       return -0.25;
   }
   throw new RuntimeException("Unknown initial sigma type!");
 }
コード例 #18
0
  /**
   * From Auger&Hansen, CEC '05, stopping criterion noeffectaxis.
   *
   * @param d
   * @param gen
   * @return
   */
  public boolean testNoChangeAddingDevAxis(Population pop, double d, int gen) {
    //		  if all(xmean == xmean + 0.1*sigma*BD(:,1+floor(mod(countiter,N))))
    //	    i = 1+floor(mod(countiter,N));
    //		stopflag(end+1) = {'warnnoeffectaxis'};
    CMAParamSet params = (CMAParamSet) pop.getData(cmaParamsKey);
    int dim = params.meanX.length;
    int k = gen % dim;
    double[] ev_k = params.mB.getColumn(k);
    Mathematics.svMult(
        Math.sqrt(params.eigenvalues[k]), ev_k, ev_k); // this is now e_k*v_k = BD(:,...)

    int i = 0;
    boolean res = true;
    while (res && (i < dim)) {
      res = res && (params.meanX[i] == (params.meanX[i] + d * getSigma(params, i) * ev_k[i]));
      i++;
    }
    if (TRACE_TEST) if (res) System.out.println("testNoChangeAddingDevAxis hit");
    return res;
  }
コード例 #19
0
 /** Override population evaluation to do some data output. */
 public void evaluatePopulationEnd(Population population) {
   // the translation on the first two dimensions
   // double delta = Math.sqrt(Math.pow(getTranslation(0, getCurrentProblemTime()), 2.) +
   // Math.pow(getTranslation(1, getCurrentProblemTime()), 2.));
   double delta =
       getTranslation(0, getCurrentProblemTime()) + getTranslation(1, getCurrentProblemTime());
   if (isExtraPlot() == true) {
     if (myplot != null) {
       myplot.jump();
     } else {
       if (TRACE) System.out.println("creating myplot instance");
       double[] tmpD = new double[2];
       tmpD[0] = 0;
       tmpD[1] = 0;
       // im not really certain about what tmpD is required for
       this.myplot = new Plot("population measures", "x1", "x2", tmpD, tmpD);
     }
     myplot.setConnectedPoint(population.getFunctionCalls(), delta, 0);
     // myplot.setUnconnectedPoint(population.getFunctionCalls(),
     // population.getPopulationMeasures()[2], 2);
   } else myplot = null;
 }
コード例 #20
0
  /* update C */
  private void updateCov(
      CMAParamSet params,
      double[] newPathC,
      double[] newMeanX,
      double hsig,
      int mu,
      Population selected) {
    double newVal = 0;
    int dim = newMeanX.length;
    double ccv = getCCov(params.weights, mu, dim);
    if (ccv > 0) {
      double mcv = CMAParamSet.getMuCov(params.weights, mu);
      /* (only upper triangle!) */
      /* update covariance matrix */
      // System.out.println("CCov " + getCCov(selected) + " Cc " + getCc() + " muCov " +
      // getMuCov(selected));
      for (int i = 0; i < dim; ++i)
        for (int j = 0; j <= i; ++j) {
          //                	oldVal = mC.get(i,j);
          newVal =
              (1 - ccv) * params.mC.get(i, j)
                  + ccv
                      * (1. / mcv)
                      * (newPathC[i] * newPathC[j]
                          + (1 - hsig) * getCc() * (2. - getCc()) * params.mC.get(i, j));
          checkValidDouble(newVal);
          params.mC.set(i, j, newVal);
          if (isRankMu()) {
            for (int k = 0; k < mu; ++k) {
              /*
               * additional rank mu
               * update
               */
              //                    	double[] x_k =
              // ((InterfaceDataTypeDouble)selected.getEAIndividual(k)).getDoubleData();
              double[] x_k =
                  AbstractEAIndividual.getDoublePositionShallow(selected.getEAIndividual(k));
              newVal =
                  params.mC.get(i, j)
                      + ccv
                          * (1 - 1. / mcv)
                          * params.weights[k]
                          * (x_k[i] - params.meanX[i])
                          * (x_k[j] - params.meanX[j])
                          / (getSigma(params, i) * getSigma(params, j)); // TODO right sigmas?
              checkValidDouble(newVal);
              params.mC.set(i, j, newVal);
            }
          }
        }
      // fill rest of C
      for (int i = 0; i < dim; ++i) {
        for (int j = i + 1; j < dim; ++j) {

          params.mC.set(i, j, params.mC.get(j, i));
        }
      }
      if (params.mC.get(0, 1) != params.mC.get(1, 0)) {
        System.err.println("WARNING, C is not symmetric!");
      }
      //            maxsqrtdiagC = Math.sqrt(math.max(math.diag(C)));
      //            minsqrtdiagC = Math.sqrt(math.min(math.diag(C)));
    } // update of C
  }
コード例 #21
0
ファイル: Tribes.java プロジェクト: cernoiu-theo/Eva2-AL
  public void optimize() {

    int initOption = 0;
    if (iter == 0) { // first iteration!
      if (initRange == null) {
        rangeInitType = 0;
      } else {
        rangeInitType = 1; // 1 means in initRange for a start
      }
      // * initOption Options: 0 - random, 1 - on the bounds, 2 - sunny spell, 3 - around a center
      // * rangeInitType for options 0,1: 1 means use initRange, 0 use default range
      swarm.generateSwarm(initExplorerNb, initOption, rangeInitType, m_problem);
    }
    iter++;

    m_problem.evaluatePopulationStart(population);
    swarm.setSwarmSize();
    // swarm.Best.positionPrev = swarm.Best.position;

    swarm.moveSwarm(
        range, new TribesParam(), informOption, m_problem); // *** HERE IT MOVES and EVALUATES
    // public void moveSwarm(double[][] range, int fitnessSize, TribesParam pb, TribesSwarm swarm,
    //      int informOption, AbstractOptimizationProblem prob) {

    if (Tribes.adaptOption != 0) { // perform adaption
      if (Tribes.adaptOption == 1) { // Just reinitialize the swarm
        adaptThreshold = iter - adapt;
        //   adaptMax=swarmSize;
        adaptMax = swarm.linkNb(swarm);
        if (adaptThreshold >= adaptMax) {
          if (swarm.getBestMemory().getPrevPos().getTotalError()
              <= swarm.getBestMemory().getPos().getTotalError()) {
            adapt = iter; // Memorize at which iteration adaptation occurs

            for (int i = 0; i < swarm.getTribeCnt(); i++) {
              swarm.reinitTribe(i, rangeInitType, m_problem);
            }
          }
        }
      } else //   if(swarm.Best.positionPrev.getTotalError()<=swarm.Best.position.getTotalError())
      {
        // Structural adaptations

        adaptThreshold = iter - adapt;
        //   adaptMax=swarmSize;
        adaptMax = swarm.linkNb(swarm);

        if (adaptThreshold >= adaptMax) {
          adapt = iter; // Memorize at which iteration adaptation occurs
          swarm.adaptSwarm(rangeInitType, m_problem); // Re´alise l'adaptation
        }
      }
    }
    population.clear();
    population.addAll(swarm.toPopulation());
    if (m_Show) plotAll(population);
    m_problem.evaluatePopulationEnd(population);

    //		this.population.incrFunctionCallsby(evals);
    this.population.incrGeneration();
    // this.firePropertyChangedEvent("NextGenerationPerformed");	// This is now done implicitely, as
    // after every evaluation, addEvals is called

    if (TRACE) {
      System.out.println("loop finished after " + population.getFunctionCalls() + " evaluations");
      // for (int i=0; i<population.size(); i++) System.out.println(" *
      // "+((TribesExplorer)population.get(i)).getStringRepresentation());
      System.out.println(
          " best: "
              + population.getBestEAIndividual().getStringRepresentation()
              + " - "
              + population.getBestEAIndividual().getFitness(0));
      System.out.println(
          "swarm contains " + swarm.numParticles() + " particles in iteration " + iter);
    }
  }
コード例 #22
0
 /**
  * After optimization start, this returns the initial sigma value actually employed.
  *
  * @return the initial sigma value actually employed
  */
 public double getFirstSigma(Population pop) {
   return ((CMAParamSet) pop.getData(cmaParamsKey)).firstSigma;
 }
コード例 #23
0
 public static double[] getMeanXOfPop(Population pop) {
   CMAParamSet params = (CMAParamSet) pop.getData(MutateESRankMuCMA.cmaParamsKey);
   if (params == null) return null;
   else return params.meanX;
 }
コード例 #24
0
 /**
  * calculate weighted mean of the selected population
  *
  * @param selectedPop
  * @return
  */
 private double[] calcMeanX(double[] weights, Population selectedPop) {
   return selectedPop.getCenterWeighted(weights);
 }
コード例 #25
0
  /**
   * Perform the main adaption of sigma and C using evolution paths. The evolution path is deduced
   * from the center of the selected population compared to the old mean value. See Hansen&Kern 04
   * for further information.
   *
   * @param oldGen
   * @param selectedP
   */
  public void adaptAfterSelection(Population oldGen, Population selectedP) {
    Population selectedSorted =
        selectedP.getSortedBestFirst(new AbstractEAIndividualComparator(-1));

    int mu, lambda;
    mu = selectedP.size();
    lambda = oldGen.size();
    int generation = oldGen.getGeneration();
    if (mu >= lambda) {
      // try to override by oldGen additional data:
      if (oldGen.hasData(EvolutionStrategies.esMuParam))
        mu = (Integer) oldGen.getData(EvolutionStrategies.esMuParam);
      if (oldGen.hasData(EvolutionStrategies.esLambdaParam))
        lambda = (Integer) oldGen.getData(EvolutionStrategies.esLambdaParam);
    }
    if (mu >= lambda) {
      mu = Math.max(1, lambda / 2);
      EVAERROR.errorMsgOnce(
          "Warning: invalid mu/lambda ratio! Setting mu to lambda/2 = "
              + mu
              + ", lambda = "
              + lambda);
    }
    CMAParamSet params;
    if (oldGen.getGeneration()
        <= 1) { // init new param set. At gen < 1 we shouldnt be called, but better do it once too
                // often
      if (oldGen.hasData(cmaParamsKey))
        params =
            CMAParamSet.initCMAParams(
                (CMAParamSet) oldGen.getData(cmaParamsKey),
                mu,
                lambda,
                oldGen,
                getInitSigma(oldGen));
      else params = CMAParamSet.initCMAParams(mu, lambda, oldGen, getInitSigma(oldGen));
    } else {
      if (!oldGen.hasData(cmaParamsKey)) {
        if (oldGen.getGeneration() > 1)
          EVAERROR.errorMsgOnce("Error: population lost cma parameters. Incompatible optimizer?");
        params = CMAParamSet.initCMAParams(mu, lambda, oldGen, getInitSigma(oldGen));
      } else params = (CMAParamSet) oldGen.getData(cmaParamsKey);
    }

    if (lambda == 1
        && (oldGen.size() == 1)
        && (selectedP.size() == 1)
        && (oldGen.getEAIndividual(0).equals(selectedP.getEAIndividual(0)))) {
      // nothing really happened, so do not adapt and just store default params
      lastParams = (CMAParamSet) params.clone();
      oldGen.putData(cmaParamsKey, params);
      selectedP.putData(cmaParamsKey, params);
      return;
    }

    if (TRACE_1) {
      System.out.println("WCMA adaptGenerational **********");
      //			System.out.println("newPop measures: " +
      // BeanInspector.toString(newPop.getPopulationMeasures()));
      System.out.println("mu_eff: " + CMAParamSet.getMuEff(params.weights, mu));
      System.out.println(params.toString());
      System.out.println("*********************************");
    }

    double[] newMeanX = calcMeanX(params.weights, selectedSorted);
    if (TRACE_1) System.out.println("newMeanX:  " + BeanInspector.toString(newMeanX));

    int dim = params.meanX.length;
    double[] BDz = new double[dim];
    for (int i = 0; i < dim; i++) {
        /* calculate xmean and BDz~N(0,C) */
      // Eq. 4 from HK04, most right term
      BDz[i] =
          Math.sqrt(CMAParamSet.getMuEff(params.weights, mu))
              * (newMeanX[i] - params.meanX[i])
              / getSigma(params, i);
    }
    //        if (TRACE_2) System.out.println("BDz is " + BeanInspector.toString(BDz));

    double[] newPathS = params.pathS.clone();
    double[] newPathC = params.pathC.clone();

    double[] zVect = new double[dim];
    /* calculate z := D^(-1) * B^(-1) * BDz into artmp, we could have stored z instead */
    for (int i = 0; i < dim; ++i) {
      double sum = 0.;
      for (int j = 0; j < dim; ++j) {
        sum += params.mB.get(j, i) * BDz[j]; // times B transposed, (Eq 4) in HK04
      }
      if (params.eigenvalues[i] < 0) {
        EVAERROR.errorMsgOnce(
            "Warning: negative eigenvalue in MutateESRankMuCMA! (possibly multiple cases)");
        zVect[i] = 0;
      } else {
        zVect[i] = sum / Math.sqrt(params.eigenvalues[i]);
        if (!checkValidDouble(zVect[i])) {
          System.err.println("Error, infinite zVect entry!");
          zVect[i] = 0; // TODO MK
        }
      }
    }

    /* cumulation for sigma (ps) using B*z */
    for (int i = 0; i < dim; ++i) {
      double sum = 0.;
      for (int j = 0; j < dim; ++j) sum += params.mB.get(i, j) * zVect[j];
      newPathS[i] =
          (1. - params.c_sig) * params.pathS[i]
              + Math.sqrt(params.c_sig * (2. - params.c_sig)) * sum;
      if (!checkValidDouble(newPathS[i])) {
        System.err.println("Error, infinite pathS!");
      }
    }
    //		System.out.println("pathS diff: " + BeanInspector.toString(Mathematics.vvSub(newPathS,
    // pathS)));
    //		System.out.println("newPathS is " + BeanInspector.toString(newPathS));

    double psNorm = Mathematics.norm(newPathS);

    double hsig = 0;
    if (psNorm / Math.sqrt(1. - Math.pow(1. - params.c_sig, 2. * generation)) / expRandStepLen
        < 1.4 + 2. / (dim + 1.)) {
      hsig = 1;
    }
    for (int i = 0; i < dim; ++i) {
      newPathC[i] =
          (1. - getCc()) * params.pathC[i] + hsig * Math.sqrt(getCc() * (2. - getCc())) * BDz[i];
      checkValidDouble(newPathC[i]);
    }

    // TODO missing: "remove momentum in ps"

    if (TRACE_1) {
      System.out.println("newPathC: " + BeanInspector.toString(newPathC));
      System.out.println("newPathS: " + BeanInspector.toString(newPathS));
    }

    if (TRACE_1) System.out.println("Bef: C is \n" + params.mC.toString());
    if (params.meanX == null) params.meanX = newMeanX;

    updateCov(params, newPathC, newMeanX, hsig, mu, selectedSorted);
    updateBD(params);

    if (TRACE_2) System.out.println("Aft: C is " + params.mC.toString());

    /* update of sigma */
    double sigFact = Math.exp(((psNorm / expRandStepLen) - 1) * params.c_sig / params.d_sig);
    if (Double.isInfinite(sigFact))
      params.sigma *= 10.; // in larger search spaces sigma tends to explode after init.
    else params.sigma *= sigFact;

    if (!testAndCorrectNumerics(params, generation, selectedSorted)) {
      // parameter seemingly exploded...
      params =
          CMAParamSet.initCMAParams(
              params,
              mu,
              lambda,
              params.meanX,
              ((InterfaceDataTypeDouble) oldGen.getEAIndividual(0)).getDoubleRange(),
              params.firstSigma);
    }

    if (TRACE_1) {
      System.out.println("sigma=" + params.sigma);
      System.out.print("psLen=" + (psNorm) + " ");
      outputParams(params, mu);
    }

    // take over data
    params.meanX = newMeanX;
    params.pathC = newPathC;
    params.pathS = newPathS;
    params.firstAdaptionDone = true;

    lastParams = (CMAParamSet) params.clone();
    oldGen.putData(cmaParamsKey, params);
    selectedP.putData(cmaParamsKey, params);
    //		if (TRACE_2) System.out.println("sampling around " + BeanInspector.toString(meanX));
  }