Пример #1
0
        public TestDataFile(PeptideWithSetModifications pepWithSetMods)
            : base(2, new SourceFile(@"no nativeID format", "mzML format", null, "SHA-1", @"C:\fake.mzML", null))
        {
            var mz1           = new double[] { pepWithSetMods.MonoisotopicMass.ToMz(2), (pepWithSetMods.MonoisotopicMass + Constants.C13MinusC12).ToMz(2), (pepWithSetMods.MonoisotopicMass + 2 * Constants.C13MinusC12).ToMz(2) };
            var intensities1  = new double[] { 1, 1, 1 };
            var MassSpectrum1 = new MzSpectrum(mz1, intensities1, false);

            var ScansHere = new List <MsDataScan> {
                new MsDataScan(MassSpectrum1, 1, 1, true, Polarity.Positive, 1, new MzLibUtil.MzRange(0, 10000), "ff", MZAnalyzerType.Unknown, 1000, 1, null, "scan=1")
            };

            List <double> mz2          = new List <double>();
            List <double> intensities2 = new List <double>();

            foreach (var aok in pepWithSetMods.Fragment(DissociationType.HCD, FragmentationTerminus.Both))
            {
                mz2.Add(aok.NeutralMass.ToMz(1));
                mz2.Add((aok.NeutralMass + Constants.C13MinusC12).ToMz(1));
                intensities2.Add(1);
                intensities2.Add(1);
            }
            var MassSpectrum2 = new MzSpectrum(mz2.OrderBy(b => b).ToArray(), intensities2.ToArray(), false);
            var scan2         = new MsDataScan(MassSpectrum2, 2, 2, true, Polarity.Positive, 2, new MzLibUtil.MzRange(0, 10000), "df", MZAnalyzerType.Orbitrap, 234734, 1, null, "scan=2", pepWithSetMods.MonoisotopicMass.ToMz(2), 2, 1, pepWithSetMods.MonoisotopicMass.ToMz(2), 2, DissociationType.HCD, 1, pepWithSetMods.MonoisotopicMass.ToMz(2));

            scan2.ComputeSelectedPeakIntensity(MassSpectrum1);
            scan2.ComputeMonoisotopicPeakIntensity(MassSpectrum1);
            ScansHere.Add(scan2);
            Scans = ScansHere.ToArray();
        }
Пример #2
0
        /// <summary>
        /// Tests that a PeptideWithSetModifications object can be parsed correctly from a string, with mod info
        /// </summary>
        public static void TestReadPeptideFromString()
        {
            // set up the test

            ModificationMotif.TryGetMotif("T", out ModificationMotif target);

            Modification carbamidomethylOnC = new Modification(_originalId: "Carbamidomethyl on C", _modificationType: "Common Fixed", _target: target, _chemicalFormula: ChemicalFormula.ParseFormula("C2H3NO"));
            string       sequence           = "HQVC[Common Fixed:Carbamidomethyl on C]TPGGTTIAGLC[Common Fixed:Carbamidomethyl on C]VMEEK";

            // parse the peptide from the string
            PeptideWithSetModifications peptide = new PeptideWithSetModifications(sequence, new Dictionary <string, Modification> {
                { carbamidomethylOnC.IdWithMotif, carbamidomethylOnC }
            });

            // test base sequence and full sequence
            Assert.That(peptide.BaseSequence == "HQVCTPGGTTIAGLCVMEEK");
            Assert.That(peptide.FullSequence == sequence);

            // test peptide mass
            Assert.That(Math.Round(peptide.MonoisotopicMass, 5) == 2187.01225);

            // test mods (correct id, correct number of mods, correct location of mods)
            Assert.That(peptide.AllModsOneIsNterminus.First().Value.IdWithMotif == "Carbamidomethyl on C");
            Assert.That(peptide.AllModsOneIsNterminus.Count == 2);
            Assert.That(new HashSet <int>(peptide.AllModsOneIsNterminus.Keys).SetEquals(new HashSet <int>()
            {
                5, 16
            }));

            // calculate fragments. just check that they exist and it doesn't crash
            List <Product> theoreticalFragments = new List <Product>();

            peptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both, theoreticalFragments);
            Assert.That(theoreticalFragments.Count > 0);
        }
Пример #3
0
        public TestDataFile(PeptideWithSetModifications pepWithSetMods, string v) : base(2, new SourceFile(null, null, null, null, null))
        {
            if (v.Equals("quadratic"))
            {
                // Add three ms1 peaks with charge 2, exact
                var MassSpectrum1 = new MzSpectrum(new double[] { pepWithSetMods.MonoisotopicMass.ToMz(2), (pepWithSetMods.MonoisotopicMass + Constants.C13MinusC12).ToMz(2), (pepWithSetMods.MonoisotopicMass + 2 * Constants.C13MinusC12).ToMz(2) }, new double[] { 1, 1, 1 }, false);

                List <double> mz2          = new List <double>();
                List <double> intensities2 = new List <double>();
                foreach (var aok in pepWithSetMods.Fragment(DissociationType.HCD, FragmentationTerminus.Both))
                {
                    var t1 = aok.NeutralMass.ToMz(1);
                    var c  = 0.0000001;
                    mz2.Add(t1 + c * Math.Pow(t1, 2));
                    var t2 = (aok.NeutralMass + Constants.C13MinusC12).ToMz(1);
                    mz2.Add(t2 + c * Math.Pow(t2, 2));
                    intensities2.Add(1);
                    intensities2.Add(1);
                }
                var MassSpectrum2 = new MzSpectrum(mz2.OrderBy(b => b).ToArray(), intensities2.ToArray(), false);

                var scan2 = new MsDataScan(MassSpectrum2, 2, 2, true, Polarity.Positive, 2, new MzLibUtil.MzRange(0, 10000), "df", MZAnalyzerType.Orbitrap, 234734, 1, null, "scan=2", pepWithSetMods.MonoisotopicMass.ToMz(2), 2, 1, pepWithSetMods.MonoisotopicMass.ToMz(2), 2, DissociationType.HCD, 1, pepWithSetMods.MonoisotopicMass.ToMz(2));
                scan2.ComputeSelectedPeakIntensity(MassSpectrum1);
                scan2.ComputeMonoisotopicPeakIntensity(MassSpectrum1);
                var ScansHere = new List <MsDataScan>  {
                    new MsDataScan(MassSpectrum1, 1, 1, true, Polarity.Positive, 1, new MzLibUtil.MzRange(0, 10000), "ff", MZAnalyzerType.Unknown, 1000, 1, null, "scan=1"),
                    scan2
                };
                Scans = ScansHere.ToArray();
            }
        }
Пример #4
0
        public static void TestLastPeaks()
        {
            IDictionary <int, List <Modification> > mods = new Dictionary <int, List <Modification> >();

            ModificationMotif.TryGetMotif("M", out ModificationMotif motif);
            var                         prot            = new Protein("MMMM", null, null, null, mods);
            DigestionParams             digestionParams = new DigestionParams(minPeptideLength: 1);
            PeptideWithSetModifications thePep          = prot.Digest(digestionParams, new List <Modification>(), new List <Modification>()).First();

            var massArray = thePep.Fragment(DissociationType.HCD, FragmentationTerminus.Both).Select(p => p.NeutralMass).ToArray();

            Array.Sort(massArray);
            double[]   intensities  = new double[] { 1, 1, 1 };
            double[]   mz           = new double[] { 1, 2, massArray[4].ToMz(1) };
            MzSpectrum massSpectrum = new MzSpectrum(mz, intensities, false);
            MsDataScan scan         = new MsDataScan(massSpectrum, 1, 1, true, Polarity.Positive, 1, new MzRange(300, 2000), "", MZAnalyzerType.Unknown, massSpectrum.SumOfAllY, null, null, "scan=1", 0, null, null, 0, null, DissociationType.Unknown, 1, null);

            PeptideSpectralMatch[]    globalPsms            = new PeptideSpectralMatch[1];
            Ms2ScanWithSpecificMass[] arrayOfSortedMS2Scans = { new Ms2ScanWithSpecificMass(scan, 0, 1, null, new CommonParameters()) };
            CommonParameters          CommonParameters      = new CommonParameters(
                scoreCutoff: 1,
                productMassTolerance: new PpmTolerance(5),
                digestionParams: new DigestionParams(
                    maxMissedCleavages: 0,
                    minPeptideLength: 1,
                    maxModificationIsoforms: int.MaxValue,
                    initiatorMethionineBehavior: InitiatorMethionineBehavior.Retain));
            ClassicSearchEngine cse = new ClassicSearchEngine(globalPsms, arrayOfSortedMS2Scans, new List <Modification>(), new List <Modification>(), null, new List <Protein> {
                prot
            }, new OpenSearchMode(), CommonParameters, new List <string>());

            cse.Run();
            Assert.Less(globalPsms[0].Score, 2);
            Assert.Greater(globalPsms[0].Score, 1);
        }
