// CONSTRUCTORS
        public AlleleCheckPrefab(Allele allele, Series series, DataGridViewColumn column, int row)
        {
            _series = series;
            _col = column;

            build(allele, row);
        }
 public void BuildRepresentation_OneDominant(string a1r, bool a1d, string a2r, bool a2d)
 {
     var a1 = new Allele(a1r, a1d);
     var a2 = new Allele(a2r, a2d);
     var gene = new Gene(a1, a2, Guid.NewGuid());
     Assert.AreEqual(a1r, gene.Representation);
 }
 public void BuildRepresentation_NoDominant(string a1r, string a2r, string expected)
 {
     var a1 = new Allele(a1r, false);
     var a2 = new Allele(a2r, false);
     var gene = new Gene(a1, a2, Guid.NewGuid());
     Assert.AreEqual(expected, gene.Representation);
 }
Example #4
0
 protected override CategoryViewModel CreateNewCategory()
 {
     var allele = new Allele()
     {
         Value = "NEW CATEGORY"
     };
     return new AlleleViewModel(allele);
 }
 public void SelectAllele_ReturnSecondAllele()
 {
     var random = new Falsy();
     var factory = new PersonFactory(random);
     var first = new Allele();
     var second = new Allele();
     var gene = new Gene(first, second, Guid.NewGuid());
     var bob = factory.SelectAllele(gene);
     Assert.AreEqual(bob, second.Id);
 }
 private static Locus BloodTypeAlleles( IWorld world)
 {
     var alleleMgr = new AlleleManager(world);
     var bloodType = new Locus("Blood Type", alleleMgr);
     var a = new Allele("A", true, .33);
     var b = new Allele("B", true, .33);
     var o = new Allele("O", false, .33);
     bloodType.AddAllele(a);
     bloodType.AddAllele(b);
     bloodType.AddAllele(o);
     return bloodType;
 }
 public void RetrieveAllele(int number, int indexOfResult)
 {
     var random = new Truthy(number);
     var firstAllele = new Allele(.33);
     var secondAllele = new Allele(.33);
     var thirdAllele = new Allele(.33);
     var alleleList = new List<IAllele> {firstAllele, secondAllele, thirdAllele};
     var mgr = new AlleleManager(alleleList);
     var factory = new PersonFactory(random);
     var actual = factory.RetrieveAllele(mgr);
     Assert.AreEqual(alleleList[indexOfResult].Id, actual.Id);
 }
 private static Locus SecondAllele(IWorld world)
 {
     var mgr = new AlleleManager(world);
     var locus = new Locus("Eye Color", mgr);
     locus.isVisibleLocus = true;
     var h = new Allele("H", false, .4);
     var bl = new Allele("B", true, .25);
     var red = new Allele("R", false, .1);
     var blue = new Allele("L", false, .25);
     locus.AddAllele(h);
     locus.AddAllele(bl);
     locus.AddAllele(blue);
     locus.AddAllele(red);
     return locus;
 }
        // ---------------------------------------------------------------------------------------------------------
        //
        // validation: extra-strict validation routines for paranoid users
        //
        // ---------------------------------------------------------------------------------------------------------

        /// <summary>
        /// Run all extra-strict validation tests on a Variant Context object
        /// </summary>
        /// <param name="reportedReference">   the reported reference allele </param>
        /// <param name="observedReference">   the actual reference allele </param>
        /// <param name="rsIDs">               the true dbSNP IDs </param>
        public void extraStrictValidation(Allele reportedReference, Allele observedReference, ISet<string> rsIDs)
        {
            // validate the reference
            validateReferenceBases(reportedReference, observedReference);

            // validate the RS IDs
            ValidateRSIDs(rsIDs);

            // validate the altenate alleles
            ValidateAlternateAlleles();

            // validate the AN and AC fields
            ValidateChromosomeCounts();

            // TODO: implement me
            //checkReferenceTrack();
        }
        /// <summary>
        /// Returns the domain value that is represented by <paramref name="key"/> as <see cref="IAllele"/>.
        /// </summary>
        /// <param name="key">
        /// The column representation of the requested domain value.
        /// </param>
        /// <returns>
        /// The domain value as <see cref="IAllele"/>.
        /// </returns>
        public IAllele GetDomainValueAsAllele(double[] key)
        {
            lock (this._keyToAlleleLock)
            {
                // convert the domain member value to allele, if not already done
                if (!this.KeyToAllele.ContainsKey(key))
                {
                    // get the value represented as domain member
                    var value = this.GetDomainValue(key);

                    var allele = new Allele <T>(value);
                    this.KeyToAllele.Add(key, allele);
                }

                return(this.KeyToAllele[key]);
            }
        }
        private void build(Allele allele, int row)
        {
            int x = INIT_HORZ_PADDING;
            int y = INIT_VERT_PADDING + (CHK_HEIGHT + VERT_PADDING) * row;

            // Initialize the Checkbox
            _chk = new CheckBox() {
                Name = $"AlleleChk{row}",
                AutoSize = true,
                Location = new Point(x, y),
                Checked = true,
                TabIndex = row,
                Text = allele.Symbol,
                UseVisualStyleBackColor = true,
            };
            _chk.CheckedChanged += AlleleChk_CheckedChanged;
        }
