Ejemplo n.º 1
0
        private void RunGA(){
            _teams = LoadTeams();
            _winners = _teams.FindAll(l => l.Winner == true);
            _losers = _teams.FindAll(l => l.Winner == false);

            const double crossoverProbability = 0.85;
            const double mutationProbability = 0.15;
            const int elitismPercentage = 5;

            var population = new Population(1000, 72, true, false, ParentSelectionMethod.TournamentSelection);

            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.DoublePoint
            };

            var mutation = new BinaryMutate(mutationProbability, true);

            var ga = new GeneticAlgorithm(population, EvaluateFitness);

            ga.OnGenerationComplete += ga_OnGenerationComplete;

            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            ga.Run(TerminateAlgorithm);

        }
Ejemplo n.º 2
0
        public void Run()
        {
            if (running)
            {
                return;
            }

            //create the elite operator
            var elite = new Elite(ElitismPercentage);

            //create the crossover operator
            var crossover = new CrossoverIndex(CrossOverPercentage, ChromosomeUtils.NUMBER_GENES, true, GAF.Operators.CrossoverType.DoublePoint, ReplacementMethod.GenerationalReplacement);

            //create the mutation operator
            var mutate = new BinaryMutate(MutationPercentage);
            //create the GA
            var ga = new GeneticAlgorithm(population, fitness.CalculateFitness);

            //add the operators
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutate);

            ga.OnRunComplete += OnRunComplete;

            //run the GA
            running = true;
            ga.Run(TerminateFunction);
        }
Ejemplo n.º 3
0
        public Genetics(Main form1, Func <string, int, string, bool> populateM)
        {
            pop        = populateM;
            form1.Text = "test";
            form       = form1;

            var population = new Population(populationSize, 576, false, false);

            //create the genetic operators
            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.SinglePoint
            };

            var mutation = new BinaryMutate(mutationProbability, true);

            //create the GA itself
            ga = new GeneticAlgorithm(population, EvaluateFitness);

            ga.OnGenerationComplete += ga_OnGenerationComplete;

            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);
        }
Ejemplo n.º 4
0
        private static void xMain(string[] args)
        {
            const double crossoverProbability = 0.85;
            const double mutationProbability  = 0.08;
            const int    elitismPercentage    = 5;

            //create a Population of 100 random chromosomes of length 44
            var population = new Population(100, 44, false, false);

            //create the genetic operators
            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.SinglePoint
            };

            var mutation = new BinaryMutate(mutationProbability, true);

            //create the GA itself
            var ga = new GeneticAlgorithm(population, EvaluateFitness);

            //subscribe to the GAs Generation Complete event
            ga.OnGenerationComplete += ga_OnGenerationComplete;

            //add the operators to the ga process pipeline
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            //run the GA
            ga.Run(TerminateAlgorithm);
        }
        // Using Genetic Algorithms
        public static void RunThrowAndStick(this House house)
        {
            boundaryXDim = house.Boundary.XDim;
            boundaryYDim = house.Boundary.YDim;

            var population = new Population(populationSize, bitsToAdjustRoom * house.RoomCount, false, false);

            //create the genetic operators
            var elite     = new Elite(5);
            var crossover = new Crossover(0.85, true, CrossoverType.SinglePoint);
            var mutation  = new BinaryMutate(0.2, true);

            //create the GA itself
            var ga = new GeneticAlgorithm(population, chromosome => EvaluateFitness(chromosome, house));

            //add the operators to the ga process pipeline
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            // Events subscription
            ga.OnGenerationComplete += (sender, e) => WriteLine($"Fitness is {e.Population.GetTop(1)[0].Fitness}");
            ga.OnRunComplete        += (sender, e) => ga_OnRunComplete(sender, e, house);

            // Run the GA
            WriteLine("Starting the GA");
            ga.Run(Terminate);
        }
Ejemplo n.º 6
0
        public void RunGA()
        {
            const double crossoverProbability = 0.8;
            const double mutationProbability  = 0.02;
            const int    elitismPercentage    = 5;

            //create the population
            var population = new Population();

            //create the chromosomes
            foreach (User currUser in GA.currBoard.boardMembers)
            {
                var chromosome = new Chromosome();
                chromosome.Genes.Add(new Gene(currUser));
                chromosome.Genes.ShuffleFast();
                population.Solutions.Add(chromosome);
            }

            //create the genetic operators
            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.SinglePoint
            };

            var mutation = new BinaryMutate(mutationProbability, true);

            //create the GA itself
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            //subscribe to the GAs Generation Complete event
            //ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete += ga_OnRunComplete;

            //add the operators to the ga process pipeline
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            //run the GA
            ga.Run(TerminateAlgorithm);
        }
Ejemplo n.º 7
0
        private static void Main(string[] args)
        {
            const double crossoverProbability = 0.85;
            const double mutationProbability  = 0.08;
            const int    elitismPercentage    = 5;

            //create a Population of 100 random chromosomes of length 44
            var population = new Population(100, 44, false, false);

            //create the genetic operators
            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.SinglePoint
            };

            var mutation = new BinaryMutate(mutationProbability);

            //create the GA itself passing in the fitness function.
            var ga = new GeneticAlgorithm(population, EvaluateFitness);

            /* ------------------------------------------------------------------------------------
             * if the fitness is defined in a separate assembly (see documentation),
             * the following class can be used to load the assembly and access the
             * fitness function
             *
             *    var fitnessAssembly = new FitnessAssembly ("Example.IFitness.dll");
             *    var ga = new GeneticAlgorithm (population, fitnessAssembly.FitnessFunction);
             * ------------------------------------------------------------------------------------*/

            //subscribe to the GAs Generation Complete event
            ga.OnGenerationComplete += ga_OnGenerationComplete;

            //add the operators to the ga process pipeline
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            //run the GA
            ga.Run(TerminateAlgorithm);
        }
