public static void main(String[] args) throws JMException, ClassNotFoundException {
    int numberOfVariables = 20;
    int populationSize = 10;
    int maxEvaluations = 1000000;

    Problem problem; // The problem to solve
    Algorithm algorithm; // The algorithm to use

    // problem = new Sphere("Real", numberOfVariables) ;
    // problem = new Easom("Real") ;
    // problem = new Griewank("Real", populationSize) ;
    // problem = new Schwefel("Real", numberOfVariables) ;
    problem = new Rosenbrock("Real", numberOfVariables);
    // problem = new Rastrigin("Real", numberOfVariables) ;

    algorithm = new CMAES(problem);

    /* Algorithm parameters*/
    algorithm.setInputParameter("populationSize", populationSize);
    algorithm.setInputParameter("maxEvaluations", maxEvaluations);

    /* Execute the Algorithm */
    long initTime = System.currentTimeMillis();
    SolutionSet population = algorithm.execute();
    long estimatedTime = System.currentTimeMillis() - initTime;
    System.out.println("Total execution time: " + estimatedTime);

    /* Log messages */
    System.out.println("Objectives values have been written to file FUN");
    population.printObjectivesToFile("FUN");
    System.out.println("Variables values have been written to file VAR");
    population.printVariablesToFile("VAR");
  } // main
  protected void generate(String folder, List<String> files, int totalOfFiles, int level)
      throws Exception {
    logger.info(
        "Generating Quality Indicators for "
            + folder
            + ". Finding a True Pareto-front file in the path");

    File parent = new File(folder);

    for (int i = 0; i < level; i++) {
      parent = parent.getParentFile();
    }

    String approxTrueParetoFrontPath = parent.getAbsolutePath() + File.separator + "PFAPPROX";

    if (!new File(approxTrueParetoFrontPath).exists()) {
      throw new Exception("You must to define a true Pareto-front before");
    }

    SolutionSet paretoFront = SolutionSetUtils.getFromFile(approxTrueParetoFrontPath);

    if (paretoFront.size() == 0) {
      throw new IllegalArgumentException("The Approximate Pareto-front cannot be empty");
    }

    int numberOfObjectives = paretoFront.get(0).getNumberOfObjectives();

    Problem p = new FakeProblem(numberOfObjectives);

    QualityIndicator qi = new QualityIndicator(p, approxTrueParetoFrontPath);

    for (String file : files) {
      generateQualityIndicators(qi, folder, file, paretoFront, totalOfFiles);
    }
  }
Пример #3
0
 /**
  * Apply a mutation operator to some particles in the swarm
  *
  * @throws jmetal.util.JMException
  */
 private void mopsoMutation(int actualIteration, int totalIterations) throws JMException {
   for (int i = 0; i < particles_.size(); i++) {
     if ((i % 6) == 0) polynomialMutation_.execute(particles_.get(i));
     // if (i % 3 == 0) { //particles_ mutated with a non-uniform mutation %3
     //  nonUniformMutation_.execute(particles_.get(i));
     // } else if (i % 3 == 1) { //particles_ mutated with a uniform mutation operator
     //  uniformMutation_.execute(particles_.get(i));
     // } else //particles_ without mutation
     // ;
   }
 } // mopsoMutation
Пример #4
0
  public static void main(String[] args) throws JMException, ClassNotFoundException {
    Problem problem; // The problem to solve
    Algorithm algorithm; // The algorithm to use
    Operator crossover; // Crossover operator
    Operator mutation; // Mutation operator
    Operator selection; // Selection operator

    // int bits ; // Length of bit string in the OneMax problem
    HashMap parameters; // Operator parameters

    int threads = 4; // 0 - use all the available cores
    IParallelEvaluator parallelEvaluator = new MultithreadedEvaluator(threads);

    // problem = new Sphere("Real", 10) ;
    problem = new Griewank("Real", 10);

    algorithm = new pgGA(problem, parallelEvaluator); // Generational GA

    /* Algorithm parameters*/
    algorithm.setInputParameter("populationSize", 100);
    algorithm.setInputParameter("maxEvaluations", 2500000);

    // Mutation and Crossover for Real codification
    parameters = new HashMap();
    parameters.put("probability", 0.9);
    parameters.put("distributionIndex", 20.0);
    crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover", parameters);

    parameters = new HashMap();
    parameters.put("probability", 1.0 / problem.getNumberOfVariables());
    parameters.put("distributionIndex", 20.0);
    mutation = MutationFactory.getMutationOperator("PolynomialMutation", parameters);

    /* Selection Operator */
    parameters = null;
    selection = SelectionFactory.getSelectionOperator("BinaryTournament", parameters);

    /* Add the operators to the algorithm*/
    algorithm.addOperator("crossover", crossover);
    algorithm.addOperator("mutation", mutation);
    algorithm.addOperator("selection", selection);

    /* Execute the Algorithm */
    long initTime = System.currentTimeMillis();
    SolutionSet population = algorithm.execute();
    long estimatedTime = System.currentTimeMillis() - initTime;
    System.out.println("Total execution time: " + estimatedTime);

    /* Log messages */
    System.out.println("Objectives values have been writen to file FUN");
    population.printObjectivesToFile("FUN");
    System.out.println("Variables values have been writen to file VAR");
    population.printVariablesToFile("VAR");
  } // main
