Ejemplo n.º 1
0
        public override void Evaluate(Solution solution)
        {
            _counter++;
            IntergenSolution s = (IntergenSolution)solution;

            s.FoundAtEval = _counter;

            var doubleVal = new double[Model.Setting.NumberOfFeatures];
            var values    = new XReal(solution);

            for (var i = 0; i < Model.Setting.NumberOfFeatures; i++)
            {
                doubleVal[i] = values.GetValue(i);
            }

            //the distribution from the NSGA2
            var nsgaFv = new Distribution(doubleVal);

            var fc            = new FitnessCalculator(Model, _counter);
            var fitnessValues = fc.Calculate(null, null, nsgaFv, FeatureTarget, null, null);

            solution.Objective[0] = fitnessValues.FeatureVal;

            FitnessTracker.AddFeat(s.FoundAtEval, fitnessValues.FeatureVal);
        }
Ejemplo n.º 2
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;

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

            SolutionSet population;
            SolutionSet offspringPopulation;
            SolutionSet union;

            Operator mutationOperator;
            Operator crossoverOperator;
            Operator selectionOperator;

            Distance distance = new Distance();

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

            parallelEvaluator.StartParallelRunner(Problem);;

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

            requiredEvaluations = 0;

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


            // Create the initial solutionSet
            IntergenSolution newSolution;

            for (int i = 0; i < populationSize; i++)
            {
                newSolution = new IntergenSolution((IntergenProblem)Problem);
                parallelEvaluator.AddTaskForExecution(new object[] { newSolution, i });;
            }

            List <IntergenSolution> solutionList = (List <IntergenSolution>)parallelEvaluator.ParallelExecution();

            foreach (IntergenSolution solution in solutionList)
            {
                population.Add(solution);
                evaluations++;
            }

            // Generations
            while (evaluations < maxEvaluations)
            {
                // Create the offSpring solutionSet
                offspringPopulation = new SolutionSet(populationSize);
                IntergenSolution[] parents = new IntergenSolution[2];

                for (int i = 0; i < (populationSize / 2); i++)
                {
                    if (evaluations < maxEvaluations)
                    {
                        //obtain parents
                        parents[0] = (IntergenSolution)selectionOperator.Execute(population);
                        parents[1] = (IntergenSolution)selectionOperator.Execute(population);
                        IntergenSolution[] offSpring = (IntergenSolution[])crossoverOperator.Execute(parents);
                        mutationOperator.Execute(offSpring[0]);
                        mutationOperator.Execute(offSpring[1]);

                        parallelEvaluator.AddTaskForExecution(new object[] { offSpring[0], evaluations + i });
                        parallelEvaluator.AddTaskForExecution(new object[] { offSpring[1], evaluations + i });
                    }
                }

                List <IntergenSolution> solutions = (List <IntergenSolution>)parallelEvaluator.ParallelExecution();

                foreach (IntergenSolution solution in solutions)
                {
                    offspringPopulation.Add(solution);
                    evaluations++;
                    //solution.FoundAtEval = evaluations;
                }

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

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

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

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

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

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

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

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

                    remain = 0;
                }

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

                //TODO

                /*
                 * Ranking rank2 = new Ranking(population);
                 *
                 * Result = rank2.GetSubfront(0);
                 */

                /*Ranking forGraphicOutput = new Ranking(population);
                 * var currentBestResultSet = forGraphicOutput.GetSubfront(0);
                 *
                 * var firstBestResult = currentBestResultSet.Get(0);
                 *
                 * var myProblem = (IntergenProblem)Problem;
                 * //myProblem.calculated;
                 *
                 * //var variantValuesWithoutInteraction = Matrix.Multiply(myProblem.calculated, firstBestResult.);
                 * //var Model = myProblem.GetModel();
                 * int mycounter = 0;
                 * if (mycounter % 500 == 0)
                 * {
                 *  //RIntegrator.PlotValues(currentBestResultSet, myProblem);
                 * }
                 * mycounter++;
                 * var progress = new UserProgress();
                 * progress.FeatureP = firstBestResult.Objective[0];
                 * if (!myProblem.Model.Setting.NoVariantCalculation) progress.VariantP = firstBestResult.Objective[1];
                 * myProblem.Worker.ReportProgress(evaluations * 100 / maxEvaluations, progress); ;
                 *
                 * //Model.CurrentBestImage = "CurrentBest.png"; */
                front = ranking.GetSubfront(0);

                var minmax = new MinMaxFitness
                {
                    FeatMax  = double.MinValue,
                    FeatMin  = double.MaxValue,
                    VarMax   = double.MinValue,
                    VarMin   = double.MaxValue,
                    InterMax = double.MinValue,
                    InterMin = double.MaxValue
                };
                var prob = (IntergenProblem)Problem;
                var list = ObjectiveMapping.GetList(prob.ProblemType);
                for (var i = 0; i < populationSize; i++)
                {
                    var sol = population.Get(i);



                    var objindex = 0;
                    if (list[0])
                    {
                        if (sol.Objective[objindex] < minmax.FeatMin)
                        {
                            minmax.FeatMin = sol.Objective[objindex];
                        }
                        if (sol.Objective[objindex] > minmax.FeatMax)
                        {
                            minmax.FeatMax = sol.Objective[objindex];
                        }

                        objindex++;
                    }
                    if (list[1])
                    {
                        if (sol.Objective[objindex] < minmax.InterMin)
                        {
                            minmax.InterMin = sol.Objective[objindex];
                        }
                        if (sol.Objective[objindex] > minmax.InterMax)
                        {
                            minmax.InterMax = sol.Objective[objindex];
                        }

                        objindex++;
                    }
                    if (list[2])
                    {
                        if (sol.Objective[objindex] < minmax.VarMin)
                        {
                            minmax.VarMin = sol.Objective[objindex];
                        }
                        if (sol.Objective[objindex] > minmax.VarMax)
                        {
                            minmax.VarMax = sol.Objective[objindex];
                        }
                    }
                }

                var sol0 = front.Best(new CrowdingDistanceComparator());
                var done = FitnessTracker.AddFitn(minmax);
                SolutionPlotter.Plot(sol0);
                ProgressReporter.ReportSolution(evaluations, sol0, _worker);

                if (done)
                {
                    Ranking rank3 = new Ranking(population);

                    Result = rank3.GetSubfront(0);
                    SetOutputParameter("evaluations", evaluations);

                    return(this.Result);
                }
            }
            // Return as output parameter the required evaluations
            SetOutputParameter("evaluations", evaluations);

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

            Result = rank.GetSubfront(0);

            return(this.Result);
        }
