Пример #1
0
        public void RunNSGAII <S>()
            where S : ContinuousVector, new()
        {
            NSGAII <S> algorithm = new NSGAII <S>(GetProblem());

            algorithm.PopulationSize = 100;

            algorithm.Initialize();

            ClearStatusInfo();

            BackgroundWorker worker = new BackgroundWorker();

            worker.WorkerReportsProgress = true;
            worker.DoWork += (s1, e1) =>
            {
                while (!algorithm.IsTerminated)
                {
                    algorithm.Evolve();
                    worker.ReportProgress(0);
                }
            };
            worker.ProgressChanged += (s1, e1) =>
            {
                txtStatus1.Text = string.Format("Current Generation: {0}", algorithm.CurrentGeneration);
                //Console.WriteLine("Number of Dominating Improvements: {0}", algorithm.NumberOfDominatingImprovements);
                txtStatus2.Text = string.Format("Size of Archive: {0}", algorithm.NondominatedArchiveSize);
            };
            worker.RunWorkerCompleted += (s1, e1) =>
            {
                NondominatedPopulation <S> archive = algorithm.NondominatedArchive;
                DisplayParetoFront(archive);
            };
            worker.RunWorkerAsync();
        }
Пример #2
0
        private static void SolveNSGAII()
        {
            NSGAII nsgaii = new NSGAII();

            Console.WriteLine("WA NSGAII Solver Started");
            Console.WriteLine("Press ESC to stop");

            var res = nsgaii.Solve();

            Console.WriteLine("WA NSGAII Solver Finished");
        }
Пример #3
0
        static void RunNSGAII()
        {
            NSGAII <ContinuousVector> algorithm = new NSGAII <ContinuousVector>(new NDNDProblem());

            algorithm.PopulationSize = 100;

            algorithm.Initialize();

            while (!algorithm.IsTerminated)
            {
                algorithm.Evolve();
                Console.WriteLine("Current Generation: {0}", algorithm.CurrentGeneration);
                Console.WriteLine("Size of Archive: {0}", algorithm.NondominatedArchiveSize);
            }
            ContinuousVector finalSolution = algorithm.GlobalBestSolution;
        }
Пример #4
0
        /// <summary>
        /// Create and return a NeatEvolutionAlgorithm object ready for running the NEAT algorithm/search. Various sub-parts
        /// of the algorithm are also constructed and connected up.
        /// This overload accepts a pre-built genome population and their associated/parent genome factory.
        /// </summary>
        public NeatEvolutionAlgorithm <NeatGenome> CreateEvolutionAlgorithm(IGenomeFactory <NeatGenome> genomeFactory, List <NeatGenome> genomeList)
        {
            // Create distance metric. Mismatched genes have a fixed distance of 10; for matched genes the distance is their weigth difference.
            IDistanceMetric distanceMetric = new ManhattanDistanceMetric(1.0, 0.0, 10.0);
            ISpeciationStrategy <NeatGenome> speciationStrategy = new ParallelKMeansClusteringStrategy <NeatGenome>(distanceMetric, _parallelOptions);

            // Create the evolution algorithm.
            NeatEvolutionAlgorithm <NeatGenome> ea = new NeatEvolutionAlgorithm <NeatGenome>(_eaParams, speciationStrategy, _complexityRegulationStrategy);

            // Create genome decoder.
            IGenomeDecoder <NeatGenome, IBlackBox> genomeDecoder = CreateGenomeDecoder();

            INoveltyScorer <NeatGenome>          noveltyScorer          = new TuringNoveltyScorer <NeatGenome>(_noveltySearchParams);
            IGeneticDiversityScorer <NeatGenome> geneticDiversityScorer = new GeneticDiversityKnn <NeatGenome>(_neatGenomeParams.ConnectionWeightRange);
            IMultiObjectiveScorer multiObjectiveScorer = new NSGAII(_multiObjectiveParams);

            _listEvaluator = new MultiObjectiveListEvaluator <NeatGenome, IBlackBox>(
                genomeDecoder,
                _evaluator,
                noveltyScorer,
                geneticDiversityScorer,
                multiObjectiveScorer,
                _multiThreading,
                _parallelOptions);

            _listEvaluator.MultiObjectiveParams = _multiObjectiveParams;
            _listEvaluator.ReportInterval       = _logInterval;

            NoveltySearchEnabled  = _noveltySearchParams?.Enabled ?? false;
            MultiObjectiveEnabled = _multiObjectiveParams?.Enabled ?? false;

            // Initialize the evolution algorithm.
            ea.Initialize(_listEvaluator, genomeFactory, genomeList);

            ea.UpdateScheme = new UpdateScheme(1);
            // Finished. Return the evolution algorithm
            return(ea);
        }
