Пример #1
0
 /// <summary>
 /// Build the representation of a gene for easy identification
 /// </summary>
 /// <param name="firstAllele"></param>
 /// <param name="secondAllele"></param>
 public void BuildRepresentation(IAllele firstAllele, IAllele secondAllele)
 {
     if (firstAllele.Representation == secondAllele.Representation)
     {
         _representation = firstAllele.Representation;
         return;
     }
     if(firstAllele.IsDominant && secondAllele.IsDominant)
     {
         _representation = GeneRepresentationBuilder.CreateName(firstAllele.Representation, secondAllele.Representation);
         return;
     }
     if (firstAllele.IsDominant)
     {
         _representation = firstAllele.Representation;
         return;
     }
     if (secondAllele.IsDominant)
     {
         _representation = secondAllele.Representation;
         return;
     }
     _representation = GeneRepresentationBuilder.CreateName(firstAllele.Representation,
         secondAllele.Representation);
 }
 public AlleleControl(IAllele allele, StackPanel sp, Func<object, int> query, bool coDominant = false)
 {
     _allele = allele;
     _stackPanel = sp;
     _query = query;
     _isCoDominant = coDominant;
 }
Пример #3
0
        public void ContainsGeneValueReturnsTrueForMaximum()
        {
            IAllele maximumValue = this.WrapInAlleleWithCorrectType(NumericalDomainTest.maximum);

            Assert.True(
                this._domain.ContainsGeneValue(maximumValue),
                $"{maximumValue} supposedly not contained in {this._domain}.");
        }
Пример #4
0
        public void ContainsGeneValueReturnsFalseForLowerValue()
        {
            IAllele lowValue = this.WrapInAlleleWithCorrectType(NumericalDomainTest.minimum - 1);

            Assert.False(
                this._domain.ContainsGeneValue(lowValue),
                $"{lowValue} supposedly contained in {this._domain}.");
        }
Пример #5
0
        public void ContainsGeneValueReturnsFalseForHigherValue()
        {
            IAllele highValue = this.WrapInAlleleWithCorrectType(NumericalDomainTest.maximum + 1);

            Assert.False(
                this._domain.ContainsGeneValue(highValue),
                $"{highValue} supposedly contained in {this._domain}.");
        }
Пример #6
0
        public void GeneIsSetCorrectly()
        {
            this._genome.SetGene("a", new Allele <int>(5));

            IAllele geneValue = this._genome.GetGeneValue("a");

            Assert.Equal(5, geneValue.GetValue());
        }
Пример #7
0
 public Gene(IAllele firstAllele, IAllele secondAllele, Guid locusId)
 {
     _fitnessGain = 1;
     _locusId = locusId;
     this._firstAlleleId = firstAllele.Id;
     this._secondAlleleId = secondAllele.Id;
     _alleles = new List<Guid> {firstAllele.Id, secondAllele.Id};
     BuildRepresentation(firstAllele, secondAllele);
 }
Пример #8
0
        /// <summary>
        /// Converts the given <paramref name="member"/> of this <see cref="IDomain"/> into a double value.
        /// </summary>
        /// <param name="member">A member of the current domain.</param>
        /// <returns>A double that represents the <paramref name="member"/>.</returns>
        public virtual double ConvertToDouble(IAllele member)
        {
            // check if this is a member
            if (this.ContainsGeneValue(member))
            {
                return(this.ConvertMemberToDouble((T)member.GetValue()));
            }

            throw new ArgumentException($"Allele {member} is not a member of this Domain.", nameof(member));
        }
