Ejemplo n.º 1
0
        public void MultiLabelExplicitSerialTest()
        {
            // Create a simple document and add two peptides
            SrmDocument  document     = new SrmDocument(SrmSettingsList.GetDefault());
            const string pepSequence1 = "QFVLSCVILR";
            const string pepSequence2 = "DIEVYCDGAITTK";
            var          reader       = new StringReader(string.Join("\n", new[] { ">peptides1", pepSequence1, pepSequence2 }));
            IdentityPath path;

            document = document.ImportFasta(reader, true, IdentityPath.ROOT, out path);
            Assert.AreEqual(2, document.PeptideCount);

            // Add some modifications in two new label types
            var modCarb      = new StaticMod("Carbamidomethyl Cysteine", "C", null, "C2H3ON");
            var modOther     = new StaticMod("Another Cysteine", "C", null, "CO8N2");
            var staticMods   = new[] { modCarb, modOther };
            var mod15N       = new StaticMod("All 15N", null, null, null, LabelAtoms.N15, null, null);
            var modK13C      = new StaticMod("13C K", "K", ModTerminus.C, null, LabelAtoms.C13, null, null);
            var modR13C      = new StaticMod("13C R", "R", ModTerminus.C, null, LabelAtoms.C13, null, null);
            var modV13C      = new StaticMod("Heavy V", "V", null, null, LabelAtoms.C13 | LabelAtoms.N15, null, null);
            var heavyMods    = new[] { mod15N, modK13C, modR13C, modV13C };
            var labelTypeAA  = new IsotopeLabelType("heavy AA", IsotopeLabelType.FirstHeavy);
            var labelTypeAll = new IsotopeLabelType("heavy All", IsotopeLabelType.FirstHeavy + 1);

            var settings = document.Settings;

            settings = settings.ChangePeptideModifications(mods =>
                                                           new PeptideModifications(mods.StaticModifications,
                                                                                    new[]
            {
                new TypedModifications(labelTypeAA, new[] { modK13C, modR13C }),
                new TypedModifications(labelTypeAll, new[] { mod15N })
            }));
            document = document.ChangeSettings(settings);
            Assert.AreEqual(6, document.PeptideTransitionGroupCount);

            // Add modifications to light and heavy AA in the first peptide
            path = document.GetPathTo((int)SrmDocument.Level.Molecules, 0);
            var nodePepMod  = (PeptideDocNode)document.FindNode(path);
            var explicitMod = new ExplicitMods(nodePepMod.Peptide,
                                               new[] { new ExplicitMod(pepSequence1.IndexOf('C'), modOther) },
                                               new[] { new TypedExplicitModifications(nodePepMod.Peptide, labelTypeAA, new ExplicitMod[0]) });

            document = document.ChangePeptideMods(path, explicitMod, staticMods, heavyMods);
            Assert.AreEqual(5, document.PeptideTransitionGroupCount);

            // Add a modification to heavy All in the second peptide
            path        = document.GetPathTo((int)SrmDocument.Level.Molecules, 1);
            nodePepMod  = (PeptideDocNode)document.FindNode(path);
            explicitMod = new ExplicitMods(nodePepMod.Peptide, null,
                                           new[] { new TypedExplicitModifications(nodePepMod.Peptide, labelTypeAll,
                                                                                  new[] { new ExplicitMod(pepSequence2.IndexOf('V'), modV13C) }) });
            document = document.ChangePeptideMods(path, explicitMod, staticMods, heavyMods);
            Assert.AreEqual(5, document.PeptideTransitionGroupCount);

            AssertEx.Serializable(document, 3, AssertEx.DocumentCloned);
        }
Ejemplo n.º 2
0
        public static void CreateAndShowFindResults(ZedGraphControl sender, GraphSummary graphSummary, SrmDocument document, AreaCVGraphData.CVData data)
        {
            var peptideAnnotationPairs = data.PeptideAnnotationPairs.ToList();
            var results = new List <FindResult>(peptideAnnotationPairs.Count);

            var pred = new FindPredicate(new FindOptions().ChangeCustomFinders(new[] { new PeptideAnnotationPairFinder(peptideAnnotationPairs, data.CV) }), Program.MainWindow.SequenceTree.GetDisplaySettings(null));

            for (var i = 0; i < Math.Min(peptideAnnotationPairs.Count, MAX_FINDRESULTS_PEPTIDES); i++)
            {
                var pair        = peptideAnnotationPairs[i];
                var displayText = PeptideAnnotationPairFinder.GetDisplayText(data.CV, pair.Annotation);

                results.Add(new FindResult(pred,
                                           new BookmarkEnumerator(document,
                                                                  new Bookmark(document.GetPathTo((int)SrmDocument.Level.Molecules,
                                                                                                  document.Molecules.ToList().IndexOf(pair.Peptide)))), new FindMatch(displayText)));
            }

            var count = peptideAnnotationPairs.Count;

            if (results.Count != count)
            {
                MessageDlg.Show(sender, string.Format(Resources.HistogramHelper_CreateAndShowFindResults_Only_showing__0___1__peptides, MAX_FINDRESULTS_PEPTIDES, count));
                results = results.GetRange(0, MAX_FINDRESULTS_PEPTIDES);
            }

            if (peptideAnnotationPairs.Count == 1)
            {
                var nodes = peptideAnnotationPairs[0];
                graphSummary.StateProvider.SelectedPath = new IdentityPath(nodes.PeptideGroup.PeptideGroup, nodes.Peptide.Peptide);
            }

            Program.MainWindow.ShowFindResults(results);
        }
Ejemplo n.º 3
0
        public void NeutralLossListTest()
        {
            TestSmallMolecules = false; // No concept of neutral loss for small molecules

            var phosphoLossMod = new StaticMod("Phospho Loss", "S, T, Y", null, false, "HPO3",
                                               LabelAtoms.None, RelativeRT.Matching, null, null, new[] { new FragmentLoss("H3PO4"), });

            SrmDocument document = new SrmDocument(SrmSettingsList.GetDefault().ChangePeptideModifications(mods =>
                                                                                                           mods.ChangeStaticModifications(new List <StaticMod>(mods.StaticModifications)
            {
                phosphoLossMod
            })));
            IdentityPath path     = IdentityPath.ROOT;
            SrmDocument  docFasta = document.ImportFasta(new StringReader(TEXT_FASTA_YEAST_7), false, path, out path);

            Assert.AreEqual(0, GetLossCount(docFasta, 1));

            // Insert losses into the first transition group
            var pathPeptide  = docFasta.GetPathTo((int)SrmDocument.Level.Molecules, 0);
            var nodePep      = (PeptideDocNode)docFasta.FindNode(pathPeptide);
            var nodeGroup    = (TransitionGroupDocNode)nodePep.Children[0];
            var listChildren = new List <DocNode>(nodeGroup.Children);

            foreach (var nodeTran in nodeGroup.GetTransitions(docFasta.Settings,
                                                              nodePep.ExplicitMods, nodeGroup.PrecursorMz, null, null, null, false))
            {
                if (!nodeTran.HasLoss)
                {
                    continue;
                }

                var tran       = nodeTran.Transition;
                int matchIndex = listChildren.IndexOf(node =>
                                                      Equals(tran, ((TransitionDocNode)node).Transition));
                if (matchIndex == -1)
                {
                    continue;
                }

                while (matchIndex < listChildren.Count &&
                       Equals(tran, ((TransitionDocNode)listChildren[matchIndex]).Transition))
                {
                    matchIndex++;
                }
                listChildren.Insert(matchIndex, nodeTran);
            }

            var docLosses = (SrmDocument)docFasta.ReplaceChild(pathPeptide,
                                                               nodeGroup.ChangeChildren(listChildren));

            int lossCount = GetLossCount(docLosses, 1);

            Assert.IsTrue(lossCount > 0);
            var docRoundTripped = AssertEx.RoundTripTransitionList(new ThermoMassListExporter(docLosses));

            Assert.AreEqual(lossCount, GetLossCount(docRoundTripped, 1));
            docRoundTripped = AssertEx.RoundTripTransitionList(new AgilentMassListExporter(docLosses));
            Assert.AreEqual(lossCount, GetLossCount(docRoundTripped, 1));
        }
Ejemplo n.º 4
0
        private SrmDocument RemoveTransitions(SrmDocument document, params int[] indexes)
        {
            foreach (var i in indexes)
            {
                var pathToTran = document.GetPathTo((int)SrmDocument.Level.Transitions, i - 1);  // Numbers are from the 1-based status bar
                document = (SrmDocument)document.RemoveChild(pathToTran.Parent, document.FindNode(pathToTran));
            }

            return(document);
        }
Ejemplo n.º 5
0
        private static SrmDocument CreateMixedDoc()
        {
            SrmDocument  document = new SrmDocument(SrmSettingsList.GetDefault0_6());
            IdentityPath path;
            // Add fasta sequences
            SrmDocument docFasta = document.ImportFasta(new StringReader(ExampleText.TEXT_FASTA_YEAST),
                                                        false, IdentityPath.ROOT, out path);

            AssertEx.IsDocumentState(docFasta, 1, 2, 98, 311);
            // Insert peptide list at beginnning
            SrmDocument docMixed = docFasta.ImportFasta(new StringReader(SrmDocEditTest.TEXT_BOVINE_PEPTIDES1),
                                                        true, docFasta.GetPathTo(0), out path);

            AssertEx.IsDocumentState(docMixed, 2, 3, 111, 352);
            return(docMixed);
        }
