示例#1
0
        public IndividualMetricsTests()
        {
            // Set up multi-objective population

            moTestInd = ObjectCreators.GetIndividual(new double[] { 0, 2 });
            moTestInd.SendForEvaluation();

            var solution1     = 0.2;
            var solution1Name = ObjectCreators.Solution_Key;
            var solution2     = 5.1;
            var solution2Name = ObjectCreators.Solution_Key + "2";
            var solution3     = 55.0;
            var solution3Name = ObjectCreators.Solution_Key + "3";

            moTestInd.SetProperty(solution1Name, solution1);
            moTestInd.SetProperty(solution2Name, solution2);
            moTestInd.SetProperty(solution3Name, solution3);

            indEqual          = moTestInd.Clone();
            indParetoDominant = moTestInd.Clone();
            indParetoEqual1   = moTestInd.Clone();
            indWrong          = moTestInd.Clone();

            indParetoDominant.SetProperty(solution1Name, solution1 - 0.1);
            indParetoEqual1.SetProperty(solution1Name, solution1 - 0.1);
            indParetoEqual1.SetProperty(solution2Name, solution2 + 0.1);

            minimise = new[] { true, true, true };

            moTestInd.SetSolution(solution1Name, solution2Name, solution3Name);
            indEqual.SetSolution(solution1Name, solution2Name, solution3Name);
            indParetoDominant.SetSolution(solution1Name, solution2Name, solution3Name);
            indParetoEqual1.SetSolution(solution1Name, solution2Name, solution3Name);
            indWrong.SetSolution(solution1Name, solution2Name);
        }
示例#2
0
        private void startButton_Click(object sender, EventArgs e)
        {
            double a         = Convert.ToDouble(aBox.Text);
            double b         = Convert.ToDouble(bBox.Text);
            double d         = Convert.ToDouble(dBox.Text);
            double tau       = Convert.ToDouble(tauBox.Text);
            int    T         = Convert.ToInt32(Tbox.Text);
            Random generator = new Random();
            int    round     = 0;
            int    l         = (int)Math.Ceiling(Math.Log(((b - a) * (1 / d)) + 1, 2));

            double pom = d;

            while (pom < 1)
            {
                round++;
                pom *= 10;
            }

            List <Individual> individuals = null;
            List <Individual> ListVb      = new List <Individual>();
            List <Individual> ListVbest   = new List <Individual>();
            Individual        Vbest;

            Individual individual = Geo.MakeFirstInd(a, b, d, l, generator);

            Vbest = individual.Clone();
            ListVb.Add(individual.Clone());
            ListVbest.Add(Vbest.Clone());
            for (int i = 1; i < T; i++)
            {
                individuals = Geo.MakePopulation(individual, a, b, l, round);

                Geo.CountProbability(individuals, tau);

                Geo.MutateInd(individual, individuals, a, b, l, round, generator);

                if (Vbest.Fx < individual.Fx)
                {
                    Vbest = individual.Clone();
                }

                ListVbest.Add(Vbest.Clone());
                ListVb.Add(individual.Clone());
                individuals.Clear();
            }

            individuals.Add(Vbest);
            var bindingList = new BindingList <Individual>(individuals);
            var source      = new BindingSource(bindingList, null);

            table.DataSource = source;

            ToTxt.WriteToFile(ListVb, T, tau, d);
            MakeChart(ListVb, ListVbest);
        }
示例#3
0
    Individual tournamentSelection(List <Individual> oldpop, int num)
    {
        List <Individual> selectedInds = new List <Individual> ();
        int   chosen  = 0;
        float best    = 10000;
        int   popsize = oldpop.Count;

        for (int i = 0; i < num; i++)
        {
            //make sure selected individuals are different
            Individual ind = oldpop [Random.Range(0, popsize)];
            while (selectedInds.Contains(ind))
            {
                ind = oldpop [Random.Range(0, popsize)];
            }
            selectedInds.Add(ind.Clone());              //we return copys of the selected individuals
        }


        for (int i = 0; i < num; i++)
        {
            if (selectedInds [i].fitness < best)
            {
                chosen = i;
                best   = selectedInds [i].fitness;
            }
        }
        return(selectedInds[chosen]);
    }
    private static void AdvanceGeneration()
    {
        Individual[] nextPopulation     = new Individual[Config.nIndividualsPerPopulation];
        Individual[] orderedIndividuals = FitnessHelper.GetOrderedIndividuals(population);

        for (int i = 0; i < Config.nElite; i++)
        {
            nextPopulation[i]          = orderedIndividuals[i];
            nextPopulation[i].wasElite = true;
        }
        Debug.Log("ordered generation " + generationsFinished);
        Print(orderedIndividuals);

        //sacar el promedio de fitness, y hacer que la mutación pase empezando por el promedio ese dividido 2 (por ejemplo, si el fitness promedio es 4, empezás a mutar desde el frame 2)
        //y aumentás el mutationRate un toque

        Individual[] childrenIndividuals = ReproductionHelper.GetChildrenIndividuals(population, Config.nIndividualsPerPopulation - Config.nElite);
        MutationHelper.MutatePopulation(childrenIndividuals);

        for (int i = Config.nElite; i < childrenIndividuals.Length + Config.nElite; i++)
        {
            nextPopulation[i] = childrenIndividuals[i - Config.nElite];
        }

        Debug.Log("next generation " + generationsFinished + 1);
        Print(nextPopulation);


        generationsFinished++;
        individualsFinished = 0;
        population          = (Individual[])nextPopulation.Clone();
        StartIndividual(0);
    }
示例#5
0
    List <Individual> torneioSelection(List <Individual> oldpop, int num)
    {
        List <Individual> selectedInds = new List <Individual>();
        List <Individual> listaTorneio = new List <Individual>();
        int popsize = oldpop.Count;


        // Repete o numero de individuos que há na população
        for (int i = 0; i < num; i++)
        {
            // Limpa a lista do torneio, pois cada um é independente
            listaTorneio.Clear();
            for (int j = 0; j < tam; j++)
            {
                // Escolhe individuo aleatório
                Individual ind = oldpop[Random.Range(0, popsize)];
                listaTorneio.Add(ind);
            }

            // Compara os individuos selecionados em relação à sua aptidão
            IComparer <Individual> aptidao = new Best();

            // Ordenação da aptidão por ordem crescente
            listaTorneio.Sort(aptidao);

            // Vai buscar melhor individuo

            Individual bestIndividuo = listaTorneio[0];

            selectedInds.Add(bestIndividuo.Clone()); //we return copys of the selected individuals*/
        }

        return(selectedInds);
    }
