public static Leaf GetLeafInstance(StreamReader streamreader)
        {
            StringBuilder sb = new StringBuilder();

            while (true)
            {
                char peek = Peek(streamreader);
                if (peek == ':')
                {
                    break;
                }
                SpecialFunctions.CheckCondition(!("()".Contains(peek.ToString())));
                sb.Append(Read(streamreader));
            }

            Leaf leaf = new Leaf();

            leaf.CaseName = sb.ToString();
            if (leaf.CaseName.Contains("->")) //!!!const
            {
                int pos = leaf.CaseName.IndexOf("->");
                Debug.Assert(pos >= 0); // real assert
                int nodeId = int.Parse(leaf.CaseName.Substring(0, pos));
                leaf.CaseName = leaf.CaseName.Substring(pos + 2);
                Debug.WriteLine(SpecialFunctions.CreateTabString("NodeId", nodeId));
            }
            return(leaf);
        }
        private static void BinarySearchForNonInfiniteEvaluation(
            double nonInfInput, double nonInfOutput,
            double infInput, double infOutput,
            out double bestInput, out double bestOutput,
            //FuncEval nonInfiniteEval, FuncEval infiniteEval,
            Converter <double, double> oneDRealFunctionInSearchSpace, double inputTol, double outputTol)
        {
            SpecialFunctions.CheckCondition(!double.IsInfinity(nonInfOutput));

            double mid    = (nonInfInput + infInput) / 2.0;
            double fOfMid = oneDRealFunctionInSearchSpace(mid);

            //FuncEval mid = new FuncEval((nonInfiniteEval.X + infiniteEval.X) / 2, oneDRealFunctionInSearchSpace);

            Debug.WriteLine(string.Format("Binary search: f({0}) = {1}, f({2}) = {3}", nonInfInput, nonInfOutput, infInput, infOutput));
            if (Math.Abs(fOfMid - nonInfOutput) < outputTol)
            {
                Debug.Assert(!double.IsInfinity(fOfMid));
                bestInput  = mid;
                bestOutput = fOfMid;
            }
            else if (Math.Abs(mid - nonInfInput) < inputTol)
            {
                bestInput  = nonInfInput;
                bestOutput = nonInfOutput;
            }
            else if (double.IsInfinity(fOfMid))
            {
                BinarySearchForNonInfiniteEvaluation(nonInfInput, nonInfOutput, mid, fOfMid, out bestInput, out bestOutput, oneDRealFunctionInSearchSpace, inputTol, outputTol);
            }
            else
            {
                BinarySearchForNonInfiniteEvaluation(mid, fOfMid, infInput, infOutput, out bestInput, out bestOutput, oneDRealFunctionInSearchSpace, inputTol, outputTol);
            }
        }
Пример #3
0
        internal static KeyValuePair <MerAndHlaToLength, bool> GetRandomInstance(MerAndHlaToLength[] originalTrainingKeysAsArray, bool label, Random random)
        {
            MerAndHlaToLength hlaModel = originalTrainingKeysAsArray[random.Next(originalTrainingKeysAsArray.Length)];

            MerAndHlaToLength aMerAndHlaToLength = new MerAndHlaToLength();

            aMerAndHlaToLength.HlaToLength = hlaModel.HlaToLength;
            //aMerAndHlaToLength.Study = hlaModel.Study;
            aMerAndHlaToLength.KmerDefinition = hlaModel.KmerDefinition;
            int merLength = hlaModel.Mer.Length;

            char[] rgchMer = new char[hlaModel.Mer.Length];
            for (int iMer = 0; iMer < rgchMer.Length; ++iMer)
            {
                MerAndHlaToLength merModel = originalTrainingKeysAsArray[random.Next(originalTrainingKeysAsArray.Length)];
                SpecialFunctions.CheckCondition(merLength == merModel.Mer.Length); //!!!raise error - the selection will not be uniform unless all are off the same length
                rgchMer[iMer] = merModel.Mer[random.Next(merLength)];
            }
            aMerAndHlaToLength.Mer = new string(rgchMer);

            KeyValuePair <MerAndHlaToLength, bool> aMerAndHlaToLengthWithLabel
                = new KeyValuePair <MerAndHlaToLength, bool>(aMerAndHlaToLength, label);

            return(aMerAndHlaToLengthWithLabel);
        }
