Ejemplo n.º 1
0
        public void TestGetAllIsotopePeaks()
        {
            var methodName = MethodBase.GetCurrentMethod().Name;
            TestUtils.ShowStarting(methodName);

            const string specFilePath = @"H:\Research\GlycoTopDown\raw\User_sample_test_02252015.raw";
            if (!File.Exists(specFilePath))
            {
                Assert.Ignore(@"Skipping test {0} since file not found: {1}", methodName, specFilePath);
            }
            
            //const int scanNum = 17338;
            const double relativeIntensity = 0.1;
            var run = PbfLcMsRun.GetLcMsRun(specFilePath);
            var spec = run.GetSpectrum(17338);

            var comp = Composition.Parse("C(610) H(945) N(172) O(189) S(3)");
            var ion = new Ion(comp + BaseIonType.B.OffsetComposition, 9);   // b127(9+)
            Console.WriteLine("Composition: " + comp + " " + comp.Mass);
            Console.WriteLine("b127(9+): " + ion.GetMonoIsotopicMz());
            Console.WriteLine("b127(9+) 0th isotope: " + ion.GetIsotopeMz(0));
            Console.WriteLine("b127(9+) 6th isotope: " + ion.GetIsotopeMz(6));

            var peaks = spec.GetAllIsotopePeaks(ion, new Tolerance(10), relativeIntensity);
            var isotopes = ion.GetIsotopes(relativeIntensity).ToArray();

            for (var i = 0; i < isotopes.Length; i++)
            {
                if (peaks[i] == null) continue;
                var isotopeIndex = isotopes[i].Index;
                Console.WriteLine("{0}\t{1}\t{2}\t{3}", isotopeIndex, peaks[isotopeIndex].Mz, ion.GetIsotopeMz(isotopeIndex), GetPeakPpmError(peaks[isotopeIndex], ion.GetIsotopeMz(isotopeIndex)));
            }
        }
Ejemplo n.º 2
0
        public void TestFitScoreCalculationCid()
        {
            var methodName = MethodBase.GetCurrentMethod().Name;
            TestUtils.ShowStarting(methodName);

            if (!File.Exists(TestLcMsRun.TestTopDownRawFilePathCid))
            {
                Assert.Ignore(@"Skipping test " + methodName + @" since file not found: " + TestLcMsRun.TestTopDownRawFilePathCid);
            }

            var run = InMemoryLcMsRun.GetLcMsRunScanRange(TestLcMsRun.TestTopDownRawFilePathCid, 5743, 5743);
            var spec = run.GetSpectrum(5743);
            Assert.True(spec != null);

            const string protein = "MRIILLGAPGAGKGTQAQFIMEKYGIPQISTGDMLRAAVKSGSELGKQAKDIMDAGKLVTDELVIALVKERIAQEDCRNGFLLDGFPRTIPQADAMKEAGIVVDYVLEFDVPDELIVDRIVGRRVHAASGRVYHVKFNPPKVEGKDDVTGEDLTTRKDDQEETVRKRLVEYHQMTAPLIGYYQKEAEAGNTKYAKVDGTQAVADVRAALEKILG";
            var protComp = new AminoAcidSet().GetComposition(protein) + Composition.H2O;
            Assert.True(protComp != null);
            Assert.True(protComp.C == 1035);
            Assert.True(protComp.H == 1683);
            Assert.True(protComp.N == 289);
            Assert.True(protComp.O == 318);
            Assert.True(protComp.P == 0);
            Assert.True(protComp.S == 7);
            Assert.True(Math.Abs(protComp.Mass - 23473.245267145) < 0.0000001);
            Assert.True(protComp.NominalMass == 23461);

            var ion = new Ion(protComp, 20);
//            ion.Composition.ComputeApproximateIsotopomerEnvelop();
            var isotopomerEnvelop = ion.Composition.GetIsotopomerEnvelopeRelativeIntensities();
            Console.WriteLine(@"MonoMz: {0}, MonoMass: {1}", ion.GetMonoIsotopicMz(), ion.Composition.Mass);

            var matchedPeaks = spec.GetAllIsotopePeaks(ion, new Tolerance(15), 0.1);
            for (var i = 0; i < matchedPeaks.Length; i++)
            {
                Console.WriteLine(@"{0}	{1}	{2}	{3}", i, ion.GetIsotopeMz(i), isotopomerEnvelop[i], matchedPeaks[i] == null ? 0 : matchedPeaks[i].Intensity);
            }
            var fitScore = spec.GetFitScore(ion, new Tolerance(15), 0.1);
            var cosine = spec.GetConsineScore(ion, new Tolerance(15), 0.1);
            var corr = spec.GetCorrScore(ion, new Tolerance(15), 0.1);

            Console.WriteLine(@"FitScore: {0}", fitScore);
            Console.WriteLine(@"Cosine: {0}", cosine);
            Console.WriteLine(@"Corr: {0}", corr);

            Assert.True(Math.Abs(fitScore - 0.181194589537041) < 0.0001);
            Assert.True(Math.Abs(cosine - 0.917609346566222) < 0.0001);
            Assert.True(Math.Abs(corr - 0.808326778009839) < 0.0001);

        }