Пример #5
0
        private void Button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.Title      = "Open Matrix File";
            openFileDialog1.DefaultExt = "xlsx";
            openFileDialog1.Filter     = "Excel files (*.xlsx)|*.xlsx";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                label1.Text = openFileDialog1.FileName;
            }

            OpenExcel      a        = new OpenExcel(label1.Text);
            featureModel   fmO      = new featureModel(a.OldMatrix);
            PaireSet       newPairs = new PaireSet(a.newPairs);
            Compare        c        = new Compare(fmO, newPairs, a.ChangedFeatureList);
            FilterTestCase f        = new FilterTestCase(c);

            for (int i = 0; i < c.NewPairs.Count; i++)
            {
                listBox1.Items.Add(c.NewPairs[i].Feature1 + "," + c.NewPairs[i].Feature2);
            }
            listBox2.DataSource = f.RetestableTestCases;
            listBox3.DataSource = f.ReUsableTestCases;
            listBox4.DataSource = f.ObsoleteTestCases;
            listBox5.DataSource = GetPairsList(c.Changed);
            listBox6.DataSource = GetPairsList(c.SamePairs);
            listBox7.DataSource = GetPairsList(c.RemovedPairs);
            int[]    rowcol = new int[2];
            string[] arg    = new string[1];
            arg[0]        = "Regression";
            rowcol[0]     = f.Matrix.GetLength(0);
            rowcol[1]     = f.Matrix.GetLength(1);
            NSGAII.Matrix = f.Matrix;
            NSGAII.RowCol = rowcol;
            NSGAII.Main(arg);
        }
