Пример #1
0
        /// <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);
                }
            }
        }
Пример #2
0
        /// <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()");
            }
        }
Пример #3
0
        //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);
        }
Пример #4
0
        /// <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))));
        }
Пример #5
0
        /// <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;
            }
        }
Пример #7
0
        /// <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);
                }
            }
        }
Пример #9
0
        /// <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>
        /// 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);
        }
Пример #11
0
        /// <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>
        /// 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);
        }
Пример #13
0
        /// <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));
            }
        }
Пример #14
0
        /// <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;
                }
            }
        }
Пример #15
0
        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);
            }
        }
Пример #17
0
        /// <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()");
            }
        }
Пример #18
0
        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);
        }
Пример #19
0
        /// <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);
            }
        }
Пример #20
0
        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);
        }
Пример #21
0
        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>
        /// 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);
        }
Пример #23
0
 public bool ShouldCrossOver()
 {
     return(JMetalRandom.NextDouble() >= CrossOverPercentage);
 }
Пример #24
0
        /// <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);
        }
Пример #25
0
        private void Run()
        {
            neighborhood = parentThread.neighborhood;
            Problem      = parentThread.Problem;
            lambda       = parentThread.lambda;
            population   = parentThread.population;
            z            = parentThread.z;
            indArray     = parentThread.indArray;
            barrier      = parentThread.barrier;


            int partitions = parentThread.populationSize / parentThread.numberOfThreads;

            evaluations    = 0;
            maxEvaluations = parentThread.maxEvaluations / parentThread.numberOfThreads;

            barrier.SignalAndWait();

            int first;
            int last;

            first = partitions * id;
            if (id == (parentThread.numberOfThreads - 1))
            {
                last = parentThread.populationSize - 1;
            }
            else
            {
                last = first + partitions - 1;
            }

            Logger.Log.Info("Id: " + id + "  Partitions: " + partitions + " First: " + first + " Last: " + last);
            Console.WriteLine("Id: " + id + "  Partitions: " + partitions + " First: " + first + " Last: " + last);
            do
            {
                for (int i = first; i <= last; i++)
                {
                    int    n = i;
                    int    type;
                    double rnd = JMetalRandom.NextDouble();

                    // STEP 2.1. Mating selection based on probability
                    if (rnd < parentThread.delta)
                    {
                        type = 1;                           // neighborhood
                    }
                    else
                    {
                        type = 2;                           // whole population
                    }

                    List <int> p = new List <int>();
                    this.MatingSelection(p, n, 2, type);

                    // STEP 2.2. Reproduction
                    Solution   child   = null;
                    Solution[] parents = new Solution[3];

                    try
                    {
                        lock (parentThread)
                        {
                            parents[0] = parentThread.population.Get(p[0]);
                            parents[1] = parentThread.population.Get(p[1]);
                            parents[2] = parentThread.population.Get(n);
                            // Apply DE crossover
                            child = (Solution)parentThread.crossover.Execute(new object[] { parentThread.population.Get(n), parents });
                        }
                        // Apply mutation
                        parentThread.mutation.Execute(child);

                        // Evaluation
                        parentThread.Problem.Evaluate(child);
                    }
                    catch (Exception ex)
                    {
                        Logger.Log.Error(this.GetType().FullName + ".Run()", ex);
                        Console.WriteLine("Error in " + this.GetType().FullName + ".Run()");
                    }

                    evaluations++;

                    // STEP 2.3. Repair. Not necessary

                    // STEP 2.4. Update z
                    UpdateReference(child);

                    // STEP 2.5. Update of solutions
                    UpdateOfSolutions(child, n, type);
                }
            } while (evaluations < maxEvaluations);

            long estimatedTime = Environment.TickCount - parentThread.initTime;

            Logger.Log.Info("Time thread " + id + ": " + estimatedTime);
            Console.WriteLine("Time thread " + id + ": " + estimatedTime);
        }
        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);
        }
Пример #27
0
 private bool ShouldMutate()
 {
     return(JMetalRandom.NextDouble() >= MutationPercentage);
 }