Ejemplo n.º 3
0
        public override void Evaluate(Solution solution)
        {
#if DEBUG
            if (_counter == 0)
            {
                if (Model.Setting.Logging)
                {
                    LogArrayValues(FeatureTarget.Values, "targetFeatures");
                    if (Model.Setting.NumberOfInteractions > 0)
                    {
                        LogArrayValues(InteractionTarget.Values, "targetInteraction");
                    }
                }
            }

            _counter++;
#endif
            Console.WriteLine(_counter);
            Distribution variantTarget = null;
            if (!Model.Setting.NoVariantCalculation)
            {
                var localScaledVariants = new double[ScaledVariantTarget.Values.Length];
                Array.Copy(ScaledVariantTarget.Values, localScaledVariants, ScaledVariantTarget.Values.Length);
                variantTarget = new Distribution(localScaledVariants);
            }
            var doubleVal  = new double[Model.Setting.NumberOfFeatures];
            var interacVal = new double[Model.Setting.NumberOfInteractions];
            var values     = new XReal(solution);
            for (var i = 0; i < Model.Setting.NumberOfFeatures; i++)
            {
                doubleVal[i] = values.GetValue(i);
            }

            for (var i = 0; i < Model.Setting.NumberOfInteractions; i++)
            {
                interacVal[i] = values.GetValue(i + Model.Setting.NumberOfFeatures);
            }

            //the distribution from the NSGA2
            var nsgaFv      = new Distribution(doubleVal);
            var interacDist = new Distribution(interacVal);

            var watch = Stopwatch.StartNew();
            //calculate the variant values
            Distribution variantResult = null;

            if (_counter > 9500)
            {
                var variantValuesWithoutInteraction = FeatureMatrix.Dot(doubleVal);



                if (Model.Setting.NumberOfInteractions > 0)
                {
                    var interacVals    = InteractionMatrix.Dot(interacVal);
                    var variantResults = variantValuesWithoutInteraction.Add(interacVals);
                    variantResult = new Distribution(variantResults);
                }
                else
                {
                    variantResult = new Distribution(variantValuesWithoutInteraction);
                }
            }
            watch.Stop();
            calcTime += watch.ElapsedMilliseconds;

            //scale the variant target distribution to the size of the calculated variant distribution

            var       scaleWatch = Stopwatch.StartNew();
            FMScaling fms        = new FMScaling(Model);
            if (Model.Setting.ScaleToGlobalMinMax)
            {
                var change = false;
                if (currentMin > variantResult.Values.Min())
                {
                    currentMin = variantResult.Values.Min();
                    change     = true;
                }
                if (currentMax < variantResult.Values.Max())
                {
                    currentMax = variantResult.Values.Max();
                    change     = true;
                }
                if (change)
                {
                    ScaledVariantTarget = FMScaling.InteractionToScale(ScaledVariantTarget, currentMin, currentMax);
                }
            }
            else
            {
                if (!Model.Setting.NoVariantCalculation)
                {
                    variantTarget = FMScaling.InteractionToScale(variantTarget, variantResult.Values.Min(),
                                                                 variantResult.Values.Max());
                }
            }

            scaleWatch.Stop();
            scaleTime += scaleWatch.ElapsedMilliseconds;

            IntergenSolution s = (IntergenSolution)solution;
            s.FoundAtEval = _counter;


            var testWatch = Stopwatch.StartNew();
            //calculate the fitness values for features and variants



            var fc            = new FitnessCalculator(Model, _counter);
            var fitnessValues = fc.Calculate(variantResult, variantTarget, nsgaFv, FeatureTarget, interacDist, InteractionTarget);
            solution.Objective[0] = fitnessValues.FeatureVal;

            if (Model.Setting.NoVariantCalculation)
            {
                if (Model.Setting.NumberOfInteractions > 0)
                {
                    solution.Objective[1] = fitnessValues.InteracVal;
                }
            }
            else
            {
                //interacs and variants
                if (Model.Setting.NumberOfInteractions > 0)
                {
                    solution.Objective[1] = fitnessValues.InteracVal;
                    solution.Objective[2] = fitnessValues.VariantVal;
                }
                else
                {
                    solution.Objective[1] = fitnessValues.VariantVal;
                }
            }



            /* if (Model.Setting.UseKs)
             * {
             *  PerfomKs(variantResult, variantTarget, nsgaFv, FeatureTarget, solution);
             *
             * }
             * else if (Model.Setting.UseCmv)
             * {
             *  PerformCmv(variantResult, variantTarget, nsgaFv, FeatureTarget, InteractionTarget, interacDist, solution);
             * }
             * else if (Model.Setting.UseEuclidean) {
             *  var bd = new BinnedDistance(variantTarget, variantResult, Model.VariantDynamicHist, _counter);
             *  var bd2 = new BinnedDistance(nsgaFv, FeatureTarget, Model.FeaturesDynamicHist, _counter);
             *
             *  solution.Objective[0] = bd2.EuclidianDist();
             *  solution.Objective[1] = bd.EuclidianDist();
             *  if (Model.Setting.NumberOfInteractions > 0)
             *  {
             *      var interac = new BinnedDistance(interacDist, InteractionTarget, Model.InteracDynamicHist, _counter);
             *      solution.Objective[2] = interac.EuclidianDist();
             *  }
             * }
             * else if (Model.Setting.UseChiSquared)
             * {
             *  var bd = new BinnedDistance(variantTarget, variantResult, Model.VariantDynamicHist,
             *      _counter);
             *  var bd2 = new BinnedDistance(nsgaFv, FeatureTarget, Model.FeaturesDynamicHist, _counter);
             *
             *
             *  solution.Objective[0] = bd2.ChiSquaredDist();
             *  solution.Objective[1] = bd.ChiSquaredDist();
             *  if (Model.Setting.NumberOfInteractions > 0)
             *  {
             *      var interac = new BinnedDistance(interacDist, InteractionTarget, Model.InteracDynamicHist, _counter);
             *      solution.Objective[2] = interac.ChiSquaredDist();
             *  }
             * }
             * else if (Model.Setting.EuclAndCmv)
             * {
             *  PerformCmv(variantTarget, variantResult, nsgaFv, FeatureTarget, InteractionTarget, interacDist, solution);
             *
             *  var variant = new BinnedDistance(variantTarget, variantResult, Model.VariantDynamicHist, _counter);
             *  var feat = new BinnedDistance(nsgaFv, FeatureTarget, Model.FeaturesDynamicHist, _counter);
             *  var interac = new BinnedDistance(interacDist, InteractionTarget, Model.InteracDynamicHist, _counter);
             *
             *  solution.Objective[3] = feat.EuclidianDist();
             *  solution.Objective[4] = variant.EuclidianDist();
             *  solution.Objective[5] = interac.EuclidianDist();
             * }
             * else if (Model.Setting.ChiAndCmv)
             * {
             *  PerformCmv(variantTarget, variantResult, nsgaFv, FeatureTarget, InteractionTarget, interacDist, solution);
             * var variant = new BinnedDistance(variantTarget, variantResult, Model.VariantDynamicHist,_counter);
             *  var feat = new BinnedDistance(nsgaFv, FeatureTarget, Model.FeaturesDynamicHist, _counter);
             *  var interac = new BinnedDistance(interacDist, InteractionTarget, Model.InteracDynamicHist, _counter);
             *  solution.Objective[3] = feat.ChiSquaredDist();
             *  solution.Objective[4] = variant.ChiSquaredDist();
             *  solution.Objective[5] = interac.ChiSquaredDist();
             * }
             */
            testWatch.Stop();
            fitnessTime += testWatch.ElapsedMilliseconds;

            //report our progress to the model for GUI
            if (_counter % 200 == 0)
            {
                if (!Model.Setting.Parallel /*|| (Model.Parallel && parallelIndex % 50 == 0) */)
                {
                    if (Model.Setting.DrawDensity && Model.Setting.DrawHistogram)
                    {
                        RIntegrator.FeatureHistAndDens(nsgaFv.Values, FeatureTarget.Values);
                        RIntegrator.VariantHistAndDens(variantResult.Values, variantTarget.Values);
                    }
                    else if (Model.Setting.DrawDensity)
                    {
                        RIntegrator.PlotFeatureTarget(nsgaFv.Values, FeatureTarget.Values, Model.Setting.FeatureAdjust);
                        if (Model.Setting.NoVariantCalculation)
                        {
                            if (_counter > 9500)
                            {
                                RIntegrator.PlotVariantTarget(variantResult.Values);
                            }
                        }
                        else
                        {
                            RIntegrator.PlotVariantTarget(variantResult.Values, variantTarget.Values);
                        }

                        if (Model.Setting.NumberOfInteractions > 0)
                        {
                            RIntegrator.PlotInteracTarget(interacDist.Values, InteractionTarget.Values);
                        }
                    }
                    else if (Model.Setting.DrawHistogram)
                    {
                        RIntegrator.FeatureComparisonHist(nsgaFv.Values, FeatureTarget.Values);

                        if (Model.Setting.NoVariantCalculation)
                        {
                            RIntegrator.PlotVariantTarget(variantResult.Values);
                        }
                        else
                        {
                            RIntegrator.VariantComparisonHisto(variantResult.Values, variantTarget.Values);
                        }
                    }


                    else
                    {
                    }

                    //ReportProgress(solution);
                }
                ReportProgress(solution, fitnessValues);
                //Worker.ReportProgress((int)(counter * 100 / (double)Model.MaxEvaluations), new UserProgress { VariantP = solution.Objective[1], FeatureP = solution.Objective[0] });
            }

            if (_counter == Model.Setting.MaxEvaluations)
            {
                Console.WriteLine("FitnessTime: " + fitnessTime);
                Console.WriteLine("ScaleTime: " + scaleTime);
                Console.WriteLine("CalcTime: " + calcTime);
            }

            var cont = new SolutionContainer
            {
                //TargetVariant = variantTarget,
                Variant     = variantResult,
                Features    = nsgaFv,
                Interaction = interacDist,
                //TargetFeatures = FeatureTarget,
                FeatureTVal = fitnessValues.FeatureVal,
                InteracTVal = fitnessValues.InteracVal,
                VariantTVal = fitnessValues.VariantVal,

                CalcTime    = watch.ElapsedMilliseconds,
                FitnessTime = testWatch.ElapsedMilliseconds,
                ScaleTime   = scaleWatch.ElapsedMilliseconds,
                TestName    = GetUsedTest(),
                FoundAtEval = _counter,
            };


            //if (_counter > 7000)
            //  {
            //    cont.Write(Model.Setting.LogFolder + "evalstep" + _counter + ".json");
            // }

            //cont = null;
            //Console.WriteLine(cont.FoundAtEval + "\t" +  cont.FeatureTVal + "\t" + cont.VariantTVal);



            if (Model.Setting.ChiAndCmv || Model.Setting.EuclAndCmv)
            {
                cont.AdditionalFeatureCmv = solution.Objective[4];
                cont.AdditionalVariantCmv = solution.Objective[5];
            }

            //if (!Model.Setting.Parallel)Model.History.Add(counter, cont);
            Model.AddSolutionToHistory(cont);

            if (!Model.Setting.Logging)
            {
                return;
            }
            var usedTest = GetUsedTest();

            //LogArrayValues(nsgaFV.Values, "Features");
            //LogArrayValues(variantResult.Values, "Variants");
            //LogArrayValues(ScaledVariantTarget.Values, "targetVariants");

            if (Model.Setting.NumberOfInteractions > 0)
            {
                LogSingleValue(fitnessValues.InteracVal, "InteracFitn" + usedTest);
            }
            if (!Model.Setting.NoVariantCalculation)
            {
                LogSingleValue(fitnessValues.VariantVal, "VarFitn" + usedTest);
            }
            LogSingleValue(fitnessValues.FeatureVal, "FeatFitn" + usedTest);
        }