Ejemplo n.º 8
0
        //En este metodo se configura los operadores y sus parametros para la corrida
        public void correrAlgoritmoGenetico(ProgressBar progressBar, int cantPoblacion, int cantIteraciones)
        {
            reloj.Start();
            this.progress        = progressBar;
            this.cantIteraciones = cantIteraciones;
            this.fitnessRequired = 630;

            var population = new Population(populationSize: cantPoblacion,
                                            chromosomeLength: 63,
                                            reEvaluateAll: true,
                                            useLinearlyNormalisedFitness: true,
                                            selectionMethod: ParentSelectionMethod.FitnessProportionateSelection);


            var crossover = new Crossover(0.4)
            {
                AllowDuplicates = true,
                CrossoverType   = CrossoverType.SinglePoint
            };

            var binaryMutate  = new BinaryMutate(mutationProbability: 0.05D, allowDuplicates: true);
            var randomReplace = new RandomReplace(numberToReplace: 9, allowDuplicates: true);
            var elite         = new Elite(1);
            var tempMutate    = new MutacionPorTemperatura(0.01D, 0.3D, cantIteraciones, true);
            var ga            = new GeneticAlgorithm(population, CalculateFitness)
            {
                UseMemory = false
            };

            ga.OnGenerationComplete += ga_OnGenerationComplete;
            ga.OnRunComplete        += ga_OnRunComplete;

            //aca se agregan los operadores para el algoritmo genetico

            ga.Operators.Add(crossover);
            //ga.Operators.Add(randomReplace);
            ga.Operators.Add(tempMutate);
            //ga.Operators.Add(binaryMutate);
            ga.Operators.Add(elite);
            ga.Run(Terminate);
        }
Ejemplo n.º 9
0
        static void ga()
        {
            vrange    = new double[6];
            vrange[1] = GAF.Math.GetRangeConstant(p.geo_amax - p.geo_amin, 10);
            vrange[2] = GAF.Math.GetRangeConstant(p.geo_tmax - p.geo_tmin, 10);
            vrange[3] = GAF.Math.GetRangeConstant(p.geo_bwmax - p.geo_bwmin, 10);
            vrange[4] = GAF.Math.GetRangeConstant(p.geo_lmax - p.geo_lmin, 10);
            vrange[5] = GAF.Math.GetRangeConstant(p.geo_nlmax - p.geo_nlmin, 10);

            var pop       = new Population(p.ga_pop, 50);
            var elite     = new Elite(Convert.ToInt32(p.ga_elit));
            var crossover = new Crossover(p.ga_cros);
            var mutacao   = new BinaryMutate(p.ga_mut);
            var ag        = new GeneticAlgorithm(pop, fapt2d);

            ag.Operators.Add(elite);
            ag.Operators.Add(crossover);
            ag.Operators.Add(mutacao);
            ag.OnGenerationComplete += geracao2d;
            Console.WriteLine("----------------------------------");
            Console.WriteLine("Starting...");
            Console.WriteLine("----------------------------------");
            ag.Run(fim2d);
        }
Ejemplo n.º 10
0
        public static void Main(string[] args)
        {
            _ads = SetupAppDomain();


            const double crossoverProbability = 0.65;
            const double mutationProbability  = 0.08;
            const int    elitismPercentage    = 5;

            //create the population
            //var population = new Population(100, 44, false, false);

            var population = new Population();

            //create the chromosomes
            for (var p = 0; p < 10; p++)
            {
                var chromosome = new Chromosome();
                for (int i = 0; i < 2; i++)
                {
                    ConfigVars v = new ConfigVars();
                    v.vars ["EMA_VAR1"] = RandomNumberBetweenInt(0, 20);
                    v.vars ["EMA_VAR2"] = RandomNumberBetweenInt(0, 100);
                    //v.vars ["LTD3"] = RandomNumberBetweenInt (0, 100);
                    //v.vars ["LTD4"] = RandomNumberBetweenInt (2, 200);

                    chromosome.Genes.Add(new Gene(v));
                }
                chromosome.Genes.ShuffleFast();
                population.Solutions.Add(chromosome);
            }



            //create the genetic operators
            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.SinglePoint
            };

            var mutation = new BinaryMutate(mutationProbability, true);

            //create the GA itself
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            //subscribe to the GAs Generation Complete event
            ga.OnGenerationComplete += ga_OnGenerationComplete;

            //add the operators to the ga process pipeline
//			ga.Operators.Add(elite);
//			ga.Operators.Add(crossover);
//			ga.Operators.Add(mutation);

            var cv_operator = new ConfigVarsOperator();

            ga.Operators.Add(cv_operator);

            //run the GA
            ga.Run(Terminate);
        }