Пример #6
0
        private void Button1_Click(object sender, EventArgs e)
        {
            CleareLabel();

            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.Title      = "Open Matrix File";
            openFileDialog1.DefaultExt = "xlsx";
            openFileDialog1.Filter     = "Excel files (*.xlsx)|*.xlsx";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                FileName = getFileName(openFileDialog1.FileName.Split('\\').Last());
                string path = openFileDialog1.FileName;
                CurrentFileName = path.Split('\\').Last();
                label1.Text     = path;

                OpenExcel a = new OpenExcel(label1.Text);
                fmO = new featureModel(a.OldMatrix);
                PaireSet newPairs = new PaireSet(a.newPairs);
                compair = new Compare(fmO, newPairs, a.ChangedFeatureList);
                filter  = new FilterTestCase(compair);

                Faults = setFaults(compair.ChangedPairs.Count);

                List <string> list1Source = new List <string>();
                for (int i = 0; i < compair.NewPairs.Count; i++)
                {
                    list1Source.Add(compair.NewPairs[i].Feature1 + "," + compair.NewPairs[i].Feature2);
                }

                listBox1.DataSource = list1Source;
                listBox2.DataSource = filter.RetestableTestCases;
                listBox3.DataSource = filter.ReUsableTestCases;
                listBox4.DataSource = filter.ObsoleteTestCases;
                listBox5.DataSource = GetPairsList(compair.ChangedPairs);
                listBox6.DataSource = GetPairsList(compair.SamePairs);
                listBox7.DataSource = GetPairsList(compair.RemovedPairs);
                int[]    rowcol = new int[2];
                string[] arg    = new string[1];
                arg[0] = "Regression";

                rowcol[0]     = filter.Matrix.GetLength(0);
                rowcol[1]     = filter.Matrix.GetLength(1);
                NSGAII.Matrix = filter.Matrix;

                NSGAII.RowCol = rowcol;
                NSGAII.Main(arg);

                //JMetalCSharp.Core.SolutionSet s = new JMetalCSharp.Core.SolutionSet();
                List <string> fun = new List <string>();
                Var = NSGAII.variables;
                fun = NSGAII.fun;
                //fun.Sort();
                listBox8.DataSource = Var;
                listBox9.DataSource = SeperateFun(fun);



                RC = new computingRandom(fmO, compair, filter, Faults);
                double Randomreusability = RC.GetReusability(fmO.Pairs, RC.Variable.ToList());
                LRCover.Text = RC.UnCoverage;
                LRCost.Text  = RC.Cost;
                LRFDE.Text   = RC.FDE.ToString();
                string[] algo = listBox9.Items[0].ToString().Split("\t"[0]);

                int[] ourVariable = new int[compair.TestName.Count];
                ourVariable = SetOurVariable(filter.removedTest, Var[0]);


                computingRandom mr = new computingRandom();

                double MyFDE         = mr.GetFDE(ourVariable, Faults, compair.ChangedPairs);
                double MyReusability = mr.GetReusability(fmO.Pairs, ourVariable.ToList(), compair.ChangedPairs.Count);
                //double MyReusability = mr.GetReusability(compair.ChangedPairs, ourVariable.ToList(),compair.ChangedPairs.Count);
                Reusability    = (MyReusability - Randomreusability) / Randomreusability;
                MyFDE          = Math.Round(MyFDE, 2);
                Reusability    = Math.Round(Reusability, 2);
                Lcoverage.Text = algo[0];
                Lcost.Text     = algo[1].Trim();
                LFDE.Text      = MyFDE.ToString();


                //Appearence -------------------------------------------------------------
                if (Convert.ToDouble(RC.UnCoverage) > Convert.ToDouble(algo[0]))
                {
                    tick1.Text      = "\u2714";
                    tick1.ForeColor = Color.FromArgb(80, 200, 80);
                }
                else
                {
                    tick1.Text      = "X";
                    tick1.ForeColor = Color.FromArgb(200, 80, 80);
                }
                if (Convert.ToDouble(RC.Cost) > Convert.ToDouble(algo[1]))
                {
                    tick2.Text      = "\u2714";
                    tick2.ForeColor = Color.FromArgb(80, 200, 80);
                }
                else
                {
                    tick2.Text      = "X";
                    tick2.ForeColor = Color.FromArgb(200, 80, 80);
                }
                if (Convert.ToDouble(RC.FDE) < Convert.ToDouble(MyFDE))
                {
                    tick3.Text      = "\u2714";
                    tick3.ForeColor = Color.FromArgb(80, 200, 80);
                }
                else
                {
                    tick3.Text      = "X";
                    tick3.ForeColor = Color.FromArgb(200, 80, 80);
                }
                //Appearence -------------------------------------------------------------
                //SaveCompairViaRandom
                SaveCompairViaRandom(MyReusability, Randomreusability);
                saveResult(path);

                int    numberoftest = 0;
                string variable     = Var[0];
                for (int i = 0; i < Var[0].Length; i++)
                {
                    if (variable[i].ToString() == "1")
                    {
                        numberoftest++;
                    }
                }
                //int numberOfSelectedTest =  filter.RetestableTestCases.Count;
                double            newCover = 1 - Convert.ToDouble(algo[0]);
                VersionEvaluation Ve       = new VersionEvaluation(fmO.Pairs, compair.initialSamePairs, newPairs.PairsList.Count, numberoftest, Faults, compair.ChangedPairs, MyFDE, MyReusability, newCover);
                SaveVersionEval   SEV      = new SaveVersionEval(Ve.M5, Ve.M6, Ve.M7, Ve.M8, CurrentFileName);
                SEV.Run();

                Dolabel();
            }
        }