Пример #5
0
        public TestDataFile(PeptideWithSetModifications pepWithSetMods, int charge, double intensity, double rt) : base(2, new SourceFile(null, null, null, null, null))
        {
            var mz1           = new double[] { pepWithSetMods.MonoisotopicMass.ToMz(charge), (pepWithSetMods.MonoisotopicMass + 1.003).ToMz(charge), (pepWithSetMods.MonoisotopicMass + 2.005).ToMz(charge) };
            var intensities1  = new double[] { intensity, intensity * 10, intensity / 10 };
            var MassSpectrum1 = new MzSpectrum(mz1, intensities1, false);

            var ScansHere = new List <MsDataScan> {
                new MsDataScan(MassSpectrum1, 1, 1, true, Polarity.Positive, rt, new MzLibUtil.MzRange(0, 10000), "ff", MZAnalyzerType.Unknown, 1000, 1, null, "scan=1")
            };

            List <double> mz2          = new List <double>();
            List <double> intensities2 = new List <double>();

            foreach (var aok in pepWithSetMods.Fragment(DissociationType.HCD, FragmentationTerminus.Both))
            {
                mz2.Add(aok.NeutralMass.ToMz(1));
                mz2.Add((aok.NeutralMass + 1.003).ToMz(1));
                intensities2.Add(intensity);
                intensities2.Add(intensity);
            }
            var MassSpectrum2 = new MzSpectrum(mz2.OrderBy(b => b).ToArray(), intensities2.ToArray(), false);
            var scan2         = new MsDataScan(MassSpectrum2, 2, 2, true, Polarity.Positive, rt + 0.01, new MzLibUtil.MzRange(0, 10000), "df", MZAnalyzerType.Orbitrap, 234734, 1, null, "scan=2", pepWithSetMods.MonoisotopicMass.ToMz(2), 2, 1, pepWithSetMods.MonoisotopicMass.ToMz(2), 2, DissociationType.HCD, 1, pepWithSetMods.MonoisotopicMass.ToMz(2));

            scan2.ComputeSelectedPeakIntensity(MassSpectrum1);
            scan2.ComputeMonoisotopicPeakIntensity(MassSpectrum1);
            ScansHere.Add(scan2);
            Scans = ScansHere.ToArray();
        }
        public static IEnumerable <Tuple <int, List <Product> > > XlGetTheoreticalFragments(DissociationType dissociationType, Crosslinker crosslinker,
                                                                                            List <int> possibleCrosslinkerPositions, double otherPeptideMass, PeptideWithSetModifications peptide)
        {
            List <double> massesToLocalize = new List <double>();

            if (crosslinker.Cleavable && crosslinker.CleaveDissociationTypes.Contains(dissociationType))
            {
                massesToLocalize.Add(crosslinker.CleaveMassShort);
                massesToLocalize.Add(crosslinker.CleaveMassLong);
            }
            else
            {
                massesToLocalize.Add(crosslinker.TotalMass + otherPeptideMass);
            }

            var fragments           = new List <Product>();
            HashSet <double> masses = new HashSet <double>();

            foreach (int crosslinkerPosition in possibleCrosslinkerPositions)
            {
                List <Product> theoreticalProducts = new List <Product>(); //need a new one each time to pass as a reference, don't clear
                masses.Clear();

                foreach (double massToLocalize in massesToLocalize)
                {
                    Dictionary <int, Modification> testMods = new Dictionary <int, Modification> {
                        { crosslinkerPosition + 1, new Modification(_monoisotopicMass: massToLocalize) }
                    };

                    foreach (var mod in peptide.AllModsOneIsNterminus)
                    {
                        testMods.Add(mod.Key, mod.Value);
                    }

                    var testPeptide = new PeptideWithSetModifications(peptide.Protein, peptide.DigestionParams, peptide.OneBasedStartResidueInProtein,
                                                                      peptide.OneBasedEndResidueInProtein, peptide.CleavageSpecificityForFdrCategory, peptide.PeptideDescription, peptide.MissedCleavages, testMods, peptide.NumFixedMods);

                    testPeptide.Fragment(dissociationType, FragmentationTerminus.Both, fragments);

                    // add fragmentation ions for this crosslinker position guess
                    foreach (var fragment in fragments)
                    {
                        if (!masses.Contains(fragment.NeutralMass))
                        {
                            theoreticalProducts.Add(fragment);
                            masses.Add(fragment.NeutralMass);
                        }
                    }

                    // add signature ions
                    if (crosslinker.Cleavable)
                    {
                        theoreticalProducts.Add(new Product(ProductType.M, FragmentationTerminus.None, peptide.MonoisotopicMass + massToLocalize,
                                                            peptide.Length, peptide.Length, 0));
                    }
                }

                yield return(new Tuple <int, List <Product> >(crosslinkerPosition, theoreticalProducts));
            }
        }
Пример #7
0
        //TO THINK: filter reasonable fragments here. The final solution is to change mzLib.Proteomics.PeptideWithSetModifications.Fragment
        public static List <Product> OGlyGetTheoreticalFragments(DissociationType dissociationType, PeptideWithSetModifications peptide, PeptideWithSetModifications modPeptide)
        {
            List <Product>   theoreticalProducts = new List <Product>();
            HashSet <double> masses = new HashSet <double>();

            List <Product> products = new List <Product>();

            if (dissociationType == DissociationType.HCD || dissociationType == DissociationType.CID)
            {
                List <Product> diag = new List <Product>();
                modPeptide.Fragment(dissociationType, FragmentationTerminus.Both, diag);
                peptide.Fragment(dissociationType, FragmentationTerminus.Both, products);
                products = products.Concat(diag.Where(p => p.ProductType != ProductType.b && p.ProductType != ProductType.y)).ToList();
            }
            else if (dissociationType == DissociationType.ETD)
            {
                modPeptide.Fragment(dissociationType, FragmentationTerminus.Both, products);
            }
            else if (dissociationType == DissociationType.EThcD)
            {
                List <Product> diag = new List <Product>();
                modPeptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both, diag);
                peptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both, products);
                products = products.Concat(diag.Where(p => p.ProductType != ProductType.b && p.ProductType != ProductType.y)).ToList();


                List <Product> etdProducts = new List <Product>();
                modPeptide.Fragment(DissociationType.ETD, FragmentationTerminus.Both, etdProducts);
                products = products.Concat(etdProducts.Where(p => p.ProductType != ProductType.y)).ToList();
            }

            foreach (var fragment in products)
            {
                if (!masses.Contains(fragment.NeutralMass))
                {
                    masses.Add(fragment.NeutralMass);
                    theoreticalProducts.Add(fragment);
                }
            }

            return(theoreticalProducts);
        }
Пример #8
0
        public TestDataFile(PeptideWithSetModifications pwsm, List <double> labelMassDifferences, bool includeMassDifferenceInPrecursor = false)
            : base(2, new SourceFile(@"no nativeID format", "mzML format", null, "SHA-1", @"C:\fake.mzML", null))
        {
            List <MsDataScan> ScansHere = new List <MsDataScan>();
            double            lightMass = pwsm.MonoisotopicMass;

            for (int i = 0; i < labelMassDifferences.Count; i++)
            {
                labelMassDifferences[i] += lightMass;
            }

            labelMassDifferences.Insert(0, lightMass);

            List <double> mz1          = new List <double>();
            List <double> intensities1 = new List <double>();

            for (int z = 3; z >= 2; z--)
            {
                for (int i = 0; i < labelMassDifferences.Count; i++)
                {
                    double mass = labelMassDifferences[i];

                    for (int isotope = 0; isotope < 3; isotope++)
                    {
                        mz1.Add((mass + isotope * Constants.C13MinusC12).ToMz(z));
                        intensities1.Add(Math.Pow(0.5, i) * (Math.Pow(0.5, isotope) * 1000000)); //makes each label half the intensity of the previous
                    }
                }
            }
            var MassSpectrum1 = new MzSpectrum(mz1.ToArray(), intensities1.ToArray(), false);

            ScansHere.Add(new MsDataScan(MassSpectrum1, 1, 1, true, Polarity.Positive, 0, new MzLibUtil.MzRange(0, 10000), "gg", MZAnalyzerType.Orbitrap, 1000, 1, null, "scan=1"));

            //only make the light ms2, it should find the heavy ms1 from that
            List <double> mz2          = new List <double>();
            List <double> intensities2 = new List <double>();

            foreach (var aok in pwsm.Fragment(DissociationType.HCD, FragmentationTerminus.Both))
            {
                mz2.Add(aok.NeutralMass.ToMz(1));
                mz2.Add((aok.NeutralMass + Constants.C13MinusC12).ToMz(1));
                intensities2.Add(1);
                intensities2.Add(1);
            }
            if (includeMassDifferenceInPrecursor)
            {
                lightMass = labelMassDifferences[1];
            }
            var MassSpectrum2 = new MzSpectrum(mz2.OrderBy(b => b).ToArray(), intensities2.ToArray(), false);

            ScansHere.Add(new MsDataScan(MassSpectrum2, 2, 2, true, Polarity.Positive, 1, new MzLibUtil.MzRange(0, 10000), "gg", MZAnalyzerType.Orbitrap, 234734, 1, null, "scan=2", lightMass.ToMz(2), 2, 1, lightMass.ToMz(2), 2, DissociationType.HCD, 1, lightMass.ToMz(2)));

            Scans = ScansHere.ToArray();
        }
Пример #9
0
        public static void TestSerializationPeptideFromProtein()
        {
            // purpose of this test is to serialize/deserialize a PeptideWithSetModifications and make sure the deserialized peptide
            // has the same properties as before it was serialized. This peptide is unmodified and generated from digesting a protein
            Protein protein = new Protein("PEPTIDE", "Accession1", name: "MyProtein");

            PeptideWithSetModifications peptide             = protein.Digest(new DigestionParams(), new List <Modification>(), new List <Modification>()).First();
            PeptideWithSetModifications deserializedPeptide = null;

            string dir = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, "TestSerializationPeptideFromProtein");

            System.IO.Directory.CreateDirectory(dir);
            string path = System.IO.Path.Combine(dir, "myPeptideIndex.ind");

            var messageTypes = typeof(PeptideWithSetModifications);
            var ser          = new NetSerializer.Serializer(new List <Type> {
                messageTypes
            });

            using (var file = System.IO.File.Create(path))
            {
                ser.Serialize(file, peptide);
            }

            using (var file = System.IO.File.OpenRead(path))
            {
                deserializedPeptide = (PeptideWithSetModifications)ser.Deserialize(file);
            }

            deserializedPeptide.SetNonSerializedPeptideInfo(new Dictionary <string, Modification>(), new Dictionary <string, Protein> {
                { protein.Accession, protein }
            }, peptide.DigestionParams);

            Assert.That(peptide.DigestionParams.Equals(deserializedPeptide.DigestionParams));
            Assert.That(peptide.Equals(deserializedPeptide));
            Assert.That(deserializedPeptide.Protein.Name == peptide.Protein.Name);
            Assert.That(deserializedPeptide.MonoisotopicMass == peptide.MonoisotopicMass);
            Assert.That(deserializedPeptide.SequenceWithChemicalFormulas == peptide.SequenceWithChemicalFormulas);

            var products = new List <Product>();

            deserializedPeptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both, products);
            List <double> deserializedPeptideFragments = products.Select(v => v.NeutralMass).ToList();

            peptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both, products);
            List <double> peptideFragments = products.Select(v => v.NeutralMass).ToList();

            Assert.That(deserializedPeptideFragments.SequenceEqual(peptideFragments));
        }