示例#6
0
        /// <summary>
        /// Operator operate method
        /// </summary>
        /// <param name="parents">parents</param>
        /// <param name="offspring">offspring</param>
        public void Operate(Population parents, Population offspring)
        {
            int size = parents.GetPopulationSize();

            for (int i = 0; i < size; i++)
            {
                Individual p1 = parents.Get(i);
                Individual o1 = (Individual)p1.Clone();

                if (rng.NextDouble() < mutationProbability)
                {
                    // any nondetoured edge might get activated
                    List <Edge> nondetouredEdges = p1.GetUndetoured();
                    if (nondetouredEdges.Count > 0)
                    {
                        foreach (var edge in Program.graph.GetEdges())
                        {
                            if (rng.NextDouble() < bitFlipProbability &&
                                nondetouredEdges.Contains(edge))
                            {
                                o1.SetActivityOnEdge(edge.ID, 1);
                                o1.changed = true;
                            }
                        }
                    }
                }
                offspring.Add(o1);
            }
        }
示例#7
0
        private void SaveGenetaionFitness(int generationNumber)
        {
            var result = new Result
            {
                GenerationNumber = generationNumber
            };
            float sum = 0;

            for (int i = 0; i < GENERATION_SIZE; i++)
            {
                Individual crentIndiv = Generation[i];
                float      fitness    = crentIndiv.Fitness;
                sum += fitness;
                if (fitness < result.Min)
                {
                    result.Min = fitness;
                }
                if (fitness > result.Max)
                {
                    result.Max            = fitness;
                    result.BestIndividual = (Individual)crentIndiv.Clone();
                }
            }
            result.Average = sum / GENERATION_SIZE;
            result.Average = -result.Average;
            result.Max     = -result.Max;
            result.Min     = -result.Min;
            AlgorythmResult[generationNumber] = result;
            if (generationNumber % 1000 == 0)
            {
                Console.WriteLine($"Thread: {Thread.CurrentThread.Name} Generation: {generationNumber}; Average: {result.Average}; Max: {result.Max}; Min: {result.Min};");
            }
        }
示例#8
0
        public static List <Individual> PerformCrossOver(List <Individual> population, IUniformRandomGenerator randomGenerator, IGenoTypeCrossoverator crossOverator)
        {
            var returnObject = new List <Individual>();

            do
            {
                var leftIndex      = randomGenerator.GetIntegerRandomNumber(0, population.Count - 1);
                var leftIndividual = population[leftIndex];
                population.RemoveAt(leftIndex);

                Individual rightIndividual = null;
                if (population.Count > 0)
                {
                    var rightIndex = randomGenerator.GetIntegerRandomNumber(0, population.Count - 1);
                    rightIndividual = population[rightIndex];
                    population.RemoveAt(rightIndex);
                }

                if (rightIndividual != null)
                {
                    crossOverator.PerformCrossover(ref leftIndividual.GenoType, ref rightIndividual.GenoType);
                    returnObject.Add((Individual)rightIndividual.Clone());
                }
                returnObject.Add((Individual)leftIndividual.Clone());
            } while (population.Count >= 1);

            if (population.Count == 1)
            {
                returnObject.Add(population[0]);
            }

            return(returnObject);
        }
示例#9
0
        public override int Produce(
            int min,
            int max,
            int subpop,
            IList <Individual> inds,
            IEvolutionState state,
            int thread,
            IDictionary <string, object> misc)
        {
            // First things first: build our individual and his parents array
            if (Individual == null)
            {
                IDictionary <string, object> misc1 = null;
                if (misc != null && misc[SelectionMethod.KEY_PARENTS] != null)
                {
                    // the user is providing a parents array.  We'll need to make our own.
                    var parentsArray = new IntBag[1];
                    misc1 = new Dictionary <string, object>
                    {
                        [SelectionMethod.KEY_PARENTS] = parentsArray
                    };
                }
                IList <Individual> temp = new List <Individual>();
                Sources[0].Produce(1, 1, subpop, temp, state, thread, misc1);
                Individual = temp[0];

                // Now we extract from misc1 if we have to
                if (misc1?[SelectionMethod.KEY_PARENTS] != null) // we already know this second fact unless it was somehow removed
                {
                    Parents = ((IntBag[])misc[SelectionMethod.KEY_PARENTS])[0];
                }
                else
                {
                    Parents = null;
                }
            }

            int start = inds.Count;

            // Now we can copy the individual in
            for (int i = 0; i < min; i++)
            {
                inds.Add((Individual)Individual.Clone());
            }

            // add in the parents if we need to
            if (Parents != null && misc != null && misc[SelectionMethod.KEY_PARENTS] != null)
            {
                var parentsArray = (IntBag[])misc[SelectionMethod.KEY_PARENTS];
                for (int i = 0; i < min; i++)
                {
                    parentsArray[start + i] = new IntBag(Parents);
                }
            }

            return(min);
        }
    private List <Individual> tournamentSelection(List <Individual> oldpop, int num)
    {
        List <Individual> selectedInds = new List <Individual> ();
        int popsize = oldpop.Count;

        for (int i = 0; i < num; i++)
        {
            //make sure selected individuals are different
            Individual ind  = oldpop [Random.Range(0, popsize)];
            Individual ind2 = oldpop [Random.Range(0, popsize)];

            while (ind2 == ind)
            {
                ind2 = oldpop [Random.Range(0, popsize)];
            }

            if (Random.Range(0f, 1f) < k)
            {
                if (ind.Fitness > ind2.Fitness)
                {
                    selectedInds.Add(ind.Clone());
                }
                else
                {
                    selectedInds.Add(ind2.Clone());
                }
            }
            else
            {
                if (ind.Fitness > ind2.Fitness)
                {
                    selectedInds.Add(ind2.Clone());
                }
                else
                {
                    selectedInds.Add(ind.Clone());
                }
            }
        }
        //we return copys of the selected individuals
        return(selectedInds);
    }
示例#11
0
        private IndividualViewModel GetIndividualViewModel(Individual individual, int includeAncestors = 0, bool includeFamilies = false)
        {
            var ind = individual.Clone();

            ind.Facts = _factService.Get(ind.TreeId, f => f.OwnerId == ind.Id && f.OwnerType == EntityType.Individual).ToList();

            var individualViewModel = new IndividualViewModel(ind);

            if (includeAncestors > 0)
            {
                if (individualViewModel.FatherId > 0)
                {
                    individualViewModel.Father = GetIndividualViewModel(_individualService.Get(individualViewModel.FatherId, ind.TreeId), includeAncestors - 1);
                }
                if (individualViewModel.MotherId > 0)
                {
                    individualViewModel.Mother = GetIndividualViewModel(_individualService.Get(individualViewModel.MotherId, ind.TreeId), includeAncestors - 1);
                }
            }

            if (includeFamilies)
            {
                individualViewModel.Families = new List <FamilyViewModel>();

                var families = _familyService.Get(ind.TreeId,
                                                  fam => ind.Sex == Sex.Male ? fam.HusbandId == ind.Id : fam.WifeId == ind.Id);
                foreach (var family in families)
                {
                    individualViewModel.Families.Add(GetFamilyViewModel(family, ind.Sex));
                }
            }

            individualViewModel.Facts = new List <FactViewModel>();
            foreach (var fact in ind.Facts)
            {
                individualViewModel.Facts.Add(new FactViewModel(fact));
            }

            if (ind.ImageId == -1)
            {
                individualViewModel.ImageUrl = (ind.Sex == Sex.Female)
                                                    ? "DesktopModules/FTP/FamilyTreeProject/Images/female.png"
                                                    : "DesktopModules/FTP/FamilyTreeProject/Images/male.png";
            }
            else
            {
                var file = FileManager.Instance.GetFile(ind.ImageId);
                individualViewModel.ImageUrl = (file.PortalId == -1)
                                            ? Globals.HostPath + file.RelativePath
                                            : PortalSettings.HomeDirectory + file.RelativePath;
            }

            return(individualViewModel);
        }
