public void AddIntersection(GeneticIndividual first, GeneticIndividual second, TicTacToeContext context)
        {
            var newIndividual = new GeneticIndividual
            {
                GenerationNumber = first.GenerationNumber,
                ImportanceOrder  = 7,
                PlayedGames      = 0,
                Score            = 0,
            };

            context.Set <GeneticIndividual>().Add(newIndividual);
            context.SaveChanges();

            var firstFactors =
                context.Set <GeneticFactor>()
                .Where(factor => factor.GeneticIndividualId == first.GeneticIndividualId)
                .ToList();

            var secondFactors =
                context.Set <GeneticFactor>()
                .Where(factor => factor.GeneticIndividualId == second.GeneticIndividualId)
                .ToList();

            var newFactors = (from firstFactor in firstFactors
                              join secondFactor in secondFactors on firstFactor.FieldId equals secondFactor.FieldId
                              select new GeneticFactor
            {
                Factor = (firstFactor.Factor + secondFactor.Factor) / 2,
                FieldId = firstFactor.FieldId,
                GeneticIndividualId = newIndividual.GeneticIndividualId
            }).ToList();

            context.Set <GeneticFactor>().AddRange(newFactors);
            context.SaveChanges();
        }
        public void AddNewMember(GeneticIndividual individual, TicTacToeContext context)
        {
            var newIndividual = new GeneticIndividual
            {
                GenerationNumber = individual.GenerationNumber,
                ImportanceOrder  = 10,
                PlayedGames      = 0,
                Score            = 0,
            };

            context.Set <GeneticIndividual>().Add(newIndividual);
            context.SaveChanges();

            var factors =
                context.Set <GeneticFactor>()
                .Where(factor => factor.GeneticIndividualId == individual.GeneticIndividualId)
                .ToList();

            var newFactors = factors.Select(factor => new GeneticFactor
            {
                GeneticIndividualId = newIndividual.GeneticIndividualId,
                Factor  = this.random.Next(0, 100),
                FieldId = factor.FieldId
            }).ToList();

            context.Set <GeneticFactor>().AddRange(newFactors);
            context.SaveChanges();
        }
Beispiel #3
0
    private void SwapGenes(GeneticIndividual partner, int num)
    {
        float aux;

        aux = partner.genotype[num];
        partner.genotype[num] = this.genotype[num];
        this.genotype[num]    = aux;
    }
Beispiel #4
0
            public static GeneticIndividual Crossover(GeneticIndividual a, GeneticIndividual b)
            {
                var ret = new GeneticIndividual(a._recognizer);

                for (var i = 0; i < a.Items.Length; i++)
                {
                    ret.Items[i] = GeneticIndividualItem.Crossover(a.Items[i], b.Items[i]);
                }
                return(ret);
            }
Beispiel #5
0
    public override Individual Clone()
    {
        GeneticIndividual new_ind = new GeneticIndividual(this.topology, this.maxNumberOfEvaluations, this.mutation);

        genotype.CopyTo(new_ind.genotype, 0);
        new_ind.fitness   = this.Fitness;
        new_ind.evaluated = false;

        return(new_ind);
    }
Beispiel #6
0
    public override Individual Clone()
    {
        GeneticIndividual new_ind = new GeneticIndividual(this.topology, this.n_pontos);

        genotype.CopyTo(new_ind.genotype, 0);
        new_ind.fitness   = this.Fitness;
        new_ind.evaluated = false;

        return(new_ind);
    }
Beispiel #7
0
 public override void InitPopulation()
 {
     //You should implement the code to initialize the population here
     population = new List <Individual>();
     while (population.Count < populationSize)
     {
         GeneticIndividual new_ind = new GeneticIndividual(topology);
         new_ind.Initialize();
         population.Add(new_ind);
     }
 }
Beispiel #8
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++;
    }