Example #12
0
        public Plant GetRandomPlant()
        {
            var values = Enum.GetValues(typeof(Allele));
            var genome = new Allele[Parameters.NbGenes];

            for (int i = 0; i < genome.Length; i++)
            {
                var alleleIndex = Rng.Next(0, values.Length);
                var value       = values.GetValue(alleleIndex);
                if (value == null)
                {
                    throw new ApplicationException("Unexpected null value!");
                }
                genome[i] = (Allele)(int)value;
            }

            return(new Plant(genome));
        }
Example #13
0
        /// <summary>
        /// Method to have a consistent single crossover point
        /// Only used for testing purposes
        /// </summary>
        public static Chromosome[] ConstantCrossover(Chromosome a, Chromosome b)
        {
            //declaring the new subset of offspring allele
            Allele[] firstSet  = new Allele[a.Length];
            Allele[] secondSet = new Allele[a.Length];

            //Controlled Chrossover point
            int split = 4;

            //setting first set of allele
            for (int i = 0; i < firstSet.Length; i++)
            {
                if (i <= split)
                {
                    firstSet[i] = a[i];
                }
                else
                {
                    firstSet[i] = b[i];
                }
            }

            //setting the second set of allele
            for (int i = 0; i < secondSet.Length; i++)
            {
                if (i <= split)
                {
                    secondSet[i] = b[i];
                }
                else
                {
                    secondSet[i] = a[i];
                }
            }

            Chromosome[] children = new Chromosome[2];

            //storing the newly created chromosomes
            children[0] = new Chromosome(firstSet);
            children[1] = new Chromosome(secondSet);

            return(children);
        }
Example #14
0
        public void CrossoverRandomlyDecidesOnParentToTakeGeneValueFromForSingleGene()
        {
            // Build genome builder with a parameter tree that consists of a single continuous parameter.
            string         parameterName = "parameter";
            IParameterNode parameter     = new ValueNode <double>(parameterName, new ContinuousDomain());
            var            genomeBuilder = new GenomeBuilder(
                new ParameterTree(parameter),
                new AlgorithmTunerConfiguration.AlgorithmTunerConfigurationBuilder().Build(maximumNumberParallelEvaluations: 1));

            // Build genomes with different parameter values.
            var             parent1       = new Genome();
            var             parent2       = new Genome();
            Allele <double> parent1Allele = new Allele <double>(0);
            Allele <double> parent2Allele = new Allele <double>(1);

            parent1.SetGene(parameterName, parent1Allele);
            parent2.SetGene(parameterName, parent2Allele);

            // Observe what gene value the children's genes have.
            int numberLoops = 1000;
            int observedInheritanceFromParent1 = 0;

            for (int i = 0; i < numberLoops; i++)
            {
                var child = genomeBuilder.Crossover(parent1, parent2);
                if (object.Equals(parent1Allele, child.GetGeneValue(parameterName)))
                {
                    observedInheritanceFromParent1++;
                }
            }

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

            // We would expect each value the same number of times:
            double[] expected = { numberLoops / 2, numberLoops / 2 };

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

            Assert.False(
                equalProbabilityTest.Significant,
                $"Single gene was found to be not equally distributed in crossovers by the Chi-Squared test with significance level of {equalProbabilityTest.Size}.");
        }