Ejemplo n.º 3
0
 /// <summary>
 /// Find intensity rank of ion in spectrum.
 /// </summary>
 /// <param name="ion">Ion to search for.</param>
 /// <param name="tolerance"></param>
 /// <returns>Intensity rank of ion. 1-based.</returns>
 public int RankIon(Ion ion, Tolerance tolerance)
 {
     var peak = _spectrum.FindPeak(ion.GetMonoIsotopicMz(), tolerance);
     int position;
     if (peak != null)
     {
         var searchPeak = new Peak(peak.Mz, peak.Intensity);
         position = Array.BinarySearch(Peaks, searchPeak, new IntensityComparer());
         position++;
     }
     else
     {
         position = -1;
     }
     return position;
 }
        /// <summary>
        /// The run informed workflow.
        /// </summary>
        /// <param name="target">
        /// The Target.
        /// </param>
        /// <returns>
        /// The <see cref="ChargeStateCorrelationResult"/>.
        /// </returns>
        public ChargeStateCorrelationResult RunInformedWorkflow(PeptideTarget target)
        {
            Composition targetComposition = target.CompositionWithoutAdduct;
            double targetMass = targetComposition.Mass;
            string empiricalFormula = targetComposition.ToPlainString();

            double targetNet = target.NormalizedElutionTime;
            double targetNetMin = targetNet - this._parameters.NetTolerance;
            double targetNetMax = targetNet + this._parameters.NetTolerance;

            double reverseAlignedNetMin = targetNetMin;
            double reverseAlignedNetMax = targetNetMax;

            if (this._netAlignment != null)
            {
                double reverseAlignedNet = this.GetReverseAlignedNet(targetNet);
                reverseAlignedNetMin = reverseAlignedNet - this._parameters.NetTolerance;
                reverseAlignedNetMax = reverseAlignedNet + this._parameters.NetTolerance;
            }

            int scanLcSearchMin = (int)Math.Floor(reverseAlignedNetMin * this.NumberOfFrames);
            int scanLcSearchMax = (int)Math.Ceiling(reverseAlignedNetMax * this.NumberOfFrames);

            int iteration = (targetComposition == null) ? 1 : this._parameters.ChargeStateMax;
            for (int chargeState = 1; chargeState <= iteration; chargeState++)
            {
                if (targetComposition != null)
                {
                    Ion targetIon = new Ion(targetComposition, chargeState);
                    target.MassWithAdduct = targetIon.GetMonoIsotopicMz();
                }

                double minMzForSpectrum = target.MassWithAdduct - (1.6 / chargeState);
                double maxMzForSpectrum = target.MassWithAdduct + (4.6 / chargeState);

                // Generate Theoretical Isotopic Profile
                IsotopicProfile theoreticalIsotopicProfile = this._theoreticalFeatureGenerator.GenerateTheorProfile(empiricalFormula, chargeState);
                List<Peak> theoreticalIsotopicProfilePeakList = theoreticalIsotopicProfile.Peaklist.Cast<Peak>().ToList();

                // Find XIC Features
                IEnumerable<FeatureBlob> featureBlobs = this.FindFeatures(target.MassWithAdduct, scanLcSearchMin, scanLcSearchMax);

                // Filter away small XIC peaks
                featureBlobs = FeatureDetection.FilterFeatureList(featureBlobs, 0.25);

                if(!featureBlobs.Any())
                {
                    LcImsTargetResult result = new LcImsTargetResult
                    {
                        ChargeState = chargeState,
                        AnalysisStatus = AnalysisStatus.XicNotFound
                    };

                    target.ResultList.Add(result);
                }

                // Check each XIC Peak found
                foreach (var featureBlob in featureBlobs)
                {
                    // Setup result object
                    LcImsTargetResult result = new LcImsTargetResult
                    {
                        ChargeState = chargeState,
                        AnalysisStatus = AnalysisStatus.Positive
                    };

                    target.ResultList.Add(result);

                    FeatureBlobStatistics statistics = featureBlob.CalculateStatistics();
                    int unsaturatedIsotope = 0;
                    FeatureBlob isotopeFeature = null;

                    int scanLcMin = statistics.ScanLcMin;
                    int scanLcMax = statistics.ScanLcMax;
                    int scanImsMin = statistics.ScanImsMin;
                    int scanImsMax = statistics.ScanImsMax;

                    // TODO: Verify that there are no peaks at isotope #s 0.5 and 1.5?? (If we filter on drift time, this shouldn't actually be necessary)

                    // Find an unsaturated peak in the isotopic profile
                    for (int i = 1; i < 10; i++)
                    {
                        if (!statistics.IsSaturated) break;

                        // Target isotope m/z
                        double isotopeTargetMz = (target.CompositionWithoutAdduct != null) ? new Ion(targetComposition, chargeState).GetIsotopeMz(i) : target.MassWithAdduct;

                        // Find XIC Features
                        IEnumerable<FeatureBlob> newFeatureBlobs = this.FindFeatures(isotopeTargetMz, scanLcMin - 20, scanLcMax + 20);

                        // If no feature, then get out
                        if (!newFeatureBlobs.Any())
                        {
                            statistics = null;
                            break;
                        }

                        bool foundFeature = false;
                        foreach (var newFeatureBlob in newFeatureBlobs.OrderByDescending(x => x.PointList.Count))
                        {
                            var newStatistics = newFeatureBlob.CalculateStatistics();
                            if(newStatistics.ScanImsRep <= scanImsMax && newStatistics.ScanImsRep >= scanImsMin && newStatistics.ScanLcRep <= scanLcMax && newStatistics.ScanLcRep >= scanLcMin)
                            {
                                isotopeFeature = newFeatureBlob;
                                foundFeature = true;
                                break;
                            }
                        }

                        if(!foundFeature)
                        {
                            statistics = null;
                            break;
                        }

                        statistics = isotopeFeature.CalculateStatistics();
                        unsaturatedIsotope = i;
                    }

                    // Bad Feature, so get out
                    if (statistics == null)
                    {
                        result.AnalysisStatus = AnalysisStatus.IsotopicProfileNotFound;
                        continue;
                    }

                    // TODO: Calculate accurate NET and drift time using quadratic equation
                    int scanLcRep = statistics.ScanLcRep + 1;
                    int scanImsRep = statistics.ScanImsRep;

                    // Calculate NET using aligned data if applicable
                    double net = scanLcRep / this.NumberOfFrames;
                    if (this._netAlignment != null)
                    {
                        net = this._netAlignment.Interpolate(net);
                    }

                    FeatureBlob featureToUseForResult = unsaturatedIsotope > 0 ? isotopeFeature : featureBlob;

                    // Set data to result
                    result.FeatureBlobStatistics = statistics;
                    result.IsSaturated = unsaturatedIsotope > 0;
                    result.ScanLcRep = statistics.ScanLcRep;
                    result.NormalizedElutionTime = net;
                    result.DriftTime = this._uimfReader.GetDriftTime(statistics.ScanLcRep, statistics.ScanImsRep, true);
                    result.XicFeature = featureToUseForResult;

                    // Don't consider bogus results
                    if (scanImsRep < 5 || scanImsRep > this.NumberOfScans - 5)
                    {
                        result.AnalysisStatus = AnalysisStatus.DriftTimeError;
                        continue;
                    }

                        // Don't consider bogus results
                        if (scanLcRep < 3 || scanLcRep > this.NumberOfFrames - 4)
                        {
                            result.AnalysisStatus = AnalysisStatus.ElutionTimeError;
                            continue;
                        }

                        // TODO: ViperCompatibleMass Alignment???
                    if (target.TargetType == TargetType.Peptide)
                    {
                        // Filter by NET
                        if (net > targetNetMax || net < targetNetMin)
                        {
                            result.AnalysisStatus = AnalysisStatus.ElutionTimeError;
                            continue;
                        }
                    }

                    //Console.WriteLine(Target.PeptideSequence + "\t" + targetMass + "\t" + targetMz + "\t" + scanLcRep);

                    // Get ViperCompatibleMass Spectrum Data
                    XYData massSpectrum = this.GetMassSpectrum(scanLcRep, scanImsRep, minMzForSpectrum, maxMzForSpectrum);
                    List<Peak> massSpectrumPeakList = this._peakDetector.FindPeaks(massSpectrum);
                    //WriteXYDataToFile(massSpectrum, targetMz);

                    // Find Isotopic Profile
                    List<Peak> massSpectrumPeaks;
                    IsotopicProfile observedIsotopicProfile = this._msFeatureFinder.IterativelyFindMSFeature(massSpectrum, theoreticalIsotopicProfile, out massSpectrumPeaks);

                    // Add data to result
                    result.MassSpectrum = massSpectrum;

                    // No need to move on if the isotopic profile is not found
                    if (observedIsotopicProfile == null || observedIsotopicProfile.MonoIsotopicMass < 1)
                    {
                        result.AnalysisStatus = AnalysisStatus.IsotopicProfileNotFound;
                        continue;
                    }

                    // Add data to result
                    result.IsotopicProfile = observedIsotopicProfile;
                    result.MonoisotopicMass = observedIsotopicProfile.MonoIsotopicMass;
                    result.PpmError = Math.Abs(PeptideUtil.PpmError(targetMass, observedIsotopicProfile.MonoIsotopicMass));

                    // If not enough peaks to reach unsaturated isotope, no need to move on
                    if (observedIsotopicProfile.Peaklist.Count <= unsaturatedIsotope)
                    {
                        result.AnalysisStatus = AnalysisStatus.IsotopicProfileNotFound;
                        continue;
                    }

                    // If the mass error is too high, then ignore
                    if (result.PpmError > this._parameters.MassToleranceInPpm)
                    {
                        result.AnalysisStatus = AnalysisStatus.MassError;
                        continue;
                    }

                    // Correct for Saturation if needed
                    if (unsaturatedIsotope > 0)
                    {
                        IsotopicProfileUtil.AdjustSaturatedIsotopicProfile(observedIsotopicProfile, theoreticalIsotopicProfile, unsaturatedIsotope);
                    }

                    //WriteMSPeakListToFile(observedIsotopicProfile.Peaklist, targetMz);

                    // TODO: This is a hack to fix an issue where the peak width is being calculated way too large which causes the leftOfMonoPeakLooker to use too wide of a tolerance
                    MSPeak monoPeak = observedIsotopicProfile.getMonoPeak();
                    if (monoPeak.Width > 0.15) monoPeak.Width = 0.15f;

                    // Filter out flagged results
                    MSPeak peakToLeft = this._leftOfMonoPeakLooker.LookforPeakToTheLeftOfMonoPeak(monoPeak, observedIsotopicProfile.ChargeState, massSpectrumPeaks);
                    if (peakToLeft != null)
                    {
                        result.AnalysisStatus = AnalysisStatus.PeakToLeft;
                        continue;
                    }

                    double isotopicFitScore;

                    // Calculate isotopic fit score
                    if(unsaturatedIsotope > 0)
                    {
                        int unsaturatedScanLc = this.FindFrameNumberUseForIsotopicProfile(target.MassWithAdduct, scanLcRep, scanImsRep);

                        if (unsaturatedScanLc > 0)
                        {
                            // Use the unsaturated profile if we were able to get one
                            XYData unsaturatedMassSpectrum = this.GetMassSpectrum(unsaturatedScanLc, scanImsRep, minMzForSpectrum, maxMzForSpectrum);
                            //WriteXYDataToFile(unsaturatedMassSpectrum, targetMz);
                            List<Peak> unsaturatedMassSpectrumPeakList = this._peakDetector.FindPeaks(unsaturatedMassSpectrum);
                            isotopicFitScore = this._isotopicPeakFitScoreCalculator.GetFit(theoreticalIsotopicProfilePeakList, unsaturatedMassSpectrumPeakList, 0.15, this._parameters.MassToleranceInPpm);
                        }
                        else
                        {
                            // Use the saturated profile
                            isotopicFitScore = this._isotopicPeakFitScoreCalculator.GetFit(theoreticalIsotopicProfilePeakList, massSpectrumPeakList, 0.15, this._parameters.MassToleranceInPpm);
                        }
                    }
                    else
                    {
                        isotopicFitScore = this._isotopicPeakFitScoreCalculator.GetFit(theoreticalIsotopicProfilePeakList, massSpectrumPeakList, 0.15, this._parameters.MassToleranceInPpm);
                    }

                    // Add data to result
                    result.IsotopicFitScore = isotopicFitScore;

                    // Filter out bad isotopic fit scores
                    if (isotopicFitScore > this._parameters.IsotopicFitScoreThreshold && unsaturatedIsotope == 0)
                    {
                        result.AnalysisStatus = AnalysisStatus.IsotopicFitScoreError;
                        continue;
                    }

                    Console.WriteLine(chargeState + "\t" + unsaturatedIsotope + "\t" + statistics.ScanLcMin + "\t" + statistics.ScanLcMax + "\t" + statistics.ScanLcRep + "\t" + statistics.ScanImsMin + "\t" + statistics.ScanImsMax + "\t" + statistics.ScanImsRep + "\t" + isotopicFitScore.ToString("0.0000") + "\t" + result.NormalizedElutionTime.ToString("0.0000") + "\t" + result.DriftTime.ToString("0.0000"));
                }

                // TODO: Isotope Correlation (probably not going to do because of saturation issues)
            }

            // Charge State Correlation (use first unsaturated XIC feature)
            List<ChargeStateCorrelationResult> chargeStateCorrelationResultList = new List<ChargeStateCorrelationResult>();
            ChargeStateCorrelationResult bestCorrelationResult = null;
            double bestCorrelationSum = -1;

            List<LcImsTargetResult> resultList = target.ResultList.Where(x => x.AnalysisStatus == AnalysisStatus.Positive).OrderBy(x => x.IsotopicFitScore).ToList();
            int numResults = resultList.Count;

            for (int i = 0; i < numResults; i++)
            {
                LcImsTargetResult referenceResult = resultList[i];

                ChargeStateCorrelationResult chargeStateCorrelationResult = new ChargeStateCorrelationResult(target, referenceResult);
                chargeStateCorrelationResultList.Add(chargeStateCorrelationResult);

                for (int j = i + 1; j < numResults; j++)
                {
                    LcImsTargetResult testResult = resultList[j];
                    double correlation = FeatureCorrelator.CorrelateFeaturesUsingLc(referenceResult.XicFeature, testResult.XicFeature);
                    chargeStateCorrelationResult.CorrelationMap.Add(testResult, correlation);
                    Console.WriteLine(referenceResult.FeatureBlobStatistics.ScanLcRep + "\t" + referenceResult.FeatureBlobStatistics.ScanImsRep + "\t" + testResult.FeatureBlobStatistics.ScanLcRep + "\t" + testResult.FeatureBlobStatistics.ScanImsRep + "\t" + correlation);
                }

                List<LcImsTargetResult> possibleBestResultList;
                double correlationSum = chargeStateCorrelationResult.GetBestCorrelation(out possibleBestResultList);

                if(correlationSum > bestCorrelationSum)
                {
                    bestCorrelationSum = correlationSum;
                    bestCorrelationResult = chargeStateCorrelationResult;
                }
            }

            // TODO: Score Target

            // TODO: Quantify Target (return isotopic profile abundance)

            return bestCorrelationResult;
        }
        public void ExtractData(IEnumerable<PeptideTarget> targetList)
        {
            Stopwatch fastWatch = new Stopwatch();
            Stopwatch slowWatch = new Stopwatch();

            double totalChargeStateTargets = 0;

            foreach (var target in targetList)
            {
                // Get empirical formula
                Composition targetComposition = target.CompositionWithoutAdduct;

                double targetNet = target.NormalizedElutionTime;
                double targetNetMin = targetNet - this._parameters.NetTolerance;
                double targetNetMax = targetNet + this._parameters.NetTolerance;

                double reverseAlignedNetMin = targetNetMin;
                double reverseAlignedNetMax = targetNetMax;

                if (this._netAlignment != null)
                {
                    double reverseAlignedNet = this.GetReverseAlignedNet(targetNet);
                    reverseAlignedNetMin = reverseAlignedNet - this._parameters.NetTolerance;
                    reverseAlignedNetMax = reverseAlignedNet + this._parameters.NetTolerance;
                }

                int scanLcSearchMin = (int)Math.Floor(reverseAlignedNetMin * this.NumberOfFrames);
                int scanLcSearchMax = (int)Math.Ceiling(reverseAlignedNetMax * this.NumberOfFrames);

                for (int chargeState = 1; chargeState <= this._parameters.ChargeStateMax; chargeState++)
                {
                    // Calculate Target m/z
                    var targetIon = new Ion(targetComposition, chargeState);
                    double targetMz = targetIon.GetMonoIsotopicMz();

                    if (targetMz > 2500) continue;

                    // Generate Chromatogram Fast
                    fastWatch.Start();
                    List<IntensityPoint> intensityPointList = this._uimfReader.GetXic(targetMz, this._parameters.MassToleranceInPpm, scanLcSearchMin, scanLcSearchMax, 0, 359, DataReader.FrameType.MS1, DataReader.ToleranceType.PPM);
                    fastWatch.Stop();

                    // Generate Chromatogram Slow
                    slowWatch.Start();
                    FrameParams frameParameters = this._uimfReader.GetFrameParams(1);
                    double slope = frameParameters.CalibrationSlope;
                    double intercept = frameParameters.CalibrationIntercept;
                    double binWidth = this._uimfReader.GetGlobalParams().BinWidth;
                    float tofCorrectionTime = this._uimfReader.GetGlobalParams().TOFCorrectionTime;

                    double mzTolerance = targetMz / 1000000 * this._parameters.MassToleranceInPpm;
                    double lowMz = targetMz - mzTolerance;
                    double highMz = targetMz + mzTolerance;

                    int startBin = (int)Math.Floor(DataReader.GetBinClosestToMZ(slope, intercept, binWidth, tofCorrectionTime, lowMz)) - 1;
                    int endBin = (int)Math.Ceiling(DataReader.GetBinClosestToMZ(slope, intercept, binWidth, tofCorrectionTime, highMz)) + 1;

                    int[][][] frameIntensities = this._uimfReader.GetIntensityBlock(scanLcSearchMin, scanLcSearchMax, DataReader.FrameType.MS1, 0, 359, startBin, endBin);
                    slowWatch.Stop();

                    totalChargeStateTargets++;
                }
            }

            double fastTimePerTarget = fastWatch.ElapsedMilliseconds / totalChargeStateTargets;
            double slowTimePerTarget = slowWatch.ElapsedMilliseconds / totalChargeStateTargets;

            Console.WriteLine("Num Targets = " + targetList.Count());
            Console.WriteLine("Num CS Targets = " + totalChargeStateTargets);
            Console.WriteLine("Fast = " + fastTimePerTarget + " ms per Target.");
            Console.WriteLine("Slow = " + slowTimePerTarget + " ms per Target.");
        }