示例#12
0
    //The Step function assumes that the fitness values of all the individuals in the population have been calculated.
    public override void Step()
    {
        //criar a nova populacao
        List <Individual> new_pop = new List <Individual>();

        updateReport(); //called to get some stats
                        // fills the rest with mutations of the best!
        if (elitist)
        {
            for (int i = 0; i < populationSize - (elistismoValor * populationSize); i++)
            {
                GeneticIndividual best  = (GeneticIndividual) new TournmentSelect().selectIndividuals(population, tournamentSize).Clone();
                GeneticIndividual best2 = (GeneticIndividual) new TournmentSelect().selectIndividuals(population, tournamentSize).Clone();
                best.Crossover(best2, crossoverProbability);
                best.Mutate(mutationProbability);
                new_pop.Add(best.Clone());
                Debug.Log(new_pop.Count);
            }


            float      max2  = float.MaxValue;
            Individual elite = null;
            for (int i = 0; i < (elistismoValor * populationSize); i++)
            {
                float max = float.MinValue;
                for (int j = 0; j < populationSize; j++)
                {
                    if (population[j].Fitness > max && population[j].Fitness < max2)
                    {
                        max   = population[j].Fitness;
                        elite = (GeneticIndividual)population[j];
                    }
                }
                max2 = max;
                new_pop.Add(elite.Clone());
            }
        }
        else
        {
            for (int i = 0; i < populationSize; i++)
            {
                GeneticIndividual best  = (GeneticIndividual) new TournmentSelect().selectIndividuals(population, tournamentSize).Clone();
                GeneticIndividual best2 = (GeneticIndividual) new TournmentSelect().selectIndividuals(population, tournamentSize).Clone();
                best.Crossover(best2, crossoverProbability);
                best.Mutate(mutationProbability);
                new_pop.Add(best.Clone());
                Debug.Log(new_pop.Count);
            }
        }

        population = new_pop;

        generation++;
    }
        /// <summary>
        /// Test methods exposed by the EntityHelper class.
        /// </summary>
        private void Step_20_TestEntityHelper_Generated()
        {
            using (TransactionManager tm = CreateTransaction())
            {
                mock = CreateMockInstance(tm);

                Individual entity = mock.Copy() as Individual;
                entity = (Individual)mock.Clone();
                Assert.IsTrue(Individual.ValueEquals(entity, mock), "Clone is not working");
            }
        }
        /// <summary>
        /// The operator operate method
        /// </summary>
        /// <param name="parents">parents</param>
        /// <param name="offspring">offspring</param>
        public void Operate(Population parents, Population offspring)
        {
            int size = parents.GetPopulationSize();

            for (int i = 0; i < size; i++)
            {
                Individual p1 = parents.Get(i);
                Individual o1 = (Individual)p1.Clone();

                if (rng.NextDouble() < mutationProbability)
                {
                    // get all undetoured edges
                    List <Edge> nondetouredEdges = p1.GetUndetoured();
                    // monitoring repairs
                    Dictionary <Edge, int> repairs = new Dictionary <Edge, int>();
                    int max     = 0;
                    int counter = 0;
                    // if there is any nondetoured edge
                    if (nondetouredEdges.Count > 0)
                    {
                        foreach (var edge in nondetouredEdges)
                        {
                            // set activity, check number of detour then and set activity back
                            p1.SetActivityOnEdge(edge.ID, 1);
                            int count = p1.GetUndetoured().Count();
                            repairs.Add(edge, count);
                            if (count > max)
                            {
                                max     = count;
                                counter = 1;
                            }
                            else if (count == max)
                            {
                                counter++;
                            }
                            p1.SetActivityOnEdge(edge.ID, 0);
                        }
                        // find the edge that solves most problems
                        foreach (var edge in nondetouredEdges)
                        {
                            // with probability activate it (might be multiple)
                            if (rng.NextDouble() < 1 / counter &&
                                repairs[edge] == max)
                            {
                                o1.SetActivityOnEdge(edge.ID, 1);
                            }
                        }
                    }
                    o1.changed = true;
                }
                offspring.Add(o1);
            }
        }
        private IndividualViewModel GetIndividualViewModel(Individual individual, int includeAncestors = 0, bool includeFamilies = false)
        {
            var ind = individual.Clone();
            ind.Facts = _factService.Get(ind.TreeId, f => f.OwnerId == ind.Id && f.OwnerType == EntityType.Individual).ToList();

            var individualViewModel = new IndividualViewModel(ind);

            if (includeAncestors > 0)
            {
                if (individualViewModel.FatherId > 0)
                {
                    individualViewModel.Father = GetIndividualViewModel(_individualService.Get(individualViewModel.FatherId, ind.TreeId), includeAncestors-1);
                }
                if (individualViewModel.MotherId > 0)
                {
                    individualViewModel.Mother = GetIndividualViewModel(_individualService.Get(individualViewModel.MotherId, ind.TreeId), includeAncestors - 1);
                }
            }

            if (includeFamilies)
            {
                individualViewModel.Families = new List<FamilyViewModel>();

                var families = _familyService.Get(ind.TreeId,
                                fam => ind.Sex == Sex.Male ? fam.HusbandId == ind.Id : fam.WifeId == ind.Id);
                foreach (var family in families)
                {
                    individualViewModel.Families.Add(GetFamilyViewModel(family, ind.Sex));
                }
            }

            individualViewModel.Facts = new List<FactViewModel>();
            foreach (var fact in ind.Facts)
            {
                individualViewModel.Facts.Add(new FactViewModel(fact));
            }

            if (ind.ImageId == -1)
            {
                individualViewModel.ImageUrl = (ind.Sex == Sex.Female)
                                                    ? "DesktopModules/FTP/FamilyTreeProject/Images/female.png" 
                                                    : "DesktopModules/FTP/FamilyTreeProject/Images/male.png";
            }
            else
            {
                var file = FileManager.Instance.GetFile(ind.ImageId);
                individualViewModel.ImageUrl = (file.PortalId == -1)
                                            ? Globals.HostPath + file.RelativePath
                                            : PortalSettings.HomeDirectory + file.RelativePath;
            }

            return individualViewModel;
        }
示例#16
0
        public static Generation Initial(Individual sample, int size)
        {
            Individual[] initial = new Individual[size];

            Parallel.For(0, size, i =>
            {
                Individual n = (Individual)sample.Clone();
                n.RandomInitialization();
                initial[i] = n;
            });

            return(new Generation(initial, 1));
        }