Пример #4
0
        private bool CoreIsMoreGeneralThan(AASet c1, AASet c2)
        {
            SpecialFunctions.CheckCondition(IsCore(c1) && IsCore(c2));             //!!!raise error
            bool b = ((c1 & (~c2)) != AASet.Empty);

            return(b);
        }
 private static bool ExtractFlankSize(out int flankSize, string featurerizerName, params string[] mainNameCollection)
 {
     //!!!should use Regex
     foreach (string mainName in mainNameCollection)
     {
         if (featurerizerName.Equals(mainName))
         {
             flankSize = 0;
             return(true);
         }
         if (featurerizerName.StartsWith(mainName))
         {
             string rest = featurerizerName.Substring(mainName.Length);
             if (!rest.StartsWith("."))
             {
                 continue;
             }
             SpecialFunctions.CheckCondition(rest.Length >= 2, "Expect '.NUMBER' after main name of featurizer");
             flankSize = int.Parse(rest.Substring(1));
             return(true);
         }
     }
     flankSize = int.MinValue;
     return(false);
 }
Пример #6
0
 public GeneticCodeMapping(string codon, string aminoAcid, bool normal)
 {
     SpecialFunctions.CheckCondition(codon.Length == 3);             //!!!raise error
     Codon     = codon;
     AminoAcid = aminoAcid;
     Normal    = normal;
 }
Пример #7
0
        private void LoadUpPredictor(string modelName, int eLength, int ncLength, Converter <Hla, Hla> hlaForNormalization)
        {
            //Load up the predictor

            string featurerizerName;

            switch (modelName.ToLower())
            {
            //!!!would be better not to have multiple of these switch statements around - looks like a job for a Class
            case "lanliedb03062007":
                featurerizerName   = "[email protected]";
                SampleNEC          = NEC.GetInstance("", new string(' ', eLength), "");
                HlaFactory         = HlaFactory.GetFactory("MixedWithB15AndA68");
                SourceDataFileName = "lanlIedb03062007.pos.source.txt";
                NameList           = new string[] { "LANL", "IEDB" };
                break;

            default:
                SpecialFunctions.CheckCondition(false, "Don't know what featurerizer to use for the model");
                featurerizerName   = null;
                SourceDataFileName = null;
                NameList           = null;
                break;
            }
            Converter <object, Set <IHashableFeature> > featurizer = FeatureLib.CreateFeaturizer(featurerizerName);

            //GeneratorType generatorType = GeneratorType.ComboAndZero6SuperType;
            //FeatureSerializer featureSerializer = PositiveNegativeExperimentCollection.GetFeatureSerializer();
            //KmerDefinition = kmerDefinition;
            //HlaResolution hlaResolution = HlaResolution.ABMixed;
            string resourceName = string.Format("maxentModel{0}{1}{2}{3}.xml", modelName.Split('.')[0], SampleNEC.N.Length, SampleNEC.E.Length, SampleNEC.C.Length);

            EpitopeLearningDataList = new List <EpitopeLearningDataDupHlaOK>();
            using (StreamReader streamReader = Predictor.OpenResource(resourceName))
            {
                Logistic = (Logistic)FeatureLib.FeatureSerializer.FromXmlStreamReader(streamReader);
                //Logistic.FeatureGenerator = EpitopeFeatureGenerator.GetInstance(KmerDefinition, generatorType, featureSerializer).GenerateFeatureSet;
                Logistic.FeatureGenerator = FeatureLib.CreateFeaturizer(featurerizerName);
                foreach (string name in NameList)
                {
                    EpitopeLearningData epitopeLearningDataX = EpitopeLearningData.GetDbWhole(HlaFactory, SampleNEC.E.Length, name, SourceDataFileName);
                    Debug.Assert(epitopeLearningDataX.Count > 0, "Expect given data to have some data");
                    //!!!combine with previous step
                    EpitopeLearningDataDupHlaOK epitopeLearningData = new EpitopeLearningDataDupHlaOK(epitopeLearningDataX.Name);
                    foreach (KeyValuePair <Pair <string, Hla>, bool> merAndHlaAndLabel in epitopeLearningDataX)
                    {
                        Hla hlaIn  = merAndHlaAndLabel.Key.Second;
                        Hla hlaOut = hlaForNormalization(hlaIn);

                        Dictionary <Hla, Dictionary <Hla, bool> > hla2ToHlaToLabel = SpecialFunctions.GetValueOrDefault(epitopeLearningData, merAndHlaAndLabel.Key.First);
                        Dictionary <Hla, bool> hlaToLabel = SpecialFunctions.GetValueOrDefault(hla2ToHlaToLabel, hlaOut);
                        hlaToLabel.Add(hlaIn, merAndHlaAndLabel.Value);
                    }

                    EpitopeLearningDataList.Add(epitopeLearningData);
                }
            }

            HlaForNormalization = hlaForNormalization;
        }
        private static string SetSupertypeAny(Hla hla, SupertypeSpec hasBlanks)
        {
            switch (hasBlanks)
            {
            case SupertypeSpec.HasBlanksTrue:
            {
                HlaToLength hlaToLength  = HlaToLength.GetInstanceABMixed(hla.Name);
                string      supertypeAny = hlaToLength.ToZero6SupertypeBlanksString();
                return(supertypeAny);
            }

            case SupertypeSpec.HasBlanksFalse:
            {
                HlaToLength hlaToLength  = HlaToLength.GetInstanceABMixed(hla.Name);
                string      supertypeAny = hlaToLength.ToZero6SupertypeNoBlanksString();
                return(supertypeAny);
            }

            case SupertypeSpec.None:
                return("none");    //!!!const

            default:
                SpecialFunctions.CheckCondition(false, "unknown SupertypeSpec: " + hasBlanks.ToString());
                return(null);
            }
        }