Пример #9
0
        /// <summary>
        /// Generates a gene value from the domain that results from mutating the given gene value.
        /// </summary>
        /// <param name="allele">The value to base the mutated value on. Has to be part of the domain.</param>
        /// <param name="variancePercentage">
        /// Mutation might utilize Gaussian distributions.
        /// This parameter defines the respective variance as a certain percentage of the variable's domain.
        /// Needs to be positive and at most 1.
        /// </param>
        /// <returns>The generated gene value.</returns>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Thrown if the given value is not part of the domain
        /// or the given percentage is not a positive value at most 1.
        /// </exception>
        public IAllele MutateGeneValue(IAllele allele, double variancePercentage)
        {
            if (!this.ContainsGeneValue(allele))
            {
                throw new ArgumentOutOfRangeException(
                          $"{allele.GetValue().GetType()} {allele} is not part of the {typeof(T)} domain {this}.");
            }

            var typedValue = (T)allele.GetValue();

            return(new Allele <T>(this.Mutate(typedValue, variancePercentage)));
        }
Пример #10
0
 public void RandomGenerationStaysInDomain()
 {
     // For a lot of tries:
     for (int i = 0; i < CategoricalDomainTest.triesForRandomTests; i++)
     {
         // Check that the generated value is in the domain.
         IAllele generated = this._categoricalDomain.GenerateRandomGeneValue();
         Assert.True(
             this._categoricalDomain.ContainsGeneValue(generated),
             $"Generated value {generated} which is not contained in {this._categoricalDomain}");
     }
 }
Пример #11
0
        /// <summary>
        /// Checks if the given gene value is part of the domain.
        /// </summary>
        /// <param name="allele">Gene value to check.</param>
        /// <returns>Whether or not the given gene value is part of the domain.</returns>
        public bool ContainsGeneValue(IAllele allele)
        {
            // Check given value's type.
            if (!(allele.GetValue() is T))
            {
                return(false);
            }

            // Check if it is contained in domain.
            var typedValue = (T)allele.GetValue();

            return(this.Contains(typedValue));
        }
Пример #12
0
        public void RandomGenerationCreatesLegalGenes()
        {
            this._integerDomain = new IntegerDomain(IntegerDomainTest.minimum, IntegerDomainTest.maximum);

            // For a lot of tries:
            for (int i = 0; i < IntegerDomainTest.triesForRandomTests; i++)
            {
                // Check that the generated gene is legal.
                IAllele generated = this._integerDomain.GenerateRandomGeneValue();
                Assert.True(
                    this._integerDomain.ContainsGeneValue(generated),
                    $"Generated value {generated} is not a legal gene of {this._integerDomain}.");
            }
        }
 public StackPanel CreateDataPairLinq(string controlName, string labelContent, Func<IAllele, int> bindingSource, IValueConverter converter, IAllele allele)
 {
     var stackPanel = CreateDataPairBase(controlName, labelContent);
     var binding = new Binding
     {
         Source = bindingSource,
         Mode = BindingMode.OneWay,
         Converter = converter,
         ConverterParameter = allele
     };
     var tb = stackPanel.Children[1] as TextBox;
     tb?.SetBinding(TextBox.TextProperty, binding);
     return stackPanel;
 }
Пример #14
0
        public void RandomGenerationStaysInDomain()
        {
            IDomain domain = new ContinuousDomain(ContinuousDomainTest.minimum, ContinuousDomainTest.maximum);

            // For a lot of tries:
            for (int i = 0; i < ContinuousDomainTest.TriesForRandomTests; i++)
            {
                // Check that the generated value is in the domain.
                IAllele generated = domain.GenerateRandomGeneValue();
                Assert.True(
                    domain.ContainsGeneValue(generated),
                    $"Generated value {generated} which is not contained in {domain}");
            }
        }
Пример #15
0
        public void MutationStaysInDomain()
        {
            // Initialize bounded domain.
            var domain = new ContinuousDomain(ContinuousDomainTest.minimum, ContinuousDomainTest.maximum);

            // Fix the value to mutate and the variance percentage.
            Allele <double> valueToMutate      = new Allele <double>(ContinuousDomainTest.maximum - 1);
            double          variancePercentage = 1.0;

            // For a lot of tries:
            for (int i = 0; i < ContinuousDomainTest.TriesForRandomTests; i++)
            {
                // Mutate and check that the mutated value is in the domain.
                IAllele mutatedGeneValue = domain.MutateGeneValue(valueToMutate, variancePercentage);
                Assert.True(
                    domain.ContainsGeneValue(mutatedGeneValue),
                    $"Value {mutatedGeneValue} was generated by mutation and is not contained in {domain}");
            }
        }