示例#17
0
    public override void Crossover(Individual partner, float probability)
    {
        //Implementar
        GeneticIndividual tmp = (GeneticIndividual)partner.Clone();

        if (Random.Range(0.0f, 1.0f) < probability)
        {
            for (int i = 0; i < totalSize / 2; i++)
            {
                genotype[i] = tmp.genotype[i];
            }
        }
    }
示例#18
0
        /// <summary>
        /// Operator's operate method.
        /// </summary>
        /// <param name="parents">parents</param>
        /// <param name="offspring">offspring</param>
        public void Operate(Population parents, Population offspring)
        {
            int size = parents.GetPopulationSize();

            for (int i = 0; i < size / 2; i++)
            {
                Individual p1 = parents.Get(2 * i);
                Individual p2 = parents.Get(2 * i + 1);

                Individual o1 = (Individual)p1.Clone();
                Individual o2 = (Individual)p2.Clone();

                if (rng.NextDouble() < xOverProb)
                {
                    HashSet <int> indices = new HashSet <int>();
                    bool          flipper = true;

                    // select crossover points
                    while (indices.Count < numberOfPoints)
                    {
                        indices.Add(rng.NextInt(p1.Length()));
                    }

                    // perform the crossover
                    for (int j = 0; j < p1.Length(); j++)
                    {
                        if (indices.Contains(j))
                        {
                            flipper = flipper == true ? false : true;
                        }

                        if (flipper)
                        {
                            o1.SetActivityOnEdge(j, p1.IsActiveOnEdge(j));
                            o2.SetActivityOnEdge(j, p2.IsActiveOnEdge(j));
                        }
                        else
                        {
                            o1.SetActivityOnEdge(j, p2.IsActiveOnEdge(j));
                            o2.SetActivityOnEdge(j, p1.IsActiveOnEdge(j));
                        }
                    }
                    o1.changed = true;
                    o2.changed = true;
                }
                offspring.Add(o1);
                offspring.Add(o2);
            }
        }
示例#19
0
        public ParetoFrontMetricsTests()
        {
            // Set up multi-objective population

            moTestInd = ObjectCreators.GetIndividual(new double[] { 0, 2 });
            moTestInd.SendForEvaluation();

            var solution1Name = ObjectCreators.Solution_Key;
            var solution2Name = ObjectCreators.Solution_Key + "2";
            var solution3Name = ObjectCreators.Solution_Key + "3";

            moTestInd.SetProperty(solution1Name, WorstSolution1 - 0.01); // 3
            moTestInd.SetProperty(solution2Name, WorstSolution2 - 0.18); // 2
            moTestInd.SetProperty(solution3Name, WorstSolution3 - 0.1);  // 1

            indParetoEqual1 = moTestInd.Clone();
            indParetoEqual2 = moTestInd.Clone();
            indParetoEqual3 = moTestInd.Clone();

            indParetoEqual1.SetProperty(solution1Name, WorstSolution1 - 0.1);  // 1
            indParetoEqual1.SetProperty(solution2Name, WorstSolution2);        // 4
            indParetoEqual1.SetProperty(solution3Name, WorstSolution3 - 0.09); // 2
            indParetoEqual2.SetProperty(solution1Name, WorstSolution1 - 0.09); // 2
            indParetoEqual2.SetProperty(solution2Name, WorstSolution2 - 0.02); // 3
            indParetoEqual2.SetProperty(solution3Name, WorstSolution3 - 0.01); // 3
            indParetoEqual3.SetProperty(solution1Name, WorstSolution1);        // 4
            indParetoEqual3.SetProperty(solution2Name, WorstSolution2 - 0.2);  // 1
            indParetoEqual3.SetProperty(solution3Name, WorstSolution3);        // 4

            minimise = new[] { true, true, true };

            moTestInd.SetSolution(solution1Name, solution2Name, solution3Name);
            indParetoEqual1.SetSolution(solution1Name, solution2Name, solution3Name);
            indParetoEqual2.SetSolution(solution1Name, solution2Name, solution3Name);
            indParetoEqual3.SetSolution(solution1Name, solution2Name, solution3Name);
        }
示例#20
0
    private static void AdvanceGeneration()
    {
        Individual[] nextPopulation    = new Individual[Config.nIndividualsPerPopulation];
        Individual[] orderedPopulation = FitnessHelper.GetOrderedPopulation(population);

        AddElite(nextPopulation, orderedPopulation);
        AddChildren(nextPopulation, population);

        Debug.Log("population " + generationsFinished);
        PopulationLogger.AddPopulation(orderedPopulation, generationsFinished);

        generationsFinished++;
        individualsFinished = 0;
        population          = (Individual[])nextPopulation.Clone();
        StartIndividual(0);
    }
示例#21
0
    public Individual tournamentSelection(List <Individual> population, int tournamentSize)
    {
        Individual best = null;

        for (int i = 0; i < tournamentSize; i++)
        {
            Individual ind = population[(int)Random.Range(0, population.Count)]; // escolho um individuo aleatorio da população

            if (best == null || ind.Fitness > best.Fitness)                      // se ainda não tiver avaliações ou se a fitness do individuo for melhor que a melhor avaliação
            {
                best = ind.Clone();                                              // reproduzo o individuo
            }
        }

        return(best);
    }
示例#22
0
        public Individual Evaluate(Individual individual)
        {
            var rng = new Random();

            var firstIndex  = rng.Next(individual.Towns.Count);
            var secondIndex = rng.Next(individual.Towns.Count);

            var clone = (Individual)individual.Clone();

            var temp = clone.Towns[firstIndex];

            clone.Towns[firstIndex]  = clone.Towns[secondIndex];
            clone.Towns[secondIndex] = temp;

            return(clone);
        }
    public Individual tournamentSelection(List <Individual> population, int tournamentSize)
    {
        //* YOUR CODE HERE *//
        Individual best = null;

        for (int i = 0; i < tournamentSize; i++)
        {
            Individual ind = population[RandomInteger(0, population.Count - 1)];

            if (best == null || ind.Fitness > best.Fitness)
            {
                best = ind.Clone();
            }
        }

        return(best);
    }
示例#24
0
    List <Individual> randomSelection(List <Individual> oldpop, int num)
    {
        List <Individual> selectedInds = new List <Individual> ();
        int popsize = oldpop.Count;

        for (int i = 0; i < num; i++)
        {
            //make sure selected individuals are different
            Individual ind = oldpop [Random.Range(0, popsize)];
            while (selectedInds.Contains(ind))
            {
                ind = oldpop [Random.Range(0, popsize)];
            }
            selectedInds.Add(ind.Clone());              //we return copies of the selected individuals
        }

        return(selectedInds);
    }