Пример #5
0
  /**
   * Returns the minimum distance from a <code>Solution</code> to a <code>
   * SolutionSet according to the variable values</code>.
   *
   * @param solution The <code>Solution</code>.
   * @param solutionSet The <code>SolutionSet</code>.
   * @return The minimum distance between solution and the set.
   * @throws JMException
   */
  public double distanceToSolutionSetInSolutionSpace(Solution solution, SolutionSet solutionSet)
      throws JMException {
    // At start point the distance is the max
    double distance = Double.MAX_VALUE;

    // found the min distance respect to population
    for (int i = 0; i < solutionSet.size(); i++) {
      double aux = this.distanceBetweenSolutions(solution, solutionSet.get(i));
      if (aux < distance) distance = aux;
    } // for

    // ->Return the best distance
    return distance;
  } // distanceToSolutionSetInSolutionSpace
Пример #6
0
  /**
   * Constructor
   *
   * @param problem Problem to solve
   */
  public SMPSO(Problem problem, String trueParetoFront) throws FileNotFoundException {
    super(problem);
    hy_ = new Hypervolume();
    jmetal.qualityIndicator.util.MetricsUtil mu = new jmetal.qualityIndicator.util.MetricsUtil();
    trueFront_ = mu.readNonDominatedSolutionSet(trueParetoFront);
    trueHypervolume_ =
        hy_.hypervolume(
            trueFront_.writeObjectivesToMatrix(),
            trueFront_.writeObjectivesToMatrix(),
            problem_.getNumberOfObjectives());

    // Default configuration
    r1Max_ = 1.0;
    r1Min_ = 0.0;
    r2Max_ = 1.0;
    r2Min_ = 0.0;
    C1Max_ = 2.5;
    C1Min_ = 1.5;
    C2Max_ = 2.5;
    C2Min_ = 1.5;
    WMax_ = 0.1;
    WMin_ = 0.1;
    ChVel1_ = -1;
    ChVel2_ = -1;
  } // Constructor
Пример #7
0
  public static void main(String[] args) {
    try {
      Datos datos = Datos.cargarDatosDeArgs(args);

      String salidaFun = "SALIDA_FUN_GREEDY.txt";
      String salidaVar = "SALIDA_VAR_GREEDY.txt";

      if (args.length >= 7) {
        salidaFun = args[8];
      }

      if (args.length >= 8) {
        salidaVar = args[9];
      }

      System.out.println("---- Parametros a utilizar ----");
      System.out.println("Salidas: " + salidaFun + ", " + salidaVar);

      double[] params = {0.0, 0.05, 0.1, 0.15, 0.20, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5};

      SolutionSet solSetGreedy = new SolutionSet(params.length);
      Problem problem = new Problema(datos);
      for (double p : params) {
        Permutation resultado = ejecutarGreedy(datos, p);
        Solution solucionGreedy = new Solution(problem, new Variable[] {resultado});

        problem.evaluateConstraints(solucionGreedy);
        problem.evaluate(solucionGreedy);

        solSetGreedy.add(solucionGreedy);

        // Imprimo y genero datos de la misma forma que el AE

        System.out.println("F1: " + solucionGreedy.getObjective(0));
        System.out.println("F2: " + solucionGreedy.getObjective(1));
        System.out.println("----");
      }

      ((Problema) problem).imprimirSolucion("SALIDA_GREEDY.txt", solSetGreedy);
      solSetGreedy.printFeasibleFUN(salidaFun);
      solSetGreedy.printFeasibleVAR(salidaVar);

    } catch (Throwable t) {
      System.out.println(t.getMessage());
      return;
    }
  }
  /**
   * Performs the operation
   *
   * @param object Object representing a SolutionSet.
   * @return the best solution found
   */
  public Object execute(Object object) {
    SolutionSet solutionSet = (SolutionSet) object;

    if (solutionSet.size() == 0) {
      return null;
    }
    int worstSolution;

    worstSolution = 0;

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

    return worstSolution;
  } // Execute
Пример #9
0
 private List<Solution> copyList(SolutionSet population) {
   List<Solution> copySolutions = new ArrayList<Solution>();
   Iterator<Solution> iterator = population.iterator();
   while (iterator.hasNext()) {
     Solution solution = (Solution) iterator.next();
     copySolutions.add(solution);
   }
   return copySolutions;
 }
