示例#1
0
文件: Program.cs 项目: tgy/CSharp
        public static void Main(string[] args)
        {
            Events.Quit += new EventHandler<QuitEventArgs>(ApplicationQuitEventHandler);

            Surface plate = Video.SetVideoMode(220, 220, 32, false, false, false, true);
            Surface pic = new Surface("nyanbig.png");
            pic.Update();

            Population fellows = new Population(15, 100);
            List<float> fitnesses;

            while (fellows.members[0].fitness < 700f)
            {
                fitnesses = new List<float>();
                foreach (Genome g in fellows.members)
                {
                    g.Draw(plate);
                    Console.Read();
                    float f = g.GetFitness(plate, pic);
                    fitnesses.Add(f);
                    g.fitness = f;
                }

                fellows.members.Sort();
                fellows.members[0].Draw(plate);
                Console.WriteLine(fellows.members[0].fitness);
                int x = 0;
            }
        }
示例#2
0
        static void Main(string[] args)
        {
            Population p = new Population();
            p.WriteNextGeneration();

            int count = 0;
            byte res = 0;
            EquationGenome resGenome;
            while (p.Converged() == false)
            {
                p.NextGeneration();
                if (count % 50 == 0) {
                    p.WriteNextGeneration();

                    resGenome = (EquationGenome) p.GetNextGenerationBest();
                    res = resGenome.PerformCalculation(0, 1, 1, 1);
                    Console.WriteLine("<Loop> Result => {0}", res.ToString());

                }
                count++;

                if (count > 40000) {
                    Console.WriteLine("---------------");
                    p.WriteNextGenerationBest();
                    Console.WriteLine("---------------");
                    break;
                } // End of if
            } // End of the while

            Console.WriteLine("Done");

            resGenome = (EquationGenome) p.GetNextGenerationBest();
            res = resGenome.PerformCalculation(0, 1, 1, 1);
            Console.WriteLine("Result => {0}", res.ToString());
        }
示例#3
0
        static void Main(string[] args)
        {
            //This code runs a standard search for a randomly assigned alphanumeric string with 80% accuracy
            //(i.e. 2 non matching "genes" allowed in solution organism)

            DateTime start = DateTime.Now;
            Population pop1 = new Population(100);
            DateTime now = DateTime.Now;
            Console.WriteLine("Time taken was: " + (now-start).TotalSeconds + " seconds");
            Console.Out.WriteLine("Press Enter to Continue...");
            Console.In.ReadLine();

            //this code tests the genetic algorithm, organisms, and chromosomes
            //GeneticAlgorithmTester tester = new GeneticAlgorithmTester();
        }
 public void AddPopulationThread(string name)
 {
     TestPopulation = new Population(name);
     Populations.Add(TestPopulation);
     ThreadPool.QueueUserWorkItem(new WaitCallback(this.RunPopulation), (object)TestPopulation);
 }