Ejemplo n.º 6
0
        public void AnalyizeFusionDdaData()
        {
            var methodName = MethodBase.GetCurrentMethod().Name;
            TestUtils.ShowStarting(methodName);

            // Parameters
            //const double relativeIntensityThreshold = 0.7;
            const double precursorTolerancePpm = 20;

            const string specFilePath = @"D:\Research\Data\UW\Fusion\WT_D_DDA_130412065618.raw";
            var run = InMemoryLcMsRun.GetLcMsRun(specFilePath);
            const double fdrThreshold = 0.01;

            var tolerance = new Tolerance(precursorTolerancePpm);
            var aaSet = new AminoAcidSet(Modification.Carbamidomethylation);

            const string resultFilePath = @"D:\Research\Data\UW\Fusion\WT_D_DDA_130412065618_10ppm_TI2_SGD_Decoy.tsv";

            Console.WriteLine("IsDecoy\tPeptide\tScanNum\tCharge\tSpecEValue\tQValue\tPrecursorMz" +
                              "\tTheo0\tTheo1\tTheo2\tTheo3" +
                              "\tObs0\tCorr0\tObs1\tCorr1\tObs2\tCorr2\tObs3\tCorr3\tObs-1\tCorr-1\tObs0.5\tCorr0.5");
            foreach (var line in File.ReadLines(resultFilePath))
            {
                if (line.StartsWith("#")) continue;
                var token = line.Split('\t');
                if (token.Length != 16) continue;

                var qValue = Convert.ToDouble(token[14]);
                if (qValue > fdrThreshold) continue;

                var peptide = token[8].Replace("C+57.021", "C");
                var scanNum = Convert.ToInt32(token[2]);
                var charge = Convert.ToInt32(token[7]);
                var specEValue = Convert.ToDouble(token[12]);

                var protein = token[9];
                var isDecoy = protein.StartsWith("XXX_");

                var precursorIon = new Ion(aaSet.GetComposition(peptide) + Composition.H2O, charge);
                var baseXic = run.GetPrecursorExtractedIonChromatogram(precursorIon.GetMostAbundantIsotopeMz(), tolerance, scanNum);
                var baseIntensity = baseXic.GetSumIntensities();

                Console.Write("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", (isDecoy ? 1 : 0), peptide, scanNum, charge, specEValue, qValue, precursorIon.GetMonoIsotopicMz());

                var isotopeIndices = new double[] {0, 1, 2, 3, -1, 0.5};
                var theoIsotopes = precursorIon.GetIsotopes(0.01);
                var numIsotopes = 0;
                foreach (var theoIsotope in theoIsotopes)
                {
                   Console.Write("\t"+theoIsotope.Ratio);
                    if (++numIsotopes == 4) break;
                }

                foreach (var isotopeIndex in isotopeIndices)
                {
                    var isotopeMz = precursorIon.GetIsotopeMz(isotopeIndex);
                    var xic = run.GetPrecursorExtractedIonChromatogram(isotopeMz, tolerance, scanNum);
                    var relativeIntensity = xic.GetSumIntensities() / baseIntensity;
                    var correlation = xic.GetCorrelation(baseXic);
                    Console.Write("\t{0}\t{1}", relativeIntensity, correlation);
                }
                Console.WriteLine();
            }
        }