Пример #16
0
        public void MutateRespectsMutationRate()
        {
            // Create genome builder with a mutation rate of 0.35.
            double mutationRate  = 0.35;
            var    configuration =
                new AlgorithmTunerConfiguration.AlgorithmTunerConfigurationBuilder()
                .SetMutationRate(mutationRate)
                .Build(maximumNumberParallelEvaluations: 1);
            var genomeBuilder = new GenomeBuilder(GenomeBuilderTest.BuildParameterTree(), configuration);

            // Create genome.
            var genome = GenomeBuilderTest.BuildFittingGenome();

            // For a lot of iterations:
            IAllele oldGeneValue = genome.GetGeneValue(GenomeBuilderTest.ContinuousParameter);
            int     changeCount  = 0;
            int     numberLoops  = 1000;

            for (int i = 0; i < numberLoops; i++)
            {
                // Mutate the genome ...
                genomeBuilder.Mutate(genome);
                // ... compare the continuous parameter gene...
                IAllele newGeneValue = genome.GetGeneValue(GenomeBuilderTest.ContinuousParameter);
                if (!object.Equals(newGeneValue, oldGeneValue))
                {
                    changeCount++;
                }

                // ... and count the number of times it changes.
                oldGeneValue = newGeneValue;
            }

            // Finally compare the number of mutations with the expected number.
            double expectedNumberMutations = mutationRate * numberLoops;

            Assert.True(
                Math.Abs(expectedNumberMutations - changeCount) <= 0.1 * expectedNumberMutations,
                "Number of mutations was not as expected.");
        }
Пример #17
0
        public override void MutateGeneValueThrowsExceptionForInvalidValue()
        {
            IAllele geneValue = this.WrapInAlleleWithCorrectType(NumericalDomainTest.maximum + 1);

            Assert.Throws <ArgumentOutOfRangeException>(() => this._domain.MutateGeneValue(geneValue, NumericalDomainTest.irrelevantVariance));
        }
Пример #18
0
 public bool Equals(IAllele other)
 {
     return this.DNA.Equals(other.DNA);
 }
Пример #19
0
 /// <summary>
 /// Sets the value for the <see cref="ControlledParameterIdentifier"/>,
 /// that should be used when the <see cref="IndicatorParameterIdentifier"/> parameter
 /// is set to <see cref="IndicatorParameterValue"/> in the current genome.
 /// </summary>
 /// <param name="value">
 /// The value for the <see cref="IAllele"/>.
 /// </param>
 /// <typeparam name="T">
 /// The value type of the <see cref="Allele{T}"/>.
 /// </typeparam>
 internal void SetNativeOverrideValue <T>(T value)
 {
     this.NativeOverrideValue = new Allele <T>(value);
 }
 public override double ConvertToDouble(IAllele member)
 {
     throw new NotSupportedException("Please use the ICategoricalEncoding to convert a categorical value to double!");
 }
Пример #21
0
 /// <summary>
 /// Check if override of <see cref="ParameterReplacementDefinition.IndicatorParameterIdentifier"/> is required.
 /// </summary>
 /// <param name="indicatorInCurrentTree">
 /// The indicator's value in the current tree.
 /// </param>
 /// <param name="replacementDefinitionWithOverride">
 /// The wrapper with override.
 /// </param>
 /// <returns>
 /// True, if <paramref name="indicatorInCurrentTree"/>.GetValue().Equals(<see cref="ParameterReplacementDefinition.IndicatorParameterValue"/>).
 /// </returns>
 private static bool CheckIfOverrideIsRequired(
     IAllele indicatorInCurrentTree,
     ParameterReplacementDefinition replacementDefinitionWithOverride)
 {
     return(object.Equals(indicatorInCurrentTree.GetValue(), replacementDefinitionWithOverride.IndicatorParameterValue));
 }