Example #15
0
        public static Chromosome[] SingleCrossover(Chromosome a, Chromosome b)
        {
            //declaring the new subset of offspring allele
            Allele[] firstSet  = new Allele[a.Length];
            Allele[] secondSet = new Allele[a.Length];

            //number at which splits the two chromosomes
            int split = Helpers.rand.Next(0, a.Length);

            //setting first set of allele
            for (int i = 0; i < firstSet.Length; i++)
            {
                if (i <= split)
                {
                    firstSet[i] = a[i];
                }
                else
                {
                    firstSet[i] = b[i];
                }
            }

            //setting the second set of allele
            for (int i = 0; i < secondSet.Length; i++)
            {
                if (i <= split)
                {
                    secondSet[i] = b[i];
                }
                else
                {
                    secondSet[i] = a[i];
                }
            }

            Chromosome[] children = new Chromosome[2];

            //storing the newly created chromosomes
            children[0] = new Chromosome(firstSet);
            children[1] = new Chromosome(secondSet);

            return(children);
        }
Example #16
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}");
            }
        }
Example #17
0
        public void BbobRunnerReturnsCorrectResult(int functionId, int instanceSeed, double x0, double x1, double x2, double expectedResult)
        {
            Assert.True(File.Exists(PythonBinary), "The python binary cannot be found. Please adopt its path in BbobRunnerTests.cs.");

            var parameters = new Dictionary <string, IAllele>();

            parameters["x0"] = new Allele <double>(x0);
            parameters["x1"] = new Allele <double>(x1);
            parameters["x2"] = new Allele <double>(x2);
            var bbobRunner = new BbobRunner(functionId, parameters, BbobRunnerTests.PythonBinary, BbobRunnerTests.BbobScript);

            var instance = BbobRunnerTests.CreateInstanceFile(instanceSeed);

            var runnerTask = bbobRunner.Run(instance, CancellationToken.None);

            runnerTask.Wait();
            var result = runnerTask.Result;

            result.Value.ShouldBe(expectedResult, "Expected different result.");
        }
        public void GenerateRandomGeneValueDoesNotDepartFromUniformDistribution()
        {
            // Create domain.
            ContinuousDomain domain = new ContinuousDomain(ContinuousDomainTest.minimum, ContinuousDomainTest.maximum);

            // Collect results of value generation.
            double[] generatedValues = new double[ContinuousDomainTest.TriesForRandomTests];
            for (int i = 0; i < ContinuousDomainTest.TriesForRandomTests; i++)
            {
                Allele <double> generated = domain.GenerateRandomGeneValue();
                generatedValues[i] = generated.GetValue();
            }

            // Apply the Anderson-Darling test.
            AndersonDarlingTest uniformTest = new AndersonDarlingTest(generatedValues, new UniformContinuousDistribution(ContinuousDomainTest.minimum, ContinuousDomainTest.maximum));

            Assert.False(
                uniformTest.Significant,
                $"Random generation was found to be not uniform by the Anderson-Darling test with significance level of {uniformTest.Size}.");
        }
Example #19
0
        /// <summary>
        /// Cosntructor initializes chromosome array
        /// through a deep copy
        /// </summary>
        /// <param name="members">Chromosome array to be copied</param>
        public Generation(Chromosome[] members)
        {
            population = new Chromosome[members.Length];
            Allele[] temp;

            //iterating through every chromosome
            for (int i = 0; i < members.Length; i++)
            {
                //setting the length of the allele array
                temp = new Allele[members[i].Length];

                //iterating through the alleles of chromosome at index i
                for (int j = 0; j < members[i].Length; j++)
                {
                    temp[j] = members[i][j];
                }

                population[i] = new Chromosome(temp);
            }
        }