Ejemplo n.º 6
0
        public void ModifyExplicitModTest()
        {
            SrmDocument docStudy7      = CreateStudy7Doc();
            var         settings       = docStudy7.Settings.ChangeTransitionFilter(filter => filter.ChangeAutoSelect(false));
            var         listStaticMods = settings.PeptideSettings.Modifications.StaticModifications;
            var         listHeavyMods  = new List <StaticMod>(settings.PeptideSettings.Modifications.AllHeavyModifications);

            // Change an explicit heavy modification to something new
            var modV = new StaticMod("Heavy V", "V", null, LabelAtoms.C13 | LabelAtoms.N15);

            listHeavyMods.Add(modV);

            IdentityPath path         = docStudy7.GetPathTo((int)SrmDocument.Level.Molecules, 0);
            var          peptideMod   = (PeptideDocNode)docStudy7.FindNode(path);
            var          explicitMods = peptideMod.ExplicitMods;

            explicitMods = explicitMods.ChangeHeavyModifications(new[] { explicitMods.HeavyModifications[0].ChangeModification(modV) });
            var docHeavyV = docStudy7.ChangePeptideMods(path, explicitMods, listStaticMods, listHeavyMods);

            var modSettings = docHeavyV.Settings.PeptideSettings.Modifications;

            Assert.AreEqual(5, modSettings.AllHeavyModifications.Count());
            Assert.AreEqual(4, modSettings.AllHeavyModifications.Count(mod => mod.Formula != null));
            Assert.AreEqual(1, modSettings.AllHeavyModifications.Count(mod => mod.Label13C && mod.Label15N));
            Assert.AreEqual(3, docHeavyV.Peptides.Count(peptide => peptide.HasExplicitMods));
            Assert.AreEqual(1, docHeavyV.Peptides.Count(peptide => peptide.HasExplicitMods &&
                                                        peptide.ExplicitMods.HeavyModifications[0].Modification.AAs[0] == 'V' &&
                                                        peptide.ExplicitMods.HeavyModifications[0].Modification.Label13C));
            Assert.AreEqual(1, docHeavyV.Peptides.Count(peptide => peptide.HasExplicitMods &&
                                                        peptide.ExplicitMods.HeavyModifications[0].Modification.AAs[0] == 'V' &&
                                                        peptide.ExplicitMods.HeavyModifications[0].Modification.Label13C &&
                                                        peptide.ExplicitMods.HeavyModifications[0].Modification.Label15N));

            // Change an explicit heavy modification to something new
            listHeavyMods = new List <StaticMod>(settings.PeptideSettings.Modifications.AllHeavyModifications);
            modV          = listHeavyMods[2] = ATOMIC_HEAVY_MODS[2];

            explicitMods = peptideMod.ExplicitMods;
            explicitMods = explicitMods.ChangeHeavyModifications(new[] { explicitMods.HeavyModifications[0].ChangeModification(modV) });
            var doc13V = docStudy7.ChangePeptideMods(path, explicitMods, listStaticMods, listHeavyMods);

            modSettings = doc13V.Settings.PeptideSettings.Modifications;
            Assert.AreEqual(4, modSettings.AllHeavyModifications.Count());
            Assert.AreEqual(3, modSettings.AllHeavyModifications.Count(mod => mod.Formula != null));
            Assert.AreEqual(1, modSettings.AllHeavyModifications.Count(mod => mod.Label13C));
            Assert.AreEqual(3, doc13V.Peptides.Count(peptide => peptide.HasExplicitMods));
            Assert.AreEqual(2, doc13V.Peptides.Count(peptide => peptide.HasExplicitMods &&
                                                     peptide.ExplicitMods.HeavyModifications[0].Modification.AAs[0] == 'V' &&
                                                     peptide.ExplicitMods.HeavyModifications[0].Modification.Label13C));

            // No change to the peptide, but change an orthoganal modification
            path       = docStudy7.GetPathTo((int)SrmDocument.Level.Molecules, docStudy7.Peptides.Count() - 1);
            peptideMod = (PeptideDocNode)docStudy7.FindNode(path);
            doc13V     = docStudy7.ChangePeptideMods(path, peptideMod.ExplicitMods, listStaticMods, listHeavyMods);

            modSettings = doc13V.Settings.PeptideSettings.Modifications;
            Assert.AreEqual(4, modSettings.AllHeavyModifications.Count());
            Assert.AreEqual(3, modSettings.AllHeavyModifications.Count(mod => mod.Formula != null));
            Assert.AreEqual(1, modSettings.AllHeavyModifications.Count(mod => mod.Label13C));
            Assert.AreEqual(3, doc13V.Peptides.Count(peptide => peptide.HasExplicitMods));
            Assert.AreEqual(2, doc13V.Peptides.Count(peptide => peptide.HasExplicitMods &&
                                                     peptide.ExplicitMods.HeavyModifications[0].Modification.AAs[0] == 'V' &&
                                                     peptide.ExplicitMods.HeavyModifications[0].Modification.Label13C));

            // No change to the peptide, but remove all other modifications from global lists
            var docClear = docStudy7.ChangePeptideMods(path, peptideMod.ExplicitMods,
                                                       new StaticMod[0], new[] { listHeavyMods[3] });

            Assert.AreSame(docClear, docStudy7);

            // Remove explicit modifications from the global lists
            listHeavyMods.RemoveRange(2, 2);
            // Mimic the way PeptideSettingsUI would change the settings
            var docRemoveExplicit = docStudy7.ChangeSettings(docStudy7.Settings.ChangePeptideModifications(
                                                                 mods => mods.ChangeModifications(IsotopeLabelType.heavy, listHeavyMods)
                                                                 .DeclareExplicitMods(docStudy7, listStaticMods, listHeavyMods)));

            // Test expected changes
            modSettings = docRemoveExplicit.Settings.PeptideSettings.Modifications;
            Assert.AreEqual(2, modSettings.AllHeavyModifications.Count());
            Assert.AreEqual(3, docRemoveExplicit.Peptides.Count(peptide => peptide.HasExplicitMods));
            // Should leave no heavy modifications on the explicitly modified peptides
            Assert.AreEqual(0, docRemoveExplicit.Peptides.Count(peptide => peptide.HasExplicitMods &&
                                                                peptide.ExplicitMods.HeavyModifications.Count > 0));
        }