Ejemplo n.º 7
0
        public void ParseMsGfString()
        {
            var methodName = MethodBase.GetCurrentMethod().Name;
            ShowStarting(methodName);

            const string msgfPepStr = "+229.163C+57.021GLGGSGTPVDELDK+229.163C+57.021C+57.021QTHDNC+57.021YDQAK+229.163";
            var sequence = Sequence.GetSequenceFromMsGfPlusPeptideStr(msgfPepStr);
            var ion = new Ion(sequence.Composition + Composition.H2O, 4);
            Console.WriteLine("{0} {1} {2}", msgfPepStr, ion.Composition, ion.GetMonoIsotopicMz());

            var comp = Composition.Parse("H(257) C(150) N(42) O(56) S(4) 13C(12) 15N(3)");
            Console.WriteLine("AveragineMass: " + comp.Mass);
        }
        public void GetIntensity(string peptideSequence, double ppmTolerance)
        {
            Composition composition;

            if (peptideSequence.Equals("Tetraoctylammonium"))
            {
                composition = new Composition(32, 67, 1, 0, 0);
            }
            else if (peptideSequence.Equals("Tetraoctylammonium Bromide"))
            {
                composition = new Composition(64, 135, 2, 0, 0) + Composition.ParseFromPlainString("Br");
            }
            else
            {
                composition = PeptideUtil.GetCompositionOfPeptide(peptideSequence);
            }

            string empiricalFormula = composition.ToPlainString();

            for (int chargeState = 1; chargeState <= 5; chargeState++)
            {
                // Calculate Target m/z
                var targetIon = new Ion(composition, chargeState);
                double targetMz = targetIon.GetMonoIsotopicMz();
                double minMzForSpectrum = targetMz - (3.0 / chargeState);
                double maxMzForSpectrum = targetMz + (10.0 / chargeState);

                Console.WriteLine(peptideSequence + " - +" + chargeState + " - " + targetMz);

                // Generate Theoretical Isotopic Profile
                IsotopicProfile theoreticalIsotopicProfile = _theoreticalFeatureGenerator.GenerateTheorProfile(empiricalFormula, chargeState);
                List<Peak> theoreticalIsotopicProfilePeakList = theoreticalIsotopicProfile.Peaklist.Cast<Peak>().ToList();

                // Find XIC Features
                IEnumerable<FeatureBlob> featureBlobs = FindFeatures(targetMz, ppmTolerance, 1, 1);

                // Check each XIC Peak found
                foreach (var featureBlob in featureBlobs)
                {
                    FeatureBlobStatistics statistics = featureBlob.CalculateStatistics();
                    int unsaturatedIsotope = 0;
                    FeatureBlob isotopeFeature = null;

                    int scanLcMin = statistics.ScanLcMin;
                    int scanLcMax = statistics.ScanLcMax;
                    int scanImsMin = statistics.ScanImsMin;
                    int scanImsMax = statistics.ScanImsMax;
                    double intensity = statistics.SumIntensities;

                    // Find an unsaturated peak in the isotopic profile
                    for (int i = 1; i < 10; i++)
                    {
                        if (!statistics.IsSaturated) break;

                        // Target isotope m/z
                        double isotopeTargetMz = targetIon.GetIsotopeMz(i);

                        // Find XIC Features
                        IEnumerable<FeatureBlob> newFeatureBlobs = FindFeatures(isotopeTargetMz, ppmTolerance, 1, 1);

                        // If no feature, then get out
                        if (!newFeatureBlobs.Any())
                        {
                            statistics = null;
                            break;
                        }

                        bool foundFeature = false;
                        foreach (var newFeatureBlob in newFeatureBlobs.OrderByDescending(x => x.PointList.Count))
                        {
                            var newStatistics = newFeatureBlob.CalculateStatistics();
                            if (newStatistics.ScanImsRep <= scanImsMax && newStatistics.ScanImsRep >= scanImsMin && newStatistics.ScanLcRep <= scanLcMax && newStatistics.ScanLcRep >= scanLcMin)
                            {
                                isotopeFeature = newFeatureBlob;
                                foundFeature = true;
                                break;
                            }
                        }

                        if (!foundFeature)
                        {
                            statistics = null;
                            break;
                        }

                        statistics = isotopeFeature.CalculateStatistics();
                        unsaturatedIsotope = i;
                    }

                    int scanImsRep = statistics.ScanImsRep;

                    // Get ViperCompatibleMass Spectrum Data
                    XYData massSpectrum = GetMassSpectrum(1, scanImsMin, scanImsMax, scanImsRep, minMzForSpectrum, maxMzForSpectrum);
                    //List<Peak> massSpectrumPeakList = _peakDetector.FindPeaks(massSpectrum);
                    //WriteXYDataToFile(massSpectrum, targetMz);

                    // Find Isotopic Profile
                    List<Peak> massSpectrumPeaks;
                    IsotopicProfile observedIsotopicProfile = _msFeatureFinder.IterativelyFindMSFeature(massSpectrum, theoreticalIsotopicProfile, out massSpectrumPeaks);
                    double unsaturatedIntensity = observedIsotopicProfile != null ? observedIsotopicProfile.GetSummedIntensity() : 0;

                    // Correct for Saturation if needed
                    if (unsaturatedIsotope > 0)
                    {
                        IsotopicProfileUtil.AdjustSaturatedIsotopicProfile(observedIsotopicProfile, theoreticalIsotopicProfile, unsaturatedIsotope);
                    }

                    if (observedIsotopicProfile != null && observedIsotopicProfile.MonoIsotopicMass > 1)
                    {
                        Console.WriteLine("ScanIMS = " + scanImsMin + "-" + scanImsMax + "\tImsRep = " + scanImsRep + "\tUncorrectedIntensity = " + unsaturatedIntensity + "\tIntensity = " + observedIsotopicProfile.GetSummedIntensity());
                    }
                }
            }
        }