Пример #10
0
        public static void SingleEventArgsTest()
        {
            Protein          parentProteinForMatch = new Protein("MEK", null);
            CommonParameters commonParameters      = new CommonParameters(digestionParams: new DigestionParams(minPeptideLength: 1));
            var fsp = new List <(string fileName, CommonParameters fileSpecificParameters)>();

            fsp.Add(("", commonParameters));
            ModificationMotif.TryGetMotif("E", out ModificationMotif motif);
            List <Modification> variableModifications = new List <Modification> {
                new Modification(_originalId: "21", _target: motif, _locationRestriction: "Anywhere.", _monoisotopicMass: 21.981943)
            };

            List <PeptideWithSetModifications> allPeptidesWithSetModifications = parentProteinForMatch.Digest(commonParameters.DigestionParams, new List <Modification>(), variableModifications).ToList();

            Assert.AreEqual(4, allPeptidesWithSetModifications.Count());
            PeptideWithSetModifications ps = allPeptidesWithSetModifications.First();

            PeptideWithSetModifications pepWithSetModsForSpectrum = allPeptidesWithSetModifications[1];
            MsDataFile myMsDataFile = new TestDataFile(new List <PeptideWithSetModifications> {
                pepWithSetModsForSpectrum
            });
            Tolerance fragmentTolerance = new AbsoluteTolerance(0.01);

            Ms2ScanWithSpecificMass scan = new Ms2ScanWithSpecificMass(myMsDataFile.GetAllScansList().Last(), pepWithSetModsForSpectrum.MonoisotopicMass.ToMz(1), 1, null, new CommonParameters());

            var theoreticalProducts = new List <Product>();

            ps.Fragment(DissociationType.HCD, FragmentationTerminus.Both, theoreticalProducts);

            var matchedIons             = MetaMorpheusEngine.MatchFragmentIons(scan, theoreticalProducts, new CommonParameters());
            PeptideSpectralMatch newPsm = new PeptideSpectralMatch(ps, 0, 0, 2, scan, commonParameters, matchedIons);

            LocalizationEngine f = new LocalizationEngine(new List <PeptideSpectralMatch> {
                newPsm
            }, myMsDataFile, new CommonParameters(), fsp, new List <string>());

            var singleEngine = new SingleEngineEventArgs(f);

            Assert.That(singleEngine.MyEngine.Equals(f));

            var singleFile = new SingleFileEventArgs("", new List <string>());

            Assert.That(singleFile.WrittenFile.Equals(""));

            var stringList = new StringListEventArgs(new List <string>());
            var rr         = (stringList.StringList.DefaultIfEmpty().First());

            Assert.That(stringList.StringList.DefaultIfEmpty().First() == null);
        }
        private List <MatchedFragmentIon> ScoreChildScan(Ms2ScanWithSpecificMass parentScan, Ms2ScanWithSpecificMass childScan, int possibleSite, BestPeptideScoreNotch mainPeptide, BestPeptideScoreNotch otherPeptide)
        {
            bool shortMassAlphaMs3 = XLPrecusorSearchMode.Accepts(childScan.PrecursorMass, mainPeptide.BestPeptide.MonoisotopicMass + Crosslinker.CleaveMassShort) >= 0;
            bool longMassAlphaMs3  = XLPrecusorSearchMode.Accepts(childScan.PrecursorMass, mainPeptide.BestPeptide.MonoisotopicMass + Crosslinker.CleaveMassLong) >= 0;

            List <Product> childProducts;

            if (Crosslinker.Cleavable && (shortMassAlphaMs3 || longMassAlphaMs3))
            {
                double massToLocalize = shortMassAlphaMs3 ? Crosslinker.CleaveMassShort : Crosslinker.CleaveMassLong;
                if (mainPeptide.BestPeptide.AllModsOneIsNterminus.TryGetValue(possibleSite + 1, out var existingMod))
                {
                    massToLocalize += existingMod.MonoisotopicMass.Value;
                }

                Dictionary <int, Modification> mod = new Dictionary <int, Modification> {
                    { possibleSite + 1, new Modification(_monoisotopicMass: massToLocalize) }
                };

                foreach (var otherExistingMod in mainPeptide.BestPeptide.AllModsOneIsNterminus.Where(p => p.Key != possibleSite + 1))
                {
                    mod.Add(otherExistingMod.Key, otherExistingMod.Value);
                }

                var peptideWithMod = new PeptideWithSetModifications(mainPeptide.BestPeptide.Protein, mainPeptide.BestPeptide.DigestionParams,
                                                                     mainPeptide.BestPeptide.OneBasedStartResidueInProtein, mainPeptide.BestPeptide.OneBasedEndResidueInProtein,
                                                                     mainPeptide.BestPeptide.CleavageSpecificityForFdrCategory, mainPeptide.BestPeptide.PeptideDescription,
                                                                     mainPeptide.BestPeptide.MissedCleavages, mod, mainPeptide.BestPeptide.NumFixedMods);

                childProducts = peptideWithMod.Fragment(CommonParameters.ChildScanDissociationType, FragmentationTerminus.Both).ToList();
            }
            else if (Math.Abs(childScan.PrecursorMass - parentScan.PrecursorMass) < 0.01 && CommonParameters.DissociationType != CommonParameters.ChildScanDissociationType)
            {
                // same species got fragmented twice, the second time with a different dissociation type
                childProducts = CrosslinkedPeptide.XlGetTheoreticalFragments(CommonParameters.ChildScanDissociationType,
                                                                             Crosslinker, new List <int> {
                    possibleSite
                }, otherPeptide.BestPeptide.MonoisotopicMass, mainPeptide.BestPeptide).First().Item2;
            }
            else
            {
                return(null);
            }

            var matchedChildIons = MatchFragmentIons(childScan, childProducts, CommonParameters);

            return(matchedChildIons);
        }
Пример #12
0
        public static void TestSerializationPeptideFromString()
        {
            // purpose of this test is to serialize/deserialize a PeptideWithSetModifications and make sure the deserialized peptide
            // has the same properties as before it was serialized. This peptide is unmodified and generated from reading in a string
            string sequence = "PEPTIDE";
            PeptideWithSetModifications peptide             = new PeptideWithSetModifications(sequence, new Dictionary <string, Modification>(), 0, null, null, 1, 7, 0);
            PeptideWithSetModifications deserializedPeptide = null;

            string dir = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, "TestSerializationPeptideFromString");

            System.IO.Directory.CreateDirectory(dir);
            string path = System.IO.Path.Combine(dir, "myPeptideIndex.ind");

            var messageTypes = typeof(PeptideWithSetModifications);
            var ser          = new NetSerializer.Serializer(new List <Type> {
                messageTypes
            });

            using (var file = System.IO.File.Create(path))
            {
                ser.Serialize(file, peptide);
            }

            using (var file = System.IO.File.OpenRead(path))
            {
                deserializedPeptide = (PeptideWithSetModifications)ser.Deserialize(file);
            }

            deserializedPeptide.SetNonSerializedPeptideInfo(new Dictionary <string, Modification>(), new Dictionary <string, Protein>(), null);

            // not asserting any protein properties - since the peptide was created from a sequence string it didn't have a protein to begin with

            Assert.That(peptide.Equals(deserializedPeptide));
            Assert.That(deserializedPeptide.MonoisotopicMass == peptide.MonoisotopicMass);
            Assert.That(deserializedPeptide.SequenceWithChemicalFormulas == peptide.SequenceWithChemicalFormulas);

            var products = new List <Product>();

            deserializedPeptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both, products);
            List <double> deserializedPeptideFragments = products.Select(v => v.NeutralMass).ToList();

            peptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both, products);
            List <double> peptideFragments = products.Select(v => v.NeutralMass).ToList();

            Assert.That(deserializedPeptideFragments.SequenceEqual(peptideFragments));
        }
Пример #13
0
        public static void TestLocalization()
        {
            Protein          parentProteinForMatch = new Protein("MEK", null);
            CommonParameters commonParameters      = new CommonParameters(digestionParams: new DigestionParams(minPeptideLength: 1));
            var fsp = new List <(string fileName, CommonParameters fileSpecificParameters)>();

            fsp.Add(("", commonParameters));
            ModificationMotif.TryGetMotif("E", out ModificationMotif motif);
            List <Modification> variableModifications = new List <Modification> {
                new Modification(_originalId: "21", _target: motif, _locationRestriction: "Anywhere.", _monoisotopicMass: 21.981943)
            };

            List <PeptideWithSetModifications> allPeptidesWithSetModifications = parentProteinForMatch.Digest(commonParameters.DigestionParams, new List <Modification>(), variableModifications).ToList();

            Assert.AreEqual(4, allPeptidesWithSetModifications.Count());
            PeptideWithSetModifications ps = allPeptidesWithSetModifications.First();

            PeptideWithSetModifications pepWithSetModsForSpectrum = allPeptidesWithSetModifications[1];
            MsDataFile myMsDataFile = new TestDataFile(new List <PeptideWithSetModifications> {
                pepWithSetModsForSpectrum
            });
            Tolerance fragmentTolerance = new AbsoluteTolerance(0.01);

            Ms2ScanWithSpecificMass scan = new Ms2ScanWithSpecificMass(myMsDataFile.GetAllScansList().Last(), pepWithSetModsForSpectrum.MonoisotopicMass.ToMz(1), 1, null, new CommonParameters());

            var theoreticalProducts = new List <Product>();

            ps.Fragment(DissociationType.HCD, FragmentationTerminus.Both, theoreticalProducts);
            var matchedIons             = MetaMorpheusEngine.MatchFragmentIons(scan, theoreticalProducts, new CommonParameters());
            PeptideSpectralMatch newPsm = new PeptideSpectralMatch(ps, 0, 0, 2, scan, commonParameters, matchedIons);

            newPsm.ResolveAllAmbiguities();

            LocalizationEngine f = new LocalizationEngine(new List <PeptideSpectralMatch> {
                newPsm
            }, myMsDataFile, commonParameters, fsp, new List <string>());

            f.Run();

            // single peak matches
            Assert.AreEqual(1, newPsm.MatchedFragmentIons.Where(p => p.NeutralTheoreticalProduct.ProductType == ProductType.b).Count());//including b1 now
            Assert.AreEqual(1, newPsm.MatchedFragmentIons.Where(p => p.NeutralTheoreticalProduct.ProductType == ProductType.y).Count());

            // when localizing, three peaks match
            Assert.IsTrue(newPsm.LocalizedScores[1] > 4 && newPsm.LocalizedScores[1] < 5);//we have another matched ion
        }
Пример #14
0
        public static void AddCompIonsMzOutput()
        {
            PeptideWithSetModifications pwsm     = new PeptideWithSetModifications("ASDFASDF", null);
            Ms2ScanWithSpecificMass     testScan = MetaMorpheusTask.GetMs2Scans(new TestDataFile(pwsm), null, new CommonParameters()).OrderBy(b => b.PrecursorMass).First();

            CommonParameters cp = new CommonParameters(addCompIons: true);
            List <Product>   theoreticalIons = new List <Product>();

            pwsm.Fragment(cp.DissociationType, FragmentationTerminus.Both, theoreticalIons);
            List <MatchedFragmentIon> matchedIons = MetaMorpheusEngine.MatchFragmentIons(testScan, theoreticalIons, cp);

            //check that the matchedIons have m/z values that are similar to their neutral mass.
            //There was an "issue" where the saved m/z was the original experimental peak (which is the complementary of the added ion).
            //A fix was introduced to save a "fake" m/z for the added ion
            foreach (MatchedFragmentIon ion in matchedIons)
            {
                Assert.IsTrue(ion.NeutralTheoreticalProduct.NeutralMass < ion.Mz);
                Assert.IsTrue(ion.NeutralTheoreticalProduct.NeutralMass + 2 > ion.Mz);
            }
        }
Пример #15
0
        public static void TestFragmentCTerminalModifiedPeptide()
        {
            ModificationMotif.TryGetMotif("E", out ModificationMotif motif);
            Modification cTermMod = new Modification(_originalId: "acetylation", _modificationType: "testModType", _target: motif, _chemicalFormula: ChemicalFormula.ParseFormula("C2H2O1"), _locationRestriction: "C-terminal.");

            Dictionary <int, List <Modification> > mods = new Dictionary <int, List <Modification> > {
                { 7, new List <Modification> {
                      cTermMod
                  } }
            };

            Protein protein = new Protein("PEPTIDE", "", oneBasedModifications: mods);
            PeptideWithSetModifications peptide = protein.Digest(new DigestionParams(), new List <Modification>(), new List <Modification>()).Where(p => p.AllModsOneIsNterminus.Count == 1).First();

            Assert.That(peptide.FullSequence == "PEPTIDE[testModType:acetylation on E]");

            var fragments        = peptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both).ToList();
            var roundedFragments = fragments.Select(f => (int)f.NeutralMass).ToList();

            Assert.That(roundedFragments.SequenceEqual(new int[] { 97, 226, 323, 424, 537, 652, 189, 304, 417, 518, 615, 744 }));
        }