Example #20
0
        /// <summary>
        /// Creates a <see cref="ParameterTree"/> consisting of <paramref name="parameterCount"/> independent nodes:
        /// * x0 through x{<paramref name="parameterCount"/> - 1}.
        /// * All parameters range from -5 to 5, as all BBOB Functions will have their respective optimum in that range.
        /// </summary>
        /// <param name="parameterCount">The number of parameters to use for BBOB functions.</param>
        /// <returns>The <see cref="ParameterTree"/>.</returns>
        public static ParameterTree CreateParameterTree(int parameterCount)
        {
            if (parameterCount <= 0)
            {
                throw new ArgumentException($"{nameof(parameterCount)} must be positive.", nameof(parameterCount));
            }

            var root = new AndNode();
            for (var i = 0; i < parameterCount; i++)
            {
                // This is just a placeholder to demonstrate specification of default values in code.
                var exemplaryDefaultValue = new Allele<double>(0.42);
                var node = new ValueNode<double>(
                    string.Format(BbobUtils.IdentifierTemplate, i),
                    new ContinuousDomain(minimum: -5, maximum: 5, exemplaryDefaultValue));
                root.AddChild(node);
            }

            return new ParameterTree(root);
        }
Example #21
0
        /// <summary>
        /// Initializes <see cref="Genomes"/> creating one <see cref="Genome"/> per value of a
        /// <see cref="CategoricalDomain{T}"/>, where the domain consists of <paramref name="categoricalValueCount"/>
        /// strings.
        /// </summary>
        /// <typeparam name="TEncoding">Encoding of domain.</typeparam>
        /// <param name="categoricalValueCount">Number of categorical values to use.</param>
        private void InitializeSingleCategoryOneGenomePerValue <TEncoding>(int categoricalValueCount)
            where TEncoding : CategoricalEncodingBase, new()
        {
            var domain = this.GetTestDomain(categoricalValueCount);
            var tree   = this.SingleCategoryTree(domain);

            var genomes        = new List <Genome>();
            var singleTreeNode = tree.GetParameters().Single();

            foreach (var possibleValue in domain.PossibleValues)
            {
                var allele = new Allele <string>(possibleValue);
                var genome = new Genome();
                genome.SetGene(singleTreeNode.Identifier, allele);
                genomes.Add(genome);
            }

            this.CurrentTree = tree;
            this.Genomes     = genomes;
            this.InitializeTypedTransformation <TEncoding>(this.CurrentTree);
        }
Example #22
0
    public static BinomialAlleles Punnet(BinomialAlleles a, BinomialAlleles b)
    {
        Allele aInherit = FromBinomial(a);
        Allele bInherit = FromBinomial(b);

        if (aInherit == bInherit)
        {
            if (aInherit == Allele.A)
            {
                return(BinomialAlleles.AA);
            }
            else
            {
                return(BinomialAlleles.BB);
            }
        }
        else
        {
            return(BinomialAlleles.AB);
        }
    }
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not allowed in .NET:
//ORIGINAL LINE: private final void buildAlleleMap(final org.broadinstitute.variant.variantcontext.VariantContext vc)
            private void buildAlleleMap(VariantContext vc)
            {
                // these are fast path options to determine the offsets for
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int nAlleles = vc.getNAlleles();
                int nAlleles = vc.NAlleles;

                @ref = vc.Reference;
                alt1 = nAlleles > 1 ? vc.getAlternateAllele(0) : null;

                if (nAlleles > 2)
                {
                    // for multi-allelics we need to clear the map, and add additional looks
                    alleleMapForTriPlus.Clear();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.List<org.broadinstitute.variant.variantcontext.Allele> alleles = vc.getAlleles();
                    IList <Allele> alleles = vc.Alleles;
                    for (int i = 2; i < alleles.Count; i++)
                    {
                        alleleMapForTriPlus[alleles[i]] = i;
                    }
                }
            }