Ejemplo n.º 11
0
        public void EvaluateProbe(List<IPosOnlyFeedback> test_probe_data, List<IPosOnlyFeedback> training_probe_data, List<IList<int>> test_users, List<IMapping> user_mapping,
            List<IMapping> item_mapping,
         int n = -1)
        {
            List<IList<int>> candidate_items = new List<IList<int>>();
            List<RepeatedEvents> repeated_events = new List<RepeatedEvents>();
            List<IBooleanMatrix> training_user_matrix = new List<IBooleanMatrix>();
            List<IBooleanMatrix> test_user_matrix = new List<IBooleanMatrix>();

            for (int i = 0; i < m_recommenders.Count; i++)
            {

                candidate_items.Add(new List<int>(test_probe_data[i].AllItems.Union(training_probe_data[i].AllItems)));
                repeated_events.Add(RepeatedEvents.No);

                if (candidate_items[i] == null)
                    throw new ArgumentNullException("candidate_items");
                if (test_probe_data[i] == null)
                    test_users[i] = test_probe_data[i].AllUsers;

                training_user_matrix.Add(training_probe_data[i].UserMatrix);
                test_user_matrix.Add(test_probe_data[i].UserMatrix);
            }
            int num_users = 0;
            var result = new ItemRecommendationEvaluationResults();

            // make sure that the user matrix is completely initialized before entering parallel code

            foreach (int user_id in test_users[0])
            {

                string original = user_mapping[0].ToOriginalID(user_id);

                List<IList<Tuple<int, float>>> list_of_predictions = new List<IList<Tuple<int, float>>>();

                HashSet<int> correct_items = new HashSet<int>();

                List<HashSet<int>> ignore_items_for_this_user = new List<HashSet<int>>();

                List<int> num_candidates_for_this_user = new List<int>();

                correct_items = new HashSet<int>(test_user_matrix[0][user_id]);
                correct_items.IntersectWith(candidate_items[0]);

                for (int i = 0; i < m_recommenders.Count; i++)
                {

                    int internalId = user_mapping[i].ToInternalID(original);

                    ignore_items_for_this_user.Add(new HashSet<int>(training_user_matrix[i][internalId]));

                    /* if (correct_items[i].Count == 0)
                         continue;
                     */

                    ignore_items_for_this_user[i].IntersectWith(candidate_items[i]);
                    num_candidates_for_this_user.Add(candidate_items[i].Count - ignore_items_for_this_user[i].Count);
                    /*if (correct_items[i].Count == num_candidates_for_this_user[i])
                        continue;
                    */

                    //Recomenda

                    var listaRecomendacao = m_recommenders[i].Recommend(user_id, candidate_items: candidate_items[i], n: n, ignore_items: ignore_items_for_this_user[i]);
                    for (int j = 0; j < listaRecomendacao.Count; j++)
                    {
                        string idOriginal = item_mapping[i].ToOriginalID(listaRecomendacao[j].Item1);
                        int idMappingZero = item_mapping[0].ToInternalID(idOriginal);

                        Tuple<int, float> tupla = new Tuple<int, float>(idMappingZero, listaRecomendacao[j].Item2);

                        listaRecomendacao[j] = tupla;
                    }

                    list_of_predictions.Add(listaRecomendacao);

                }

                //Usar o melhor
                double maiorMapping = 0;
                int idMaiorMapping = 0;

                //Testar cada individual
                for (int k = 0; k < list_of_predictions.Count; k++)
                {
                    int[] prediction_probe = (from t in list_of_predictions[k] select t.Item1).ToArray();

                    double resultado = PrecisionAndRecall.AP(prediction_probe, correct_items);

                    if (resultado > maiorMapping)
                    {
                        maiorMapping = resultado;
                        idMaiorMapping = k;

                    }

                }

                //Set global so Fitness itens can see.
                list_prediction_probes = list_of_predictions;
                correct_items_global = correct_items;

                //Algortimo Genetico
                /*   //  Crossover		= 80%
                   //  Mutation		=  5%
                   //  Population size = 100
                   //  Generations		= 2000
                   //  Genome size		= 2
                   GA ga = new GA(0.8, 0.05, 40, 400, list_prediction_probes.Count);

                   ga.FitnessFunction = new GAFunction(Fitness);

                   //ga.FitnessFile = @"H:\fitness.csv";
                   ga.Elitism = true;
                   ga.Go();

                   double[] values;
                   double fitness;
                   ga.GetBest(out values, out fitness);*/

                //create the GA using an initialised population and user defined Fitness Function
                const double crossoverProbability = 0.85;
                const double mutationProbability = 0.08;
                const int elitismPercentage = 5;

                //create a Population of random chromosomes of length 44
                var population = new Population(40, list_of_predictions.Count * 10, false, false);

                //create the genetic operators
                var elite = new Elite(elitismPercentage);
                var crossover = new Crossover(crossoverProbability, true)
                {
                    CrossoverType = CrossoverType.DoublePoint
                };
                var mutation = new BinaryMutate(mutationProbability, true);

                //create the GA itself
                var ga = new GeneticAlgorithm(population, CalculateFitness);

                //add the operators to the ga process pipeline
                ga.Operators.Add(elite);
                ga.Operators.Add(crossover);
                ga.Operators.Add(mutation);

                //run the GA
                ga.Run(Terminate);

                var best = population.GetTop(1)[0];
                double rangeConst = 1 / (System.Math.Pow(2, 10) - 1);
                ga_weights[original] = new List<double>();

                for (int i = 0; i < list_prediction_probes.Count; i++)
                {
                    string str = best.ToBinaryString((i * 10), 10);
                    Int64 convertInt32 = Convert.ToInt32(str, 2);

                    double x = (convertInt32 * rangeConst);

                    ga_weights[original].Add(x);
                }

                best_alg[original] = idMaiorMapping;
                num_users++;

                if (num_users % 10 == 0)
                    Console.Error.Write(".");
                if (num_users % 100 == 0)
                    Console.Error.WriteLine("");

            }
        }