Ejemplo n.º 7
0
        private void PerformTestMeasuredDriftValues(bool asSmallMolecules)
        {
            if (asSmallMolecules)
            {
                if (!RunSmallMoleculeTestVersions)
                {
                    Console.Write(MSG_SKIPPING_SMALLMOLECULE_TEST_VERSION);
                    return;
                }
                TestSmallMolecules = false;                                                          // No need to add the magic small molecule test node
            }
            var testFilesDir = new TestFilesDir(TestContext, @"Test\Results\BlibDriftTimeTest.zip"); // Re-used from BlibDriftTimeTest
            // Open document with some peptides but no results
            var docPath = testFilesDir.GetTestPath("BlibDriftTimeTest.sky");
            // This was a malformed document, which caused problems after a fix to not recalculate
            // document library settings on open. To avoid rewriting this test for the document
            // which now contains 2 precursors, the first precursor is removed immediately.
            SrmDocument docOriginal      = ResultsUtil.DeserializeDocument(docPath);
            var         pathFirstPeptide = docOriginal.GetPathTo((int)SrmDocument.Level.Molecules, 0);
            var         nodeFirstPeptide = (DocNodeParent)docOriginal.FindNode(pathFirstPeptide);

            docOriginal = (SrmDocument)docOriginal.RemoveChild(pathFirstPeptide, nodeFirstPeptide.Children[0]);
            if (asSmallMolecules)
            {
                var refine = new RefinementSettings();
                docOriginal = refine.ConvertToSmallMolecules(docOriginal, testFilesDir.FullPath);
            }
            using (var docContainer = new ResultsTestDocumentContainer(docOriginal, docPath))
            {
                var doc = docContainer.Document;

                // Import an mz5 file that contains drift info
                const string replicateName = "ID12692_01_UCA168_3727_040714";
                var          chromSets     = new[]
                {
                    new ChromatogramSet(replicateName, new[]
                                        { new MsDataFilePath(testFilesDir.GetTestPath("ID12692_01_UCA168_3727_040714" + ExtensionTestContext.ExtMz5)), }),
                };
                var docResults = doc.ChangeMeasuredResults(new MeasuredResults(chromSets));
                Assert.IsTrue(docContainer.SetDocument(docResults, docOriginal, true));
                docContainer.AssertComplete();
                var document = docContainer.Document;
                document = document.ChangeSettings(document.Settings.ChangePeptidePrediction(prediction => new PeptidePrediction(null, IonMobilityPredictor.EMPTY)));

                // Verify ability to extract predictions from raw data
                var newPred = document.Settings.PeptideSettings.Prediction.IonMobilityPredictor.ChangeMeasuredIonMobilityValuesFromResults(
                    document, docContainer.DocumentFilePath);
                var result = newPred.MeasuredMobilityIons;
                Assert.AreEqual(TestSmallMolecules ? 2 : 1, result.Count);
                const double expectedDT     = 4.0019;
                var          expectedOffset = .4829;
                Assert.AreEqual(expectedDT, result.Values.First().IonMobility.Mobility.Value, .001);
                Assert.AreEqual(expectedOffset, result.Values.First().HighEnergyIonMobilityValueOffset, .001);

                // Check ability to update, and to preserve unchanged
                var revised = new Dictionary <LibKey, IonMobilityAndCCS>();
                var libKey  = result.Keys.First();
                revised.Add(libKey, IonMobilityAndCCS.GetIonMobilityAndCCS(IonMobilityValue.GetIonMobilityValue(4, eIonMobilityUnits.drift_time_msec), null, 0.234));  // N.B. CCS handling would require actual raw data in this test, it's covered in a perf test
                var libKey2 = new LibKey("DEADEELS", asSmallMolecules ? Adduct.NonProteomicProtonatedFromCharge(2) : Adduct.DOUBLY_PROTONATED);
                revised.Add(libKey2, IonMobilityAndCCS.GetIonMobilityAndCCS(IonMobilityValue.GetIonMobilityValue(5, eIonMobilityUnits.drift_time_msec), null, 0.123));
                document =
                    document.ChangeSettings(
                        document.Settings.ChangePeptidePrediction(prediction => new PeptidePrediction(null, new IonMobilityPredictor("test", revised, null, null, IonMobilityWindowWidthCalculator.IonMobilityPeakWidthType.resolving_power, 40, 0, 0))));
                newPred = document.Settings.PeptideSettings.Prediction.ChangeDriftTimePredictor(
                    document.Settings.PeptideSettings.Prediction.IonMobilityPredictor.ChangeMeasuredIonMobilityValuesFromResults(
                        document, docContainer.DocumentFilePath)).IonMobilityPredictor;
                result = newPred.MeasuredMobilityIons;
                Assert.AreEqual(TestSmallMolecules ? 3 : 2, result.Count);
                Assert.AreEqual(expectedDT, result[libKey].IonMobility.Mobility.Value, .001);
                Assert.AreEqual(expectedOffset, result[libKey].HighEnergyIonMobilityValueOffset, .001);
                Assert.AreEqual(5, result[libKey2].IonMobility.Mobility.Value, .001);
                Assert.AreEqual(0.123, result[libKey2].HighEnergyIonMobilityValueOffset, .001);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Removes peaks and annotations that were in the document but not in the file, so that all peptide results that were not explicitly imported as part of this file are now blank
        /// </summary>
        /// <param name="docNew">SrmDocument for which missing peaks should be removed</param>
        /// <param name="trackAdjustedResults">List of peaks that were in the imported file</param>
        /// <param name="changePeaks">If true, remove both peaks and annotations.  If false, only remove annotations</param>
        /// <returns></returns>
        private SrmDocument RemoveMissing(SrmDocument docNew, ICollection<ResultsKey> trackAdjustedResults, bool changePeaks)
        {
            var measuredResults = docNew.Settings.MeasuredResults;
            var chromatogramSets = measuredResults.Chromatograms;
            for (int i = 0; i < chromatogramSets.Count; ++i)
            {
                var set = chromatogramSets[i];
                var nameSet = set.Name;
                for (int k = 0; k < docNew.MoleculeCount; ++k)
                {
                    IdentityPath pepPath = docNew.GetPathTo((int)SrmDocument.Level.Molecules, k);
                    var pepNode = (PeptideDocNode)Document.FindNode(pepPath);
                    if (pepNode.IsDecoy)
                        continue;
                    if (pepNode.GlobalStandardType != null)
                        continue;
                    foreach (var groupNode in pepNode.TransitionGroups)
                    {
                        var groupPath = new IdentityPath(pepPath, groupNode.Id);
                        var chromInfos = groupNode.Results[i];
                        if (chromInfos == null)
                            continue;

                        foreach (var groupChromInfo in chromInfos)
                        {
                            if (groupChromInfo == null)
                                continue;
                            var key = new ResultsKey(groupChromInfo.FileId.GlobalIndex, groupNode.Id);
                            if (!trackAdjustedResults.Contains(key))
                            {
                                CountMissing++;
                                var fileId = groupChromInfo.FileId;
                                var fileInfo = set.GetFileInfo(fileId);
                                var filePath = fileInfo.FilePath;
                                // Remove annotations for defs that were imported into the document and were on this peptide prior to import
                                var newAnnotationValues = groupChromInfo.Annotations.ListAnnotations().ToList();
                                newAnnotationValues = newAnnotationValues.Where(a => !AnnotationsAdded.Contains(a.Key)).ToList();
                                var newAnnotations = new Annotations(groupChromInfo.Annotations.Note, newAnnotationValues, groupChromInfo.Annotations.ColorIndex);
                                var newGroupNode = groupNode.ChangePrecursorAnnotations(fileId, newAnnotations);
                                if (!ReferenceEquals(groupNode, newGroupNode))
                                    docNew = (SrmDocument) docNew.ReplaceChild(groupPath.Parent, newGroupNode);
                                // Adjust peaks to null if they weren't in the file
                                if (changePeaks)
                                {
                                    docNew = docNew.ChangePeak(groupPath, nameSet, filePath,
                                        null, null, null, UserSet.IMPORTED, null, false);
                                }
                            }
                        }
                    }
                }
            }
            return docNew;
        }
Ejemplo n.º 9
0
        public void RunTestFindNode(RefinementSettings.ConvertToSmallMoleculesMode asSmallMolecules)
        {
            if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.none)
            {
                TestDirectoryName = asSmallMolecules.ToString();
            }
            TestSmallMolecules = false;  // Don't need the magic test node, we have an explicit test

            SrmDocument doc = CreateStudy7Doc();

            doc = (new RefinementSettings()).ConvertToSmallMolecules(doc, asSmallMolecules);
            var displaySettings = new DisplaySettings(null, false, 0, 0); //, ProteinDisplayMode.ByName);
            // Find every other transition, searching down.
            List <TransitionDocNode> listTransitions = doc.MoleculeTransitions.ToList();
            var pathFound = doc.GetPathTo(0, 0);
            int i;

            for (i = 0; i < doc.MoleculeTransitionCount; i += 2)
            {
                pathFound = doc.SearchDocumentForString(pathFound, String.Format("{0:F04}", listTransitions[i].Mz), displaySettings, false, false);
                Assert.AreEqual(doc.GetPathTo((int)SrmDocument.Level.Transitions, i), pathFound);
            }

            // Test wrapping in search down.
            pathFound = doc.SearchDocumentForString(pathFound, String.Format("{0:F04}", listTransitions[0].Mz), displaySettings, false, false);
            Assert.AreEqual(doc.GetPathTo((int)SrmDocument.Level.Transitions, 0), pathFound);

            // Find every other peptide searching up while for each finding one of its children searching down.
            pathFound = doc.LastNodePath;
            List <PeptideDocNode> listPeptides = new List <PeptideDocNode>();

            listPeptides.AddRange(doc.Molecules);
            List <TransitionGroupDocNode> listTransitionGroups = new List <TransitionGroupDocNode>();

            listTransitionGroups.AddRange(doc.MoleculeTransitionGroups);
            for (int x = doc.MoleculeCount; x > 0; x -= 2)
            {
                // Test case insensitivity.
                pathFound = doc.SearchDocumentForString(pathFound, listPeptides[x - 1].ToString().ToLower(), displaySettings, true, false);
                Assert.AreEqual(doc.GetPathTo((int)SrmDocument.Level.Molecules, x - 1), pathFound);
                // Test parents can find children.
                pathFound = doc.SearchDocumentForString(pathFound, String.Format("{0:F04}", listTransitionGroups[x * 2 - 1].PrecursorMz.Value), displaySettings,
                                                        false, true);
                Assert.AreEqual(doc.GetPathTo((int)SrmDocument.Level.TransitionGroups, x * 2 - 1), pathFound);
                // Test Children can find parents.
                pathFound = doc.SearchDocumentForString(pathFound, listPeptides[x - 1].ToString().ToLower(), displaySettings, true, false);
                Assert.AreEqual(doc.GetPathTo((int)SrmDocument.Level.Molecules, x - 1), pathFound);
            }

            // Test wrapping in search up.
            pathFound = doc.SearchDocumentForString(pathFound, String.Format("{0:F04}", listTransitionGroups[listTransitionGroups.Count - 1].PrecursorMz.Value),
                                                    displaySettings, false, true);
            Assert.AreEqual(doc.GetPathTo((int)SrmDocument.Level.TransitionGroups, listTransitionGroups.Count - 1), pathFound);

            // Test children can find other parents.
            pathFound = doc.SearchDocumentForString(pathFound, listPeptides[0].ToString().ToLowerInvariant(), displaySettings, true, false);
            Assert.AreEqual(doc.GetPathTo((int)SrmDocument.Level.Molecules, 0), pathFound);

            // Test forward and backward searching in succession
            const string heavyText         = "heavy";
            int          countHeavyForward = CountOccurrances(doc, heavyText, displaySettings, false, true);

            Assert.IsTrue(countHeavyForward > 0);
            Assert.AreEqual(countHeavyForward, CountOccurrances(doc, heavyText, displaySettings, true, true));
            // More tests of case insensitive searching
            Assert.AreEqual(0, CountOccurrances(doc, heavyText.ToUpperInvariant(), displaySettings, false, true));
            Assert.AreEqual(countHeavyForward, CountOccurrances(doc, heavyText.ToUpperInvariant(), displaySettings, false, false));
            if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.masses_only)
            {
                Assert.AreEqual(1, CountOccurrances(doc, "hgflpr", displaySettings, true, false));
            }

            // Test mismatched transitions finder
            var missmatchFinder = new FindOptions().ChangeCustomFinders(new[] { new MismatchedIsotopeTransitionsFinder() });

            Assert.AreEqual(4, CountOccurrances(doc, missmatchFinder, displaySettings));
            var docRemoved = (SrmDocument)doc.RemoveChild(doc.Children[1]).RemoveChild(doc.Children[2]);

            Assert.AreEqual(0, CountOccurrances(docRemoved, missmatchFinder, displaySettings));
            var refineRemoveHeavy = new RefinementSettings {
                RefineLabelType = IsotopeLabelType.heavy
            };
            var docLight = refineRemoveHeavy.Refine(doc);

            Assert.AreEqual(0, CountOccurrances(docLight, missmatchFinder, displaySettings));
            var refineRemoveLight = new RefinementSettings {
                RefineLabelType = IsotopeLabelType.light
            };
            var docHeavy = refineRemoveLight.Refine(doc);

            Assert.AreEqual(0, CountOccurrances(docHeavy, missmatchFinder, displaySettings));
            var docMulti = ResultsUtil.DeserializeDocument("MultiLabel.sky", typeof(MultiLabelRatioTest));

            docMulti = (new RefinementSettings()).ConvertToSmallMolecules(docMulti, asSmallMolecules);
            Assert.AreEqual(0, CountOccurrances(docMulti, missmatchFinder, displaySettings));
            var pathTranMultiRemove = docMulti.GetPathTo((int)SrmDocument.Level.Transitions, 7);
            var tranMultiRemove     = docMulti.FindNode(pathTranMultiRemove);
            var docMultiRemoved     = (SrmDocument)docMulti.RemoveChild(pathTranMultiRemove.Parent, tranMultiRemove);

            Assert.AreEqual(2, CountOccurrances(docMultiRemoved, missmatchFinder, displaySettings));
            var tranGroupMultiRemove = docMulti.FindNode(pathTranMultiRemove.Parent);
            var docMultiGroupRemoved = (SrmDocument)
                                       docMulti.RemoveChild(pathTranMultiRemove.Parent.Parent, tranGroupMultiRemove);

            Assert.AreEqual(0, CountOccurrances(docMultiGroupRemoved, missmatchFinder, displaySettings));
        }