Пример #10
0
  /**
   * Update the speed of each particle
   *
   * @throws JMException
   */
  private void computeSpeed(int iter, int miter) throws JMException, IOException {
    double r1, r2, W, C1, C2;
    double wmax, wmin, deltaMax, deltaMin;
    XReal bestGlobal;

    for (int i = 0; i < swarmSize_; i++) {
      XReal particle = new XReal(particles_.get(i));
      XReal bestParticle = new XReal(best_[i]);

      // Select a global best_ for calculate the speed of particle i, bestGlobal

      Solution one, two;
      int pos1 = PseudoRandom.randInt(0, leaders_.size() - 1);
      int pos2 = PseudoRandom.randInt(0, leaders_.size() - 1);
      one = leaders_.get(pos1);
      two = leaders_.get(pos2);

      if (crowdingDistanceComparator_.compare(one, two) < 1) {
        bestGlobal = new XReal(one);
      } else {
        bestGlobal = new XReal(two);
        // Params for velocity equation
      }

      // Juanjo, si usamos esto en lugar de lo de antes va de pena
      // bestGlobal = new XReal(leaders_.get(0)) ;

      r1 = PseudoRandom.randDouble(r1Min_, r1Max_);
      r2 = PseudoRandom.randDouble(r2Min_, r2Max_);
      C1 = PseudoRandom.randDouble(C1Min_, C1Max_);
      C2 = PseudoRandom.randDouble(C2Min_, C2Max_);
      W = PseudoRandom.randDouble(WMin_, WMax_);
      //
      wmax = WMax_;
      wmin = WMin_;

      for (int var = 0; var < particle.getNumberOfDecisionVariables(); var++) {
        // Computing the velocity of this particle
        speed_[i][var] =
            velocityConstriction(
                constrictionCoefficient(C1, C2)
                    * (inertiaWeight(iter, miter, wmax, wmin) * speed_[i][var]
                        + C1 * r1 * (bestParticle.getValue(var) - particle.getValue(var))
                        + C2 * r2 * (bestGlobal.getValue(var) - particle.getValue(var))),
                deltaMax_, // [var],
                deltaMin_, // [var],
                var,
                i);
      }
    }
  } // computeSpeed
Пример #11
0
  /**
   * Update the position of each particle
   *
   * @throws jmetal.util.JMException
   */
  private void computeNewPositions() throws JMException {
    for (int i = 0; i < swarmSize_; i++) {
      XReal particle = new XReal(particles_.get(i));
      for (int var = 0; var < particle.getNumberOfDecisionVariables(); var++) {
        particle.setValue(var, particle.getValue(var) + speed_[i][var]);

        if (particle.getValue(var) < problem_.getLowerLimit(var)) {
          particle.setValue(var, problem_.getLowerLimit(var));
          speed_[i][var] = speed_[i][var] * ChVel1_; //
        }
        if (particle.getValue(var) > problem_.getUpperLimit(var)) {
          particle.setValue(var, problem_.getUpperLimit(var));
          speed_[i][var] = speed_[i][var] * ChVel2_; //
        }
      }
    }
  } // computeNewPositions
Пример #12
0
  private void computeNewPositions_parallel(int i) throws JMException {
		//Variable[] particle = particles_.get(i).getDecisionVariables();
	  XReal particle = new XReal(particles_.get(i)) ;
	  //particle.move(speed_[i]);
	  for (int var = 0; var < particle.size(); var++) {
		  particle.setValue(var, particle.getValue(var) +  speed_[i][var]) ;

		  if (particle.getValue(var) < problem_.getLowerLimit(var)) {
			  particle.setValue(var, problem_.getLowerLimit(var));
			  speed_[i][var] = speed_[i][var] * ChVel1_; //    
		  }
		  if (particle.getValue(var) > problem_.getUpperLimit(var)) {
			  particle.setValue(var, problem_.getUpperLimit(var));
			  speed_[i][var] = speed_[i][var] * ChVel2_; //   
		  }
	  }
  }
Пример #13
0
  /**
   * Returns a matrix with distances between solutions in a <code>SolutionSet</code>.
   *
   * @param solutionSet The <code>SolutionSet</code>.
   * @return a matrix with distances.
   */
  public double[][] distanceMatrix(SolutionSet solutionSet) {
    Solution solutionI, solutionJ;

    // The matrix of distances
    double[][] distance = new double[solutionSet.size()][solutionSet.size()];
    // -> Calculate the distances
    for (int i = 0; i < solutionSet.size(); i++) {
      distance[i][i] = 0.0;
      solutionI = solutionSet.get(i);
      for (int j = i + 1; j < solutionSet.size(); j++) {
        solutionJ = solutionSet.get(j);
        distance[i][j] = this.distanceBetweenObjectives(solutionI, solutionJ);
        distance[j][i] = distance[i][j];
      } // for
    } // for

    // ->Return the matrix of distances
    return distance;
  } // distanceMatrix