示例#25
0
        private Individual GenerateOffspring()
        {
            var rnd = new Random();

            // base offspring on previous generation
            // so it essentially evolves towards optimal
            var child = Individual.Clone(Child);

            // crossbreed
            Crossbreed(child);

            // mutate - chance < 7%
            if (rnd.Next(0, 100) < 7)
            {
                Mutate(child);
            }

            return(Child = child);
        }
示例#26
0
        /// <summary>
        /// Operator operate method
        /// </summary>
        /// <param name="parents">parents</param>
        /// <param name="offspring">offspring</param>
        public void Operate(Population parents, Population offspring)
        {
            int size = parents.GetPopulationSize();

            for (int i = 0; i < size; i++)
            {
                Individual p1 = parents.Get(i);
                Individual o1 = (Individual)p1.Clone();

                if (rng.NextDouble() < mutationProbability)
                {
                    int length = p1.Length();

                    byte activity;

                    foreach (Edge edge in Program.graph.GetEdges())
                    {
                        if (rng.NextDouble() < bitFlipProbability)
                        {
                            // swap values
                            activity = p1.IsActiveOnEdge(edge.ID);
                            if (Settings.task != "eds")
                            {
                                activity = (byte)(activity > 0 ? 0 : 1);
                            }
                            // if doing eds, dont just swap, but choose random colour
                            else
                            {
                                activity = (byte)rng.NextInt(1, Settings.maxColours + 1);
                            }
                            o1.SetActivityOnEdge(edge.ID, activity);
                            o1.changed = true;
                        }
                    }
                }
                offspring.Add(o1);
            }
        }