Пример #22
0
 public void AddAllele(IAllele allele)
 {
     _alleleManager.CreateAllele(allele);
 }
 /// <summary>
 /// Gets the percentage that IAllele one and IAllele two are similar.
 /// 100% would be identical and 0% would indicate that the IAlleles share nothing.
 /// </summary>
 /// <param name="one">The first IAllele to compare.</param>
 /// <param name="two">The second IAllele to compare.</param>
 /// <returns>The percentage that IAllele one and IAllele two are similar.
 /// 100% would be identical and 0% would indicate that the IAlleles share nothing.</returns>
 public abstract double GetPercentageIAlleleSimilarity(IAllele one, IAllele two);
Пример #24
0
        public void MutateGeneValueThrowsExceptionForZeroVariancePercentage()
        {
            IAllele geneValue = this.WrapInAlleleWithCorrectType(NumericalDomainTest.minimum);

            Assert.Throws <ArgumentOutOfRangeException>(() => this._domain.MutateGeneValue(geneValue, variancePercentage: 0));
        }
Пример #25
0
        public void CrossoverRespectsSwitchProbability()
        {
            // Build parameter tree that consists of two dependent continuous parameters.
            string rootParameterName  = "parameterRoot";
            string childParameterName = "parameterChild";
            var    rootParameter      = new ValueNode <double>(rootParameterName, new ContinuousDomain());
            var    childParameter     = new ValueNode <double>(childParameterName, new ContinuousDomain());

            rootParameter.SetChild(childParameter);

            // Build genome builder with that parameter tree and a specific crossover switch probability.
            double crossoverSwitchParameter    = 0.25;
            AlgorithmTunerConfiguration config = new AlgorithmTunerConfiguration.AlgorithmTunerConfigurationBuilder()
                                                 .SetCrossoverSwitchProbability(crossoverSwitchParameter)
                                                 .Build(maximumNumberParallelEvaluations: 1);
            var genomeBuilder = new GenomeBuilder(new ParameterTree(rootParameter), config);

            // Build parents.
            var parent1            = new Genome();
            var parent2            = new Genome();
            var parent1RootAllele  = new Allele <double>(1);
            var parent1ChildAllele = new Allele <double>(2);
            var parent2RootAllele  = new Allele <double>(3);
            var parent2ChildAllele = new Allele <double>(4);

            parent1.SetGene(rootParameterName, parent1RootAllele);
            parent1.SetGene(childParameterName, parent1ChildAllele);
            parent2.SetGene(rootParameterName, parent2RootAllele);
            parent2.SetGene(childParameterName, parent2ChildAllele);

            // Observe if children's genes come from the same parent or not.
            int numberLoops             = 1000;
            int genesCameFromSameParent = 0;

            for (int i = 0; i < numberLoops; i++)
            {
                var     child       = genomeBuilder.Crossover(parent1, parent2);
                IAllele rootAllele  = child.GetGeneValue(rootParameterName);
                IAllele childAllele = child.GetGeneValue(childParameterName);
                bool    geneValuesInheritedFromSameParent =
                    (object.Equals(rootAllele, parent1RootAllele) && object.Equals(childAllele, parent1ChildAllele)) ||
                    (object.Equals(rootAllele, parent2RootAllele) && object.Equals(childAllele, parent2ChildAllele));
                if (geneValuesInheritedFromSameParent)
                {
                    genesCameFromSameParent++;
                }
            }

            double[] observed = { genesCameFromSameParent, numberLoops - genesCameFromSameParent };

            // We would expect each case according to switch probability:
            int expectedSwitches = (int)(crossoverSwitchParameter * numberLoops);

            double[] expected = { numberLoops - expectedSwitches, expectedSwitches };

            // Use Chi-Squared Test.
            var matchesSwitchProbabilityTest = new ChiSquareTest(expected, observed, degreesOfFreedom: numberLoops - 1);

            Assert.False(
                matchesSwitchProbabilityTest.Significant,
                $"Crossover was found not to respect the switch probability by the Chi-Squared test with significance level of {matchesSwitchProbabilityTest.Size}.");
        }