Пример #14
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
   * @throws JMException
   */
  @Override
  public SolutionSet execute() throws JMException, ClassNotFoundException {
    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++) {
      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));
      leaders_.add(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_) {
      System.out.println("Iteration: " + iteration_ + " times");
      try {
        // Compute the speed_
        computeSpeed(iteration_, maxIterations_);
      } catch (IOException ex) {
        Logger.getLogger(SMPSOhv.class.getName()).log(Level.SEVERE, null, ex);
      }

      // 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);
      }

      // Actualize the archive
      for (int i = 0; i < particles_.size(); i++) {
        Solution particle = new Solution(particles_.get(i));
        leaders_.add(particle);
      }
      if (leaders_.size() < archiveSize_) leaders_.computeHVContribution();

      // Actualize 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 remeber
          Solution particle = new Solution(particles_.get(i));
          best_[i] = particle;
        }
      }

      iteration_++;
    }
    return this.leaders_;
  } // execute
Пример #15
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  
   * @throws JMException 
   */
  public SolutionSet execute() throws JMException, ClassNotFoundException {
    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)))
        globalBest_ = new Solution(particle) ;
    }

    //-> Step2. Initialize the speed_ of each particle to 0
    for (int i = 0; i < particlesSize_; i++) {
      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 bestIndividual = (Integer)findBestSolution_.execute(particles_) ;
      try {
        //Compute the speed_
        computeSpeed(iteration_, maxIterations_);
      } catch (IOException ex) {
        Logger.getLogger(PSO.class.getName()).log(Level.SEVERE, null, ex);
      }

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

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

      //Evaluate the new particles_ in new positions
      evaluations_ += particles_.size();
      finish {		// 
    	  async {
    		  for (int i = 0; i < particles_.size(); i++) {
    			  evaluate_parallel_internal(i);
    		  }
    	  }
      }

      //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));
          localBest_[i] = particle;
        } // if
      	if ((particles_.get(i).getObjective(0) < globalBest_.getObjective(0))) {
          Solution particle = new Solution(particles_.get(i));
          globalBest_ = particle;
        } // if
      	
      }
      iteration_++;
    }
    
    // Return a population with the best individual
    SolutionSet resultPopulation = new SolutionSet(1) ;
    resultPopulation.add(particles_.get((Integer)findBestSolution_.execute(particles_))) ;
    
    return resultPopulation ;
  } // execute