示例#27
0
        public void ClonedIndividuals_AreEqualButNotTheSame()
        {
            var ind1 = ind.Clone();

            // Currently equal
            Assert.Equal(ind1, ind);

            // Change some properties
            var fitness = 0.2;

            ind1.SendForEvaluation();
            ind1.SetProperty(Cloning_Key, 1.2);
            ind1.SetProperty(ObjectCreators.Solution_Key, fitness);
            ind1.SetProperty("sol2", 5.1);
            ind1.SetProperty("sol3", 55.0);
            ind1.SetSolution(ObjectCreators.Solution_Key, "sol2", "sol3");
            ind1.SetFitness(fitness);

            // Now not equal
            Assert.Throws <System.ArgumentOutOfRangeException>(
                () => ind.GetProperty <double>(Cloning_Key));
            Assert.NotEqual(ind.SolutionVector, ind1.SolutionVector);
            Assert.NotEqual(ind.Fitness, ind1.Fitness);
        }
        private void generateZad2_Click(object sender, EventArgs e)
        {
            List <List <Individual> > generationList = new List <List <Individual> >();
            List <Individual>         individuals;
            List <Individual>         individualsSelect;
            List <double>             avg = new List <double>();
            Individual    masterElite     = null;
            List <double> pkTest          = new List <double>
            {
                0.5, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90
            };
            List <double> pmTest = new List <double>
            {
                0.0001, 0.0005, 0.001, 0.0015, 0.002, 0.0025, 0.003, 0.0035, 0.004, 0.0045, 0.005, 0.01
            };
            List <Generation> listTest = new List <Generation>();

            double     a         = 0;
            double     b         = 0;
            int        n         = 0;
            double     d         = 0;
            double     precision = 1;
            double     pk        = 0.0;
            double     pm        = 0.0;
            int        t         = 0;
            int        test      = 0;
            Individual elite     = null;



            a    = Convert.ToDouble(ABox.Text);
            b    = Convert.ToDouble(BBox.Text);
            d    = Convert.ToInt32(DBox.Text);
            test = Convert.ToInt32(testBox.Text);

            if (a > b)
            {
                throw new Exception();
            }

            double pom   = d;
            int    round = 0;

            while (pom > 1)
            {
                precision /= 10;
                round++;
                pom *= 0.1;
            }
            int l = (int)Math.Ceiling(Math.Log(((b - a) * d) + 1, 2));

            BitCountBox.Text  = l.ToString();
            individuals       = new List <Individual>();
            individualsSelect = new List <Individual>();
            Random generator = new Random();

            for (n = 30; n <= 80; n += 5)
            {
                foreach (var pmItem in pmTest)
                {
                    pm = pmItem;

                    foreach (var pkItem in pkTest)
                    {
                        pk = pkItem;

                        for (t = 50; t <= 150; t += 10)
                        {
                            for (int s = 0; s < test; s++)
                            {
                                for (int i = 0; i < n; i++)
                                {
                                    Individual individual = new Individual
                                    {
                                        Id    = i,
                                        Xreal = generator.Next((int)(a * d), (int)(b * d)) / d
                                    };

                                    individual.Xint = (int)Math.Round(((1 / (b - a)) * (individual.Xreal - a) * (Math.Pow(2, l) - 1)));

                                    string bin = Convert.ToString(individual.Xint, 2);
                                    for (int k = bin.Length; k < l; k++)
                                    {
                                        bin = "0" + bin;
                                    }
                                    individual.Xbit = bin;
                                    double x = individual.Xreal;
                                    individual.Fx = x % 1 * (Math.Cos(20 * Math.PI * x) - Math.Sin(x));

                                    individuals.Add(individual);
                                }

                                if (checkElite.Checked)
                                {
                                    elite = individuals.Find(i => i.Fx == individuals.Max(ind => ind.Fx)).Clone();
                                }

                                generationList.Add(individuals);

                                //petla do pokolen
                                for (int j = 0; j < t; j++)
                                {
                                    var fmin = individuals.Min(i => i.Fx);

                                    foreach (var i in individuals)
                                    {
                                        i.Gx = i.Fx - fmin + precision;
                                    }

                                    var SumGx = individuals.Sum(i => i.Gx);

                                    foreach (var i in individuals)
                                    {
                                        i.Px = i.Gx / SumGx;
                                    }


                                    int index = 0;
                                    foreach (var ind in individuals)
                                    {
                                        for (int i = 0; i <= index; i++)
                                        {
                                            ind.Qx += individuals[i].Px;
                                        }
                                        index++;
                                        ind.R = generator.NextDouble();
                                    }



                                    int it = 0;
                                    foreach (var i in individuals)
                                    {
                                        it++;
                                        foreach (var ind in individuals)
                                        {
                                            if (i.R <= ind.Qx)
                                            {
                                                individualsSelect.Add(ind.Clone());
                                                break;
                                            }
                                        }
                                    }

                                    foreach (var i in individualsSelect)
                                    {
                                        if (generator.NextDouble() <= pk)
                                        {
                                            i.Parent = i.Xbit;
                                        }
                                        else
                                        {
                                            i.Parent = "--";
                                            i.Ppk    = i.Xbit;
                                        }
                                    }


                                    List <Individual> parents = new List <Individual>();

                                    foreach (var i in individualsSelect)
                                    {
                                        if (!i.Parent.Equals("--"))
                                        {
                                            parents.Add(i);
                                        }
                                    }

                                    if (parents.Count > 1)
                                    {
                                        for (int i = 0; i < parents.Count - 1; i = i + 2)
                                        {
                                            int pc = parents[i].Pc = parents[i + 1].Pc = generator.Next(1, l);
                                            parents[i].Ppk     = parents[i].ChildXbin = parents[i].Parent.Substring(0, pc) + parents[i + 1].Parent.Substring(pc, l - pc);
                                            parents[i + 1].Ppk = parents[i + 1].ChildXbin = parents[i + 1].Parent.Substring(0, pc) + parents[i].Parent.Substring(pc, l - pc);
                                        }
                                        if (parents.Count % 2 != 0)
                                        {
                                            int pc = parents[parents.Count - 1].Pc = generator.Next(1, l);
                                            parents[parents.Count - 1].Ppk = parents[parents.Count - 1].ChildXbin = String.Concat(parents[parents.Count - 1].Parent.Substring(0, pc) + parents[0].Parent.Substring(pc, l - pc));
                                        }
                                    }
                                    else
                                    {
                                        foreach (var i in parents)
                                        {
                                            i.Ppk = i.Parent;
                                        }
                                    }

                                    StringBuilder strBuilder = new StringBuilder();
                                    foreach (var ind in individualsSelect)
                                    {
                                        ind.Pm     = ind.Ppk;
                                        strBuilder = new StringBuilder(ind.Pm);;
                                        for (int i = 0; i < ind.Pm.Length; i++)
                                        {
                                            if (generator.NextDouble() <= pm)
                                            {
                                                strBuilder[i] = strBuilder[i].Equals('0') ? '1' : '0';
                                                ind.Zg       += i + 1 + ",";
                                            }
                                        }
                                        ind.Pm    = strBuilder.ToString();
                                        ind.Xbit  = ind.Pm;
                                        ind.Xint  = int.Parse(Convert.ToString(Convert.ToInt32(ind.Pm + "", 2), 10));
                                        ind.Xreal = Math.Round(a + ((b - a) * ind.Xint) / (Math.Pow(2, l) - 1), round);
                                        double x = ind.Xreal;
                                        ind.Fx = x % 1 * (Math.Cos(20 * Math.PI * x) - Math.Sin(x));
                                    }

                                    if (checkElite.Checked)
                                    {
                                        if (individualsSelect.All(ind => ind.Fx != elite.Fx))
                                        {
                                            int        randomId  = generator.Next(0, individualsSelect.Count);
                                            Individual randomInd = individualsSelect[randomId];
                                            if (randomInd.Fx < elite.Fx)
                                            {
                                                individualsSelect[randomId] = elite.Clone();
                                            }
                                        }
                                        double maxFx = individualsSelect.Max(ind => ind.Fx);
                                        if (maxFx > elite.Fx)
                                        {
                                            elite = individualsSelect.Find(i => i.Fx == maxFx).Clone();
                                        }
                                    }


                                    List <Individual> genToAdd = individualsSelect.ConvertAll(ind => ind.Clone());
                                    generationList.Add(genToAdd);
                                    individuals = individualsSelect.ConvertAll(ind => ind.Clone());
                                    individualsSelect.Clear();
                                }


                                if (masterElite == null)
                                {
                                    masterElite = elite;
                                }
                                else if (elite.Fx > masterElite.Fx)
                                {
                                    masterElite = elite;
                                }
                                avg.Add(generationList.Last().Average(ind => ind.Fx));

                                generationList.Clear();
                                individuals.Clear();
                                individualsSelect.Clear();
                            }
                            Generation gen = new Generation
                            {
                                T    = t,
                                N    = n,
                                Pk   = pk,
                                Pm   = pm,
                                Fmax = masterElite.Fx,
                                Favg = avg.Average(av => av)
                            };

                            avg.Clear();
                            listTest.Add(gen);
                        }
                    }
                }
            }
            listTest.Sort(delegate(Generation x, Generation y)
            {
                return(y.Pk.CompareTo(x.Pk));
            });
            listTest.Sort(delegate(Generation x, Generation y)
            {
                return(y.Pm.CompareTo(x.Pm));
            });
            listTest.Sort(delegate(Generation x, Generation y)
            {
                return(y.T.CompareTo(x.T));
            });
            listTest.Sort(delegate(Generation x, Generation y)
            {
                return(y.N.CompareTo(x.N));
            });
            listTest.Sort(delegate(Generation x, Generation y)
            {
                return(y.N.CompareTo(x.N));
            });
            listTest.Sort(delegate(Generation x, Generation y)
            {
                return(y.Fmax.CompareTo(x.Fmax));
            });
            listTest.Sort(delegate(Generation x, Generation y)
            {
                return(y.Favg.CompareTo(x.Favg));
            });


            var bindingList = new BindingList <Generation>(listTest);
            var source      = new BindingSource(bindingList, null);

            zad2Table.DataSource = source;
        }
        private void ObliczButton_Click(object sender, EventArgs e)
        {
            double     a         = 0;
            double     b         = 0;
            int        n         = 0;
            double     d         = 0;
            double     precision = 1;
            double     pk        = 0.0;
            double     pm        = 0.0;
            int        t         = 0;
            Individual elite     = null;



            a  = Convert.ToDouble(ABox.Text);
            b  = Convert.ToDouble(BBox.Text);
            n  = Convert.ToInt32(CountBox.Text);
            d  = Convert.ToInt32(DBox.Text);
            pk = Convert.ToDouble(pkBox.Text);
            pm = Convert.ToDouble(pmBox.Text);
            t  = Convert.ToInt32(tBox.Text);

            if (a > b)
            {
                throw new Exception();
            }

            double pom   = d;
            int    round = 0;

            while (pom > 1)
            {
                precision /= 10;
                round++;
                pom *= 0.1;
            }

            int l = (int)Math.Ceiling(Math.Log(((b - a) * d) + 1, 2));

            BitCountBox.Text  = l.ToString();
            individuals       = new List <Individual>();
            individualsSelect = new List <Individual>();
            Random generator = new Random();

            for (int i = 0; i < n; i++)
            {
                Individual individual = new Individual
                {
                    Id    = i,
                    Xreal = generator.Next((int)(a * d), (int)(b * d)) / d
                };

                individual.Xint = (int)Math.Round(((1 / (b - a)) * (individual.Xreal - a) * (Math.Pow(2, l) - 1)));

                string bin = Convert.ToString(individual.Xint, 2);
                for (int k = bin.Length; k < l; k++)
                {
                    bin = "0" + bin;
                }
                individual.Xbit = bin;
                double x = individual.Xreal;
                individual.Fx = x % 1 * (Math.Cos(20 * Math.PI * x) - Math.Sin(x));

                individuals.Add(individual);
            }
            if (checkElite.Checked)
            {
                elite = individuals.Find(i => i.Fx == individuals.Max(ind => ind.Fx)).Clone();
            }


            generationList.Add(individuals);

            //petla do pokolen
            for (int j = 0; j < t; j++)
            {
                var fmin = individuals.Min(i => i.Fx);

                foreach (var i in individuals)
                {
                    i.Gx = i.Fx - fmin + precision;
                }

                var SumGx = individuals.Sum(i => i.Gx);

                foreach (var i in individuals)
                {
                    i.Px = i.Gx / SumGx;
                }


                int index = 0;
                foreach (var ind in individuals)
                {
                    for (int i = 0; i <= index; i++)
                    {
                        ind.Qx += individuals[i].Px;
                    }
                    index++;
                    ind.R = generator.NextDouble();
                }



                int it = 0;
                foreach (var i in individuals)
                {
                    it++;
                    foreach (var ind in individuals)
                    {
                        if (i.R <= ind.Qx)
                        {
                            individualsSelect.Add(ind.Clone());
                            break;
                        }
                    }
                }

                foreach (var i in individualsSelect)
                {
                    if (generator.NextDouble() <= pk)
                    {
                        i.Parent = i.Xbit;
                    }
                    else
                    {
                        i.Parent = "--";
                        i.Ppk    = i.Xbit;
                    }
                }


                List <Individual> parents = new List <Individual>();

                foreach (var i in individualsSelect)
                {
                    if (!i.Parent.Equals("--"))
                    {
                        parents.Add(i);
                    }
                }

                if (parents.Count > 1)
                {
                    for (int i = 0; i < parents.Count - 1; i = i + 2)
                    {
                        int pc = parents[i].Pc = parents[i + 1].Pc = generator.Next(1, l);
                        parents[i].Ppk     = parents[i].ChildXbin = parents[i].Parent.Substring(0, pc) + parents[i + 1].Parent.Substring(pc, l - pc);
                        parents[i + 1].Ppk = parents[i + 1].ChildXbin = parents[i + 1].Parent.Substring(0, pc) + parents[i].Parent.Substring(pc, l - pc);
                    }
                    if (parents.Count % 2 != 0)
                    {
                        int pc = parents[parents.Count - 1].Pc = generator.Next(1, l);
                        parents[parents.Count - 1].Ppk = parents[parents.Count - 1].ChildXbin = String.Concat(parents[parents.Count - 1].Parent.Substring(0, pc) + parents[0].Parent.Substring(pc, l - pc));
                    }
                }
                else
                {
                    foreach (var i in parents)
                    {
                        i.Ppk = i.Parent;
                    }
                }

                StringBuilder strBuilder = new StringBuilder();
                foreach (var ind in individualsSelect)
                {
                    ind.Pm     = ind.Ppk;
                    strBuilder = new StringBuilder(ind.Pm);;
                    for (int i = 0; i < ind.Pm.Length; i++)
                    {
                        if (generator.NextDouble() <= pm)
                        {
                            strBuilder[i] = strBuilder[i].Equals('0') ? '1' : '0';
                            ind.Zg       += i + 1 + ",";
                        }
                    }
                    ind.Pm    = strBuilder.ToString();
                    ind.Xbit  = ind.Pm;
                    ind.Xint  = int.Parse(Convert.ToString(Convert.ToInt32(ind.Pm + "", 2), 10));
                    ind.Xreal = Math.Round(a + ((b - a) * ind.Xint) / (Math.Pow(2, l) - 1), round);
                    double x = ind.Xreal;
                    ind.Fx = x % 1 * (Math.Cos(20 * Math.PI * x) - Math.Sin(x));
                }

                if (checkElite.Checked)
                {
                    if (individualsSelect.All(ind => ind.Fx != elite.Fx))
                    {
                        int        randomId  = generator.Next(0, individualsSelect.Count);
                        Individual randomInd = individualsSelect[randomId];
                        if (randomInd.Fx < elite.Fx)
                        {
                            individualsSelect[randomId] = elite.Clone();
                        }
                    }
                    double maxFx = individualsSelect.Max(ind => ind.Fx);
                    if (maxFx > elite.Fx)
                    {
                        elite = individualsSelect.Find(i => i.Fx == maxFx).Clone();
                    }
                }


                List <Individual> genToAdd = individualsSelect.ConvertAll(ind => ind.Clone());
                generationList.Add(genToAdd);
                individuals = individualsSelect.ConvertAll(ind => ind.Clone());
                individualsSelect.Clear();
            }

            List <Individual> individualsToPersent = new List <Individual>();

            int endIndex = 0;

            foreach (var ind in individuals)
            {
                if (!individualsToPersent.Any(i => i.Fx == ind.Fx))
                {
                    double indCount = individuals.Where(i => i.Fx == ind.Fx).Count();
                    double persent  = (indCount / individuals.Count) * 100;
                    ind.Persent = persent + "%";
                    ind.Id      = endIndex;
                    individualsToPersent.Add(ind);
                    endIndex++;
                }
            }


            Methods.WriteToFile(generationList, n, t, pm, pk, precision);
            Methods.WriteToFileFx(generationList, n, t, pm, pk, precision);
            MakeChart(generationList);

            var bindingList = new BindingList <Individual>(individualsToPersent);
            var source      = new BindingSource(bindingList, null);

            TableView.DataSource = source;
            generationList.Clear();
            individuals.Clear();
            individualsSelect.Clear();
        }