Beispiel #9
0
 public override void InitPopulation()
 {
     population = new List <Individual>();
     // jncor
     while (population.Count < populationSize)
     {
         GeneticIndividual new_ind = new GeneticIndividual(topology);
         new_ind.Initialize();
         population.Add(new_ind);
     }
 }
 public override void InitPopulation()
 {
     population = new List <Individual>();
     while (population.Count < populationSize)
     {
         GeneticIndividual gene = new GeneticIndividual(topology);
         gene.Initialize();
         population.Add(gene);
     }
     Debug.Log("-------------------------------INITIALIZATION END -------------------------------");
 }
Beispiel #11
0
 public override void InitPopulation()
 {
     //You should implement the code to initialize the population
     //tournmentsize atribuido ja
     this.population = new List <Individual>();
     for (int i = 0; i < populationSize; i++)
     {
         GeneticIndividual a = new GeneticIndividual(this.topology);
         a.Initialize();
         this.population.Add(a);
     }
 }
Beispiel #12
0
    public override void Step()
    {
        List <Individual> new_pop = new List <Individual>();


        updateReport(); //called to get some stats
        if (elitist)
        {
            GeneticIndividual melhor = (GeneticIndividual)overallBest.Clone();
            new_pop.Add(melhor); //coloca o melhor de sempre na populaçao
        }

        while (new_pop.Count < populationSize)
        {
            GeneticIndividual parent1 = (GeneticIndividual)selection.torneio(population, tournamentSize); //torneio
            GeneticIndividual parent2;
            do
            {
                parent2 = (GeneticIndividual)selection.torneio(population, tournamentSize);
            } while (parent1 == parent2);//para que o pai 1 seja diferente do 2

            GeneticIndividual tmp1 = (GeneticIndividual)parent1.Clone();
            GeneticIndividual tmp2 = (GeneticIndividual)parent2.Clone();

            tmp1.Crossover(tmp2, crossoverProbability); // crossover em temporarios
            tmp2.Crossover(tmp1, crossoverProbability);

            GeneticIndividual child1 = tmp1;// apenas para clareza
            GeneticIndividual child2 = tmp2;

            child1.Mutate(mutationProbability);//mutaçoes
            child2.Mutate(mutationProbability);

            new_pop.Add(child1); //adiciona à população os filhos
            new_pop.Add(child2);
        }
        population = new_pop;

        /*
         * float maximum = population[0].Fitness;
         * for(int i = 0; i < population.Count - 1; i++)
         * {
         *  if (population[i].Fitness > maximum)
         *  {
         *      maximum = population[i].Fitness;
         *  }
         * }
         *
         * Debug.Log("Max: " + maximum);
         */

        generation++;//passa para a próxima geração
    }
    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];
            }
        }
    }
Beispiel #14
0
            public static GeneticIndividual Mutation(GeneticIndividual a)
            {
                var ret = new GeneticIndividual(a._recognizer);
                var idx = Random.Next(a._recognizer.DigitsCount);

                for (var i = 0; i < a.Items.Length; i++)
                {
                    ret.Items[i] = i == idx
                        ? GeneticIndividualItem.Mutation(a.Items[i])
                        : a.Items[i];
                }
                return(ret);
            }