Ejemplo n.º 12
0
        public void StartLocating()
        {
            System.Data.DataTable dtStationCells = new System.Data.DataTable();

            //Create XML Datat for first time
            dtStationCells.TableName = "dt";
            dtStationCells.Columns.Add("Index", typeof(int));
            dtStationCells.Columns.Add("Name", typeof(string));
            dtStationCells.Columns.Add("Weight", typeof(double));
            dtStationCells.Columns.Add("Latitude", typeof(double));
            dtStationCells.Columns.Add("Longitude", typeof(double));
            dtStationCells.Columns.Add("RequestCount", typeof(int));

            MovementProbilityMatrix = new Matrix(NumberOfCells, NumberOfCells);

            Random rndi = new Random();
            //CreateShiraz Map Cells
            //29.5280603    29.57823449     29.72383715     29.69640358
            //52.55447388   52.62863159     52.47344971     52.40478516
            double latStart = 29.5280603, latEnd = 29.7238371, longStart = 52.4047851, longEnd = 52.6286315, currentLat = 0, currentLong = 0, latDistance = 0, longDistance = 0;

            currentLat   = latStart;
            currentLong  = longStart;
            longDistance = (longEnd - longStart) / 2;
            latDistance  = (latEnd - latStart) / (NumberOfCells / 2);
            for (int i = 0; i < NumberOfCells; i++)
            {
                int weight = rndi.Next(0, 100);
                //dtStationCells.Rows.Add(i, i.ToString(), weight, rndi.Next(295280603, 297238371) / (double)100000000, rndi.Next(524047851, 526286315) / (double)100000000, weight);
                dtStationCells.Rows.Add(i, i.ToString(), weight, currentLat, currentLong, weight);

                currentLat += latDistance;
                if (currentLat > latEnd)
                {
                    currentLat = latStart;
                }
                currentLong += longDistance;
                if (currentLong > longEnd)
                {
                    currentLong = longStart;
                }
            }
            dtStationCells.WriteXmlSchema(StationLocating.strRootResaultPath + "stationsSchema.xml");
            dtStationCells.WriteXml(StationLocating.strRootResaultPath + "stations.xml");

            //ReadPoints from Excel
            //Microsoft.Office.Interop.Excel.Application xlApp1 = new Microsoft.Office.Interop.Excel.Application();
            //Microsoft.Office.Interop.Excel.Workbook xlWorkBook1 = xlApp1.Workbooks.Open(Application.StartupPath + "\\Neighborhood_Labels.xls");
            //Microsoft.Office.Interop.Excel.Worksheet xlSheet1 = xlWorkBook1.Sheets[1];
            //Microsoft.Office.Interop.Excel.Range xlRange = xlSheet1.UsedRange;
            //NumberOfCells = xlRange.Rows.Count;
            //for (int i = 2; i <= xlRange.Rows.Count; i++)
            //{
            //    if (xlRange.Cells[i, 1] != null && xlRange.Cells[i, 1].Value2 != null)
            //        dtStationCells.Rows.Add(xlRange.Cells[i, 3].Value2, rndi.Next(0, 100), Convert.ToDouble(xlRange.Cells[i, 2].Value2), Convert.ToDouble(xlRange.Cells[i, 1].Value2));
            //}
            //dtStationCells.WriteXmlSchema(@"c:\stationsSchema.xml");
            //dtStationCells.WriteXml(@"c:\stations.xml");

            //Create Movement Probility Matrix and Save it
            MovementProbilityMatrix.FillMatrixWithEqalTotal();
            //MovementProbilityMatrix.PrintMatrix();
            //MovementProbilityMatrix.SaveMarixToJson("c:\\MovementProbilityMatrix.json");

            // read Movement Probility Matrix from file
            //MovementProbilityMatrix.ReadMatrixFromJson("c:\\MovementProbilityMatrix.json");


            //Read stations data from XML file
            //dtStationCells = new System.Data.DataTable();
            //dtStationCells.ReadXmlSchema(@"c:\stationsSchema.xml");
            //dtStationCells.ReadXml(@"c:\stations.xml");


            StationCells = new List <BikeSharingStations.StationCell>();

            for (int i = 0; i < dtStationCells.Rows.Count; i++)
            {
                StationCells.Add(new StationCell(Convert.ToInt32(dtStationCells.Rows[i]["Index"]), dtStationCells.Rows[i]["Name"].ToString(), (double)dtStationCells.Rows[i]["Weight"], (double)dtStationCells.Rows[i]["Latitude"], (double)dtStationCells.Rows[i]["Longitude"], Convert.ToInt32(dtStationCells.Rows[i]["RequestCount"])));
            }



            foreach (StationCell item in StationCells)
            {
                SumOfStationWeights += item.Weight;
            }

            const double crossoverProbability = 0.65;
            const double mutationProbability  = 0.08;
            const int    elitismPercentage    = 5;


            Microsoft.Office.Interop.Excel.Application xlApp      = new Microsoft.Office.Interop.Excel.Application();;
            Microsoft.Office.Interop.Excel.Workbook    xlWorkBook = xlApp.Workbooks.Open(StationLocating.strRootResaultPath + "StationsData2.xls");;
            object misValue = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Excel.Worksheet xlSheetFinalData = xlWorkBook.Sheets[1];

            for (RoundCount = 1; RoundCount <= 20; RoundCount++)
            {
                //create the population
                var    population   = new Population();//NumberOfChoromosomes, NumberOfCells, false, false);
                Random rndGeneIndex = new Random();
                Random rnd          = new Random();
                //create the chromosomes;
                for (var p = 0; p < NumberOfChoromosomes; p++)
                {
                    var chromosome = new Chromosome();
                    int NumberOfBikesInThisChoromosome = 0;
                    for (var g = 0; g < NumberOfCells; g++)
                    {
                        chromosome.Genes.Add(new Gene(0));
                    }

                    //int geneIndex = 0;
                    while (NumberOfBikesInThisChoromosome < MaximumNumberOfBikesInSystem)
                    {
                        int temp = rnd.Next(MaximumNumberOfbikeInEachStation / 2, MaximumNumberOfbikeInEachStation);
                        if (NumberOfBikesInThisChoromosome + temp > MaximumNumberOfBikesInSystem)
                        {
                            temp = MaximumNumberOfBikesInSystem - NumberOfBikesInThisChoromosome;
                        }
                        NumberOfBikesInThisChoromosome += temp;
                        chromosome.Genes[rndGeneIndex.Next(0, NumberOfCells)] = new Gene(temp);
                        //chromosome.Genes.Add(new Gene(temp));
                        //geneIndex++;
                    }
                    //chromosome.Genes.ShuffleFast();

                    int sumBikes = 0;
                    for (int i = 0; i < chromosome.Count; i++)
                    {
                        sumBikes += Convert.ToInt32(chromosome.Genes[i].RealValue);
                    }
                    if (sumBikes > MaximumNumberOfBikesInSystem)
                    {
                        sumBikes = 0;
                    }
                    population.Solutions.Add(chromosome);
                }


                //create the chromosomes;
                //for (var p = 0; p < NumberOfChoromosomes; p++)
                //{
                //    var chromosome = new Chromosome();
                //    for (var g = 0; g < NumberOfCells; g++)
                //    {
                //        chromosome.Genes.Add(new Gene(rnd.Next(0, MaximumNumberOfbikeInEachStation)));
                //    }
                //    chromosome.Genes.ShuffleFast();
                //    population.Solutions.Add(chromosome);
                //}

                //create the genetic operators
                var elite = new Elite(elitismPercentage);


                //create the crossover operator
                var crossover = new Crossover(crossoverProbability, true)
                {
                    CrossoverType = CrossoverType.SinglePoint
                };
                //crossover.ReplacementMethod = ReplacementMethod.DeleteLast;

                var mutation = new BinaryMutate(mutationProbability, true);

                //create the GA itself
                var ga = new GeneticAlgorithm(population, EvaluateFitness);

                //subscribe to the GAs Generation Complete event
                ga.OnGenerationComplete += ga_OnGenerationComplete;
                //add the operators to the ga process pipeline
                ga.Operators.Add(elite);
                ga.Operators.Add(crossover);
                ga.Operators.Add(mutation);

                //run the GA
                ga.Run(TerminateAlgorithm);

                Console.WriteLine("intFitnessCount : " + intFitnessCount.ToString());
                Console.WriteLine("intWrongFitnessCount : " + intWrongFitnessCount.ToString());
                //Export Resault to excel
                Microsoft.Office.Interop.Excel.Worksheet xlStationsDataSheet;
                xlWorkBook.Worksheets.Add();
                xlStationsDataSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

                int excelColumnIndex = 1;
                xlStationsDataSheet.Name = string.Format("Round{0:00}", RoundCount);
                xlStationsDataSheet.Cells[1, excelColumnIndex] = "CellIndex";                       // Index
                xlStationsDataSheet.Cells[2, excelColumnIndex] = "StationName";                     // Name
                xlStationsDataSheet.Cells[3, excelColumnIndex] = "Latitude";                        // Latitude
                xlStationsDataSheet.Cells[4, excelColumnIndex] = "Longitude";                       // Longitude
                xlStationsDataSheet.Cells[5, excelColumnIndex] = "Weight";                          // Weight
                xlStationsDataSheet.Cells[6, excelColumnIndex] = "NumberOfBikes";                   // NumberOfBikes
                xlStationsDataSheet.Cells[7, excelColumnIndex] = "Station capacity";                // Station capacity
                xlStationsDataSheet.Cells[8, excelColumnIndex] = "Total Distance";                  // Avrage Of Accessibility
                xlStationsDataSheet.Cells[9, excelColumnIndex] = "Number of Bikes for Rebalancing"; // Number of Bikes for Rebalancing


                excelColumnIndex += 1;

                var Topchromosome = population.Solutions[0];
                ComputeAccessibility(Topchromosome);
                ComputeRebalancingCost(Topchromosome);
                SaveProbilityMartix(string.Format(StationLocating.strRootResaultPath + "ProbibilityMatrix-Round{0:00}.json", RoundCount), Topchromosome);
                double totalbikeinthissystem = 0;
                for (int i = 0; i < Topchromosome.Count; i++)
                {
                    if (Topchromosome.Genes[i].RealValue != 0)
                    {
                        xlStationsDataSheet.Cells[1, excelColumnIndex] = StationCells[i].Index;            // Index
                        xlStationsDataSheet.Cells[2, excelColumnIndex] = StationCells[i].Name;             // Name
                        xlStationsDataSheet.Cells[3, excelColumnIndex] = StationCells[i].Latitude;         // Latitude
                        xlStationsDataSheet.Cells[4, excelColumnIndex] = StationCells[i].Longitude;        // Longitude
                        xlStationsDataSheet.Cells[5, excelColumnIndex] = StationCells[i].Weight;           // Weight
                        xlStationsDataSheet.Cells[6, excelColumnIndex] = StationCells[i].NumberOfBikes;    // NumberOfBikes
                        xlStationsDataSheet.Cells[7, excelColumnIndex] = Topchromosome.Genes[i].RealValue; // Station capacity
                        xlStationsDataSheet.Cells[8, excelColumnIndex] = TotalDistance;                    // Avrage Of Accessibility
                        xlStationsDataSheet.Cells[9, excelColumnIndex] = NumberOfBikesToBeRebalance;       // Number of Bikes for Rebalancing
                        totalbikeinthissystem += Topchromosome.Genes[i].RealValue;
                        excelColumnIndex++;
                    }
                }

                xlSheetFinalData.Cells[1, 1] = "Round Count";
                xlSheetFinalData.Cells[1, 2] = "TotalDistance";
                xlSheetFinalData.Cells[1, 3] = "NumberOfBikesToBeRebalance";
                xlSheetFinalData.Cells[1, 4] = "Number of Bikes in system";
                xlSheetFinalData.Cells[1, 5] = "Number of stations";
                xlSheetFinalData.Cells[1, 6] = "Rebalancing is Computed";
                xlSheetFinalData.Cells[1, 7] = "fitnessValue";
                xlSheetFinalData.Cells[1, 8] = "AccessibilityFitness";
                xlSheetFinalData.Cells[1, 9] = "RebalancingFitness";

                xlSheetFinalData.Cells[RoundCount + 1, 1] = RoundCount;
                xlSheetFinalData.Cells[RoundCount + 1, 2] = TotalDistance;
                xlSheetFinalData.Cells[RoundCount + 1, 3] = NumberOfBikesToBeRebalance;                    // Number of Bikes for Rebalancing
                xlSheetFinalData.Cells[RoundCount + 1, 4] = totalbikeinthissystem;                         // Number of Bikes in system
                xlSheetFinalData.Cells[RoundCount + 1, 5] = excelColumnIndex - 2;                          // Number of stations
                xlSheetFinalData.Cells[RoundCount + 1, 6] = (RoundCount % 2 == 0) ? "True" : "False";
                xlSheetFinalData.Cells[RoundCount + 1, 7] = fitnessValue;                                  // Number of Bikes for Rebalancing
                xlSheetFinalData.Cells[RoundCount + 1, 8] = AccessibilityFitness;                          // Number of Bikes for Rebalancing
                xlSheetFinalData.Cells[RoundCount + 1, 9] = (RoundCount % 2 == 0)? RebalancingFitness : 0; // Number of Bikes for Rebalancing

                releaseObject(xlStationsDataSheet);

                xlWorkBook.Save();

                //xlWorkBook.SaveAs(string.Format("c:\\StationsData.xls"), Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            }

            xlWorkBook.SaveAs(string.Format(StationLocating.strRootResaultPath + "StationsData.xls"), Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

            releaseObject(xlSheetFinalData);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            MessageBox.Show("Excel file created , you can find the file " + StationLocating.strRootResaultPath);
        }
        public void EvaluateProbe(List <IPosOnlyFeedback> test_probe_data, List <IPosOnlyFeedback> training_probe_data, List <IList <int> > test_users, List <IMapping> user_mapping,
                                  List <IMapping> item_mapping,
                                  int n = -1)
        {
            List <IList <int> >   candidate_items      = new List <IList <int> >();
            List <RepeatedEvents> repeated_events      = new List <RepeatedEvents>();
            List <IBooleanMatrix> training_user_matrix = new List <IBooleanMatrix>();
            List <IBooleanMatrix> test_user_matrix     = new List <IBooleanMatrix>();



            for (int i = 0; i < m_recommenders.Count; i++)
            {
                candidate_items.Add(new List <int>(test_probe_data[i].AllItems.Union(training_probe_data[i].AllItems)));
                repeated_events.Add(RepeatedEvents.No);


                if (candidate_items[i] == null)
                {
                    throw new ArgumentNullException("candidate_items");
                }
                if (test_probe_data[i] == null)
                {
                    test_users[i] = test_probe_data[i].AllUsers;
                }

                training_user_matrix.Add(training_probe_data[i].UserMatrix);
                test_user_matrix.Add(test_probe_data[i].UserMatrix);
            }
            int num_users = 0;
            var result    = new ItemRecommendationEvaluationResults();

            // make sure that the user matrix is completely initialized before entering parallel code



            foreach (int user_id in test_users[0])
            {
                string original = user_mapping[0].ToOriginalID(user_id);


                List <IList <Tuple <int, float> > > list_of_predictions = new List <IList <Tuple <int, float> > >();

                HashSet <int> correct_items = new HashSet <int>();

                List <HashSet <int> > ignore_items_for_this_user = new List <HashSet <int> >();

                List <int> num_candidates_for_this_user = new List <int>();


                correct_items = new HashSet <int>(test_user_matrix[0][user_id]);
                correct_items.IntersectWith(candidate_items[0]);


                for (int i = 0; i < m_recommenders.Count; i++)
                {
                    int internalId = user_mapping[i].ToInternalID(original);


                    ignore_items_for_this_user.Add(new HashSet <int>(training_user_matrix[i][internalId]));



                    /* if (correct_items[i].Count == 0)
                     *   continue;
                     */

                    ignore_items_for_this_user[i].IntersectWith(candidate_items[i]);
                    num_candidates_for_this_user.Add(candidate_items[i].Count - ignore_items_for_this_user[i].Count);

                    /*if (correct_items[i].Count == num_candidates_for_this_user[i])
                     *  continue;
                     */


                    //Recomenda


                    var listaRecomendacao = m_recommenders[i].Recommend(user_id, candidate_items: candidate_items[i], n: n, ignore_items: ignore_items_for_this_user[i]);
                    for (int j = 0; j < listaRecomendacao.Count; j++)
                    {
                        string idOriginal    = item_mapping[i].ToOriginalID(listaRecomendacao[j].Item1);
                        int    idMappingZero = item_mapping[0].ToInternalID(idOriginal);


                        Tuple <int, float> tupla = new Tuple <int, float>(idMappingZero, listaRecomendacao[j].Item2);

                        listaRecomendacao[j] = tupla;
                    }

                    list_of_predictions.Add(listaRecomendacao);
                }



                //Usar o melhor
                double maiorMapping   = 0;
                int    idMaiorMapping = 0;

                //Testar cada individual
                for (int k = 0; k < list_of_predictions.Count; k++)
                {
                    int[] prediction_probe = (from t in list_of_predictions[k] select t.Item1).ToArray();


                    double resultado = PrecisionAndRecall.AP(prediction_probe, correct_items);

                    if (resultado > maiorMapping)
                    {
                        maiorMapping   = resultado;
                        idMaiorMapping = k;
                    }
                }

                //Set global so Fitness itens can see.
                list_prediction_probes = list_of_predictions;
                correct_items_global   = correct_items;

                //Algortimo Genetico

                /*   //  Crossover		= 80%
                 * //  Mutation		=  5%
                 * //  Population size = 100
                 * //  Generations		= 2000
                 * //  Genome size		= 2
                 * GA ga = new GA(0.8, 0.05, 40, 400, list_prediction_probes.Count);
                 *
                 * ga.FitnessFunction = new GAFunction(Fitness);
                 *
                 * //ga.FitnessFile = @"H:\fitness.csv";
                 * ga.Elitism = true;
                 * ga.Go();
                 *
                 * double[] values;
                 * double fitness;
                 * ga.GetBest(out values, out fitness);*/

                //create the GA using an initialised population and user defined Fitness Function
                const double crossoverProbability = 0.85;
                const double mutationProbability  = 0.08;
                const int    elitismPercentage    = 5;

                //create a Population of random chromosomes of length 44
                var population = new Population(40, list_of_predictions.Count * 10, false, false);

                //create the genetic operators
                var elite     = new Elite(elitismPercentage);
                var crossover = new Crossover(crossoverProbability, true)
                {
                    CrossoverType = CrossoverType.DoublePoint
                };
                var mutation = new BinaryMutate(mutationProbability, true);

                //create the GA itself
                var ga = new GeneticAlgorithm(population, CalculateFitness);

                //add the operators to the ga process pipeline
                ga.Operators.Add(elite);
                ga.Operators.Add(crossover);
                ga.Operators.Add(mutation);

                //run the GA
                ga.Run(Terminate);


                var    best       = population.GetTop(1)[0];
                double rangeConst = 1 / (System.Math.Pow(2, 10) - 1);
                ga_weights[original] = new List <double>();

                for (int i = 0; i < list_prediction_probes.Count; i++)
                {
                    string str          = best.ToBinaryString((i * 10), 10);
                    Int64  convertInt32 = Convert.ToInt32(str, 2);

                    double x = (convertInt32 * rangeConst);

                    ga_weights[original].Add(x);
                }


                best_alg[original] = idMaiorMapping;
                num_users++;


                if (num_users % 10 == 0)
                {
                    Console.Error.Write(".");
                }
                if (num_users % 100 == 0)
                {
                    Console.Error.WriteLine("");
                }
            }
        }
Ejemplo n.º 14
0
        private static void Main(string[] args)
        {
            Console.Title = "TMNF Ga AI";
            Console.WriteLine("__________________TMNF AI GA__________________");
            Console.Write($"MaxTime for each chromosome (enter for default: {maxTime}): ");
            string maxTimeInput = Console.ReadLine();

            if (!(maxTimeInput.ToString() == ""))
            {
                maxTime = Convert.ToInt32(maxTimeInput);
                Console.WriteLine("Maxtime set to " + maxTime);
            }

            Console.Write($"Cheat engine speed cheat (enter for no speed hack): ");
            string cheatEngineSpeedInput = Console.ReadLine();

            if (!(cheatEngineSpeedInput.ToString() == ""))
            {
                cheatEngineSpeed = Convert.ToInt32(cheatEngineSpeedInput);
            }

            Console.Write($"Population number |must be even| (enter for default {populationCount}): ");
            string populationInput = Console.ReadLine();

            if (!(populationInput.ToString() == ""))
            {
                populationCount = Convert.ToInt32(populationInput);
                int mod = populationCount % 2;
                populationCount += mod;
                Console.WriteLine("Population set to: " + populationCount);
            }

            Console.Write($"Interval - ms between actions (enter for default {intervalTime}): ");
            string intervalTimeInput = Console.ReadLine();

            if (!(intervalTimeInput.ToString() == ""))
            {
                intervalTime = Convert.ToInt32(intervalTimeInput);
            }

            Console.WriteLine("Focus trackmania window now");
            //Sleep 4000 ms for at få tid til at klikke ind på Trackmania.
            Thread.Sleep(4000);
            Console.WriteLine("Starting program");

            //Angiv probabilities af crossover/mutation og procentdelen af population der kan være elite(eligible for crossover)
            const double crossoverProbability = 1;
            const double mutationProbability  = 0.08;
            const int    elitismPercentage    = 10;

            Console.WriteLine($"{maxTime}, {intervalTime}");
            int chroLengths = ((maxTime * 1000) * 4) / intervalTime;

            Console.WriteLine("Calculated chromosome length: " + chroLengths);
            int test = chroLengths % 4;

            chroLengths += test;
            Console.WriteLine("Adapted Length: " + chroLengths);

            //create a Population with ? random chromosomes of length ?
            //First generation/population will have double the amount automatically for better results
            var population = new Population(populationCount, chroLengths, false, false);

            //create the genetic operators
            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.SinglePoint
            };

            var mutation = new BinaryMutate(mutationProbability, true);

            //create the GA itself
            var ga = new GeneticAlgorithm(population, EvaluateFitness);

            //subscribe to the GAs Generation Complete event
            ga.OnGenerationComplete += ga_OnGenerationComplete;

            //add the operators to the ga process pipeline
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            //run the GA
            ga.Run(TerminateAlgorithm);
        }
Ejemplo n.º 15
0
        public List <Star> Solve()
        {
            const double crossoverProbability = 0.75;
            const double mutationProbability  = 0.5;
            const int    elitismPercentage    = 5;

            var population = new Population();

            //create the chromosomes
            for (var p = 0; p < 100; p++)
            {
                var chromosome = new Chromosome();
                for (var g = 0; g < GlobalVariables.Comparables - _elitestars.Count; g++)
                {
                    chromosome.Genes.Add(new Gene(_rnd.NextDouble()));
                }
                population.Solutions.Add(chromosome);
            }

            //create the genetic operators
            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.SinglePoint
            };

            var mutation = new BinaryMutate(mutationProbability, true);

            //create the GA itself
            var ga = new GeneticAlgorithm(population, EvaluateQuality);

            //subscribe to the GAs Generation Complete event
            ga.OnGenerationComplete += ga_OnGenerationComplete;

            //add the operators to the ga process pipeline
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            //run the GA
            ga.Run(TerminateAlgorithm);

            List <Star> picks = new List <Star>();

            picks.AddRange(_elitestars);

            foreach (Gene gene in population.GetTop(1)[0].Genes)
            {
                picks.Add(_eligiblestars[(int)(System.Math.Abs(gene.RealValue) * _eligiblestars.Count)]);
            }

            FastReduction();

            var mag = _teststars
                      .Select(x => (x.VMag - x.CatalogEntry.Vmag));

            Console.WriteLine();
            Console.WriteLine("Best fit mean     : " + mag.Average());
            Console.WriteLine("Best fit deviation: " + mag.StdDev());

            picks = picks.Distinct(new StarComparer()).ToList();
            return(picks);
        }