Пример #7
0
        static void Main(string[] args)
        {
            List <Individuo> solucion = new List <Individuo>();
            Seleccion        seleccion;
            Mutacion         mutacion;
            Reemplazo        reemplazo;
            Cruce            cruce;
            PaisajeAptitud   paisaje;
            Random           rand;

            Archivo.Archivo datosDistancia;
            Archivo.Archivo datosTiempo;
            int             opc = 0;

            datosDistancia = new Archivo.Archivo("DataSetDistancia.txt", 0);
            datosTiempo    = new Archivo.Archivo("DataSetTiempo.txt", 0);
            double[][] matrizDistacncia, matrizTiempo;
            matrizDistacncia = datosDistancia.getMatriz();
            matrizTiempo     = datosTiempo.getMatriz();
            do
            {
                try
                {
                    int dimensiones, numIteraciones, semilla;
                    dimensiones = datosDistancia.cantLineas;
                    //Parametros a afinar
                    semilla        = (new Random()).Next(1, 1001);
                    numIteraciones = 500;

                    if (semilla == -1)
                    {
                        rand = new Random();
                    }
                    else
                    {
                        rand = new Random(semilla);
                    }
                    NSGAII algoritmo;
                    algoritmo = new NSGAII(rand);
                    paisaje   = new fxAgenteViajero(opc, matrizDistacncia, matrizTiempo);
                    cruce     = new Combinado(rand, 2);
                    mutacion  = new Intercambio(rand);
                    seleccion = new SxTorneo(rand, 2);
                    reemplazo = new DelPeor();
                    algoritmo.inicializar(cruce, mutacion, seleccion, paisaje, reemplazo, numIteraciones, dimensiones, 0.50);
                    solucion = algoritmo.ejecutar();
                    Console.WriteLine("Semilla: " + semilla + " Tamaño poblacion: " + algoritmo.tamañoPoblacion + " Ciudades: " + algoritmo.dimensiones);

                    /*Console.WriteLine("Mejor individuo");
                     * solucion[0].mostrar();
                     * Console.WriteLine("Aptitud: " + solucion[0].getAptitud());*/
                    foreach (var ind in solucion)
                    {
                        Debug.WriteLine(ind.FitnessDistancia + "\t" + ind.FitnessTiempo + "\t" + ind.Rank);
                    }
                }
                catch (Exception e) { Console.WriteLine("Error: " + e.Message + "\n" + e.StackTrace); }
                Console.Write("Presiona 0 para salir...\nOtra tecla para volver a ejecutar...");
                try
                {
                    opc = Int32.Parse(Console.ReadKey(false).KeyChar.ToString());
                }
                catch (Exception e) { opc = -1; }
                //Console.Clear();
            } while (opc != 0);
            datosDistancia.close();
            datosTiempo.close();
        }
Пример #8
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Application.Run(new LoadConfig());

            // VariabilityModel model = new VariabilityModel("Model1");
            //  InfluenceModel infModel = new InfluenceModel(model, new NFProperty("Test"));

            //  BettyFileParser bfp = new BettyFileParser(model, infModel);

            String[] file = System.IO.File.ReadAllLines(@"C:\Users\Tom\Desktop\Masterarbeit\SPLConqueror\SPLConqueror\BettyConqueror\FeatureModel0.afm");

            //  bfp.readConfiguration(file);
            //ILArray<float> A = ILMath.tosingle()
            //ILArray<float> A = ILMath.tosingle(ILMath.rand(3, 100));


            // RDotNet.NativeLibrary.UnmanagedDll.SetDllDirectory(@"C:\Program Files\R\R-3.2.0\bin\i386\R.dll");


            engine = REngine.GetInstance();

            NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 });

            engine.SetSymbol("group1", group1);

            // e.Evaluate("hist(group1)");
            // e.Evaluate("hist(group1)");

            Problem  problem;
            Operator crossover; // Crossover operator
            Operator mutation;  // Mutation operator
            Operator selection; // Selection operator

            var logger = Logger.Log;

            // var appenders = logger.Logger.Repository.GetAppenders();
            // var fileAppender = appenders[0] as log4net.Appender.FileAppender;
            // fileAppender.File = "NSGAII.log";
            //.ActivateOptions();

            Dictionary <string, object> parameters; // Operator parameters

            QualityIndicator indicators;            // Object to get quality indicators

            problem = new GeneratorProblem("Real", 30);


            NSGAII algorithm = new NSGAII(problem);

            indicators = null;

            algorithm.SetInputParameter("populationSize", 200);
            algorithm.SetInputParameter("maxEvaluations", 25000);

            // Mutation and Crossover for Real codification
            parameters = new Dictionary <string, object>();
            parameters.Add("probability", 0.9);
            parameters.Add("distributionIndex", 20.0);
            crossover = CrossoverFactory.GetCrossoverOperator("SBXCrossover", parameters);

            parameters = new Dictionary <string, object>();
            parameters.Add("probability", 1.0 / problem.NumberOfVariables);
            parameters.Add("distributionIndex", 20.0);
            mutation = MutationFactory.GetMutationOperator("PolynomialMutation", parameters);

            // Selection Operator
            parameters = null;
            selection  = SelectionFactory.GetSelectionOperator("BinaryTournament2", parameters);

            // Add the operators to the algorithm
            algorithm.AddOperator("crossover", crossover);
            algorithm.AddOperator("mutation", mutation);
            algorithm.AddOperator("selection", selection);

            // Add the indicator object to the algorithm
            algorithm.SetInputParameter("indicators", indicators);

            // Execute the Algorithm
            long initTime = Environment.TickCount;
            //SolutionSet population = algorithm.Execute();
            long estimatedTime = Environment.TickCount - initTime;

            logger.Info("Variables values have been writen to file VAR");