Beispiel #15
0
 // Função alterada, original em baixo
 public override void InitPopulation()
 {
     population = new List <Individual>();
     Debug.Log("Estou a inicializar a população no Genetic");
     // jncor
     while (population.Count < populationSize)
     {
         GeneticIndividual new_ind = new GeneticIndividual(topology);
         new_ind.Initialize();
         population.Add(new_ind);
     }
     Debug.Log("População inicializada");
     Debug.Log("Valor" + numeroValoresPreservados);
 }
    public override void InitPopulation()
    {
        maxNumberOfEvaluations = Mathf.Min(maxNumberOfEvaluations, populationSize);
        populationRed          = new List <Individual>();
        populationBlue         = new List <Individual>();

        while (populationRed.Count < populationSize)
        {
            GeneticIndividual new_ind_red = new GeneticIndividual(NNTopology, maxNumberOfEvaluations, mutationMethod)
            {
                Mean  = Mean,
                Stdev = Stdev
            };
            GeneticIndividual new_ind_blue = new GeneticIndividual(NNTopology, maxNumberOfEvaluations, mutationMethod)
            {
                Mean  = Mean,
                Stdev = Stdev
            };

            if (seedPopulationFromFile)
            {
                NeuralNetwork nnRed  = getRedIndividualFromFile();
                NeuralNetwork nnBlue = getBlueIndividualFromFile();
                new_ind_red.Initialize(nnRed);
                new_ind_blue.Initialize(nnBlue);
                //only the first individual is an exact copy. the other are going to suffer mutations
                if (populationRed.Count != 0 && populationBlue.Count != 0)
                {
                    new_ind_red.Mutate(mutationProbabilityRedPopulation);
                    new_ind_blue.Mutate(mutationProbabilityBluePopulation);
                }
            }
            else
            {
                new_ind_red.Initialize();
                new_ind_blue.Initialize();
            }

            populationRed.Add(new_ind_red);
            populationBlue.Add(new_ind_blue);
        }

        switch (selectionMethod)
        {
        case SelectionType.Tournament:
            selection = new TournamentSelection(tournamentSize);
            break;
        }
    }
Beispiel #17
0
    //The Step function assumes that the fitness values of all the individuals in the population have been calculated.
    public override void Step()
    {
        System.Random random = new System.Random();
        //You should implement the code runs in each generation here
        List <Individual> new_pop = new List <Individual>();

        updateReport();

        population.Sort((x, y) => x.Fitness.CompareTo(y.Fitness));
        population.Reverse();

        if (elitist == true)
        {
            for (int i = 0; i < elitistSize; i++)
            {
                new_pop.Add(population[i].Clone());
            }
        }

        if (tournamentSize > 0)
        {
            List <Individual> winners = fitnessSelect.selectIndividuals(population, tournamentSize, tournamentProbability);

            for (int i = new_pop.Count; i < population.Count; i++)
            {
                Individual parent1 = winners[Random.Range(0, winners.Count)];
                winners.Remove(parent1);
                Individual parent2 = winners[Random.Range(0, winners.Count)].Clone();

                parent2.Crossover(parent1, crossoverProbability);
                parent2.Mutate(mutationProbability);

                winners.Add(parent1);

                new_pop.Add(parent2);
            }
        }
        else
        {
            for (int i = new_pop.Count; i < populationSize; i++)
            {
                GeneticIndividual tmp = (GeneticIndividual)overallBest.Clone();
                tmp.Mutate(mutationProbability);
                new_pop.Add(tmp);
            }
        }
        population = new_pop;
        generation++;
    }
Beispiel #18
0
    public void MakeNewPopulation()
    {
        List<GeneticIndividual> newIndividuals = new List<GeneticIndividual>();

        // TODO make the genetic stuff and crossover etc

        // temp, just make a new population
        for (int i = 0 ; i < individuals.Count ; i++)
        {
            GeneticIndividual child = new GeneticIndividual();
            child.SetFromParents(individuals[i], individuals[i]);
            newIndividuals.Add(child);
        }
        individuals.Clear();
        individuals.AddRange(newIndividuals);
    }