Ejemplo n.º 9
0
        // Feature, precursorScore, totalScore
        public Tuple<Feature, double, double> GetBestFeatureAndScore(int precursorCharge)
        {
            var precursorIon = new Ion(_sequenceComposition + Composition.H2O, precursorCharge);
            var imsScorer = _imsScorerFactory.GetImsScorer(_imsData, precursorIon);

            var precursorFeatureSet = _imsData.GetPrecursorFeatures(precursorIon.GetMonoIsotopicMz());
            var bestPrecursorScore = double.NegativeInfinity;
            var bestScore = double.NegativeInfinity;
            Feature bestFeature = null;
            foreach (var precursorFeature in precursorFeatureSet)
            {
                var precursorScore = imsScorer.GetPrecursorScore(precursorFeature);
                if (precursorScore < PrecursorScoreThreshold) continue;
                var productScore = GetProductIonScore(imsScorer, precursorFeature);

                var curFeatureScore = precursorScore + productScore;
                if (curFeatureScore > bestScore)
                {
                    bestPrecursorScore = precursorScore;
                    bestScore = curFeatureScore;
                    bestFeature = precursorFeature;
                }
            }

            return new Tuple<Feature, double, double>(bestFeature, bestPrecursorScore, bestScore);
        }
Ejemplo n.º 10
0
        public void ComputeSpikedInPeptideMzHist()
        {
            var methodName = MethodBase.GetCurrentMethod().Name;
            TestUtils.ShowStarting(methodName);

            const string pepListFile = @"C:\cygwin\home\kims336\Data\DIA\SpikedPeptides.txt";

            var aaSet = new AminoAcidSet(Modification.Carbamidomethylation);
            var charges = new[] {2};

            var hist = new int[4];

            var sum = 0;

            Console.WriteLine("Peptide\tCharge\tMz");
            foreach (var line in File.ReadLines(pepListFile))
            {
                if (line.Length == 0) continue;
                var peptide = line;
                var composition = aaSet.GetComposition(peptide) + Composition.H2O;

                foreach (var charge in charges)
                {
                    var precursorIon = new Ion(composition, charge);
                    var precursorIonMz = precursorIon.GetMonoIsotopicMz();

                    if (precursorIonMz < 400 || precursorIonMz >= 900) continue;
                    var histIndex = (int)((precursorIonMz - 400)/125);
                    hist[histIndex]++;

                    Console.WriteLine("{0}\t{1}\t{2}\t{3}", peptide, charge, precursorIonMz, histIndex);

                    sum++;
                }
            }

            Console.WriteLine("\nRange\tNum\tRatio");
            for (var i = 0; i < hist.Length; i++)
            {
                Console.WriteLine("{0}-{1}\t{2}\t{3}", 400+i*125, 525+i*125, hist[i], hist[i] / (float)sum);
            }

        }