Пример #9
0
        static HlaAssignMain CreateProgramFromArguments(string[] args)
        {
            ArgCollection argCollection = ArgCollection.GetInstance(args);

            if (argCollection.ExtractOptionalFlag("help"))
            {
                Console.WriteLine();
                Console.WriteLine(UsageMessage);
                Console.WriteLine(HelpMessage);
                return(null);
            }

            bool bExcel = argCollection.ExtractOptionalFlag("EXCEL");

            argCollection.CheckNoMoreOptions();

            double?leakProbabilityOrNull = argCollection.ExtractNext <double?>("leakProbabilityOrNull");
            double pValue = argCollection.ExtractNext <double>("pValue");

            string directoryName = argCollection.ExtractNext <string>("directory");
            string caseName      = argCollection.ExtractNext <string>("caseName");

            string          hlaFactoryName  = argCollection.ExtractNext <string>("hlaFactory");
            RangeCollection pieceIndexRange = argCollection.ExtractNext <RangeCollection>("pieceIndexRange");
            int             pieceCount      = argCollection.ExtractNext <int>("pieceCount");

            SpecialFunctions.CheckCondition(0 <= pieceIndexRange.FirstElement && pieceIndexRange.LastElement < pieceCount, "The pieceIndexRange must be a subrange of " + RangeCollection.GetInstance(0, pieceCount - 1).ToString());
            RangeCollection nullIndexRange = argCollection.ExtractNext <RangeCollection>("nullIndexRange");

            argCollection.CheckThatEmpty();

            return(new HlaAssignMain(bExcel, leakProbabilityOrNull, pValue, directoryName, caseName, hlaFactoryName, pieceIndexRange, pieceCount, nullIndexRange));
        }