Пример #16
0
        public static void TestFragmentNterminalModifiedPeptide()
        {
            ModificationMotif.TryGetMotif("P", out ModificationMotif motif);
            Modification nTermMod = new Modification(_originalId: "acetylation", _modificationType: "testModType", _target: motif, _chemicalFormula: ChemicalFormula.ParseFormula("C2H2O1"), _locationRestriction: "N-terminal.");

            Dictionary <int, List <Modification> > mods = new Dictionary <int, List <Modification> > {
                { 1, new List <Modification> {
                      nTermMod
                  } }
            };

            Protein protein = new Protein("PEPTIDE", "", oneBasedModifications: mods);
            PeptideWithSetModifications peptide = protein.Digest(new DigestionParams(), new List <Modification>(), new List <Modification>()).Where(p => p.AllModsOneIsNterminus.Count == 1).First();

            Assert.That(peptide.FullSequence == "[testModType:acetylation on P]PEPTIDE");

            var fragments        = peptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both).ToList();
            var roundedFragments = fragments.Select(f => (int)f.NeutralMass).ToList();

            Assert.That(roundedFragments.SequenceEqual(new int[] { 139, 268, 365, 466, 579, 694, 147, 262, 375, 476, 573, 702 }));
        }
        protected override MetaMorpheusEngineResults RunSpecific()
        {
            // don't try to localize mass differences for ambiguous peptides
            foreach (PeptideSpectralMatch psm in AllResultingIdentifications.Where(b => b.FullSequence != null))
            {
                // Stop loop if canceled
                if (GlobalVariables.StopLoops)
                {
                    break;
                }

                MsDataScan scan = MyMsDataFile.GetOneBasedScan(psm.ScanNumber);
                Ms2ScanWithSpecificMass     scanWithSpecificMass = new Ms2ScanWithSpecificMass(scan, psm.ScanPrecursorMonoisotopicPeakMz, psm.ScanPrecursorCharge, psm.FullFilePath, CommonParameters);
                PeptideWithSetModifications peptide = psm.BestMatchingPeptides.First().Peptide;
                double massDifference = psm.ScanPrecursorMass - peptide.MonoisotopicMass;

                // this section will iterate through all residues of the peptide and try to localize the mass-diff at each residue and report a score for each residue
                var localizedScores = new List <double>();
                for (int r = 0; r < peptide.Length; r++)
                {
                    // create new PeptideWithSetMods with unidentified mass difference at the given residue
                    PeptideWithSetModifications peptideWithLocalizedMassDiff = peptide.Localize(r, massDifference);

                    // this is the list of theoretical products for this peptide with mass-difference on this residue
                    List <Product> productsWithLocalizedMassDiff = peptideWithLocalizedMassDiff.Fragment(CommonParameters.DissociationType, CommonParameters.DigestionParams.FragmentationTerminus).ToList();

                    var matchedIons = MatchFragmentIons(scanWithSpecificMass, productsWithLocalizedMassDiff, CommonParameters);

                    // score when the mass-diff is on this residue
                    double localizedScore = CalculatePeptideScore(scan, matchedIons);

                    localizedScores.Add(localizedScore);
                }

                psm.LocalizedScores = localizedScores;
            }

            return(new LocalizationEngineResults(this));
        }
Пример #18
0
        protected override MetaMorpheusEngineResults RunSpecific()
        {
            double progress           = 0;
            int    oldPercentProgress = 0;

            ReportProgress(new ProgressEventArgs(oldPercentProgress, "Performing modern search... " + CurrentPartition + "/" + commonParameters.TotalPartitions, nestedIds));

            byte byteScoreCutoff = (byte)commonParameters.ScoreCutoff;

            if (commonParameters.CalculateEValue)
            {
                byteScoreCutoff = 1;
            }

            int maxThreadsPerFile = commonParameters.MaxThreadsToUsePerFile;

            int[] threads = Enumerable.Range(0, maxThreadsPerFile).ToArray();
            Parallel.ForEach(threads, (i) =>
            {
                byte[] scoringTable = new byte[PeptideIndex.Count];
                List <int> idsOfPeptidesPossiblyObserved = new List <int>();

                for (; i < ListOfSortedMs2Scans.Length; i += maxThreadsPerFile)
                {
                    // Stop loop if canceled
                    if (GlobalVariables.StopLoops)
                    {
                        return;
                    }

                    // empty the scoring table to score the new scan (conserves memory compared to allocating a new array)
                    Array.Clear(scoringTable, 0, scoringTable.Length);
                    idsOfPeptidesPossiblyObserved.Clear();
                    Ms2ScanWithSpecificMass scan = ListOfSortedMs2Scans[i];

                    // get fragment bins for this scan
                    List <int> allBinsToSearch = GetBinsToSearch(scan);

                    // get allowed theoretical masses from the known experimental mass
                    // note that this is the OPPOSITE of the classic search (which calculates experimental masses from theoretical values)
                    // this is just PRELIMINARY precursor-mass filtering
                    // additional checks are made later to ensure that the theoretical precursor mass is acceptable
                    IEnumerable <AllowedIntervalWithNotch> notches = MassDiffAcceptor.GetAllowedPrecursorMassIntervalsFromObservedMass(scan.PrecursorMass);

                    double lowestMassPeptideToLookFor  = notches.Min(p => p.AllowedInterval.Minimum);
                    double highestMassPeptideToLookFor = notches.Max(p => p.AllowedInterval.Maximum);

                    // first-pass scoring
                    IndexedScoring(allBinsToSearch, scoringTable, byteScoreCutoff, idsOfPeptidesPossiblyObserved, scan.PrecursorMass, lowestMassPeptideToLookFor, highestMassPeptideToLookFor, PeptideIndex, MassDiffAcceptor, MaxMassThatFragmentIonScoreIsDoubled, commonParameters.DissociationType);

                    // done with indexed scoring; refine scores and create PSMs
                    foreach (int id in idsOfPeptidesPossiblyObserved)
                    {
                        PeptideWithSetModifications peptide = PeptideIndex[id];

                        List <Product> peptideTheorProducts = peptide.Fragment(commonParameters.DissociationType, FragmentationTerminus.Both).ToList();

                        List <MatchedFragmentIon> matchedIons = MatchFragmentIons(scan, peptideTheorProducts, commonParameters);

                        double thisScore = CalculatePeptideScore(scan.TheScan, matchedIons);
                        int notch        = MassDiffAcceptor.Accepts(scan.PrecursorMass, peptide.MonoisotopicMass);

                        bool meetsScoreCutoff = thisScore >= commonParameters.ScoreCutoff;
                        bool scoreImprovement = PeptideSpectralMatches[i] == null || (thisScore - PeptideSpectralMatches[i].RunnerUpScore) > -PeptideSpectralMatch.ToleranceForScoreDifferentiation;

                        if (meetsScoreCutoff && scoreImprovement || commonParameters.CalculateEValue)
                        {
                            if (PeptideSpectralMatches[i] == null)
                            {
                                PeptideSpectralMatches[i] = new PeptideSpectralMatch(peptide, notch, thisScore, i, scan, commonParameters.DigestionParams, matchedIons);
                            }
                            else
                            {
                                PeptideSpectralMatches[i].AddOrReplace(peptide, thisScore, notch, commonParameters.ReportAllAmbiguity, matchedIons, 0);
                            }

                            if (commonParameters.CalculateEValue)
                            {
                                PeptideSpectralMatches[i].AllScores.Add(thisScore);
                            }
                        }
                    }

                    // report search progress
                    progress++;
                    var percentProgress = (int)((progress / ListOfSortedMs2Scans.Length) * 100);

                    if (percentProgress > oldPercentProgress)
                    {
                        oldPercentProgress = percentProgress;
                        ReportProgress(new ProgressEventArgs(percentProgress, "Performing modern search... " + CurrentPartition + "/" + commonParameters.TotalPartitions, nestedIds));
                    }
                }
            });

            // remove peptides below the score cutoff that were stored to calculate expectation values
            if (commonParameters.CalculateEValue)
            {
                for (int i = 0; i < PeptideSpectralMatches.Length; i++)
                {
                    if (PeptideSpectralMatches[i] != null && PeptideSpectralMatches[i].Score < commonParameters.ScoreCutoff)
                    {
                        PeptideSpectralMatches[i] = null;
                    }
                }
            }

            foreach (PeptideSpectralMatch psm in PeptideSpectralMatches.Where(p => p != null))
            {
                psm.ResolveAllAmbiguities();
            }

            return(new MetaMorpheusEngineResults(this));
        }
Пример #19
0
        public static void TestSerializationPeptideFromProteinWithMod()
        {
            // purpose of this test is to serialize/deserialize a PeptideWithSetModifications and make sure the deserialized peptide
            // has the same properties as before it was serialized. This peptide is modified with a phosphorylation

            ModificationMotif.TryGetMotif("T", out ModificationMotif motif);

            Dictionary <DissociationType, List <double> > myNeutralLosses = new Dictionary <DissociationType, List <double> >()
            {
                { DissociationType.HCD, new List <double> {
                      ChemicalFormula.ParseFormula("H3 O4 P1").MonoisotopicMass
                  } },
                { DissociationType.ETD, new List <double>()
                  {
                      ChemicalFormula.ParseFormula("H3 N1").MonoisotopicMass
                  } }                                                                                                   // this makes no sense in real life, it's just for a unit test
            };

            Modification mod = new Modification(_originalId: "phospho", _modificationType: "testModType", _target: motif, _chemicalFormula: ChemicalFormula.ParseFormula("H1 O3 P1"), _neutralLosses: myNeutralLosses, _locationRestriction: "Anywhere.");

            Dictionary <int, List <Modification> > mods = new Dictionary <int, List <Modification> > {
                { 4, new List <Modification> {
                      mod
                  } }
            };

            Protein protein = new Protein("PEPTIDE", "Accession1", name: "MyProtein", oneBasedModifications: mods);

            PeptideWithSetModifications peptide             = protein.Digest(new DigestionParams(), new List <Modification>(), new List <Modification>()).Where(v => v.AllModsOneIsNterminus.Count == 1).First();
            PeptideWithSetModifications deserializedPeptide = null;

            string dir = System.IO.Path.Combine(TestContext.CurrentContext.TestDirectory, "TestSerializationPeptideFromProteinWithMod");

            System.IO.Directory.CreateDirectory(dir);
            string path = System.IO.Path.Combine(dir, "myPeptideIndex.ind");

            var messageTypes = typeof(PeptideWithSetModifications);
            var ser          = new NetSerializer.Serializer(new List <Type> {
                messageTypes
            });

            using (var file = System.IO.File.Create(path))
            {
                ser.Serialize(file, peptide);
            }

            using (var file = System.IO.File.OpenRead(path))
            {
                deserializedPeptide = (PeptideWithSetModifications)ser.Deserialize(file);
            }

            Dictionary <string, Modification> stringToMod = new Dictionary <string, Modification> {
                { mods.Values.First().First().IdWithMotif, mods.Values.First().First() }
            };

            deserializedPeptide.SetNonSerializedPeptideInfo(stringToMod, new Dictionary <string, Protein> {
                { protein.Accession, protein }
            }, peptide.DigestionParams);

            Assert.That(peptide.Equals(deserializedPeptide));
            Assert.That(deserializedPeptide.Protein.Name == peptide.Protein.Name);
            Assert.That(deserializedPeptide.MonoisotopicMass == peptide.MonoisotopicMass);
            Assert.That(deserializedPeptide.SequenceWithChemicalFormulas == peptide.SequenceWithChemicalFormulas);

            var products = new List <Product>();

            deserializedPeptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both, products);
            List <double> deserializedPeptideFragments = products.Select(v => v.NeutralMass).ToList();

            peptide.Fragment(DissociationType.HCD, FragmentationTerminus.Both, products);
            List <double> peptideFragments = products.Select(v => v.NeutralMass).ToList();

            Assert.That(deserializedPeptideFragments.SequenceEqual(peptideFragments));
        }
