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