Ejemplo n.º 10
0
        public void MoveNodeTest()
        {
            SrmDocument  document = new SrmDocument(SrmSettingsList.GetDefault());
            IdentityPath path     = IdentityPath.ROOT;
            SrmDocument  docFasta = document.ImportFasta(new StringReader(ExampleText.TEXT_FASTA_YEAST), false, path, out path);
            // 1. From peptide group to root
            SrmDocument docMoved = docFasta.MoveNode(docFasta.GetPathTo(0), IdentityPath.ROOT, out path);

            Assert.AreEqual(1, docMoved.FindNodeIndex(path));
            Assert.AreSame(docFasta.Children[0], docMoved.Children[1]);
            Assert.AreSame(docFasta.Children[1], docMoved.Children[0]);
            // 2. From peptide group to before other peptide group
            docMoved = docFasta.MoveNode(docFasta.GetPathTo(1), docFasta.GetPathTo(0), out path);
            Assert.AreEqual(0, docMoved.FindNodeIndex(path));
            Assert.AreSame(docFasta.Children[0], docMoved.Children[1]);
            Assert.AreSame(docFasta.Children[1], docMoved.Children[0]);

            // Some peptide lists
            IdentityPath pathPeptides;
            SrmDocument  docPeptides = docFasta.ImportFasta(new StringReader(TEXT_BOVINE_PEPTIDES2), true,
                                                            docFasta.GetPathTo(1), out pathPeptides);

            docPeptides = docPeptides.ImportFasta(new StringReader(TEXT_BOVINE_PEPTIDES1), true,
                                                  IdentityPath.ROOT, out path);
            docPeptides = docPeptides.MoveNode(path, pathPeptides, out pathPeptides);
            Assert.AreEqual(1, docPeptides.FindNodeIndex(pathPeptides));

            // 3. Peptide from one group to another
            IdentityPath fromParent   = docPeptides.GetPathTo(2);
            IdentityPath from         = new IdentityPath(fromParent, ((DocNodeParent)docPeptides.FindNode(fromParent)).Children[0].Id);
            SrmDocument  docPeptides2 = docPeptides.MoveNode(from, pathPeptides, out path);

            Assert.AreEqual(pathPeptides, path.Parent);
            Assert.AreEqual(((DocNodeParent)docPeptides.Children[1]).Children.Count,
                            ((DocNodeParent)docPeptides2.Children[1]).Children.Count - 1);
            Assert.AreEqual(((DocNodeParent)docPeptides.Children[2]).Children.Count,
                            ((DocNodeParent)docPeptides2.Children[2]).Children.Count + 1);
            // Though moved to a different group, this should not have changed the overall
            // peptide order, since it was moved from the beginning of one group to the end
            // of the group before it.
            Assert.AreEqual(docPeptides.FindNodeIndex(from), docPeptides2.FindNodeIndex(path));

            // 4. To before another peptide
            from = new IdentityPath(fromParent, ((DocNodeParent)docPeptides2.FindNode(fromParent)).Children[0].Id);
            IdentityPath path2;
            SrmDocument  docPeptides3 = docPeptides2.MoveNode(from, path, out path2);

            Assert.AreEqual(pathPeptides, path.Parent);
            Assert.AreEqual(((DocNodeParent)docPeptides2.Children[1]).Children.Count,
                            ((DocNodeParent)docPeptides3.Children[1]).Children.Count - 1);
            Assert.AreEqual(((DocNodeParent)docPeptides2.Children[2]).Children.Count,
                            ((DocNodeParent)docPeptides3.Children[2]).Children.Count + 1);
            // Relative to all peptides, index should be 1 less than before
            Assert.AreEqual(docPeptides2.FindNodeIndex(from), docPeptides3.FindNodeIndex(path2) + 1);

            // 5. To within another peptide
            IdentityPath to           = new IdentityPath(path, ((DocNodeParent)docPeptides3.FindNode(path)).Children[0].Id);
            SrmDocument  docPeptides4 = docPeptides3.MoveNode(path2, to, out path);

            // Should not have changed to count in the group
            Assert.AreEqual(((DocNodeParent)docPeptides3.Children[1]).Children.Count,
                            ((DocNodeParent)docPeptides4.Children[1]).Children.Count);
            // Relative to all peptides, should have been returned to original order
            Assert.AreEqual(docPeptides2.FindNodeIndex(from), docPeptides4.FindNodeIndex(path));

            // Make sure expected exceptions are thrown
            Assert.IsNull(docPeptides4.FindNode(from));
            AssertEx.ThrowsException <IdentityNotFoundException>(() =>
                                                                 docPeptides4.MoveNode(from, to, out path));
            AssertEx.ThrowsException <InvalidOperationException>(() =>
                                                                 docPeptides2.MoveNode(from, docPeptides2.GetPathTo(0), out path));
            AssertEx.ThrowsException <InvalidOperationException>(() =>
                                                                 docPeptides3.MoveNode(docPeptides2.GetPathTo((int)SrmDocument.Level.Molecules, 0), to, out path));
            AssertEx.ThrowsException <InvalidOperationException>(() =>
                                                                 docPeptides3.MoveNode(docPeptides2.GetPathTo((int)SrmDocument.Level.Transitions, 0), to, out path));
        }
Ejemplo n.º 11
0
        private void PerformTestMeasuredDriftValues(bool asSmallMolecules)
        {
            if (asSmallMolecules)
            {
                if (!RunSmallMoleculeTestVersions)
                {
                    Console.Write(MSG_SKIPPING_SMALLMOLECULE_TEST_VERSION);
                    return;
                }
            }
            var testFilesDir = new TestFilesDir(TestContext, @"TestData\Results\BlibDriftTimeTest.zip"); // Re-used from BlibDriftTimeTest
            // Open document with some peptides but no results
            var docPath = testFilesDir.GetTestPath("BlibDriftTimeTest.sky");
            // This was a malformed document, which caused problems after a fix to not recalculate
            // document library settings on open. To avoid rewriting this test for the document
            // which now contains 2 precursors, the first precursor is removed immediately.
            SrmDocument docOriginal      = ResultsUtil.DeserializeDocument(docPath);
            var         pathFirstPeptide = docOriginal.GetPathTo((int)SrmDocument.Level.Molecules, 0);
            var         nodeFirstPeptide = (DocNodeParent)docOriginal.FindNode(pathFirstPeptide);

            docOriginal = (SrmDocument)docOriginal.RemoveChild(pathFirstPeptide, nodeFirstPeptide.Children[0]);
            if (asSmallMolecules)
            {
                var refine = new RefinementSettings();
                docOriginal = refine.ConvertToSmallMolecules(docOriginal, testFilesDir.FullPath);
            }
            using (var docContainer = new ResultsTestDocumentContainer(docOriginal, docPath))
            {
                var doc = docContainer.Document;

                // Import an mz5 file that contains drift info
                const string replicateName = "ID12692_01_UCA168_3727_040714";
                var          chromSets     = new[]
                {
                    new ChromatogramSet(replicateName, new[]
                                        { new MsDataFilePath(testFilesDir.GetTestPath("ID12692_01_UCA168_3727_040714" + ExtensionTestContext.ExtMz5)), }),
                };
                var docResults = doc.ChangeMeasuredResults(new MeasuredResults(chromSets));
                Assert.IsTrue(docContainer.SetDocument(docResults, docOriginal, true));
                docContainer.AssertComplete();
                var document = docContainer.Document;

                // Clear out any current settings
                document = document.ChangeSettings(document.Settings.ChangeTransitionIonMobilityFiltering(s => TransitionIonMobilityFiltering.EMPTY));

                // Verify ability to extract predictions from raw data
                var libraryName0   = "test0";
                var dbPath0        = testFilesDir.GetTestPath(libraryName0 + IonMobilityDb.EXT);
                var newIMFiltering = document.Settings.TransitionSettings.IonMobilityFiltering.ChangeLibrary(
                    IonMobilityLibrary.CreateFromResults(
                        document, docContainer.DocumentFilePath, true,
                        libraryName0, dbPath0));
                var result = newIMFiltering.IonMobilityLibrary.GetIonMobilityLibKeyMap().AsDictionary();
                Assert.AreEqual(1, result.Count);
                var expectedDT     = 4.0019;
                var expectedOffset = .4829;
                Assert.AreEqual(expectedDT, result.Values.First().First().IonMobility.Mobility.Value, .001);
                Assert.AreEqual(expectedOffset, result.Values.First().First().HighEnergyIonMobilityValueOffset ?? 0, .001);

                // Check ability to update, and to preserve unchanged
                var revised = new List <PrecursorIonMobilities>();
                var libKey  = result.Keys.First();
                revised.Add(new PrecursorIonMobilities(libKey, IonMobilityAndCCS.GetIonMobilityAndCCS(IonMobilityValue.GetIonMobilityValue(expectedDT = 4, eIonMobilityUnits.drift_time_msec), null, expectedOffset = 0.234)));  // N.B. CCS handling would require actual raw data in this test, it's covered in a perf test
                var pepSequence = "DEADEELS";
                var libKey2     = asSmallMolecules ?
                                  new LibKey(SmallMoleculeLibraryAttributes.Create(pepSequence, "C12H5", null, null, null, null), Adduct.M_PLUS_2H) :
                                  new LibKey(pepSequence, Adduct.DOUBLY_PROTONATED);
                revised.Add(new PrecursorIonMobilities(libKey2, IonMobilityAndCCS.GetIonMobilityAndCCS(IonMobilityValue.GetIonMobilityValue(5, eIonMobilityUnits.drift_time_msec), null, 0.123)));
                var libraryName = "test";
                var dbPath      = testFilesDir.GetTestPath(libraryName + IonMobilityDb.EXT);
                var imsdb       = IonMobilityDb.CreateIonMobilityDb(dbPath, libraryName, false, revised);
                var newLibIM    = new IonMobilityLibrary(libraryName, dbPath, imsdb);
                var ionMobilityWindowWidthCalculator = new IonMobilityWindowWidthCalculator(
                    IonMobilityWindowWidthCalculator.IonMobilityWindowWidthType.resolving_power, 40, 0, 0, 0);
                var calculator = ionMobilityWindowWidthCalculator;
                document = document.ChangeSettings(
                    document.Settings.ChangeTransitionIonMobilityFiltering(
                        imf => imf.ChangeFilterWindowWidthCalculator(calculator).
                        ChangeLibrary(newLibIM)));
                result = document.Settings.TransitionSettings.IonMobilityFiltering.IonMobilityLibrary.GetIonMobilityLibKeyMap().AsDictionary();
                Assert.AreEqual(2, result.Count);
                Assert.AreEqual(expectedDT, result[libKey].First().IonMobility.Mobility.Value, .001);
                Assert.AreEqual(expectedOffset, result[libKey].First().HighEnergyIonMobilityValueOffset ?? 0, .001);
                Assert.AreEqual(5, result[libKey2].First().IonMobility.Mobility.Value, .001);
                Assert.AreEqual(0.123, result[libKey2].First().HighEnergyIonMobilityValueOffset ?? 0, .001);

                ionMobilityWindowWidthCalculator = new IonMobilityWindowWidthCalculator(
                    IonMobilityWindowWidthCalculator.IonMobilityWindowWidthType.fixed_width, 40, 0, 0, 100);
                document = document.ChangeSettings(
                    document.Settings.ChangeTransitionIonMobilityFiltering(
                        imf => imf.ChangeFilterWindowWidthCalculator(ionMobilityWindowWidthCalculator).
                        ChangeLibrary(newLibIM)));
                result = document.Settings.TransitionSettings.IonMobilityFiltering.IonMobilityLibrary.GetIonMobilityLibKeyMap().AsDictionary();
                Assert.AreEqual(2, result.Count);
                Assert.AreEqual(expectedDT, result[libKey].First().IonMobility.Mobility.Value, .001);
                Assert.AreEqual(expectedOffset, result[libKey].First().HighEnergyIonMobilityValueOffset ?? 0, .001);
                Assert.AreEqual(5, result[libKey2].First().IonMobility.Mobility.Value, .001);
                Assert.AreEqual(0.123, result[libKey2].First().HighEnergyIonMobilityValueOffset ?? 0, .001);
            }
        }
