Example #1
0
 private bool ParentAlreadySelected(IGenotype candidate, IEnumerable <IGenotype> parents)
 {
     return(parents
            .Any(parent => parent != null &&
                 (candidate == parent || candidate is null || candidate.SimilarityCheck(parent) > IncestLimit)
                 ));
 }
Example #2
0
        protected override IPhenotype CreatePhenotype(IGenotype genotype)
        {
            var configGeno = genotype as ConfigGenotype;
            var targetEA   = CreateTargetEA(configGeno, CreateRandomNumberGenerator());

            return(new ConfigPhenotype(configGeno, TargetEA_FitnessRuns, targetEA));
        }
 public TPhenotype Make(IGenotype genotype)
 {
     return(new()
     {
         Genotype = genotype
     });
 }
Example #4
0
        public override IGenotype CrossoverWith(IGenotype other, CrossoverType crossover, IRandomNumberGenerator random)
        {
            var newgeno = new StringGenotype(null);
            var og      = other as StringGenotype;

            switch (crossover)
            {
            case CrossoverType.Uniform:
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < Math.Min(str.Length, og.str.Length); i++)
                {
                    sb.Append(random.NextBool() ? str[i] : og.str[i]);
                }
                newgeno.str = sb.ToString();
                break;

            case CrossoverType.OnePoint:
                var point = random.Next(Math.Min(str.Length, og.str.Length));
                newgeno.str = str.Substring(0, point) + og.str.Substring(point);
                break;

            default: throw new NotImplementedException(crossover.ToString());
            }
            return(newgeno);
        }
 public CollectivePhenotype <T> Make(IGenotype genotype)
 {
     return(new()
     {
         Genotype = genotype
     });
 }
Example #6
0
        public override double SimilarityCheck(IGenotype other)
        {
            double sum = 0;
            var    otherCombinatoryGenotype = other as CombinatoryGenotype;

            if (otherCombinatoryGenotype == null)
            {
                return(0);
            }

            for (var testedValue = 0; testedValue < Count; testedValue++)
            {
                var testedIndex      = _reverseIndexValue[testedValue];
                var otherTestedIndex = otherCombinatoryGenotype._reverseIndexValue[testedValue];

                testedIndex      = testedIndex >= Count - 2 ? 0 : testedIndex + 1;
                otherTestedIndex = otherTestedIndex >= Count - 2 ? 0 : otherTestedIndex + 1;
                if (Value[testedIndex] == otherCombinatoryGenotype.Value[otherTestedIndex])
                {
                    sum++;
                }
            }

            return(sum / Count);
        }
Example #7
0
 public TPhenotype Make(IGenotype genotype)
 {
     return(new()
     {
         Genotype = genotype,
         Scale = Range
     });
 }
Example #8
0
 public Genotype(IGenotype <int, int> genotype, ICache <int, int> cache)
 {
     this.cache    = cache;
     this.genotype = new List <IGene <int, int> >();
     for (int i = 0; i < genotype.GetGenotypeSize(); i++)
     {
         this.genotype.Add(new Gene <int, int>(genotype.GetGene(i).GetKey(), genotype.GetGene(i).GetValue()));
     }
 }
        public IGenotype[] Cross(IGenotype[] parents)
        {
            var parentsPermutation = new PermutationGenotype[ParentsCount];
            var children           = new IGenotype[ChildrenCount];

            for (var j = 0; j < ParentsCount; j++)
            {
                parentsPermutation[j] = parents[j] as PermutationGenotype;
            }

            for (var j = 0; j < ChildrenCount; j++)
            {
                children[j] = parentsPermutation[0].EmptyCopy <PermutationGenotype>();
            }

            var childrenValues   = new short[ChildrenCount][];
            var availableIndexes = new bool[ChildrenCount][];
            var genotypeSize     = parentsPermutation[0].Count;

            for (var childIndex = 0; childIndex < ChildrenCount; childIndex++)
            {
                childrenValues[childIndex]   = new short[genotypeSize];
                availableIndexes[childIndex] = new bool[genotypeSize];
                for (var i = 0; i < genotypeSize; i++)
                {
                    availableIndexes[childIndex][i] = true;
                }

                var nextParentIndex = childIndex + 1 >= ParentsCount ? 0 : childIndex + 1;

                var index = 0;
                while (availableIndexes[childIndex][index])
                {
                    childrenValues[childIndex][index]   = parentsPermutation[childIndex].Value[index];
                    availableIndexes[childIndex][index] = false;
                    index = parentsPermutation[childIndex].GetIndex(parentsPermutation[nextParentIndex].Value[index]);
                }

                for (var i = 0; i < genotypeSize; i++)
                {
                    if (availableIndexes[childIndex][i])
                    {
                        childrenValues[childIndex][i] = parentsPermutation[nextParentIndex].Value[i];
                    }
                }
            }

            for (var j = 0; j < ChildrenCount; j++)
            {
                ((PermutationGenotype)children[j]).Value = childrenValues[j];
            }

            return(children);
        }