Пример #16
0
  /**
   * Assigns crowding distances to all solutions in a <code>SolutionSet</code>.
   *
   * @param solutionSet The <code>SolutionSet</code>.
   * @param nObjs Number of objectives.
   */
  public void crowdingDistanceAssignment(SolutionSet solutionSet, int nObjs) {
    int size = solutionSet.size();

    if (size == 0) return;

    if (size == 1) {
      solutionSet.get(0).setCrowdingDistance(Double.POSITIVE_INFINITY);
      return;
    } // if

    if (size == 2) {
      solutionSet.get(0).setCrowdingDistance(Double.POSITIVE_INFINITY);
      solutionSet.get(1).setCrowdingDistance(Double.POSITIVE_INFINITY);
      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
      front.sort(new ObjectiveComparator(i));
      objetiveMinn = front.get(0).getObjective(i);
      objetiveMaxn = front.get(front.size() - 1).getObjective(i);

      // Set de crowding distance
      front.get(0).setCrowdingDistance(Double.POSITIVE_INFINITY);
      front.get(size - 1).setCrowdingDistance(Double.POSITIVE_INFINITY);

      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
  } // crowdingDistanceAssing
Пример #17
0
  /**
   * @param args Command line arguments. The first (optional) argument specifies the problem to
   *     solve.
   * @throws JMException
   */
  public static void main(String[] args) throws JMException, IOException, ClassNotFoundException {
    Problem problem; // The problem to solve
    Algorithm algorithm; // The algorithm to use
    Operator crossover; // Crossover operator
    Operator mutation; // Mutation operator
    Operator selection; // Selection operator

    QualityIndicator indicators; // Object to get quality indicators

    HashMap parameters; // Operator parameters

    // Logger object and file to store log messages
    logger_ = Configuration.logger_;
    fileHandler_ = new FileHandler("FastPGA_main.log");
    logger_.addHandler(fileHandler_);

    indicators = null;
    if (args.length == 1) {
      Object[] params = {"Real"};
      problem = (new ProblemFactory()).getProblem(args[0], params);
    } // if
    else if (args.length == 2) {
      Object[] params = {"Real"};
      problem = (new ProblemFactory()).getProblem(args[0], params);
      indicators = new QualityIndicator(problem, args[1]);
    } // if
    else { // Default problem
      problem = new Kursawe("Real", 3);
      // problem = new Kursawe("BinaryReal", 3);
      // problem = new Water("Real");
      // problem = new ZDT1("ArrayReal", 100);
      // problem = new ConstrEx("Real");
      // problem = new DTLZ1("Real");
      // problem = new OKA2("Real") ;
    } // else

    algorithm = new FastPGA(problem);

    algorithm.setInputParameter("maxPopSize", 100);
    algorithm.setInputParameter("initialPopulationSize", 100);
    algorithm.setInputParameter("maxEvaluations", 25000);
    algorithm.setInputParameter("a", 20.0);
    algorithm.setInputParameter("b", 1.0);
    algorithm.setInputParameter("c", 20.0);
    algorithm.setInputParameter("d", 0.0);

    // Parameter "termination"
    // If the preferred stopping criterium is PPR based, termination must
    // be set to 0; otherwise, if the algorithm is intended to iterate until
    // a give number of evaluations is carried out, termination must be set to
    // that number
    algorithm.setInputParameter("termination", 1);

    // Mutation and Crossover for Real codification
    parameters = new HashMap();
    parameters.put("probability", 0.9);
    parameters.put("distributionIndex", 20.0);
    crossover = CrossoverFactory.getCrossoverOperator("SBXCrossover", parameters);
    // crossover.setParameter("probability",0.9);
    // crossover.setParameter("distributionIndex",20.0);

    parameters = new HashMap();
    parameters.put("probability", 1.0 / problem.getNumberOfVariables());
    parameters.put("distributionIndex", 20.0);
    mutation = MutationFactory.getMutationOperator("PolynomialMutation", parameters);
    // Mutation and Crossover for Binary codification

    parameters = new HashMap();
    parameters.put("comparator", new FPGAFitnessComparator());
    selection = new BinaryTournament(parameters);

    algorithm.addOperator("crossover", crossover);
    algorithm.addOperator("mutation", mutation);
    algorithm.addOperator("selection", selection);

    long initTime = System.currentTimeMillis();
    SolutionSet population = algorithm.execute();
    long estimatedTime = System.currentTimeMillis() - initTime;

    // Result messages
    logger_.info("Total execution time: " + estimatedTime + "ms");
    logger_.info("Variables values have been writen to file VAR");
    population.printVariablesToFile("VAR");
    logger_.info("Objectives values have been writen to file FUN");
    population.printObjectivesToFile("FUN");

    if (indicators != null) {
      logger_.info("Quality indicators");
      logger_.info("Hypervolume: " + indicators.getHypervolume(population));
      logger_.info("GD         : " + indicators.getGD(population));
      logger_.info("IGD        : " + indicators.getIGD(population));
      logger_.info("Spread     : " + indicators.getSpread(population));
      logger_.info("Epsilon    : " + indicators.getEpsilon(population));

      int evaluations = ((Integer) algorithm.getOutputParameter("evaluations")).intValue();
      logger_.info("Speed      : " + evaluations + " evaluations");
    } // if
  } // main
Пример #18
0
 /**
  * Execute the ElitistES algorithm
 * @throws JMException 
  */
  public SolutionSet execute() throws JMException, ClassNotFoundException {
    int maxEvaluations ;
    int evaluations    ;

    SolutionSet population          ;
    SolutionSet offspringPopulation ;  

    Operator   mutationOperator ;
    Comparator comparator       ;
    
    comparator = new ObjectiveComparator(0) ; // Single objective comparator
    
    // Read the params
    maxEvaluations = ((Integer)this.getInputParameter("maxEvaluations")).intValue();                
   
    // Initialize the variables
    population          = new SolutionSet(mu_) ;   
    offspringPopulation = new SolutionSet(mu_ + lambda_) ;
    
    evaluations  = 0;                

    // Read the operators
    mutationOperator  = this.operators_.get("mutation");

    System.out.println("(" + mu_ + " + " + lambda_+")ES") ;
     
    // Create the parent population of mu solutions
    Solution newIndividual;
    for (int i = 0; i < mu_; i++) {
      newIndividual = new Solution(problem_);                    
      evaluations++;
      population.add(newIndividual);
    } //for
    
    finish {
	// 
    	async {
    		for (int i = 0; i < mu_; i++) {
    			evaluate_internal(population, i, null);
    		}
    	}
    }
     
    // Main loop
    int offsprings ;
    offsprings = lambda_ / mu_ ; 
    while (evaluations < maxEvaluations) {
      // STEP 1. Generate the mu+lambda population
      for (int i = 0; i < mu_; i++) {
        for (int j = 0; j < offsprings; j++) {
          Solution offspring = new Solution(population.get(i)) ;
          offspringPopulation.add(offspring) ;
          evaluations ++ ;
        } // for
      } // for
      
      finish {
	// 
      	async {
      		for (int i = 0; i < mu_*offsprings; i++) {
      			evaluate_internal(offspringPopulation, i, mutationOperator);
      		}
      	}
      }
       
      
      // STEP 2. Add the mu individuals to the offspring population
      for (int i = 0 ; i < mu_; i++) {
        offspringPopulation.add(population.get(i)) ;
      } // for
      population.clear() ;

      // STEP 3. Sort the mu+lambda population
      offspringPopulation.sort(comparator) ;
            
      // STEP 4. Create the new mu population
      for (int i = 0; i < mu_; i++)
        population.add(offspringPopulation.get(i)) ;

      System.out.println("Evaluation: " + evaluations + " Fitness: " + 
          population.get(0).getObjective(0)) ; 

      // STEP 6. Delete the mu+lambda population
      offspringPopulation.clear() ;
    } // while
    
    // Return a population with the best individual
    SolutionSet resultPopulation = new SolutionSet(1) ;
    resultPopulation.add(population.get(0)) ;
    
Пример #19
0
  } // execute
  
  private void evaluate_internal(SolutionSet s, int i, Operator mutationOperator) throws JMException, ClassNotFoundException {
	  Solution sol = s.get(i);
	  if(mutationOperator != null) mutationOperator.execute(sol);
Пример #20
0
  /**
   * Update the speed of each particle
   * @throws JMException 
   */
  private void computeSpeed(int iter, int miter) throws JMException, IOException {
    double r1, r2 ;
    //double W ;
    double C1, C2;
    double wmax, wmin, deltaMax, deltaMin;
    XReal bestGlobal;

  	bestGlobal = new XReal(globalBest_) ;

    for (int i = 0; i < particlesSize_; i++) {
    	XReal particle = new XReal(particles_.get(i)) ;
    	XReal bestParticle = new XReal(localBest_[i]) ;

      //int bestIndividual = (Integer)findBestSolution_.execute(particles_) ;

      C1Max_ = 2.5;
      C1Min_ = 1.5;
      C2Max_ = 2.5;
      C2Min_ = 1.5;

      r1 = PseudoRandom.randDouble(r1Min_, r1Max_);
      r2 = PseudoRandom.randDouble(r2Min_, r2Max_);
      C1 = PseudoRandom.randDouble(C1Min_, C1Max_);
      C2 = PseudoRandom.randDouble(C2Min_, C2Max_);
      //W =  PseudoRandom.randDouble(WMin_, WMax_);
      //

      WMax_ = 0.9;
      WMin_ = 0.9;
      ChVel1_ = 1.0;
      ChVel2_ = 1.0;
      
      C1 = 2.5 ;
      C2 = 1.5 ;
      
      wmax = WMax_;
      wmin = WMin_;
/*
      for (int var = 0; var < particle.size(); var++) {
        //Computing the velocity of this particle 
        speed_[i][var] = velocityConstriction(constrictionCoefficient(C1, C2) *
          (inertiaWeight(iter, miter, wmax, wmin) *
          speed_[i][var] +
          C1 * r1 * (bestParticle.getValue(var) - particle.getValue(var)) +
          C2 * r2 * (bestGlobal.getValue(var) -
          particle.getValue(var))), deltaMax_,
          deltaMin_, //[var], 
          var,
          i);
      }
*/
      C1 = 1.5 ;
      C2 = 1.5 ;
      double W = 0.9 ;
      for (int var = 0; var < particle.size(); var++) {
        //Computing the velocity of this particle 
        speed_[i][var] = inertiaWeight(iter, miter, wmax, wmin) * speed_[i][var] +
          C1 * r1 * (bestParticle.getValue(var) - particle.getValue(var)) +
          C2 * r2 * (bestGlobal.getValue(var) - particle.getValue(var)) ;
      }
    }
  } // computeSpeed
Пример #21
0
  /**
   * Runs the NSGA-II algorithm.
   *
   * @return a <code>SolutionSet</code> that is a set of non dominated solutions as a result of the
   *     algorithm execution
   * @throws JMException
   */
  public SolutionSet execute() throws JMException, ClassNotFoundException {
    int populationSize;
    int maxEvaluations;
    int evaluations;

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

    SolutionSet population;
    SolutionSet offspringPopulation;
    SolutionSet union;

    Distance distance = new Distance();

    // Read the parameters
    populationSize = ((Integer) getInputParameter("populationSize")).intValue();
    maxEvaluations = ((Integer) getInputParameter("maxEvaluations")).intValue();
    indicators = (QualityIndicator) getInputParameter("indicators");

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

    // Read the operators
    List<Operator> mutationOperators = new ArrayList<Operator>();
    mutationOperators.add(operators_.get("oneNoteMutation"));
    mutationOperators.add(operators_.get("harmonyNoteToPitch"));
    mutationOperators.add(operators_.get("swapHarmonyNotes"));
    mutationOperators.add(operators_.get("melodyNoteToHarmonyNote"));
    mutationOperators.add(operators_.get("pitchSpaceMutation"));
    Operator crossoverOperator = operators_.get("crossover");
    Operator selectionOperator = operators_.get("selection");

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

    int changeCount = 0;

    // Generations ...
    // while ((evaluations < maxEvaluations) && changeCount < 10 *
    // populationSize) {
    while ((evaluations < maxEvaluations)) {
      List<Solution> copySolutions = copyList(population);
      // Create the offSpring solutionSet
      offspringPopulation = new SolutionSet(populationSize);
      Solution[] parents = new Solution[2];
      for (int i = 0; i < (populationSize / 2); i++) {
        if (evaluations < maxEvaluations) {
          // obtain parents
          parents[0] = (Solution) selectionOperator.execute(population);
          parents[1] = (Solution) selectionOperator.execute(population);
          Solution[] offSpring = (Solution[]) crossoverOperator.execute(parents);
          for (Operator operator : mutationOperators) {
            operator.execute(offSpring[0]);
            operator.execute(offSpring[1]);
          }
          if (decorated) {
            decorator.decorate(offSpring[0]);
            decorator.decorate(offSpring[1]);
          }
          problem_.evaluate(offSpring[0]);
          problem_.evaluateConstraints(offSpring[0]);
          problem_.evaluate(offSpring[1]);
          problem_.evaluateConstraints(offSpring[1]);
          offspringPopulation.add(offSpring[0]);
          offspringPopulation.add(offSpring[1]);
          evaluations += 2;
        }
      }

      // Create the solutionSet union of solutionSet and offSpring
      union = ((SolutionSet) population).union(offspringPopulation);

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

      int remain = populationSize;
      int index = 0;
      SolutionSet front = null;
      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(front.get(k));
        }

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

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

      // 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());
        front.sort(new jmetal.util.comparators.CrowdingComparator());
        for (int k = 0; k < remain; k++) {
          population.add(front.get(k));
        }

        remain = 0;
      }

      // 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.
      if ((indicators != null) && (requiredEvaluations == 0)) {
        double HV = indicators.getHypervolume(population);
        double p = indicators.getTrueParetoFrontHypervolume();
        if (HV >= (0.98 * indicators.getTrueParetoFrontHypervolume())) {
          requiredEvaluations = evaluations;
        }
      }
      // check changes pareto front
      // SolutionSet paretoFront = ranking.getSubfront(0);
      List<Solution> frontSolutions = copyList(population);
      boolean changed = hasPopulationChanged(copySolutions, frontSolutions);
      LOGGER.fine(
          "Population changed: "
              + changed
              + ", evaluations: "
              + evaluations
              + ", change count:"
              + changeCount);
      if (changed) {
        changeCount = 0;
      } else {
        changeCount++;
      }
    }

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

    // Return the first non-dominated front
    Ranking ranking = new Ranking(population);
    return ranking.getSubfront(0);
  }