Пример #10
0
        public HlaMsr1 GetGroundInstance(string name, ref HashSet <string> warningSet)
        {
            HlaMsr1 hla = (HlaMsr1)GetGroundOrAbstractInstance(name, ref warningSet);

            SpecialFunctions.CheckCondition(hla.IsGround, "Hla is not ground. " + name);
            return(hla);
        }
        private IEnumerable <int> KEnumeration(MerLength merLength, int inputPeptideLength)
        {
            switch (merLength)
            {
            case MerLength.scan:
                for (int k = (int)MerLength.firstLength; k <= (int)MerLength.lastLength; ++k)
                {
                    yield return(k);
                }
                break;

            case MerLength.given:
                int inputEpitopeLength = inputPeptideLength - NCLength - NCLength;
                SpecialFunctions.CheckCondition((int)MerLength.firstLength <= inputEpitopeLength && inputEpitopeLength <= (int)MerLength.lastLength,
                                                string.Format("Given peptide length {0} is out of range", inputPeptideLength));
                yield return(inputEpitopeLength);

                break;

            default:
                SpecialFunctions.CheckCondition(MerLength.firstLength <= merLength && merLength <= MerLength.lastLength,
                                                string.Format("Given peptide length {0} is out of range", (int)merLength));
                yield return((int)merLength);

                break;
            }
        }
Пример #12
0
        internal IEnumerable <HlaMsr1> GeneralizationList(HlaMsr1Factory hlaMsr1Factory)
        {
            HashSet <string> warningSetToIgnore = new HashSet <string>();

            SpecialFunctions.CheckCondition(IsGround, "Can only get generalization list for ground hlas");
            if (Name.Length == 5)
            {
                yield return(this);
            }
            if (Name.Length >= 3)
            {
                string twoDigit = Name.Substring(0, 3);
                if (HlaMsr1Factory.MoreThan100.ContainsKey(twoDigit))
                {
                    twoDigit = ClassName + HlaMsr1Factory.MoreThan100[twoDigit];
                }
                yield return((HlaMsr1)hlaMsr1Factory.GetGroundOrAbstractInstance(twoDigit, ref warningSetToIgnore));

                Debug.Assert(warningSetToIgnore.Count == 0); // real assert
            }

            yield return((HlaMsr1)hlaMsr1Factory.GetGroundOrAbstractInstance(ClassName, ref warningSetToIgnore));

            Debug.Assert(warningSetToIgnore.Count == 0); // real assert
        }
Пример #13
0
        static public PatchPatternFactory GetFactory(string language)
        {
            SpecialFunctions.CheckCondition(language == "strings", "patch language must be 'strings'");
            PatchPatternFactory patchPatternFactory = new PatchStringFactory();

            return(patchPatternFactory);
        }
        static public AASet UnifyOrEmpty(AASet c1, AASet c2)
        {
            SpecialFunctions.CheckCondition(!AASetSequence.IsOptional(c1) && !AASetSequence.IsOptional(c2));             //!!!raise error
            AASet result = c1 & c2;

            return(result);
        }
        static public HlaFactory GetFactory(string name)
        {
            HlaFactory hlaFactory;

            //!!!switch to switch
            if (name == "noConstraints")
            {
                hlaFactory = new NoConstraints();
            }
            else if (name == "MixedWithB15AndA68")
            {
                hlaFactory = new MixedWithB15AndA68();
            }
            else if (name == "FourDigit")
            {
                hlaFactory = new FourDigit();
            }
            else if (name == "JustSlash")
            {
                hlaFactory = new JustSlash();
            }
            else
            {
                SpecialFunctions.CheckCondition(false, "Don't know how to create HlaFactory " + name);
                hlaFactory = null;
            }
            hlaFactory.Name = name;
            return(hlaFactory);
        }
        void stopButton_Click(object sender, RoutedEventArgs e)
        {
            SpecialFunctions.CheckCondition(stopButton.IsEnabled, "expect stopButton to be enabled");
            switch ((string)stopButton.Content)
            {
            case "Pause":     //!!!Const
            {
                CompositionTarget.Rendering -= CurrentRenderingDelegate;
                stopButton.Content           = "Continue";
                showLastCheckBox.IsEnabled   = true;
                break;
            }

            case "Continue":     //!!!Const
            {
                stopButton.Content           = "Pause";
                CompositionTarget.Rendering += CurrentRenderingDelegate;
                showLastCheckBox.IsEnabled   = false;
                break;
            }

            default:
            {
                SpecialFunctions.CheckCondition(false, "Don't know state " + stopButton.Content);
                break;
            }
            }
        }
        //private bool AllVarianceZero(Dictionary<string, GaussianStatistics> caseNameToTarget)
        private static bool AllVarianceZero(IEnumerable <Leaf> LeafCollection, Converter <Leaf, SufficientStatistics> caseNameToTarget)
        {
            bool varianceIsZero = false; //If empty input, then return false
            bool firstTime      = true;

            foreach (Leaf leaf in LeafCollection)
            {
                SufficientStatistics stats = caseNameToTarget(leaf);
                if (stats.IsMissing())
                {
                    continue;
                }
                GaussianStatistics gaussianStatistics = (GaussianStatistics)stats;
                SpecialFunctions.CheckCondition((gaussianStatistics.Variance == 0) == (gaussianStatistics.SampleSize == 1), "Variance must be zero exactly when the sample size is 1");
                if (firstTime)
                {
                    firstTime      = false;
                    varianceIsZero = (gaussianStatistics.Variance == 0);
                }
                else
                {
                    SpecialFunctions.CheckCondition(varianceIsZero == (gaussianStatistics.Variance == 0), "If any variances are zero, then all must be zero");
                }
            }
            return(varianceIsZero);
        }