Ejemplo n.º 16
0
        public static void Main(string[] args)
        {
            //Initialize:
            string mode = "RELEASE";
            var liveMode = Config.GetBool("live-mode");

            #if DEBUG
            mode = "DEBUG";
            #endif

            //			Console.WriteLine("Running " + algorithm + "...");
            Config.Set("live-mode", "false");
            Config.Set("messaging-handler", "QuantConnect.Messaging.Messaging");
            Config.Set("job-queue-handler", "QuantConnect.Queues.JobQueue");
            Config.Set("api-handler", "QuantConnect.Api.Api");
            //Config.Set("result-handler", "QuantConnect.Lean.Engine.Results.OptimizationResultHandler");
            Config.Set("result-handler", "QuantConnect.Lean.Engine.Results.ConsoleResultHandler");
            Config.Set("EMA_VAR1", "10");

            _ads = SetupAppDomain();

            //rc = new RunClass();
            const double crossoverProbability = 0.65;
            const double mutationProbability = 0.08;
            const int elitismPercentage = 5;

            //create the population
            //var population = new Population(100, 44, false, false);

            var population = new Population();

            //create the chromosomes
            for (var p = 0; p < 100; p++)
            {
                var chromosome = new Chromosome();
                for (int i = 0; i < 100; i++)
                    chromosome.Genes.Add(new Gene(i));
                chromosome.Genes.ShuffleFast();
                population.Solutions.Add(chromosome);
            }

            //create the genetic operators
            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.SinglePoint
            };

            var mutation = new BinaryMutate(mutationProbability, true);

            //create the GA itself
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            //subscribe to the GAs Generation Complete event
            ga.OnGenerationComplete += ga_OnGenerationComplete;

            //add the operators to the ga process pipeline
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            //run the GA
            ga.Run(Terminate);
        }
