/// <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); }
/// <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 x = new XReal(solution); for (int var = 0; var < solution.Variable.Length; var++) { if (JMetalRandom.NextDouble() < probability) { double rand = JMetalRandom.NextDouble(); double tmp; if (rand <= 0.5) { tmp = Delta(x.GetUpperBound(var) - x.GetValue(var), perturbation.Value); tmp += x.GetValue(var); } else { tmp = Delta(x.GetLowerBound(var) - x.GetValue(var), perturbation.Value); tmp += x.GetValue(var); } if (tmp < x.GetLowerBound(var)) { tmp = x.GetLowerBound(var); } else if (tmp > x.GetUpperBound(var)) { tmp = x.GetUpperBound(var); } x.SetValue(var, tmp); } } }
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> /// 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> /// 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()"); } }
//double[] pro = new double[2]; /// <summary> /// /// </summary> /// <param name="cid">the id of current subproblem</param> /// <param name="type">1 - minimum; otherwise - whole neighborhood probability</param> public int ACOrSelection(int cid, int type) { int ss; ss = neighborhood[cid].Length; double r; int p = neighborhood[cid][0]; Solution[] parents = new Solution[ss]; double[] fitness = new double[ss]; int indexOfmin = 0; double sum = 0; double[] pro = new double[ss]; double a1 = 0; double a2 = 0; if (type == 1) { for (int i = 0; i < ss; i++) { parents[i] = population.Get(neighborhood[cid][i]); fitness[i] = FitnessFunction(parents[i], lambda[cid]); if (fitness[i] < FitnessFunction(population.Get(p), lambda[cid])) { indexOfmin = i; } p = neighborhood[cid][indexOfmin]; } } else { for (int i = 0; i < ss; i++) { parents[i] = population.Get(neighborhood[cid][i]); fitness[i] = 1 / FitnessFunction(parents[i], lambda[cid]); sum = sum + fitness[i]; } for (int j = 0; j < ss; j++) { pro[j] = fitness[j] / sum; } r = JMetalRandom.NextDouble(); for (int k = 0; k < pro.Length; k++) { a2 = a2 + pro[k]; if (r < a2 && r >= a1) { p = neighborhood[cid][k]; break; } a1 = a1 + pro[k]; } } return(p); }
/// <summary> /// Calculates the delta value used in NonUniform mutation operator /// </summary> /// <param name="y"></param> /// <param name="bMutationParameter"></param> /// <returns></returns> private double Delta(double y, double bMutationParameter) { double rand = JMetalRandom.NextDouble(); int it, maxIt; it = currentIteration.Value; maxIt = maxIterations; return(y * (1.0 - Math.Pow(rand, Math.Pow((1.0 - it / (double)maxIt), bMutationParameter)))); }
/// <summary> /// DoMutation method /// </summary> /// <param name="realProbability"></param> /// <param name="binaryProbability"></param> /// <param name="solution"></param> private void DoMutation(double realProbability, double binaryProbability, Solution solution) { double rnd, delta1, delta2, mut_pow, deltaq; double y, yl, yu, val, xy; XReal x = new XReal(solution); Binary binaryVariable = (Binary)solution.Variable[1]; // Polynomial mutation applied to the array real for (int var = 0; var < x.Size(); var++) { if (JMetalRandom.NextDouble() <= realProbability) { y = x.GetValue(var); yl = x.GetLowerBound(var); yu = x.GetUpperBound(var); delta1 = (y - yl) / (yu - yl); delta2 = (yu - y) / (yu - yl); rnd = JMetalRandom.NextDouble(); mut_pow = 1.0 / (eta_m + 1.0); if (rnd <= 0.5) { xy = 1.0 - delta1; val = 2.0 * rnd + (1.0 - 2.0 * rnd) * (Math.Pow(xy, (distributionIndex + 1.0))); deltaq = Math.Pow(val, mut_pow) - 1.0; } else { xy = 1.0 - delta2; val = 2.0 * (1.0 - rnd) + 2.0 * (rnd - 0.5) * (Math.Pow(xy, (distributionIndex + 1.0))); deltaq = 1.0 - (Math.Pow(val, mut_pow)); } y = y + deltaq * (yu - yl); if (y < yl) { y = yl; } if (y > yu) { y = yu; } x.SetValue(var, y); } } // BitFlip mutation applied to the binary part for (int i = 0; i < binaryVariable.NumberOfBits; i++) { if (JMetalRandom.NextDouble() < binaryProbability) { binaryVariable.Bits.Flip(i); } } }
/// <summary> /// Constructor /// </summary> /// <param name="size">Size of the array</param> /// <param name="problem"></param> public ArrayReal(int size, Problem problem) { this.problem = problem; Size = size; Array = new double[Size]; for (int i = 0; i < Size; i++) { double val = JMetalRandom.NextDouble() * (this.problem.UpperLimit[i] - this.problem.LowerLimit[i]) + this.problem.LowerLimit[i]; Array[i] = val; } }
/// <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> /// /// </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="type">1 - neighborhood; otherwise - whole population</param> public int ACOrSelection2(int cid, int type, double[] pro) { double r; int b = neighborhood[cid][0]; Solution[] parents = new Solution[t]; Solution[] parent = new Solution[populationSize]; double[] fitness = new double[t]; double[] fit = new double[populationSize]; Dictionary <int, double> tmp = new Dictionary <int, double>(); Dictionary <int, double> resultSort = new Dictionary <int, double>(); double a1 = 0; double a2 = 0; r = JMetalRandom.NextDouble(); for (int k = 0; k < pro.Length; k++) { a2 = a2 + pro[k]; if (r < a2 && r >= a1) { b = k; break; } a1 = a1 + pro[k]; } if (type == 1) { for (int i = 0; i < t; i++) { parents[i] = population.Get(neighborhood[cid][i]); fitness[i] = FitnessFunction(parents[i], lambda[cid]); tmp.Add(neighborhood[cid][i], fitness[i]); } } else { for (int i = 0; i < populationSize; i++) { parent[i] = population.Get(i); fit[i] = FitnessFunction(parent[i], lambda[cid]); tmp.Add(i, fit[i]); } } resultSort = tmp.OrderBy(Data => Data.Value).ToDictionary(keyvalue => keyvalue.Key, keyvalue => keyvalue.Value); int[] person = resultSort.Keys.ToArray(); return(person[b]); }
/// <summary> /// Perform the mutation operation /// </summary> /// <param name="probability">Mutation probability</param> /// <param name="solution">The solution to mutate</param> private void DoMutation(Solution solution) { double rnd, delta1, delta2, mut_pow, deltaq; double y, yl, yu, val, xy; mutationProbability = mutationProbability - solution.NumberofReplace * 0.001; if (mutationProbability <= 0.1) { mutationProbability = 0.1; } XReal x = new XReal(solution); for (int var = 0; var < solution.NumberOfVariables(); var++) { if (JMetalRandom.NextDouble() <= mutationProbability) { y = x.GetValue(var); yl = x.GetLowerBound(var); yu = x.GetUpperBound(var); delta1 = (y - yl) / (yu - yl); delta2 = (yu - y) / (yu - yl); rnd = JMetalRandom.NextDouble(); mut_pow = 1.0 / (eta_m + 1.0); if (rnd <= 0.5) { xy = 1.0 - delta1; val = 2.0 * rnd + (1.0 - 2.0 * rnd) * (Math.Pow(xy, (distributionIndex + 1.0))); deltaq = Math.Pow(val, mut_pow) - 1.0; } else { xy = 1.0 - delta2; val = 2.0 * (1.0 - rnd) + 2.0 * (rnd - 0.5) * (Math.Pow(xy, (distributionIndex + 1.0))); deltaq = 1.0 - (Math.Pow(val, mut_pow)); } y = y + deltaq * (yu - yl); if (y < yl) { y = yl; } if (y > yu) { y = yu; } x.SetValue(var, y); } } }
/// <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 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 containing the two offsprings</returns> public 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) { for (int i = 0; i < parent1.Variable.Length; i++) { Binary p1 = (Binary)parent1.Variable[i]; Binary p2 = (Binary)parent2.Variable[i]; for (int bit = 0; bit < p1.NumberOfBits; bit++) { if (p1.Bits[bit] != p2.Bits[bit]) { if (JMetalRandom.NextDouble() < 0.5) { ((Binary)offSpring[0].Variable[i]) .Bits[bit] = p2.Bits[bit]; ((Binary)offSpring[1].Variable[i]) .Bits[bit] = p1.Bits[bit]; } } } } //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(); } } } catch (InvalidCastException 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> /// This method executes the operator represented by the current object. /// </summary> /// <param name="obj">A Solution object.</param> public override object Execute(object obj) { var solutionSet = obj as SolutionSet; var solutions = solutionSet.SolutionsList; var bestPerformance = solutions.OrderBy(s => s.Objective [0]).Last(); var bestArea = solutions.OrderBy(s => s.Objective [1]).First(); if (JMetalRandom.NextDouble() > 0.5) { return(DeepCopy(bestPerformance)); } else { return(DeepCopy(bestArea)); } }
/// <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> /// Constructor /// </summary> /// <param name="numberOfBits">Length of the bit string</param> public Binary(int numberOfBits) { this.NumberOfBits = numberOfBits; this.Bits = new BitSet(numberOfBits); for (int i = 0; i < numberOfBits; i++) { if (JMetalRandom.NextDouble() < 0.5) { this.Bits[i] = true; } else { this.Bits[i] = false; } } }
private Solution DoMutation(double probability, Solution parent) { Solution current = new Solution(parent); Solution child; child = new Solution(current); XReal xCurrent = new XReal(current); XReal xChild = new XReal(child); int numberOfVariables = xCurrent.GetNumberOfDecisionVariables(); randStdNormal = new double[numberOfVariables]; for (int j = 0; j < numberOfVariables; j++) { double value; // value = xParent2.GetValue(j) + f * (xParent0.GetValue(j) - xParent1.GetValue(j)); double u1 = JMetalRandom.NextDouble(0, 1); double u2 = JMetalRandom.NextDouble(0, 1); if (JMetalRandom.NextDouble() <= probability) { randStdNormal[j] = Math.Sqrt(-2.0 * Math.Log(u1)) * Math.Sin(2.0 * Math.PI * u2); //random normal(0,1) value = xCurrent.GetValue(j) + zeta * xCurrent.GetStdDev(j) * randStdNormal[j]; if (value < xChild.GetLowerBound(j)) { value = xChild.GetLowerBound(j); //value = JMetalRandom.NextDouble(xChild.GetLowerBound(j), xChild.GetUpperBound(j)); } if (value > xChild.GetUpperBound(j)) { value = xChild.GetUpperBound(j); //value = JMetalRandom.NextDouble(xChild.GetLowerBound(j), xChild.GetUpperBound(j)); } xChild.SetValue(j, value); } } return(child); }
/// <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 population = (SolutionSet)obj; if (index == 0) //Create the permutation { a = (new PermutationUtility()).IntPermutation(population.Size()); } Solution solution1, solution2; solution1 = population.Get(a[index]); solution2 = population.Get(a[index + 1]); index = (index + 2) % population.Size(); int flag = dominance.Compare(solution1, solution2); if (flag == -1) { return(solution1); } else if (flag == 1) { return(solution2); } else if (solution1.CrowdingDistance > solution2.CrowdingDistance) { return(solution1); } else if (solution2.CrowdingDistance > solution1.CrowdingDistance) { return(solution2); } else if (JMetalRandom.NextDouble() < 0.5) { return(solution1); } else { return(solution2); } }
/// <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()"); } }
private List <int> TourSelection(int depth) { // selection based on utility List <int> selected = new List <int>(); List <int> candidate = new List <int>(); for (int k = 0; k < Problem.NumberOfObjectives; k++) { selected.Add(k); // WARNING! HERE YOU HAVE TO USE THE WEIGHT PROVIDED BY QINGFU (NOT SORTED!!!!) } for (int n = Problem.NumberOfObjectives; n < populationSize; n++) { candidate.Add(n); // set of unselected weights } while (selected.Count < (int)(populationSize / 5.0)) { int bestIdd = (int)(JMetalRandom.NextDouble() * candidate.Count); int i2; int bestSub = candidate[bestIdd]; int s2; for (int i = 1; i < depth; i++) { i2 = (int)(JMetalRandom.NextDouble() * candidate.Count); s2 = candidate[i2]; if (utility[s2] > utility[bestSub]) { bestIdd = i2; bestSub = s2; } } selected.Add(bestSub); candidate.Remove(bestIdd); } return(selected); }
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); } }
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> /// 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 containing 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); int i; double rand; double y1, y2, yL, yu; double c1, c2; double alpha, beta, betaq; double valueX1, valueX2; XReal x1 = new XReal(parent1); XReal x2 = new XReal(parent2); XReal offs1 = new XReal(offSpring[0]); XReal offs2 = new XReal(offSpring[1]); int numberOfVariables = x1.GetNumberOfDecisionVariables(); if (JMetalRandom.NextDouble() <= probability) { for (i = 0; i < numberOfVariables; i++) { valueX1 = x1.GetValue(i); valueX2 = x2.GetValue(i); if (JMetalRandom.NextDouble() <= 0.5) { if (Math.Abs(valueX1 - valueX2) > EPS) { if (valueX1 < valueX2) { y1 = valueX1; y2 = valueX2; } else { y1 = valueX2; y2 = valueX1; } yL = x1.GetLowerBound(i); yu = x1.GetUpperBound(i); rand = JMetalRandom.NextDouble(); beta = 1.0 + (2.0 * (y1 - yL) / (y2 - y1)); alpha = 2.0 - Math.Pow(beta, -(distributionIndex + 1.0)); if (rand <= (1.0 / alpha)) { betaq = Math.Pow((rand * alpha), (1.0 / (distributionIndex + 1.0))); } else { betaq = Math.Pow((1.0 / (2.0 - rand * alpha)), (1.0 / (distributionIndex + 1.0))); } c1 = 0.5 * ((y1 + y2) - betaq * (y2 - y1)); beta = 1.0 + (2.0 * (yu - y2) / (y2 - y1)); alpha = 2.0 - Math.Pow(beta, -(distributionIndex + 1.0)); if (rand <= (1.0 / alpha)) { betaq = Math.Pow((rand * alpha), (1.0 / (distributionIndex + 1.0))); } else { betaq = Math.Pow((1.0 / (2.0 - rand * alpha)), (1.0 / (distributionIndex + 1.0))); } c2 = 0.5 * ((y1 + y2) + betaq * (y2 - y1)); if (c1 < yL) { c1 = yL; } if (c2 < yL) { c2 = yL; } if (c1 > yu) { c1 = yu; } if (c2 > yu) { c2 = yu; } if (JMetalRandom.NextDouble() <= 0.5) { offs1.SetValue(i, c2); offs2.SetValue(i, c1); } else { offs1.SetValue(i, c1); offs2.SetValue(i, c2); } } else { offs1.SetValue(i, valueX1); offs2.SetValue(i, valueX2); } } else { offs1.SetValue(i, valueX2); offs2.SetValue(i, valueX1); } } } return(offSpring); }
/// <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); }