/** * 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
/** * Creates a new instance of problem CEC2009_UF6. * * @param numberOfVariables Number of variables. * @param solutionType The solution type must "Real" or "BinaryReal". */ public CEC2009_UF6(String solutionType, Integer numberOfVariables, int N, double epsilon) throws ClassNotFoundException { numberOfVariables_ = numberOfVariables.intValue(); numberOfObjectives_ = 2; numberOfConstraints_ = 0; problemName_ = "CEC2009_UF6"; N_ = N; epsilon_ = epsilon; upperLimit_ = new double[numberOfVariables_]; lowerLimit_ = new double[numberOfVariables_]; lowerLimit_[0] = 0.0; upperLimit_[0] = 1.0; for (int var = 1; var < numberOfVariables_; var++) { lowerLimit_[var] = -1.0; upperLimit_[var] = 1.0; } // for if (solutionType.compareTo("BinaryReal") == 0) solutionType_ = new BinaryRealSolutionType(this); else if (solutionType.compareTo("Real") == 0) solutionType_ = new RealSolutionType(this); else { System.out.println("Error: solution type " + solutionType + " invalid"); System.exit(-1); } } // CEC2009_UF6
public boolean[] randomProduct() { boolean[] prod = new boolean[ProductLineProblem.numFeatures]; for (int i = 0; i < prod.length; i++) { prod[i] = r.nextBoolean(); } int rand = r.nextInt(3); try { IOrder order; if (rand == 0) { order = new RandomWalkDecorator(new VarOrderHeap(new NegativeLiteralSelectionStrategy()), 1); } else if (rand == 1) { order = new RandomWalkDecorator(new VarOrderHeap(new PositiveLiteralSelectionStrategy()), 1); } else { order = new RandomWalkDecorator(new VarOrderHeap(new RandomLiteralSelectionStrategy()), 1); } // dimacsSolver.reset(); ISolver dimacsSolver2 = SolverFactory.instance().createSolverByName("MiniSAT"); dimacsSolver2.setTimeout(SATtimeout); DimacsReader dr = new DimacsReader(dimacsSolver2); dr.parseInstance(new FileReader(ProductLineProblem.fm)); ((Solver) dimacsSolver2).setOrder(order); ISolver solverIterator = new ModelIterator(dimacsSolver2); solverIterator.setTimeoutMs(iteratorTimeout); if (solverIterator.isSatisfiable()) { int[] i = solverIterator.findModel(); for (int j = 0; j < i.length; j++) { int feat = i[j]; int posFeat = feat > 0 ? feat : -feat; if (posFeat > 0) { prod[posFeat - 1] = feat > 0; } // else // { // prod[nFeat-1] = r.nextBoolean(); // } } } // solverIterator = null; } catch (Exception e) { e.printStackTrace(); System.exit(0); } return prod; }
/** @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(); } }