/** * 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 */ @Test public Poblacion execute() throws JMException, ClassNotFoundException { int populationSize; int maxEvaluations; int evaluations; int probMutacion; int nrocaso; int corridas; int requiredEvaluations; // Use in the example of use of the // indicators object (see below) // Poblacion population; // SolutionSet population; Poblacion offspringPopulation; Poblacion union; Poblacion copyPopulation; Operator mutationOperator; Operator crossoverOperator; Operator selectionOperator; Distance distance = new Distance(); // Read the parameters populationSize = ((Integer) getInputParameter("populationSize")).intValue(); maxEvaluations = ((Integer) getInputParameter("maxEvaluations")).intValue(); probMutacion = ((Integer) getInputParameter("probMutacion")).intValue(); nrocaso = ((Integer) getInputParameter("nrocaso")).intValue(); corridas = ((Integer) getInputParameter("corridas")).intValue(); // Initialize the variables // population = new SolutionSet(populationSize); evaluations = 0; caso = casosDePrueba[nrocaso]; // Initialize Nsfnet NSFNET = em.find(Red.class, 1); // NSFnet NSFNET.inicializar(); long time_start, time_end = 0; // captura tiempo Inicial time_start = System.currentTimeMillis(); // 0. Obtener Poblacion Inicial this.obtenerPoblacion(populationSize); requiredEvaluations = 0; // Read the operators // mutationOperator = operators_.get("mutation"); // crossoverOperator = operators_.get("crossover"); // selectionOperator = operators_.get("selection"); OperadorSeleccion seleccionOp = new TorneoBinario(); // Create the initial solutionSet Solution newSolution; // population = new Poblacion(populationSize); for (int i = 0; i < populationSize; i++) { newSolution = new Solution(problem_); problem_.evaluate(newSolution); problem_.evaluateConstraints(newSolution); evaluations++; population.add(newSolution); } // for Ranking ranking = new Ranking(population); evaluations = 0; int cantIt = 0; int size, tamanho = 0; // Generations System.out.println(caso + "-" + corridas + " Test Genetico."); while (evaluations < tiempoTotal[nrocaso]) { size = population.getIndividuos().size(); tamanho = (size * size) + size; offspringPopulation = new Poblacion(populationSize * populationSize + populationSize); copyPopulation = new Poblacion(populationSize * populationSize + populationSize); // offspringPopulation.copiarPoblacion(population);; // for (int i = 0; i < (populationSize); i++) { if (evaluations < tiempoTotal[nrocaso]) { for (Individuo ind : population.getIndividuos()) { Solution s = (Solution) ind; s.setNumberOfObjectives(problem_.getNumberOfObjectives()); problem_.evaluate(s); // if (s.getCosto()<2.8) // System.out.println(s.getCosto()); if (s.getCosto() > 0) offspringPopulation.add(s); } Collection<Individuo> selectos = seleccionOp.seleccionar(population); population.cruzar(selectos, probMutacion); /*copyPopulation.copiarPoblacion(offspringPopulation); Poblacion mejores = getFront(copyPopulation); population.siguienteGeneracion(mejores);*/ population.siguienteGeneracion(); evaluations++; } // if // } // for for (Individuo ind : population.getIndividuos()) { Solution s = (Solution) ind; s.setNumberOfObjectives(problem_.getNumberOfObjectives()); problem_.evaluate(s); if (s.getCosto() > 0) offspringPopulation.add(s); } // Create the solutionSet union of solutionSet and offSpring // union = ((SolutionSet) population).union(offspringPopulation); union = offspringPopulation.union(population); // Ranking the union ranking = new Ranking(union); int remain = populationSize; int index = 0; Poblacion front = null; population.clear(); // Obtain the next front front = ranking.getSubfront(index); while (front != null && (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)); } // for // Decrement remain remain = remain - front.size(); // Obtain the next front index++; if (remain > 0) { front = ranking.getSubfront(index); } // if } // while if (front != null) { // 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 CrowdingComparator()); for (int k = 0; k < remain; k++) { population.add(front.get(k)); } // for } remain = 0; } // if // 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); if (HV >= (0.98 * indicators.getTrueParetoFrontHypervolume())) { requiredEvaluations = evaluations; } // if } // if*/ if (evaluations % maxEvaluations == 0) { System.out.println(); System.out.print("Población Nro: " + evaluations + " "); // System.out.println("MEJOR--> " + p.getMejor().toString()); System.out.print("Costo-MEJOR==> "); ranking = new Ranking(population); if (ranking.getSubfront(0) != null) { ranking.getSubfront(0).printParcialResults(); ranking.getSubfront(0).printVariablesToFile("VAR_p3" + "_" + caso); } // ((Solution) p.getMejor()).imprimirCosto(); } } // while cantIt++; // captura tiempo final // time_end = System.currentTimeMillis(); // Calculo del Tiempo /*long tiempo = time_end - time_start; long hora = tiempo / 3600000; long restohora = tiempo % 3600000; long minuto = restohora / 60000; long restominuto = restohora % 60000; long segundo = restominuto / 1000; long restosegundo = restominuto % 1000; String time = hora + ":" + minuto + ":" + segundo + "." + restosegundo; time = " Tiempo: " + time; String fin = caso + " FIN - Test Genetico. Tiempo:" + time; fin += " - Nº Generaciones: " + evaluations; System.out.println(fin); */ System.out.println("Evaluaciones: " + evaluations); // Return as output parameter the required evaluations setOutputParameter("evaluations", requiredEvaluations); // Return the first non-dominated front ranking = new Ranking(population); if (ranking.getSubfront(0) != null) ranking.getSubfront(0).printFeasibleFUN("FUN_NSGAII"); return ranking.getSubfront(0); } // execute
/** * Constructor. Creates a new instance of Spea2Fitness for a given <code>SolutionSet</code>. * * @param solutionSet The <code>SolutionSet</code> */ public Spea2Fitness(SolutionSet solutionSet) { distance = distance_.distanceMatrix(solutionSet); solutionSet_ = solutionSet; for (int i = 0; i < solutionSet_.size(); i++) { solutionSet_.get(i).setLocation(i); } // for } // Spea2Fitness
public Poblacion getFront(Poblacion population) { Ranking ranking = new Ranking(population); Distance distance = new Distance(); int remain = population.size(); int index = 0; Poblacion front = null; Poblacion poblacion = new Poblacion(population.size()); front = ranking.getSubfront(index); while (front != null && (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++) { poblacion.add(front.get(k)); } // for // Decrement remain remain = remain - front.size(); // Obtain the next front index++; if (remain > 0) { front = ranking.getSubfront(index); } // if } // while if (front != null) { // 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 CrowdingComparator()); for (int k = 0; k < remain; k++) { poblacion.add(front.get(k)); } // for } remain = 0; } // if return ranking.getSubfront(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
/** * Gets 'size' elements from a population of more than 'size' elements using for this de * enviromentalSelection truncation * * @param size The number of elements to get. */ public SolutionSet environmentalSelection(int size) { if (solutionSet_.size() < size) { size = solutionSet_.size(); } // Create a new auxiliar population for no alter the original population SolutionSet aux = new SolutionSet(solutionSet_.size()); int i = 0; while (i < solutionSet_.size()) { if (solutionSet_.get(i).getFitness() < 1.0) { aux.add(solutionSet_.get(i)); solutionSet_.remove(i); } else { i++; } // if } // while if (aux.size() < size) { Comparator comparator = new FitnessComparator(); solutionSet_.sort(comparator); int remain = size - aux.size(); for (i = 0; i < remain; i++) { aux.add(solutionSet_.get(i)); } return aux; } else if (aux.size() == size) { return aux; } double[][] distance = distance_.distanceMatrix(aux); List<List<DistanceNode>> distanceList = new LinkedList<List<DistanceNode>>(); for (int pos = 0; pos < aux.size(); pos++) { aux.get(pos).setLocation(pos); List<DistanceNode> distanceNodeList = new ArrayList<DistanceNode>(); for (int ref = 0; ref < aux.size(); ref++) { if (pos != ref) { distanceNodeList.add(new DistanceNode(distance[pos][ref], ref)); } // if } // for distanceList.add(distanceNodeList); } // for for (int q = 0; q < distanceList.size(); q++) { Collections.sort(distanceList.get(q), distanceNodeComparator); } // for while (aux.size() > size) { double minDistance = Double.MAX_VALUE; int toRemove = 0; i = 0; Iterator<List<DistanceNode>> iterator = distanceList.iterator(); while (iterator.hasNext()) { List<DistanceNode> dn = iterator.next(); if (dn.get(0).getDistance() < minDistance) { toRemove = i; minDistance = dn.get(0).getDistance(); // i y toRemove have the same distance to the first solution } else if (dn.get(0).getDistance() == minDistance) { int k = 0; while ((dn.get(k).getDistance() == distanceList.get(toRemove).get(k).getDistance()) && k < (distanceList.get(i).size() - 1)) { k++; } if (dn.get(k).getDistance() < distanceList.get(toRemove).get(k).getDistance()) { toRemove = i; } // if } // if i++; } // while int tmp = aux.get(toRemove).getLocation(); aux.remove(toRemove); distanceList.remove(toRemove); Iterator<List<DistanceNode>> externIterator = distanceList.iterator(); while (externIterator.hasNext()) { Iterator<DistanceNode> interIterator = externIterator.next().iterator(); while (interIterator.hasNext()) { if (interIterator.next().getReference() == tmp) { interIterator.remove(); continue; } // if } // while } // while } // while return aux; } // environmentalSelection
/** * @author Juanjo This method selects N solutions from a set M, where N <= M using the same method * proposed by Qingfu Zhang, W. Liu, and Hui Li in the paper describing MOEA/D-DRA (CEC 09 * COMPTETITION) An example is giving in that paper for two objectives. If N = 100, then the * best solutions attenting to the weights (0,1), (1/99,98/99), ...,(98/99,1/99), (1,0) are * selected. * <p>Using this method result in 101 solutions instead of 100. We will just compute 100 even * distributed weights and used them. The result is the same * <p>In case of more than two objectives the procedure is: 1- Select a solution at random 2- * Select the solution from the population which have maximum distance to it (whithout * considering the already included) * @param n: The number of solutions to return * @return A solution set containing those elements */ SolutionSet finalSelection(int n) throws JMException { SolutionSet res = new SolutionSet(n); if (problem_.getNumberOfObjectives() == 2) { // subcase 1 double[][] intern_lambda = new double[n][2]; for (int i = 0; i < n; i++) { double a = 1.0 * i / (n - 1); intern_lambda[i][0] = a; intern_lambda[i][1] = 1 - a; } // for // we have now the weights, now select the best solution for each of them for (int i = 0; i < n; i++) { Solution current_best = population.get(0); int index = 0; double value = fitnessFunction(current_best, intern_lambda[i]); for (int j = 1; j < n; j++) { double aux = fitnessFunction( population.get(j), intern_lambda[i]); // we are looking the best for the weight i if (aux < value) { // solution in position j is better! value = aux; current_best = population.get(j); } } res.add(new Solution(current_best)); } } else { // general case (more than two objectives) Distance distance_utility = new Distance(); int random_index = PseudoRandom.randInt(0, population.size() - 1); // create a list containing all the solutions but the selected one (only references to them) List<Solution> candidate = new LinkedList<Solution>(); candidate.add(population.get(random_index)); for (int i = 0; i < population.size(); i++) { if (i != random_index) { candidate.add(population.get(i)); } } // for while (res.size() < n) { int index = 0; Solution selected = candidate.get(0); // it should be a next! (n <= population size!) double distance_value = distance_utility.distanceToSolutionSetInObjectiveSpace(selected, res); int i = 1; while (i < candidate.size()) { Solution next_candidate = candidate.get(i); double aux = distance_value = distance_utility.distanceToSolutionSetInObjectiveSpace(next_candidate, res); if (aux > distance_value) { distance_value = aux; index = i; } i++; } // add the selected to res and remove from candidate list res.add(new Solution(candidate.remove(index))); } // } return res; }
/** * 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); }