Пример #18
0
        public static OneDOptimization GetInstance(string optimizerName)
        {
            //Console.WriteLine("Using {0} for 1D optimization.", optimizerName);
            if (optimizerName.Equals("default", StringComparison.CurrentCultureIgnoreCase))
            {
                optimizerName = "brentthengrid";
            }

            optimizerName = optimizerName.ToLower();
            if (optimizerName == "grid")
            {
                return(new OneDGrid());
            }

            string brentwithnogrid = "brentwithnogrid";

            if (optimizerName.StartsWith(brentwithnogrid))
            {
                double tol = GetTolOrDefault(optimizerName, brentwithnogrid);
                return(new Brent(tol));
            }

            string brentthengrid = "brentthengrid";

            if (optimizerName.StartsWith(brentthengrid))
            {
                double tol = GetTolOrDefault(optimizerName, brentthengrid);
                return(new BrentThenGrid(tol));
            }

            SpecialFunctions.CheckCondition(false, string.Format("The optimizer named {0} is no known", optimizerName));
            return(null);
        }
        internal static PatchTable GetInstanceWithUniformWeights(VaccineMaker vaccineMaker)
        {
            SpecialFunctions.CheckCondition(vaccineMaker is Greedy);
            Greedy greedy = (Greedy)vaccineMaker;

            return(GetInstanceWithUniformWeightByLength(PatchPatternCollection(greedy)));
        }
Пример #20
0
        static public HlaToLength GetInstanceABMixed(string hlaPattern)
        {
            HlaToLength aHlaToLength = new HlaToLength();

            aHlaToLength.HlaResolution = HlaResolution.ABMixed;

            if (HlaResolution.TwoDigitHlaPatternIsOK(hlaPattern))
            {
                aHlaToLength._hlaClass          = hlaPattern.Substring(0, 1);
                aHlaToLength._hlaNumberToLength = int.Parse(hlaPattern.Substring(1));
                SpecialFunctions.CheckCondition(aHlaToLength._hlaClass != "B" || aHlaToLength._hlaNumberToLength != 15);                 //!!!raise error
                SpecialFunctions.CheckCondition(aHlaToLength._hlaClass != "A" || aHlaToLength._hlaNumberToLength != 68);                 //!!!raise error
            }
            else
            {
                HlaToLength hlaToLengthFour = GetInstanceFour(hlaPattern);
                int         twoDigits       = hlaToLengthFour.TwoDigits();
                if ((twoDigits == 15 && hlaToLengthFour.HlaClass == "B") || (twoDigits == 68 && hlaToLengthFour.HlaClass == "A"))
                {
                    aHlaToLength._hlaClass          = hlaToLengthFour.HlaClass;
                    aHlaToLength._hlaNumberToLength = hlaToLengthFour._hlaNumberToLength;
                }
                else
                {
                    aHlaToLength._hlaClass          = hlaToLengthFour.HlaClass;
                    aHlaToLength._hlaNumberToLength = twoDigits;
                }
            }
            return(aHlaToLength);
        }