Example #24
0
        public void MutateDoesNotDepartFromUniformDistribution()
        {
            // Set up categorical domain with integer values 0 - 3.
            var possibleValues = new List <int> {
                0, 1, 2, 3
            };
            CategoricalDomain <int> domain = new CategoricalDomain <int>(possibleValues);

            // Remember which values were generated for a lot of iterations.
            double[]     observations = new double[CategoricalDomainTest.triesForRandomTests];
            Allele <int> geneValue    = new Allele <int>(1);

            for (int i = 0; i < CategoricalDomainTest.triesForRandomTests; i++)
            {
                observations[i] = (int)domain.MutateGeneValue(geneValue, CategoricalDomainTest.dummyVariancePercentage).GetValue();
            }

            // Apply the Chi-Squared test.
            ChiSquareTest uniformTest = new ChiSquareTest(observations, new UniformDiscreteDistribution(0, 3));

            Assert.False(
                uniformTest.Significant,
                $"Mutation was found to not produce a uniform distribution by the Chi-Squared test with significance level {uniformTest.Size}.");
        }
        private static VariantType typeOfBiallelicVariant(Allele reference, Allele allele)
        {
            if (reference.Symbolic)
            {
                throw new Exception("Unexpected error: encountered a record with a symbolic reference allele");
            }

            if (allele.Symbolic)
            {
                return VariantType.SYMBOLIC;
            }

            if (reference.Length == allele.Length)
            {
                if (allele.Length == 1)
                {
                    return VariantType.SNP;
                }
                else
                {
                    return VariantType.MNP;
                }
            }

            // Important note: previously we were checking that one allele is the prefix of the other.  However, that's not an
            // appropriate check as can be seen from the following example:
            // REF = CTTA and ALT = C,CT,CA
            // This should be assigned the INDEL type but was being marked as a MIXED type because of the prefix check.
            // In truth, it should be absolutely impossible to return a MIXED type from this method because it simply
            // performs a pairwise comparison of a single alternate allele against the reference allele (whereas the MIXED type
            // is reserved for cases of multiple alternate alleles of different types).  Therefore, if we've reached this point
            // in the code (so we're not a SNP, MNP, or symbolic allele), we absolutely must be an INDEL.

            return VariantType.INDEL;

            // old incorrect logic:
            // if (oneIsPrefixOfOther(ref, allele))
            //     return Type.INDEL;
            // else
            //     return Type.MIXED;
        }
Example #26
0
		/// <summary>
		/// Returns the number of chromosomes carrying allele A in the genotypes
		/// </summary>
		/// <param name="a"> allele </param>
		/// <returns> chromosome count </returns>
		public  int GetCalledChrCount (Allele a)
		{
			return GetCalledChrCount (a, new HashSet<string> ());
		}
Example #27
0
		public  bool HasAlternateAllele (Allele allele, bool ignoreRefState)
		{
			return hasAllele (allele, ignoreRefState, false);
		}
Example #28
0
		public  bool HasAllele (Allele allele, bool ignoreRefState)
		{
			return hasAllele (allele, ignoreRefState, true);
		}
Example #29
0
			/// <summary>
			/// Fast path code to determine the offset.
			/// 
			/// Inline tests for == against ref (most common, first test)
			/// == alt1 (second most common, second test)
			/// == NO_CALL (third)
			/// and finally in the map from allele => offset for all alt 2+ alleles
			/// </summary>
			/// <param name="a"> the allele whose offset we wish to determine </param>
			/// <returns> the offset (from 0) of the allele in the list of variant context alleles (-1 means NO_CALL) </returns>
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Requires("a != null") private final int getAlleleOffset(final org.broadinstitute.variant.variantcontext.Allele a)
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not allowed in .NET:
			private int getAlleleOffset(Allele a)
			{
				if (a == @ref)
				{
					return 0;
				}
				else if (a == alt1)
				{
					return 1;
				}
				else if (a == Allele.NO_CALL)
				{
					return -1;
				}
				else
				{
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final Integer o = alleleMapForTriPlus.get(a);
					int? o = alleleMapForTriPlus[a];
					if (o == null)
					{
						throw new IllegalStateException("BUG: Couldn't find allele offset for allele " + a);
					}
					return o;
				}
			}
 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);
     }
 }
Example #31
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}.");
        }
Example #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="IntegerDomain"/> class.
 /// </summary>
 /// <param name="minimum">
 /// The minimum value. Default is <see cref="int.MinValue"/>.
 /// </param>
 /// <param name="maximum">
 /// The maximum value. Default is <see cref="int.MaxValue"/>.
 /// </param>
 /// <param name="defaultValue">The optional default value.</param>
 public IntegerDomain(int minimum = int.MinValue, int maximum = int.MaxValue, Allele <int>?defaultValue = null)
     : base(minimum, maximum, defaultValue)
 {
 }