Пример #28
0
        private IntergenSolution[] DoCrossover(double probability, IntergenSolution parent1, IntergenSolution parent2)
        {
            IntergenSolution[] offSpring = new IntergenSolution[2];

            offSpring[0] = new IntergenSolution(parent1);
            offSpring[1] = new IntergenSolution(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));
                            //Console.WriteLine("Beta1" + beta);
                            alpha = 2.0 - Math.Pow(beta, -(distributionIndex + 1.0));

                            if (rand <= (1.0 / alpha))
                            {
                                betaq = Math.Pow((rand * alpha), (1.0 / (distributionIndex + 1.0)));

                                /* if (double.IsNaN(betaq))
                                 * {
                                 *   Console.WriteLine("NAN BETAq");
                                 * } */
                            }
                            else
                            {
                                betaq = Math.Pow((1.0 / (2.0 - rand * alpha)), (1.0 / (distributionIndex + 1.0)));

                                /* var betax = Math.Pow((1.0 / (2.0 - rand * alpha)), (1.0 / (distributionIndex + 1.0)));
                                 * if (double.IsNaN(betax))
                                 * {
                                 *   Console.WriteLine("NAN BETAx");
                                 * }
                                 * if (double.IsNaN(betaq))
                                 * {
                                 *   Console.WriteLine("NAN BETAq");
                                 * }
                                 */
                            }

                            /*
                             * if (double.IsNaN(betaq))
                             * {
                             *  Console.WriteLine("NAN BETAq");
                             * } */
                            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)));

                                /*if (double.IsNaN(betaq))
                                 * {
                                 *  Console.WriteLine("NAN BETAq");
                                 * } */
                            }
                            else
                            {
                                betaq = Math.Pow((1.0 / (2.0 - rand * alpha)), (1.0 / (distributionIndex + 1.0)));

                                /*if (double.IsNaN(betaq))
                                 * {
                                 *  Console.WriteLine("NAN BETAq");
                                 * }*/
                            }

                            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 (double.IsNaN(c2) || double.IsNaN(c1))
                             * {
                             *  Console.WriteLine("Setting NAN");
                             * } */

                            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);
                    }
                }
            }



            /*
             * var o1 = offSpring[0];
             * XReal values = new XReal(o1);
             * for (int u = 0; u < values.Size(); u++)
             * {
             *
             *  if (double.IsNaN(values.GetValue(u)))
             *  {
             *
             *      Console.WriteLine("crossover NAN1");
             *  }
             * }
             *
             * var s = offSpring[1];
             * XReal values2 = new XReal(s);
             * for (int u = 0; u < values2.Size(); u++)
             * {
             *  if (double.IsNaN(values2.GetValue(u)))
             *  {
             *      Console.WriteLine("crossover NAN2");
             *  }
             * } */

            return(offSpring);
        }
Пример #29
0
        public override SolutionSet Execute()
        {
            int maxEvaluations = -1;

            evaluations = 0;
            JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations);
            JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize);
            JMetalCSharp.Utils.Utils.GetStringValueFromParameter(this.InputParameters, "dataDirectory", ref dataDirectory);

            population  = new SolutionSet(populationSize);
            savedValues = new Solution[populationSize];
            utility     = new double[populationSize];
            frequency   = new int[populationSize];
            for (int i = 0; i < utility.Length; i++)
            {
                utility[i]   = 1.0;
                frequency[i] = 0;
            }
            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];

            lambda = new double[populationSize][];

            for (int i = 0; i < populationSize; i++)
            {
                lambda[i] = new double[Problem.NumberOfObjectives];
            }

            crossover = Operators["crossover"];            // default: DE crossover
            mutation  = Operators["mutation"];             // default: polynomial mutation

            // STEP 1. Initialization
            // STEP 1.1. Compute euclidean distances between weight vectors and find T
            InitUniformWeight();
            InitNeighborhood();

            // STEP 1.2. Initialize population
            InitPopulation();

            // STEP 1.3. Initialize z
            InitIdealPoint();

            int gen = 0;

            // STEP 2. Update
            do
            {
                int[] permutation = new int[populationSize];
                Utils.RandomPermutation(permutation, populationSize);
                List <int> order = TourSelection(10);

                for (int i = 0; i < order.Count; i++)
                {
                    int n = order[i];
                    frequency[n]++;

                    int    type;
                    double rnd = JMetalRandom.NextDouble();

                    // STEP 2.1. Mating selection based on probability
                    if (rnd < delta)
                    {
                        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);
                }

                gen++;
                if (gen % 30 == 0)
                {
                    CompUtility();
                }
            } while (evaluations < maxEvaluations);

            int finalSize = populationSize;

            try
            {
                finalSize = (int)GetInputParameter("finalSize");

                Logger.Log.Info("FINAL SIZE: " + finalSize);
                Console.WriteLine("FINAL SIZE: " + finalSize);
            }
            catch (Exception ex)
            {             // if there is an exception indicate it!
                Logger.Log.Warn("The final size paramater has been ignored", ex);
                Logger.Log.Warn("The number of solutions is " + population.Size());
                Console.WriteLine("The final size paramater has been ignored");
                Console.WriteLine("The number of solutions is " + population.Size());
                return(population);
            }

            Result = FinalSelection(finalSize);
            return(Result);
        }
Пример #30
0
        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);
        }