Ejemplo n.º 17
0
        public static void Main(string[] args)
        {
            _ads = SetupAppDomain ();

            const double crossoverProbability = 0.65;
            const double mutationProbability = 0.08;
            const int elitismPercentage = 5;

            //create the population
            //var population = new Population(100, 44, false, false);

            var population = new Population();

            //create the chromosomes
            for (var p = 0; p < 10; p++)
            {

                var chromosome = new Chromosome();
                for (int i = 0; i < 2; i++) {
                    ConfigVars v = new ConfigVars ();
                    v.vars ["EMA_VAR1"] = RandomNumberBetweenInt (0, 20);
                    v.vars ["EMA_VAR2"] = RandomNumberBetweenInt (0, 100);
                    //v.vars ["LTD3"] = RandomNumberBetweenInt (0, 100);
                    //v.vars ["LTD4"] = RandomNumberBetweenInt (2, 200);

                    chromosome.Genes.Add (new Gene (v));
                }
                chromosome.Genes.ShuffleFast();
                population.Solutions.Add(chromosome);
            }

            //create the genetic operators
            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.SinglePoint
            };

            var mutation = new BinaryMutate(mutationProbability, true);

            //create the GA itself
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            //subscribe to the GAs Generation Complete event
            ga.OnGenerationComplete += ga_OnGenerationComplete;

            //add the operators to the ga process pipeline
            //			ga.Operators.Add(elite);
            //			ga.Operators.Add(crossover);
            //			ga.Operators.Add(mutation);

            var cv_operator = new ConfigVarsOperator ();
            ga.Operators.Add (cv_operator);

            //run the GA
            ga.Run(Terminate);
        }