Example #10
0
        /// <summary>
        /// Handles a new generation
        /// </summary>
        private void NewGeneration()
        {
            Bitmap img;
            int    size;

            if (best != ga.BestCurrent)
            {
                best             = ga.BestCurrent;
                size             = Math.Min(pictureBox.Width - 2, pictureBox.Height - 2);
                img              = ga.DrawIndividual((Genotype <int>)ga.BestCurrent, size, size);
                pictureBox.Image = img;
            }
        }
        public Individual(IGenotype genotype, IPhenotype phenotype)
        {
            Genotype           = genotype;
            Phenotype          = phenotype;
            Phenotype.Genotype = genotype;

            if (_fitnessFunction != null)
            {
                return;
            }

            var factory = new TFitnessFunctionFactory();

            _fitnessFunction = factory.Make();
        }
Example #12
0
        public (IGenotype, IGenotype) Crossover(IGenotype partner, XOptions options = default)
        {
            if (!Equals(partner))
            {
                throw new ArgumentException();
            }

            EvoNet offspringX = new EvoNet(layers);
            EvoNet offspringY = new EvoNet(layers);

            offspringX.Build();
            offspringY.Build();

            (float[] offspringX, float[] offspringY)offsprings = (new float[0], new float[0]);
            switch (options.xType)
            {
            case XType.OnePointX:
                offsprings = Reproduction.OnePointX(ToRowMajorArray(), ((EvoNet)partner).ToRowMajorArray());
                break;

            case XType.KPointX:
                offsprings = Reproduction.KPointX(ToRowMajorArray(), ((EvoNet)partner).ToRowMajorArray(), options.kPoints);
                break;
            }

            int gene = 0;

            for (int w = 0; w < weights.Length; w++)
            {
                for (int y = 0; y < weights[w].RowCount; y++)
                {
                    for (int x = 0; x < weights[w].ColumnCount; x++)
                    {
                        offspringX.weights[w][y, x] = offsprings.offspringX[gene];
                        offspringY.weights[w][y, x] = offsprings.offspringY[gene];
                        gene++;
                    }
                }
                for (int x = 0; x < b_weights[w].ColumnCount; x++)
                {
                    offspringX.b_weights[w][0, x] = offsprings.offspringX[gene];
                    offspringY.b_weights[w][0, x] = offsprings.offspringY[gene];
                    gene++;
                }
            }

            return(offspringX, offspringY);
        }
Example #13
0
        public bool TryGetFitness(IGenotype <int, int> genotype, out float fitness)
        {
            var _fitnessIsCalculated = calculatedFitnesses.TryGetValue(genotype.ToString(), out fitness);

            if (!_fitnessIsCalculated)
            {
                for (int y = 0; y < genotype.GetGenotypeSize(); y++)
                {
                    for (int x = y + 1; x < genotype.GetGenotypeSize(); x++)
                    {
                        fitness += distance[x, y] *
                                   (flow[genotype.GetGene(y).GetValue(), genotype.GetGene(x).GetValue()] +
                                    flow[genotype.GetGene(x).GetValue(), genotype.GetGene(y).GetValue()]);
                    }
                }
            }
            return(_fitnessIsCalculated);
        }
Example #14
0
        private IGenotype[] SelectParentalGenotypes()
        {
            var parents = new IGenotype[Crossover.ParentsCount];

            for (var x = 0; x < parents.Length; x++)
            {
                var trial     = 0;
                var candidate = SelectionMethod.Select(this)?.Genotype;
                while (ParentAlreadySelected(candidate, parents) && Homogeneity < DegenerationLimit && trial++ < MaxSelectionTries)
                {
                    candidate = SelectionMethod.Select(this)?.Genotype;
                }

                parents[x] = candidate;
            }

            return(parents);
        }