Ejemplo n.º 12
0
        public void TestPaste()
        {
            ClearDefaultModifications();
            _yeastDoc = new SrmDocument(SrmSettingsList.GetDefault().ChangeTransitionInstrument(instrument => instrument.ChangeMaxMz(1600)));
            _yeastDoc = _yeastDoc.ChangeSettings(_yeastDoc.Settings.ChangeTransitionFilter(filter =>
                                                                                           filter.ChangeMeasuredIons(new MeasuredIon[0])));
            IdentityPath path;
            _yeastDocReadOnly = _yeastDoc = _yeastDoc.ImportFasta(new StringReader(ExampleText.TEXT_FASTA_YEAST_LIB),
                false, IdentityPath.ROOT, out path);

            _study7DocReadOnly = _study7Doc = CreateStudy7Doc();

            IdentityPath pathRoot = IdentityPath.ROOT;

            // Test pasting into document with same implicit modifications does not create any extra explicit modifications.
            var study7EmptyDoc = (SrmDocument) _study7Doc.ChangeChildren(new DocNode[0]);
            var study7PasteDoc = CopyPaste(_study7Doc, null, study7EmptyDoc, pathRoot);
            var arrayPeptides = _study7Doc.Peptides.ToArray();
            var arrayPastePeptides = study7PasteDoc.Peptides.ToArray();
            Assert.AreEqual(arrayPeptides.Length, arrayPastePeptides.Length);
            AssertEx.DocsEqual(_study7Doc, study7PasteDoc); // DocsEqual gives a more verbose failure message using XML output

            // Test implicit mods in source document become explicit mods in target document.
            ResetDocuments();
            _yeastDoc = (SrmDocument) _yeastDoc.ChangeChildren(new DocNode[0]);
            var settings = _yeastDoc.Settings;
            _yeastDoc = _yeastDoc.ChangeSettings(settings.ChangePeptideModifications(mods =>
                mods.ChangeStaticModifications(new StaticMod[0])));
            _yeastDoc = CopyPaste(_study7Doc, null, _yeastDoc, pathRoot);
            var pepMods = _yeastDoc.Settings.PeptideSettings.Modifications;
            Assert.IsTrue(pepMods.StaticModifications != null);
            Assert.IsTrue(pepMods.HasHeavyModifications);
            Assert.IsFalse(pepMods.StaticModifications.Contains(mod => !mod.IsExplicit));
            Assert.IsFalse(pepMods.HeavyModifications.Contains(mod => !mod.IsExplicit));

            // Test explicit mods are dropped if the target document has matching implicit modifications.
            study7PasteDoc = CopyPaste(_yeastDoc, null, study7EmptyDoc, pathRoot);
            Assert.AreEqual(_study7Doc, study7PasteDoc);

            // Add new label type to source document.
            ResetDocuments();
            const string labelTypeName13C = "heavy 13C";
            var labelType13C = new IsotopeLabelType(labelTypeName13C, IsotopeLabelType.light.SortOrder + 1);
            _yeastDoc = ChangePeptideModifications(_yeastDoc,
                 new[] {new TypedModifications(labelType13C, HEAVY_MODS_13_C)});
            Assert.IsTrue(_yeastDoc.PeptideTransitionGroups.Contains(nodeGroup =>
                Equals(nodeGroup.TransitionGroup.LabelType, labelType13C)));
               // Test pasting into the same document with new label type.
            _yeastDoc = CopyPaste(_yeastDoc, null, _yeastDoc, pathRoot);
            // Check all transition have correct label type references.
            Assert.IsFalse(_yeastDoc.PeptideTransitionGroups.Contains(nodeGroup =>
                {
                    IsotopeLabelType labelType = nodeGroup.TransitionGroup.LabelType;
                    return !ReferenceEquals(labelType,
                        _yeastDoc.Settings.PeptideSettings.Modifications.GetModificationsByName(labelType.Name).LabelType);
                }));

            // Check new document still serializes correctly.
            AssertEx.Serializable(_yeastDoc, AssertEx.DocumentCloned);

            // Test pasting into new document drops label types from source document that are not found in the target document.
            _yeastDoc = CopyPaste(_yeastDoc, null, new SrmDocument(SrmSettingsList.GetDefault()), pathRoot);
            Assert.IsNull(_yeastDoc.Settings.PeptideSettings.Modifications.GetModificationsByName(labelTypeName13C));

            // If only specific children are selected, test that only these children get copied.
            ResetDocuments();
            var arrayTrans = _study7Doc.PeptideTransitions.ToArray();
            IList<DocNode> selNodes = new List<DocNode>();
            for (int i = 0; i < arrayTrans.Length; i += 2)
            {
                selNodes.Add(arrayTrans[i]);
            }
            _study7Doc = CopyPaste(_study7Doc, selNodes, _study7Doc, pathRoot);
            Assert.AreEqual(arrayTrans.Length + selNodes.Count, _study7Doc.PeptideTransitionCount);

            // Test after pasting to a peptide list, all children have been updated to point to the correct parent.
            ResetDocuments();
            _study7Doc = CopyPaste(_yeastDoc, new[] { _yeastDoc.Peptides.ToArray()[0] }, _study7Doc,
                                  _study7Doc.GetPathTo((int) SrmDocument.Level.MoleculeGroups, 0));
            Assert.AreEqual(_yeastDoc.Peptides.ToArray()[0].Peptide, _study7Doc.Peptides.ToArray()[0].Peptide);
            Assert.AreEqual(_study7Doc.Peptides.ToArray()[0].Peptide,
                          _study7Doc.PeptideTransitionGroups.ToArray()[0].TransitionGroup.Peptide);
            Assert.AreEqual(_study7Doc.PeptideTransitionGroups.ToArray()[0].TransitionGroup,
                          _study7Doc.PeptideTransitions.ToArray()[0].Transition.Group);

            // If only specific transition are selected for a peptide, but all transition groups are included, test AutoManageChildren is true.
            ResetDocuments();
            selNodes = new List<DocNode>();
            foreach (TransitionGroupDocNode transGroup in _study7Doc.PeptideTransitionGroups)
            {
                selNodes.Add(transGroup.Children[0]);
            }
            // TODO: Fix this and make it pass
            //            var emptyDoc = (SrmDocument)_study7Doc.ChangeChildren(new List<DocNode>());
            //            _study7Doc = CopyPaste(_study7Doc, selNodes, emptyDoc, pathRoot);
            _study7Doc = (SrmDocument)_study7Doc.ChangeChildren(new List<DocNode>());
            _study7Doc = CopyPaste(_study7Doc, selNodes, _study7Doc, pathRoot);
            foreach (PeptideDocNode peptide in _study7Doc.Peptides)
                Assert.IsTrue(peptide.AutoManageChildren);

            // Test pasting in modifications with the same name as but different definition from existing modifications not allowed.
            ResetDocuments();
            _yeastDoc = ChangePeptideModifications(_yeastDoc,
                new[] { new TypedModifications(IsotopeLabelType.heavy, HEAVY_C_K_DIFDEF) });
            SetDefaultModifications(_study7Doc);
            AssertEx.ThrowsException<Exception>(() => _yeastDoc.Settings.UpdateDefaultModifications(false));

            // Test variable modifications kept if target document has matching variable modifications turned on.
            ResetDocuments();
            settings = _yeastDoc.Settings;
            var modsDefault = settings.PeptideSettings.Modifications;
            var listVariableMods = new List<StaticMod>(modsDefault.StaticModifications) { VAR_MET_OXIDIZED };
            _yeastDoc = _yeastDoc.ChangeSettings(settings.ChangePeptideModifications(mods =>
                mods.ChangeStaticModifications(listVariableMods.ToArray())));
            // Make sure there is an implicitly modified peptide in the yeast document
            Assert.IsTrue(_yeastDoc.Peptides.Contains(nodePep => nodePep.Peptide.Sequence.Contains("C")));
            Assert.IsTrue(_yeastDoc.Peptides.Contains(nodePep => nodePep.HasVariableMods));
            _yeastDoc = CopyPaste(_yeastDoc, null, _yeastDoc, pathRoot);
            Assert.IsFalse(_yeastDoc.Peptides.Contains(nodePep => nodePep.HasExplicitMods && !nodePep.HasVariableMods));

            // Otherwise the variable modifications become only explicit modifications.
            var yeastDocVar = _yeastDoc;
            _yeastDoc = _yeastDoc.ChangeSettings(_yeastDoc.Settings.ChangePeptideModifications(mods => modsDefault));
            _yeastDoc = CopyPaste(yeastDocVar, null, _yeastDoc, pathRoot);
            Assert.IsFalse(_yeastDoc.Settings.PeptideSettings.Modifications.HasVariableModifications);
            Assert.IsTrue(_yeastDoc.Peptides.Contains(nodePep => nodePep.HasExplicitMods));
            Assert.IsFalse(_yeastDoc.Peptides.Contains(nodePep => nodePep.HasVariableMods));
        }
Ejemplo n.º 13
0
        public void LibraryMultipleTest()
        {
            var streamManager = new MemoryStreamManager();
            var loader        = new LibraryLoadTest.TestLibraryLoader {
                StreamManager = streamManager
            };

            // Create library files
            const string hunterText = LibraryLoadTest.TEXT_LIB_YEAST_NIST1 + "\n" + LibraryLoadTest.TEXT_LIB_YEAST_NIST2;

            LibraryLoadTest.CreateHunterFile(streamManager, loader, hunterText);
            const string biblioText = LibraryLoadTest.TEXT_LIB_YEAST_NIST2 + "\n" + LibraryLoadTest.TEXT_LIB_YEAST_NIST3;

            LibraryLoadTest.CreateBiblioFile(streamManager, loader, biblioText);
            const string nistText = LibraryLoadTest.TEXT_LIB_YEAST_NIST3 + "\n" + LibraryLoadTest.TEXT_LIB_YEAST_NIST4;

            streamManager.TextFiles.Add(LibraryLoadTest.PATH_NIST_LIB, nistText);

            var hunterSpec = new XHunterLibSpec("Yeast (X!)", LibraryLoadTest.PATH_HUNTER_LIB);
            var bilbioSpec = new BiblioSpecLibSpec("Yeast (BS)", LibraryLoadTest.PATH_BIBLIOSPEC_LIB);
            var nistSpec   = new NistLibSpec("Yeast (NIST)", LibraryLoadTest.PATH_NIST_LIB);

            // For serialization, add the library spec to the settings
            TestLibraryList = new SpectralLibraryList {
                hunterSpec, bilbioSpec, nistSpec
            };

            var libraryManager = new LibraryManager {
                StreamManager = streamManager
            };
            var docContainer = new TestDocumentContainer();

            SrmSettings settings = SrmSettingsList.GetDefault();

            settings = settings.ChangePeptideLibraries(l => l.ChangeLibrarySpecs(new LibrarySpec[] { hunterSpec, bilbioSpec, nistSpec }));

            int         startRev;
            SrmDocument docLoaded = CreateLibraryDocument(settings, ExampleText.TEXT_FASTA_YEAST_LIB, false,
                                                          docContainer, libraryManager, out startRev);

            AssertEx.IsDocumentState(docLoaded, startRev, 2, 4, 12);
            Assert.IsTrue(HasLibraryInfo(docLoaded, typeof(XHunterSpectrumHeaderInfo)));
            Assert.IsTrue(HasLibraryInfo(docLoaded, typeof(BiblioSpecSpectrumHeaderInfo)));
            Assert.IsTrue(HasLibraryInfo(docLoaded, typeof(NistSpectrumHeaderInfo)));

            // Remove the rank 1 transition from each transition group
            TransitionDocNode[] transitionNodes = docLoaded.PeptideTransitions.ToArray();
            for (int i = 0; i < transitionNodes.Length; i++)
            {
                var nodeTran = transitionNodes[i];
                if (nodeTran.LibInfo.Rank != 1)
                {
                    continue;
                }
                var path = docLoaded.GetPathTo((int)SrmDocument.Level.TransitionGroups, i / 3);
                docLoaded = (SrmDocument)docLoaded.RemoveChild(path, nodeTran);
                ++startRev;
            }
            AssertEx.IsDocumentState(docLoaded, startRev, 2, 4, 8);
            // Make sure this can be serialized and deserialized without causing
            // a recalculation of the nodes in the tree.
            AssertEx.Serializable(docLoaded, (doc1, doc2) => ValidateLibraryDocs(doc1, doc2, libraryManager));
        }