Пример #21
0
//		public bool IsLessGeneralThan(Disjunct other)
//		{
//			SpecialFunctions.CheckCondition(this != other); //!!! raise error
//			SpecialFunctions.CheckCondition(FullAsString != other.FullAsString); //!!! raise error
//
//			bool b = CoreIsLessGeneralThan(other) && BeforeOrAfterIsLessGeneralThan(Before, other.Before) && BeforeOrAfterIsLessGeneralThan(After, other.After);
//			return b;
//		}

//		private bool CoreIsLessGeneralThan(Disjunct other)
//		{
//			SpecialFunctions.CheckCondition(Core.Count == other.Core.Count); //!!! raise error
//			bool bAtLeastOneCharOfOtherIsMoreGeneral = false;
//			for(int i = 0; i < Core.Count; ++i)
//			{
//				AASet cMe = Core[i];
//				AASet cOther = other.Core[i];
//				if (CoreIsMoreGeneralThan(cMe, cOther))
//				{
//					return false;
//				}
//				else if (CoreIsMoreGeneralThan(cOther, cMe))
//				{
//					bAtLeastOneCharOfOtherIsMoreGeneral = true;
//				}
//			}
//			return bAtLeastOneCharOfOtherIsMoreGeneral;
//		}

//		static private bool BeforeOrAfterIsLessGeneralThan(AASetSequence flanking1, AASetSequence flanking2)
//		{
//			if (flanking1.Count > flanking2.Count)
//			{
//				return false;
//			}
//
//			bool bAtLeastOneCharOfOtherIsMoreGeneral = (flanking2.Count > flanking1.Count);
//			for(int i = 0; i < flanking1.Count; ++i)
//			{
//				AASet c1 = flanking1[i];
//				AASet c2 = flanking2[i];
//				if (BeforeOrAfterIsMoreGeneralThan(c1, c2))
//				{
//					return false;
//				}
//				else if (BeforeOrAfterIsMoreGeneralThan(c2, c1))
//				{
//					bAtLeastOneCharOfOtherIsMoreGeneral = true;
//				}
//			}
//			return bAtLeastOneCharOfOtherIsMoreGeneral;
//		}



        static private bool BeforeOrAfterIsMoreGeneralThan(AASet c1, AASet c2)
        {
            SpecialFunctions.CheckCondition(!IsCore(c1) && !IsCore(c2));             //!!!raise error
            bool b = (c1 == AASet.OptionalAny && c2 != AASet.OptionalAny);

            return(b);
        }
Пример #22
0
        public string ToZero6SupertypeNoBlanksString()
        {
            SpecialFunctions.CheckCondition(HlaResolution == HlaResolution.ABMixed, "Currently, supertype is only defined for ABMixed");
            string asString = ToString();

            return(ToZero6SupertypeNoBlanksString(asString));
        }
Пример #23
0
        public bool IsLessGeneralThan(Disjunct other)
        {
            SpecialFunctions.CheckCondition(this != other);                      //!!! raise error
            SpecialFunctions.CheckCondition(FullAsString != other.FullAsString); //!!! raise error

            bool falseForSure;
            bool bAtLeastOneCharOfOtherIsMoreGeneral = false;

            CoreIsLessGeneralThan(other, out falseForSure, ref bAtLeastOneCharOfOtherIsMoreGeneral);
            if (falseForSure)
            {
                return(false);
            }

            BeforeOrAfterIsLessGeneralThan(Before, other.Before, out falseForSure, ref bAtLeastOneCharOfOtherIsMoreGeneral);
            if (falseForSure)
            {
                return(false);
            }

            BeforeOrAfterIsLessGeneralThan(After, other.After, out falseForSure, ref bAtLeastOneCharOfOtherIsMoreGeneral);
            if (falseForSure)
            {
                return(false);
            }
            ;

            return(bAtLeastOneCharOfOtherIsMoreGeneral);
        }