示例#30
0
        public void Evaluate(IEvolutionState state,
                             Individual ind,
                             int subpopulation,
                             int threadnum)
        {
            if (ind.Evaluated && !ReevaluateIndividuals)
            {
                return;
            }

            var fits = new ArrayList();

            Individual bestOfRuns = null;

            for (int run = 0; run < Runs; run++)
            {
                // too annoying
                //state.Output.message("Thread " + threadnum + " Run " + run);
                try
                {
                    // The following uses BinaryFormatter to create a separate copy of the ParameterDatabase.
                    CurrentDatabase = (ParameterDatabase)p_database.DeepClone();
                }
                catch (Exception e)
                {
                    state.Output.Fatal("Exception copying database.\n" + e);
                }
                ModifyParameters(state, CurrentDatabase, run, ind);

                var output = new Output(false); // do not store messages, just print them
                output.AddLog(Log.D_STDOUT, false);
                output.AddLog(Log.D_STDERR, true);
                output.ThrowsErrors = true; // don't do System.exit(1);

                EvolutionState evaluatedState = null;
                try
                {
                    evaluatedState = Evolve.Initialize(CurrentDatabase, 0, output);

                    // should we override the seeds?
                    if (SetRandom)
                    {
                        // we use the random number generator to seed the generators
                        // of the underlying process.  This isn't optimal but it should
                        // probably do okay.  To be extra careful we prime the generators.

                        for (int i = 0; i < evaluatedState.Random.Length; i++)
                        {
                            int seed = state.Random[threadnum].NextInt();
                            evaluatedState.Random[i] = Evolve.PrimeGenerator(new MersenneTwisterFast(seed));
                        }
                    }

                    evaluatedState.Run(EvolutionState.C_STARTED_FRESH);

                    // Issue a warning if there's more than one subpopulation
                    if (evaluatedState.Population.Subpops.Count > 1)
                    {
                        state.Output.WarnOnce(
                            "MetaProblem used, but underlying evolution state has more than one subpopulation: only the results from subpopulation 0 will be considered.");
                    }


                    // Identify the best fitness of the underlying EvolutionState run,

                    // we can only easily detect if the underlying EvolutionState has a proper Statistics
                    // object we can use AFTER we've run it because the Statistics object is set up during
                    // run().  We could modify this but I'm too lazy to do so, so...

                    Individual[] inds = null; // will get set, don't worry
                    if (evaluatedState.Statistics != null &&
                        (evaluatedState.Statistics is SimpleStatistics ||
                         evaluatedState.Statistics is SimpleShortStatistics))
                    {
                        inds = null;

                        // obviously we need an interface here rather than this nonsense
                        if (evaluatedState.Statistics is SimpleStatistics)
                        {
                            inds = ((SimpleStatistics)evaluatedState.Statistics).GetBestSoFar();
                        }
                        else
                        {
                            inds = ((SimpleShortStatistics)evaluatedState.Statistics).GetBestSoFar();
                        }
                        if (inds == null)
                        {
                            state.Output.Fatal(
                                "Underlying evolution state has a Statistics object which provides a null best-so-far array.  Can't extract fitness.");
                        }
                        fits.Add((Fitness)(inds[0].Fitness));
                        //System.err.println("" + inds[0] + " " + inds[0].fitness);
                    }
                    else if (evaluatedState.Statistics == null)
                    {
                        state.Output.Fatal(
                            "Underlying evolution state has a null Statistics object.  Can't extract fitness.");
                    }
                    else
                    {
                        state.Output.Fatal(
                            "Underlying evolution state has a Statistics object which doesn't implement ProvidesBestSoFar.  Can't extract fitness.");
                    }


                    // Now we need to suck out the best individual discovered so far.  If the underlying
                    // evoluationary system itself has a MetaProblem, we need to do this recursively.
                    // We presume that the MetaProblem exists in subpopulation 0.

                    if (evaluatedState.Evaluator.p_problem is MetaProblem)
                    {
                        var mp = (MetaProblem)evaluatedState.Evaluator.p_problem;
                        lock (mp.Lock)
                        {
                            Individual bestind = mp.BestUnderlyingIndividual[0];

                            if (bestOfRuns == null || bestind.Fitness.BetterThan(bestOfRuns.Fitness))
                            {
                                bestOfRuns = (Individual)bestind.Clone();
                            }
                        }
                    }
                    // otherwise we grab the best individual found in the underlying evolutionary run,
                    // gathered from the inds array we used earlier.
                    else
                    {
                        // gather the best individual found during the runs
                        if (bestOfRuns == null || inds[0].Fitness.BetterThan(bestOfRuns.Fitness))
                        {
                            bestOfRuns = (Individual)(inds[0].Clone());
                        }
                    }


                    // now clean up
                    Evolve.Cleanup(evaluatedState);
                }
                catch (OutputExitException e)
                {
                    // looks like an error occurred.
                    state.Output.Warning(
                        "Error occurred in underlying evolutionary run.  NOTE: multiple threads may still be running:\n" +
                        e.Message);
                }
                catch (OutOfMemoryException e)
                {
                    // Let's try fixing things
                    evaluatedState = null;
                    //System.gc();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();

                    state.Output.Warning(
                        "An Out of Memory error occurred in underlying evolutionary run.  Attempting to recover and reset.  NOTE: multiple threads may still be running:\n" +
                        e.Message);
                }
            }


            // Load the fitness into our individual
            var fits2 = new IFitness[fits.Count];

            for (var i = 0; i < fits2.Length; i++)
            {
                fits2[i] = (IFitness)fits[i];
            }
            Combine(state, fits2, ind.Fitness);
            ind.Evaluated = true;

            // store the best individual found during the runs if it's superior.
            // We need to do a lock here, which is rare in ECJ.  This is because the
            // bestUnderlyingIndividual array is shared among MetaProblem instances
            lock (Lock)
            {
                if (bestOfRuns != null &&
                    (BestUnderlyingIndividual[subpopulation] == null ||
                     bestOfRuns.Fitness.BetterThan(BestUnderlyingIndividual[subpopulation].Fitness)))
                {
                    BestUnderlyingIndividual[subpopulation] = bestOfRuns; // no clone necessary
                }
            }
        }