Пример #22
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
   * @throws jmetal.util.JMException
   */
  public SolutionSet execute() throws JMException, ClassNotFoundException {
    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++) {
      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));
      leaders_.add(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());

    // -> Step 7. Iterations ..
    while (iteration_ < maxIterations_) {
      try {
        // Compute the speed_
        computeSpeed(iteration_, maxIterations_);
      } catch (IOException ex) {
        Logger.getLogger(SMPSO.class.getName()).log(Level.SEVERE, null, ex);
      }

      // 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);
      }

      // Actualize the archive
      for (int i = 0; i < particles_.size(); i++) {
        Solution particle = new Solution(particles_.get(i));
        leaders_.add(particle);
      }

      // Actualize 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 remeber
          Solution particle = new Solution(particles_.get(i));
          best_[i] = particle;
        }
      }

      // Assign crowding distance to the leaders_
      distance_.crowdingDistanceAssignment(leaders_, problem_.getNumberOfObjectives());
      iteration_++;
      /*
            if ((iteration_ % 1) == 0) {
              leaders_.printObjectivesOfValidSolutionsToFile("FUNV"+iteration_) ;
              leaders_.printObjectivesToFile("FUN"+iteration_) ;
              leaders_.printVariablesToFile("VAR"+iteration_) ;
            }
      */
    }
    // leaders_.printObjectivesOfValidSolutionsToFile("FUNV.SMPSO") ;
    leaders_.printFeasibleFUN("FUN_SMPSO");

    return this.leaders_;
  } // execute