Пример #24
0
        static public HlaToLength GetInstance(string hlaPattern, HlaResolution hlaResolution)
        {
            HlaToLength aHlaToLength = hlaResolution.GetHlaLengthInstance(hlaPattern);

            SpecialFunctions.CheckCondition(aHlaToLength != null);
            return(aHlaToLength);
        }
        private static bool ExtractFlankSize(out int flankSize, out string given, string featurerizerName, params string[] mainNameCollection)
        {
            //!!!should use regex
            int posGiven = featurerizerName.IndexOf('@');

            if (posGiven < 0)
            {
                given     = null;
                flankSize = int.MinValue;
                return(false);
            }

            string prefix = featurerizerName.Substring(0, posGiven + 1);
            int    posDot = featurerizerName.IndexOf('.');

            SpecialFunctions.CheckCondition(posDot >= 0 && posDot > posGiven, "'Given' features must have an explicit '.FlankSize'");

            given = featurerizerName.Substring(posGiven + 1, posDot - posGiven - 1);

            string flankSizeAsString = featurerizerName.Substring(posDot + 1);

            flankSize = int.Parse(flankSizeAsString);

            foreach (string mainName in mainNameCollection)
            {
                if (prefix.Equals(mainName))
                {
                    return(true);
                }
            }
            return(false);
        }
        /// <summary>
        /// Read table from http://users.rcn.com/jkimball.ma.ultranet/BiologyPages/C/Codons.html
        /// </summary>
        private void ReadTheGeneticCode()
        {
            Debug.Assert(CodonToAminoAcid == null);             // real assert
            CodonToAminoAcid    = new Dictionary <string, GeneticCodeMapping>();
            AminoAcidCollection = new Dictionary <string, bool>();

            //!!!could load these into memory instead of reading them over and over again
            string sTheGenenicCodeFile = @"GeneticCodeDna.txt";             //!!!const

            using (StreamReader streamreaderTheGenenicCodeFile = OpenResource(sTheGenenicCodeFile))
            {
                string sLine = null;
                while (null != (sLine = streamreaderTheGenenicCodeFile.ReadLine()))
                {
                    string[] rgFields = sLine.Split('\t');
                    SpecialFunctions.CheckCondition(rgFields.Length == 3);            //!!!raise error
                    string sCodon = rgFields[0];
                    SpecialFunctions.CheckCondition(sCodon.Length == 3);              //!!!raise error
                    string             sAminoAcid          = rgFields[1];
                    bool               bNormal             = bool.Parse(rgFields[2]); //!!!could raise error
                    GeneticCodeMapping aGeneticCodeMapping = new GeneticCodeMapping(sCodon, sAminoAcid, bNormal);
                    CodonToAminoAcid.Add(sCodon, aGeneticCodeMapping);

                    if (!AminoAcidCollection.ContainsKey(sAminoAcid))
                    {
                        AminoAcidCollection.Add(sAminoAcid, true);
                    }
                }
            }
        }