示例#31
0
        private void testStabilityButton_Click(object sender, EventArgs e)
        {
            double a         = Convert.ToDouble(aBox.Text);
            double b         = Convert.ToDouble(bBox.Text);
            double d         = Convert.ToDouble(dBox.Text);
            double T         = Convert.ToDouble(testTBox.Text);
            double tau       = Convert.ToDouble(testTauBox.Text);
            Random generator = new Random();
            int    round     = 0;
            int    l         = (int)Math.Ceiling(Math.Log(((b - a) * (1 / d)) + 1, 2));


            List <Individual> VbestList   = new List <Individual>();
            List <Generation> genList     = new List <Generation>();
            List <Individual> individuals = null;
            Individual        Vbest;
            double            pom = d;

            while (pom < 1)
            {
                round++;
                pom *= 10;
            }

            for (int j = 0; j < 100; j++)
            {
                Individual individual = Geo.MakeFirstInd(a, b, d, l, generator);
                Vbest = individual.Clone();

                for (int i = 0; i < T; i++)
                {
                    individuals = Geo.MakePopulation(individual, a, b, l, round);

                    Geo.CountProbability(individuals, tau);

                    Geo.MutateInd(individual, individuals, a, b, l, round, generator);

                    if (Vbest.Fx < individual.Fx)
                    {
                        Vbest = individual.Clone();
                    }

                    individuals.Clear();
                }

                VbestList.Add(Vbest.Clone());
            }


            var       chartMaker = testChart.ChartAreas[0];
            ChartArea CA         = testChart.ChartAreas[0];

            CA.AxisX.ScaleView.Zoomable                   = true;
            chartMaker.AxisX.LabelStyle.Format            = "";
            chartMaker.AxisY.LabelStyle.Format            = "";
            chartMaker.AxisX.LabelStyle.IsEndLabelVisible = true;
            chartMaker.AxisY.Minimum  = 1.5;
            chartMaker.AxisX.Minimum  = 0;
            chartMaker.AxisX.Maximum  = VbestList.Count;
            chartMaker.AxisY.Interval = 0.1;
            chartMaker.AxisX.Interval = 2;

            testChart.Series[0].IsVisibleInLegend = false;

            if (testChart.Series.Count == 1)
            {
                testChart.Series.Add("Vb");
            }
            else
            {
                testChart.Series["Vb"].Points.Clear();
            }

            testChart.Series["Vb"].ChartType   = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            testChart.Series["Vb"].Color       = Color.Green;
            testChart.Series["Vb"].BorderWidth = 1;

            for (int i = 0; i < VbestList.Count; i++)
            {
                testChart.Series["Vb"].Points.AddXY(i, VbestList[i].Fx);
            }
        }