Пример #26
0
        public void MutateGeneValueDoesNotThrowForVariancePercentage100()
        {
            IAllele geneValue = this.WrapInAlleleWithCorrectType(NumericalDomainTest.minimum);

            this._domain.MutateGeneValue(geneValue, variancePercentage: 1);
        }
Пример #27
0
 private void CreateCoDominantControls(IAllele allele)
 {
     foreach (var all in _dominantAlleles)
     {
         var rep = GeneRepresentationBuilder.CreateName(all.Representation, allele.Representation);
         var func = new Func<object, int>(CoDominantPopulation);
         var cdAll = new Allele(rep, false);
         var sp = _controlManager.CreateCoDominantPairLinq(rep, rep + " Population" + " Populus",
          func, new ValueConverter());
         var control = new AlleleControl(cdAll, sp, func, true);
         control.UpdateControlValue();
         _controls.Add(control);
     }
 }
Пример #28
0
 public Gene(int value, IAllele allele)
 {
     Value  = value;
     Allele = allele;
 }
Пример #29
0
        private void CreateControl(IAllele allele, string representation)
        {
            var func = new Func<object, int>(AllelePopulation);
            var sp = _controlManager.CreateDataPairLinq(representation, representation + " Population" + " Populus",
                 func, new ValueConverter(), allele);

            var control = new AlleleControl(allele, sp, func);
            _controls.Add(control);
        }
Пример #30
0
 public void CreateAllele(IAllele allele)
 {
     _alleles.Add(allele);
     //CreateAlleleControls(allele);
     if (allele.IsDominant) _dominantAlleles.Add(allele);
 }
Пример #31
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="inactiveAlleles">The inactive IAlleles at this IGenomeUnit position in the IGenome.
 /// These are the IAlleles that will not be used in the IGene's phenotype.</param>
 /// <param name="chromosomeIndex">The IChromosome to which the IGene belongs. 
 /// 0 corresponds with the 1st IChromosome. 
 /// 1 corresponds with the 2nd IChromosome.</param>
 /// <param name="geneLevel">0 Corresponds with the top-level IGenes that belong directly to IChromosomes.
 /// 1+ Corresponds with the IGenes that belong to the IGenes at level 1.</param>
 /// <param name="activeAllele">The active IAllele at this IGenomeUnit position in the IGenome.
 /// 
 /// This active IAllele is the IAllele whose DNA will be used to create the IGene's Phenotype.</param>
 public GenomeUnit(IAllele activeAllele, IEnumerable<IAllele> inactiveAlleles, 
     int chromosomeIndex, int geneLevel)
     : base(activeAllele: activeAllele, inactiveAlleles: inactiveAlleles, 
 chromosomeIndex: chromosomeIndex, geneLevel: geneLevel)
 {
 }
Пример #32
0
 /// <summary>
 /// Gets the percentage that IAllele one and IAllele two are similar.
 /// 100% would be identical and 0% would indicate that the IAlleles share nothing.
 /// </summary>
 /// <param name="one">The first IAllele to compare.</param>
 /// <param name="two">The second IAllele to compare.</param>
 /// <returns>The percentage that IAllele one and IAllele two are similar.
 /// 100% would be identical and 0% would indicate that the IAlleles share nothing.</returns>
 public override double GetPercentageIAlleleSimilarity(IAllele one, IAllele two)
 {
     return this.GetPercentageIAlleleSimilarityDelegate(one: one, two: two);
 }
Пример #33
0
 private void CreateAlleleControls(IAllele allele)
 {
     if (allele.IsDominant) CreateCoDominantControls(allele);
     //CreateControl(allele, allele.Representation);
 }