Пример #20
0
        public static void TestProteinQuantFileHeaders(bool hasDefinedExperimentalDesign, int bioreps, int fractions, int techreps)
        {
            // create the unit test directory
            string unitTestFolder = Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestProteinQuantFileHeaders");

            Directory.CreateDirectory(unitTestFolder);

            List <SpectraFileInfo> fileInfos = new List <SpectraFileInfo>();
            string peptide      = "PEPTIDE";
            double ionIntensity = 1e6;
            string condition    = hasDefinedExperimentalDesign ? "TestCondition" : "";

            // create the protein database
            Protein prot   = new Protein(peptide, @"");
            string  dbName = Path.Combine(unitTestFolder, "testDB.fasta");

            UsefulProteomicsDatabases.ProteinDbWriter.WriteFastaDatabase(new List <Protein> {
                prot
            }, dbName, ">");

            // create the .mzML files to search/quantify
            for (int b = 0; b < bioreps; b++)
            {
                for (int f = 0; f < fractions; f++)
                {
                    for (int r = 0; r < techreps; r++)
                    {
                        string fileToWrite = "file_" + "b" + b + "f" + f + "r" + r + ".mzML";

                        // generate mzml file
                        MsDataScan[] scans = new MsDataScan[2];

                        // create the MS1 scan
                        ChemicalFormula      cf          = new Proteomics.AminoAcidPolymer.Peptide(peptide).GetChemicalFormula();
                        IsotopicDistribution dist        = IsotopicDistribution.GetDistribution(cf, 0.125, 1e-8);
                        double[]             mz          = dist.Masses.Select(v => v.ToMz(1)).ToArray();
                        double[]             intensities = dist.Intensities.Select(v => v * ionIntensity).ToArray();

                        scans[0] = new MsDataScan(massSpectrum: new MzSpectrum(mz, intensities, false), oneBasedScanNumber: 1, msnOrder: 1, isCentroid: true,
                                                  polarity: Polarity.Positive, retentionTime: 1.0, scanWindowRange: new MzRange(400, 1600), scanFilter: "f",
                                                  mzAnalyzer: MZAnalyzerType.Orbitrap, totalIonCurrent: intensities.Sum(), injectionTime: 1.0, noiseData: null, nativeId: "scan=1");

                        // create the MS2 scan
                        var            pep   = new PeptideWithSetModifications(peptide, new Dictionary <string, Proteomics.Modification>());
                        List <Product> frags = new List <Product>();
                        pep.Fragment(DissociationType.HCD, FragmentationTerminus.Both, frags);
                        double[] mz2          = frags.Select(v => v.NeutralMass.ToMz(1)).ToArray();
                        double[] intensities2 = frags.Select(v => 1e6).ToArray();

                        scans[1] = new MsDataScan(massSpectrum: new MzSpectrum(mz2, intensities2, false), oneBasedScanNumber: 2, msnOrder: 2, isCentroid: true,
                                                  polarity: Polarity.Positive, retentionTime: 1.01, scanWindowRange: new MzRange(100, 1600), scanFilter: "f",
                                                  mzAnalyzer: MZAnalyzerType.Orbitrap, totalIonCurrent: intensities.Sum(), injectionTime: 1.0, noiseData: null, nativeId: "scan=2", selectedIonMz: pep.MonoisotopicMass.ToMz(1),
                                                  selectedIonChargeStateGuess: 1, selectedIonIntensity: 1e6, isolationMZ: pep.MonoisotopicMass.ToMz(1), isolationWidth: 1.5, dissociationType: DissociationType.HCD,
                                                  oneBasedPrecursorScanNumber: 1, selectedIonMonoisotopicGuessMz: pep.MonoisotopicMass.ToMz(1), hcdEnergy: "35");

                        // write the .mzML
                        string fullPath = Path.Combine(unitTestFolder, fileToWrite);
                        IO.MzML.MzmlMethods.CreateAndWriteMyMzmlWithCalibratedSpectra(
                            new MsDataFile(scans, new SourceFile(@"scan number only nativeID format", "mzML format", null, "SHA-1", @"C:\fake.mzML", null)),
                            fullPath, false);

                        var spectraFileInfo = new SpectraFileInfo(fullPath, condition, b, r, f);
                        fileInfos.Add(spectraFileInfo);
                    }
                }
            }

            // write the experimental design for this quantification test
            if (hasDefinedExperimentalDesign)
            {
                ExperimentalDesign.WriteExperimentalDesignToFile(fileInfos);
            }

            // run the search/quantification
            SearchTask task = new SearchTask();

            task.RunTask(unitTestFolder, new List <DbForTask> {
                new DbForTask(dbName, false)
            }, fileInfos.Select(p => p.FullFilePathWithExtension).ToList(), "");

            // read in the protein quant results
            Assert.That(File.Exists(Path.Combine(unitTestFolder, "AllQuantifiedProteinGroups.tsv")));
            var lines = File.ReadAllLines(Path.Combine(unitTestFolder, "AllQuantifiedProteinGroups.tsv"));

            // check the intensity column headers
            var splitHeader            = lines[0].Split(new char[] { '\t' }).ToList();
            var intensityColumnHeaders = splitHeader.Where(p => p.Contains("Intensity", StringComparison.OrdinalIgnoreCase)).ToList();

            Assert.That(intensityColumnHeaders.Count == 2);

            if (!hasDefinedExperimentalDesign)
            {
                Assert.That(intensityColumnHeaders[0] == "Intensity_file_b0f0r0");
                Assert.That(intensityColumnHeaders[1] == "Intensity_file_b1f0r0");
            }
            else
            {
                Assert.That(intensityColumnHeaders[0] == "Intensity_TestCondition_1");
                Assert.That(intensityColumnHeaders[1] == "Intensity_TestCondition_2");
            }

            // check the protein intensity values
            int    ind1       = splitHeader.IndexOf(intensityColumnHeaders[0]);
            int    ind2       = splitHeader.IndexOf(intensityColumnHeaders[1]);
            double intensity1 = double.Parse(lines[1].Split(new char[] { '\t' })[ind1]);
            double intensity2 = double.Parse(lines[1].Split(new char[] { '\t' })[ind2]);

            Assert.That(intensity1 > 0);
            Assert.That(intensity2 > 0);
            Assert.That(intensity1 == intensity2);

            Directory.Delete(unitTestFolder, true);
        }