Ejemplo n.º 14
0
        public void MultiLabelExplicitSerialTest()
        {
            // Create a simple document and add two peptides
            SrmDocument document = new SrmDocument(SrmSettingsList.GetDefault());
            const string pepSequence1 = "QFVLSCVILR";
            const string pepSequence2 = "DIEVYCDGAITTK";
            var reader = new StringReader(string.Join("\n", new[] {">peptides1", pepSequence1, pepSequence2}));
            IdentityPath path;
            document = document.ImportFasta(reader, true, IdentityPath.ROOT, out path);
            Assert.AreEqual(2, document.PeptideCount);

            // Add some modifications in two new label types
            var modCarb = new StaticMod("Carbamidomethyl Cysteine", "C", null, "C2H3ON");
            var modOther = new StaticMod("Another Cysteine", "C", null, "CO8N2");
            var staticMods = new[] {modCarb, modOther};
            var mod15N = new StaticMod("All 15N", null, null, null, LabelAtoms.N15, null, null);
            var modK13C = new StaticMod("13C K", "K", ModTerminus.C, null, LabelAtoms.C13, null, null);
            var modR13C = new StaticMod("13C R", "R", ModTerminus.C, null, LabelAtoms.C13, null, null);
            var modV13C = new StaticMod("Heavy V", "V", null, null, LabelAtoms.C13 | LabelAtoms.N15, null, null);
            var heavyMods = new[] { mod15N, modK13C, modR13C, modV13C };
            var labelTypeAA = new IsotopeLabelType("heavy AA", IsotopeLabelType.FirstHeavy);
            var labelTypeAll = new IsotopeLabelType("heavy All", IsotopeLabelType.FirstHeavy + 1);

            var settings = document.Settings;
            settings = settings.ChangePeptideModifications(mods =>
                new PeptideModifications(mods.StaticModifications,
                    new[]
                        {
                            new TypedModifications(labelTypeAA, new[] {modK13C, modR13C}),
                            new TypedModifications(labelTypeAll, new[] {mod15N})
                        }));
            document = document.ChangeSettings(settings);
            Assert.AreEqual(6, document.PeptideTransitionGroupCount);

            // Add modifications to light and heavy AA in the first peptide
            path = document.GetPathTo((int) SrmDocument.Level.Molecules, 0);
            var nodePepMod = (PeptideDocNode) document.FindNode(path);
            var explicitMod = new ExplicitMods(nodePepMod.Peptide,
                new[] {new ExplicitMod(pepSequence1.IndexOf('C'), modOther)},
                new[] {new TypedExplicitModifications(nodePepMod.Peptide, labelTypeAA, new ExplicitMod[0])});
            document = document.ChangePeptideMods(path, explicitMod, staticMods, heavyMods);
            Assert.AreEqual(5, document.PeptideTransitionGroupCount);

            // Add a modification to heavy All in the second peptide
            path = document.GetPathTo((int)SrmDocument.Level.Molecules, 1);
            nodePepMod = (PeptideDocNode)document.FindNode(path);
            explicitMod = new ExplicitMods(nodePepMod.Peptide, null,
                new[] { new TypedExplicitModifications(nodePepMod.Peptide, labelTypeAll,
                            new[] {new ExplicitMod(pepSequence2.IndexOf('V'), modV13C)}) });
            document = document.ChangePeptideMods(path, explicitMod, staticMods, heavyMods);
            Assert.AreEqual(5, document.PeptideTransitionGroupCount);

            AssertEx.Serializable(document, 3, AssertEx.DocumentCloned);
        }
Ejemplo n.º 15
0
        public void AddRemoveExplicitModTest()
        {
            SrmDocument docStudy7      = CreateStudy7Doc();
            string      transitionList = ExportCsv(docStudy7);

            Assert.AreEqual(69, transitionList.Split('\n').Length); // Special test mode may add an extra doc node

            var modifications  = docStudy7.Settings.PeptideSettings.Modifications;
            var listStaticMods = modifications.StaticModifications;
            var listHeavyMods  = modifications.AllHeavyModifications.ToList();

            docStudy7 = docStudy7.ChangeSettings(docStudy7.Settings.ChangeTransitionFilter(filter => filter.ChangeAutoSelect(false)));

            // Remove all modifications
            int i = 0;
            // But save them for later
            var removedMods = new Dictionary <int, ExplicitMods>();

            foreach (var peptide in docStudy7.Peptides)
            {
                if (peptide.HasExplicitMods)
                {
                    removedMods.Add(i, peptide.ExplicitMods);

                    IdentityPath path = docStudy7.GetPathTo((int)SrmDocument.Level.Molecules, i);
                    docStudy7 = docStudy7.ChangePeptideMods(path, null, listStaticMods, listHeavyMods);
                }
                i++;
            }

            // Removes heavy from peptide with c-terminal P
            AssertEx.IsDocumentState(docStudy7, 6, 7, 11, 21, 63);
            modifications = docStudy7.Settings.PeptideSettings.Modifications;
            Assert.AreEqual(2, modifications.AllHeavyModifications.Count());
            Assert.AreEqual(0, modifications.AllHeavyModifications.Count(mod => mod.IsExplicit));
            Assert.AreEqual(0, docStudy7.Peptides.Count(peptide => peptide.HasExplicitMods));

            listHeavyMods = ATOMIC_HEAVY_MODS;

            foreach (var pair in removedMods)
            {
                IdentityPath path = docStudy7.GetPathTo((int)SrmDocument.Level.Molecules, pair.Key);
                docStudy7 = docStudy7.ChangePeptideMods(path, pair.Value, listStaticMods, listHeavyMods);
            }

            AssertEx.IsDocumentState(docStudy7, 11, 7, 11, 21, 63);

            // Replace the heavy precursor that was removed
            // TODO: Yuck.  Would be nice to have a way to do this without duplicating
            //       so much of the logic in PeptideDocNode and PeptideTreeNode
            var pepPath        = docStudy7.GetPathTo((int)SrmDocument.Level.Molecules, 10);
            var nodePep        = (PeptideDocNode)docStudy7.FindNode(pepPath);
            var mods           = nodePep.ExplicitMods;
            var nodeGroupLight = (TransitionGroupDocNode)nodePep.Children[0];
            var settings       = docStudy7.Settings;

            foreach (var tranGroup in nodePep.GetTransitionGroups(settings, mods, false))
            {
                if (tranGroup.PrecursorAdduct.Equals(nodeGroupLight.TransitionGroup.PrecursorAdduct) &&
                    !tranGroup.LabelType.IsLight)
                {
                    TransitionDocNode[] transitions = nodePep.GetMatchingTransitions(tranGroup, settings, mods);
                    var nodeGroup = new TransitionGroupDocNode(tranGroup, transitions);
                    nodeGroup = nodeGroup.ChangeSettings(settings, nodePep, mods, SrmSettingsDiff.ALL);
                    docStudy7 = (SrmDocument)docStudy7.Add(pepPath, nodeGroup);
                    break;
                }
            }

            AssertEx.IsDocumentState(docStudy7, 12, 7, 11, 22, 66);

            modifications = docStudy7.Settings.PeptideSettings.Modifications;
            Assert.AreEqual(2, modifications.AllHeavyModifications.Count(mod => mod.IsExplicit && mod.Label13C));
            Assert.AreEqual(2, modifications.AllHeavyModifications.Count(mod => mod.Formula != null));
            Assert.AreEqual(3, docStudy7.Peptides.Count(peptide => peptide.HasExplicitMods));
            Assert.AreEqual(2, docStudy7.Peptides.Count(peptide => peptide.HasExplicitMods &&
                                                        peptide.ExplicitMods.StaticModifications.Count > 0 &&
                                                        peptide.ExplicitMods.StaticModifications[0].Modification.AAs[0] == 'C'));
            Assert.AreEqual(2, docStudy7.Peptides.Count(peptide => peptide.HasExplicitMods &&
                                                        peptide.ExplicitMods.HeavyModifications[0].Modification.AAs[0] == 'V' &&
                                                        peptide.ExplicitMods.HeavyModifications[0].Modification.Label13C));
            Assert.AreEqual(1, docStudy7.Peptides.Count(peptide => peptide.HasExplicitMods &&
                                                        peptide.ExplicitMods.HeavyModifications[0].Modification.AAs[0] == 'L' &&
                                                        peptide.ExplicitMods.HeavyModifications[0].Modification.Label13C));

            AssertEx.NoDiff(transitionList, ExportCsv(docStudy7));
        }
