/// <summary> /// Executes the operation /// </summary> /// <param name="obj">An object containing the population and the position (index) of the current individual</param> /// <returns>An object containing the three selected parents</returns> public override object Execute(object obj) { object[] parameters = (object[])obj; SolutionSet population = (SolutionSet)parameters[0]; int index = (int)parameters[1]; Solution[] parents = new Solution[3]; int r1, r2, r3; if (population.Size() < 4) { throw new Exception("DifferentialEvolutionSelection: the population has less than four solutions"); } do { r1 = (int)(JMetalRandom.Next(0, population.Size() - 1)); } while (r1 == index); do { r2 = (int)(JMetalRandom.Next(0, population.Size() - 1)); } while (r2 == index || r2 == r1); do { r3 = (int)(JMetalRandom.Next(0, population.Size() - 1)); } while (r3 == index || r3 == r1 || r3 == r2); parents[0] = population.Get(r1); parents[1] = population.Get(r2); parents[2] = population.Get(r3); return(parents); }
/// <summary> /// Returns a permutation vector between the 0 and (length - 1) /// </summary> /// <param name="length"></param> /// <returns></returns> public int[] IntPermutation(int length) { int[] aux = new int[length]; int[] result = new int[length]; // First, create an array from 0 to length - 1. // Also is needed to create an random array of size length for (int i = 0; i < length; i++) { result[i] = i; aux[i] = JMetalRandom.Next(0, length - 1); } // Sort the random array with effect in result, and then we obtain a // permutation array between 0 and length - 1 for (int i = 0; i < length; i++) { for (int j = i + 1; j < length; j++) { if (aux[i] > aux[j]) { int tmp; tmp = aux[i]; aux[i] = aux[j]; aux[j] = tmp; tmp = result[i]; result[i] = result[j]; result[j] = tmp; } } } return(result); }
public override Solution GetOffspring(SolutionSet solutionSet, int index) { Solution[] parents = new Solution[3]; Solution offSpring = null; try { int r1, r2; do { r1 = JMetalRandom.Next(0, solutionSet.Size() - 1); } while (r1 == index); do { r2 = JMetalRandom.Next(0, solutionSet.Size() - 1); } while (r2 == index || r2 == r1); parents[0] = solutionSet.Get(r1); parents[1] = solutionSet.Get(r2); parents[2] = solutionSet.Get(index); offSpring = (Solution)crossover.Execute(new object[] { solutionSet.Get(index), parents }); } catch (Exception ex) { Logger.Log.Error("Exception in " + this.GetType().FullName + ".GetOffSpring()", ex); Console.Error.WriteLine("Exception in " + this.GetType().FullName + ".GetOffSpring()"); } //Create a new solution, using DE return(offSpring); }
/// <summary> /// /// </summary> /// <param name="list">the set of the indexes of selected mating parents</param> /// <param name="cid">the id of current subproblem</param> /// <param name="size">the number of selected mating parents</param> /// <param name="type">1 - neighborhood; otherwise - whole population</param> private void MatingSelection(List <int> list, int cid, int size, int type) { int ss; int r; int p; ss = neighborhood[cid].Length; while (list.Count < size) { if (type == 1) { r = JMetalRandom.Next(0, ss - 1); p = neighborhood[cid][r]; } else { p = JMetalRandom.Next(0, populationSize - 1); } bool flag = true; for (int i = 0; i < list.Count; i++) { if (list[i] == p) // p is in the list { flag = false; break; } } if (flag) { list.Add(p); } } }
/// <summary> /// Performs the operation /// </summary> /// <param name="obj">Object representing a SolutionSet. This solution set must be an instancen <code>AdaptiveGridArchive</code></param> /// <returns>the selected solution</returns> public override object Execute(object obj) { try { AdaptiveGridArchive archive = (AdaptiveGridArchive)obj; int selected; int hypercube1 = archive.Grid.RandomOccupiedHypercube(); int hypercube2 = archive.Grid.RandomOccupiedHypercube(); if (hypercube1 != hypercube2) { if (archive.Grid.GetLocationDensity(hypercube1) < archive.Grid.GetLocationDensity(hypercube2)) { selected = hypercube1; } else if (archive.Grid.GetLocationDensity(hypercube2) < archive.Grid.GetLocationDensity(hypercube1)) { selected = hypercube2; } else { if (JMetalRandom.NextDouble() < 0.5) { selected = hypercube2; } else { selected = hypercube1; } } } else { selected = hypercube1; } int bas = JMetalRandom.Next(0, archive.Size() - 1); int cnt = 0; while (cnt < archive.Size()) { Solution individual = archive.Get((bas + cnt) % archive.Size()); if (archive.Grid.Location(individual) != selected) { cnt++; } else { return(individual); } } return(archive.Get((bas + cnt) % archive.Size())); } catch (InvalidCastException ex) { Logger.Log.Error("Exception in " + this.GetType().FullName + ".Execute()", ex); throw new Exception("Exception in " + this.GetType().FullName + ".Execute()"); } }
/// <summary> /// /// </summary> /// <param name="cid">the id of current subproblem</param> /// <param name="type">1 - neighborhood; otherwise - whole population</param> public int ACOrSelection3(int cid, int type) { int ss; ss = neighborhood[cid].Length; double r; int p = neighborhood[cid][0]; Solution[] parents = new Solution[ss]; Solution[] parent = new Solution[populationSize]; double[] fitness = new double[ss]; double[] fit = new double[populationSize]; int indexOfmin = 0; double sum = 0; double[] pro = new double[populationSize]; double a1 = 0; double a2 = 0; if (type == 1) { indexOfmin = JMetalRandom.Next(0, ss - 1); p = neighborhood[cid][indexOfmin]; } else { for (int i = 0; i < populationSize; i++) { parent[i] = population.Get(i); fit[i] = 1 / FitnessFunction(parent[i], lambda[cid]); sum = sum + fit[i]; } for (int j = 0; j < populationSize; j++) { pro[j] = fit[j] / sum; } r = JMetalRandom.NextDouble(); for (int k = 0; k < pro.Length; k++) { a2 = a2 + pro[k]; if (r < a2 && r >= a1) { p = k; break; } a1 = a1 + pro[k]; } } return(p); }
/// <summary> /// Constructor /// </summary> /// <param name="size">The size of the array</param> /// <param name="lowerBounds">Lower bounds</param> /// <param name="upperBounds">Upper bounds</param> public ArrayInt(int size, double[] lowerBounds, double[] upperBounds) { Size = size; Array = new int[Size]; LowerBound = new int[Size]; UpperBound = new int[Size]; for (int i = 0; i < Size; i++) { LowerBound[i] = (int)lowerBounds[i]; UpperBound[i] = (int)upperBounds[i]; Array[i] = JMetalRandom.Next(LowerBound[i], UpperBound[i]); } }
/// <summary> /// /Update the speed of each particle /// </summary> /// <param name="iter"></param> /// <param name="miter"></param> private void ComputeSpeed(int iter, int miter) { double r1, r2, W, C1, C2; double wmax, wmin; XReal bestGlobal; for (int i = 0; i < swarmSize; i++) { XReal particle = new XReal(particles.Get(i)); XReal bestParticle = new XReal(best[i]); //Select a global best for calculate the speed of particle i, bestGlobal Solution one, two; int pos1 = JMetalRandom.Next(0, Leaders.Size() - 1); int pos2 = JMetalRandom.Next(0, Leaders.Size() - 1); one = Leaders.Get(pos1); two = Leaders.Get(pos2); if (crowdingDistanceComparator.Compare(one, two) < 1) { bestGlobal = new XReal(one); } else { bestGlobal = new XReal(two); //Params for velocity equation } r1 = JMetalRandom.NextDouble(r1Min, r1Max); r2 = JMetalRandom.NextDouble(r2Min, r2Max); C1 = JMetalRandom.NextDouble(C1Min, C1Max); C2 = JMetalRandom.NextDouble(C2Min, C2Max); W = JMetalRandom.NextDouble(WMin, WMax); wmax = WMax; wmin = WMin; for (int var = 0; var < particle.GetNumberOfDecisionVariables(); var++) { //Computing the velocity of this particle speed[i][var] = VelocityConstriction(ConstrictionCoefficient(C1, C2) * (InertiaWeight(iter, miter, wmax, wmin) * speed[i][var] + C1 * r1 * (bestParticle.GetValue(var) - particle.GetValue(var)) + C2 * r2 * (bestGlobal.GetValue(var) - particle.GetValue(var))), deltaMax, deltaMin, var, i); } } }
/// <summary> /// Constructor /// </summary> /// <param name="size">Size of the array</param> public ArrayInt(int size, Problem problem) { _problem = problem; Size = size; Array = new int[size]; LowerBound = new int[size]; UpperBound = new int[size]; for (int i = 0; i < Size; i++) { LowerBound[i] = (int)_problem.LowerLimit[i]; UpperBound[i] = (int)_problem.UpperLimit[i]; Array[i] = JMetalRandom.Next(LowerBound[i], UpperBound[i]); } }
/// <summary> /// Returns a <code>Solution</code> using the diversification generation method /// described in the scatter search template. /// </summary> /// <returns></returns> public Solution DiversificationGeneration() { Solution solution; solution = new Solution(this.Problem); XReal wrapperSolution = new XReal(solution); double value; int range; for (int i = 0; i < this.Problem.NumberOfVariables; i++) { sumOfReverseFrequencyValues[i] = 0; for (int j = 0; j < numberOfSubranges; j++) { reverseFrequency[j][i] = sumOfFrequencyValues[i] - frequency[j][i]; sumOfReverseFrequencyValues[i] += reverseFrequency[j][i]; } if (sumOfReverseFrequencyValues[i] == 0) { range = JMetalRandom.Next(0, numberOfSubranges - 1); } else { value = JMetalRandom.Next(0, sumOfReverseFrequencyValues[i] - 1); range = 0; while (value > reverseFrequency[range][i]) { value -= reverseFrequency[range][i]; range++; } } frequency[range][i]++; sumOfFrequencyValues[i]++; double low = this.Problem.LowerLimit[i] + range * (this.Problem.UpperLimit[i] - this.Problem.LowerLimit[i]) / numberOfSubranges; double high = low + (this.Problem.UpperLimit[i] - this.Problem.LowerLimit[i]) / numberOfSubranges; value = JMetalRandom.NextDouble(low, high); wrapperSolution.SetValue(i, value); } return(solution); }
/// <summary> /// Perform the mutation operation /// </summary> /// <param name="probability">Mutation probability</param> /// <param name="solution">The solution to mutate</param> private void DoMutation(double probability, Solution solution) { XReal v = new XReal(solution); try { if ((solution.Type.GetType() == typeof(BinarySolutionType)) || (solution.Type.GetType() == typeof(BinaryRealSolutionType))) { for (int i = 0; i < solution.Variable.Length; i++) { for (int j = 0; j < ((Binary)solution.Variable[i]).NumberOfBits; j++) { if (JMetalRandom.NextDouble() < probability) { ((Binary)solution.Variable[i]).Bits.Flip(j); } } } for (int i = 0; i < solution.Variable.Length; i++) { ((Binary)solution.Variable[i]).Decode(); } } else { // Integer representation for (int i = 0; i < solution.Variable.Length; i++) { if (JMetalRandom.NextDouble() < probability) { int value = JMetalRandom.Next( (int)v.GetLowerBound(i), (int)v.GetUpperBound(i)); v.SetValue(i, value); } } } } catch (Exception ex) { Logger.Log.Error("Error in " + this.GetType().FullName + ".DoMutation()", ex); Console.WriteLine("Error in " + this.GetType().FullName + ".DoMutation()"); throw new Exception("Exception in " + this.GetType().FullName + ".DoMutation()"); } }
/// <summary> /// Performs the operation /// </summary> /// <param name="obj">Object representing a SolutionSet.</param> /// <returns>An object representing an array with the selected parents</returns> public override object Execute(object obj) { SolutionSet population = (SolutionSet)obj; int pos1, pos2; pos1 = JMetalRandom.Next(0, population.Size() - 1); pos2 = JMetalRandom.Next(0, population.Size() - 1); while ((pos1 == pos2) && (population.Size() > 1)) { pos2 = JMetalRandom.Next(0, population.Size() - 1); } Solution[] parents = new Solution[2]; parents[0] = population.Get(pos1); parents[1] = population.Get(pos2); return(parents); }
/// <summary> /// Performs the operation /// </summary> /// <param name="probability">Mutation probability</param> /// <param name="solution">The solution to mutate</param> private void DoMutation(double probability, Solution solution) { int[] permutation; int permutationLength; if (solution.Type.GetType() == typeof(PermutationSolutionType)) { permutationLength = ((Permutation)solution.Variable[0]).Size; permutation = ((Permutation)solution.Variable[0]).Vector; if (JMetalRandom.NextDouble() < probability) { int pos1; int pos2; pos1 = JMetalRandom.Next(0, permutationLength - 1); pos2 = JMetalRandom.Next(0, permutationLength - 1); while (pos1 == pos2) { if (pos1 == (permutationLength - 1)) { pos2 = JMetalRandom.Next(0, permutationLength - 2); } else { pos2 = JMetalRandom.Next(pos1, permutationLength - 1); } } // swap int temp = permutation[pos1]; permutation[pos1] = permutation[pos2]; permutation[pos2] = temp; } } else { Logger.Log.Error("Exception in " + this.GetType().FullName + ".DoMutation()"); Console.WriteLine("Exception in " + this.GetType().FullName + ".DoMutation()"); throw new Exception("Exception in " + this.GetType().FullName + ".DoMutation()"); } }
public static void RandomPermutation(int[] perm, int size) { int[] index = new int[size]; bool[] flag = new bool[size]; for (int n = 0; n < size; n++) { index[n] = n; flag[n] = true; } int num = 0; while (num < size) { int start = JMetalRandom.Next(0, size - 1); while (true) { if (flag[start]) { perm[num] = index[start]; flag[start] = false; num++; break; } if (start == (size - 1)) { start = 0; } else { start++; } } } }
/// <summary> /// Performs the operation /// </summary> /// <param name="obj">Object representing a SolutionSet</param> /// <returns>The selected solution</returns> public override object Execute(object obj) { SolutionSet solutionSet = (SolutionSet)obj; Solution solution1, solution2; solution1 = solutionSet.Get(JMetalRandom.Next(0, solutionSet.Size() - 1)); solution2 = solutionSet.Get(JMetalRandom.Next(0, solutionSet.Size() - 1)); if (solutionSet.Size() >= 2) { while (solution1 == solution2) { solution2 = solutionSet.Get(JMetalRandom.Next(0, solutionSet.Size() - 1)); } } int flag = comparator.Compare(solution1, solution2); if (flag == -1) { return(solution1); } else if (flag == 1) { return(solution2); } else if (JMetalRandom.NextDouble() < 0.5) { return(solution1); } else { return(solution2); } }
/// <summary> /// Executes the operation /// </summary> /// <param name="obj">An object containing an array of three parents</param> /// <returns>An object containing the offSprings</returns> public override object Execute(object obj) { object[] parameters = (object[])obj; Solution current = (Solution)parameters[0]; Solution[] parent = (Solution[])parameters[1]; Solution child; if (!(VALID_TYPES.Contains(parent[0].Type.GetType()) && VALID_TYPES.Contains(parent[1].Type.GetType()) && VALID_TYPES.Contains(parent[2].Type.GetType()))) { Logger.Log.Error("Exception in " + this.GetType().FullName + ".Execute()"); throw new Exception("Exception in " + this.GetType().FullName + ".Execute()"); } int jrand; child = new Solution(current); XReal xParent0 = new XReal(parent[0]); XReal xParent1 = new XReal(parent[1]); XReal xParent2 = new XReal(parent[2]); XReal xCurrent = new XReal(current); XReal xChild = new XReal(child); int numberOfVariables = xParent0.GetNumberOfDecisionVariables(); jrand = JMetalRandom.Next(0, numberOfVariables - 1); // STEP 4. Checking the DE variant if ((deVariant == "rand/1/bin") || (deVariant == "best/1/bin")) { for (int j = 0; j < numberOfVariables; j++) { if (JMetalRandom.NextDouble(0, 1) < cr || j == jrand) { double value; value = xParent2.GetValue(j) + f * (xParent0.GetValue(j) - xParent1.GetValue(j)); if (value < xChild.GetLowerBound(j)) { value = xChild.GetLowerBound(j); } if (value > xChild.GetUpperBound(j)) { value = xChild.GetUpperBound(j); } xChild.SetValue(j, value); } else { double value; value = xCurrent.GetValue(j); xChild.SetValue(j, value); } } } else if ((deVariant == "rand/1/exp") || (deVariant == "best/1/exp")) { for (int j = 0; j < numberOfVariables; j++) { if (JMetalRandom.NextDouble(0, 1) < cr || j == jrand) { double value; value = xParent2.GetValue(j) + f * (xParent0.GetValue(j) - xParent1.GetValue(j)); if (value < xChild.GetLowerBound(j)) { value = xChild.GetLowerBound(j); } if (value > xChild.GetUpperBound(j)) { value = xChild.GetUpperBound(j); } xChild.SetValue(j, value); } else { cr = 0; double value; value = xCurrent.GetValue(j); xChild.SetValue(j, value); } } } else if ((deVariant == "current-to-rand/1") || (deVariant == "current-to-best/1")) { for (int j = 0; j < numberOfVariables; j++) { double value; value = xCurrent.GetValue(j) + k * (xParent2.GetValue(j) - xCurrent.GetValue(j)) + f * (xParent0.GetValue(j) - xParent1.GetValue(j)); if (value < xChild.GetLowerBound(j)) { value = xChild.GetLowerBound(j); } if (value > xChild.GetUpperBound(j)) { value = xChild.GetUpperBound(j); } xChild.SetValue(j, value); } } else if ((deVariant == "current-to-rand/1/bin") || (deVariant == "current-to-best/1/bin")) { for (int j = 0; j < numberOfVariables; j++) { if (JMetalRandom.NextDouble(0, 1) < cr || j == jrand) { double value; value = xCurrent.GetValue(j) + k * (xParent2.GetValue(j) - xCurrent.GetValue(j)) + f * (xParent0.GetValue(j) - xParent1.GetValue(j)); if (value < xChild.GetLowerBound(j)) { value = xChild.GetLowerBound(j); } if (value > xChild.GetUpperBound(j)) { value = xChild.GetUpperBound(j); } xChild.SetValue(j, value); } else { double value; value = xCurrent.GetValue(j); xChild.SetValue(j, value); } } } else if ((deVariant == "current-to-rand/1/exp") || (deVariant == "current-to-best/1/exp")) { for (int j = 0; j < numberOfVariables; j++) { if (JMetalRandom.NextDouble(0, 1) < cr || j == jrand) { double value; value = xCurrent.GetValue(j) + k * (xParent2.GetValue(j) - xCurrent.GetValue(j)) + f * (xParent0.GetValue(j) - xParent1.GetValue(j)); if (value < xChild.GetLowerBound(j)) { value = xChild.GetLowerBound(j); } if (value > xChild.GetUpperBound(j)) { value = xChild.GetUpperBound(j); } xChild.SetValue(j, value); } else { cr = 0.0; double value; value = xCurrent.GetValue(j); xChild.SetValue(j, value); } } } else { Logger.Log.Error("Exception in " + this.GetType().FullName + ".Execute()"); throw new Exception("Exception in " + this.GetType().FullName + ".Execute()"); } return(child); }
/// <summary> /// Perform the crossover operation. /// </summary> /// <param name="probability">Crossover probability</param> /// <param name="parent1">The first parent</param> /// <param name="parent2">The second parent</param> /// <returns>An array containig the two offsprings</returns> private Solution[] DoCrossover(double probability, Solution parent1, Solution parent2) { Solution[] offSpring = new Solution[2]; offSpring[0] = new Solution(parent1); offSpring[1] = new Solution(parent2); try { if (JMetalRandom.NextDouble() < probability) { if ((parent1.Type.GetType() == typeof(BinarySolutionType)) || (parent1.Type.GetType() == typeof(BinaryRealSolutionType))) { //1. Compute the total number of bits int totalNumberOfBits = 0; for (int i = 0; i < parent1.Variable.Length; i++) { totalNumberOfBits += ((Binary)parent1.Variable[i]).NumberOfBits; } //2. Calculate the point to make the crossover int crossoverPoint = JMetalRandom.Next(0, totalNumberOfBits - 1); //3. Compute the encodings.variable containing the crossoverPoint bit int variable = 0; int acountBits = ((Binary)parent1.Variable[variable]).NumberOfBits; while (acountBits < (crossoverPoint + 1)) { variable++; acountBits += ((Binary)parent1.Variable[variable]).NumberOfBits; } //4. Compute the bit into the selected encodings.variable int diff = acountBits - crossoverPoint; int intoVariableCrossoverPoint = ((Binary)parent1.Variable[variable]).NumberOfBits - diff; //5. Make the crossover into the gene; Binary offSpring1, offSpring2; offSpring1 = (Binary)parent1.Variable[variable].DeepCopy(); offSpring2 = (Binary)parent2.Variable[variable].DeepCopy(); for (int i = intoVariableCrossoverPoint; i < offSpring1.NumberOfBits; i++) { bool swap = offSpring1.Bits[i]; offSpring1.Bits[i] = offSpring2.Bits[i]; offSpring2.Bits[i] = swap; } offSpring[0].Variable[variable] = offSpring1; offSpring[1].Variable[variable] = offSpring2; //6. Apply the crossover to the other variables for (int i = 0; i < variable; i++) { offSpring[0].Variable[i] = parent2.Variable[i].DeepCopy(); offSpring[1].Variable[i] = parent1.Variable[i].DeepCopy(); } //7. Decode the results for (int i = 0; i < offSpring[0].Variable.Length; i++) { ((Binary)offSpring[0].Variable[i]).Decode(); ((Binary)offSpring[1].Variable[i]).Decode(); } } // Binary or BinaryReal else { // Integer representation int crossoverPoint = JMetalRandom.Next(0, parent1.NumberOfVariables() - 1); int valueX1; int valueX2; for (int i = crossoverPoint; i < parent1.NumberOfVariables(); i++) { valueX1 = ((Int)parent1.Variable[i]).Value; valueX2 = ((Int)parent2.Variable[i]).Value; ((Int)offSpring[0].Variable[i]).Value = valueX2; ((Int)offSpring[1].Variable[i]).Value = valueX1; } } } } catch (Exception ex) { Logger.Log.Error("Error in: " + this.GetType().FullName + ".DoCrossover()", ex); Console.WriteLine("Error in " + this.GetType().FullName + ".DoCrossover()"); throw new Exception("Exception in " + this.GetType().FullName + ".DoCrossover()"); } return(offSpring); }
/// <summary> /// Constructor /// </summary> /// <param name="lowerBound">Variable lower bound</param> /// <param name="upperBound">Variable upper bound</param> public Int(int lowerBound, int upperBound) { this.LowerBound = lowerBound; this.UpperBound = upperBound; this.Value = JMetalRandom.Next(lowerBound, upperBound); }
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> /// @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); }
/// <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> /// Perform the crossover operation /// </summary> /// <param name="probability">Crossover probability</param> /// <param name="parent1">The first parent</param> /// <param name="parent2">The second parent</param> /// <returns>Two offspring solutions</returns> private Solution[] DoCrossover(double probability, Solution parent1, Solution parent2) { Solution[] offspring = new Solution[2]; offspring[0] = new Solution(parent1); offspring[1] = new Solution(parent2); if (parent1.Type.GetType() == typeof(PermutationSolutionType)) { if (JMetalRandom.NextDouble() < probability) { int crosspoint1; int crosspoint2; int permutationLength; int[] parent1Vector; int[] parent2Vector; int[] offspring1Vector; int[] offspring2Vector; permutationLength = ((Permutation)parent1.Variable[0]).Size; parent1Vector = ((Permutation)parent1.Variable[0]).Vector; parent2Vector = ((Permutation)parent2.Variable[0]).Vector; offspring1Vector = ((Permutation)offspring[0].Variable[0]).Vector; offspring2Vector = ((Permutation)offspring[1].Variable[0]).Vector; // STEP 1: Get two cutting points crosspoint1 = JMetalRandom.Next(0, permutationLength - 1); crosspoint2 = JMetalRandom.Next(0, permutationLength - 1); while (crosspoint2 == crosspoint1) { crosspoint2 = JMetalRandom.Next(0, permutationLength - 1); } if (crosspoint1 > crosspoint2) { int swap; swap = crosspoint1; crosspoint1 = crosspoint2; crosspoint2 = swap; } // STEP 2: Obtain the first child int m = 0; for (int j = 0; j < permutationLength; j++) { bool exist = false; int temp = parent2Vector[j]; for (int k = crosspoint1; k <= crosspoint2; k++) { if (temp == offspring1Vector[k]) { exist = true; break; } } if (!exist) { if (m == crosspoint1) { m = crosspoint2 + 1; } offspring1Vector[m++] = temp; } } // STEP 3: Obtain the second child m = 0; for (int j = 0; j < permutationLength; j++) { bool exist = false; int temp = parent1Vector[j]; for (int k = crosspoint1; k <= crosspoint2; k++) { if (temp == offspring2Vector[k]) { exist = true; break; } } if (!exist) { if (m == crosspoint1) { m = crosspoint2 + 1; } offspring2Vector[m++] = temp; } } } } else { Logger.Log.Error("Exception in " + this.GetType().FullName + ".DoCrossover()"); Console.WriteLine("Exception in " + this.GetType().FullName + ".DoCrossover()"); throw new Exception("Exception in " + this.GetType().FullName + ".DoCrossover()"); } return(offspring); }
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); }
public Solution[] DoCrossover(double probability, Solution parent1, Solution parent2) { Solution[] offspring = new Solution[2]; offspring[0] = new Solution(parent1); offspring[1] = new Solution(parent2); int permutationLength = ((Permutation)parent1.Variable[0]).Size; int[] parent1Vector = ((Permutation)parent1.Variable[0]).Vector; int[] parent2Vector = ((Permutation)parent2.Variable[0]).Vector; int[] offspring1Vector = ((Permutation)offspring[0].Variable[0]).Vector; int[] offspring2Vector = ((Permutation)offspring[1].Variable[0]).Vector; if (JMetalRandom.NextDouble() < probability) { int cuttingPoint1; int cuttingPoint2; // STEP 1: Get two cutting points cuttingPoint1 = JMetalRandom.Next(0, permutationLength - 1); cuttingPoint2 = JMetalRandom.Next(0, permutationLength - 1); while (cuttingPoint1 == cuttingPoint2) { cuttingPoint2 = JMetalRandom.Next(0, permutationLength - 1); } if (cuttingPoint1 > cuttingPoint2) { int swap; swap = cuttingPoint1; cuttingPoint1 = cuttingPoint2; cuttingPoint2 = swap; } // STEP 2: Get the subchains to interchange int[] replacement1 = new int[permutationLength]; int[] replacement2 = new int[permutationLength]; for (int i = 0; i < permutationLength; i++) { replacement1[i] = replacement2[i] = -1; } // STEP 3: Interchange for (int i = cuttingPoint1; i <= cuttingPoint2; i++) { offspring1Vector[i] = parent2Vector[i]; offspring2Vector[i] = parent1Vector[i]; replacement1[parent2Vector[i]] = parent1Vector[i]; replacement2[parent1Vector[i]] = parent2Vector[i]; } // STEP 4: Repair offsprings for (int i = 0; i < permutationLength; i++) { if ((i >= cuttingPoint1) && (i <= cuttingPoint2)) { continue; } int n1 = parent1Vector[i]; int m1 = replacement1[n1]; int n2 = parent2Vector[i]; int m2 = replacement2[n2]; while (m1 != -1) { n1 = m1; m1 = replacement1[m1]; } while (m2 != -1) { n2 = m2; m2 = replacement2[m2]; } offspring1Vector[i] = n1; offspring2Vector[i] = n2; } } return(offspring); }