Ejemplo n.º 1
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);
        }
        /// <summary>
        /// Runs the SMS-EMOA algorithm.
        /// </summary>
        /// <returns>A <code>SolutionSet</code> that is a set of non dominated solutions as a result of the algorithm execution</returns>
        public override SolutionSet Execute()
        {
            int    populationSize = -1;
            int    maxEvaluations = -1;
            int    evaluations;
            double offset = 100.0;

            QualityIndicator.QualityIndicator indicators = null; // QualityIndicator object
            int requiredEvaluations;                             // Use in the example of use of the indicators object (see below)

            SolutionSet population;
            SolutionSet offspringPopulation;
            SolutionSet union;

            Operator mutationOperator;
            Operator crossoverOperator;
            Operator selectionOperator;

            //Read the parameters
            JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize);
            JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations);
            JMetalCSharp.Utils.Utils.GetIndicatorsFromParameters(this.InputParameters, "indicators", ref indicators);
            JMetalCSharp.Utils.Utils.GetDoubleValueFromParameter(this.InputParameters, "offset", ref offset);

            //Initialize the variables
            population  = new SolutionSet(populationSize);
            evaluations = 0;

            requiredEvaluations = 0;

            //Read the operators
            mutationOperator  = Operators["mutation"];
            crossoverOperator = Operators["crossover"];
            selectionOperator = Operators["selection"];

            // Create the initial solutionSet
            Solution newSolution;

            for (int i = 0; i < populationSize; i++)
            {
                newSolution = new Solution(Problem);
                Problem.Evaluate(newSolution);
                Problem.EvaluateConstraints(newSolution);
                evaluations++;
                population.Add(newSolution);
            }

            // Generations ...
            while (evaluations < maxEvaluations)
            {
                // select parents
                offspringPopulation = new SolutionSet(populationSize);
                List <Solution> selectedParents = new List <Solution>();
                Solution[]      parents         = new Solution[0];
                while (selectedParents.Count < 2)
                {
                    object selected = selectionOperator.Execute(population);
                    try
                    {
                        Solution parent = (Solution)selected;
                        selectedParents.Add(parent);
                    }
                    catch (InvalidCastException e)
                    {
                        parents = (Solution[])selected;
                        selectedParents.AddRange(parents);
                    }
                }
                parents = selectedParents.ToArray <Solution>();

                // crossover
                Solution[] offSpring = (Solution[])crossoverOperator.Execute(parents);

                // mutation
                mutationOperator.Execute(offSpring[0]);

                // evaluation
                Problem.Evaluate(offSpring[0]);
                Problem.EvaluateConstraints(offSpring[0]);

                // insert child into the offspring population
                offspringPopulation.Add(offSpring[0]);

                evaluations++;

                // Create the solutionSet union of solutionSet and offSpring
                union = ((SolutionSet)population).Union(offspringPopulation);

                // Ranking the union (non-dominated sorting)
                Ranking ranking = new Ranking(union);

                // ensure crowding distance values are up to date
                // (may be important for parent selection)
                for (int j = 0; j < population.Size(); j++)
                {
                    population.Get(j).CrowdingDistance = 0.0;
                }

                SolutionSet lastFront = ranking.GetSubfront(ranking.GetNumberOfSubfronts() - 1);
                if (lastFront.Size() > 1)
                {
                    double[][] frontValues        = lastFront.WriteObjectivesToMatrix();
                    int        numberOfObjectives = Problem.NumberOfObjectives;
                    // STEP 1. Obtain the maximum and minimum values of the Pareto front
                    double[] maximumValues = utils.GetMaximumValues(union.WriteObjectivesToMatrix(), numberOfObjectives);
                    double[] minimumValues = utils.GetMinimumValues(union.WriteObjectivesToMatrix(), numberOfObjectives);
                    // STEP 2. Get the normalized front
                    double[][] normalizedFront = utils.GetNormalizedFront(frontValues, maximumValues, minimumValues);
                    // compute offsets for reference point in normalized space
                    double[] offsets = new double[maximumValues.Length];
                    for (int i = 0; i < maximumValues.Length; i++)
                    {
                        offsets[i] = offset / (maximumValues[i] - minimumValues[i]);
                    }
                    // STEP 3. Inverse the pareto front. This is needed because the original
                    //metric by Zitzler is for maximization problems
                    double[][] invertedFront = utils.InvertedFront(normalizedFront);
                    // shift away from origin, so that boundary points also get a contribution > 0
                    for (int j = 0, lj = invertedFront.Length; j < lj; j++)
                    {
                        var point = invertedFront[j];
                        for (int i = 0; i < point.Length; i++)
                        {
                            point[i] += offsets[i];
                        }
                    }

                    // calculate contributions and sort
                    double[] contributions = HvContributions(invertedFront);
                    for (int i = 0; i < contributions.Length; i++)
                    {
                        // contribution values are used analogously to crowding distance
                        lastFront.Get(i).CrowdingDistance = contributions[i];
                    }

                    lastFront.Sort(new CrowdingDistanceComparator());
                }

                // all but the worst are carried over to the survivor population
                SolutionSet front = null;
                population.Clear();
                for (int i = 0; i < ranking.GetNumberOfSubfronts() - 1; i++)
                {
                    front = ranking.GetSubfront(i);
                    for (int j = 0; j < front.Size(); j++)
                    {
                        population.Add(front.Get(j));
                    }
                }
                for (int i = 0; i < lastFront.Size() - 1; i++)
                {
                    population.Add(lastFront.Get(i));
                }

                // This piece of code shows how to use the indicator object into the code
                // of SMS-EMOA. In particular, it finds the number of evaluations required
                // by the algorithm to obtain a Pareto front with a hypervolume higher
                // than the hypervolume of the true Pareto front.
                if (indicators != null && requiredEvaluations == 0)
                {
                    double HV = indicators.GetHypervolume(population);
                    if (HV >= (0.98 * indicators.TrueParetoFrontHypervolume))
                    {
                        requiredEvaluations = evaluations;
                    }
                }
            }

            // Return as output parameter the required evaluations
            SetOutputParameter("evaluations", requiredEvaluations);

            // Return the first non-dominated front
            Ranking rnk = new Ranking(population);

            Result = rnk.GetSubfront(0);
            return(Result);
        }
        public static void GetIndicatorsFromParameters(Dictionary <string, object> parameters, string parameterText, ref QualityIndicator.QualityIndicator indicators)
        {
            object value;

            if (parameters.TryGetValue(parameterText, out value))
            {
                indicators = (QualityIndicator.QualityIndicator)value;
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Runs the NSGA-II algorithm.
        /// </summary>
        /// <returns>a <code>SolutionSet</code> that is a set of non dominated solutions as a result of the algorithm execution</returns>
        public override SolutionSet Execute()
        {
            int populationSize = -1;
            int maxEvaluations = -1;
            int evaluations;

            QualityIndicator.QualityIndicator indicators = null; // QualityIndicator object
            int requiredEvaluations;                             // Use in the example of use of the
            // indicators object (see below)

            SolutionSet population;
            SolutionSet offspringPopulation;
            SolutionSet union;

            Operator mutationOperator;
            Operator crossoverOperator;
            Operator selectionOperator;

            Distance distance = new Distance();

            //Read the parameters
            JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations);
            JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize);
            JMetalCSharp.Utils.Utils.GetIndicatorsFromParameters(this.InputParameters, "indicators", ref indicators);

            //Initialize the variables
            population  = new SolutionSet(populationSize);
            evaluations = 0;

            requiredEvaluations = 0;

            //Read the operators
            mutationOperator  = Operators["mutation"];
            crossoverOperator = Operators["crossover"];
            selectionOperator = Operators["selection"];

            Random random = new Random(2);

            JMetalRandom.SetRandom(random);

            // Create the initial solutionSet
            Solution newSolution;

            for (int i = 0; i < populationSize; i++)
            {
                newSolution = new Solution(Problem);
                Problem.Evaluate(newSolution);
                Problem.EvaluateConstraints(newSolution);
                evaluations++;
                population.Add(newSolution);
            }

            // Generations
            while (evaluations < maxEvaluations)
            {
                // Create the offSpring solutionSet
                offspringPopulation = new SolutionSet(populationSize);
                Solution[] parents = new Solution[2];
                for (int i = 0; i < (populationSize / 2); i++)
                {
                    if (evaluations < maxEvaluations)
                    {
                        //obtain parents
                        parents[0] = (Solution)selectionOperator.Execute(population);
                        parents[1] = (Solution)selectionOperator.Execute(population);
                        Solution[] offSpring = (Solution[])crossoverOperator.Execute(parents);
                        mutationOperator.Execute(offSpring[0]);
                        mutationOperator.Execute(offSpring[1]);
                        Problem.Evaluate(offSpring[0]);
                        Problem.EvaluateConstraints(offSpring[0]);
                        Problem.Evaluate(offSpring[1]);
                        Problem.EvaluateConstraints(offSpring[1]);
                        offspringPopulation.Add(offSpring[0]);
                        offspringPopulation.Add(offSpring[1]);
                        evaluations += 2;
                    }
                }

                // Create the solutionSet union of solutionSet and offSpring
                union = ((SolutionSet)population).Union(offspringPopulation);


                var list   = union.SolutionsList;
                var unique = list.Distinct(new ComparerP()).ToList();

                union = new SolutionSet(unique.Count);
                union.SolutionsList.AddRange(unique);

                //ConfigurationSolutionType.AllSolutions = new object ();

                // Ranking the union
                Ranking ranking = new Ranking(union);

                int         remain = populationSize;
                int         index  = 0;
                SolutionSet front  = null;
                population.Clear();

                // Obtain the next front
                front = ranking.GetSubfront(index);

                while ((remain > 0) && (remain >= front.Size()))
                {
                    //Assign crowding distance to individuals
                    distance.CrowdingDistanceAssignment(front, Problem.NumberOfObjectives);
                    //Add the individuals of this front
                    for (int k = 0; k < front.Size(); k++)
                    {
                        population.Add(front.Get(k));
                    }

                    //Decrement remain
                    remain = remain - front.Size();

                    //Obtain the next front
                    index++;
                    if (remain > 0)
                    {
                        front = ranking.GetSubfront(index);
                    }
                }

                // Remain is less than front(index).size, insert only the best one
                if (remain > 0)
                {                  // front contains individuals to insert
                    distance.CrowdingDistanceAssignment(front, Problem.NumberOfObjectives);
                    front.Sort(new CrowdingComparator());
                    for (int k = 0; k < remain; k++)
                    {
                        population.Add(front.Get(k));
                    }

                    remain = 0;
                }

                // This piece of code shows how to use the indicator object into the code
                // of NSGA-II. In particular, it finds the number of evaluations required
                // by the algorithm to obtain a Pareto front with a hypervolume higher
                // than the hypervolume of the true Pareto front.
                if ((indicators != null) && (requiredEvaluations == 0))
                {
                    double HV = indicators.GetHypervolume(population);
                    if (HV >= (0.98 * indicators.TrueParetoFrontHypervolume))
                    {
                        requiredEvaluations = evaluations;
                    }
                }
            }

            // Return as output parameter the required evaluations
            SetOutputParameter("evaluations", requiredEvaluations);


            // Return the first non-dominated front
            Ranking rank = new Ranking(population);

            Result = rank.GetSubfront(0);

            return(population);
        }
        /// <summary>
        /// Runs the FastSMSEMOA algorithm.
        /// </summary>
        /// <returns> a <code>SolutionSet</code> that is a set of non dominated solutions as a result of the algorithm execution</returns>
        public override SolutionSet Execute()
        {
            int    populationSize = -1;
            int    maxEvaluations = -1;
            int    evaluations;
            double offset = -1;

            QualityIndicator.QualityIndicator indicators = null; // QualityIndicator object
            int requiredEvaluations;                             // Use in the example of use of the indicators object (see below)

            FastHypervolume fastHypervolume;

            SolutionSet population;
            SolutionSet offspringPopulation;
            SolutionSet union;

            Operator mutationOperator;
            Operator crossoverOperator;
            Operator selectionOperator;

            //Read the parameters
            JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize);
            JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations);
            JMetalCSharp.Utils.Utils.GetIndicatorsFromParameters(this.InputParameters, "indicators", ref indicators);
            JMetalCSharp.Utils.Utils.GetDoubleValueFromParameter(this.InputParameters, "offset", ref offset);


            //Initialize the variables
            population  = new SolutionSet(populationSize);
            evaluations = 0;

            requiredEvaluations = 0;

            fastHypervolume = new FastHypervolume(offset);

            //Read the operators
            mutationOperator  = Operators["mutation"];
            crossoverOperator = Operators["crossover"];
            selectionOperator = Operators["selection"];

            // Create the initial solutionSet
            Solution newSolution;

            for (int i = 0; i < populationSize; i++)
            {
                newSolution = new Solution(Problem);
                Problem.Evaluate(newSolution);
                Problem.EvaluateConstraints(newSolution);
                evaluations++;
                population.Add(newSolution);
            }

            // Generations ...
            while (evaluations < maxEvaluations)
            {
                // select parents
                offspringPopulation = new SolutionSet(populationSize);
                List <Solution> selectedParents = new List <Solution>();
                Solution[]      parents         = new Solution[0];
                while (selectedParents.Count < 2)
                {
                    object selected = selectionOperator.Execute(population);

                    try
                    {
                        Solution parent = (Solution)selected;
                        selectedParents.Add(parent);
                    }
                    catch (InvalidCastException e)
                    {
                        parents = (Solution[])selected;
                        selectedParents.AddRange(parents);
                    }
                }
                parents = selectedParents.ToArray <Solution>();

                // crossover
                Solution[] offSpring = (Solution[])crossoverOperator.Execute(parents);

                // mutation
                mutationOperator.Execute(offSpring[0]);

                // evaluation
                Problem.Evaluate(offSpring[0]);
                Problem.EvaluateConstraints(offSpring[0]);

                // insert child into the offspring population
                offspringPopulation.Add(offSpring[0]);

                evaluations++;

                // Create the solutionSet union of solutionSet and offSpring
                union = ((SolutionSet)population).Union(offspringPopulation);

                // Ranking the union (non-dominated sorting)
                Ranking ranking = new Ranking(union);

                // ensure crowding distance values are up to date
                // (may be important for parent selection)
                for (int j = 0; j < population.Size(); j++)
                {
                    population.Get(j).CrowdingDistance = 0.0;
                }

                SolutionSet lastFront = ranking.GetSubfront(ranking.GetNumberOfSubfronts() - 1);

                fastHypervolume.ComputeHVContributions(lastFront);
                lastFront.Sort(new CrowdingDistanceComparator());

                // all but the worst are carried over to the survivor population
                SolutionSet front = null;
                population.Clear();
                for (int i = 0; i < ranking.GetNumberOfSubfronts() - 1; i++)
                {
                    front = ranking.GetSubfront(i);
                    for (int j = 0; j < front.Size(); j++)
                    {
                        population.Add(front.Get(j));
                    }
                }
                for (int i = 0; i < lastFront.Size() - 1; i++)
                {
                    population.Add(lastFront.Get(i));
                }

                // This piece of code shows how to use the indicator object into the code
                // of SMS-EMOA. In particular, it finds the number of evaluations required
                // by the algorithm to obtain a Pareto front with a hypervolume higher
                // than the hypervolume of the true Pareto front.
                if (indicators != null && requiredEvaluations == 0)
                {
                    double HV = indicators.GetHypervolume(population);
                    if (HV >= (0.98 * indicators.TrueParetoFrontHypervolume))
                    {
                        requiredEvaluations = evaluations;
                    }
                }
            }

            // Return as output parameter the required evaluations
            SetOutputParameter("evaluations", requiredEvaluations);

            // Return the first non-dominated front
            Ranking rnk = new Ranking(population);

            Result = rnk.GetSubfront(0);
            return(Result);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Runs the NSGA-II algorithm.
        /// </summary>
        /// <returns>a <code>SolutionSet</code> that is a set of non dominated solutions as a result of the algorithm execution</returns>
        public override SolutionSet Execute()
        {
            int populationSize   = -1;
            int maxEvaluations   = -1;
            int iterationsNumber = -1;
            int evaluations;
            int iteration;

            QualityIndicator.QualityIndicator indicators = null; // QualityIndicator object
            int requiredEvaluations;                             // Use in the example of use of the
            // indicators object (see below)

            SolutionSet population;
            SolutionSet offspringPopulation;
            SolutionSet union;

            Operator mutationOperator;
            Operator crossoverOperator;
            Operator selectionOperator;

            Distance distance = new Distance();

            //Read the parameters
            JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "maxEvaluations", ref maxEvaluations);
            JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "populationSize", ref populationSize);
            JMetalCSharp.Utils.Utils.GetIntValueFromParameter(this.InputParameters, "iterationsNumber", ref iterationsNumber);
            JMetalCSharp.Utils.Utils.GetIndicatorsFromParameters(this.InputParameters, "indicators", ref indicators);

            //Initialize the variables
            population  = new SolutionSet(populationSize);
            evaluations = 0;
            iteration   = 0;

            requiredEvaluations = 0;

            //Read the operators
            mutationOperator  = Operators["mutation"];
            crossoverOperator = Operators["crossover"];
            selectionOperator = Operators["selection"];

            Random random = new Random();

            JMetalRandom.SetRandom(random);

            // Create the initial solutionSet
            Solution newSolution;

            for (int i = 0; i < populationSize; i++)
            {
                newSolution = new Solution(Problem);
                Problem.Evaluate(newSolution);
                Problem.EvaluateConstraints(newSolution);
                evaluations++;
                population.Add(newSolution);
            }

            /*
             * string dir = "Result/MOEAD_ACOR/ZDT4_Real/Record/NSGAII_SBX_nr16";
             * if (Directory.Exists(dir))
             * {
             *  Console.WriteLine("The directory {0} already exists.", dir);
             * }
             * else
             * {
             *  Directory.CreateDirectory(dir);
             *  Console.WriteLine("The directory {0} was created.", dir);
             * }*/

            // Generations
            while (iteration < iterationsNumber)
            {
                // Create the offSpring solutionSet
                offspringPopulation = new SolutionSet(populationSize);
                Solution[] parents = new Solution[2];
                for (int i = 0; i < (populationSize / 2); i++)
                {
                    if (iteration < iterationsNumber)
                    {
                        //obtain parents
                        parents[0] = (Solution)selectionOperator.Execute(population);
                        parents[1] = (Solution)selectionOperator.Execute(population);
                        Solution[] offSpring = (Solution[])crossoverOperator.Execute(parents);
                        mutationOperator.Execute(offSpring[0]);
                        mutationOperator.Execute(offSpring[1]);
                        Problem.Evaluate(offSpring[0]);
                        Problem.EvaluateConstraints(offSpring[0]);
                        Problem.Evaluate(offSpring[1]);
                        Problem.EvaluateConstraints(offSpring[1]);
                        offspringPopulation.Add(offSpring[0]);
                        offspringPopulation.Add(offSpring[1]);
                        evaluations += 2;
                    }
                }

                // Create the solutionSet union of solutionSet and offSpring
                union = ((SolutionSet)population).Union(offspringPopulation);

                // Ranking the union
                Ranking ranking = new Ranking(union);

                int         remain = populationSize;
                int         index  = 0;
                SolutionSet front  = null;
                population.Clear();

                // Obtain the next front
                front = ranking.GetSubfront(index);

                while ((remain > 0) && (remain >= front.Size()))
                {
                    //Assign crowding distance to individuals
                    distance.CrowdingDistanceAssignment(front, Problem.NumberOfObjectives);
                    //Add the individuals of this front
                    for (int k = 0; k < front.Size(); k++)
                    {
                        population.Add(front.Get(k));
                    }

                    //Decrement remain
                    remain = remain - front.Size();

                    //Obtain the next front
                    index++;
                    if (remain > 0)
                    {
                        front = ranking.GetSubfront(index);
                    }
                }

                // Remain is less than front(index).size, insert only the best one
                if (remain > 0)
                {                  // front contains individuals to insert
                    distance.CrowdingDistanceAssignment(front, Problem.NumberOfObjectives);
                    front.Sort(new CrowdingComparator());
                    for (int k = 0; k < remain; k++)
                    {
                        population.Add(front.Get(k));
                    }

                    remain = 0;
                }

                /*
                 * string filevar = dir + "/VAR" + iteration;
                 * string filefun = dir + "/FUN" + iteration;
                 * population.PrintVariablesToFile(filevar);
                 * population.PrintObjectivesToFile(filefun);*/

                iteration++;

                // This piece of code shows how to use the indicator object into the code
                // of NSGA-II. In particular, it finds the number of evaluations required
                // by the algorithm to obtain a Pareto front with a hypervolume higher
                // than the hypervolume of the true Pareto front.
                if ((indicators != null) && (requiredEvaluations == 0))
                {
                    double HV = indicators.GetHypervolume(population);
                    if (HV >= (0.98 * indicators.TrueParetoFrontHypervolume))
                    {
                        requiredEvaluations = evaluations;
                    }
                }
            }

            Logger.Log.Info("ITERATION: " + iteration);
            Console.WriteLine("ITERATION: " + iteration);

            // Return as output parameter the required evaluations
            SetOutputParameter("evaluations", requiredEvaluations);

            // Return the first non-dominated front
            Ranking rank = new Ranking(population);

            Result = rank.GetSubfront(0);

            return(Result);
        }