Пример #27
0
        // !! Add support for ModelTesterGaussian
        public static NullDataGenerator GetInstance(string generatorName, ModelScorer modelScorer, IDistribution distribution)
        {
            switch (generatorName.ToLower())
            {
            case "predictorpermutation":
                return(new NullDataGeneratorPredictorPermutation());

            case "targetpermutation":
                return(new NullDataGeneratorTargetPermutation());

            case "predictorparametric":
                //!!HACK!! We can currently only evolve binary data. But even if modelTester is gaussian, the predictor is still binary.
                // so all we need is a discrete model tester with any distribution (they all have the same null distribution, which is all
                // that's used.
                SpecialFunctions.CheckCondition(distribution is DistributionDiscrete, "Parametric data generation is currently only supported for discrete variables");
                return(new NullDataGeneratorPredictorParametric(modelScorer, (DistributionDiscrete)distribution));

            case "targetparametric":
                SpecialFunctions.CheckCondition(distribution is DistributionDiscrete, "Parametric data generation is currently only supported for discrete variables");
                return(new NullDataGeneratorTargetParametric(modelScorer, (DistributionDiscrete)distribution));

            default:
                throw new ArgumentException("Cannot parse " + generatorName + " into a NullDataGenerator");
            }
        }
        //public AAMatch Match(SimpleAminoAcidSet aminoAcidCollection2)
        //{
        //    Debug.Fail("Be sure this has Match defined the desired way");

        //    Debug.Assert(false); //!!!where is this called?
        //    if (this == null || aminoAcidCollection2 == null) //!!!const
        //    {
        //        return AAMatch.NA;
        //    }

        //    if (PositiveCount != 1 || aminoAcidCollection2.PositiveCount() != 1)
        //    {
        //        return AAMatch.FALSE;
        //    }

        //    // There is only one item
        //    foreach (string s in Positives)
        //    {
        //        if (aminoAcidCollection2.Contains(s))
        //        {
        //            return AAMatch.TRUE;
        //        }
        //        else
        //        {
        //            return AAMatch.FALSE;
        //        }
        //    }
        //    Debug.Assert(false);
        //    return AAMatch.NA;
        //}


        static public AAMatch Match(string sAminoAcid, string sAminoAcidPatientHiv)
        {
            SpecialFunctions.CheckCondition(sAminoAcid != "<none>");                       //!!!const //!!! raise error
            SpecialFunctions.CheckCondition(!sAminoAcid.StartsWith("Not an amino acid:")); //!!!const //!!!raise error
            //Debug.Assert(sAminoAcid.Length == 3 || sAminoAcid == "STOP"); //!!!const


            if (sAminoAcidPatientHiv == "<none>") //!!!const
            {
                return(AAMatch.NA);
            }
            if (sAminoAcidPatientHiv == sAminoAcid)
            {
                // Being equal is a match only if they are not ambiguous
                if (sAminoAcid == "Ambiguous Amino Acid") //!!!const
                {
                    return(AAMatch.FALSE);
                }
                else
                {
                    return(AAMatch.TRUE);
                }
            }
            else
            {
                Debug.Assert(sAminoAcidPatientHiv != null); //real assert
                return(AAMatch.FALSE);
            }
        }
Пример #29
0
        private static string LanlFileNormalizedOutput(string fileSuffix, HlaResolution hlaResolution)
        {
            SpecialFunctions.CheckCondition(fileSuffix == "Lanl");                                               //!!!raise error
            string sInputFileName = string.Format(@"lanl-{0}digit.Normalized.new.txt", hlaResolution.ShortName); //!!!const

            return(sInputFileName);
        }
        public override HlaToLength GetHlaLengthInstanceWithFixup(string name)
        {
            Match aMatch = HlaParseRegex.Match(name);

            SpecialFunctions.CheckCondition(aMatch.Success);
            string theClass = aMatch.Groups["class"].Value;
            string num      = aMatch.Groups["number"].Value;
            string s        = null;

            if (num.Length == 4)
            {
                s = string.Format("{0}{1}", theClass[0], num);
            }
            else
            {
                SpecialFunctions.CheckCondition(false);
            }
            return(GetHlaLengthInstance(s));

            /*
             * HLA-A*0201
             * HLA-A*1101
             * HLA-B*0801
             * HLA-B*2705
             * HLA-B*2709
             * HLA-B*3501
             * HLA-B*4402
             * HLA-B*4403
             * HLA-B*5101
             * HLA-B*5301
             * HLA-CW*3
             * HLA-CW*4
             */
        }