Beispiel #19
0
    //The Step function assumes that the fitness values of all the individuals in the population have been calculated.
    public override void Step()
    {
        List <Individual> new_pop      = new List <Individual> ();
        List <Individual> elitist_list = new List <Individual> ();

        if (elitist)
        {
            population.Sort((x, y) => x.Fitness.CompareTo(y.Fitness));
            Debug.Log("P: ");
            for (int i = 0; i < populationSize; i++)
            {
                Debug.Log(population [i].Fitness);
            }
            for (int i = 0; i < n_elitists; i++)
            {
                int pop = populationSize - 1;
                elitist_list.Add(population [pop - i].Clone());
            }
        }

        updateReport();          //called to get some stats
        // fills the rest with mutations of the best !
        for (int i = 0; i < populationSize; i++)
        {
            GeneticIndividual pai  = (GeneticIndividual)Tournament(population, tournamentSize).Clone();
            GeneticIndividual pai2 = (GeneticIndividual)Tournament(population, tournamentSize).Clone();

            pai.Crossover(pai2.Clone(), crossoverProbability, numerocortes);
            pai.Mutate(mutationProbability);
            new_pop.Add(pai.Clone());
        }

        population = new_pop;

        if (elitist)
        {
            for (int i = 0; i < n_elitists; i++)
            {
                Individual pick_to_delete = new_pop [Random.Range(0, populationSize - 1)];
                new_pop.Remove(pick_to_delete);
                new_pop.Add(elitist_list [i].Clone());
            }
        }
        generation++;
    }
Beispiel #20
0
            public void DoIteration()
            {
                int size = Individuals.Count;

                for (var i = 0; i < size; i++)
                {
                    for (var j = 0; j < i; j++)
                    {
                        Individuals.Add(GeneticIndividual.Crossover(Individuals[i], Individuals[j]));
                    }
                    for (var j = 0; j < 100; j++)
                    {
                        Individuals.Add(GeneticIndividual.Mutation(Individuals[i]));
                    }
                }
                Individuals = Individuals
                              .Where(x => !x.IsInvalid())
                              .OrderBy(x => x.Fitness())
                              .Reverse()
                              .Take(MaxSize)
                              .ToList();
            }
        public void AddMutation(GeneticIndividual individual, TicTacToeContext context)
        {
            var newIndividual = new GeneticIndividual
            {
                GenerationNumber = individual.GenerationNumber,
                ImportanceOrder  = 4,
                PlayedGames      = 0,
                Score            = 0,
            };

            context.Set <GeneticIndividual>().Add(newIndividual);
            context.SaveChanges();

            var factors =
                context.Set <GeneticFactor>()
                .Where(factor => factor.GeneticIndividualId == individual.GeneticIndividualId)
                .ToList();

            var newFactors = factors.Select(factor => new GeneticFactor
            {
                GeneticIndividualId = newIndividual.GeneticIndividualId,
                Factor = this.winFactors.ContainsKey(factor.FieldId)
                                                                        ? factor.Factor + this.winFactors[factor.FieldId] * 5
                                                                        : factor.Factor + this.random.Next(11) - 5,
                FieldId = factor.FieldId
            })
                             .Select(factor => new GeneticFactor
            {
                GeneticIndividualId = factor.GeneticIndividualId,
                Factor  = factor.Factor > 100 ? 100 : factor.Factor < 0 ? 0 : factor.Factor,
                FieldId = factor.FieldId
            }).ToList();

            context.Set <GeneticFactor>().AddRange(newFactors);
            context.SaveChanges();
        }
Beispiel #22
0
            public GeneticPopolation(CaptchaRecognizer recognizer, int maxSize)
            {
                _recognizer = recognizer;
                MaxSize     = maxSize;
                var consecutiveInvalidCount = 0;

                while (Individuals.Count < MaxSize)
                {
                    var nxt = GeneticIndividual.Mutation(new GeneticIndividual(_recognizer, true));
                    if (!nxt.IsInvalid())
                    {
                        consecutiveInvalidCount = 0;
                        Individuals.Add(nxt);
                    }
                    else
                    {
                        consecutiveInvalidCount++;
                        if (consecutiveInvalidCount > MaxConsecutiveFailures)
                        {
                            throw new CantSplitDigitsException();
                        }
                    }
                }
            }
Beispiel #23
0
 public void SetFromParents(GeneticIndividual a, GeneticIndividual b)
 {
     // todo
     fitnessHACK = (a.GetFitness() + b.GetFitness()) / 2;
 }