Example #33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ContinuousDomain" /> class.
 /// </summary>
 /// <param name="minimum">The smallest value. Default is <see cref="double.MinValue" />.</param>
 /// <param name="maximum">The largest value. Default is <see cref="double.MaxValue" />.</param>
 /// <param name="defaultValue">The optional default value, if specified by user.</param>
 public ContinuousDomain(double minimum = double.MinValue, double maximum = double.MaxValue, Allele <double>?defaultValue = null)
     : base(minimum, maximum, defaultValue)
 {
 }
Example #34
0
		private string getAlleleText(Allele allele, IDictionary<Allele, string> alleleMap)
		{
			string encoding = alleleMap[allele];
			if (encoding == null)
			{
				throw new Exception("Allele " + allele + " is not an allele in the variant context");
			}
            return encoding;
		}
Example #35
0
        /// <summary>
        /// add a record to the file
        /// </summary>
        /// <param name="vc">      the Variant Context object </param>
        public override void add(VariantContext vc)
        {
            if (mHeader == null)
            {
                throw new IllegalStateException("The VCF Header must be written before records can be added: " + StreamName);
            }

            if (doNotWriteGenotypes)
            {
                vc = (new VariantContextBuilder(vc)).noGenotypes().make();
            }

            try
            {
                base.add(vc);

                IDictionary <Allele, string> alleleMap = buildAlleleMap(vc);

                // CHROM
                write(vc.Chr);
                write(VCFConstants.FIELD_SEPARATOR);

                // POS
                write(Convert.ToString(vc.Start));
                write(VCFConstants.FIELD_SEPARATOR);

                // ID
                string ID = vc.ID;
                write(ID);
                write(VCFConstants.FIELD_SEPARATOR);

                // REF
                string refString = vc.Reference.DisplayString;
                write(refString);
                write(VCFConstants.FIELD_SEPARATOR);

                // ALT
                if (vc.Variant)
                {
                    Allele altAllele = vc.getAlternateAllele(0);
                    string alt       = altAllele.DisplayString;
                    write(alt);

                    for (int i = 1; i < vc.AlternateAlleles.Count; i++)
                    {
                        altAllele = vc.getAlternateAllele(i);
                        alt       = altAllele.DisplayString;
                        write(",");
                        write(alt);
                    }
                }
                else
                {
                    write(VCFConstants.EMPTY_ALTERNATE_ALLELE_FIELD);
                }
                write(VCFConstants.FIELD_SEPARATOR);

                // QUAL
                if (!vc.hasLog10PError())
                {
                    write(VCFConstants.MISSING_VALUE_v4);
                }
                else
                {
                    write(formatQualValue(vc.PhredScaledQual));
                }
                write(VCFConstants.FIELD_SEPARATOR);

                // FILTER
                string filters = getFilterString(vc);
                write(filters);
                write(VCFConstants.FIELD_SEPARATOR);

                // INFO
                IDictionary <string, string> infoFields = new SortedDictionary <string, string>();
                foreach (KeyValuePair <string, object> field in vc.Attributes)
                {
                    string key = field.Key;

                    if (!mHeader.hasInfoLine(key))
                    {
                        fieldIsMissingFromHeaderError(vc, key, "INFO");
                    }

                    string outputValue = formatVCFField(field.Value);
                    if (outputValue != null)
                    {
                        infoFields[key] = outputValue;
                    }
                }
                writeInfoString(infoFields);

                // FORMAT
                GenotypesContext gc = vc.Genotypes;
                if (gc.LazyWithData && ((LazyGenotypesContext)gc).UnparsedGenotypeData is string)
                {
                    write(VCFConstants.FIELD_SEPARATOR);
                    write(((LazyGenotypesContext)gc).UnparsedGenotypeData.ToString());
                }
                else
                {
                    IList <string> genotypeAttributeKeys = calcVCFGenotypeKeys(vc, mHeader);
                    if (genotypeAttributeKeys.Count > 0)
                    {
                        foreach (String format in genotypeAttributeKeys)
                        {
                            if (!mHeader.hasFormatLine(format))
                            {
                                fieldIsMissingFromHeaderError(vc, format, "FORMAT");
                            }
                        }

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final String genotypeFormatString = org.broad.tribble.util.ParsingUtils.join(VCFConstants.GENOTYPE_FIELD_SEPARATOR, genotypeAttributeKeys);
                        string genotypeFormatString = ParsingUtils.join(VCFConstants.GENOTYPE_FIELD_SEPARATOR, genotypeAttributeKeys);

                        write(VCFConstants.FIELD_SEPARATOR);
                        write(genotypeFormatString);

                        addGenotypeData(vc, alleleMap, genotypeAttributeKeys);
                    }
                }

                write("\n");
                // note that we cannot call flush here if we want block gzipping to work properly
                // calling flush results in all gzipped blocks for each variant
                flushBuffer();
            }
            catch (IOException e)
            {
                throw new Exception("Unable to write the VCF object to " + StreamName, e);
            }
        }