Пример #21
0
        //used for SILAC, generates multiple ms1 envelopes for the pwsms specified to simulate multiplexing
        //The mass difference(s) of the peaks are specified in listLabelMassDifferences. This is a double list, where there should be mass difference(s) specified for each peptide in pwsms
        //additionally, the precursor intensities can be specified (again a double list for each pwsm). This list should have the same number of lists as pwsms, and each internal list should have as many intensities as the number of mass differences+1 (for the original)
        //If listPrecursorIntensities is null, then the default functionality is to make each envelope half the intensity of the previous
        //numPeaksSeparatedByZeroes is used in some tests to evaluate that the silac quantification is using only ms1s where both a heavy and a light are evaluated.
        //The last obnoxiously long parameter allows for flashLFQ to quantify larger peptides. The default envelope has 3 isotopes with intensities of 1, 0.5, 0.25.
        //If this parameter is true, then 4 isotopes with intensities of 1, 1, 0.5, and 0.25 will be generated.
        public TestDataFile(List <PeptideWithSetModifications> pwsms, List <List <double> > listLabelMassDifferences,
                            List <List <double> > listPrecursorIntensities = null, int numPeaksSeparatedByZeroes = 1, bool largePeptideSoDoubleFirstPeakIntensityAndAddAnotherPeak = false)
            : base(2, new SourceFile(@"no nativeID format", "mzML format", null, "SHA-1", @"C:\fake.mzML", null))
        {
            List <MsDataScan> ScansHere = new List <MsDataScan>();
            int currentScanNumber       = 1;

            for (int pwsmIndex = 0; pwsmIndex < pwsms.Count; pwsmIndex++)
            {
                int precursorScanNumber            = currentScanNumber;
                PeptideWithSetModifications pwsm   = pwsms[pwsmIndex];
                List <double> labelMassDifferences = listLabelMassDifferences[pwsmIndex];
                List <double> precursorIntensities = listPrecursorIntensities == null ? null : listPrecursorIntensities[pwsmIndex];
                double        lightMass            = pwsm.MonoisotopicMass;
                for (int i = 0; i < labelMassDifferences.Count; i++)
                {
                    labelMassDifferences[i] += lightMass;
                }

                labelMassDifferences.Insert(0, lightMass);

                for (int chromatographicPeakNumber = 0; chromatographicPeakNumber < numPeaksSeparatedByZeroes; chromatographicPeakNumber++)
                {
                    if (chromatographicPeakNumber != 0) //separate with zeroes
                    {
                        var emptySpectrum = new MzSpectrum(new double[0], new double[0], false);
                        for (int skip = 0; skip < 5; skip++)
                        {
                            ScansHere.Add(new MsDataScan(emptySpectrum, currentScanNumber, 1, true, Polarity.Positive, currentScanNumber, new MzLibUtil.MzRange(0, 10000), "gg", MZAnalyzerType.Orbitrap, 1000, 1, null, "scan=" + currentScanNumber.ToString()));
                            currentScanNumber++;
                        }
                    }
                    List <double> mz1          = new List <double>();
                    List <double> intensities1 = new List <double>();
                    for (int z = 3; z >= 2; z--)
                    {
                        for (int i = 0; i < labelMassDifferences.Count; i++)
                        {
                            double mass = labelMassDifferences[i];

                            int numIsotopes = largePeptideSoDoubleFirstPeakIntensityAndAddAnotherPeak ? 4 : 3;
                            for (int isotope = 0; isotope < numIsotopes; isotope++)
                            {
                                mz1.Add((mass + isotope * Constants.C13MinusC12).ToMz(z));
                                if (precursorIntensities == null)
                                {
                                    if (largePeptideSoDoubleFirstPeakIntensityAndAddAnotherPeak && isotope != 0)
                                    {
                                        intensities1.Add(Math.Pow(0.5, i) * (Math.Pow(0.5, isotope - 1) * 1000000));
                                    }
                                    else
                                    {
                                        intensities1.Add(Math.Pow(0.5, i) * (Math.Pow(0.5, isotope) * 1000000)); //makes each label half the intensity of the previous
                                    }
                                }
                                else
                                {
                                    intensities1.Add(precursorIntensities[i] * (Math.Pow(0.5, isotope) * 1000000));
                                }
                            }
                        }
                    }
                    var MassSpectrum1 = new MzSpectrum(mz1.ToArray(), intensities1.ToArray(), false);
                    ScansHere.Add(new MsDataScan(MassSpectrum1, currentScanNumber, 1, true, Polarity.Positive, currentScanNumber, new MzLibUtil.MzRange(0, 10000), "gg", MZAnalyzerType.Orbitrap, intensities1.Sum(), 1, null, "scan=" + currentScanNumber.ToString()));
                    currentScanNumber++;

                    //only make the light ms2, it should find the heavy ms1 from that
                    List <double> mz2          = new List <double>();
                    List <double> intensities2 = new List <double>();
                    var           frags        = new List <Product>();
                    pwsm.Fragment(DissociationType.HCD, FragmentationTerminus.Both, frags);
                    foreach (var aok in frags)
                    {
                        mz2.Add(aok.NeutralMass.ToMz(1));
                        mz2.Add((aok.NeutralMass + Constants.C13MinusC12).ToMz(1));
                        intensities2.Add(1);
                        intensities2.Add(1);
                    }

                    var MassSpectrum2 = new MzSpectrum(mz2.OrderBy(b => b).ToArray(), intensities2.ToArray(), false);
                    ScansHere.Add(new MsDataScan(MassSpectrum2, currentScanNumber, 2, true, Polarity.Positive, currentScanNumber, new MzLibUtil.MzRange(0, 10000), "gg", MZAnalyzerType.Orbitrap, 234734, 1, null, "scan=" + currentScanNumber.ToString(), lightMass.ToMz(2), 2, 1, lightMass.ToMz(2), 2, DissociationType.HCD, precursorScanNumber, lightMass.ToMz(2)));
                    currentScanNumber++;

                    //if making additional ms1s for quant
                    if (precursorIntensities != null)
                    {
                        for (int i = 1; i < precursorIntensities.Count / (labelMassDifferences.Count); i++)
                        {
                            intensities1 = new List <double>();
                            for (int z = 3; z >= 2; z--)
                            {
                                for (int j = 0; j < labelMassDifferences.Count; j++)
                                {
                                    for (int isotope = 0; isotope < 3; isotope++)
                                    {
                                        intensities1.Add(precursorIntensities[(i) * labelMassDifferences.Count + j] * (Math.Pow(0.5, isotope) * 1000000));
                                    }
                                }
                            }
                            MassSpectrum1 = new MzSpectrum(mz1.ToArray(), intensities1.ToArray(), false);
                            ScansHere.Add(new MsDataScan(MassSpectrum1, currentScanNumber, 1, true, Polarity.Positive, currentScanNumber, new MzLibUtil.MzRange(0, 10000), "gg", MZAnalyzerType.Orbitrap, intensities1.Sum(), 1, null, "scan=" + currentScanNumber.ToString()));
                            currentScanNumber++;
                        }
                    }
                }
            }
            Scans = ScansHere.ToArray();
        }
        /// <summary>
        /// Localizes the deadend mod to a residue
        /// </summary>
        private CrosslinkSpectralMatch LocalizeDeadEndSite(PeptideWithSetModifications originalPeptide, Ms2ScanWithSpecificMass theScan, CommonParameters commonParameters,
                                                           List <int> possiblePositions, Modification deadEndMod, int notch, int scanIndex, int peptideIndex)
        {
            double bestScore = 0;
            List <MatchedFragmentIon>   bestMatchingFragments = new List <MatchedFragmentIon>();
            PeptideWithSetModifications bestLocalizedPeptide  = null;
            int bestPosition = 0;

            foreach (int location in possiblePositions)
            {
                Dictionary <int, Modification> mods = originalPeptide.AllModsOneIsNterminus.ToDictionary(p => p.Key, p => p.Value);
                if (mods.ContainsKey(location + 1))
                {
                    var          alreadyAnnotatedMod = mods[location + 1];
                    double       combinedMass        = mods[location + 1].MonoisotopicMass.Value + deadEndMod.MonoisotopicMass.Value;
                    Modification combinedMod         = new Modification(_originalId: alreadyAnnotatedMod.OriginalId + "+" + deadEndMod.OriginalId, _modificationType: "Crosslink", _target: alreadyAnnotatedMod.Target, _locationRestriction: "Anywhere.", _monoisotopicMass: combinedMass);
                    mods[location + 1] = combinedMod;
                }
                else
                {
                    mods.Add(location + 1, deadEndMod);
                }

                var localizedPeptide = new PeptideWithSetModifications(originalPeptide.Protein, originalPeptide.DigestionParams, originalPeptide.OneBasedStartResidueInProtein,
                                                                       originalPeptide.OneBasedEndResidueInProtein, originalPeptide.CleavageSpecificityForFdrCategory, originalPeptide.PeptideDescription, originalPeptide.MissedCleavages, mods, originalPeptide.NumFixedMods);

                var products            = localizedPeptide.Fragment(commonParameters.DissociationType, FragmentationTerminus.Both).ToList();
                var matchedFragmentIons = MatchFragmentIons(theScan, products, commonParameters);

                double score = CalculatePeptideScore(theScan.TheScan, matchedFragmentIons);

                if (score > bestScore)
                {
                    bestMatchingFragments = matchedFragmentIons;
                    bestScore             = score;
                    bestLocalizedPeptide  = localizedPeptide;
                    bestPosition          = location;
                }
            }

            if (bestScore < commonParameters.ScoreCutoff)
            {
                return(null);
            }

            var csm = new CrosslinkSpectralMatch(bestLocalizedPeptide, notch, bestScore, scanIndex, theScan, originalPeptide.DigestionParams, bestMatchingFragments);

            if (deadEndMod == TrisDeadEnd)
            {
                csm.CrossType = PsmCrossType.DeadEndTris;
            }
            else if (deadEndMod == H2ODeadEnd)
            {
                csm.CrossType = PsmCrossType.DeadEndH2O;
            }
            else if (deadEndMod == NH2DeadEnd)
            {
                csm.CrossType = PsmCrossType.DeadEndNH2;
            }

            csm.LinkPositions = new List <int> {
                bestPosition
            };
            csm.XlRank = new List <int> {
                peptideIndex
            };

            return(csm);
        }
