public static Individ[] mate(Individ[] population , Random rand, int numParents)
        {
            Individ[] temp_Population = new Individ[population.Length];
            //calculate parents
            int parent1;
            int parent2;

            for (int i = 0; i < population.Length; i++)
            {
                parent1 = rand.Next(0, numParents);
                parent2 = parent1;

                //parent2 should not be like parent1
                while(parent2 == parent1)
                {
                    parent2 = rand.Next(0, numParents);
                }

                //if (i == 0)
                //{
                //    temp_Population[i] = population[0];
                //}
                //else
                //{
                    temp_Population[i] = procreation(population[parent1], population[parent2], rand);
                //}
            }

            return temp_Population;
        }
        public async Task <IActionResult> Edit(int id, [Bind("Id,Idanimal,Name,Bio")] Individ individ)
        {
            if (id != individ.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(individ);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!IndividExists(individ.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(individ));
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            string anchor = Intent.GetStringExtra("anchor");

            this.SetContentView(Resource.Layout.individ_info);

            DataBase db = new DataBase();

            _ = db.CreateDataBaseAsync();
            HttpClient client = new HttpClient();

            Main    main    = GetMains(anchor, db, client);
            Individ individ = GetIndivid(main.Idindivid, db, client);

            animal = GetAnimal(individ.Idanimal, db, client);
            IndividImages individImages = GetImages(individ.Id, db, client);

            IndividInfo        individInfo = new IndividInfo(individ, individImages);
            IndividInfoAdapter adapter     = new IndividInfoAdapter(this, new List <IndividInfo>()
            {
                individInfo
            });

            ListView.Adapter = adapter;

            Button backButton = this.FindViewById <Button>(Resource.Id.BackButton);

            backButton.Click += this.OnBackClick;
            Button viewMoreButton = this.FindViewById <Button>(Resource.Id.ViewButton);

            viewMoreButton.Click += this.OnViewClick;
        }
        public long StartAlgorithm(int generations, int sampleSize)
        {
            var generationNumber = 0;

            Stopwatch watch = new Stopwatch();

            watch.Start();

            while (generations != generationNumber && Population.Fittest().Fitness != 0)
            {
                var newPopulation = new Individ[PopulationSize];

                for (var i = 0; i < PopulationSize; i += 2)
                {
                    var siblings = Crossover(Sample(sampleSize));
                    newPopulation[i]     = siblings.Item1;
                    newPopulation[i + 1] = siblings.Item2;
                }

                Population.Individs = newPopulation.ToList();

                Population.Mutate();

                Population.ComputeFitness();

                generationNumber++;
            }

            Console.WriteLine($"Generation: {generationNumber}");

            watch.Stop();

            return(watch.ElapsedMilliseconds);
        }
Exemple #5
0
        public async Task <IActionResult> PutIndivid(int id, Individ individ)
        {
            if (id != individ.Id)
            {
                return(BadRequest());
            }

            _context.Entry(individ).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!IndividExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        private Tuple <Individ, Individ> Crossover(Individ pater, Individ mater)
        {
            var random    = new Random();
            var child     = new Individ();
            var antiChild = new Individ();

            for (var index = 0; index < pater.Genes.Count; index++)
            {
                var timeProb     = random.NextDouble();
                var dayProb      = random.NextDouble();
                var locationProb = random.NextDouble();

                var paterGene = pater.Genes[index];
                var materGene = mater.Genes[index];
                var childGene = new Gene()
                {
                    Time     = timeProb <= CROSSOVER_SELECTION_RATE ? paterGene.Time : materGene.Time,
                    Day      = dayProb <= CROSSOVER_SELECTION_RATE ? paterGene.Day : materGene.Day,
                    Location = locationProb <= CROSSOVER_SELECTION_RATE ? paterGene.Location : materGene.Location
                };
                var antiChildGene = new Gene()
                {
                    Time     = timeProb <= CROSSOVER_SELECTION_RATE ? materGene.Time : paterGene.Time,
                    Day      = dayProb <= CROSSOVER_SELECTION_RATE ? materGene.Day : paterGene.Day,
                    Location = locationProb <= CROSSOVER_SELECTION_RATE ? materGene.Location : paterGene.Location
                };

                child.Genes.Add(childGene);
                antiChild.Genes.Add(antiChildGene);
            }

            return(Tuple.Create(child, antiChild));
        }
        private void Mutate(Individ individ)
        {
            var random = new Random();

            foreach (var gene in individ.Genes)
            {
                var timeProb     = random.NextDouble();
                var dayProb      = random.NextDouble();
                var locationProb = random.NextDouble();

                if (timeProb <= MUTATION_RATE)
                {
                    gene.Time = random.Next(0, AlgorithmData.TimeDecoded.Count);
                }

                if (dayProb <= MUTATION_RATE)
                {
                    gene.Day = random.Next(0, AlgorithmData.DayDecoded.Count);
                }

                if (locationProb <= MUTATION_RATE)
                {
                    gene.Location = random.Next(0, AlgorithmData.LocationNumber);
                }
            }
        }
Exemple #8
0
        public static void ComputeFitness(this Individ individ)
        {
            var fitness = 0;

            fitness += individ.Genes.Count - individ.Genes.Distinct().Count();

            individ.Fitness = fitness;
        }
        public async Task <IActionResult> Create([Bind("Id,Idanimal,Name,Bio")] Individ individ)
        {
            if (ModelState.IsValid)
            {
                _context.Add(individ);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(individ));
        }
        public Individ GetIndivid(int id, DataBase db, HttpClient client)
        {
            Individ individ = (Individ)db.SelectQueryTable(id, Constants.Constants.selectIndividQuery);

            if (individ == null)
            {
                System.Threading.Tasks.Task <string> result = client.GetStringAsync(Constants.Constants.individUri + id);
                individ = JsonConvert.DeserializeObject <Individ>(result.Result);
                db.InsertIntoTable(individ);
            }

            return(individ);
        }
Exemple #11
0
 public static bool checkIfAtMostOneLocationIsCapturedPerTurn(Individ _individ)
 {
     for (int i = 0; i < _individ.Chromosome.Length; i++)
     {
         var turnsList   = _individ.Chromosome[i].Select(x => x.CameraPosition.turn).ToList();
         var uniqueTurns = turnsList.Distinct().ToList();
         if (turnsList.Count != uniqueTurns.Count)
         {
             return(false);
         }
     }
     return(true);
 }
Exemple #12
0
 public static bool checkIfLocationIsInTimeRange(Individ _individ, Inputs _inputs)
 {
     for (int i = 0; i < _individ.Chromosome.Length; i++)
     {
         foreach (var item in _individ.Chromosome[i])
         {
             var collection = _inputs.collections.Single(x => x.Id == item.CollectionID);
             if (!collection.isInTimeRange(item.CameraPosition.turn))
             {
                 return(false);
             }
         }
     }
     return(true);
 }
        public void text_jobs_in_stank(Individ A, RichTextBox el)
        {
            el.Clear();
            List <List <int> > job_n_st = raspred_work(A.get_body(), 0);

            for (int i = 0; i < job_n_st.Count; i++)
            {
                List <int> element = job_n_st[i];
                el.AppendText("Станок - " + name_of_stank[i] + "\n");
                for (int j = 0; j < element.Count; j++)
                {
                    el.AppendText("Работа №" + (j + 1) + " - " + detal_names_time_type_on_id[element[j], 1] + "\n");
                }
                el.AppendText("Суммарное время работы станка: " + get_time_stank(element) + "\n\n");
            }
        }//выводит в текстовый блок работы на станках
        public long StartAlgorithm(int generations, int sampleSize)
        {
            bestIndivid = null;
            var generationNumber = 0;

            var watch = new Stopwatch();

            watch.Start();

            while (generations != generationNumber && BestFitness() != 0)
            {
                var newPopulation = new ConcurrentBag <Individ>();

                for (var i = 0; i < Population.Individs.Count / 2; i++)
                {
                    var parents = ChoseTwo(sampleSize);
                    var message = new Message()
                    {
                        Command  = "childrens",
                        Individ1 = parents.Item1,
                        Individ2 = parents.Item2
                    };

                    engine.ExecutorService.ScheduleTask(message, result =>
                    {
                        newPopulation.Add(result.Individ1);
                        newPopulation.Add(result.Individ2);
                    });
                }

                engine.ExecutorService.WaitToFinish();
                var newPopList = newPopulation.ToList();
                if (newPopList.Count != 0)
                {
                    Population.Individs = newPopulation.ToList();
                }
                else
                {
                }

                generationNumber++;
            }

            var time = watch.ElapsedMilliseconds;

            return(time);
        }
Exemple #15
0
        /* BACK UP Method
         *
         * public static bool checkCameraOffsetForConsecutivePictures(Individ _individ, Inputs _inputs)
         * {
         *  double w_latitude = 0;
         *  double w_longitude = 0;
         *  for (int i = 0; i < _individ.Chromosome.Length; i++)
         *  {
         *      var satelliteContent = _individ.Chromosome[i].OrderBy(x => x.CameraPosition.turn).ToList();
         *      Offset CameraPosition_t0 = new Offset();
         *      Satellite satellite = _inputs.satellites[i];
         *
         *      // foreach (var item in satelliteContent)
         *      for (int j = 0; j < satelliteContent.Count; j++)
         *      {
         *
         *          var item = satelliteContent[j];
         *
         *          if (item.CameraPosition.deltaLat > satellite.D || item.CameraPosition.deltaLong > satellite.D)
         *              return false;
         *
         *          w_latitude = Math.Abs(item.CameraPosition.deltaLat - CameraPosition_t0.deltaLat) / ((double)item.CameraPosition.turn - (double)CameraPosition_t0.turn);
         *          w_longitude = Math.Abs(item.CameraPosition.deltaLong - CameraPosition_t0.deltaLong) / ((double)item.CameraPosition.turn - (double)CameraPosition_t0.turn);
         *
         *          if (!(w_latitude <= (double)satellite.W && w_longitude <= (double)satellite.W))
         *              return false;
         *
         *          CameraPosition_t0 = new Offset();
         *          CameraPosition_t0.deltaLat = item.CameraPosition.deltaLat;
         *          CameraPosition_t0.deltaLong = item.CameraPosition.deltaLong;
         *          CameraPosition_t0.turn = item.CameraPosition.turn;
         *      }
         *  }
         *  return true;
         * }
         *
         */


        //public static bool _checkCameraOffsetForConsecutivePictures(Individ _individ, Inputs _inputs)
        //{
        //    double w_latitude = 0;
        //    double w_longitude = 0;
        //    for (int i = 0; i < _individ.Chromosome.Length; i++)
        //    {
        //        var satelliteContent = _individ._Chromosome[i].OrderBy(x => x.Key).ToList();
        //        Offset CameraPosition_t0 = new Offset();
        //        Satellite satellite = _inputs.satellites[i];
        //        foreach (var item in satelliteContent)
        //        {
        //            if (item.Value.CameraPosition.deltaLat > satellite.D || item.Value.CameraPosition.deltaLong > satellite.D)
        //                return false;

        //            w_latitude = Math.Abs(item.Value.CameraPosition.deltaLat - CameraPosition_t0.deltaLat) / ((double)item.Value.CameraPosition.turn - (double)CameraPosition_t0.turn);
        //            w_longitude = Math.Abs(item.Value.CameraPosition.deltaLong - CameraPosition_t0.deltaLong) / ((double)item.Value.CameraPosition.turn - (double)CameraPosition_t0.turn);

        //            if (!(w_latitude < satellite.W && w_longitude < satellite.W))
        //                return false;

        //            CameraPosition_t0 = new Offset();
        //            CameraPosition_t0.deltaLat = item.Value.CameraPosition.deltaLat;
        //            CameraPosition_t0.deltaLong = item.Value.CameraPosition.deltaLong;
        //            CameraPosition_t0.turn = item.Value.CameraPosition.turn;
        //        }
        //    }
        //    return true;
        //}



        //public static bool checkCameraOffsetForConsecutivePictures(Individ _individ, Inputs _inputs)
        //{
        //    for (int i = 0; i < _individ.Chromosome.Length; i++)
        //    {
        //        foreach (var gene in _individ.Chromosome[i])
        //        {
        //            Satellite satellite = _inputs.satellites[i];
        //            if (gene.CameraPosition.w_lat > satellite.W || gene.CameraPosition.w_long > satellite.W)
        //                return false;
        //        }
        //    }
        //    return true;
        //}


        public static bool checkIfOneLocationIsCapturedOnce(Individ _individ)
        {
            List <int> locationsCaptured = new List <int>();

            for (int i = 0; i < _individ.Chromosome.Length; i++)
            {
                foreach (var location in _individ.Chromosome[i])
                {
                    if (locationsCaptured.Contains(location.LocationID))
                    {
                        return(false);
                    }

                    locationsCaptured.Add(location.LocationID);
                }
            }
            return(true);
        }
        public static Individ[] mutate_Population(Individ[] population, Random rand, double chance)
        {
            //initialize temporary population
            Individ[] temp_Population = population;

            //Mutate every individual of the population
            for (int i = 0; i < temp_Population.Length; i++)
            {
                for (int j = 0; j < temp_Population[i].genes.Length; j++)
                {
                    if (rand.Next(0, 101) < chance)
                    {
                        //random R,G,B,A,X,Y picker
                        int rand_int = rand.Next(1, 7);

                        switch (rand_int)
                        {
                            case 1:
                                temp_Population[i].Genes[j].R = rand.Next(0, 256);
                                break;
                            case 2:
                                temp_Population[i].Genes[j].G = rand.Next(0, 256);
                                break;
                            case 3:
                                temp_Population[i].Genes[j].B = rand.Next(0, 256);
                                break;
                            case 4:
                                temp_Population[i].Genes[j].A = rand.Next(0, 256);
                                break;
                            case 5:
                                temp_Population[i].Genes[j].pos[rand.Next(0, 3)].X = rand.Next(0, population[0].source.Width);
                                break;
                            case 6:
                                temp_Population[i].Genes[j].pos[rand.Next(0, 3)].Y = rand.Next(0, population[0].source.Height);
                                break;

                        }
                    }

                }
            }

            return temp_Population;
        }
Exemple #17
0
        public async Task <ActionResult <Individ> > PostIndivid(Individ individ)
        {
            _context.Individ.Add(individ);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (IndividExists(individ.Id))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            return(CreatedAtAction("GetIndivid", new { id = individ.Id }, individ));
        }
Exemple #18
0
        private int CaculateFitness(Individ individ)
        {
            var intersections = new Dictionary <Gene, int>();

            foreach (var gene in individ.Genes)
            {
                if (!intersections.ContainsKey(gene))
                {
                    intersections[gene] = 0;
                }
                intersections[gene]++;
            }

            var fitness = 0;

            foreach (var keyValuePair in intersections)
            {
                fitness += keyValuePair.Value - 1;
            }

            return(fitness);
        }
Exemple #19
0
        private void btnRunGeneticAlgorithm_Click(object sender, EventArgs e)
        {
            // Initialize GA
            GeneticAlgorithm ga = new GeneticAlgorithm((int)numPopulationSize.Value,
                                                       (int)numTournamentSize.Value,
                                                       (int)numMaxGenerations.Value,
                                                       (int)numTerminationThreshold.Value,
                                                       Path.GetFileName(txtPathFile.Text).Split('.')[0],
                                                       chbExternalInitialize.Checked);

            BestIndivid = ga.RunGeneticAlgorithm(inputs);


            // Check Validation of the Best Solution
            if (!Validation.checkIfLocationIsInTimeRange(BestIndivid, inputs))
            {
                MessageBox.Show("The solution is not valid! \n Problem with time range!");
            }

            if (!Validation.checkCameraOffsetForConsecutivePictures(BestIndivid, inputs))    // This is false..., Why?
            {
                MessageBox.Show("The solution is not valid! \n Camera offset is greater than w arcseconds between taking two consecutive pictures.");
            }

            if (!Validation.checkIfOneLocationIsCapturedOnce(BestIndivid))
            {
                MessageBox.Show("The solution is not valid! \n Location has been captured twice! ");
            }

            if (!Validation.checkIfAtMostOneLocationIsCapturedPerTurn(BestIndivid))
            {
                MessageBox.Show("The solution is not valid! \n More than one location has been captured in a turn by the same satellite! ");
            }
            ExtractSubmissionIntoFile();
            MessageBox.Show("Finished! \n Score: " + BestIndivid.Fitness);
        }
Exemple #20
0
        public static Tuple <Individ, Individ> Crossover(this Individ fatherIndivid, Individ motherIndivid)
        {
            var brotherIndividGenes     = new Gene[AlgorithmData.CoursesNumber * AlgorithmData.GroupsNumber];
            var stuckSisterIndividGenes = new Gene[AlgorithmData.CoursesNumber * AlgorithmData.GroupsNumber];

            for (var index = 0; index < AlgorithmData.CoursesNumber * AlgorithmData.GroupsNumber; index++)
            {
                var siblingsGenesTuple = fatherIndivid.Genes[index].Crossover(motherIndivid.Genes[index]);
                brotherIndividGenes[index]     = siblingsGenesTuple.Item1;
                stuckSisterIndividGenes[index] = siblingsGenesTuple.Item2;
            }

            return(new Tuple <Individ, Individ>
                   (
                       new Individ()
            {
                Genes = brotherIndividGenes.ToList()
            },
                       new Individ()
            {
                Genes = stuckSisterIndividGenes.ToList()
            }
                   ));
        }
Exemple #21
0
        /*
         * Characteristic of Method:
         * It recalculates from scratch all the positions of camera per turn between taking two consecutive pictures!
         */
        public static bool checkCameraOffsetForConsecutivePictures(Individ _individ, Inputs _inputs)
        {
            double w_latitude  = 0;
            double w_longitude = 0;

            for (int i = 0; i < _individ.Chromosome.Length; i++)
            {
                var       satelliteContent  = _individ.Chromosome[i].OrderBy(x => x.Turn).ToList();
                Offset    CameraPosition_t0 = new Offset();
                Satellite satellite         = _inputs.satellites[i];

                // foreach (var item in satelliteContent)
                for (int j = 0; j < satelliteContent.Count; j++)
                {
                    var item = satelliteContent[j];
                    if (item.CameraPosition.deltaLat > satellite.D || item.CameraPosition.deltaLong > satellite.D)
                    {
                        return(false);
                    }

                    w_latitude  = Math.Abs(item.CameraPosition.deltaLat - CameraPosition_t0.deltaLat) / ((double)item.CameraPosition.turn - (double)CameraPosition_t0.turn);
                    w_longitude = Math.Abs(item.CameraPosition.deltaLong - CameraPosition_t0.deltaLong) / ((double)item.CameraPosition.turn - (double)CameraPosition_t0.turn);

                    if (w_latitude > (double)satellite.W && w_longitude > (double)satellite.W)
                    {
                        return(false);
                    }

                    CameraPosition_t0           = new Offset();
                    CameraPosition_t0.deltaLat  = item.CameraPosition.deltaLat;
                    CameraPosition_t0.deltaLong = item.CameraPosition.deltaLong;
                    CameraPosition_t0.turn      = item.CameraPosition.turn;
                }
            }
            return(true);
        }
        public int BestFitness()
        {
            var     bestFitnessPop = Int32.MaxValue;
            Individ bestIndividPop = null;

            Population.Individs.ForEach(individ =>
            {
                if (bestFitnessPop > individ.Fitness)
                {
                    bestFitnessPop = individ.Fitness;
                    bestIndividPop = individ;
                }
            });

            if (bestIndivid == null)
            {
                bestIndivid = bestIndividPop;
            }
            else if (bestIndividPop != null && bestIndivid.Fitness > bestIndividPop.Fitness)
            {
                bestIndivid = bestIndividPop;
            }
            return(bestFitnessPop);
        }
Exemple #23
0
 public static void Mutate(this Individ individ)
 {
     individ.Genes.AsParallel().ForAll(gene => gene.Mutate());
 }
        private void button1_Click(object sender, EventArgs e)
        {
            Application.DoEvents();
            //initialize source image
            Source_Image_Path.ShowDialog();
            Bitmap source_Image = (Bitmap)Image.FromFile(Source_Image_Path.FileName);
            Source_Imagebox.BackgroundImage = source_Image;
            Application.DoEvents();

            //initialize Population
            int numGenes = 10;
            int popSize = 32;
            int mutateChance = 5;
            Random rand = new Random();
            Individ[] population = new Individ[popSize];

            for (int i = 0; i < popSize; i++)
            {
                population[i] = new Individ(source_Image, numGenes, rand);
            }

            //Sorting initial Population
            Array.Sort(population, delegate (Individ num1, Individ num2)
            {
                return num1.fitness.CompareTo(num2.fitness);
            });

            //Evolving population until best individ fitness meets some value 5500000
            while(population[0].fitness > 55000)
            {
                //evolving Population
                population = mate(population, rand, 4);

                //Mutate population
                population = mutate_Population(population, rand, mutateChance);

                //Sorting Population
                Array.Sort(population, delegate (Individ num1, Individ num2)
                {
                    return num1.fitness.CompareTo(num2.fitness);
                });

                //print best image of the generation

                Application.DoEvents();
                Genes_Textbox.Text = (population[0].fitness + Environment.NewLine) + Genes_Textbox.Text;
                Evo_Imagebox.BackgroundImage = population[0].evoImage;
                Application.DoEvents();
            }
            Application.DoEvents();
            Genes_Textbox.Text = (population[0].fitness + Environment.NewLine) + Genes_Textbox.Text;
            Evo_Imagebox.BackgroundImage = population[0].evoImage;
            Application.DoEvents();
        }
        public static Individ procreation(Individ Parent1, Individ Parent2, Random rand)
        {
            //initialize a cutoff point where all the genes of parent 1 will be transferred from before the point
            //and all the genes from parent 2 will be transferred to the kid from after the point
            int cutoff = rand.Next(0, Parent1.genes.Length);

            //Initialize kid
            Individ kid = new Individ(Parent1.source, Parent1.genes.Length, rand);
            Triangle[] kid_Genes = new Triangle[kid.genes.Length];

            for (int i = 0; i < kid.genes.Length; i++)
            {
                if (i < cutoff)
                {
                    kid_Genes[i] = Parent1.genes[i];
                }
                else kid_Genes[i] = Parent2.genes[i];
            }

            kid.Genes = kid_Genes;

            return kid;
        }
        }// создает новую популяцию из текущей

        private Individ[] crossengover(Individ A1, Individ A2)
        {
            List <List <int> > body_1 = new List <List <int> >(A1.get_body()),
                               body_2 = new List <List <int> >(A2.get_body()),
                               body_3 = new List <List <int> >(),
                               body_4 = new List <List <int> >();

            Individ[] result = new Individ[2];
            for (int ID_yach = 0; ID_yach < body_1.Count; ID_yach++)
            {
                List <int> yach_1          = body_1[ID_yach],
                           yach_2          = body_2[ID_yach],
                           yach_3          = new List <int>(),
                           yach_4          = new List <int>();
                List <int[]> col_n_types_1 = get_col_n_types_jobs(yach_1);
                List <int[]> col_n_types_2 = get_col_n_types_jobs(yach_2);
                //порядок вперед для 1 ребенка
                for (int id_job = 0; id_job < yach_1.Count; id_job++)
                {
                    for (int i = 0; i < col_n_types_1.Count; i++)
                    {
                        int[] elem = col_n_types_1[i];
                        if (elem[0] == yach_1[id_job])
                        {
                            if (elem[1] != 0)
                            {
                                elem[1]--;
                                yach_3.Add(yach_1[id_job]);
                                col_n_types_1[i] = elem;
                                break;
                            }
                        }
                    }
                    for (int i = 0; i < col_n_types_1.Count; i++)
                    {
                        int[] elem = col_n_types_1[i];
                        if (elem[0] == yach_2[id_job])
                        {
                            if (elem[1] != 0)
                            {
                                elem[1]--;
                                yach_3.Add(yach_2[id_job]);
                                break;
                            }
                        }
                    }
                }
                for (int i = 0; i < col_n_types_1.Count; i++)
                {
                    int[] elem = col_n_types_1[i];
                    for (int j = 0; j < elem[1]; j++)
                    {
                        yach_3.Add(elem[0]);
                    }
                }
                // обратный порядок для 2 ребенка
                for (int id_job = yach_1.Count - 1; id_job >= 0; id_job--)
                {
                    //MessageBox.Show(yach_1[id_job] + "");
                    for (int i = 0; i < col_n_types_2.Count; i++)
                    {
                        int[] elem = col_n_types_2[i];
                        if (elem[0] == yach_1[id_job])
                        {
                            if (elem[1] != 0)
                            {
                                elem[1]--;
                                yach_4.Add(yach_1[id_job]);
                                col_n_types_2[i] = elem;
                                break;
                            }
                        }
                    }
                    for (int i = 0; i < col_n_types_2.Count; i++)
                    {
                        int[] elem = col_n_types_2[i];
                        if (elem[0] == yach_2[id_job])
                        {
                            if (elem[1] != 0)
                            {
                                elem[1]--;
                                yach_4.Add(yach_2[id_job]);
                                break;
                            }
                        }
                    }
                }
                for (int i = 0; i < col_n_types_2.Count; i++)
                {
                    int[] elem = col_n_types_2[i];
                    for (int j = 0; j < elem[1]; j++)
                    {
                        yach_4.Add(elem[0]);
                    }
                }
                //MessageBox.Show(yach_4.Count +"");
                body_3.Add(yach_3);
                body_4.Add(yach_4);

                /*string red = "";
                 * foreach (int[] el in col_n_types)
                 * {
                 *  red += el[0] + " " + el[1] + "\n";
                 * }
                 * MessageBox.Show(red);*/
            }
            result[0] = new Individ(body_3, false);
            get_Function(result[0].get_body());
            result[1] = new Individ(body_4, false);
            get_Function(result[1].get_body());
            return(result);
        }// скрещивание двух особей
        private List <Individ> selection_individ()
        {
            Individ[]      cross = new Individ[2];
            List <Individ> result = new List <Individ>();
            List <Individ> VERH = new List <Individ>();
            List <Individ> NIZ = new List <Individ>();
            int            col_VERH = Convert.ToInt32(col_population * _PERSENTV_), col_NIZ = Convert.ToInt32(col_population * _PERSENTN_);

            for (int i = 0; i < col_VERH; i++)
            {
                VERH.Add(NOW_POPULATION[i]);
            }
            for (int i = (NOW_POPULATION.Count - 1); i >= NOW_POPULATION.Count - col_NIZ; i--)
            {
                NIZ.Add(NOW_POPULATION[i]);
            }
            result.Add(VERH[0]);
            for (int i = 0; i < VERH.Count - 1; i++)
            {
                for (int j = i + 1; j < VERH.Count; j++)
                {
                    cross = crossengover(VERH[i], VERH[j]);
                    result.Add(cross[0]);
                    result.Add(cross[1]);
                }
                //MessageBox.Show("r1=" + get_Function(VERH[0].get_body()) + "  r2=" + get_Function(VERH[1].get_body()) + "\n ch1=" + get_Function(result[0].get_body()) + "   ch2=" + get_Function(result[1].get_body()));
            }
            for (int i = 0; i < NIZ.Count - 1; i++)
            {
                for (int j = i + 1; j < NIZ.Count; j++)
                {
                    cross = crossengover(NIZ[i], NIZ[j]);
                    result.Add(cross[0]);
                    result.Add(cross[1]);
                }
                //MessageBox.Show("r1=" + get_Function(VERH[0].get_body()) + "  r2=" + get_Function(VERH[1].get_body()) + "\n ch1=" + get_Function(result[0].get_body()) + "   ch2=" + get_Function(result[1].get_body()));
            }
            for (int i = 1; i < VERH.Count; i++)
            {
                if (result.Count >= col_population)
                {
                    break;
                }
                result.Add(VERH[i]);
            }
            for (int i = 0; i < NIZ.Count; i++)
            {
                if (result.Count >= col_population)
                {
                    break;
                }
                result.Add(NIZ[i]);
            }
            if (result.Count > col_population)
            {
                int col_del = result.Count - col_population;

                for (int i = result.Count - 1; i >= col_population; i--)
                {
                    result.RemoveAt(i);
                }
            }
            //MessageBox.Show(result.Count + "");
            NOW_POPULATION = result;
            Pver_n_sort();
            return(result);
        }// создает новую популяцию из текущей
Exemple #28
0
 public IndividInfo(Individ individ, IndividImages images)
 {
     this.individ = individ;
     this.images  = images;
 }
Exemple #29
0
 public MutationResponse()
 {
     individ = new Individ();
 }