Ejemplo n.º 18
0
        internal void Run(AreaManager areaManager, Population conv, Population inno, Population obj)
        {
            if (running)
            {
                return;
            }

            cells = originalMap.SpawnCells;


            Chromosome chrom = ChromosomeUtils.ChromosomeFromMap(originalMap);

            string binaryString = chrom.ToBinaryString();

            convergenceFitness = new ConvergenceFitness(cells, binaryString);
            guidelineFitness   = new Guideline(cells, areaManager, MaxMonsters, MaxItens, HordesPercentage)
            {
                MaxItemsLever      = LeverMaxItem,
                MaxMonstersLever   = LeverMaxMonster,
                AmountHordesLever  = LeverAmountHordes,
                DangerLever        = LeverDanger,
                AccessibilityLever = LeverAccessibility
            };

            double total = GuidelinePercentage + UserPercentage + InnovationPercentage;

            guidelineLevel   = GuidelinePercentage / total;
            ConvergenceLevel = UserPercentage / total;
            innovationLevel  = InnovationPercentage / total;

            //we can create an empty population as we will be creating the
            //initial solutions manually.
            var population = new Population(InitialPopulation, cells.Count * ChromosomeUtils.NUMBER_GENES, true, true, ParentSelectionMethod.StochasticUniversalSampling);

            population.Solutions.Clear();

            population.Solutions.AddRange(obj.GetTop(10));
            population.Solutions.AddRange(inno.GetTop(10));
            population.Solutions.AddRange(conv.GetTop(10));

            //create the elite operator
            var elite = new Elite(ElitismPercentage);

            //create the crossover operator
            var crossover = new CrossoverIndex(CrossOverPercentage, ChromosomeUtils.NUMBER_GENES, true, GAF.Operators.CrossoverType.DoublePoint, ReplacementMethod.GenerationalReplacement);

            //create the mutation operator
            var mutate = new BinaryMutate(MutationPercentage);
            //create the GA
            var ga = new GeneticAlgorithm(population, CalculateFitness);

            //add the operators
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            //ga.Operators.Add(mutate);

            ga.OnRunComplete += OnRunComplete;

            //run the GA
            running = true;
            ga.Run(TerminateFunction);
        }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            knapsackItems = new List <Bag.Item>();
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Map", Weight = 9, Value = 150
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Water", Weight = 153, Value = 200
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Compass", Weight = 13, Value = 35
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Sandwitch", Weight = 50, Value = 160
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Glucose", Weight = 15, Value = 60
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Tin", Weight = 68, Value = 45
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Banana", Weight = 27, Value = 60
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Apple", Weight = 39, Value = 40
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Cheese", Weight = 23, Value = 30
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Beer", Weight = 52, Value = 10
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Suntan Cream", Weight = 11, Value = 70
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Camera", Weight = 32, Value = 30
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "T-shirt", Weight = 24, Value = 15
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Trousers", Weight = 48, Value = 10
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Umbrella", Weight = 73, Value = 40
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "WaterProof Trousers", Weight = 42, Value = 70
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Note-Case", Weight = 22, Value = 80
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Sunglasses", Weight = 7, Value = 20
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Towel", Weight = 18, Value = 12
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Socks", Weight = 4, Value = 50
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "Book", Weight = 30, Value = 10
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "waterproof overclothes ", Weight = 43, Value = 75
            });

            const double crossoverProbability = 0.65;
            const double mutationProbability  = 0.08;
            const int    elitismPercentage    = 5;

            //create the population
            var population = new Population(100, 22, false, false);

            //create the genetic operators
            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.SinglePoint
            };

            var mutation = new BinaryMutate(mutationProbability, true);

            //create the GA itself
            var ga = new GeneticAlgorithm(population, EvaluateFitness);

            //subscribe to the GAs Generation Complete event
            ga.OnGenerationComplete += ga_OnGenerationComplete;

            //add the operators to the ga process pipeline
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            //run the GA
            ga.Run(TerminateAlgorithm);


            //get the best solution and print Items
            var Bestchromosome = ga.Population.GetTop(1)[0];

            //decode chromosome
            Console.WriteLine("Maximum value of knapsack contains these Items : ");
            Bag BestBag = new Bag();

            for (int i = 0; i < Bestchromosome.Count; i++)
            {
                if (Bestchromosome.Genes[i].BinaryValue == 1)
                {
                    Console.WriteLine(knapsackItems[i].ToString());
                    BestBag.AddItem(knapsackItems[i]);
                }
            }
            Console.WriteLine(" Best knapsack information:\n Total Weight : {0}   Total Value : {1} Fitness : {2}", BestBag.TotalWeight, BestBag.TotalValue, Bestchromosome.Fitness);

            Console.ReadKey();
        }