Пример #23
0
        protected override MetaMorpheusEngineResults RunSpecific()
        {
            bool semiSpecificSearch = CommonParameters.DigestionParams.SearchModeType == CleavageSpecificity.Semi;

            double progress           = 0;
            int    oldPercentProgress = 0;

            ReportProgress(new ProgressEventArgs(oldPercentProgress, "Performing nonspecific search... " + CurrentPartition + "/" + CommonParameters.TotalPartitions, NestedIds));

            byte byteScoreCutoff = (byte)CommonParameters.ScoreCutoff;

            int maxThreadsPerFile = CommonParameters.MaxThreadsToUsePerFile;

            int[] threads = Enumerable.Range(0, maxThreadsPerFile).ToArray();
            Parallel.ForEach(threads, (i) =>
            {
                byte[] scoringTable = new byte[PeptideIndex.Count];
                HashSet <int> idsOfPeptidesPossiblyObserved = new HashSet <int>();

                for (; i < ListOfSortedMs2Scans.Length; i += maxThreadsPerFile)
                {
                    // Stop loop if canceled
                    if (GlobalVariables.StopLoops)
                    {
                        return;
                    }

                    // empty the scoring table to score the new scan (conserves memory compared to allocating a new array)
                    Array.Clear(scoringTable, 0, scoringTable.Length);
                    idsOfPeptidesPossiblyObserved.Clear();
                    Ms2ScanWithSpecificMass scan = ListOfSortedMs2Scans[i];

                    //get bins to add points to
                    List <int> allBinsToSearch = GetBinsToSearch(scan, FragmentIndex, CommonParameters.DissociationType);

                    //the entire indexed scoring is done here
                    for (int j = 0; j < allBinsToSearch.Count; j++)
                    {
                        FragmentIndex[allBinsToSearch[j]].ForEach(id => scoringTable[id]++);
                    }

                    //populate ids of possibly observed with those containing allowed precursor masses
                    List <AllowedIntervalWithNotch> validIntervals = MassDiffAcceptor.GetAllowedPrecursorMassIntervalsFromObservedMass(scan.PrecursorMass).ToList(); //get all valid notches
                    foreach (AllowedIntervalWithNotch interval in validIntervals)
                    {
                        int obsPrecursorFloorMz   = (int)Math.Floor(interval.AllowedInterval.Minimum * FragmentBinsPerDalton);
                        int obsPrecursorCeilingMz = (int)Math.Ceiling(interval.AllowedInterval.Maximum * FragmentBinsPerDalton);

                        foreach (ProductType pt in ProductTypesToSearch)
                        {
                            int dissociationBinShift = (int)Math.Round((WaterMonoisotopicMass - DissociationTypeCollection.GetMassShiftFromProductType(pt)) * FragmentBinsPerDalton);
                            int lowestBin            = obsPrecursorFloorMz - dissociationBinShift;
                            int highestBin           = obsPrecursorCeilingMz - dissociationBinShift;
                            for (int bin = lowestBin; bin <= highestBin; bin++)
                            {
                                if (bin < FragmentIndex.Length && FragmentIndex[bin] != null)
                                {
                                    FragmentIndex[bin].ForEach(id => idsOfPeptidesPossiblyObserved.Add(id));
                                }
                            }
                        }

                        for (int bin = obsPrecursorFloorMz; bin <= obsPrecursorCeilingMz; bin++) //no bin shift, since they're precursor masses
                        {
                            if (bin < PrecursorIndex.Length && PrecursorIndex[bin] != null)
                            {
                                PrecursorIndex[bin].ForEach(id => idsOfPeptidesPossiblyObserved.Add(id));
                            }
                        }
                    }

                    // done with initial scoring; refine scores and create PSMs
                    if (idsOfPeptidesPossiblyObserved.Any())
                    {
                        int maxInitialScore = idsOfPeptidesPossiblyObserved.Max(id => scoringTable[id]) + 1;
                        while (maxInitialScore > CommonParameters.ScoreCutoff) //go through all until we hit the end
                        {
                            maxInitialScore--;
                            foreach (int id in idsOfPeptidesPossiblyObserved.Where(id => scoringTable[id] == maxInitialScore))
                            {
                                PeptideWithSetModifications peptide = PeptideIndex[id];
                                List <Product> peptideTheorProducts = peptide.Fragment(CommonParameters.DissociationType, CommonParameters.DigestionParams.FragmentationTerminus).ToList();

                                Tuple <int, PeptideWithSetModifications> notchAndUpdatedPeptide = Accepts(peptideTheorProducts, scan.PrecursorMass, peptide, CommonParameters.DigestionParams.FragmentationTerminus, MassDiffAcceptor, semiSpecificSearch);
                                int notch = notchAndUpdatedPeptide.Item1;
                                if (notch >= 0)
                                {
                                    peptide = notchAndUpdatedPeptide.Item2;
                                    peptideTheorProducts = peptide.Fragment(CommonParameters.DissociationType, FragmentationTerminus.Both).ToList();
                                    List <MatchedFragmentIon> matchedIons = MatchFragmentIons(scan, peptideTheorProducts, ModifiedParametersNoComp);

                                    double thisScore = CalculatePeptideScore(scan.TheScan, matchedIons);
                                    if (thisScore > CommonParameters.ScoreCutoff)
                                    {
                                        PeptideSpectralMatch[] localPeptideSpectralMatches = GlobalCategorySpecificPsms[(int)FdrClassifier.GetCleavageSpecificityCategory(peptide.CleavageSpecificityForFdrCategory)];
                                        if (localPeptideSpectralMatches[i] == null)
                                        {
                                            localPeptideSpectralMatches[i] = new PeptideSpectralMatch(peptide, notch, thisScore, i, scan, CommonParameters.DigestionParams, matchedIons);
                                        }
                                        else
                                        {
                                            localPeptideSpectralMatches[i].AddOrReplace(peptide, thisScore, notch, CommonParameters.ReportAllAmbiguity, matchedIons, 0);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // report search progress
                    progress++;
                    int percentProgress = (int)((progress / ListOfSortedMs2Scans.Length) * 100);

                    if (percentProgress > oldPercentProgress)
                    {
                        oldPercentProgress = percentProgress;
                        ReportProgress(new ProgressEventArgs(percentProgress, "Performing nonspecific search... " + CurrentPartition + "/" + CommonParameters.TotalPartitions, NestedIds));
                    }
                }
            });
            return(new MetaMorpheusEngineResults(this));
        }
        /// <summary>
        ///
        /// </summary>
        private CrosslinkSpectralMatch FindCrosslinkedPeptide(Ms2ScanWithSpecificMass theScan, List <BestPeptideScoreNotch> theScanBestPeptide, int scanIndex)
        {
            List <CrosslinkSpectralMatch> possibleMatches = new List <CrosslinkSpectralMatch>();

            for (int alphaIndex = 0; alphaIndex < theScanBestPeptide.Count; alphaIndex++)
            {
                PeptideWithSetModifications bestPeptide = theScanBestPeptide[alphaIndex].BestPeptide;

                //Single Peptide
                if (XLPrecusorSearchMode.Accepts(theScan.PrecursorMass, bestPeptide.MonoisotopicMass) >= 0)
                {
                    List <Product> products            = bestPeptide.Fragment(CommonParameters.DissociationType, FragmentationTerminus.Both).ToList();
                    var            matchedFragmentIons = MatchFragmentIons(theScan, products, CommonParameters);
                    double         score = CalculatePeptideScore(theScan.TheScan, matchedFragmentIons);

                    var psmCrossSingle = new CrosslinkSpectralMatch(bestPeptide, theScanBestPeptide[alphaIndex].BestNotch, score, scanIndex, theScan, CommonParameters.DigestionParams, matchedFragmentIons)
                    {
                        CrossType = PsmCrossType.Single,
                        XlRank    = new List <int> {
                            alphaIndex
                        }
                    };

                    possibleMatches.Add(psmCrossSingle);
                }
                // Deadend Peptide
                else if (QuenchTris && XLPrecusorSearchMode.Accepts(theScan.PrecursorMass, bestPeptide.MonoisotopicMass + Crosslinker.DeadendMassTris) >= 0)
                {
                    List <int> possibleCrosslinkLocations = CrosslinkSpectralMatch.GetPossibleCrosslinkerModSites(AllCrosslinkerSites, bestPeptide);

                    if (possibleCrosslinkLocations.Any())
                    {
                        // tris deadend
                        possibleMatches.Add(LocalizeDeadEndSite(bestPeptide, theScan, CommonParameters, possibleCrosslinkLocations, TrisDeadEnd, theScanBestPeptide[alphaIndex].BestNotch, scanIndex, alphaIndex));
                    }
                }
                else if (QuenchH2O && XLPrecusorSearchMode.Accepts(theScan.PrecursorMass, bestPeptide.MonoisotopicMass + Crosslinker.DeadendMassH2O) >= 0)
                {
                    List <int> possibleCrosslinkLocations = CrosslinkSpectralMatch.GetPossibleCrosslinkerModSites(AllCrosslinkerSites, bestPeptide);

                    if (possibleCrosslinkLocations.Any())
                    {
                        // H2O deadend
                        possibleMatches.Add(LocalizeDeadEndSite(bestPeptide, theScan, CommonParameters, possibleCrosslinkLocations, H2ODeadEnd, theScanBestPeptide[alphaIndex].BestNotch, scanIndex, alphaIndex));
                    }
                }
                else if (QuenchNH2 && XLPrecusorSearchMode.Accepts(theScan.PrecursorMass, bestPeptide.MonoisotopicMass + Crosslinker.DeadendMassNH2) >= 0)
                {
                    List <int> possibleCrosslinkLocations = CrosslinkSpectralMatch.GetPossibleCrosslinkerModSites(AllCrosslinkerSites, bestPeptide);

                    if (possibleCrosslinkLocations.Any())
                    {
                        // NH2 deadend
                        possibleMatches.Add(LocalizeDeadEndSite(bestPeptide, theScan, CommonParameters, possibleCrosslinkLocations, NH2DeadEnd, theScanBestPeptide[alphaIndex].BestNotch, scanIndex, alphaIndex));
                    }
                }
                // loop peptide
                else if (Crosslinker.LoopMass != 0 && XLPrecusorSearchMode.Accepts(theScan.PrecursorMass, bestPeptide.MonoisotopicMass + Crosslinker.LoopMass) >= 0)
                {
                    List <int> possibleCrosslinkLocations = CrosslinkSpectralMatch.GetPossibleCrosslinkerModSites(AllCrosslinkerSites, bestPeptide);

                    if (possibleCrosslinkLocations.Count >= 2)
                    {
                        possibleMatches.Add(LocalizeLoopSites(bestPeptide, theScan, CommonParameters, possibleCrosslinkLocations, Loop, theScanBestPeptide[alphaIndex].BestNotch, scanIndex, alphaIndex));
                    }
                }
                // Cross-linked peptide
                else if (theScan.PrecursorMass - bestPeptide.MonoisotopicMass >= (CommonParameters.DigestionParams.MinPeptideLength * 50))
                {
                    List <int> possibleCrosslinkLocations = CrosslinkSpectralMatch.GetPossibleCrosslinkerModSites(AllCrosslinkerSites, bestPeptide);
                    if (!possibleCrosslinkLocations.Any())
                    {
                        continue;
                    }

                    PeptideWithSetModifications alphaPeptide = bestPeptide;

                    for (int betaIndex = 0; betaIndex < theScanBestPeptide.Count; betaIndex++)
                    {
                        PeptideWithSetModifications betaPeptide = theScanBestPeptide[betaIndex].BestPeptide;

                        if (XLPrecusorSearchMode.Accepts(theScan.PrecursorMass, alphaPeptide.MonoisotopicMass + betaPeptide.MonoisotopicMass + Crosslinker.TotalMass) >= 0)
                        {
                            List <int> possibleBetaCrosslinkSites = CrosslinkSpectralMatch.GetPossibleCrosslinkerModSites(AllCrosslinkerSites, betaPeptide);

                            if (!possibleBetaCrosslinkSites.Any())
                            {
                                continue;
                            }

                            CrosslinkSpectralMatch csm = LocalizeCrosslinkSites(theScan, theScanBestPeptide[alphaIndex], theScanBestPeptide[betaIndex], Crosslinker, alphaIndex, betaIndex);

                            possibleMatches.Add(csm);
                        }
                    }
                }
            }

            // get the best match for this spectrum
            // bestPsmCross will be null if there are no valid hits
            possibleMatches.RemoveAll(v => v == null);
            possibleMatches = possibleMatches.OrderByDescending(p => p.XLTotalScore).ToList();
            var bestPsmCross = possibleMatches.FirstOrDefault();

            // resolve ambiguities
            if (bestPsmCross != null)
            {
                bestPsmCross.ResolveAllAmbiguities();

                if (bestPsmCross.BetaPeptide != null)
                {
                    bestPsmCross.BetaPeptide.ResolveAllAmbiguities();
                }
            }

            // calculate delta score
            if (possibleMatches.Count > 1)
            {
                bestPsmCross.DeltaScore = possibleMatches[0].XLTotalScore - possibleMatches[1].XLTotalScore;
            }

            return(bestPsmCross);
        }
Пример #25
0
        /// <summary>
        ///
        /// </summary>
        private List <CrosslinkSpectralMatch> FindCrosslinkedPeptide(Ms2ScanWithSpecificMass theScan, List <BestPeptideScoreNotch> theScanBestPeptide, int scanIndex)
        {
            List <CrosslinkSpectralMatch> possibleMatches = new List <CrosslinkSpectralMatch>();

            for (int alphaIndex = 0; alphaIndex < theScanBestPeptide.Count; alphaIndex++)
            {
                PeptideWithSetModifications bestPeptide = theScanBestPeptide[alphaIndex].BestPeptide;

                //Single Peptide
                if (XLPrecusorSearchMode.Accepts(theScan.PrecursorMass, bestPeptide.MonoisotopicMass) >= 0)
                {
                    List <Product> products            = bestPeptide.Fragment(CommonParameters.DissociationType, FragmentationTerminus.Both).ToList();
                    var            matchedFragmentIons = MatchFragmentIons(theScan, products, CommonParameters);
                    double         score = CalculatePeptideScore(theScan.TheScan, matchedFragmentIons);

                    var psmCrossSingle = new CrosslinkSpectralMatch(bestPeptide, theScanBestPeptide[alphaIndex].BestNotch, score, scanIndex, theScan, CommonParameters.DigestionParams, matchedFragmentIons)
                    {
                        CrossType = PsmCrossType.Single,
                        XlRank    = new List <int> {
                            alphaIndex
                        }
                    };

                    possibleMatches.Add(psmCrossSingle);
                }
                // Deadend Peptide
                else if (QuenchTris && XLPrecusorSearchMode.Accepts(theScan.PrecursorMass, bestPeptide.MonoisotopicMass + Crosslinker.DeadendMassTris) >= 0)
                {
                    List <int> possibleCrosslinkLocations = CrosslinkSpectralMatch.GetPossibleCrosslinkerModSites(AllCrosslinkerSites, bestPeptide);

                    if (possibleCrosslinkLocations.Any())
                    {
                        // tris deadend
                        possibleMatches.Add(LocalizeDeadEndSite(bestPeptide, theScan, CommonParameters, possibleCrosslinkLocations, TrisDeadEnd, theScanBestPeptide[alphaIndex].BestNotch, scanIndex, alphaIndex));
                    }
                }
                else if (QuenchH2O && XLPrecusorSearchMode.Accepts(theScan.PrecursorMass, bestPeptide.MonoisotopicMass + Crosslinker.DeadendMassH2O) >= 0)
                {
                    List <int> possibleCrosslinkLocations = CrosslinkSpectralMatch.GetPossibleCrosslinkerModSites(AllCrosslinkerSites, bestPeptide);

                    if (possibleCrosslinkLocations.Any())
                    {
                        // H2O deadend
                        possibleMatches.Add(LocalizeDeadEndSite(bestPeptide, theScan, CommonParameters, possibleCrosslinkLocations, H2ODeadEnd, theScanBestPeptide[alphaIndex].BestNotch, scanIndex, alphaIndex));
                    }
                }
                else if (QuenchNH2 && XLPrecusorSearchMode.Accepts(theScan.PrecursorMass, bestPeptide.MonoisotopicMass + Crosslinker.DeadendMassNH2) >= 0)
                {
                    List <int> possibleCrosslinkLocations = CrosslinkSpectralMatch.GetPossibleCrosslinkerModSites(AllCrosslinkerSites, bestPeptide);

                    if (possibleCrosslinkLocations.Any())
                    {
                        // NH2 deadend
                        possibleMatches.Add(LocalizeDeadEndSite(bestPeptide, theScan, CommonParameters, possibleCrosslinkLocations, NH2DeadEnd, theScanBestPeptide[alphaIndex].BestNotch, scanIndex, alphaIndex));
                    }
                }
                // loop peptide
                else if (Crosslinker.LoopMass != 0 && XLPrecusorSearchMode.Accepts(theScan.PrecursorMass, bestPeptide.MonoisotopicMass + Crosslinker.LoopMass) >= 0)
                {
                    List <int> possibleCrosslinkLocations = CrosslinkSpectralMatch.GetPossibleCrosslinkerModSites(AllCrosslinkerSites, bestPeptide);

                    if (possibleCrosslinkLocations.Count >= 2)
                    {
                        possibleMatches.Add(LocalizeLoopSites(bestPeptide, theScan, CommonParameters, possibleCrosslinkLocations, Loop, theScanBestPeptide[alphaIndex].BestNotch, scanIndex, alphaIndex));
                    }
                }
                // Cross-linked peptide
                else if (theScan.PrecursorMass - bestPeptide.MonoisotopicMass >= (CommonParameters.DigestionParams.MinPeptideLength * 50))
                {
                    List <int> possibleCrosslinkLocations = CrosslinkSpectralMatch.GetPossibleCrosslinkerModSites(AllCrosslinkerSites, bestPeptide);
                    if (!possibleCrosslinkLocations.Any())
                    {
                        continue;
                    }

                    PeptideWithSetModifications alphaPeptide = bestPeptide;

                    for (int betaIndex = 0; betaIndex < theScanBestPeptide.Count; betaIndex++)
                    {
                        PeptideWithSetModifications betaPeptide = theScanBestPeptide[betaIndex].BestPeptide;

                        if (XLPrecusorSearchMode.Accepts(theScan.PrecursorMass, alphaPeptide.MonoisotopicMass + betaPeptide.MonoisotopicMass + Crosslinker.TotalMass) >= 0)
                        {
                            List <int> possibleBetaCrosslinkSites = CrosslinkSpectralMatch.GetPossibleCrosslinkerModSites(AllCrosslinkerSites, betaPeptide);

                            if (!possibleBetaCrosslinkSites.Any())
                            {
                                continue;
                            }

                            CrosslinkSpectralMatch csm = LocalizeCrosslinkSites(theScan, theScanBestPeptide[alphaIndex], theScanBestPeptide[betaIndex], Crosslinker, alphaIndex, betaIndex);

                            possibleMatches.Add(csm);
                        }
                    }
                }
            }

            return(possibleMatches);
        }
        public static Dictionary <Tuple <int, int>, List <Product> > XlLoopGetTheoreticalFragments(DissociationType dissociationType, Modification loopMass,
                                                                                                   List <int> modPos, PeptideWithSetModifications peptide)
        {
            Dictionary <Tuple <int, int>, List <Product> > AllTheoreticalFragmentsLists = new Dictionary <Tuple <int, int>, List <Product> >();
            var originalFragments = new List <Product>();

            peptide.Fragment(dissociationType, FragmentationTerminus.Both, originalFragments);
            var loopProducts = new List <Product>();

            foreach (int position1 in modPos)
            {
                foreach (int position2 in modPos)
                {
                    if (position2 <= position1)
                    {
                        continue;
                    }

                    // add N and C terminal fragments that do not contain the loop
                    Tuple <int, int> loopPositions = new Tuple <int, int>(position1, position2);
                    List <Product>   loopFragments = originalFragments
                                                     .Where(p => p.Terminus == FragmentationTerminus.N && p.AminoAcidPosition <position1 ||
                                                                                                                               p.Terminus == FragmentationTerminus.C && p.AminoAcidPosition> position2).ToList();

                    // add N-terminal fragments containing the loop
                    Dictionary <int, Modification> modDict = new Dictionary <int, Modification>();
                    if (peptide.AllModsOneIsNterminus.Any())
                    {
                        double       combinedModMass = loopMass.MonoisotopicMass.Value + peptide.AllModsOneIsNterminus.Where(v => v.Key <= position2 + 1).Sum(p => p.Value.MonoisotopicMass.Value);
                        Modification combined        = new Modification(_monoisotopicMass: combinedModMass);
                        modDict.Add(position1 + 1, combined);

                        foreach (var mod in peptide.AllModsOneIsNterminus.Where(m => m.Key > position2 + 1))
                        {
                            modDict.Add(mod.Key, mod.Value);
                        }
                    }
                    else
                    {
                        modDict.Add(position1 + 1, loopMass);
                    }
                    PeptideWithSetModifications peptideWithLoop = new PeptideWithSetModifications(peptide.Protein, peptide.DigestionParams,
                                                                                                  peptide.OneBasedStartResidueInProtein, peptide.OneBasedEndResidueInProtein, peptide.CleavageSpecificityForFdrCategory,
                                                                                                  peptide.PeptideDescription, peptide.MissedCleavages, modDict, peptide.NumFixedMods);

                    peptideWithLoop.Fragment(dissociationType, FragmentationTerminus.Both, loopProducts);
                    loopFragments.AddRange(loopProducts.Where(p => p.Terminus == FragmentationTerminus.N && p.AminoAcidPosition >= position2));

                    // add C-terminal fragments containing the loop
                    modDict.Clear();
                    if (peptide.AllModsOneIsNterminus.Any())
                    {
                        double       combinedModMass = loopMass.MonoisotopicMass.Value + peptide.AllModsOneIsNterminus.Where(v => v.Key >= position1 + 1).Sum(p => p.Value.MonoisotopicMass.Value);
                        Modification combined        = new Modification(_monoisotopicMass: combinedModMass);
                        modDict.Add(position2 + 1, combined);

                        foreach (var mod in peptide.AllModsOneIsNterminus.Where(m => m.Key < position1 + 1))
                        {
                            modDict.Add(mod.Key, mod.Value);
                        }
                    }
                    else
                    {
                        modDict.Add(position2 + 1, loopMass);
                    }
                    peptideWithLoop = new PeptideWithSetModifications(peptide.Protein, peptide.DigestionParams,
                                                                      peptide.OneBasedStartResidueInProtein, peptide.OneBasedEndResidueInProtein, peptide.CleavageSpecificityForFdrCategory,
                                                                      peptide.PeptideDescription, peptide.MissedCleavages, modDict, peptide.NumFixedMods);

                    peptideWithLoop.Fragment(dissociationType, FragmentationTerminus.Both, loopProducts);
                    loopFragments.AddRange(
                        loopProducts.Where(p => p.Terminus == FragmentationTerminus.C && p.AminoAcidPosition <= position1));

                    AllTheoreticalFragmentsLists.Add(loopPositions, loopFragments);
                }
            }

            return(AllTheoreticalFragmentsLists);
        }
Пример #27
0
        protected override MetaMorpheusEngineResults RunSpecific()
        {
            // don't try to localize mass differences for ambiguous peptides
            PeptideSpectralMatch[] unambiguousPsms = AllResultingIdentifications.Where(b => b.FullSequence != null).ToArray();

            double psmsSearched       = 0;
            int    oldPercentProgress = 0;

            ReportProgress(new ProgressEventArgs(oldPercentProgress, "Localizing mass-differences... ", NestedIds));

            Parallel.ForEach(Partitioner.Create(0, unambiguousPsms.Length),
                             new ParallelOptions {
                MaxDegreeOfParallelism = CommonParameters.MaxThreadsToUsePerFile
            },
                             (range, loopState) =>
            {
                for (int i = range.Item1; i < range.Item2; i++)
                {
                    PeptideSpectralMatch psm = unambiguousPsms[i];

                    // Stop loop if canceled
                    if (GlobalVariables.StopLoops)
                    {
                        break;
                    }

                    MsDataScan scan = MyMsDataFile.GetOneBasedScan(psm.ScanNumber);
                    Ms2ScanWithSpecificMass scanWithSpecificMass = new Ms2ScanWithSpecificMass(scan, psm.ScanPrecursorMonoisotopicPeakMz, psm.ScanPrecursorCharge, psm.FullFilePath, CommonParameters);
                    PeptideWithSetModifications peptide          = psm.BestMatchingPeptides.First().Peptide;
                    double massDifference = psm.ScanPrecursorMass - peptide.MonoisotopicMass;

                    // this section will iterate through all residues of the peptide and try to localize the mass-diff at each residue and report a score for each residue
                    var localizedScores = new List <double>();
                    for (int r = 0; r < peptide.Length; r++)
                    {
                        // create new PeptideWithSetMods with unidentified mass difference at the given residue
                        PeptideWithSetModifications peptideWithLocalizedMassDiff = peptide.Localize(r, massDifference);

                        // this is the list of theoretical products for this peptide with mass-difference on this residue
                        List <Product> productsWithLocalizedMassDiff = peptideWithLocalizedMassDiff.Fragment(CommonParameters.DissociationType, CommonParameters.DigestionParams.FragmentationTerminus).ToList();

                        var matchedIons = MatchFragmentIons(scanWithSpecificMass, productsWithLocalizedMassDiff, CommonParameters);

                        // score when the mass-diff is on this residue
                        double localizedScore = CalculatePeptideScore(scan, matchedIons);

                        localizedScores.Add(localizedScore);
                    }

                    psm.LocalizedScores = localizedScores;

                    // report search progress (PSM mass differences localized so far out of total)
                    psmsSearched++;
                    var percentProgress = (int)((psmsSearched / unambiguousPsms.Length) * 100);

                    if (percentProgress > oldPercentProgress)
                    {
                        oldPercentProgress = percentProgress;
                        ReportProgress(new ProgressEventArgs(percentProgress, "Localizing mass-differences... ", NestedIds));
                    }
                }
            });

            return(new LocalizationEngineResults(this));
        }