private void InitPopulation() { for (int i = 0; i < populationSize; i++) { Solution newSolution = new Solution(Problem); Problem.Evaluate(newSolution); Problem.EvaluateConstraints(newSolution); evaluations++; population.Add(newSolution); } }
/// <summary> /// Returns a <code>SolutionSet</code> with the North, Sout, East, West, /// North-West, South-West, North-East and South-East neighbors solutions of /// ratio 0 of a given location into a given <code>SolutionSet</code>. /// solutions of a given location into a given <code>SolutionSet</code>. /// </summary> /// <param name="population">The <code>SolutionSet</code>.</param> /// <param name="individual">The individual.</param> /// <returns>A <code>SolutionSet</code> with the neighbors.</returns> public SolutionSet GetEightNeighbors(SolutionSet population, int individual) { //SolutionSet that contains the neighbors (to return) SolutionSet neighbors; //instance the population to a non dominated li of individuals neighbors = new SolutionSet(24); //Gets the neighboords N, S, E, W int index; //N index = this.structure[individual][0][(int)Row.N]; neighbors.Add(population.Get(index)); //S index = this.structure[individual][0][(int)Row.S]; neighbors.Add(population.Get(index)); //E index = this.structure[individual][0][(int)Row.E]; neighbors.Add(population.Get(index)); //W index = this.structure[individual][0][(int)Row.W]; neighbors.Add(population.Get(index)); //NE index = this.structure[individual][0][(int)Row.NE]; neighbors.Add(population.Get(index)); //NW index = this.structure[individual][0][(int)Row.NW]; neighbors.Add(population.Get(index)); //SE index = this.structure[individual][0][(int)Row.SE]; neighbors.Add(population.Get(index)); //SW index = this.structure[individual][0][(int)Row.SW]; neighbors.Add(population.Get(index)); //Return the list of non-dominated individuals return(neighbors); }
/// <summary> /// Runs of the Spea2 algorithm. /// </summary> /// <returns>A <code>SolutionSet</code> that is a set of non dominated solutions as a result of the algorithm execution</returns> public override SolutionSet Execute() { int populationSize = -1, archiveSize = -1, maxEvaluations = -1, evaluations; Operator crossoverOperator, mutationOperator, selectionOperator; SolutionSet solutionSet, archive, offSpringSolutionSet; //Read the params JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "archiveSize", ref archiveSize); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations); //Read the operators crossoverOperator = Operators["crossover"]; mutationOperator = Operators["mutation"]; selectionOperator = Operators["selection"]; //Initialize the variables solutionSet = new SolutionSet(populationSize); archive = new SolutionSet(archiveSize); evaluations = 0; //-> Create the initial solutionSet Solution newSolution; for (int i = 0; i < populationSize; i++) { newSolution = new Solution(Problem); Problem.Evaluate(newSolution); Problem.EvaluateConstraints(newSolution); evaluations++; solutionSet.Add(newSolution); } while (evaluations < maxEvaluations) { SolutionSet union = ((SolutionSet)solutionSet).Union(archive); Spea2Fitness spea = new Spea2Fitness(union); spea.FitnessAssign(); archive = spea.EnvironmentalSelection(archiveSize); // Create a new offspringPopulation offSpringSolutionSet = new SolutionSet(populationSize); Solution[] parents = new Solution[2]; while (offSpringSolutionSet.Size() < populationSize) { int j = 0; do { j++; parents[0] = (Solution)selectionOperator.Execute(archive); } while (j < SPEA2.TOURNAMENTS_ROUNDS); int k = 0; do { k++; parents[1] = (Solution)selectionOperator.Execute(archive); } while (k < SPEA2.TOURNAMENTS_ROUNDS); //make the crossover Solution[] offSpring = (Solution[])crossoverOperator.Execute(parents); mutationOperator.Execute(offSpring[0]); Problem.Evaluate(offSpring[0]); Problem.EvaluateConstraints(offSpring[0]); offSpringSolutionSet.Add(offSpring[0]); evaluations++; } // End Create a offSpring solutionSet solutionSet = offSpringSolutionSet; } Ranking ranking = new Ranking(archive); Result = ranking.GetSubfront(0); return(Result); }
/// <summary> /// Runs of the AbYSS algorithm. /// </summary> /// <returns>a <code>SolutionSet</code> that is a set of non dominated solutions /// as a result of the algorithm execution </returns> public override SolutionSet Execute() { // STEP 1. Initialize parameters InitParam(); // STEP 2. Build the initial solutionSet Solution solution; for (int i = 0; i < solutionSetSize; i++) { solution = DiversificationGeneration(); this.Problem.Evaluate(solution); this.Problem.EvaluateConstraints(solution); evaluations++; solution = (Solution)improvementOperator.Execute(solution); evaluations += improvementOperator.GetEvaluations(); solutionSet.Add(solution); } // STEP 3. Main loop int newSolutions = 0; while (evaluations < maxEvaluations) { ReferenceSetUpdate(true); newSolutions = SubSetGeneration(); while (newSolutions > 0) { // New solutions are created ReferenceSetUpdate(false); if (evaluations >= maxEvaluations) { Result = archive; return(archive); } newSolutions = SubSetGeneration(); } // while // RE-START if (evaluations < maxEvaluations) { solutionSet.Clear(); // Add refSet1 to SolutionSet for (int i = 0; i < refSet1.Size(); i++) { solution = refSet1.Get(i); solution.UnMarked(); solution = (Solution)improvementOperator.Execute(solution); evaluations += improvementOperator.GetEvaluations(); solutionSet.Add(solution); } // Remove refSet1 and refSet2 refSet1.Clear(); refSet2.Clear(); // Sort the archive and insert the best solutions distance.CrowdingDistanceAssignment(archive, this.Problem.NumberOfObjectives); archive.Sort(crowdingDistance); int insert = solutionSetSize / 2; if (insert > archive.Size()) { insert = archive.Size(); } if (insert > (solutionSetSize - solutionSet.Size())) { insert = solutionSetSize - solutionSet.Size(); } // Insert solutions for (int i = 0; i < insert; i++) { solution = new Solution(archive.Get(i)); solution.UnMarked(); solutionSet.Add(solution); } // Create the rest of solutions randomly while (solutionSet.Size() < solutionSetSize) { solution = DiversificationGeneration(); this.Problem.EvaluateConstraints(solution); this.Problem.Evaluate(solution); evaluations++; solution = (Solution)improvementOperator.Execute(solution); evaluations += improvementOperator.GetEvaluations(); solution.UnMarked(); solutionSet.Add(solution); } } } // STEP 4. Return the archive Result = archive; return(archive); }
/// <summary> /// Gets 'size' elements from a population of more than 'size' elements /// using for this de enviromentalSelection truncation /// </summary> /// <param name="size">The number of elements to get.</param> /// <returns></returns> 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).Fitness < 1.0) { aux.Add(solutionSet.Get(i)); solutionSet.Remove(i); } else { i++; } } if (aux.Size() < size) { IComparer <Solution> 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[][] distanceMatrix = distance.DistanceMatrix(aux); List <List <DistanceNode> > distanceList = new List <List <DistanceNode> >(); for (int pos = 0; pos < aux.Size(); pos++) { aux.Get(pos).Location = pos; List <DistanceNode> distanceNodeList = new List <DistanceNode>(); for (int refe = 0; refe < aux.Size(); refe++) { if (pos != refe) { distanceNodeList.Add(new DistanceNode(distanceMatrix[pos][refe], refe)); } } distanceList.Add(distanceNodeList); } foreach (List <DistanceNode> aDistanceList in distanceList) { aDistanceList.Sort(distanceNodeComparator); } while (aux.Size() > size) { double minDistance = double.MaxValue; int toRemove = 0; i = 0; foreach (List <DistanceNode> dn in distanceList) { if (dn[0].Distance < minDistance) { toRemove = i; minDistance = dn[0].Distance; //i and toRemove have the same distance to the first solution } else if (dn[0].Distance == minDistance) { int k = 0; while ((dn[k].Distance == distanceList[toRemove][k].Distance) && k < (distanceList[i].Count - 1)) { k++; } if (dn[k].Distance < distanceList[toRemove][k].Distance) { toRemove = i; } } i++; } int tmp = aux.Get(toRemove).Location; aux.Remove(toRemove); distanceList.RemoveAt(toRemove); foreach (List <DistanceNode> aDistanceList in distanceList) { List <DistanceNode> interIterator = aDistanceList.ToList(); foreach (var element in interIterator) { if (element.Reference == tmp) { aDistanceList.Remove(element); } } } } return(aux); }
/// <summary> /// Runs the SMS-EMOA algorithm. /// </summary> /// <returns>A <code>SolutionSet</code> that is a set of non dominated solutions as a result of the algorithm execution</returns> public override SolutionSet Execute() { int populationSize = -1; int maxEvaluations = -1; int evaluations; double offset = 100.0; QualityIndicator.QualityIndicator indicators = null; // QualityIndicator object int requiredEvaluations; // Use in the example of use of the indicators object (see below) SolutionSet population; SolutionSet offspringPopulation; SolutionSet union; Operator mutationOperator; Operator crossoverOperator; Operator selectionOperator; //Read the parameters JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations); JMetalCSharp.Utils.Utils.GetIndicatorsFromParameters(this.InputParameters, "indicators", ref indicators); JMetalCSharp.Utils.Utils.GetDoubleValueFromParameter(this.InputParameters, "offset", ref offset); //Initialize the variables population = new SolutionSet(populationSize); evaluations = 0; requiredEvaluations = 0; //Read the operators mutationOperator = Operators["mutation"]; crossoverOperator = Operators["crossover"]; selectionOperator = Operators["selection"]; // Create the initial solutionSet Solution newSolution; for (int i = 0; i < populationSize; i++) { newSolution = new Solution(Problem); Problem.Evaluate(newSolution); Problem.EvaluateConstraints(newSolution); evaluations++; population.Add(newSolution); } // Generations ... while (evaluations < maxEvaluations) { // select parents offspringPopulation = new SolutionSet(populationSize); List <Solution> selectedParents = new List <Solution>(); Solution[] parents = new Solution[0]; while (selectedParents.Count < 2) { object selected = selectionOperator.Execute(population); try { Solution parent = (Solution)selected; selectedParents.Add(parent); } catch (InvalidCastException e) { parents = (Solution[])selected; selectedParents.AddRange(parents); } } parents = selectedParents.ToArray <Solution>(); // crossover Solution[] offSpring = (Solution[])crossoverOperator.Execute(parents); // mutation mutationOperator.Execute(offSpring[0]); // evaluation Problem.Evaluate(offSpring[0]); Problem.EvaluateConstraints(offSpring[0]); // insert child into the offspring population offspringPopulation.Add(offSpring[0]); evaluations++; // Create the solutionSet union of solutionSet and offSpring union = ((SolutionSet)population).Union(offspringPopulation); // Ranking the union (non-dominated sorting) Ranking ranking = new Ranking(union); // ensure crowding distance values are up to date // (may be important for parent selection) for (int j = 0; j < population.Size(); j++) { population.Get(j).CrowdingDistance = 0.0; } SolutionSet lastFront = ranking.GetSubfront(ranking.GetNumberOfSubfronts() - 1); if (lastFront.Size() > 1) { double[][] frontValues = lastFront.WriteObjectivesToMatrix(); int numberOfObjectives = Problem.NumberOfObjectives; // STEP 1. Obtain the maximum and minimum values of the Pareto front double[] maximumValues = utils.GetMaximumValues(union.WriteObjectivesToMatrix(), numberOfObjectives); double[] minimumValues = utils.GetMinimumValues(union.WriteObjectivesToMatrix(), numberOfObjectives); // STEP 2. Get the normalized front double[][] normalizedFront = utils.GetNormalizedFront(frontValues, maximumValues, minimumValues); // compute offsets for reference point in normalized space double[] offsets = new double[maximumValues.Length]; for (int i = 0; i < maximumValues.Length; i++) { offsets[i] = offset / (maximumValues[i] - minimumValues[i]); } // STEP 3. Inverse the pareto front. This is needed because the original //metric by Zitzler is for maximization problems double[][] invertedFront = utils.InvertedFront(normalizedFront); // shift away from origin, so that boundary points also get a contribution > 0 for (int j = 0, lj = invertedFront.Length; j < lj; j++) { var point = invertedFront[j]; for (int i = 0; i < point.Length; i++) { point[i] += offsets[i]; } } // calculate contributions and sort double[] contributions = HvContributions(invertedFront); for (int i = 0; i < contributions.Length; i++) { // contribution values are used analogously to crowding distance lastFront.Get(i).CrowdingDistance = contributions[i]; } lastFront.Sort(new CrowdingDistanceComparator()); } // all but the worst are carried over to the survivor population SolutionSet front = null; population.Clear(); for (int i = 0; i < ranking.GetNumberOfSubfronts() - 1; i++) { front = ranking.GetSubfront(i); for (int j = 0; j < front.Size(); j++) { population.Add(front.Get(j)); } } for (int i = 0; i < lastFront.Size() - 1; i++) { population.Add(lastFront.Get(i)); } // This piece of code shows how to use the indicator object into the code // of SMS-EMOA. 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.TrueParetoFrontHypervolume)) { requiredEvaluations = evaluations; } } } // Return as output parameter the required evaluations SetOutputParameter("evaluations", requiredEvaluations); // Return the first non-dominated front Ranking rnk = new Ranking(population); Result = rnk.GetSubfront(0); return(Result); }
public override SolutionSet Execute() { double contrDE = 0; double contrSBX = 0; double contrBLXA = 0; double contrPol = 0; double[] contrReal = new double[3]; contrReal[0] = contrReal[1] = contrReal[2] = 0; IComparer <Solution> dominance = new DominanceComparator(); IComparer <Solution> crowdingComparator = new CrowdingComparator(); Distance distance = new Distance(); Operator selectionOperator; //Read parameter values JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize); JMetalCSharp.Utils.Utils.GetIndicatorsFromParameters(this.InputParameters, "indicators", ref indicators); //Init the variables population = new SolutionSet(populationSize); evaluations = 0; selectionOperator = Operators["selection"]; Offspring[] getOffspring; int N_O; // number of offpring objects getOffspring = (Offspring[])GetInputParameter("offspringsCreators"); N_O = getOffspring.Length; contribution = new double[N_O]; contributionCounter = new int[N_O]; contribution[0] = (double)(populationSize / (double)N_O) / (double)populationSize; for (int i = 1; i < N_O; i++) { contribution[i] = (double)(populationSize / (double)N_O) / (double)populationSize + (double)contribution[i - 1]; } // Create the initial solutionSet Solution newSolution; for (int i = 0; i < populationSize; i++) { newSolution = new Solution(Problem); Problem.Evaluate(newSolution); Problem.EvaluateConstraints(newSolution); evaluations++; newSolution.Location = i; population.Add(newSolution); } while (evaluations < maxEvaluations) { // Create the offSpring solutionSet // Create the offSpring solutionSet offspringPopulation = new SolutionSet(2); Solution[] parents = new Solution[2]; int selectedSolution = JMetalRandom.Next(0, populationSize - 1); Solution individual = new Solution(population.Get(selectedSolution)); int selected = 0; bool found = false; Solution offSpring = null; double rnd = JMetalRandom.NextDouble(); for (selected = 0; selected < N_O; selected++) { if (!found && (rnd <= contribution[selected])) { if ("DE" == getOffspring[selected].Id) { offSpring = getOffspring[selected].GetOffspring(population, selectedSolution); contrDE++; } else if ("SBXCrossover" == getOffspring[selected].Id) { offSpring = getOffspring[selected].GetOffspring(population); contrSBX++; } else if ("BLXAlphaCrossover" == getOffspring[selected].Id) { offSpring = getOffspring[selected].GetOffspring(population); contrBLXA++; } else if ("PolynomialMutation" == getOffspring[selected].Id) { offSpring = ((PolynomialMutationOffspring)getOffspring[selected]).GetOffspring(individual); contrPol++; } else { Console.Error.WriteLine("Error in NSGAIIARandom. Operator " + offSpring + " does not exist"); Logger.Log.Error("NSGAIIARandom. Operator " + offSpring + " does not exist"); } offSpring.Fitness = (int)selected; currentCrossover = selected; found = true; } } Problem.Evaluate(offSpring); offspringPopulation.Add(offSpring); evaluations += 1; // 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.NumberOfObjectives); //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.NumberOfObjectives); front.Sort(new CrowdingComparator()); for (int k = 0; k < remain; k++) { population.Add(front.Get(k)); } remain = 0; } } // Return the first non-dominated front Ranking rank = new Ranking(population); Result = rank.GetSubfront(0); return(Result); }
/// <summary> /// Executes the local search. The maximum number of iterations is given by /// the param "improvementRounds", which is in the parameter list of the /// operator. The archive to store the non-dominated solutions is also in the /// parameter list. /// </summary> /// <param name="obj">Object representing a solution</param> /// <returns>An object containing the new improved solution</returns> public override object Execute(object obj) { int i = 0; int best = 0; evaluations = 0; Solution solution = (Solution)obj; int rounds = improvementRounds; archive = (SolutionSet)GetParameter("archive"); if (rounds <= 0) { return(new Solution(solution)); } do { i++; Solution mutatedSolution = new Solution(solution); mutationOperator.Execute(mutatedSolution); // Evaluate the getNumberOfConstraints if (problem.NumberOfConstraints > 0) { problem.EvaluateConstraints(mutatedSolution); best = constraintComparator.Compare(mutatedSolution, solution); if (best == 0) //none of then is better that the other one { problem.Evaluate(mutatedSolution); evaluations++; best = dominanceComparator.Compare(mutatedSolution, solution); } else if (best == -1) //mutatedSolution is best { problem.Evaluate(mutatedSolution); evaluations++; } } else { problem.Evaluate(mutatedSolution); evaluations++; best = dominanceComparator.Compare(mutatedSolution, solution); } if (best == -1) // This is: Mutated is best { solution = mutatedSolution; } else if (best == 1) // This is: Original is best //delete mutatedSolution { ; } else // This is mutatedSolution and original are non-dominated { if (archive != null) { archive.Add(mutatedSolution); } } }while (i < rounds); return(new Solution(solution)); }
/// <summary> /// Execute the algorithm /// </summary> /// <returns></returns> public override SolutionSet Execute() { int populationSize = -1, archiveSize = -1, maxEvaluations = -1, evaluations = -1, feedBack = -1; Operator mutationOperator, crossoverOperator, selectionOperator; SolutionSet currentPopulation; CrowdingArchive archive; SolutionSet[] neighbors; Neighborhood neighborhood; IComparer <Solution> dominance = new DominanceComparator(); IComparer <Solution> crowdingComparator = new CrowdingComparator(); Distance distance = new Distance(); //Read the parameters JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "archiveSize", ref archiveSize); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "feedBack", ref feedBack); //Read the operators mutationOperator = Operators["mutation"]; crossoverOperator = Operators["crossover"]; selectionOperator = Operators["selection"]; //Initialize the variables //Initialize the population and the archive currentPopulation = new SolutionSet(populationSize); archive = new CrowdingArchive(archiveSize, this.Problem.NumberOfObjectives); evaluations = 0; neighborhood = new Neighborhood(populationSize); neighbors = new SolutionSet[populationSize]; //Create the comparator for check dominance dominance = new DominanceComparator(); //Create the initial population for (int i = 0; i < populationSize; i++) { Solution individual = new Solution(this.Problem); this.Problem.Evaluate(individual); this.Problem.EvaluateConstraints(individual); currentPopulation.Add(individual); individual.Location = i; evaluations++; } while (evaluations < maxEvaluations) { for (int ind = 0; ind < currentPopulation.Size(); ind++) { Solution individual = new Solution(currentPopulation.Get(ind)); Solution[] parents = new Solution[2]; Solution[] offSpring; neighbors[ind] = neighborhood.GetEightNeighbors(currentPopulation, ind); neighbors[ind].Add(individual); //parents parents[0] = (Solution)selectionOperator.Execute(neighbors[ind]); parents[1] = (Solution)selectionOperator.Execute(neighbors[ind]); //Create a new individual, using genetic operators mutation and crossover offSpring = (Solution[])crossoverOperator.Execute(parents); mutationOperator.Execute(offSpring[0]); //->Evaluate individual an his constraints this.Problem.Evaluate(offSpring[0]); this.Problem.EvaluateConstraints(offSpring[0]); evaluations++; //<-Individual evaluated int flag = dominance.Compare(individual, offSpring[0]); if (flag == 1) { //The new individuals dominate offSpring[0].Location = individual.Location; currentPopulation.Replace(offSpring[0].Location, offSpring[0]); archive.Add(new Solution(offSpring[0])); } else if (flag == 0) { //The individuals are non-dominates neighbors[ind].Add(offSpring[0]); offSpring[0].Location = -1; Ranking rank = new Ranking(neighbors[ind]); for (int j = 0; j < rank.GetNumberOfSubfronts(); j++) { distance.CrowdingDistanceAssignment(rank.GetSubfront(j), this.Problem.NumberOfObjectives); } Solution worst = neighbors[ind].Worst(crowdingComparator); if (worst.Location == -1) { //The worst is the offspring archive.Add(new Solution(offSpring[0])); } else { offSpring[0].Location = worst.Location; currentPopulation.Replace(offSpring[0].Location, offSpring[0]); archive.Add(new Solution(offSpring[0])); } } } //Store a portion of the archive into the population distance.CrowdingDistanceAssignment(archive, this.Problem.NumberOfObjectives); for (int j = 0; j < feedBack; j++) { if (archive.Size() > j) { int r = JMetalRandom.Next(0, currentPopulation.Size() - 1); if (r < currentPopulation.Size()) { Solution individual = archive.Get(j); individual.Location = r; currentPopulation.Replace(r, new Solution(individual)); } } } } Result = archive; return(archive); }
/// <summary> /// Runs of the SMPSO algorithm. /// </summary> /// <returns>A <code>SolutionSet</code> that is a set of non dominated solutions /// as a result of the algorithm execution </returns> public override SolutionSet Execute() { InitParams(); //->Step 1 (and 3) Create the initial population and evaluate for (int i = 0; i < swarmSize; i++) { Solution particle = new Solution(this.Problem); this.Problem.Evaluate(particle); this.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 < this.Problem.NumberOfVariables; 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 Leaders.ComputeHVContribution(); //-> Step 7. Iterations .. while (iteration < maxIterations) { try { //Compute the speed ComputeSpeed(iteration, maxIterations); } catch (IOException ex) { Logger.Log.Error(this.GetType().FullName + ".Execute()", 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); this.Problem.Evaluate(particle); this.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++; } Result = this.Leaders; return(this.Leaders); }
/// <summary> /// Runs the FastSMSEMOA algorithm. /// </summary> /// <returns> a <code>SolutionSet</code> that is a set of non dominated solutions as a result of the algorithm execution</returns> public override SolutionSet Execute() { int populationSize = -1; int maxEvaluations = -1; int evaluations; double offset = -1; QualityIndicator.QualityIndicator indicators = null; // QualityIndicator object int requiredEvaluations; // Use in the example of use of the indicators object (see below) FastHypervolume fastHypervolume; SolutionSet population; SolutionSet offspringPopulation; SolutionSet union; Operator mutationOperator; Operator crossoverOperator; Operator selectionOperator; //Read the parameters JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations); JMetalCSharp.Utils.Utils.GetIndicatorsFromParameters(this.InputParameters, "indicators", ref indicators); JMetalCSharp.Utils.Utils.GetDoubleValueFromParameter(this.InputParameters, "offset", ref offset); //Initialize the variables population = new SolutionSet(populationSize); evaluations = 0; requiredEvaluations = 0; fastHypervolume = new FastHypervolume(offset); //Read the operators mutationOperator = Operators["mutation"]; crossoverOperator = Operators["crossover"]; selectionOperator = Operators["selection"]; // Create the initial solutionSet Solution newSolution; for (int i = 0; i < populationSize; i++) { newSolution = new Solution(Problem); Problem.Evaluate(newSolution); Problem.EvaluateConstraints(newSolution); evaluations++; population.Add(newSolution); } // Generations ... while (evaluations < maxEvaluations) { // select parents offspringPopulation = new SolutionSet(populationSize); List <Solution> selectedParents = new List <Solution>(); Solution[] parents = new Solution[0]; while (selectedParents.Count < 2) { object selected = selectionOperator.Execute(population); try { Solution parent = (Solution)selected; selectedParents.Add(parent); } catch (InvalidCastException e) { parents = (Solution[])selected; selectedParents.AddRange(parents); } } parents = selectedParents.ToArray <Solution>(); // crossover Solution[] offSpring = (Solution[])crossoverOperator.Execute(parents); // mutation mutationOperator.Execute(offSpring[0]); // evaluation Problem.Evaluate(offSpring[0]); Problem.EvaluateConstraints(offSpring[0]); // insert child into the offspring population offspringPopulation.Add(offSpring[0]); evaluations++; // Create the solutionSet union of solutionSet and offSpring union = ((SolutionSet)population).Union(offspringPopulation); // Ranking the union (non-dominated sorting) Ranking ranking = new Ranking(union); // ensure crowding distance values are up to date // (may be important for parent selection) for (int j = 0; j < population.Size(); j++) { population.Get(j).CrowdingDistance = 0.0; } SolutionSet lastFront = ranking.GetSubfront(ranking.GetNumberOfSubfronts() - 1); fastHypervolume.ComputeHVContributions(lastFront); lastFront.Sort(new CrowdingDistanceComparator()); // all but the worst are carried over to the survivor population SolutionSet front = null; population.Clear(); for (int i = 0; i < ranking.GetNumberOfSubfronts() - 1; i++) { front = ranking.GetSubfront(i); for (int j = 0; j < front.Size(); j++) { population.Add(front.Get(j)); } } for (int i = 0; i < lastFront.Size() - 1; i++) { population.Add(lastFront.Get(i)); } // This piece of code shows how to use the indicator object into the code // of SMS-EMOA. 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.TrueParetoFrontHypervolume)) { requiredEvaluations = evaluations; } } } // Return as output parameter the required evaluations SetOutputParameter("evaluations", requiredEvaluations); // Return the first non-dominated front Ranking rnk = new Ranking(population); Result = rnk.GetSubfront(0); return(Result); }
/// <summary> /// Runs the NSGA-II algorithm. /// </summary> /// <returns>a <code>SolutionSet</code> that is a set of non dominated solutions as a result of the algorithm execution</returns> public override SolutionSet Execute() { int populationSize = -1; int maxEvaluations = -1; int iterationsNumber = -1; int evaluations; int iteration; QualityIndicator.QualityIndicator indicators = null; // QualityIndicator object int requiredEvaluations; // Use in the example of use of the // indicators object (see below) SolutionSet population; SolutionSet offspringPopulation; SolutionSet union; Operator mutationOperator; Operator crossoverOperator; Operator selectionOperator; Distance distance = new Distance(); //Read the parameters JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "iterationsNumber", ref iterationsNumber); JMetalCSharp.Utils.Utils.GetIndicatorsFromParameters(this.InputParameters, "indicators", ref indicators); //Initialize the variables population = new SolutionSet(populationSize); evaluations = 0; iteration = 0; requiredEvaluations = 0; //Read the operators mutationOperator = Operators["mutation"]; crossoverOperator = Operators["crossover"]; selectionOperator = Operators["selection"]; Random random = new Random(); JMetalRandom.SetRandom(random); // Create the initial solutionSet Solution newSolution; for (int i = 0; i < populationSize; i++) { newSolution = new Solution(Problem); Problem.Evaluate(newSolution); Problem.EvaluateConstraints(newSolution); evaluations++; population.Add(newSolution); } /* * string dir = "Result/MOEAD_ACOR/ZDT4_Real/Record/NSGAII_SBX_nr16"; * if (Directory.Exists(dir)) * { * Console.WriteLine("The directory {0} already exists.", dir); * } * else * { * Directory.CreateDirectory(dir); * Console.WriteLine("The directory {0} was created.", dir); * }*/ // Generations while (iteration < iterationsNumber) { // Create the offSpring solutionSet offspringPopulation = new SolutionSet(populationSize); Solution[] parents = new Solution[2]; for (int i = 0; i < (populationSize / 2); i++) { if (iteration < iterationsNumber) { //obtain parents parents[0] = (Solution)selectionOperator.Execute(population); parents[1] = (Solution)selectionOperator.Execute(population); Solution[] offSpring = (Solution[])crossoverOperator.Execute(parents); mutationOperator.Execute(offSpring[0]); mutationOperator.Execute(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.NumberOfObjectives); //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.NumberOfObjectives); front.Sort(new CrowdingComparator()); for (int k = 0; k < remain; k++) { population.Add(front.Get(k)); } remain = 0; } /* * string filevar = dir + "/VAR" + iteration; * string filefun = dir + "/FUN" + iteration; * population.PrintVariablesToFile(filevar); * population.PrintObjectivesToFile(filefun);*/ iteration++; // 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.TrueParetoFrontHypervolume)) { requiredEvaluations = evaluations; } } } Logger.Log.Info("ITERATION: " + iteration); Console.WriteLine("ITERATION: " + iteration); // Return as output parameter the required evaluations SetOutputParameter("evaluations", requiredEvaluations); // Return the first non-dominated front Ranking rank = new Ranking(population); Result = rank.GetSubfront(0); return(Result); }
/// <summary> /// Runs of the SMPSO algorithm. /// </summary> /// <returns>a <code>SolutionSet</code> that is a set of non dominated solutions /// as a result of the algorithm execution </returns> public override SolutionSet Execute() { InitParams(); //->Step 1 (and 3) Create the initial population and evaluate for (int i = 0; i < swarmSize; i++) { Solution particle = new Solution(this.Problem); particles.Add(particle); parallelEvaluator.AddTaskForExecution(new object[] { particle });; } parallelEvaluator.ParallelExecution(); //-> Step2. Initialize the speed_ of each particle to 0 for (int i = 0; i < swarmSize; i++) { for (int j = 0; j < this.Problem.NumberOfVariables; 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, this.Problem.NumberOfObjectives); //-> Step 7. Iterations .. while (iteration < maxIterations) { try { //Compute the speed_ ComputeSpeed(iteration, maxIterations); } catch (IOException ex) { Logger.Log.Error(this.GetType().FullName + ".Execute()", ex); } //Compute the new positions for the particles ComputeNewPositions(); //Mutate the particles MopsoMutation(iteration, maxIterations); for (int i = 0; i < particles.Size(); i++) { Solution particle = particles.Get(i); parallelEvaluator.AddTaskForExecution(new object[] { particle });; } parallelEvaluator.ParallelExecution(); //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, this.Problem.NumberOfObjectives); iteration++; } Result = this.Leaders; return(this.Leaders); }
public void ACOrSelectionTest() { Problem problem = new ZDT1("Real", 10); int populationSize = 11; SolutionSet population = new SolutionSet(populationSize); MOEAD moead = new MOEAD(problem); //Operator crossover = null; ACOR crossover = null; Dictionary <string, object> parameters = new Dictionary <string, object>(); parameters.Add("zeta", 0.85); crossover = new ACOR(parameters); int p = 0; int[] expectedp = new int[11] { 1, 1, 2, 3, 4, 4, 5, 6, 8, 8, 9 }; double[][] expectedLambda = new double[11][] { new double[] { 0, 1 }, new double[] { 0.1, 0.9 }, new double[] { 0.2, 0.8 }, new double[] { 0.3, 0.7 }, new double[] { 0.4, 0.6 }, new double[] { 0.5, 0.5 }, new double[] { 0.6, 0.4 }, new double[] { 0.7, 0.3 }, new double[] { 0.8, 0.2 }, new double[] { 0.9, 0.1 }, new double[] { 1, 0 } }; int[][] expectedneigh = new int[11][] { new int[] { 0, 1 }, new int[] { 1, 0 }, new int[] { 2, 1 }, new int[] { 3, 2 }, new int[] { 4, 5 }, new int[] { 5, 4 }, new int[] { 6, 5 }, new int[] { 7, 6 }, new int[] { 8, 9 }, new int[] { 9, 8 }, new int[] { 10, 9 } }; //double[] expectedz = new double[2] { 0, 1 }; double[] expectedz = new double[2] { 1.024e-07, 0.974113029 }; double k = 1; double[] expectedstdDev = new double[11] { 0.8, 0.8, 0.16, 0.032, 0.00128, 0.00128, 0.000256, 0.0000512, 0.000002048, 0.000002048, 4.096e-07 }; double[][] expectedpro = new double[11][] { new double[] { 0.155241307, 0.844758693 }, new double[] { 0.844758693, 0.155241307 }, new double[] { 0.875915826, 0.124084174 }, new double[] { 0.966565547, 0.033434453 }, new double[] { 0.910514895, 0.089485105 }, new double[] { 0.128479172, 0.871520828 }, new double[] { 0.37023011, 0.62976989 }, new double[] { 0.4515275, 0.5484725 }, new double[] { 0.508750379, 0.491249621 }, new double[] { 0.491249621, 0.508750379 }, new double[] { 0.496138879, 0.503861121 } }; double[][] expectedVariable = new double[11][] { new double[10], new double[10], new double[10], new double[10], new double[10], new double[10], new double[10], new double[10], new double[10], new double[10], new double[10] }; double[][] expectedvariable = new double[11][] { new double[10], new double[10], new double[10], new double[10], new double[10], new double[10], new double[10], new double[10], new double[10], new double[10], new double[10] }; for (int i = 0; i < populationSize; i++) { //double k = (double) i / 10.0; k = Math.Pow(0.2, i); Variable[] variables = new Variable[10]; for (int j = 0; j < variables.Length; j++) { variables[j] = new Real(0, 1, k); expectedVariable[i][j] = k; } Solution newSolution = new Solution(problem, variables); problem.Evaluate(newSolution); population.Add(i, newSolution); } moead.AutoSet(population); int[][] n = (int[][])moead.Get("neighborhood"); double[][] l = (double[][])moead.Get("lambda"); double[] z = (double[])moead.Get("z"); for (int i = 0; i < 11; i++) { for (int j = 0; j < 2; j++) { Assert.AreEqual(expectedneigh[i][j], n[i][j]); Assert.AreEqual(expectedLambda[i][j], l[i][j], 0.0001); Assert.AreEqual(expectedz[j], z[j], 0.0001); } } for (int i = 0; i < populationSize; i++) { double[] rand = new double[10]; p = moead.ACOrSelection(i, 1); //double[] pro = (double[])moead.Get("probability"); Assert.AreEqual(expectedp[i], p); for (int j = 0; j < expectedneigh[i].Length; j++) { Solution child = (Solution)crossover.Execute(population.Get(n[i][j])); rand = (double[])crossover.get(); //Assert.AreEqual(0.1, moead.Get(i, j), 0.00001); Assert.AreEqual(expectedstdDev[i], moead.Get(i, j), 0.000001); //Assert.AreEqual(expectedpro[i][j], pro[j], 0.0001); for (int m = 0; m < 10; m++) { expectedvariable[n[i][j]][m] = expectedVariable[n[i][j]][m] + 0.85 * expectedstdDev[n[i][j]] * rand[m]; if (expectedvariable[n[i][j]][m] > 1) { expectedvariable[n[i][j]][m] = 1; } if (expectedvariable[n[i][j]][m] < 0) { expectedvariable[n[i][j]][m] = 0; } Assert.AreEqual(expectedvariable[n[i][j]][m], Double.Parse(child.Variable[m].ToString()), 0.000001); } } } }
/// <summary> /// Runs the NSGA-II algorithm. /// </summary> /// <returns>a <code>SolutionSet</code> that is a set of non dominated solutions as a result of the algorithm execution</returns> public override SolutionSet Execute() { // !!!! NEEDED PARAMETES !!! start //J* Parameters int populationSize = -1; // J* store population size int maxEvaluations = -1; // J* store number of max Evaluations int evaluations; // J* number of current evaluations // J* Objects needed to illustrate the use of quality indicators inside the algorithms QualityIndicator indicators = null; // QualityIndicator object int requiredEvaluations; // Use in the example of use of the // indicators object (see below) // J* populations needed to implement NSGA-II SolutionSet population; //J* Current population SolutionSet offspringPopulation; //J* offspring population SolutionSet union; //J* population resultant from current and offpring population //J* Genetic Operators Operator mutationOperator; Operator crossoverOperator; Operator selectionOperator; //J* Used to evaluate crowding distance Distance distance = new Distance(); //J* !!!! NEEDED PARAMETES !!! end //J* !!! INITIALIZING PARAMETERS - start !!! //Read the parameters JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations); //J* required JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize); //J* required JMetalCSharp.Utils.Utils.GetIndicatorsFromParameters(this.InputParameters, "indicators", ref indicators); //J* optional //Initialize the variables population = new SolutionSet(populationSize); evaluations = 0; requiredEvaluations = 0; //Read the operators mutationOperator = Operators["mutation"]; crossoverOperator = Operators["crossover"]; selectionOperator = Operators["selection"]; //J* !!! INITIALIZING PARAMETERS - end !!! //J* !!! Creating first population !!! JMetalRandom.SetRandom(comp.MyRand); comp.LogAddMessage("Random seed = " + comp.Seed); // Create the initial solutionSet Solution newSolution; for (int i = 0; i < populationSize; i++) { newSolution = new Solution(Problem); Problem.Evaluate(newSolution); Problem.EvaluateConstraints(newSolution); evaluations++; population.Add(newSolution); } // Generations while (evaluations < maxEvaluations) { // 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); mutationOperator.Execute(offSpring[0]); mutationOperator.Execute(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.NumberOfObjectives); //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.NumberOfObjectives); front.Sort(new 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); if (HV >= (0.98 * indicators.TrueParetoFrontHypervolume)) { requiredEvaluations = evaluations; } } } // Return as output parameter the required evaluations SetOutputParameter("evaluations", requiredEvaluations); comp.LogAddMessage("Evaluations = " + evaluations); // Return the first non-dominated front Ranking rank = new Ranking(population); Result = rank.GetSubfront(0); return(Result); }
public SolutionSet Mix() { QualityIndicator indicators = new QualityIndicator(problem, fileRead.Qi); // QualityIndicator object int requiredEvaluations = 0; // Use in the example of use of the // indicators object (see below) evaluations = 0; iteration = 0; populationSize = int.Parse(fileRead.Ps); iterationsNumber = int.Parse(fileRead.Itn); dataDirectory = "Data/Parameters/Weight"; Logger.Log.Info("POPSIZE: " + populationSize); Console.WriteLine("POPSIZE: " + populationSize); population = new SolutionSet(populationSize); indArray = new Solution[problem.NumberOfObjectives]; t = int.Parse(fileRead.T); nr = int.Parse(fileRead.Nr); delta = double.Parse(fileRead.Delta); gamma = double.Parse(fileRead.Gamma); neighborhood = new int[populationSize][]; for (int i = 0; i < populationSize; i++) { neighborhood[i] = new int[t]; } z = new double[problem.NumberOfObjectives]; //znad = new double[Problem.NumberOfObjectives]; lambda = new double[populationSize][]; for (int i = 0; i < populationSize; i++) { lambda[i] = new double[problem.NumberOfObjectives]; } /*string dir = "Result/" + fileRead.Al + "_" + fileRead.Co + "_" + fileRead.Co2 + "/" + fileRead.Pb + "_" + fileRead.St + "/Record/SBX(" + double.Parse(fileRead.Ra).ToString("#0.00") + ")+ACOR(" + (1-double.Parse(fileRead.Ra)).ToString("#0.00") + ")"; * if (Directory.Exists(dir)) * { * Console.WriteLine("The directory {0} already exists.", dir); * } * else * { * Directory.CreateDirectory(dir); * Console.WriteLine("The directory {0} was created.", dir); * }*/ //Step 1. Initialization //Step 1.1 Compute euclidean distances between weight vectors and find T InitUniformWeight(); InitNeighborhood(); //Step 1.2 Initialize population InitPoputalion(); //Step 1.3 Initizlize z InitIdealPoint(); //Step 2 Update for (int a = 0; a < iterationsNumber; a++) { int[] permutation = new int[populationSize]; JMetalCSharp.Metaheuristics.MOEAD.Utils.RandomPermutation(permutation, populationSize); Solution[] parents = new Solution[2]; int t = 0; if (a >= double.Parse(fileRead.Ra) * iterationsNumber) { for (int i = 0; i < populationSize; i++) { int n = permutation[i]; // or int n = i; int type; double rnd = JMetalRandom.NextDouble(); // STEP 2.1. ACOR selection based on probability if (rnd < gamma) // if (rnd < realb) { type = 1; // minmum //parents[0] = population.Get(ACOrSelection2(n, type, pro_T)); } else { type = 2; // whole neighborhood probability //parents[0] = population.Get(ACOrSelection2(n, type, pro_A)); } GetStdDev(neighborhood); //GetStdDev1(neighborhood, type); //List<int> p = new List<int>(); //MatingSelection(p, n, 1, type); // STEP 2.2. Reproduction Solution child; parents[0] = population.Get(ACOrSelection(n, type)); parents[1] = population.Get(n); //parents[0] = population.Get(p[0]); // Apply ACOR crossover child = (Solution)crossover2.Execute(parents); child.NumberofReplace = t; // // Apply mutation mutation.Execute(child); // Evaluation problem.Evaluate(child); evaluations++; // STEP 2.3. Repair. Not necessary // STEP 2.4. Update z_ UpdateReference(child); // STEP 2.5. Update of solutions t = UpdateProblemWithReplace(child, n, 1); } } else { // Create the offSpring solutionSet SolutionSet offspringPopulation = new SolutionSet(populationSize); for (int i = 0; i < (populationSize / 2); i++) { int n = permutation[i]; // or int n = i; int type; double rnd = JMetalRandom.NextDouble(); // STEP 2.1. Mating selection based on probability if (rnd < delta) // if (rnd < realb) { type = 1; // neighborhood } else { type = 2; // whole population } List <int> p = new List <int>(); MatingSelection(p, n, 2, type); parents[0] = population.Get(p[0]); parents[1] = population.Get(p[1]); //obtain parents Solution[] offSpring = (Solution[])crossover1.Execute(parents); //Solution child; mutation.Execute(offSpring[0]); mutation.Execute(offSpring[1]); /*if(rnd < 0.5) * { * child = offSpring[0]; * } * else * { * child = offSpring[1]; * }*/ problem.Evaluate(offSpring[0]); problem.Evaluate(offSpring[1]); problem.EvaluateConstraints(offSpring[0]); problem.EvaluateConstraints(offSpring[1]); offspringPopulation.Add(offSpring[0]); offspringPopulation.Add(offSpring[1]); evaluations += 2; // STEP 2.3. Repair. Not necessary // STEP 2.4. Update z_ UpdateReference(offSpring[0]); UpdateReference(offSpring[1]); // STEP 2.5. Update of solutions UpdateProblem(offSpring[0], n, type); UpdateProblem(offSpring[1], n, type); } //for (int i = 0; i < populationSize; i++) //{ // int n = permutation[i]; // or int n = i; // int type; // double rnd = JMetalRandom.NextDouble(); // // STEP 2.1. Mating selection based on probability // if (rnd < delta) // if (rnd < realb) // { // type = 1; // neighborhood // } // else // { // type = 2; // whole population // } // List<int> p = new List<int>(); // MatingSelection(p, n, 2, type); // // STEP 2.2. Reproduction // Solution child; // Solution[] parent = new Solution[3]; // parent[0] = population.Get(p[0]); // parent[1] = population.Get(p[1]); // parent[2] = population.Get(n); // // Apply DE crossover // child = (Solution)crossover1.Execute(new object[] { population.Get(n), parent }); // // Apply mutation // mutation.Execute(child); // // Evaluation // problem.Evaluate(child); // evaluations++; // // STEP 2.3. Repair. Not necessary // // STEP 2.4. Update z_ // UpdateReference(child); // // STEP 2.5. Update of solutions // UpdateProblem(child, n, type); //} } /*string filevar = dir + "/VAR" + iteration; * string filefun = dir + "/FUN" + iteration; * population.PrintVariablesToFile(filevar); * population.PrintObjectivesToFile(filefun);*/ iteration++; if ((indicators != null) && (requiredEvaluations == 0)) { double HV = indicators.GetHypervolume(population); if (HV >= (0.98 * indicators.TrueParetoFrontHypervolume)) { requiredEvaluations = evaluations; } } } Logger.Log.Info("ITERATION: " + iteration); Console.WriteLine("ITERATION: " + iteration); SolutionSet Result = population; //return population; // Return the first non-dominated front Ranking rank = new Ranking(population); //SolutionSet Result = rank.GetSubfront(0); return(Result); }
/// <summary> /// Runs the NSGA-II algorithm. /// </summary> /// <returns>a <code>SolutionSet</code> that is a set of non dominated solutions as a result of the algorithm execution</returns> public override SolutionSet Execute() { int populationSize = -1; int maxEvaluations = -1; int evaluations; JMetalCSharp.QualityIndicator.QualityIndicator indicators = null; // QualityIndicator object int requiredEvaluations; // Use in the example of use of the // indicators object (see below) SolutionSet population; SolutionSet offspringPopulation; SolutionSet union; Operator mutationOperator; Operator crossoverOperator; Operator selectionOperator; Distance distance = new Distance(); //Read the parameters JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize); JMetalCSharp.Utils.Utils.GetIndicatorsFromParameters(this.InputParameters, "indicators", ref indicators); parallelEvaluator.StartParallelRunner(Problem);; //Initialize the variables population = new SolutionSet(populationSize); evaluations = 0; requiredEvaluations = 0; //Read the operators mutationOperator = Operators["mutation"]; crossoverOperator = Operators["crossover"]; selectionOperator = Operators["selection"]; // Create the initial solutionSet Solution newSolution; for (int i = 0; i < populationSize; i++) { newSolution = new Solution(Problem); parallelEvaluator.AddTaskForExecution(new object[] { newSolution });; } List <Solution> solutionList = (List <Solution>)parallelEvaluator.ParallelExecution(); foreach (Solution solution in solutionList) { population.Add(solution); evaluations++; } // Generations while (evaluations < maxEvaluations) { // 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); mutationOperator.Execute(offSpring[0]); mutationOperator.Execute(offSpring[1]); parallelEvaluator.AddTaskForExecution(new object[] { offSpring[0] });; parallelEvaluator.AddTaskForExecution(new object[] { offSpring[1] });; } } List <Solution> solutions = (List <Solution>)parallelEvaluator.ParallelExecution(); foreach (Solution solution in solutions) { offspringPopulation.Add(solution); evaluations++; } // 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.NumberOfObjectives); //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.NumberOfObjectives); front.Sort(new 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); if (HV >= (0.98 * indicators.TrueParetoFrontHypervolume)) { requiredEvaluations = evaluations; } } } // Return as output parameter the required evaluations SetOutputParameter("evaluations", requiredEvaluations); // Return the first non-dominated front Ranking rank = new Ranking(population); Result = rank.GetSubfront(0); return(this.Result); }
/** * Runs of the GDE3 algorithm. * @return a <code>SolutionSet</code> that is a set of non dominated solutions * as a result of the algorithm execution * @throws JMException */ public override SolutionSet Execute() { int populationSize = -1; int maxIterations = -1; int evaluations; int iterations; SolutionSet population; SolutionSet offspringPopulation; Distance distance; IComparer <Solution> dominance; Operator selectionOperator; Operator crossoverOperator; distance = new Distance(); dominance = new DominanceComparator(); Solution[] parent; //Read the parameters JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxIterations", ref maxIterations); selectionOperator = this.Operators["selection"]; crossoverOperator = this.Operators["crossover"]; //Initialize the variables population = new SolutionSet(populationSize); evaluations = 0; iterations = 0; // Create the initial solutionSet Solution newSolution; for (int i = 0; i < populationSize; i++) { newSolution = new Solution(this.Problem); this.Problem.Evaluate(newSolution); this.Problem.EvaluateConstraints(newSolution); evaluations++; population.Add(newSolution); } // Generations ... while (iterations < maxIterations) { // Create the offSpring solutionSet offspringPopulation = new SolutionSet(populationSize * 2); for (int i = 0; i < populationSize; i++) { // Obtain parents. Two parameters are required: the population and the // index of the current individual parent = (Solution[])selectionOperator.Execute(new object[] { population, i }); Solution child; // Crossover. Two parameters are required: the current individual and the // array of parents child = (Solution)crossoverOperator.Execute(new object[] { population.Get(i), parent }); this.Problem.Evaluate(child); this.Problem.EvaluateConstraints(child); evaluations++; // Dominance test int result; result = dominance.Compare(population.Get(i), child); if (result == -1) { // Solution i dominates child offspringPopulation.Add(population.Get(i)); } else if (result == 1) { // child dominates offspringPopulation.Add(child); } else { // the two solutions are non-dominated offspringPopulation.Add(child); offspringPopulation.Add(population.Get(i)); } } // Ranking the offspring population Ranking ranking = new Ranking(offspringPopulation); 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, this.Problem.NumberOfObjectives); //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); } } // remain is less than front(index).size, insert only the best one if (remain > 0) { // front contains individuals to insert while (front.Size() > remain) { distance.CrowdingDistanceAssignment(front, this.Problem.NumberOfObjectives); front.Remove(front.IndexWorst(new CrowdingComparator())); } for (int k = 0; k < front.Size(); k++) { population.Add(front.Get(k)); } remain = 0; } iterations++; } // Return the first non-dominated front Ranking rnk = new Ranking(population); this.Result = rnk.GetSubfront(0); return(this.Result); }
/// <summary> /// @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. /// /// 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 /// /// 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) /// </summary> /// <param name="n">The number of solutions to return</param> /// <returns>A solution set containing those elements</returns> private SolutionSet FinalSelection(int n) { SolutionSet res = new SolutionSet(n); if (Problem.NumberOfObjectives == 2) { // subcase 1 double[][] internLambda = new double[n][]; for (int i = 0; i < n; i++) { internLambda[i] = new double[2]; } for (int i = 0; i < n; i++) { double a = 1.0 * i / (n - 1); internLambda[i][0] = a; internLambda[i][1] = 1 - a; } // we have now the weights, now select the best solution for each of them for (int i = 0; i < n; i++) { Solution currentBest = population.Get(0); double value = FitnessFunction(currentBest, internLambda[i]); for (int j = 1; j < n; j++) { double aux = FitnessFunction(population.Get(j), internLambda[i]); // we are looking the best for the weight i if (aux < value) { // solution in position j is better! value = aux; currentBest = population.Get(j); } } res.Add(new Solution(currentBest)); } } else { // general case (more than two objectives) Distance distanceUtility = new Distance(); int randomIndex = JMetalRandom.Next(0, population.Size() - 1); // create a list containing all the solutions but the selected one (only references to them) List <Solution> candidate = new List <Solution>(); candidate.Add(population.Get(randomIndex)); for (int i = 0; i < population.Size(); i++) { if (i != randomIndex) { candidate.Add(population.Get(i)); } } while (res.Size() < n) { int index = 0; Solution selected = candidate[0]; // it should be a next! (n <= population size!) double distanceValue = distanceUtility.DistanceToSolutionSetInObjectiveSpace(selected, res); int i = 1; while (i < candidate.Count) { Solution nextCandidate = candidate[i]; double aux = distanceValue = distanceUtility.DistanceToSolutionSetInObjectiveSpace(nextCandidate, res); if (aux > distanceValue) { distanceValue = aux; index = i; } i++; } // add the selected to res and remove from candidate list res.Add(new Solution(candidate[index])); candidate.RemoveAt(index); } } return(res); }
public override SolutionSet Execute() { double contrDE = 0; double contrSBX = 0; double contrPol = 0; double contrTotalDE = 0; double contrTotalSBX = 0; double contrTotalPol = 0; double[] contrReal = new double[3]; contrReal[0] = contrReal[1] = contrReal[2] = 0; IComparer <Solution> dominance = new DominanceComparator(); IComparer <Solution> crowdingComparator = new CrowdingComparator(); Distance distance = new Distance(); Operator selectionOperator; //Read parameter values JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize); //Init the variables population = new SolutionSet(populationSize); evaluations = 0; selectionOperator = Operators["selection"]; Offspring[] getOffspring; int N_O; // number of offpring objects getOffspring = ((Offspring[])GetInputParameter("offspringsCreators")); N_O = getOffspring.Length; contribution = new double[N_O]; contributionCounter = new int[N_O]; contribution[0] = (double)(populationSize / (double)N_O) / (double)populationSize; for (int i = 1; i < N_O; i++) { contribution[i] = (double)(populationSize / (double)N_O) / (double)populationSize + (double)contribution[i - 1]; } for (int i = 0; i < N_O; i++) { Console.WriteLine(getOffspring[i].Configuration()); Console.WriteLine("Contribution: " + contribution[i]); } // Create the initial solutionSet Solution newSolution; for (int i = 0; i < populationSize; i++) { newSolution = new Solution(Problem); Problem.Evaluate(newSolution); Problem.EvaluateConstraints(newSolution); evaluations++; newSolution.Location = i; population.Add(newSolution); } while (evaluations < maxEvaluations) { // Create the offSpring solutionSet offspringPopulation = new SolutionSet(populationSize); Solution[] parents = new Solution[2]; for (int i = 0; i < (populationSize / 1); i++) { if (evaluations < maxEvaluations) { Solution individual = new Solution(population.Get(JMetalRandom.Next(0, populationSize - 1))); int selected = 0; bool found = false; Solution offSpring = null; double rnd = JMetalRandom.NextDouble(); for (selected = 0; selected < N_O; selected++) { if (!found && (rnd <= contribution[selected])) { if ("DE" == getOffspring[selected].Id) { offSpring = getOffspring[selected].GetOffspring(population, i); contrDE++; } else if ("SBXCrossover" == getOffspring[selected].Id) { offSpring = getOffspring[selected].GetOffspring(population); contrSBX++; } else if ("PolynomialMutation" == getOffspring[selected].Id) { offSpring = ((PolynomialMutationOffspring)getOffspring[selected]).GetOffspring(individual); contrPol++; } else { Logger.Log.Error("Error in NSGAIIAdaptive. Operator " + offSpring + " does not exist"); Console.WriteLine("Error in NSGAIIAdaptive. Operator " + offSpring + " does not exist"); } offSpring.Fitness = (int)selected; found = true; } } Problem.Evaluate(offSpring); offspringPopulation.Add(offSpring); evaluations += 1; } } // 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.NumberOfObjectives); //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.NumberOfObjectives); front.Sort(new CrowdingComparator()); for (int k = 0; k < remain; k++) { population.Add(front.Get(k)); } remain = 0; } // CONTRIBUTION CALCULATING PHASE // First: reset contribution counter for (int i = 0; i < N_O; i++) { contributionCounter[i] = 0; } // Second: determine the contribution of each operator for (int i = 0; i < population.Size(); i++) { if ((int)population.Get(i).Fitness != -1) { contributionCounter[(int)population.Get(i).Fitness] += 1; } population.Get(i).Fitness = -1; } contrTotalDE += contributionCounter[0]; contrTotalSBX += contributionCounter[1]; contrTotalPol += contributionCounter[2]; int minimumContribution = 2; int totalContributionCounter = 0; for (int i = 0; i < N_O; i++) { if (contributionCounter[i] < minimumContribution) { contributionCounter[i] = minimumContribution; } totalContributionCounter += contributionCounter[i]; } if (totalContributionCounter == 0) { for (int i = 0; i < N_O; i++) { contributionCounter[i] = 10; } } // Third: calculating contribution contribution[0] = contributionCounter[0] * 1.0 / (double)totalContributionCounter; for (int i = 1; i < N_O; i++) { contribution[i] = contribution[i - 1] + 1.0 * contributionCounter[i] / (double)totalContributionCounter; } } // Return the first non-dominated front Ranking rank = new Ranking(population); Result = rank.GetSubfront(0); return(Result); }
/// <summary> /// Runs the NSGA-II algorithm. /// </summary> /// <returns>a <code>SolutionSet</code> that is a set of non dominated solutions as a result of the algorithm execution</returns> public override SolutionSet Execute() { int populationSize = -1; int maxEvaluations = -1; int evaluations; JMetalCSharp.QualityIndicator.QualityIndicator indicators = null; // QualityIndicator object int requiredEvaluations; // Use in the example of use of the // indicators object (see below) SolutionSet population; SolutionSet offspringPopulation; SolutionSet union; Operator mutationOperator; Operator crossoverOperator; Operator selectionOperator; Distance distance = new Distance(); //Read the parameters JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize); JMetalCSharp.Utils.Utils.GetIndicatorsFromParameters(this.InputParameters, "indicators", ref indicators); parallelEvaluator.StartParallelRunner(Problem);; //Initialize the variables population = new SolutionSet(populationSize); evaluations = 0; requiredEvaluations = 0; //Read the operators mutationOperator = Operators["mutation"]; crossoverOperator = Operators["crossover"]; selectionOperator = Operators["selection"]; // Create the initial solutionSet IntergenSolution newSolution; for (int i = 0; i < populationSize; i++) { newSolution = new IntergenSolution((IntergenProblem)Problem); parallelEvaluator.AddTaskForExecution(new object[] { newSolution, i });; } List <IntergenSolution> solutionList = (List <IntergenSolution>)parallelEvaluator.ParallelExecution(); foreach (IntergenSolution solution in solutionList) { population.Add(solution); evaluations++; } // Generations while (evaluations < maxEvaluations) { // Create the offSpring solutionSet offspringPopulation = new SolutionSet(populationSize); IntergenSolution[] parents = new IntergenSolution[2]; for (int i = 0; i < (populationSize / 2); i++) { if (evaluations < maxEvaluations) { //obtain parents parents[0] = (IntergenSolution)selectionOperator.Execute(population); parents[1] = (IntergenSolution)selectionOperator.Execute(population); IntergenSolution[] offSpring = (IntergenSolution[])crossoverOperator.Execute(parents); mutationOperator.Execute(offSpring[0]); mutationOperator.Execute(offSpring[1]); parallelEvaluator.AddTaskForExecution(new object[] { offSpring[0], evaluations + i }); parallelEvaluator.AddTaskForExecution(new object[] { offSpring[1], evaluations + i }); } } List <IntergenSolution> solutions = (List <IntergenSolution>)parallelEvaluator.ParallelExecution(); foreach (IntergenSolution solution in solutions) { offspringPopulation.Add(solution); evaluations++; //solution.FoundAtEval = evaluations; } // 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.NumberOfObjectives); //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.NumberOfObjectives); front.Sort(new 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); if (HV >= (0.98 * indicators.TrueParetoFrontHypervolume)) { requiredEvaluations = evaluations; } } //TODO /* * Ranking rank2 = new Ranking(population); * * Result = rank2.GetSubfront(0); */ /*Ranking forGraphicOutput = new Ranking(population); * var currentBestResultSet = forGraphicOutput.GetSubfront(0); * * var firstBestResult = currentBestResultSet.Get(0); * * var myProblem = (IntergenProblem)Problem; * //myProblem.calculated; * * //var variantValuesWithoutInteraction = Matrix.Multiply(myProblem.calculated, firstBestResult.); * //var Model = myProblem.GetModel(); * int mycounter = 0; * if (mycounter % 500 == 0) * { * //RIntegrator.PlotValues(currentBestResultSet, myProblem); * } * mycounter++; * var progress = new UserProgress(); * progress.FeatureP = firstBestResult.Objective[0]; * if (!myProblem.Model.Setting.NoVariantCalculation) progress.VariantP = firstBestResult.Objective[1]; * myProblem.Worker.ReportProgress(evaluations * 100 / maxEvaluations, progress); ; * * //Model.CurrentBestImage = "CurrentBest.png"; */ front = ranking.GetSubfront(0); var minmax = new MinMaxFitness { FeatMax = double.MinValue, FeatMin = double.MaxValue, VarMax = double.MinValue, VarMin = double.MaxValue, InterMax = double.MinValue, InterMin = double.MaxValue }; var prob = (IntergenProblem)Problem; var list = ObjectiveMapping.GetList(prob.ProblemType); for (var i = 0; i < populationSize; i++) { var sol = population.Get(i); var objindex = 0; if (list[0]) { if (sol.Objective[objindex] < minmax.FeatMin) { minmax.FeatMin = sol.Objective[objindex]; } if (sol.Objective[objindex] > minmax.FeatMax) { minmax.FeatMax = sol.Objective[objindex]; } objindex++; } if (list[1]) { if (sol.Objective[objindex] < minmax.InterMin) { minmax.InterMin = sol.Objective[objindex]; } if (sol.Objective[objindex] > minmax.InterMax) { minmax.InterMax = sol.Objective[objindex]; } objindex++; } if (list[2]) { if (sol.Objective[objindex] < minmax.VarMin) { minmax.VarMin = sol.Objective[objindex]; } if (sol.Objective[objindex] > minmax.VarMax) { minmax.VarMax = sol.Objective[objindex]; } } } var sol0 = front.Best(new CrowdingDistanceComparator()); var done = FitnessTracker.AddFitn(minmax); SolutionPlotter.Plot(sol0); ProgressReporter.ReportSolution(evaluations, sol0, _worker); if (done) { Ranking rank3 = new Ranking(population); Result = rank3.GetSubfront(0); SetOutputParameter("evaluations", evaluations); return(this.Result); } } // Return as output parameter the required evaluations SetOutputParameter("evaluations", evaluations); // Return the first non-dominated front Ranking rank = new Ranking(population); Result = rank.GetSubfront(0); return(this.Result); }
/// <summary> /// Implements the referenceSetUpdate method. /// </summary> /// <param name="build">build if true, indicates that the reference has to be build for the /// first time; if false, indicates that the reference set has to be /// updated with new solutions</param> public void ReferenceSetUpdate(bool build) { if (build) { // Build a new reference set // STEP 1. Select the p best individuals of P, where p is refSet1Size. // Selection Criterium: Spea2Fitness Solution individual; (new Spea2Fitness(solutionSet)).FitnessAssign(); solutionSet.Sort(fitness); // STEP 2. Build the RefSet1 with these p individuals for (int i = 0; i < refSet1Size; i++) { individual = solutionSet.Get(0); solutionSet.Remove(0); individual.UnMarked(); refSet1.Add(individual); } // STEP 3. Compute Euclidean distances in SolutionSet to obtain q // individuals, where q is refSet2Size_ for (int i = 0; i < solutionSet.Size(); i++) { individual = solutionSet.Get(i); individual.DistanceToSolutionSet = distance.DistanceToSolutionSetInSolutionSpace(individual, refSet1); } int size = refSet2Size; if (solutionSet.Size() < refSet2Size) { size = solutionSet.Size(); } // STEP 4. Build the RefSet2 with these q individuals for (int i = 0; i < size; i++) { // Find the maximumMinimunDistanceToPopulation double maxMinimum = 0.0; int index = 0; for (int j = 0; j < solutionSet.Size(); j++) { if (solutionSet.Get(j).DistanceToSolutionSet > maxMinimum) { maxMinimum = solutionSet.Get(j).DistanceToSolutionSet; index = j; } } individual = solutionSet.Get(index); solutionSet.Remove(index); // Update distances to REFSET in population for (int j = 0; j < solutionSet.Size(); j++) { double aux = distance.DistanceBetweenSolutions(solutionSet.Get(j), individual); if (aux < individual.DistanceToSolutionSet) { solutionSet.Get(j).DistanceToSolutionSet = aux; } } // Insert the individual into REFSET2 refSet2.Add(individual); // Update distances in REFSET2 for (int j = 0; j < refSet2.Size(); j++) { for (int k = 0; k < refSet2.Size(); k++) { if (i != j) { double aux = distance.DistanceBetweenSolutions(refSet2.Get(j), refSet2.Get(k)); if (aux < refSet2.Get(j).DistanceToSolutionSet) { refSet2.Get(j).DistanceToSolutionSet = aux; } } } } } } else { // Update the reference set from the subset generation result Solution individual; for (int i = 0; i < subSet.Size(); i++) { individual = (Solution)improvementOperator.Execute(subSet.Get(i)); evaluations += improvementOperator.GetEvaluations(); if (RefSet1Test(individual)) { //Update distance of RefSet2 for (int indSet2 = 0; indSet2 < refSet2.Size(); indSet2++) { double aux = distance.DistanceBetweenSolutions(individual, refSet2.Get(indSet2)); if (aux < refSet2.Get(indSet2).DistanceToSolutionSet) { refSet2.Get(indSet2).DistanceToSolutionSet = aux; } } } else { RefSet2Test(individual); } } subSet.Clear(); } }
/// <summary> /// Runs of the aMOCell2 algorithm. /// </summary> /// <returns>a <code>SolutionSet</code> that is a set of non dominated solutions /// as a result of the algorithm execution</returns> public override SolutionSet Execute() { //Init the param int populationSize = -1, archiveSize = -1, maxEvaluations = -1, evaluations = -1; Operator mutationOperator, crossoverOperator, selectionOperator; SolutionSet currentSolutionSet; CrowdingArchive archive; SolutionSet[] neighbors; Neighborhood neighborhood; IComparer <Solution> dominance = new DominanceComparator(), crowding = new CrowdingComparator(); Distance distance = new Distance(); //Read the params JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "archiveSize", ref archiveSize); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations); //Read the operators mutationOperator = Operators["mutation"]; crossoverOperator = Operators["crossover"]; selectionOperator = Operators["selection"]; //Initialize the variables currentSolutionSet = new SolutionSet(populationSize); archive = new CrowdingArchive(archiveSize, this.Problem.NumberOfObjectives); evaluations = 0; neighborhood = new Neighborhood(populationSize); neighbors = new SolutionSet[populationSize]; //Create the initial population for (int i = 0; i < populationSize; i++) { Solution solution = new Solution(this.Problem); this.Problem.Evaluate(solution); this.Problem.EvaluateConstraints(solution); currentSolutionSet.Add(solution); solution.Location = i; evaluations++; } while (evaluations < maxEvaluations) { for (int ind = 0; ind < currentSolutionSet.Size(); ind++) { Solution individual = new Solution(currentSolutionSet.Get(ind)); Solution[] parents = new Solution[2]; Solution[] offSpring; neighbors[ind] = neighborhood.GetEightNeighbors(currentSolutionSet, ind); neighbors[ind].Add(individual); //parents parents[0] = (Solution)selectionOperator.Execute(neighbors[ind]); if (archive.Size() > 0) { parents[1] = (Solution)selectionOperator.Execute(archive); } else { parents[1] = (Solution)selectionOperator.Execute(neighbors[ind]); } //Create a new solution, using genetic operators mutation and crossover offSpring = (Solution[])crossoverOperator.Execute(parents); mutationOperator.Execute(offSpring[0]); //->Evaluate solution and constraints this.Problem.Evaluate(offSpring[0]); this.Problem.EvaluateConstraints(offSpring[0]); evaluations++; int flag = dominance.Compare(individual, offSpring[0]); if (flag == 1) { // OffSpring[0] dominates offSpring[0].Location = individual.Location; currentSolutionSet.Replace(offSpring[0].Location, offSpring[0]); archive.Add(new Solution(offSpring[0])); } else if (flag == 0) { //Both two are non-dominated neighbors[ind].Add(offSpring[0]); Ranking rank = new Ranking(neighbors[ind]); for (int j = 0; j < rank.GetNumberOfSubfronts(); j++) { distance.CrowdingDistanceAssignment(rank.GetSubfront(j), this.Problem.NumberOfObjectives); } bool deleteMutant = true; int compareResult = crowding.Compare(individual, offSpring[0]); if (compareResult == 1) { //The offSpring[0] is better deleteMutant = false; } if (!deleteMutant) { offSpring[0].Location = individual.Location; currentSolutionSet.Replace(offSpring[0].Location, offSpring[0]); archive.Add(new Solution(offSpring[0])); } else { archive.Add(new Solution(offSpring[0])); } } } } Result = archive; return(archive); }
/// <summary> /// Implements the subset generation method described in the scatter search /// template /// </summary> /// <returns>Number of solutions created by the method</returns> public int SubSetGeneration() { Solution[] parents = new Solution[2]; Solution[] offSpring; subSet.Clear(); //All pairs from refSet1 for (int i = 0; i < refSet1.Size(); i++) { parents[0] = refSet1.Get(i); for (int j = i + 1; j < refSet1.Size(); j++) { parents[1] = refSet1.Get(j); if (!parents[0].IsMarked() || !parents[1].IsMarked()) { offSpring = (Solution[])crossoverOperator.Execute(parents); this.Problem.Evaluate(offSpring[0]); this.Problem.Evaluate(offSpring[1]); this.Problem.EvaluateConstraints(offSpring[0]); this.Problem.EvaluateConstraints(offSpring[1]); evaluations += 2; if (evaluations < maxEvaluations) { subSet.Add(offSpring[0]); subSet.Add(offSpring[1]); } parents[0].Marked(); parents[1].Marked(); } } } // All pairs from refSet2 for (int i = 0; i < refSet2.Size(); i++) { parents[0] = refSet2.Get(i); for (int j = i + 1; j < refSet2.Size(); j++) { parents[1] = refSet2.Get(j); if (!parents[0].IsMarked() || !parents[1].IsMarked()) { offSpring = (Solution[])crossoverOperator.Execute(parents); this.Problem.EvaluateConstraints(offSpring[0]); this.Problem.EvaluateConstraints(offSpring[1]); this.Problem.Evaluate(offSpring[0]); this.Problem.Evaluate(offSpring[1]); evaluations += 2; if (evaluations < maxEvaluations) { subSet.Add(offSpring[0]); subSet.Add(offSpring[1]); } parents[0].Marked(); parents[1].Marked(); } } } return(subSet.Size()); }
public override SolutionSet Execute() { QualityIndicator.QualityIndicator indicators = null; // QualityIndicator object int requiredEvaluations = 0; // Use in the example of use of the // indicators object (see below) evaluations = 0; iteration = 0; JMetalCSharp.Utils.Utils.GetDoubleValueFromParameter(this.InputParameters, "q", ref q); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "iterationsNumber", ref iterationsNumber); JMetalCSharp.Utils.Utils.GetStringValueFromParameter(this.InputParameters, "dataDirectory", ref dataDirectory); JMetalCSharp.Utils.Utils.GetIndicatorsFromParameters(this.InputParameters, "indicators", ref indicators); Logger.Log.Info("POPSIZE: " + populationSize); Console.WriteLine("POPSIZE: " + populationSize); population = new SolutionSet(populationSize); indArray = new Solution[Problem.NumberOfObjectives]; JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "T", ref t); JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "nr", ref nr); JMetalCSharp.Utils.Utils.GetDoubleValueFromParameter(this.InputParameters, "delta", ref delta); neighborhood = new int[populationSize][]; for (int i = 0; i < populationSize; i++) { neighborhood[i] = new int[t]; } z = new double[Problem.NumberOfObjectives]; //znad = new double[Problem.NumberOfObjectives]; lambda = new double[populationSize][]; for (int i = 0; i < populationSize; i++) { lambda[i] = new double[Problem.NumberOfObjectives]; } crossover = this.Operators["crossover"]; mutation = this.Operators["mutation"]; double[] pro_T = new double[t]; double[] pro_A = new double[populationSize]; pro_T = GerPro(t); pro_A = GerPro(populationSize); /*string dir = "Result/MOEAD_ACOR/ZDT4_Real/Record/Replace/3nd_Dynamic2_nr16"; * if (Directory.Exists(dir)) * { * Console.WriteLine("The directory {0} already exists.", dir); * } * else * { * Directory.CreateDirectory(dir); * Console.WriteLine("The directory {0} was created.", dir); * }*/ //Step 1. Initialization //Step 1.1 Compute euclidean distances between weight vectors and find T InitUniformWeight(); InitNeighborhood(); //Step 1.2 Initialize population InitPoputalion(); //Step 1.3 Initizlize z InitIdealPoint(); //Step 2 Update do { int[] permutation = new int[populationSize]; Utils.RandomPermutation(permutation, populationSize); if (crossover.ToString() == "JMetalCSharp.Operators.Crossover.DifferentialEvolutionCrossover") { for (int i = 0; i < populationSize; i++) { int n = permutation[i]; // or int n = i; int type; double rnd = JMetalRandom.NextDouble(); // STEP 2.1. Mating selection based on probability if (rnd < delta) // if (rnd < realb) { type = 1; // neighborhood } else { type = 2; // whole population } List <int> p = new List <int>(); MatingSelection(p, n, 2, type); // STEP 2.2. Reproduction Solution child; Solution[] parents = new Solution[3]; parents[0] = population.Get(p[0]); parents[1] = population.Get(p[1]); parents[2] = population.Get(n); // Apply DE crossover child = (Solution)crossover.Execute(new object[] { population.Get(n), parents }); // Apply mutation mutation.Execute(child); // Evaluation Problem.Evaluate(child); evaluations++; // STEP 2.3. Repair. Not necessary // STEP 2.4. Update z_ UpdateReference(child); // STEP 2.5. Update of solutions UpdateProblem(child, n, type); } } else if (crossover.ToString() == "JMetalCSharp.Operators.Crossover.ACOR") { Solution[] parents = new Solution[2]; int t = 0; for (int i = 0; i < populationSize; i++) { int n = permutation[i]; // or int n = i; int type; double rnd = JMetalRandom.NextDouble(); // STEP 2.1. ACOR selection based on probability if (rnd < delta) // if (rnd < realb) { type = 1; // minmum //parents[0] = population.Get(ACOrSelection2(n, type, pro_T)); } else { type = 2; // whole neighborhood probability //parents[0] = population.Get(ACOrSelection2(n, type, pro_A)); } GetStdDev(neighborhood); //GetStdDev1(neighborhood, type); //List<int> p = new List<int>(); //MatingSelection(p, n, 1, type); // STEP 2.2. Reproduction Solution child; parents[0] = population.Get(ACOrSelection(n, type)); parents[1] = population.Get(n); //parents[0] = population.Get(p[0]); // Apply ACOR crossover child = (Solution)crossover.Execute(parents); child.NumberofReplace = t; // // Apply mutation mutation.Execute(child); // Evaluation Problem.Evaluate(child); evaluations++; // STEP 2.3. Repair. Not necessary // STEP 2.4. Update z_ UpdateReference(child); // STEP 2.5. Update of solutions t = UpdateProblemWithReplace(child, n, 1); } } else { // Create the offSpring solutionSet SolutionSet offspringPopulation = new SolutionSet(populationSize); Solution[] parents = new Solution[2]; for (int i = 0; i < (populationSize / 2); i++) { int n = permutation[i]; // or int n = i; int type; double rnd = JMetalRandom.NextDouble(); // STEP 2.1. Mating selection based on probability if (rnd < delta) // if (rnd < realb) { type = 1; // neighborhood } else { type = 2; // whole population } List <int> p = new List <int>(); MatingSelection(p, n, 2, type); parents[0] = population.Get(p[0]); parents[1] = population.Get(p[1]); if (iteration < iterationsNumber) { //obtain parents Solution[] offSpring = (Solution[])crossover.Execute(parents); //Solution child; mutation.Execute(offSpring[0]); mutation.Execute(offSpring[1]); /*if(rnd < 0.5) * { * child = offSpring[0]; * } * else * { * child = offSpring[1]; * }*/ Problem.Evaluate(offSpring[0]); Problem.Evaluate(offSpring[1]); Problem.EvaluateConstraints(offSpring[0]); Problem.EvaluateConstraints(offSpring[1]); offspringPopulation.Add(offSpring[0]); offspringPopulation.Add(offSpring[1]); evaluations += 2; // STEP 2.3. Repair. Not necessary // STEP 2.4. Update z_ UpdateReference(offSpring[0]); UpdateReference(offSpring[1]); // STEP 2.5. Update of solutions UpdateProblem(offSpring[0], n, type); UpdateProblem(offSpring[1], n, type); } } } /*string filevar = dir + "/VAR" + iteration; * string filefun = dir + "/FUN" + iteration; * population.PrintVariablesToFile(filevar); * population.PrintObjectivesToFile(filefun);*/ iteration++; if ((indicators != null) && (requiredEvaluations == 0)) { double HV = indicators.GetHypervolume(population); if (HV >= (0.98 * indicators.TrueParetoFrontHypervolume)) { requiredEvaluations = evaluations; } } } while (iteration < iterationsNumber); Logger.Log.Info("ITERATION: " + iteration); Console.WriteLine("ITERATION: " + iteration); // Return as output parameter the required evaluations SetOutputParameter("evaluations", requiredEvaluations); Result = population; //return population; // Return the first non-dominated front Ranking rank = new Ranking(population); //Result = rank.GetSubfront(0); return(Result); }
/// <summary> /// Calculates the hv contribution of different populations. Receives an /// array of populations and computes the contribution to HV of the /// population consisting in the union of all of them /// </summary> /// <param name="populations">Consisting in all the populatoins</param> /// <returns>HV contributions of each population</returns> public double[] HVContributions(SolutionSet[] populations) { bool empty = true; foreach (SolutionSet population2 in populations) { if (population2.Size() > 0) { empty = false; } } if (empty) { double[] contributions = new double[populations.Length]; for (int i = 0; i < populations.Length; i++) { contributions[i] = 0; } for (int i = 0; i < populations.Length; i++) { Logger.Log.Info("Contributions: " + contributions[i]); Console.WriteLine(contributions[i]); } return(contributions); } SolutionSet union; int size = 0; double offset_ = 0.0; //determining the global size of the population foreach (SolutionSet population1 in populations) { size += population1.Size(); } //allocating space for the union union = new SolutionSet(size); // filling union foreach (SolutionSet population in populations) { for (int j = 0; j < population.Size(); j++) { union.Add(population.Get(j)); } } //determining the number of objectives int numberOfObjectives = union.Get(0).NumberOfObjectives; //writing everything in matrices double[][][] frontValues = new double[populations.Length + 1][][]; frontValues[0] = union.WriteObjectivesToMatrix(); for (int i = 0; i < populations.Length; i++) { if (populations[i].Size() > 0) { frontValues[i + 1] = populations[i].WriteObjectivesToMatrix(); } else { frontValues[i + 1] = new double[0][]; } } // obtain the maximum and minimum values of the Pareto front double[] maximumValues = GetMaximumValues(union.WriteObjectivesToMatrix(), numberOfObjectives); double[] minimumValues = GetMinimumValues(union.WriteObjectivesToMatrix(), numberOfObjectives); // normalized all the fronts double[][][] normalizedFront = new double[populations.Length + 1][][]; for (int i = 0; i < normalizedFront.Length; i++) { if (frontValues[i].Length > 0) { normalizedFront[i] = GetNormalizedFront(frontValues[i], maximumValues, minimumValues); } else { normalizedFront[i] = new double[0][]; } } // compute offsets for reference point in normalized space double[] offsets = new double[maximumValues.Length]; for (int i = 0; i < maximumValues.Length; i++) { offsets[i] = offset_ / (maximumValues[i] - minimumValues[i]); } //Inverse all the fronts front. This is needed because the original //metric by Zitzler is for maximization problems double[][][] invertedFront = new double[populations.Length + 1][][]; for (int i = 0; i < invertedFront.Length; i++) { if (normalizedFront[i].Length > 0) { invertedFront[i] = InvertedFront(normalizedFront[i]); } else { invertedFront[i] = new double[0][]; } } // shift away from origin, so that boundary points also get a contribution > 0 foreach (double[][] anInvertedFront in invertedFront) { foreach (double[] point in anInvertedFront) { for (int i = 0; i < point.Length; i++) { point[i] += offsets[i]; } } } // calculate contributions double[] contribution = new double[populations.Length]; HyperVolume hyperVolume = new HyperVolume(); for (int i = 0; i < populations.Length; i++) { if (invertedFront[i + 1].Length == 0) { contribution[i] = 0; } else { if (invertedFront[i + 1].Length != invertedFront[0].Length) { double[][] aux = new double[invertedFront[0].Length - invertedFront[i + 1].Length][]; int startPoint = 0, endPoint; for (int j = 0; j < i; j++) { startPoint += invertedFront[j + 1].Length; } endPoint = startPoint + invertedFront[i + 1].Length; int index = 0; for (int j = 0; j < invertedFront[0].Length; j++) { if (j < startPoint || j >= (endPoint)) { aux[index++] = invertedFront[0][j]; } } contribution[i] = hyperVolume.CalculateHypervolume(invertedFront[0], invertedFront[0].Length, numberOfObjectives) - hyperVolume.CalculateHypervolume(aux, aux.Length, numberOfObjectives); } else { contribution[i] = hyperVolume.CalculateHypervolume(invertedFront[0], invertedFront[0].Length, numberOfObjectives); } } } return(contribution); }