Ejemplo n.º 20
0
        static void Main(string[] args)
        {
            knapsackItems = new List <Bag.Item>();
            knapsackItems.Add(new Bag.Item()
            {
                Name = "a", Weight = 9, Value = 150
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "b", Weight = 153, Value = 200
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "c", Weight = 13, Value = 35
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "d", Weight = 50, Value = 160
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "e", Weight = 15, Value = 60
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "f", Weight = 68, Value = 45
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "g", Weight = 27, Value = 60
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "h", Weight = 39, Value = 40
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "i", Weight = 23, Value = 30
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "j", Weight = 52, Value = 10
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "k", Weight = 11, Value = 70
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "l", Weight = 32, Value = 30
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "m", Weight = 24, Value = 15
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "n", Weight = 48, Value = 10
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "o", Weight = 73, Value = 40
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "p", Weight = 42, Value = 70
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "q", Weight = 22, Value = 80
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "r", Weight = 7, Value = 20
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "s", Weight = 18, Value = 12
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "t", Weight = 4, Value = 50
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "u", Weight = 30, Value = 10
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "v", Weight = 43, Value = 75
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "v", Weight = 43, Value = 75
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "v", Weight = 43, Value = 75
            });
            knapsackItems.Add(new Bag.Item()
            {
                Name = "v", Weight = 43, Value = 75
            });

            const double crossoverProbability = 0.65;
            const double mutationProbability  = 0.08;
            const int    elitismPercentage    = 5;

            // tao quan the
            var population = new Population(100, 22, false, false);

            // tao toan tu di truyen
            var elite = new Elite(elitismPercentage);

            var crossover = new Crossover(crossoverProbability, true)
            {
                CrossoverType = CrossoverType.SinglePoint
            };
            var mutation = new BinaryMutate(mutationProbability, true);

            // tao GA
            var ga = new GeneticAlgorithm(population, EvaluateFitness);

            ga.OnGenerationComplete += ga_OnGenerationComplete;

            // them tung toan tu vao GA
            ga.Operators.Add(elite);
            ga.Operators.Add(crossover);
            ga.Operators.Add(mutation);

            // chay GA
            ga.Run(TerminateAlgorithm);

            // lay do vat tot nhat
            var Bestchromosome = ga.Population.GetTop(1)[0];

            // decode chromosome
            Console.WriteLine("Maximum value of knapsack contains these Items : ");
            Bag BestBag = new Bag();

            for (int i = 0; i < Bestchromosome.Count; i++)
            {
                if (Bestchromosome.Genes[i].BinaryValue == 1)
                {
                    Console.WriteLine(knapsackItems[i].ToString());
                    BestBag.AddItem(knapsackItems[i]);
                }
            }
            Console.WriteLine(" Best knapsack information:\n Total Weight : {0}   Total Value : {1} Fitness : {2}", BestBag.TotalWeight, BestBag.TotalValue, Bestchromosome.Fitness);
            Console.ReadKey();
        }