Example #36
0
 public double DoubleValue()
 {
     return(Allele.ToDouble(null));
 }
Example #37
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: private void writeAllele(Allele allele, Map<Allele, String> alleleMap) throws IOException
		private void writeAllele(Allele allele, IDictionary<Allele, string> alleleMap)
		{
			string encoding = alleleMap[allele];
			if (encoding == null)
			{
				throw new TribbleException.InternalCodecException("Allele " + allele + " is not an allele in the variant context");
			}
			write(encoding);
		}
Example #38
0
		/// <summary>
		/// Lookup the index of allele in this variant context
		/// </summary>
		/// <param name="allele"> the allele whose index we want to get </param>
		/// <returns> the index of the allele into getAlleles(), or -1 if it cannot be found </returns>
		public  int GetAlleleIndex (Allele allele)
		{
			return Alleles.IndexOf (allele);
		}
Example #39
0
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not allowed in .NET:
//ORIGINAL LINE: private final void buildAlleleMap(final org.broadinstitute.variant.variantcontext.VariantContext vc)
			private void buildAlleleMap(VariantContext vc)
			{
				// these are fast path options to determine the offsets for
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final int nAlleles = vc.getNAlleles();
				int nAlleles = vc.NAlleles;
				@ref = vc.Reference;
				alt1 = nAlleles > 1 ? vc.getAlternateAllele(0) : null;

				if (nAlleles > 2)
				{
					// for multi-allelics we need to clear the map, and add additional looks
					alleleMapForTriPlus.Clear();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.util.List<org.broadinstitute.variant.variantcontext.Allele> alleles = vc.getAlleles();
					IList<Allele> alleles = vc.Alleles;
					for (int i = 2; i < alleles.Count; i++)
					{
						alleleMapForTriPlus[alleles[i]] = i;
					}
				}
			}
Example #40
0
		/// <summary>
		/// the actual constructor.  Private access only
		/// constructors: see VariantContextBuilder
		/// </summary>
		/// <param name="source">          source </param>
		/// <param name="contig">          the contig </param>
		/// <param name="start">           the start base (one based) </param>
		/// <param name="stop">            the stop reference base (one based) </param>
		/// <param name="alleles">         alleles </param>
		/// <param name="genotypes">       genotypes map </param>
		/// <param name="log10PError">  qual </param>
		/// <param name="filters">         filters: use null for unfiltered and empty set for passes filters </param>
		/// <param name="attributes">      attributes </param>
		/// <param name="validationToPerform">     set of validation steps to take </param>
		protected internal VariantContext (string source, string ID, string contig, long start, long stop, ICollection<Allele> alleles, GenotypesContext genotypes, double log10PError, ISet<string> filters, IDictionary<string, object> attributes, bool fullyDecoded, Validation validationToPerform)
		{
			if (contig == null) {
				throw new System.ArgumentException ("Contig cannot be null");
			}
			this.contig = contig;
			this.start = start;
			this.stop = stop;

			// intern for efficiency.  equals calls will generate NPE if ID is inappropriately passed in as null
			if (ID == null || ID.Equals ("")) {
				throw new System.ArgumentException ("ID field cannot be the null or the empty string");
			}
			this.ID = ID.Equals (VCFConstants.EMPTY_ID_FIELD) ? VCFConstants.EMPTY_ID_FIELD : ID;

			this.CommonInfo = new CommonInfo (source, log10PError, filters, attributes);

			if (alleles == null) {
				throw new System.ArgumentException ("Alleles cannot be null");
			}

			// we need to make this a LinkedHashSet in case the user prefers a given ordering of alleles
			this.alleles = makeAlleles (alleles);

			if (genotypes == null || genotypes == NO_GENOTYPES) {
				this.genotypes = NO_GENOTYPES;
			} else {
				genotypes.Mutable = false;
				this.genotypes = genotypes;
			}

			// cache the REF and ALT alleles
			int nAlleles = alleles.Count;
			foreach (Allele a in alleles) {
				if (a.Reference) {
					REF = a;
				} // only cache ALT when biallelic
				else if (nAlleles == 2) {
					ALT = a;
				}
			}

			this.FullyDecoded = fullyDecoded;
			validate (validationToPerform);
		}