Example #15
0
        /// <summary>
        /// Handles the Click event of the startStopButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        private void startStopButton_Click(object sender, EventArgs e)
        {
            GeneticAlgorithmParams parameters;

            if (startStopButton.Text == "Start")
            {
                startStopButton.Text = "Stop";
                EnableForm(false);

                parameters = (GeneticAlgorithmParams)paramsComboBox.SelectedItem;

                if (parameters.GetType() == typeof(TravellingSalesmanParams))
                {
                    ga = new TravellingSalesmanGA((TravellingSalesmanParams)parameters);
                }
                else
                {
                    ga = new NQueenGA((NQueenParams)parameters);
                }

                ga.SelectionMethod = (SelectionMethod)selectionComboBox.SelectedItem;
                ga.CrossoverMethod = (CrossoverMethod)crossoverComboBox.SelectedItem;
                ga.MutationMethod  = (MutationMethod)mutationComboBox.SelectedItem;

                ga.TerminationMethods.Clear();
                ga.TerminationMethods.Add(new GALib.Termination.SolutionFound());
                ga.TerminationMethods.Add(new GALib.Termination.GenerationLimit((int)terminationNumericUpDown.Value));

                best = null;

                backgroundWorker.RunWorkerAsync();
            }
            else
            {
                stopRequested = true;
            }
        }
Example #16
0
 public Phenotype(IGenotype genotype)
 {
     Genotype = genotype;
 }
Example #17
0
        protected override IPhenotype CreatePhenotype(IGenotype genotype)
        {
            var phenotype = new HammingPhenotype(genotype);

            return(phenotype);
        }
Example #18
0
 public HammingPhenotype(IGenotype genotype) : base(genotype)
 {
     geno = genotype as StringGenotype;
 }
Example #19
0
        protected override IPhenotype CreatePhenotype(IGenotype genotype)
        {
            var phenotype = new OneMaxPhenotype(genotype);

            return(phenotype);
        }
Example #20
0
 /// <summary>
 /// Draws the individual.
 /// </summary>
 /// <param name="individual">The individual.</param>
 /// <param name="width">The width.</param>
 /// <param name="height">The height.</param>
 /// <returns></returns>
 public override Bitmap DrawIndividual(IGenotype individual, int width, int height)
 {
     return(DrawIndividual((Genotype <int>)individual, width, height));
 }
Example #21
0
 public OneMaxPhenotype(IGenotype genotype)
     : base(genotype)
 {
 }
Example #22
0
 public Individual(ICache <int, int> cache)
 {
     this.cache = cache;
     genotype   = new Genotype(cache);
     fitness    = CalculateFitness();
 }
Example #23
0
 public TestPhenotype(IGenotype genotype) : base(genotype)
 {
 }
Example #24
0
 public LOLZPhenotype(IGenotype genotype, int z)
     : base(genotype)
 {
     _Z = z;
 }
Example #25
0
 public IIndividual <int, int> CreateNewIndividual(IGenotype <int, int> genotype, ICache <int, int> cache)
 {
     return(new Individual(genotype, cache));
 }
Example #26
0
 public Individual(IGenotype <int, int> genotype, ICache <int, int> cache)
 {
     this.cache    = cache;
     this.genotype = genotype;
     fitness       = CalculateFitness();
 }
Example #27
0
        protected override IPhenotype CreatePhenotype(IGenotype genotype)
        {
            var phenotype = new LOLZPhenotype(genotype, _z);

            return(phenotype);
        }
 public override IIndividual CreateFromGenotype(IGenotype genotype)
 {
     return(new Individual <TFitnessFunctionFactory>(genotype, Factory.Make(genotype)));
 }
Example #29
0
 protected override IPhenotype CreatePhenotype(IGenotype genotype)
 {
     CreatePhenotypeCount++;
     return(new TestPhenotype(genotype));
 }
 // In your constructor you pass the implementation
 public Individual(IGenotype genotype)
 {
     this.genotype = genotype;
 }