Ejemplo n.º 16
0
        public void ImportFastaTest()
        {
            SrmDocument  document = new SrmDocument(SrmSettingsList.GetDefault0_6());
            IdentityPath path     = IdentityPath.ROOT;
            SrmDocument  docFasta = document.ImportFasta(new StringReader(ExampleText.TEXT_FASTA_YEAST), false, path, out path);

            AssertEx.IsDocumentState(docFasta, 1, 2, 98, 311);
            Assert.AreEqual("YAL001C", ((PeptideGroupDocNode)docFasta.Children[0]).Name);
            Assert.AreEqual("YAL002W", ((PeptideGroupDocNode)docFasta.Children[1]).Name);
            Assert.AreEqual(1, path.Length);
            Assert.IsInstanceOfType(path.GetIdentity(0), typeof(FastaSequence));
            Assert.AreEqual("YAL001C", ((FastaSequence)path.GetIdentity(0)).Name);
            int maxMz = docFasta.Settings.TransitionSettings.Instrument.MaxMz - 120;

            foreach (PeptideGroupDocNode nodeGroup in docFasta.Children)
            {
                Assert.IsInstanceOfType(nodeGroup.Id, typeof(FastaSequence));

                int lastEnd = docFasta.Settings.PeptideSettings.Filter.ExcludeNTermAAs - 1;

                foreach (PeptideDocNode nodePeptide in nodeGroup.Children)
                {
                    Peptide peptide = nodePeptide.Peptide;
                    char    prev    = peptide.PrevAA;
                    if (prev != 'K' && prev != 'R')
                    {
                        Assert.Fail("Unexpected preceding cleavage at {0}", prev);
                    }
                    string seq  = peptide.Sequence;
                    char   last = seq[seq.Length - 1];
                    if (last != 'K' && last != 'R' && peptide.NextAA != '-')
                    {
                        Assert.Fail("Unexpected cleavage at {0}", last);
                    }
                    Assert.IsNotNull(peptide.Begin);
                    Assert.IsNotNull(peptide.End);

                    // Make sure peptides are ordered, and not overlapping
                    if (peptide.Begin.Value < lastEnd)
                    {
                        Assert.Fail("Begin {0} less than last end {1}.", peptide.Begin.Value, lastEnd);
                    }
                    lastEnd = peptide.End.Value;

                    IList <DocNode> nodesTrans = ((DocNodeParent)nodePeptide.Children[0]).Children;
                    int             trans      = nodesTrans.Count;
                    if (trans < 3)
                    {
                        // Might have been cut off by the instrument limit.
                        if ((trans == 0 && ((TransitionGroupDocNode)nodePeptide.Children[0]).PrecursorMz < maxMz) ||
                            (trans > 0 && ((TransitionDocNode)nodesTrans[0]).Mz < maxMz))
                        {
                            Assert.Fail("Found {0} transitions, expecting 3.", trans);
                        }
                    }
                    // Might have extra proline transitions
                    else if (trans > 3 && peptide.Sequence.IndexOf('P') == -1)
                    {
                        Assert.Fail("Found {0} transitions, expecting 3.", trans);
                    }

                    // Make sure transitions are ordered correctly
                    IonType lastType   = IonType.a;
                    int     lastOffset = -1;
                    foreach (TransitionDocNode nodeTran in nodesTrans)
                    {
                        Transition transition = nodeTran.Transition;
                        if (lastType == transition.IonType)
                        {
                            Assert.IsTrue(transition.CleavageOffset > lastOffset);
                        }
                        else
                        {
                            Assert.IsTrue(((int)transition.IonType) > ((int)lastType));
                        }
                        lastType   = transition.IonType;
                        lastOffset = transition.CleavageOffset;
                    }
                }
            }

            // Make sure old document is unmodified.
            Assert.AreEqual(0, document.RevisionIndex);
            Assert.AreEqual(0, document.PeptideTransitionCount);

            // Re-paste of fasta should have no impact.
            // path = IdentityPath.ROOT; use null as substitute for Root
            SrmDocument docFasta2 = docFasta.ImportFasta(new StringReader(ExampleText.TEXT_FASTA_YEAST), false, null, out path);

            // Returns the original document to avoid adding undo record in running app
            Assert.AreSame(docFasta, docFasta2);
            Assert.IsNull(path);

            // Discard double-insert document, and add peptides list into previous document
            path = IdentityPath.ROOT;
            SrmDocument docPeptides = docFasta.ImportFasta(new StringReader(TEXT_BOVINE_PEPTIDES1), true, path, out path);

            AssertEx.IsDocumentState(docPeptides, 2, 3, 111, 352);
            Assert.AreEqual(1, path.Length);
            Assert.IsNotInstanceOfType(path.GetIdentity(0), typeof(FastaSequence));
            Assert.AreEqual("Peptides1", ((PeptideGroupDocNode)docPeptides.FindNode(path)).Name);
            PeptideGroupDocNode nodePepList = (PeptideGroupDocNode)docPeptides.Children[2];

            Assert.IsNotInstanceOfType(nodePepList.Id, typeof(FastaSequence));
            // Make sure other two nodes are unchanged
            Assert.AreSame(docFasta.Children[0], docPeptides.Children[0]);
            Assert.AreSame(docFasta.Children[1], docPeptides.Children[1]);

            foreach (PeptideDocNode nodePeptide in nodePepList.Children)
            {
                char prev = nodePeptide.Peptide.PrevAA;
                char next = nodePeptide.Peptide.NextAA;
                if (prev != 'X' || next != 'X')
                {
                    Assert.Fail("Expected amino acids X, but found {0} or {1}", prev, next);
                }
                string seq  = nodePeptide.Peptide.Sequence;
                char   last = seq[seq.Length - 1];
                // Just because they are tryptic peptides in the list
                if (last != 'K' && last != 'R' && nodePeptide.Peptide.NextAA != '-')
                {
                    Assert.Fail("Unexpected cleavage at {0}", last);
                }
                Assert.IsNull(nodePeptide.Peptide.Begin);
                Assert.IsNull(nodePeptide.Peptide.End);

                IList <DocNode> nodesTrans = ((DocNodeParent)nodePeptide.Children[0]).Children;
                int             trans      = nodesTrans.Count;
                if (trans < 3)
                {
                    // Might have been cut off by the instrument limit.
                    if ((trans == 0 && ((TransitionGroupDocNode)nodePeptide.Children[0]).PrecursorMz < maxMz) ||
                        (trans > 0 && ((TransitionDocNode)nodesTrans[0]).Mz < maxMz))
                    {
                        Assert.Fail("Found {0} transitions, expecting 3.", trans);
                    }
                }
                // Might have extra proline transitions
                else if (trans > 3 && nodePeptide.Peptide.Sequence.IndexOf('P') == -1)
                {
                    Assert.Fail("Found {0} transitions, expecting 3.", trans);
                }
            }

            // Make sure old documents are unmodified.
            AssertEx.IsDocumentState(document, 0, 0, 0, 0);
            AssertEx.IsDocumentState(docFasta, 1, 2, 98, 311);
            AssertEx.IsDocumentState(docPeptides, 2, 3, 111, 352);

            // Add peptides in all possible locations.
            // 1. Root (already done)
            // 1. Before another group
            path = docPeptides.GetPathTo(0);
            SrmDocument docPeptides2 = docPeptides.ImportFasta(new StringReader(TEXT_BOVINE_PEPTIDES1), true, path, out path);

            AssertEx.IsDocumentState(docPeptides2, 3, 4, 124, 393);
            Assert.IsNotInstanceOfType(docPeptides2.Children[0].Id, typeof(FastaSequence));
            Assert.AreEqual(docPeptides2.Children[0].Id, path.GetIdentity(0));
            Assert.IsInstanceOfType(docPeptides2.Children[1].Id, typeof(FastaSequence));
            // Make sure previously existing groups are unchanged
            Assert.AreSame(docPeptides.Children[0], docPeptides2.Children[1]);
            Assert.AreSame(docPeptides.Children[1], docPeptides2.Children[2]);
            Assert.AreSame(docPeptides.Children[2], docPeptides2.Children[3]);

            // 2. Inside a FASTA group
            path = docPeptides2.GetPathTo((int)SrmDocument.Level.Transitions, 100);
            SrmDocument docPeptides3 = docPeptides2.ImportFasta(new StringReader(TEXT_BOVINE_PEPTIDES1), true, path, out path);

            AssertEx.IsDocumentState(docPeptides3, 4, 5, 137, 434);
            Assert.AreEqual(2, docPeptides3.FindNodeIndex(path));
            // Make sure previously existing groups are unchanged
            Assert.AreSame(docPeptides2.Children[1], docPeptides3.Children[1]);
            Assert.AreSame(docPeptides2.Children[2], docPeptides3.Children[3]);

            // 3. To a peptide list
            //    a. Same peptides
            path         = docPeptides2.GetPathTo(0);
            docPeptides3 = docPeptides2.ImportFasta(new StringReader(TEXT_BOVINE_PEPTIDES1), true, path, out path);
            // No longer filter repeated peptides, because they are useful for explicit modifictations.
            Assert.AreNotSame(docPeptides2, docPeptides3);
            Assert.IsNotNull(path);

            //    b. Different paptides
            path = docPeptides2.GetPathTo(0);
            IdentityPath pathFirstPep = docPeptides3.GetPathTo((int)SrmDocument.Level.Molecules, 0);

            docPeptides3 = docPeptides2.ImportFasta(new StringReader(TEXT_BOVINE_PEPTIDES2), true, path, out path);
            AssertEx.IsDocumentState(docPeptides3, 4, 4, 140, 448);
            Assert.AreSame(docPeptides2.Children[0].Id, docPeptides3.Children[0].Id);
            Assert.AreNotSame(docPeptides2.Children[0], docPeptides3.Children[0]);
            Assert.AreEqual("LVTDLTK", ((PeptideDocNode)docPeptides3.FindNode(path)).Peptide.Sequence);
            int          index         = docPeptides3.FindNodeIndex(path);
            IdentityPath pathPreceding = docPeptides3.GetPathTo(path.Depth, index - 1);

            Assert.AreEqual("IVGYLDEEGVLDQNR", ((PeptideDocNode)docPeptides3.FindNode(pathPreceding)).Peptide.Sequence);
            Assert.AreEqual(0, docPeptides3.FindNodeIndex(pathFirstPep));

            // 4. At a peptide in a peptide list
            path         = docPeptides2.GetPathTo((int)SrmDocument.Level.Molecules, 0);
            docPeptides3 = docPeptides2.ImportFasta(new StringReader(TEXT_BOVINE_PEPTIDES2), true, path, out path);
            AssertEx.IsDocumentState(docPeptides3, 4, 4, 140, 448);
            Assert.AreSame(docPeptides2.Children[0].Id, docPeptides3.Children[0].Id);
            Assert.AreNotSame(docPeptides2.Children[0], docPeptides3.Children[0]);
            Assert.AreEqual(0, docPeptides3.FindNodeIndex(path));
            Assert.AreEqual(16, docPeptides3.FindNodeIndex(pathFirstPep));

            // 5. Inside a peptide in a peptide list
            path         = docPeptides2.GetPathTo((int)SrmDocument.Level.Transitions, 0);
            docPeptides3 = docPeptides2.ImportFasta(new StringReader(TEXT_BOVINE_PEPTIDES2), true, path, out path);
            AssertEx.IsDocumentState(docPeptides3, 4, 4, 140, 448);
            Assert.AreSame(docPeptides2.Children[0].Id, docPeptides3.Children[0].Id);
            Assert.AreNotSame(docPeptides2.Children[0], docPeptides3.Children[0]);
            Assert.AreEqual(1, docPeptides3.FindNodeIndex(path));
            Assert.AreEqual(0, docPeptides3.FindNodeIndex(pathFirstPep));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Removes peaks and annotations that were in the document but not in the file, so that all peptide results that were not explicitly imported as part of this file are now blank
        /// </summary>
        /// <param name="docNew">SrmDocument for which missing peaks should be removed</param>
        /// <param name="trackAdjustedResults">List of peaks that were in the imported file</param>
        /// <param name="changePeaks">If true, remove both peaks and annotations.  If false, only remove annotations</param>
        /// <returns></returns>
        private SrmDocument RemoveMissing(SrmDocument docNew, ICollection <ResultsKey> trackAdjustedResults, bool changePeaks)
        {
            var measuredResults  = docNew.Settings.MeasuredResults;
            var chromatogramSets = measuredResults.Chromatograms;

            for (int i = 0; i < chromatogramSets.Count; ++i)
            {
                var set     = chromatogramSets[i];
                var nameSet = set.Name;
                for (int k = 0; k < docNew.MoleculeCount; ++k)
                {
                    IdentityPath pepPath = docNew.GetPathTo((int)SrmDocument.Level.Molecules, k);
                    var          pepNode = (PeptideDocNode)Document.FindNode(pepPath);
                    if (pepNode.IsDecoy)
                    {
                        continue;
                    }
                    if (pepNode.GlobalStandardType != null)
                    {
                        continue;
                    }
                    foreach (var groupNode in pepNode.TransitionGroups)
                    {
                        var groupPath  = new IdentityPath(pepPath, groupNode.Id);
                        var chromInfos = groupNode.Results[i];
                        if (chromInfos.IsEmpty)
                        {
                            continue;
                        }

                        foreach (var groupChromInfo in chromInfos)
                        {
                            if (groupChromInfo == null)
                            {
                                continue;
                            }
                            var key = new ResultsKey(groupChromInfo.FileId.GlobalIndex, groupNode.Id);
                            if (!trackAdjustedResults.Contains(key))
                            {
                                CountMissing++;
                                var fileId   = groupChromInfo.FileId;
                                var fileInfo = set.GetFileInfo(fileId);
                                var filePath = fileInfo.FilePath;
                                // Remove annotations for defs that were imported into the document and were on this peptide prior to import
                                var newAnnotationValues = groupChromInfo.Annotations.ListAnnotations().ToList();
                                newAnnotationValues = newAnnotationValues.Where(a => !AnnotationsAdded.Contains(a.Key)).ToList();
                                var newAnnotations = new Annotations(groupChromInfo.Annotations.Note, newAnnotationValues, groupChromInfo.Annotations.ColorIndex);
                                var newGroupNode   = groupNode.ChangePrecursorAnnotations(fileId, newAnnotations);
                                if (!ReferenceEquals(groupNode, newGroupNode))
                                {
                                    docNew = (SrmDocument)docNew.ReplaceChild(groupPath.Parent, newGroupNode);
                                }
                                // Adjust peaks to null if they weren't in the file
                                if (changePeaks)
                                {
                                    docNew = docNew.ChangePeak(groupPath, nameSet, filePath,
                                                               null, null, null, UserSet.IMPORTED, null, false);
                                }
                            }
                        }
                    }
                }
            }
            return(docNew);
        }
Ejemplo n.º 18
0
        public void TestPaste()
        {
            ClearDefaultModifications();
            _yeastDoc = new SrmDocument(SrmSettingsList.GetDefault().ChangeTransitionInstrument(instrument => instrument.ChangeMaxMz(1600)));
            _yeastDoc = _yeastDoc.ChangeSettings(_yeastDoc.Settings.ChangeTransitionFilter(filter =>
                                                                                           filter.ChangeMeasuredIons(new MeasuredIon[0])));
            IdentityPath path;

            _yeastDocReadOnly = _yeastDoc = _yeastDoc.ImportFasta(new StringReader(ExampleText.TEXT_FASTA_YEAST_LIB),
                                                                  false, IdentityPath.ROOT, out path);

            _study7DocReadOnly = _study7Doc = CreateStudy7Doc();

            IdentityPath pathRoot = IdentityPath.ROOT;

            // Test pasting into document with same implicit modifications does not create any extra explicit modifications.
            var study7EmptyDoc     = (SrmDocument)_study7Doc.ChangeChildren(new DocNode[0]);
            var study7PasteDoc     = CopyPaste(_study7Doc, null, study7EmptyDoc, pathRoot);
            var arrayPeptides      = _study7Doc.Peptides.ToArray();
            var arrayPastePeptides = study7PasteDoc.Peptides.ToArray();

            Assert.AreEqual(arrayPeptides.Length, arrayPastePeptides.Length);
            AssertEx.DocsEqual(_study7Doc, study7PasteDoc); // DocsEqual gives a more verbose failure message using XML output

            // Test implicit mods in source document become explicit mods in target document.
            ResetDocuments();
            _yeastDoc = (SrmDocument)_yeastDoc.ChangeChildren(new DocNode[0]);
            var settings = _yeastDoc.Settings;

            _yeastDoc = _yeastDoc.ChangeSettings(settings.ChangePeptideModifications(mods =>
                                                                                     mods.ChangeStaticModifications(new StaticMod[0])));
            _yeastDoc = CopyPaste(_study7Doc, null, _yeastDoc, pathRoot);
            var pepMods = _yeastDoc.Settings.PeptideSettings.Modifications;

            Assert.IsTrue(pepMods.StaticModifications != null);
            Assert.IsTrue(pepMods.HasHeavyModifications);
            Assert.IsFalse(pepMods.StaticModifications.Contains(mod => !mod.IsExplicit));
            Assert.IsFalse(pepMods.HeavyModifications.Contains(mod => !mod.IsExplicit));

            // Test explicit mods are dropped if the target document has matching implicit modifications.
            study7PasteDoc = CopyPaste(_yeastDoc, null, study7EmptyDoc, pathRoot);
            Assert.AreEqual(_study7Doc, study7PasteDoc);

            // Add new label type to source document.
            ResetDocuments();
            const string labelTypeName13C = "heavy 13C";
            var          labelType13C     = new IsotopeLabelType(labelTypeName13C, IsotopeLabelType.light.SortOrder + 1);

            _yeastDoc = ChangePeptideModifications(_yeastDoc,
                                                   new[] { new TypedModifications(labelType13C, HEAVY_MODS_13_C) });
            Assert.IsTrue(_yeastDoc.PeptideTransitionGroups.Contains(nodeGroup =>
                                                                     Equals(nodeGroup.TransitionGroup.LabelType, labelType13C)));
            // Test pasting into the same document with new label type.
            _yeastDoc = CopyPaste(_yeastDoc, null, _yeastDoc, pathRoot);
            // Check all transition have correct label type references.
            Assert.IsFalse(_yeastDoc.PeptideTransitionGroups.Contains(nodeGroup =>
            {
                IsotopeLabelType labelType = nodeGroup.TransitionGroup.LabelType;
                return(!ReferenceEquals(labelType,
                                        _yeastDoc.Settings.PeptideSettings.Modifications.GetModificationsByName(labelType.Name).LabelType));
            }));

            // Check new document still serializes correctly.
            AssertEx.Serializable(_yeastDoc, AssertEx.DocumentCloned);

            // Test pasting into new document drops label types from source document that are not found in the target document.
            _yeastDoc = CopyPaste(_yeastDoc, null, new SrmDocument(SrmSettingsList.GetDefault()), pathRoot);
            Assert.IsNull(_yeastDoc.Settings.PeptideSettings.Modifications.GetModificationsByName(labelTypeName13C));

            // If only specific children are selected, test that only these children get copied.
            ResetDocuments();
            var             arrayTrans = _study7Doc.PeptideTransitions.ToArray();
            IList <DocNode> selNodes   = new List <DocNode>();

            for (int i = 0; i < arrayTrans.Length; i += 2)
            {
                selNodes.Add(arrayTrans[i]);
            }
            _study7Doc = CopyPaste(_study7Doc, selNodes, _study7Doc, pathRoot);
            Assert.AreEqual(arrayTrans.Length + selNodes.Count, _study7Doc.PeptideTransitionCount);

            // Test after pasting to a peptide list, all children have been updated to point to the correct parent.
            ResetDocuments();
            _study7Doc = CopyPaste(_yeastDoc, new[] { _yeastDoc.Peptides.ToArray()[0] }, _study7Doc,
                                   _study7Doc.GetPathTo((int)SrmDocument.Level.MoleculeGroups, 0));
            Assert.AreEqual(_yeastDoc.Peptides.ToArray()[0].Peptide, _study7Doc.Peptides.ToArray()[0].Peptide);
            Assert.AreEqual(_study7Doc.Peptides.ToArray()[0].Peptide,
                            _study7Doc.PeptideTransitionGroups.ToArray()[0].TransitionGroup.Peptide);
            Assert.AreEqual(_study7Doc.PeptideTransitionGroups.ToArray()[0].TransitionGroup,
                            _study7Doc.PeptideTransitions.ToArray()[0].Transition.Group);

            // If only specific transition are selected for a peptide, but all transition groups are included, test AutoManageChildren is true.
            ResetDocuments();
            selNodes = new List <DocNode>();
            foreach (TransitionGroupDocNode transGroup in _study7Doc.PeptideTransitionGroups)
            {
                selNodes.Add(transGroup.Children[0]);
            }
            // TODO: Fix this and make it pass
//            var emptyDoc = (SrmDocument)_study7Doc.ChangeChildren(new List<DocNode>());
//            _study7Doc = CopyPaste(_study7Doc, selNodes, emptyDoc, pathRoot);
            _study7Doc = (SrmDocument)_study7Doc.ChangeChildren(new List <DocNode>());
            _study7Doc = CopyPaste(_study7Doc, selNodes, _study7Doc, pathRoot);
            foreach (PeptideDocNode peptide in _study7Doc.Peptides)
            {
                Assert.IsTrue(peptide.AutoManageChildren);
            }

            // Test pasting in modifications with the same name as but different definition from existing modifications not allowed.
            ResetDocuments();
            _yeastDoc = ChangePeptideModifications(_yeastDoc,
                                                   new[] { new TypedModifications(IsotopeLabelType.heavy, HEAVY_C_K_DIFDEF) });
            SetDefaultModifications(_study7Doc);
            AssertEx.ThrowsException <Exception>(() => _yeastDoc.Settings.UpdateDefaultModifications(false));

            // Test variable modifications kept if target document has matching variable modifications turned on.
            ResetDocuments();
            settings = _yeastDoc.Settings;
            var modsDefault      = settings.PeptideSettings.Modifications;
            var listVariableMods = new List <StaticMod>(modsDefault.StaticModifications)
            {
                VAR_MET_OXIDIZED
            };

            _yeastDoc = _yeastDoc.ChangeSettings(settings.ChangePeptideModifications(mods =>
                                                                                     mods.ChangeStaticModifications(listVariableMods.ToArray())));
            // Make sure there is an implicitly modified peptide in the yeast document
            Assert.IsTrue(_yeastDoc.Peptides.Contains(nodePep => nodePep.Peptide.Sequence.Contains("C")));
            Assert.IsTrue(_yeastDoc.Peptides.Contains(nodePep => nodePep.HasVariableMods));
            _yeastDoc = CopyPaste(_yeastDoc, null, _yeastDoc, pathRoot);
            Assert.IsFalse(_yeastDoc.Peptides.Contains(nodePep => nodePep.HasExplicitMods && !nodePep.HasVariableMods));

            // Otherwise the variable modifications become only explicit modifications.
            var yeastDocVar = _yeastDoc;

            _yeastDoc = _yeastDoc.ChangeSettings(_yeastDoc.Settings.ChangePeptideModifications(mods => modsDefault));
            _yeastDoc = CopyPaste(yeastDocVar, null, _yeastDoc, pathRoot);
            Assert.IsFalse(_yeastDoc.Settings.PeptideSettings.Modifications.HasVariableModifications);
            Assert.IsTrue(_yeastDoc.Peptides.Contains(nodePep => nodePep.HasExplicitMods));
            Assert.IsFalse(_yeastDoc.Peptides.Contains(nodePep => nodePep.HasVariableMods));
        }