Example #41
0
 public int CompareTo(CharacterGene that)
 {
     return(Allele.CompareTo(that.Allele));
 }
Example #42
0
 public AlleleViewModel(Allele allele)
     : base(allele)
 {
     this.allele = allele;
 }
Example #43
0
		public  int[] GetGLIndecesOfAlternateAllele (Allele targetAllele)
		{
			int index = GetAlleleIndex (targetAllele);
			if (index == -1) {
				throw new System.ArgumentException ("Allele " + targetAllele + " not in this VariantContex " + this);
			}
			return GenotypeLikelihoods.getPLIndecesOfAlleles (0, index);
		}
Example #44
0
        public void ctor_ValueRange_ShouldNotBeNull()
        {
            var sut = new Allele();

            sut.ValueRange.Should().NotBeNull();
        }
Example #45
0
		/// <returns> True if this context contains Allele allele, or false otherwise </returns>
		public  bool HasAllele (Allele allele)
		{
			return hasAllele (allele, false, true);
		}
Example #46
0
        public void ctor_ShouldNotBeNull()
        {
            var sut = new Allele();

            sut.Should().NotBeNull();
        }
Example #47
0
		public  bool HasAlternateAllele (Allele allele)
		{
			return hasAllele (allele, false, false);
		}
Example #48
0
 public int IntValue()
 {
     return(Allele.ToInt32(null));
 }
Example #49
0
		private bool hasAllele (Allele allele, bool ignoreRefState, bool considerRefAllele)
		{
			if ((considerRefAllele && allele == REF) || allele == ALT) { // optimization for cached cases
				return true;
			}

			IList<Allele> allelesToConsider = considerRefAllele ? Alleles : AlternateAlleles;
			foreach (Allele a in allelesToConsider) {
				if (a.Equals (allele, ignoreRefState)) {
					return true;
				}
			}

			return false;
		}
Example #50
0
 public long LongValue()
 {
     return(Allele.ToInt64(null));
 }
Example #51
0
		/// <summary>
		/// Returns the number of chromosomes carrying allele A in the genotypes
		/// </summary>
		/// <param name="a"> allele </param>
		/// <param name="sampleIds"> - IDs of samples to take into account. If empty then all samples are included. </param>
		/// <returns> chromosome count </returns>
		public int GetCalledChrCount (Allele a, ISet<string> sampleIds)
		{
			int n = 0;
			GenotypesContext genotypes = sampleIds.Count == 0 ? Genotypes : GetGenotypes (sampleIds);
			foreach (Genotype g in genotypes) {
				n += g.countAllele (a);
			}
			return n;
		}
 public void validateReferenceBases(Allele reportedReference, Allele observedReference)
 {
     if (reportedReference != null && !reportedReference.BasesMatch(observedReference))
     {
         throw new Exception(string.Format("the REF allele is incorrect for the record at position {0}:{1:D}, fasta says {2} vs. VCF says {3}", Chr, Start, observedReference.BaseString, reportedReference.BaseString));
     }
 }