Ejemplo n.º 11
0
        public void GeneratePrmInfo(string resultFilePath, string outputFilePath)
        {
            Console.Write("Processing {0}", Path.GetFileName(resultFilePath));
            Console.Out.Flush();

            var rawFilePath =
                @"D:\Research\Data\EDRN\DDA\raw\" + Path.GetFileNameWithoutExtension(resultFilePath) + ".raw";
            var reader = new XCaliburReader(rawFilePath);
            var run = InMemoryLcMsRun.GetLcMsRun(rawFilePath);

            var tolerance = new Tolerance(10, ToleranceUnit.Ppm);

            const string spikedInPeptideFile = @"D:\Research\Data\EDRN\SpikedPeptides.txt";
            var spikedInPeptides = File.ReadAllLines(spikedInPeptideFile);
            var spikedInPepSet = new HashSet<string>();
            foreach (var p in spikedInPeptides)
            {
                spikedInPepSet.Add(p);
            }
//            const string resultFilePath = @"D:\Research\Data\EDRN\DDA\Frac7_NTT2.tsv";
            //const string resultFilePath = @"D:\Research\Data\EDRN\DDA\Heavy\342865_EDRN_Serum_07_DDA_1_12Nov13_Samwise_13-07-28.tsv";
//            const string resultFilePath = @"D:\Research\Data\EDRN\DDA\NTT1_NoMod\342865_EDRN_Serum_07_DDA_1_12Nov13_Samwise_13-07-28.tsv";
            const double qValueThreshold = 0.01;

            var pepSet = new HashSet<string>();
            MsGfPlusHeaderInformation headerInfo = null;

            //var prefix = new HashSet<string>();
            //var suffix = new HashSet<string>();
            var numPeptides = 0;

            var prevScanNum = -1;
            using (var writer = new StreamWriter(outputFilePath))
            {
                writer.WriteLine("Peptide\tCharge\tMonoMz\tMostAbundantMz\tMs2ScanNum\tRtMs2\tRtApex\tRtStart\tRtEnd\tSpecEValue\tPepQValue");
                foreach (var line in File.ReadLines(resultFilePath))
                {
                    if (line.StartsWith("#"))
                    {
                        headerInfo = new MsGfPlusHeaderInformation(line);
                        continue;
                    }

                    var match = new MsGfMatch(line, headerInfo);

                    if (match.ScanNum == prevScanNum) continue;
                    prevScanNum = match.ScanNum;

                    if (!match.IsValid || match.Protein.StartsWith(FastaDatabase.DecoyProteinPrefix)) continue;
                    if (match.PepQValue > qValueThreshold) continue;
                    var peptide = match.Peptide.Replace("C+57.021", "C").Replace("K+8.014", "K").Replace("R+10.008", "R");

                    if (pepSet.Contains(peptide)) continue;
                    pepSet.Add(peptide);

                    if (spikedInPepSet.Contains(peptide))
                    {
                        var ion = new Ion(match.Formula, match.Charge);
                        var mostAbundantIonMz = ion.GetMostAbundantIsotopeMz();
                        var xic = run.GetPrecursorExtractedIonChromatogram(mostAbundantIonMz, tolerance, match.ScanNum);
                        if (xic.Count == 0) continue;
                        var minScan = xic.Min().ScanNum;
                        var maxScan = xic.Max().ScanNum;
                        writer.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}",
                            peptide,
                            match.Charge,
                            ion.GetMonoIsotopicMz(),
                            mostAbundantIonMz,
                            match.ScanNum,
                            reader.RtFromScanNum(match.ScanNum),
                            reader.RtFromScanNum(xic.GetApexScanNum()),    // Rt apex
                            reader.RtFromScanNum(minScan),                 // Rt start
                            reader.RtFromScanNum(maxScan),                 // Rt end
                            match.SpecEValue,
                            match.PepQValue);
                        ++numPeptides;
                    }
                    //else
                    //{
                    //    foreach (var spikedInPeptide in spikedInPeptides)
                    //    {
                    //        if (spikedInPeptide.StartsWith(peptide)) prefix.Add(spikedInPeptide + "\t" + peptide + "\t" + match.ScanNum);
                    //        else if (spikedInPeptide.EndsWith(peptide)) suffix.Add(spikedInPeptide + "\t" + peptide + "\t" + match.ScanNum);
                    //    }
                    //}
                }                
            }

            //Console.WriteLine("*********Prefix");
            //foreach(var p in prefix) Console.WriteLine(p);

            //Console.WriteLine("*********Suffix");
            //foreach (var p in suffix) Console.WriteLine(p);

            Console.WriteLine("\t{0}", numPeptides);
        }