Пример #23
0
  private void evaluate_parallel_internal(int i) throws JMException, ClassNotFoundException {
	  Solution particle = particles_.get(i);
      problem_.evaluate(particle);
  }
Пример #24
0
  /** @param args the command line arguments -- modelname, alg_name, evaluation_times, [runid] */
  public static void main(String[] args) throws Exception {

    try {
      String name = args[0];
      URL location = Main.class.getProtectionDomain().getCodeSource().getLocation();
      String loc = location.toString();
      String project_path =
          loc.substring(5, loc.lastIndexOf("SPL/")) + "SPL/"; // with '/' at the end
      String fm = project_path + "dimacs_data/" + name + ".dimacs";
      String augment = fm + ".augment";
      String dead = fm + ".dead";
      String mandatory = fm + ".mandatory";
      String seed = fm + ".richseed";
      String opfile = fm + ".sipop";

      Problem p = new ProductLineProblem(fm, augment, mandatory, dead, seed);
      //            Problem p = new ProductLineProblemNovelPrep(fm, augment, mandatory, dead, seed,
      // opfile);
      //            GroupedProblem.grouping((ProductLineProblem) p, 100); System.exit(0);
      Algorithm a;
      int evaluation_times = Integer.parseInt(args[2]);
      String alg_name = args[1];
      String runid = "";
      if (args.length >= 4) {
        runid = args[3];
      }

      switch (alg_name) {
        case "IBEA":
          a = new SPL_SettingsIBEA(p).configureICSE2013(evaluation_times);
          break;
        case "SIPIBEA":
          a = new SPL_SettingsIBEA(p).configureSIPIBEA(evaluation_times);
          break;
        case "SPEA2":
          a = new SPL_SettingsEMOs(p).configureSPEA2(evaluation_times);
          break;
        case "NSGA2":
          a = new SPL_SettingsEMOs(p).configureNSGA2(evaluation_times);
          break;
        case "IBEASEED":
          a = new SPL_SettingsIBEA(p).configureIBEASEED(evaluation_times);
          break;
        case "SATIBEA":
          // a = new SPL_SettingsIBEA(p).configureICSE15(1000, fm, ((ProductLineProblem)
          // p).getNumFeatures(),
          // ((ProductLineProblem) p).getConstraints());
          a =
              new SPL_SettingsIBEA(p)
                  .configureSATIBEA(
                      evaluation_times,
                      fm,
                      ((ProductLineProblem) p).getNumFeatures(),
                      ((ProductLineProblem) p).getConstraints());
          break;
        default:
          a = new SPL_SettingsIBEA(p).configureICSE2013(evaluation_times);
      }

      long start = System.currentTimeMillis();
      SolutionSet pop = a.execute();
      float total_time = (System.currentTimeMillis() - start) / 1000.0f;

      String file_tag =
          name + "_" + alg_name + '_' + evaluation_times / 1000 + "k_" + runid + ".txt";
      String file_path = project_path + "j_res/" + file_tag;
      File file = new File(file_path);

      if (!file.exists()) {
        file.createNewFile();
      }

      FileWriter fw = new FileWriter(file.getAbsoluteFile());
      BufferedWriter bw = new BufferedWriter(fw);

      for (int i = 0; i < pop.size(); i++) {
        Variable v = pop.get(i).getDecisionVariables()[0];
        bw.write((Binary) v + "\n");
        System.out.println("Conf" + (i + 1) + ": " + (Binary) v + " ");
      }

      bw.write("~~~\n");

      for (int i = 0; i < pop.size(); i++) {
        Variable v = pop.get(i).getDecisionVariables()[0];
        for (int j = 0; j < pop.get(i).getNumberOfObjectives(); j++) {
          bw.write(pop.get(i).getObjective(j) + " ");
          System.out.print(pop.get(i).getObjective(j) + " ");
        }
        bw.write("\n");
        System.out.println("");
      }

      System.out.println(total_time);
      bw.write("~~~\n" + total_time + "\n");

      bw.close();
      fw.close();

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Пример #25
0
  /**
   * Runs of the PESA2 algorithm.
   *
   * @return a <code>SolutionSet</code> that is a set of non dominated solutions as a result of the
   *     algorithm execution
   * @throws JMException
   */
  public SolutionSet execute() throws JMException, ClassNotFoundException {
    int archiveSize, bisections, maxEvaluations, evaluations, populationSize;
    AdaptiveGridArchive archive;
    SolutionSet solutionSet;
    Operator crossover, mutation, selection;

    // Read parameters
    populationSize = ((Integer) (inputParameters_.get("populationSize"))).intValue();
    archiveSize = ((Integer) (inputParameters_.get("archiveSize"))).intValue();
    bisections = ((Integer) (inputParameters_.get("bisections"))).intValue();
    maxEvaluations = ((Integer) (inputParameters_.get("maxEvaluations"))).intValue();

    // Get the operators
    crossover = operators_.get("crossover");
    mutation = operators_.get("mutation");

    // Initialize the variables
    evaluations = 0;
    archive = new AdaptiveGridArchive(archiveSize, bisections, problem_.getNumberOfObjectives());
    solutionSet = new SolutionSet(populationSize);
    HashMap parameters = null;
    selection = new PESA2Selection(parameters);

    // -> Create the initial individual and evaluate it and his constraints
    for (int i = 0; i < populationSize; i++) {
      Solution solution = new Solution(problem_);
      problem_.evaluate(solution);
      problem_.evaluateConstraints(solution);
      solutionSet.add(solution);
    }

    // Incorporate non-dominated solution to the archive
    for (int i = 0; i < solutionSet.size(); i++) {
      archive.add(solutionSet.get(i)); // Only non dominated are accepted by
      // the archive
    }

    // Clear the init solutionSet
    solutionSet.clear();

    // Iterations....
    Solution[] parents = new Solution[2];
    do {
      // -> Create the offSpring solutionSet
      while (solutionSet.size() < populationSize) {
        parents[0] = (Solution) selection.execute(archive);
        parents[1] = (Solution) selection.execute(archive);

        Solution[] offSpring = (Solution[]) crossover.execute(parents);
        mutation.execute(offSpring[0]);
        problem_.evaluate(offSpring[0]);
        problem_.evaluateConstraints(offSpring[0]);
        evaluations++;
        solutionSet.add(offSpring[0]);
      }

      for (int i = 0; i < solutionSet.size(); i++) archive.add(solutionSet.get(i));

      // Clear the solutionSet
      solutionSet.clear();

    } while (evaluations < maxEvaluations);
    // Return the  solutionSet of non-dominated individual
    return archive;
  } // execute