示例#5
0
        static void Main(string[] args)
        {
            TestData.GetData(out var servers, out var services);

            var chromosome = new MyChromosome(servers, services);

            var populationSize = 9;
            var population     = new Population(populationSize, populationSize, chromosome);

            var fitness = new FuncFitness((c) =>
            {
                var mc = (MyChromosome)c;

                var genes   = mc.GetGenes();
                var servers = genes.Select(x => (Server)x.Value).ToList();

                var freeServersTerm     = servers.Count(x => x.IsFree) * 2.5;
                var negativeHddFreeTerm = servers.Where(x => x.HddFree < 0).Select(x => x.HddFree * 3).Sum();
                var positiveHddFreeTerm = servers.Where(x => x.HddFree > 0).Select(x => x.HddFree * 0.2).Sum();
                var negativeRamFreeTerm = servers.Where(x => x.RamFree < 0).Select(x => x.RamFree * 3).Sum();
                var positiveRamFreeTerm = servers.Where(x => x.RamFree > 0).Select(x => x.RamFree * 0.2).Sum();
                var negativeCpuFreeTerm = servers.Where(x => x.CpuFree < 0).Select(x => x.CpuFree * 3).Sum();
                var positiveCpuFreeTerm = servers.Where(x => x.CpuFree > 0).Select(x => x.CpuFree * 0.2).Sum();

                var fitness = freeServersTerm + negativeHddFreeTerm + positiveHddFreeTerm + negativeRamFreeTerm +
                              positiveRamFreeTerm + negativeCpuFreeTerm + positiveCpuFreeTerm;

                //по каждому серверу нужно вычислить коэффициент заполненности
                var serversFill = new List <double>();
                foreach (var server in servers)
                {
                    var serverFill = ((server.HddFull - server.HddFree) / server.HddFull) * 0.2 +
                                     ((server.RamFull - server.RamFree) / server.RamFull) * 0.4 +
                                     ((server.CpuFull - server.CpuFree) / server.CpuFull) * 0.4;
                    serversFill.Add(serverFill);
                }
                serversFill = serversFill.OrderByDescending(x => x).ToList();
                //отладочная строка
                //var serversFill = new List<double> { 0.9d, 0.9d, 0.6d, 0.2d,0 };
                //среднее значение заполненности серверов
                var averageFill = serversFill.Sum() / servers.Count();
                //рассчитаем дисперсию у serversFill
                var dispersion = serversFill.Select(eachFill => (eachFill - averageFill) * (eachFill - averageFill)).Sum() / servers.Count;

                return((dispersion * 3) + fitness);
            });

            var selection = new EliteSelection();
            //сделал свой кроссовер, похожий на UniformCrossover
            var crossover = new MyCrossover();
            //строка для отладки кроссовера
            //crossover.Cross(new List<IChromosome> {chromosome.CreateNew(), chromosome.CreateNew()});

            var mutation = new MyMutation();
            //mutation.Mutate(chromosome, Single.Epsilon);

            var termination = new FitnessStagnationTermination(100);

            var ga = new GeneticSharp.Domain.GeneticAlgorithm(
                population,
                fitness,
                selection,
                crossover,
                mutation)
            {
                Termination         = termination,
                MutationProbability = 0.3f
            };

            var latestFitness = 0.0;

            ga.GenerationRan += (sender, e) =>
            {
                var ga = (GeneticSharp.Domain.GeneticAlgorithm)sender;
                Console.Write("Номер итерации: " + ga.GenerationsNumber + "  " + "Время работы: " + ga.TimeEvolving);
                Console.WriteLine();

                var bestChromosome = ga.BestChromosome as MyChromosome;
                var bestFitness    = bestChromosome.Fitness.Value;

                if (bestFitness != latestFitness)
                {
                    latestFitness = bestFitness;
                    var phenotype = bestChromosome.GetGenes()
                                    .Select(x => (Server)x.Value).ToList();

                    Console.Write("Фитнес: " + bestFitness);
                    Console.WriteLine();

                    foreach (var server in phenotype)
                    {
                        Console.Write("Сервер: " + server.Name +
                                      ", HddFull: " + server.HddFull +
                                      ", RamFull: " + server.RamFull +
                                      ", HddFree: " + server.HddFree +
                                      ", RamFree: " + server.RamFree +
                                      ", CpuFree: " + server.CpuFree +
                                      ", сервисы: ");
                        Console.Write(" Заполненность Hdd: " + Math.Round(100 - (server.HddFree / server.HddFull * 100)) + "%");
                        Console.Write(" Заполненность Ram: " + Math.Round(100 - (server.RamFree / server.RamFull * 100)) + "%");
                        Console.Write(" Заполненность Cpu: " + Math.Round(100 - server.CpuFree) + "%");
                        foreach (var service in server.Services)
                        {
                            Console.Write(service.Name + ", ");
                        }
                        Console.WriteLine();
                        Console.WriteLine();

                        //получить хромосомы на этой итерации и смотреть, равны ли они.
                        //Хромосомы равны, если равны их фитнесы.
                        //Если равны, алгоритм преждевременно сходится (вырождается популяция)
                        var chromosomesFitnessCollection = ga.Population.CurrentGeneration.Chromosomes;
                    }
                }
            };

            ga.Start();
        }
示例#6
0
 protected abstract IList <ChromoSome> AdjustInternal(Population population, IList <ChromoSome> children, IList <ChromoSome> parents);
 public InternalSearchResult(Population population, TimeSpan searchTime, bool isCompleted)
 {
     SearchTime  = searchTime;
     IsCompleted = isCompleted;
     Population  = population;
 }