//population.PrintVariablesToFile("VAR");
            logger.Info("Objectives values have been writen to file FUN");
            //   population.PrintObjectivesToFile("FUN");
            Console.WriteLine("Time: " + estimatedTime);
            Console.ReadLine();
            //Application.Run(new Form1(e, group1, new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99, 1.3, 1.7, 9.4, 11.1  }));
        }
Пример #9
0
    public void RunSimulation(object sender, EventArgs e)
    {
        var options = CreateAlgorithmOptions();

        var problem = new ConfigurationProblem();

        var algorithm = new NSGAII(problem);

        algorithm.SetInputParameter("populationSize", options.NumberOfCromozoms);
        algorithm.SetInputParameter("maxEvaluations", options.NumberOfCromozoms * options.NumberOfGenerations);

        // Mutation and Crossover for Real codification
        var parameters = new Dictionary <string, object>();

        parameters.Add(ConfigurationCrossOver.CrossOverPercentageKey, options.CrossOverPercentage);
        var crossover = new ConfigurationCrossOver(parameters);          // Nobody cares about the factory

        parameters = new Dictionary <string, object>();
        parameters.Add(ConfigurationMutation.MutationPercentageKey, options.MutationPercentage);
        var mutation = new ConfigurationMutation(parameters);          // Nobody cares about the factory.

        // Selection Operator
        parameters = null;
        var selection = new BinaryTournament2(parameters);          // Nobody cares about the factory.

        // Add the operators to the algorithm
        algorithm.AddOperator("crossover", crossover);
        algorithm.AddOperator("mutation", mutation);
        algorithm.AddOperator("selection", selection);

        // Add the indicator object to the algorithm
        // nope
        //algorithm.SetInputParameter("indicators", null);

        var solution = algorithm.Execute();

        var solutionsList = solution.SolutionsList;

        var output = "";

        using (var writer = new System.IO.StreamWriter("output.txt")) {
            foreach (var sol in solutionsList)
            {
                var line = sol.Objective [0] + "\t" + sol.Objective [1];
                output += line;
                output += "\n";
                writer.WriteLine(line);
            }

            output += "\n";
            output += "\n";
            writer.WriteLine();
            writer.WriteLine();

            var rank = new Ranking(solution);
            var n    = rank.GetNumberOfSubfronts();
            for (var i = 0; i < n; i++)
            {
                var f = rank.GetSubfront(i);
                foreach (var sol in f.SolutionsList)
                {
                    var line = sol.Objective [0] + "\t" + sol.Objective [1];
                    output += line;
                    output += "\n";
                    writer.WriteLine(line);
                }

                output += "\n";
                output += "\n";
                writer.WriteLine();
                writer.WriteLine();
            }
        }

        resultsText.Buffer.Clear();
        resultsText.Buffer.Text = output;
    }