Exemplo 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);
        }
Exemplo n.º 2
0
        private ChromatogramGroupInfo LoadChromatogramInfo(SrmDocument document, ChromatogramSet chromatogramSet, MsDataFileUri filePath,
                                                           IdentityPath precursorIdentityPath, bool loadPoints)
        {
            var measuredResults = document.Settings.MeasuredResults;

            if (null == measuredResults)
            {
                return(null);
            }
            var tolerance        = (float)document.Settings.TransitionSettings.Instrument.MzMatchTolerance;
            var peptideDocNode   = (PeptideDocNode)document.FindNode(precursorIdentityPath.Parent);
            var precursorDocNode = (TransitionGroupDocNode)peptideDocNode.FindNode(precursorIdentityPath.Child);

            ChromatogramGroupInfo[] chromatogramGroupInfos;
            if (!measuredResults.TryLoadChromatogram(chromatogramSet, peptideDocNode, precursorDocNode, tolerance, loadPoints,
                                                     out chromatogramGroupInfos))
            {
                return(null);
            }
            foreach (var chromatogramGroupInfo in chromatogramGroupInfos)
            {
                if (Equals(chromatogramGroupInfo.FilePath, filePath))
                {
                    return(chromatogramGroupInfo);
                }
            }
            return(null);
        }
Exemplo n.º 3
0
        private void CompareUntriggeredTriggered(SrmDocument untriggeredDocument, SrmDocument triggeredDocument, IdentityPath identityPath)
        {
            Assert.IsFalse(untriggeredDocument.Settings.TransitionSettings.Instrument.TriggeredAcquisition);
            Assert.IsTrue(triggeredDocument.Settings.TransitionSettings.Instrument.TriggeredAcquisition);
            PeptideDocNode untriggeredPeptide = (PeptideDocNode)untriggeredDocument.FindNode(identityPath);
            PeptideDocNode triggeredPeptide   = (PeptideDocNode)triggeredDocument.FindNode(identityPath);

            Assert.AreEqual(untriggeredPeptide.TransitionGroupCount, triggeredPeptide.TransitionGroupCount);
            for (int iTransitionGroup = 0;
                 iTransitionGroup < untriggeredPeptide.TransitionGroupCount;
                 iTransitionGroup++)
            {
                var untriggeredTransitionGroup = (TransitionGroupDocNode)untriggeredPeptide.Children[iTransitionGroup];
                var triggeredTransitionGroup   = (TransitionGroupDocNode)triggeredPeptide.Children[iTransitionGroup];
                Assert.IsNotNull(untriggeredTransitionGroup.Results);
                Assert.IsNotNull(triggeredTransitionGroup.Results);
                Assert.AreEqual(untriggeredTransitionGroup.Results.Count, triggeredTransitionGroup.Results.Count);
                Assert.AreNotEqual(0, untriggeredTransitionGroup.Results.Count);
                for (int iReplicate = 0; iReplicate < untriggeredTransitionGroup.Results.Count; iReplicate++)
                {
                    Assert.AreEqual(1, untriggeredTransitionGroup.Results[iReplicate].Count);
                    Assert.AreEqual(1, triggeredTransitionGroup.Results[iReplicate].Count);
                    var untriggeredChromInfo = untriggeredTransitionGroup.Results[iReplicate].First();
                    var triggeredChromInfo   = triggeredTransitionGroup.Results[iReplicate].First();
                    Assert.AreNotEqual(0, untriggeredChromInfo.BackgroundArea);
                    Assert.AreEqual(0, triggeredChromInfo.BackgroundArea);
                }
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Given a list of IdentityPaths, returns the unique set of NormalizationMethods that the molecules
        /// or peptides use.
        /// </summary>
        public static HashSet <NormalizationMethod> GetMoleculeNormalizationMethods(SrmDocument document,
                                                                                    IEnumerable <IdentityPath> identityPaths)
        {
            var defaultNormalizationMethod = document.Settings.PeptideSettings.Quantification.NormalizationMethod;
            var normalizationMethods       = new HashSet <NormalizationMethod>();

            foreach (var path in identityPaths.Select(path => path.GetPathTo(Math.Min(1, path.Depth))).Distinct())
            {
                var docNode = document.FindNode(path);
                IEnumerable <PeptideDocNode> molecules;
                if (docNode is PeptideDocNode molecule)
                {
                    molecules = new[] { molecule };
                }
                else if (docNode is PeptideGroupDocNode peptideGroupDocNode)
                {
                    molecules = peptideGroupDocNode.Molecules;
                }
                else
                {
                    continue;
                }

                normalizationMethods.UnionWith(molecules.Select(mol =>
                                                                mol.NormalizationMethod ?? defaultNormalizationMethod));
            }

            return(normalizationMethods);
        }
Exemplo n.º 5
0
        public Annotations GetAnnotations(SrmDocument document, ElementRef elementRef)
        {
            var nodeRef = elementRef as NodeRef;

            if (nodeRef != null)
            {
                return(document.FindNode(ToIdentityPath(nodeRef)).Annotations);
            }
            var replicateRef = elementRef as ReplicateRef;

            if (replicateRef != null)
            {
                var chromatogramSet = replicateRef.FindChromatogramSet(document);
                if (chromatogramSet == null)
                {
                    throw ElementNotFoundException(elementRef);
                }
                return(chromatogramSet.Annotations);
            }
            var resultRef = elementRef as ResultRef;

            if (resultRef != null)
            {
                return(GetResultAnnotations(document, resultRef));
            }
            throw AnnotationsNotSupported(elementRef);
        }
Exemplo n.º 6
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));
        }
Exemplo n.º 7
0
        private Annotations GetResultAnnotations(SrmDocument document, ResultRef resultRef)
        {
            var measuredResults = document.MeasuredResults;

            if (measuredResults == null)
            {
                throw ElementNotFoundException(resultRef);
            }
            var nodeRef      = (NodeRef)resultRef.Parent;
            var identityPath = ToIdentityPath(nodeRef);
            var docNode      = document.FindNode(identityPath);

            for (int replicateIndex = 0; replicateIndex < measuredResults.Chromatograms.Count; replicateIndex++)
            {
                var chromSet = measuredResults.Chromatograms[replicateIndex];
                if (resultRef.Matches(chromSet))
                {
                    var transitionGroup = docNode as TransitionGroupDocNode;
                    if (transitionGroup != null)
                    {
                        if (transitionGroup.Results == null || transitionGroup.Results.Count <= replicateIndex)
                        {
                            throw ElementNotFoundException(resultRef);
                        }
                        int i = IndexOfChromInfo(chromSet, (PrecursorResultRef)resultRef,
                                                 transitionGroup.Results[replicateIndex]);
                        if (i < 0)
                        {
                            throw ElementNotFoundException(resultRef);
                        }
                        return(transitionGroup.Results[replicateIndex][i].Annotations);
                    }
                    else
                    {
                        var transition = docNode as TransitionDocNode;
                        if (transition != null)
                        {
                            if (transition.Results == null || transition.Results.Count <= replicateIndex)
                            {
                                throw ElementNotFoundException(resultRef);
                            }
                            int i = IndexOfChromInfo(chromSet, (TransitionResultRef)resultRef,
                                                     transition.Results[replicateIndex]);
                            if (i < 0)
                            {
                                throw ElementNotFoundException(resultRef);
                            }
                            return(transition.Results[replicateIndex][i].Annotations);
                        }
                        else
                        {
                            throw AnnotationsNotSupported(resultRef);
                        }
                    }
                }
            }
            throw ElementNotFoundException(resultRef);
        }
Exemplo n.º 8
0
        public SrmDocument SetDocNodeAnnotations(SrmDocument document, NodeRef nodeRef, Annotations annotations)
        {
            var identityPath = ToIdentityPath(nodeRef);
            var docNode      = document.FindNode(identityPath);

            docNode  = docNode.ChangeAnnotations(annotations);
            document = (SrmDocument)document.ReplaceChild(identityPath.Parent, docNode);
            return(document);
        }
Exemplo n.º 9
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);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Returns the string that MSstats code uses to identify a row of data in the MSstats Input report.
        /// </summary>
        private static string GetFeatureKey(SrmDocument document, IdentityPath identityPath)
        {
            PeptideGroupDocNode    peptideGroup    = (PeptideGroupDocNode)document.FindNode(identityPath.GetIdentity(0));
            PeptideDocNode         peptide         = (PeptideDocNode)peptideGroup.FindNode(identityPath.GetIdentity(1));
            TransitionGroupDocNode transitionGroup =
                (TransitionGroupDocNode)peptide.FindNode(identityPath.GetIdentity(2));
            TransitionDocNode transition = (TransitionDocNode)transitionGroup.FindNode(identityPath.GetIdentity(3));

            return(peptide.ModifiedSequenceDisplay + '_' + transitionGroup.PrecursorCharge + '_' + GetFragmentIon(transition) +
                   '_' + transition.Transition.Charge);
        }
Exemplo n.º 11
0
        private List <DocNode> GetDocNodes(IdentityPath identityPath, SrmDocument document)
        {
            var result = new List <DocNode>();

            while (!identityPath.IsRoot)
            {
                result.Insert(0, document.FindNode(identityPath));
                identityPath = identityPath.Parent;
            }
            return(result);
        }
Exemplo n.º 12
0
            public SrmDocument ChangePeak(SrmDocument doc, SrmTreeNode nodePepTree, TransitionGroupDocNode nodeTranGroup, string nameSet, MsDataFileUri filePath)
            {
                if ((_retentionTime ?? StartTime) == null)
                {
                    return(doc);
                }

                var groupPath = new IdentityPath(nodePepTree.Path, nodeTranGroup.Id);

                doc = _retentionTime.HasValue
                    ? doc.ChangePeak(groupPath, nameSet, filePath, null, _retentionTime.Value, UserSet.TRUE)
                    : doc.ChangePeak(groupPath, nameSet, filePath, null, StartTime, EndTime, UserSet.TRUE, null, false);

                var activeTransitionGroup = (TransitionGroupDocNode)doc.FindNode(groupPath);

                if (activeTransitionGroup.RelativeRT != RelativeRT.Matching)
                {
                    return(doc);
                }

                var activeChromInfo = SkylineWindow.FindChromInfo(doc, activeTransitionGroup, nameSet, filePath);
                var peptide         = (PeptideDocNode)doc.FindNode(groupPath.Parent);

                // See if there are any other transition groups that should have their peak bounds set to the same value
                foreach (var tranGroup in peptide.TransitionGroups.Where(tranGroup => tranGroup.RelativeRT == RelativeRT.Matching))
                {
                    var otherGroupPath = new IdentityPath(groupPath.Parent, tranGroup.TransitionGroup);
                    if (Equals(groupPath, otherGroupPath) || SkylineWindow.FindChromInfo(doc, tranGroup, nameSet, filePath) == null)
                    {
                        continue;
                    }

                    doc = doc.ChangePeak(otherGroupPath, nameSet, filePath, null,
                                         activeChromInfo.StartRetentionTime, activeChromInfo.EndRetentionTime, UserSet.TRUE, activeChromInfo.Identified, false);
                }
                return(doc);
            }
Exemplo n.º 13
0
        public SrmDocument SetResultAnnotations(SrmDocument document, ResultRef resultRef, Annotations annotations)
        {
            var measuredResults = document.MeasuredResults;

            if (measuredResults == null)
            {
                throw ElementNotFoundException(resultRef);
            }
            var nodeRef      = (NodeRef)resultRef.Parent;
            var identityPath = ToIdentityPath(nodeRef);
            var docNode      = document.FindNode(identityPath);

            for (int replicateIndex = 0; replicateIndex < measuredResults.Chromatograms.Count; replicateIndex++)
            {
                var chromSet = measuredResults.Chromatograms[replicateIndex];
                if (resultRef.Matches(chromSet))
                {
                    var transitionGroup = docNode as TransitionGroupDocNode;
                    if (transitionGroup != null)
                    {
                        var results = transitionGroup.Results.ToArray();
                        results[replicateIndex] = SetChromInfoAnnotations(chromSet, (PrecursorResultRef)resultRef,
                                                                          results[replicateIndex], annotations);
                        docNode = ((TransitionGroupDocNode)docNode).ChangeResults(
                            new Results <TransitionGroupChromInfo>(results));
                    }
                    else
                    {
                        var transition = docNode as TransitionDocNode;
                        if (transition != null)
                        {
                            var results = transition.Results.ToArray();
                            results[replicateIndex] = SetChromInfoAnnotations(chromSet, (TransitionResultRef)resultRef,
                                                                              results[replicateIndex], annotations);
                            docNode = ((TransitionDocNode)docNode).ChangeResults(
                                new Results <TransitionChromInfo>(results));
                        }
                        else
                        {
                            throw AnnotationsNotSupported(resultRef);
                        }
                    }
                    return((SrmDocument)document.ReplaceChild(identityPath.Parent, docNode));
                }
            }
            throw ElementNotFoundException(resultRef);
        }
Exemplo n.º 14
0
        public virtual NodeRef ChangeIdentityPath(SrmDocument document, IdentityPath identityPath)
        {
            if (Parent == null)
            {
                return(this);
            }
            var parentNode = (DocNodeParent)document.FindNode(identityPath.Parent);
            int index      = parentNode.FindNodeIndex(identityPath.Child);

            if (index < 0)
            {
                throw new IdentityNotFoundException(identityPath.Child);
            }
            var parentRef = Parent.ChangeIdentityPath(document, identityPath.Parent);

            return((NodeRef)
                   ((NodeRef)ChangeParent(parentRef)).EnumerateSiblings(document).Skip(index).FirstOrDefault());
        }
Exemplo n.º 15
0
 private SrmDocument SetExcludeStandard(SrmDocument document, IdentityPath peptideIdPath, int resultsIndex, bool exclude)
 {
     if (!document.Settings.HasResults)
     {
         return document;
     }
     var peptideDocNode = (PeptideDocNode) document.FindNode(peptideIdPath);
     if (peptideDocNode == null)
     {
         return document;
     }
     if (resultsIndex < 0 || resultsIndex >= document.Settings.MeasuredResults.Chromatograms.Count)
     {
         return document;
     }
     bool wasExcluded = peptideDocNode.IsExcludeFromCalibration(resultsIndex);
     return (SrmDocument) document.ReplaceChild(peptideIdPath.Parent,
         peptideDocNode.ChangeExcludeFromCalibration(resultsIndex, !wasExcluded));
 }
Exemplo n.º 16
0
        private IList <DataRowDetails> SumMs1Transitions(IList <DataRowDetails> dataRows)
        {
            var dataRowsByReplicateIndexAndTransitionGroup =
                dataRows.ToLookup(row =>
                                  new Tuple <int, IdentityPath>(row.ReplicateIndex,
                                                                row.IdentityPath.GetPathTo((int)SrmDocument.Level.TransitionGroups)));
            var newDataRows = new List <DataRowDetails>();

            foreach (var grouping in dataRowsByReplicateIndexAndTransitionGroup)
            {
                DataRowDetails ms1DataRow      = null;
                var            transitionGroup = (TransitionGroupDocNode)SrmDocument.FindNode(grouping.Key.Item2);
                foreach (var dataRow in grouping)
                {
                    var transition = (TransitionDocNode)transitionGroup.FindNode(dataRow.IdentityPath.Child);
                    if (transition.IsMs1)
                    {
                        if (ms1DataRow == null)
                        {
                            ms1DataRow = new DataRowDetails()
                            {
                                IdentityPath   = grouping.Key.Item2,
                                BioReplicate   = dataRow.BioReplicate,
                                Control        = dataRow.Control,
                                ReplicateIndex = dataRow.ReplicateIndex
                            };
                        }
                        ms1DataRow.Intensity   += dataRow.Intensity;
                        ms1DataRow.Denominator += dataRow.Denominator;
                    }
                    else
                    {
                        newDataRows.Add(dataRow);
                    }
                }
                if (ms1DataRow != null)
                {
                    newDataRows.Add(ms1DataRow);
                }
            }
            return(newDataRows);
        }
Exemplo n.º 17
0
            protected override SrmDocument RemovePeaks(SrmDocument document, IGrouping <IdentityPath, ResultFileKey> peaks)
            {
                var peptideDocNode = (PeptideDocNode)document.FindNode(peaks.Key);

                foreach (var resultFileKey in peaks)
                {
                    string        replicateName;
                    MsDataFileUri filePath;
                    if (!GetReplicateName(document, resultFileKey, out replicateName, out filePath))
                    {
                        continue;
                    }
                    foreach (TransitionGroupDocNode transitionGroup in peptideDocNode.TransitionGroups)
                    {
                        var groupPath = new IdentityPath(peaks.Key, transitionGroup.Id);
                        document = RemovePrecursorPeak(document, groupPath, replicateName, filePath);
                    }
                }

                return(document);
            }
Exemplo n.º 18
0
 /// <summary>
 /// Modifies a document in response to the user clicking on a peak in the GraphChromatogram.
 /// </summary>
 private static SrmDocument PickPeak(SrmDocument document, PickedPeakEventArgs e)
 {
     document = document.ChangePeak(e.GroupPath, e.NameSet, e.FilePath, e.TransitionId, e.RetentionTime.MeasuredTime, UserSet.TRUE);
     var activeTransitionGroup = (TransitionGroupDocNode) document.FindNode(e.GroupPath);
     if (activeTransitionGroup.RelativeRT != RelativeRT.Matching)
     {
         return document;
     }
     var activeChromInfo = FindChromInfo(document, activeTransitionGroup, e.NameSet, e.FilePath);
     var peptide = (PeptideDocNode) document.FindNode(e.GroupPath.Parent);
     // See if there are any other transition groups that should have their peak bounds set to the same value
     foreach (var transitionGroup in peptide.TransitionGroups)
     {
         if (transitionGroup.RelativeRT != RelativeRT.Matching)
         {
             continue;
         }
         var groupPath = new IdentityPath(e.GroupPath.Parent, transitionGroup.TransitionGroup);
         if (Equals(groupPath, e.GroupPath))
         {
             continue;
         }
         var chromInfo = FindChromInfo(document, transitionGroup, e.NameSet, e.FilePath);
         if (null == chromInfo)
         {
             continue;
         }
         document = document.ChangePeak(groupPath, e.NameSet, e.FilePath, null,
             activeChromInfo.StartRetentionTime, activeChromInfo.EndRetentionTime, UserSet.TRUE, activeChromInfo.Identified, true);
     }
     return document;
 }
Exemplo n.º 19
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);
        }
Exemplo n.º 20
0
        public override void UpdateGraph(bool selectionChanged)
        {
            CurveList.Clear();
            GraphObjList.Clear();
            SrmDocument document         = GraphSummary.DocumentUIContainer.DocumentUI;
            var         selectedTreeNode = GraphSummary.StateProvider.SelectedNode as SrmTreeNode;

            if (selectedTreeNode == null || document.FindNode(selectedTreeNode.Path) == null)
            {
                Title.Text = Helpers.PeptideToMoleculeTextMapper.Translate(Resources.MassErrorReplicateGraphPane_UpdateGraph_Select_a_peptide_to_see_the_mass_error_graph, document.DocumentType);
                EmptyGraph(document);
                return;
            }
            if (!document.Settings.HasResults)
            {
                Title.Text = Resources.AreaReplicateGraphPane_UpdateGraph_No_results_available;
                EmptyGraph(document);
                return;
            }
            DisplayTypeChrom displayType;

            if (Equals(PaneKey, PaneKey.PRECURSORS))
            {
                displayType = DisplayTypeChrom.precursors;
            }
            else if (Equals(PaneKey, PaneKey.PRODUCTS))
            {
                displayType = DisplayTypeChrom.products;
            }
            else
            {
                displayType = GraphChromatogram.GetDisplayType(document, selectedTreeNode);
            }
            Title.Text = null;
            var aggregateOp = GraphValues.AggregateOp.FromCurrentSettings();

            YAxis.Title.Text = aggregateOp.Cv
                ? aggregateOp.AnnotateTitle(Resources.MassErrorReplicateGraphPane_UpdateGraph_Mass_Error_No_Ppm)
                : Resources.MassErrorReplicateGraphPane_UpdateGraph_Mass_Error;
            DocNode      selectedNode = selectedTreeNode.Model;
            DocNode      parentNode   = selectedNode;
            IdentityPath identityPath = selectedTreeNode.Path;

            // If the selected tree node is a transition, then its siblings are displayed.
            if (selectedTreeNode is TransitionTreeNode)
            {
                if (displayType != DisplayTypeChrom.single)
                {
                    SrmTreeNode parentTreeNode = selectedTreeNode.SrmParent;
                    parentNode   = parentTreeNode.Model;
                    identityPath = parentTreeNode.Path;
                }
            }
            // If the selected node is a peptide with one child, then show the children,
            // unless chromatogram display type is total
            else if (selectedTreeNode is PeptideTreeNode)
            {
                var children = ((PeptideDocNode)selectedNode).TransitionGroups
                               .Where(PaneKey.IncludesTransitionGroup)
                               .ToArray();
                if (children.Length == 1 && displayType != DisplayTypeChrom.total)
                {
                    selectedNode = parentNode = children[0];
                    identityPath = new IdentityPath(identityPath, parentNode.Id);
                }
            }
            else if (!(selectedTreeNode is TransitionGroupTreeNode))
            {
                Title.Text = Helpers.PeptideToMoleculeTextMapper.Translate(Resources.MassErrorReplicateGraphPane_UpdateGraph_Select_a_peptide_to_see_the_mass_error_graph, document.DocumentType);
                EmptyGraph(document);
                CanShowMassErrorLegend = false;
                return;
            }
            // If a precursor is going to be displayed with display type single
            if (parentNode is TransitionGroupDocNode && displayType == DisplayTypeChrom.single)
            {
                // If no optimization data, then show all the transitions
                displayType = DisplayTypeChrom.all;
            }

            var       replicateGroupOp = ReplicateGroupOp.FromCurrentSettings(document.Settings);
            GraphData graphData        = new MassErrorGraphData(document,
                                                                identityPath,
                                                                displayType,
                                                                replicateGroupOp,
                                                                PaneKey);

            CanShowMassErrorLegend = graphData.DocNodes.Count != 0;
            InitFromData(graphData);

            int    selectedReplicateIndex = SelectedIndex;
            double minRetentionTime       = double.MaxValue;
            double maxRetentionTime       = double.MinValue;

            int iColor = 0, iCharge = -1;
            var charge                 = Adduct.EMPTY;
            int countLabelTypes        = document.Settings.PeptideSettings.Modifications.CountLabelTypes;
            int colorOffset            = 0;
            var transitionGroupDocNode = parentNode as TransitionGroupDocNode;

            if (transitionGroupDocNode != null && displayType == DisplayTypeChrom.products)
            {
                // If we are only displaying product ions, we want to use an offset in the colors array
                // so that we do not re-use colors that would be used for any precursor ions.
                colorOffset =
                    GraphChromatogram.GetDisplayTransitions(transitionGroupDocNode, DisplayTypeChrom.precursors).Count();
            }
            for (int i = 0; i < graphData.DocNodes.Count; i++)
            {
                var docNode        = graphData.DocNodes[i];
                var pointPairLists = graphData.PointPairLists[i];
                int numSteps       = pointPairLists.Count / 2;
                for (int iStep = 0; iStep < pointPairLists.Count; iStep++)
                {
                    int   step          = iStep - numSteps;
                    var   pointPairList = pointPairLists[iStep];
                    Color color;
                    // ReSharper disable ExpressionIsAlwaysNull
                    var nodeGroup = docNode as TransitionGroupDocNode;
                    if (parentNode is PeptideDocNode)
                    {
                        int iColorGroup = GetColorIndex(nodeGroup, countLabelTypes, ref charge, ref iCharge);
                        color = COLORS_GROUPS[iColorGroup % COLORS_GROUPS.Count];
                    }
                    else if (displayType == DisplayTypeChrom.total)
                    {
                        color = COLORS_GROUPS[iColor % COLORS_GROUPS.Count];
                    }
                    else if (docNode.Equals(selectedNode) && step == 0)
                    {
                        color = ChromGraphItem.ColorSelected;
                    }
                    else
                    {
                        color = COLORS_TRANSITION[(iColor + colorOffset) % COLORS_TRANSITION.Count];
                    }
                    // ReSharper restore ExpressionIsAlwaysNull
                    iColor++;

                    string label = graphData.DocNodeLabels[i];
                    if (step != 0)
                    {
                        label = string.Format(Resources.RTReplicateGraphPane_UpdateGraph_Step__0__, step);
                    }
                    BarItem curveItem = new MeanErrorBarItem(label, pointPairList, color, Color.Black);

                    if (selectedReplicateIndex != -1 && selectedReplicateIndex < pointPairList.Count)
                    {
                        PointPair pointPair = pointPairList[selectedReplicateIndex];
                        if (!pointPair.IsInvalid)
                        {
                            minRetentionTime = Math.Min(minRetentionTime, pointPair.Y);
                            maxRetentionTime = Math.Max(maxRetentionTime, pointPair.Y);
                        }
                    }

                    curveItem.Bar.Border.IsVisible = false;
                    curveItem.Bar.Fill.Brush       = new SolidBrush(color);
                    curveItem.Tag = new IdentityPath(identityPath, docNode.Id);
                    CurveList.Add(curveItem);
                }
            }

            // Draw a box around the currently selected replicate
            if (ShowSelection && minRetentionTime != double.MaxValue)
            {
                maxRetentionTime = Math.Max(maxRetentionTime, 0);
                minRetentionTime = Math.Min(minRetentionTime, 0);
                GraphObjList.Add(new BoxObj(selectedReplicateIndex + .5, maxRetentionTime, 1,
                                            maxRetentionTime - minRetentionTime, Color.Black, Color.Empty)
                {
                    IsClippedToChartRect = true,
                });
            }

            XAxis.Scale.MinAuto = XAxis.Scale.MaxAuto = selectionChanged;
            YAxis.Scale.MinAuto = YAxis.Scale.MaxAuto = true;
            if (Settings.Default.MinMassError != 0)
            {
                YAxis.Scale.Min = Settings.Default.MinMassError;
            }
            if (Settings.Default.MaxMassError != 0)
            {
                YAxis.Scale.Max = Settings.Default.MaxMassError;
            }
            Legend.IsVisible = Settings.Default.ShowMassErrorLegend;
            AxisChange();
        }
Exemplo n.º 21
0
 /// <summary>
 /// Modifies a document in response to a user's mouse dragging on a GraphChromatogram.
 /// </summary>
 private static SrmDocument ChangePeakBounds(SrmDocument document, IEnumerable<ChangedPeakBoundsEventArgs> changes)
 {
     var changedGroupIds = new HashSet<IdentityPath>();
     var peptideChanges = new Dictionary<IdentityPath, ChangedPeakBoundsEventArgs>();
     foreach (var change in changes)
     {
         document = document.ChangePeak(change.GroupPath, change.NameSet, change.FilePath, change.Transition,
             change.StartTime.MeasuredTime, change.EndTime.MeasuredTime, UserSet.TRUE, change.Identified, false);
         changedGroupIds.Add(change.GroupPath);
         if (!peptideChanges.ContainsKey(change.GroupPath.Parent)) {
             var transitionGroup = (TransitionGroupDocNode) document.FindNode(change.GroupPath);
             if (transitionGroup.RelativeRT == RelativeRT.Matching)
             {
                 peptideChanges.Add(change.GroupPath.Parent, change);
             }
         }
     }
     // See if there are any other TransitionGroups that also have RelativeRT matching,
     // and set their peak boundaries to the same.
     foreach (var entry in peptideChanges)
     {
         var peptide = (PeptideDocNode) document.FindNode(entry.Key);
         var change = entry.Value;
         foreach (var transitionGroup in peptide.TransitionGroups)
         {
             if (transitionGroup.RelativeRT != RelativeRT.Matching)
             {
                 continue;
             }
             var groupId = new IdentityPath(entry.Key, transitionGroup.TransitionGroup);
             if (changedGroupIds.Contains(groupId))
             {
                 continue;
             }
             if (null == FindChromInfo(document, transitionGroup, change.NameSet, change.FilePath))
             {
                 continue;
             }
             document = document.ChangePeak(groupId, change.NameSet, change.FilePath, null,
                 change.StartTime.MeasuredTime, change.EndTime.MeasuredTime, UserSet.TRUE, change.Identified, true);
         }
     }
     return document;
 }
Exemplo n.º 22
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));
        }
Exemplo n.º 23
0
        public static Annotations MergeAnnotations(SrmDocument document, IEnumerable<IdentityPath> selPaths, 
            out AnnotationDef.AnnotationTargetSet annotationTarget)
        {
            annotationTarget = AnnotationDef.AnnotationTargetSet.EMPTY;

            // If the nodes have matching text, colors, or annotations, then we should display these values
            // in the EditNodeDlg. Otherwise, we should not display any value for that variable.
            bool matchingText = true;
            bool matchingColors = true;
            bool isFirstSelNode = true;
            bool allEmpty = true;

            // These are the default values we want for the annotations, if the node(s) do not already have
            // annotations, or if the annotations do not match.
            string text = null;
            int colorIndex = -1;
            var dictMatchingAnnotations = new Dictionary<string, string>();

            // Find what all nodes have in common as far as note, annotations, and color.
            foreach (IdentityPath selPath in selPaths)
            {
                if(Equals(selPath.Child, SequenceTree.NODE_INSERT_ID))
                    continue;

                var nodeDoc = document.FindNode(selPath);
                var nodeAnnotations = nodeDoc.Annotations;
                var dictNodeAnnotations = nodeAnnotations.ListAnnotations()
                    .ToDictionary(nodeAnnotation => nodeAnnotation.Key,
                                  nodeAnnotation => nodeAnnotation.Value);

                // If this is the first iteration, use the value for this node to start matching.
                if (isFirstSelNode)
                {
                    foreach (KeyValuePair<string, string> annotation in dictNodeAnnotations)
                    {
                        dictMatchingAnnotations.Add(annotation.Key, annotation.Value);
                    }
                    text = nodeAnnotations.Note;
                    colorIndex = nodeAnnotations.ColorIndex;
                    isFirstSelNode = false;
                }
                foreach (string key in dictMatchingAnnotations.Keys.ToArray())
                {
                    string value;
                    // If the list of annotations we are building for the dialog contains this key,
                    // check that the values are the same, otherwise the value for this annotation needs
                    // to be null for the dialog.
                    if (!dictNodeAnnotations.TryGetValue(key, out value) || !Equals(dictMatchingAnnotations[key], value))
                        dictMatchingAnnotations.Remove(key);
                }

                matchingText = matchingText && nodeAnnotations.Note != null && Equals(text, nodeAnnotations.Note);
                matchingColors = matchingColors
                    && !nodeAnnotations.IsEmpty
                    && nodeAnnotations.ColorIndex != -1
                    && Equals(colorIndex, nodeAnnotations.ColorIndex);

                allEmpty = allEmpty && nodeAnnotations.IsEmpty;

                // Update annotation target to include this type of node.
                annotationTarget = annotationTarget.Union(nodeDoc.AnnotationTarget);
            }
            if (!matchingText)
                text = string.Empty;
            if (allEmpty)
                colorIndex = Settings.Default.AnnotationColor;
            else if (!matchingColors)
                colorIndex = -1;
            return new Annotations(text, dictMatchingAnnotations, colorIndex);
        }
Exemplo n.º 24
0
        public void DoThermoRatioTest(RefinementSettings.ConvertToSmallMoleculesMode smallMoleculesTestMode)
        {
            TestSmallMolecules = false;  // We do this explicitly

            var         testFilesDir = new TestFilesDir(TestContext, ZIP_FILE);
            string      docPath;
            SrmDocument doc      = InitThermoDocument(testFilesDir, out docPath);
            SrmSettings settings = doc.Settings.ChangePeptideModifications(mods =>
                                                                           mods.ChangeInternalStandardTypes(new[] { IsotopeLabelType.light }));

            doc = doc.ChangeSettings(settings);
            if (smallMoleculesTestMode != RefinementSettings.ConvertToSmallMoleculesMode.none)
            {
                var docOrig = doc;
                var refine  = new RefinementSettings();
                doc = refine.ConvertToSmallMolecules(doc, smallMoleculesTestMode);
                // This is our first example of a converted label doc - check roundtripping
                AssertEx.ConvertedSmallMoleculeDocumentIsSimilar(docOrig, doc);
                AssertEx.Serializable(doc);
            }
            var    docContainer      = new ResultsTestDocumentContainer(doc, docPath);
            string extRaw            = ExtensionTestContext.ExtThermoRaw;
            var    listChromatograms = new List <ChromatogramSet>
            {
                new ChromatogramSet("rep03", new[]
                {
                    MsDataFileUri.Parse(testFilesDir.GetTestPath(
                                            "Site20_STUDY9P_PHASEII_QC_03" + extRaw))
                }),
                new ChromatogramSet("rep05", new[]
                {
                    MsDataFileUri.Parse(testFilesDir.GetTestPath(
                                            "Site20_STUDY9P_PHASEII_QC_05" + extRaw))
                })
            };
            var docResults = doc.ChangeMeasuredResults(new MeasuredResults(listChromatograms));

            Assert.IsTrue(docContainer.SetDocument(docResults, doc, true));
            docContainer.AssertComplete();
            docResults = docContainer.Document;
            // Make sure all groups have at least 5 transitions (of 6) with ratios
            int ratioGroupMissingCount = 0;

            foreach (var nodeGroup in docResults.MoleculeTransitionGroups)
            {
                if (nodeGroup.TransitionGroup.LabelType.IsLight)
                {
                    foreach (var result in nodeGroup.Results)
                    {
                        Assert.IsFalse(result[0].Ratio.HasValue, "Light group found with a ratio");
                    }
                    foreach (TransitionDocNode nodeTran in nodeGroup.Children)
                    {
                        foreach (var resultTran in nodeTran.Results)
                        {
                            Assert.IsFalse(resultTran[0].Ratio.HasValue, "Light transition found with a ratio");
                        }
                    }
                }
                else
                {
                    bool missingRatio = false;
                    foreach (ChromInfoList <TransitionGroupChromInfo> chromInfoList in nodeGroup.Results)
                    {
                        var ratioHeavy = chromInfoList[0].Ratio;
                        if (!ratioHeavy.HasValue)
                        {
                            missingRatio = true;
                        }
                    }
                    int ratioCount1 = 0;
                    int ratioCount2 = 0;
                    foreach (TransitionDocNode nodeTranHeavy in nodeGroup.Children)
                    {
                        float?ratioHeavy = nodeTranHeavy.Results[0][0].Ratio;
                        if (ratioHeavy.HasValue)
                        {
                            Assert.IsFalse(float.IsNaN(ratioHeavy.Value) || float.IsInfinity(ratioHeavy.Value));
                            ratioCount1++;
                        }
                        ratioHeavy = nodeTranHeavy.Results[1][0].Ratio;
                        if (ratioHeavy.HasValue)
                        {
                            Assert.IsFalse(float.IsNaN(ratioHeavy.Value) || float.IsInfinity(ratioHeavy.Value));
                            ratioCount2++;
                        }
                    }
                    Assert.AreEqual(3, ratioCount1);
                    if (ratioCount2 < 2)
                    {
                        ratioGroupMissingCount++;
                    }
                    else
                    {
                        Assert.IsFalse(missingRatio, "Precursor missing ratio when transitions have ratios");
                    }
                }
            }
            // 3 groups with less than 2 transition ratios
            Assert.AreEqual(3, ratioGroupMissingCount);

            // Remove the first light transition, checking that this removes the ratio
            // from the corresponding heavy transition, but not the entire group, until
            // after all light transitions have been removed.
            IdentityPath pathFirstPep = docResults.GetPathTo((int)SrmDocument.Level.Molecules, 0);
            var          nodePep      = (PeptideDocNode)docResults.FindNode(pathFirstPep);

            Assert.AreEqual(2, nodePep.Children.Count);
            var          nodeGroupLight = (TransitionGroupDocNode)nodePep.Children[0];
            IdentityPath pathGroupLight = new IdentityPath(pathFirstPep, nodeGroupLight.TransitionGroup);

            Assert.IsNull(nodeGroupLight.Results[0][0].Ratio, "Light group has ratio");
            var          nodeGroupHeavy = (TransitionGroupDocNode)nodePep.Children[1];
            IdentityPath pathGroupHeavy = new IdentityPath(pathFirstPep, nodeGroupHeavy.TransitionGroup);
            float?       ratioStart     = nodeGroupHeavy.Results[0][0].Ratio;

            Assert.IsTrue(ratioStart.HasValue, "No starting heavy group ratio");
            var expectedValues = new[] { 1.403414, 1.38697791, 1.34598482 };

            for (int i = 0; i < 3; i++)
            {
                var pathLight = docResults.GetPathTo((int)SrmDocument.Level.Transitions, 0);
                var pathHeavy = docResults.GetPathTo((int)SrmDocument.Level.Transitions, 3);
                TransitionDocNode nodeTran  = (TransitionDocNode)docResults.FindNode(pathHeavy);
                float?            ratioTran = nodeTran.Results[0][0].Ratio;
                Assert.IsTrue(ratioTran.HasValue, "Expected transition ratio not found");
                Assert.AreEqual(ratioTran.Value, expectedValues[i], 1.0e-5);
                docResults = (SrmDocument)docResults.RemoveChild(pathLight.Parent, docResults.FindNode(pathLight));
                nodeTran   = (TransitionDocNode)docResults.FindNode(pathHeavy);
                Assert.IsFalse(nodeTran.Results[0][0].Ratio.HasValue, "Unexpected transiton ratio found");
                Assert.AreEqual(pathGroupHeavy, pathHeavy.Parent, "Transition found outside expected group");
//                nodePep = (PeptideDocNode) docResults.FindNode(pathFirstPep);
                nodeGroupHeavy = (TransitionGroupDocNode)docResults.FindNode(pathGroupHeavy);
//                Assert.AreEqual(nodePep.Results[0][0].RatioToStandard, nodeGroupHeavy.Results[0][0].Ratio,
//                                "Peptide and group ratios not equal");
                if (i < 2)
                {
                    float?ratioGroup = nodeGroupHeavy.Results[0][0].Ratio;
                    Assert.IsTrue(ratioGroup.HasValue, "Group ratio removed with transition ratios");
                    Assert.AreEqual(ratioStart.Value, ratioGroup.Value, 0.1,
                                    "Unexpected group ratio change by more than 0.1");
                }
                else
                {
                    Assert.IsFalse(nodeGroupHeavy.Results[0][0].Ratio.HasValue,
                                   "Group ratio still present with no transition ratios");
                }
            }
            bool asSmallMolecules = (smallMoleculesTestMode != RefinementSettings.ConvertToSmallMoleculesMode.none);

            if (!asSmallMolecules) // GetTransitions() doesn't work the same way for small molecules - it only lists existing ones
            {
                bool      firstAdd           = true;
                var       nodeGroupLightOrig = (TransitionGroupDocNode)doc.FindNode(pathGroupLight);
                DocNode[] lightChildrenOrig  = nodeGroupLightOrig.Children.ToArray();
                foreach (var nodeTran in nodeGroupLightOrig.GetTransitions(docResults.Settings,
                                                                           null, nodeGroupLightOrig.PrecursorMz, null, null, null, false))
                {
                    var transition = nodeTran.Transition;
                    if (!firstAdd && lightChildrenOrig.IndexOf(node => Equals(node.Id, transition)) == -1)
                    {
                        continue;
                    }
                    // Add the first transition, and then the original transitions
                    docResults     = (SrmDocument)docResults.Add(pathGroupLight, nodeTran);
                    nodeGroupHeavy = (TransitionGroupDocNode)docResults.FindNode(pathGroupHeavy);
                    if (firstAdd)
                    {
                        Assert.IsNull(nodeGroupHeavy.Results[0][0].Ratio, "Unexpected heavy ratio found");
                    }
                    else
                    {
                        Assert.IsNotNull(nodeGroupHeavy.Results[0][0].Ratio,
                                         "Heavy ratio null after adding light children");
                    }
                    firstAdd = false;
                }
                Assert.AreEqual(ratioStart, nodeGroupHeavy.Results[0][0].Ratio);
            }
            // Release file handles
            docContainer.Release();
            testFilesDir.Dispose();
        }
Exemplo n.º 25
0
            public SrmDocument ChangePeak(SrmDocument doc, SrmTreeNode nodePepTree, TransitionGroupDocNode nodeTranGroup, string nameSet, MsDataFileUri filePath)
            {
                if ((_retentionTime ?? StartTime) == null)
                    return doc;

                var groupPath = new IdentityPath(nodePepTree.Path, nodeTranGroup.Id);

                doc = _retentionTime.HasValue
                    ? doc.ChangePeak(groupPath, nameSet, filePath, null, _retentionTime.Value, UserSet.TRUE)
                    : doc.ChangePeak(groupPath, nameSet, filePath, null, StartTime, EndTime, UserSet.TRUE, null, false);

                var activeTransitionGroup = (TransitionGroupDocNode) doc.FindNode(groupPath);
                if (activeTransitionGroup.RelativeRT != RelativeRT.Matching)
                    return doc;

                var activeChromInfo = SkylineWindow.FindChromInfo(doc, activeTransitionGroup, nameSet, filePath);
                var peptide = (PeptideDocNode) doc.FindNode(groupPath.Parent);
                // See if there are any other transition groups that should have their peak bounds set to the same value
                foreach (var tranGroup in peptide.TransitionGroups.Where(tranGroup => tranGroup.RelativeRT == RelativeRT.Matching))
                {
                    var otherGroupPath = new IdentityPath(groupPath.Parent, tranGroup.TransitionGroup);
                    if (Equals(groupPath, otherGroupPath) || SkylineWindow.FindChromInfo(doc, tranGroup, nameSet, filePath) == null)
                        continue;

                    doc = doc.ChangePeak(otherGroupPath, nameSet, filePath, null,
                        activeChromInfo.StartRetentionTime, activeChromInfo.EndRetentionTime, UserSet.TRUE, activeChromInfo.Identified, false);
                }
                return doc;
            }
Exemplo n.º 26
0
        public override void UpdateGraph(bool selectionChanged)
        {
            SrmDocument document         = GraphSummary.DocumentUIContainer.DocumentUI;
            var         results          = document.Settings.MeasuredResults;
            bool        resultsAvailable = results != null;

            Clear();
            if (!resultsAvailable)
            {
                Title.Text = Resources.RTReplicateGraphPane_UpdateGraph_No_results_available;
                EmptyGraph(document);
                return;
            }

            var selectedTreeNode = GraphSummary.StateProvider.SelectedNode as SrmTreeNode ??
                                   GraphSummary.StateProvider.SelectedNodes.OfType <SrmTreeNode>().FirstOrDefault();

            if (selectedTreeNode == null || document.FindNode(selectedTreeNode.Path) == null)
            {
                EmptyGraph(document);
                return;
            }

            Title.Text = null;

            DisplayTypeChrom displayType  = GraphChromatogram.GetDisplayType(document, selectedTreeNode);
            DocNode          selectedNode = selectedTreeNode.Model;
            IdentityPath     selectedPath = selectedTreeNode.Path;
            DocNode          parentNode   = selectedNode;
            IdentityPath     parentPath   = selectedTreeNode.Path;

            // If the selected tree node is a transition, then its siblings are displayed.
            if (selectedTreeNode is TransitionTreeNode)
            {
                if (displayType != DisplayTypeChrom.single)
                {
                    SrmTreeNode parentTreeNode = selectedTreeNode.SrmParent;
                    parentNode   = parentTreeNode.Model;
                    selectedPath = parentTreeNode.Path;
                }
            }
            // If the selected node is a peptide with one child, then show the children,
            // unless chromatogram display type is total
            else if (selectedTreeNode is PeptideTreeNode)
            {
                var children = ((DocNodeParent)selectedNode).Children;
                if (children.Count == 1 && displayType != DisplayTypeChrom.total)
                {
                    selectedNode = parentNode = children[0];
                    selectedPath = new IdentityPath(parentPath, children[0].Id);
                }
            }
            else if (!(selectedTreeNode is PeptideGroupTreeNode) && !(selectedTreeNode is TransitionGroupTreeNode))
            {
                Title.Text      = Resources.RTReplicateGraphPane_UpdateGraph_Select_a_peptide_to_see_the_retention_time_graph;
                CanShowRTLegend = false;
                return;
            }

            // If a precursor is going to be displayed with display type single
            if (parentNode is TransitionGroupDocNode && displayType == DisplayTypeChrom.single)
            {
                // If no optimization data, then show all the transitions
                if (!results.Chromatograms.Contains(chrom => chrom.OptimizationFunction != null))
                {
                    displayType = DisplayTypeChrom.all;
                }
            }
            var rtTransformOp = GraphSummary.StateProvider.GetRetentionTimeTransformOperation();
            var rtValue       = RTPeptideGraphPane.RTValue;

            GraphValues.ReplicateGroupOp replicateGroupOp;
            if (rtValue == RTPeptideValue.All)
            {
                replicateGroupOp = GraphValues.ReplicateGroupOp.FromCurrentSettings(document.Settings, GraphValues.AggregateOp.MEAN);
            }
            else
            {
                replicateGroupOp = GraphValues.ReplicateGroupOp.FromCurrentSettings(document.Settings);
            }
            var retentionTimeValue = new GraphValues.RetentionTimeTransform(rtValue, rtTransformOp, replicateGroupOp.AggregateOp);

            YAxis.Title.Text = retentionTimeValue.GetAxisTitle();

            var peptidePaths = GetSelectedPeptides().GetUniquePeptidePaths().ToList();

            // if PeptideGroupTreeNode is selected but has only one child isMultiSelect should still be true
            IsMultiSelect = peptidePaths.Count > 1 ||
                            (peptidePaths.Count == 1 &&
                             GraphSummary.StateProvider.SelectedNodes.FirstOrDefault() is PeptideGroupTreeNode);

            GraphData graphData = new RTGraphData(document,
                                                  IsMultiSelect
                ? peptidePaths
                : new[] { selectedPath }.AsEnumerable(), displayType, retentionTimeValue, replicateGroupOp);

            CanShowRTLegend = graphData.DocNodes.Count != 0;
            InitFromData(graphData);

            int    selectedReplicateIndex = SelectedIndex;
            double minRetentionTime = double.MaxValue;
            double maxRetentionTime = -double.MaxValue;
            int    iColor = 0, iCharge = -1;
            var    charge = Adduct.EMPTY;
            int    countLabelTypes        = document.Settings.PeptideSettings.Modifications.CountLabelTypes;
            int    colorOffset            = 0;
            var    transitionGroupDocNode = parentNode as TransitionGroupDocNode;

            if (transitionGroupDocNode != null && displayType == DisplayTypeChrom.products)
            {
                // If we are only displaying product ions, we want to use an offset in the colors array
                // so that we do not re-use colors that would be used for any precursor ions.
                colorOffset =
                    GraphChromatogram.GetDisplayTransitions(transitionGroupDocNode, DisplayTypeChrom.precursors).Count();
            }
            for (int i = 0; i < graphData.DocNodes.Count; i++)
            {
                var docNode        = graphData.DocNodes[i];
                var identityPath   = graphData.DocNodePaths[i];
                var pointPairLists = graphData.PointPairLists[i];
                int numSteps       = pointPairLists.Count / 2;
                for (int iStep = 0; iStep < pointPairLists.Count; iStep++)
                {
                    int   step          = iStep - numSteps;
                    var   pointPairList = pointPairLists[iStep];
                    Color color;
                    var   isSelected = false;
                    var   nodeGroup  = docNode as TransitionGroupDocNode;
                    if (IsMultiSelect)
                    {
                        var peptides = peptidePaths.Select(path => document.FindNode(path))
                                       .Cast <PeptideDocNode>().ToArray();
                        var peptideDocNode = peptides.FirstOrDefault(
                            peptide => 0 <= peptide.FindNodeIndex(docNode.Id));
                        if (peptideDocNode == null)
                        {
                            continue;
                        }
                        color = GraphSummary.StateProvider.GetPeptideGraphInfo(peptideDocNode).Color;
                        if (identityPath.Equals(selectedTreeNode.Path) && step == 0)
                        {
                            color      = ChromGraphItem.ColorSelected;
                            isSelected = true;
                        }
                    }
                    else if (parentNode is PeptideDocNode)
                    {
                        // Resharper code inspection v9.0 on TC gets this one wrong
                        // ReSharper disable ExpressionIsAlwaysNull
                        int iColorGroup = GetColorIndex(nodeGroup, countLabelTypes, ref charge, ref iCharge);
                        // ReSharper restore ExpressionIsAlwaysNull
                        color = COLORS_GROUPS[iColorGroup % COLORS_GROUPS.Count];
                    }
                    else if (displayType == DisplayTypeChrom.total)
                    {
                        color = COLORS_GROUPS[iColor % COLORS_GROUPS.Count];
                    }
                    else if (ReferenceEquals(docNode, selectedNode) && step == 0)
                    {
                        color      = ChromGraphItem.ColorSelected;
                        isSelected = true;
                    }
                    else
                    {
                        color = COLORS_TRANSITION[(iColor + colorOffset) % COLORS_TRANSITION.Count];
                    }
                    iColor++;

                    string label = graphData.DocNodeLabels[i];
                    if (step != 0)
                    {
                        label = string.Format(Resources.RTReplicateGraphPane_UpdateGraph_Step__0__, step);
                    }

                    CurveItem curveItem;
                    if (IsMultiSelect)
                    {
                        if (rtValue != RTPeptideValue.All)
                        {
                            curveItem = CreateLineItem(label, pointPairList, color);
                        }
                        else
                        {
                            curveItem = CreateMultiSelectBarItem(label, pointPairList, color);
                        }
                    }
                    else if (HiLowMiddleErrorBarItem.IsHiLoMiddleErrorList(pointPairList))
                    {
                        curveItem        = new HiLowMiddleErrorBarItem(label, pointPairList, color, Color.Black);
                        BarSettings.Type = BarType.Cluster;
                    }
                    else if (rtValue == RTPeptideValue.All)
                    {
                        curveItem        = new MeanErrorBarItem(label, pointPairList, color, Color.Black);
                        BarSettings.Type = BarType.Cluster;
                    }
                    else
                    {
                        curveItem = CreateLineItem(label, pointPairList, color);
                    }

                    if (curveItem != null)
                    {
                        curveItem.Tag = identityPath;

                        var barItem = curveItem as BarItem;
                        if (barItem != null)
                        {
                            barItem.Bar.Border.IsVisible = false;
                            barItem.Bar.Fill.Brush       = GetBrushForNode(docNode, color);
                            if (!isSelected)
                            {
                                barItem.SortedOverlayPriority = 1;
                            }
                        }
                        CurveList.Add(curveItem);

                        if (selectedReplicateIndex != -1 && selectedReplicateIndex < pointPairList.Count)
                        {
                            PointPair pointPair = pointPairList[selectedReplicateIndex];
                            if (!pointPair.IsInvalid)
                            {
                                minRetentionTime = Math.Min(minRetentionTime, pointPair.Z);
                                maxRetentionTime = Math.Max(maxRetentionTime, pointPair.Y);
                            }
                        }
                    }
                }
            }
            // Draw a box around the currently selected replicate
            if (ShowSelection && minRetentionTime != double.MaxValue)
            {
                AddSelection(selectedReplicateIndex, maxRetentionTime, minRetentionTime);
            }
            // Reset the scale when the parent node changes
            if (_parentNode == null || !ReferenceEquals(_parentNode.Id, parentNode.Id))
            {
                XAxis.Scale.MaxAuto = XAxis.Scale.MinAuto = true;
                YAxis.Scale.MaxAuto = YAxis.Scale.MinAuto = true;
            }
            _parentNode      = parentNode;
            Legend.IsVisible = !IsMultiSelect && Settings.Default.ShowRetentionTimesLegend;
            GraphSummary.GraphControl.Invalidate();
            AxisChange();
        }
Exemplo n.º 27
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));
        }
Exemplo n.º 28
0
        public override void UpdateGraph(bool checkData)
        {
            _dotpLabels = new GraphObjList();

            SrmDocument document         = GraphSummary.DocumentUIContainer.DocumentUI;
            var         results          = document.Settings.MeasuredResults;
            bool        resultsAvailable = results != null;

            Clear();

            if (!resultsAvailable)
            {
                Title.Text = Resources.AreaReplicateGraphPane_UpdateGraph_No_results_available;
                EmptyGraph(document);
                return;
            }

            var selectedTreeNode = GraphSummary.StateProvider.SelectedNode as SrmTreeNode;

            if (selectedTreeNode == null || document.FindNode(selectedTreeNode.Path) == null)
            {
                EmptyGraph(document);
                return;
            }

            BarSettings.Type = BarType;
            Title.Text       = null;

            DisplayTypeChrom displayType;

            if (Equals(PaneKey, PaneKey.PRECURSORS))
            {
                displayType = DisplayTypeChrom.precursors;
            }
            else if (Equals(PaneKey, PaneKey.PRODUCTS))
            {
                displayType = DisplayTypeChrom.products;
            }
            else
            {
                displayType = GraphChromatogram.GetDisplayType(document, selectedTreeNode);
            }

            DocNode      selectedNode        = selectedTreeNode.Model;
            DocNode      parentNode          = selectedNode;
            IdentityPath identityPath        = selectedTreeNode.Path;
            bool         optimizationPresent = results.Chromatograms.Contains(
                chrom => chrom.OptimizationFunction != null);

            // If the selected tree node is a transition, then its siblings are displayed.
            if (selectedTreeNode is TransitionTreeNode)
            {
                if (displayType == DisplayTypeChrom.single)
                {
                    BarSettings.Type = BarType.Cluster;
                }
                else
                {
                    SrmTreeNode parentTreeNode = selectedTreeNode.SrmParent;
                    parentNode   = parentTreeNode.Model;
                    identityPath = parentTreeNode.Path;
                }
            }
            // If the selected node is a peptide with one child, then show the children,
            // unless chromatogram display type is total
            else if (selectedTreeNode is PeptideTreeNode)
            {
                var children = ((PeptideDocNode)selectedNode).TransitionGroups
                               .Where(PaneKey.IncludesTransitionGroup)
                               .ToArray();
                if (children.Length == 1 && displayType != DisplayTypeChrom.total)
                {
                    selectedNode = parentNode = children[0];
                    identityPath = new IdentityPath(identityPath, parentNode.Id);
                }
                else
                {
                    BarSettings.Type = BarType.Cluster;
                }
            }
            else if (!(selectedTreeNode is TransitionGroupTreeNode))
            {
                Title.Text            = Resources.AreaReplicateGraphPane_UpdateGraph_Select_a_peptide_to_see_the_peak_area_graph;
                CanShowPeakAreaLegend = false;
                CanShowDotProduct     = false;
                return;
            }

            var parentGroupNode = parentNode as TransitionGroupDocNode;

            // If a precursor is going to be displayed with display type single
            if (parentGroupNode != null && displayType == DisplayTypeChrom.single)
            {
                // If no optimization data, then show all the transitions
                if (!optimizationPresent)
                {
                    displayType = DisplayTypeChrom.all;
                }
                // Otherwise, do not stack the bars
                else
                {
                    BarSettings.Type = BarType.Cluster;
                }
            }
            int ratioIndex   = AreaGraphData.RATIO_INDEX_NONE;
            var standardType = IsotopeLabelType.light;

            var areaView = AreaGraphController.AreaView;

            if (areaView == AreaNormalizeToView.area_ratio_view)
            {
                ratioIndex   = GraphSummary.RatioIndex;
                standardType = document.Settings.PeptideSettings.Modifications.RatioInternalStandardTypes[ratioIndex];
            }
            else if (areaView == AreaNormalizeToView.area_global_standard_view)
            {
                if (document.Settings.HasGlobalStandardArea)
                {
                    ratioIndex = ChromInfo.RATIO_INDEX_GLOBAL_STANDARDS;
                }
                else
                {
                    areaView = AreaNormalizeToView.none;
                }
            }

            // Sets normalizeData to optimization, maximum_stack, maximum, total, or none
            AreaNormalizeToData normalizeData;

            if (optimizationPresent && displayType == DisplayTypeChrom.single &&
                areaView == AreaNormalizeToView.area_percent_view)
            {
                normalizeData = AreaNormalizeToData.optimization;
            }
            else if (areaView == AreaNormalizeToView.area_maximum_view)
            {
                normalizeData = BarSettings.Type == BarType.Stack
                                    ? AreaNormalizeToData.maximum_stack
                                    : AreaNormalizeToData.maximum;
            }
            else if (BarSettings.Type == BarType.PercentStack)
            {
                normalizeData = AreaNormalizeToData.total;
            }
            else
            {
                normalizeData = AreaNormalizeToData.none;
            }

            // Calculate graph data points
            // IsExpectedVisible depends on ExpectedVisible
            ExpectedVisible = AreaExpectedValue.none;
            if (parentGroupNode != null &&
                displayType != DisplayTypeChrom.total &&
                areaView != AreaNormalizeToView.area_ratio_view &&
                !(optimizationPresent && displayType == DisplayTypeChrom.single))
            {
                var  displayTrans  = GraphChromatogram.GetDisplayTransitions(parentGroupNode, displayType).ToArray();
                bool isShowingMs   = displayTrans.Any(nodeTran => nodeTran.IsMs1);
                bool isShowingMsMs = displayTrans.Any(nodeTran => !nodeTran.IsMs1);
                bool isFullScanMs  = document.Settings.TransitionSettings.FullScan.IsEnabledMs && isShowingMs;
                if (isFullScanMs)
                {
                    if (!isShowingMsMs && parentGroupNode.HasIsotopeDist)
                    {
                        ExpectedVisible = AreaExpectedValue.isotope_dist;
                    }
                }
                else
                {
                    if (parentGroupNode.HasLibInfo)
                    {
                        ExpectedVisible = AreaExpectedValue.library;
                    }
                }
            }
            var expectedValue    = IsExpectedVisible ? ExpectedVisible : AreaExpectedValue.none;
            var replicateGroupOp = GraphValues.ReplicateGroupOp.FromCurrentSettings(document.Settings);
            var graphData        = new AreaGraphData(document,
                                                     parentNode,
                                                     displayType,
                                                     replicateGroupOp,
                                                     ratioIndex,
                                                     normalizeData,
                                                     expectedValue,
                                                     PaneKey);

            var aggregateOp = replicateGroupOp.AggregateOp;

            // Avoid stacking CVs
            if (aggregateOp.Cv || aggregateOp.CvDecimal)
            {
                BarSettings.Type = BarType.Cluster;
            }

            int countNodes = graphData.DocNodes.Count;

            if (countNodes == 0)
            {
                ExpectedVisible = AreaExpectedValue.none;
            }
            CanShowDotProduct = ExpectedVisible != AreaExpectedValue.none &&
                                areaView != AreaNormalizeToView.area_percent_view;
            CanShowPeakAreaLegend = countNodes != 0;

            InitFromData(graphData);

            // Add data to the graph
            int selectedReplicateIndex = SelectedIndex;

            if (IsExpectedVisible)
            {
                if (GraphSummary.ActiveLibrary)
                {
                    selectedReplicateIndex = 0;
                }
            }

            double maxArea = -double.MaxValue;
            double sumArea = 0;

            // An array to keep track of height of all bars to determine
            // where each dot product annotation (if showing) should be placed
            var sumAreas = new double[graphData.ReplicateGroups.Count];

            // If only one bar to show, then use cluster instead of stack bar type, since nothing to stack
            // Important for mean error bar checking below
            if (BarSettings.Type == BarType.Stack && countNodes == 1 && graphData.PointPairLists[0].Count == 1)
            {
                BarSettings.Type = BarType.Cluster;
            }

            int colorOffset = 0;

            if (parentGroupNode != null)
            {
                // We want the product ion colors to stay the same whether they are displayed:
                // 1. In a single pane with the precursor ions (Transitions -> All)
                // 2. In a separate pane of the split graph (Transitions -> All AND Transitions -> Split Graph)
                // 3. In a single pane by themselves (Transition -> Products)
                // We will use an offset in the colors array for cases 2 and 3 so that we do not reuse the precursor ion colors.
                var nodeDisplayType = GraphChromatogram.GetDisplayType(document, selectedTreeNode);
                if (displayType == DisplayTypeChrom.products &&
                    (nodeDisplayType != DisplayTypeChrom.single ||
                     (nodeDisplayType == DisplayTypeChrom.single && !optimizationPresent)))
                {
                    colorOffset =
                        GraphChromatogram.GetDisplayTransitions(parentGroupNode, DisplayTypeChrom.precursors).Count();
                }
            }

            int iColor = 0, iCharge = -1;
            int?charge          = null;
            int countLabelTypes = document.Settings.PeptideSettings.Modifications.CountLabelTypes;

            for (int i = 0; i < countNodes; i++)
            {
                var docNode        = graphData.DocNodes[i];
                var pointPairLists = graphData.PointPairLists[i];
                int numSteps       = pointPairLists.Count / 2;
                for (int iStep = 0; iStep < pointPairLists.Count; iStep++)
                {
                    int   step          = iStep - numSteps;
                    var   pointPairList = pointPairLists[iStep];
                    Color color;
                    var   nodeGroup = docNode as TransitionGroupDocNode;
                    if (parentNode is PeptideDocNode)
                    {
                        int iColorGroup = GetColorIndex(nodeGroup, countLabelTypes, ref charge, ref iCharge);
                        color = COLORS_GROUPS[iColorGroup % COLORS_GROUPS.Length];
                    }
                    else if (displayType == DisplayTypeChrom.total)
                    {
                        color = COLORS_GROUPS[iColor % COLORS_GROUPS.Length];
                    }
                    else if (docNode.Equals(selectedNode) && step == 0)
                    {
                        color = ChromGraphItem.ColorSelected;
                    }
                    else
                    {
                        color = COLORS_TRANSITION[(iColor + colorOffset) % COLORS_TRANSITION.Length];
                    }
                    iColor++;
                    // If showing ratios, do not add the standard type to the graph,
                    // since it will always be empty, but make sure the colors still
                    // correspond with the other graphs.
                    if (nodeGroup != null && ratioIndex >= 0)
                    {
                        var labelType = nodeGroup.TransitionGroup.LabelType;
                        if (ReferenceEquals(labelType, standardType))
                        {
                            continue;
                        }
                    }

                    string label = graphData.DocNodeLabels[i];
                    if (step != 0)
                    {
                        label = string.Format(Resources.AreaReplicateGraphPane_UpdateGraph_Step__0_, step);
                    }
                    BarItem curveItem;
                    // Only use a MeanErrorBarItem if bars are not going to be stacked.
                    // TODO(nicksh): AreaGraphData.NormalizeTo does not know about MeanErrorBarItem
                    if (BarSettings.Type != BarType.Stack && BarSettings.Type != BarType.PercentStack && normalizeData == AreaNormalizeToData.none)
                    {
                        curveItem = new MeanErrorBarItem(label, pointPairList, color, Color.Black);
                    }
                    else
                    {
                        curveItem = new BarItem(label, pointPairList, color);
                    }


                    if (0 <= selectedReplicateIndex && selectedReplicateIndex < pointPairList.Count)
                    {
                        PointPair pointPair = pointPairList[selectedReplicateIndex];
                        if (!pointPair.IsInvalid)
                        {
                            sumArea += pointPair.Y;
                            maxArea  = Math.Max(maxArea, pointPair.Y);
                        }
                    }

                    // Add area for this transition to each area entry
                    AddAreasToSums(pointPairList, sumAreas);

                    curveItem.Bar.Border.IsVisible = false;
                    curveItem.Bar.Fill.Brush       = new SolidBrush(color);
                    curveItem.Tag = new IdentityPath(identityPath, docNode.Id);
                    CurveList.Add(curveItem);
                }
            }

            ParentGroupNode = parentGroupNode;
            SumAreas        = sumAreas;

            // Draw a box around the currently selected replicate
            if (ShowSelection && maxArea > -double.MaxValue)
            {
                double yValue;
                switch (BarSettings.Type)
                {
                case BarType.Stack:
                    // The Math.Min(sumArea, .999) makes sure that if graph is in normalized view
                    // height of the selection rectangle does not exceed 1, so that top of the rectangle
                    // can be viewed when y-axis scale maximum is at 1
                    yValue = (areaView == AreaNormalizeToView.area_maximum_view ? Math.Min(sumArea, .999) : sumArea);
                    break;

                case BarType.PercentStack:
                    yValue = 99.99;
                    break;

                default:
                    // Scale the selection box to fit exactly the bar height
                    yValue = (areaView == AreaNormalizeToView.area_maximum_view ? Math.Min(maxArea, .999) : maxArea);
                    break;
                }
                GraphObjList.Add(new BoxObj(selectedReplicateIndex + .5, yValue, 0.99,
                                            yValue, Color.Black, Color.Empty)
                {
                    IsClippedToChartRect = true,
                });
            }
            // Reset the scale when the parent node changes
            bool resetAxes = (_parentNode == null || !ReferenceEquals(_parentNode.Id, parentNode.Id));

            _parentNode = parentNode;

            UpdateAxes(resetAxes, aggregateOp, normalizeData, areaView, standardType);
        }
Exemplo n.º 29
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);
            }
        }
Exemplo n.º 30
0
            protected virtual void InitData()
            {
                List <DocNode>               docNodes       = new List <DocNode>();
                List <IdentityPath>          docNodePaths   = new List <IdentityPath>();
                List <List <PointPairList> > pointPairLists = new List <List <PointPairList> >();
                List <String> docNodeLabels = new List <string>();

                ReplicateGroups = new ReplicateGroup[0];
                foreach (var docNodePath in _selectedDocNodePaths)
                {
                    var docNode          = _document.FindNode(docNodePath);
                    var replicateIndices = Enumerable.Range(0, _document.Settings.MeasuredResults.Chromatograms.Count);
                    // ReSharper disable CanBeReplacedWithTryCastAndCheckForNull
                    if (docNode is TransitionDocNode)
                    {
                        var nodeTran = (TransitionDocNode)docNode;
                        ReplicateGroups = GetReplicateGroups(replicateIndices).ToArray();
                        docNodes.Add(nodeTran);
                        docNodePaths.Add(docNodePath);
                        pointPairLists.Add(GetPointPairLists(null, nodeTran, _displayType));
                        docNodeLabels.Add(ChromGraphItem.GetTitle(nodeTran));
                    }
                    else if (docNode is TransitionGroupDocNode)
                    {
                        var nodeGroup = (TransitionGroupDocNode)docNode;
                        ReplicateGroups = GetReplicateGroups(replicateIndices).ToArray();
                        if (_displayType == DisplayTypeChrom.single || _displayType == DisplayTypeChrom.total)
                        {
                            docNodes.Add(nodeGroup);
                            docNodePaths.Add(docNodePath);
                            pointPairLists.Add(GetPointPairLists(nodeGroup, _displayType));
                            docNodeLabels.Add(ChromGraphItem.GetTitle(nodeGroup));
                        }
                        else
                        {
                            foreach (TransitionDocNode nodeTran in GraphChromatogram.GetDisplayTransitions(nodeGroup,
                                                                                                           _displayType))
                            {
                                docNodes.Add(nodeTran);
                                docNodePaths.Add(new IdentityPath(docNodePath, nodeTran.Id));
                                pointPairLists.Add(GetPointPairLists(nodeGroup, nodeTran, _displayType));
                                docNodeLabels.Add(ChromGraphItem.GetTitle(nodeTran));
                            }
                        }
                    }
                    else if (docNode is PeptideDocNode)
                    {
                        var nodePep = (PeptideDocNode)docNode;
                        ReplicateGroups = GetReplicateGroups(replicateIndices).ToArray();
                        var isMultiSelect = _selectedDocNodePaths.Count > 1 ||
                                            (_selectedDocNodePaths.Count == 1 && Program.MainWindow != null &&
                                             Program.MainWindow.SelectedNode is PeptideGroupTreeNode);
                        foreach (var tuple in GetPeptidePointPairLists(nodePep, isMultiSelect))
                        {
                            docNodes.Add(tuple.Node);
                            docNodePaths.Add(docNodePath);
                            pointPairLists.Add(tuple.PointPairList);
                            docNodeLabels.Add(tuple.DisplaySeq);
                        }
                    }
                }
                // ReSharper restore CanBeReplacedWithTryCastAndCheckForNull
                PointPairLists = pointPairLists;
                DocNodes       = docNodes;
                _docNodePaths  = ImmutableList.ValueOf(docNodePaths);
                DocNodeLabels  = docNodeLabels;

                var oldGroupNames    = ReplicateGroups.Select(g => g.GroupName).ToArray();
                var uniqueGroupNames = oldGroupNames.Distinct().ToArray();

                // Instert "All" groups and point pair lists in their correct positions
                InsertAllGroupsAndPointPairLists(uniqueGroupNames, docNodes.Count);

                // Collect all references to points that have a valid Y value
                var references = CollectValidPointRefs(uniqueGroupNames, oldGroupNames, docNodes.Count);

                // Merge groups if their replicate index is the same and each peptide only occurs in one of the files
                MergeGroups(uniqueGroupNames, references);

                // Remove groups that don't have any peptides in them
                RemoveEmptyGroups(docNodes.Count);
            }
Exemplo n.º 31
0
        private PeptideGroupDocNode GetSelectedPeptideGroupDocNode(SrmDocument document, IdentityPath selectedPath)
        {
            var to = selectedPath;
            if (to != null && to.Depth >= (int)SrmDocument.Level.MoleculeGroups)
                return (PeptideGroupDocNode) document.FindNode(to.GetIdentity((int) SrmDocument.Level.MoleculeGroups));

            PeptideGroupDocNode lastPeptideGroupDocuNode = null;
            foreach (PeptideGroupDocNode peptideGroupDocNode in document.MoleculeGroups)
            {
                lastPeptideGroupDocuNode = peptideGroupDocNode;
            }
            return lastPeptideGroupDocuNode;
        }
Exemplo n.º 32
0
        public static Annotations MergeAnnotations(SrmDocument document, IEnumerable <IdentityPath> selPaths,
                                                   out AnnotationDef.AnnotationTargetSet annotationTarget)
        {
            annotationTarget = AnnotationDef.AnnotationTargetSet.EMPTY;

            // If the nodes have matching text, colors, or annotations, then we should display these values
            // in the EditNodeDlg. Otherwise, we should not display any value for that variable.
            bool matchingText   = true;
            bool matchingColors = true;
            bool isFirstSelNode = true;
            bool allEmpty       = true;

            // These are the default values we want for the annotations, if the node(s) do not already have
            // annotations, or if the annotations do not match.
            string text       = null;
            int    colorIndex = -1;
            var    dictMatchingAnnotations = new Dictionary <string, string>();

            // Find what all nodes have in common as far as note, annotations, and color.
            foreach (IdentityPath selPath in selPaths)
            {
                if (Equals(selPath.Child, SequenceTree.NODE_INSERT_ID))
                {
                    continue;
                }

                var nodeDoc             = document.FindNode(selPath);
                var nodeAnnotations     = nodeDoc.Annotations;
                var dictNodeAnnotations = nodeAnnotations.ListAnnotations()
                                          .ToDictionary(nodeAnnotation => nodeAnnotation.Key,
                                                        nodeAnnotation => nodeAnnotation.Value);

                // If this is the first iteration, use the value for this node to start matching.
                if (isFirstSelNode)
                {
                    foreach (KeyValuePair <string, string> annotation in dictNodeAnnotations)
                    {
                        dictMatchingAnnotations.Add(annotation.Key, annotation.Value);
                    }
                    text           = nodeAnnotations.Note;
                    colorIndex     = nodeAnnotations.ColorIndex;
                    isFirstSelNode = false;
                }
                foreach (string key in dictMatchingAnnotations.Keys.ToArray())
                {
                    string value;
                    // If the list of annotations we are building for the dialog contains this key,
                    // check that the values are the same, otherwise the value for this annotation needs
                    // to be null for the dialog.
                    if (!dictNodeAnnotations.TryGetValue(key, out value) || !Equals(dictMatchingAnnotations[key], value))
                    {
                        dictMatchingAnnotations.Remove(key);
                    }
                }

                matchingText   = matchingText && nodeAnnotations.Note != null && Equals(text, nodeAnnotations.Note);
                matchingColors = matchingColors &&
                                 !nodeAnnotations.IsEmpty &&
                                 nodeAnnotations.ColorIndex != -1 &&
                                 Equals(colorIndex, nodeAnnotations.ColorIndex);

                allEmpty = allEmpty && nodeAnnotations.IsEmpty;

                // Update annotation target to include this type of node.
                annotationTarget = annotationTarget.Union(nodeDoc.AnnotationTarget);
            }
            if (!matchingText)
            {
                text = string.Empty;
            }
            if (allEmpty)
            {
                colorIndex = Settings.Default.AnnotationColor;
            }
            else if (!matchingColors)
            {
                colorIndex = -1;
            }
            return(new Annotations(text, dictMatchingAnnotations, colorIndex));
        }
Exemplo n.º 33
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));
        }
Exemplo n.º 34
0
        public override void UpdateGraph(bool checkData)
        {
            SrmDocument document         = GraphSummary.DocumentUIContainer.DocumentUI;
            var         results          = document.Settings.MeasuredResults;
            bool        resultsAvailable = results != null;

            Clear();
            if (!resultsAvailable)
            {
                Title.Text = Resources.RTReplicateGraphPane_UpdateGraph_No_results_available;
                EmptyGraph(document);
                return;
            }
            var selectedTreeNode = GraphSummary.StateProvider.SelectedNode as SrmTreeNode;

            if (selectedTreeNode == null || document.FindNode(selectedTreeNode.Path) == null)
            {
                EmptyGraph(document);
                return;
            }

            Title.Text = null;

            DisplayTypeChrom displayType  = GraphChromatogram.GetDisplayType(document, selectedTreeNode);
            DocNode          selectedNode = selectedTreeNode.Model;
            DocNode          parentNode   = selectedNode;
            IdentityPath     identityPath = selectedTreeNode.Path;

            // If the selected tree node is a transition, then its siblings are displayed.
            if (selectedTreeNode is TransitionTreeNode)
            {
                if (displayType != DisplayTypeChrom.single)
                {
                    SrmTreeNode parentTreeNode = selectedTreeNode.SrmParent;
                    parentNode   = parentTreeNode.Model;
                    identityPath = parentTreeNode.Path;
                }
            }
            // If the selected node is a peptide with one child, then show the children,
            // unless chromatogram display type is total
            else if (selectedTreeNode is PeptideTreeNode)
            {
                var children = ((DocNodeParent)selectedNode).Children;
                if (children.Count == 1 && displayType != DisplayTypeChrom.total)
                {
                    selectedNode = parentNode = children[0];
                    identityPath = new IdentityPath(identityPath, parentNode.Id);
                }
            }
            else if (!(selectedTreeNode is TransitionGroupTreeNode))
            {
                Title.Text      = Resources.RTReplicateGraphPane_UpdateGraph_Select_a_peptide_to_see_the_retention_time_graph;
                CanShowRTLegend = false;
                return;
            }

            // If a precursor is going to be displayed with display type single
            if (parentNode is TransitionGroupDocNode && displayType == DisplayTypeChrom.single)
            {
                // If no optimization data, then show all the transitions
                if (!results.Chromatograms.Contains(chrom => chrom.OptimizationFunction != null))
                {
                    displayType = DisplayTypeChrom.all;
                }
            }
            var rtTransformOp = GraphSummary.StateProvider.GetRetentionTimeTransformOperation();
            var rtValue       = RTPeptideGraphPane.RTValue;

            GraphValues.ReplicateGroupOp replicateGroupOp;
            if (rtValue == RTPeptideValue.All)
            {
                replicateGroupOp = GraphValues.ReplicateGroupOp.FromCurrentSettings(document.Settings, GraphValues.AggregateOp.MEAN);
            }
            else
            {
                replicateGroupOp = GraphValues.ReplicateGroupOp.FromCurrentSettings(document.Settings);
            }
            var retentionTimeValue = new GraphValues.RetentionTimeTransform(rtValue, rtTransformOp, replicateGroupOp.AggregateOp);

            YAxis.Title.Text = retentionTimeValue.GetAxisTitle();
            GraphData graphData = new RTGraphData(document, parentNode, displayType, retentionTimeValue, replicateGroupOp);

            CanShowRTLegend = graphData.DocNodes.Count != 0;
            InitFromData(graphData);

            int    selectedReplicateIndex = SelectedIndex;
            double minRetentionTime = double.MaxValue;
            double maxRetentionTime = -double.MaxValue;
            int    iColor = 0, iCharge = -1;
            int?   charge = null;
            int    countLabelTypes        = document.Settings.PeptideSettings.Modifications.CountLabelTypes;
            int    colorOffset            = 0;
            var    transitionGroupDocNode = parentNode as TransitionGroupDocNode;

            if (transitionGroupDocNode != null && displayType == DisplayTypeChrom.products)
            {
                // If we are only displaying product ions, we want to use an offset in the colors array
                // so that we do not re-use colors that would be used for any precursor ions.
                colorOffset =
                    GraphChromatogram.GetDisplayTransitions(transitionGroupDocNode, DisplayTypeChrom.precursors).Count();
            }
            for (int i = 0; i < graphData.DocNodes.Count; i++)
            {
                var docNode        = graphData.DocNodes[i];
                var pointPairLists = graphData.PointPairLists[i];
                int numSteps       = pointPairLists.Count / 2;
                for (int iStep = 0; iStep < pointPairLists.Count; iStep++)
                {
                    int   step          = iStep - numSteps;
                    var   pointPairList = pointPairLists[iStep];
                    Color color;
                    var   nodeGroup = docNode as TransitionGroupDocNode;
                    if (parentNode is PeptideDocNode)
                    {
                        // Resharper code inspection v9.0 on TC gets this one wrong
                        // ReSharper disable ExpressionIsAlwaysNull
                        int iColorGroup = GetColorIndex(nodeGroup, countLabelTypes, ref charge, ref iCharge);
                        // ReSharper restore ExpressionIsAlwaysNull
                        color = COLORS_GROUPS[iColorGroup % COLORS_GROUPS.Length];
                    }
                    else if (displayType == DisplayTypeChrom.total)
                    {
                        color = COLORS_GROUPS[iColor % COLORS_GROUPS.Length];
                    }
                    else if (docNode.Equals(selectedNode) && step == 0)
                    {
                        color = ChromGraphItem.ColorSelected;
                    }
                    else
                    {
                        color = COLORS_TRANSITION[(iColor + colorOffset) % COLORS_TRANSITION.Length];
                    }
                    iColor++;

                    string label = graphData.DocNodeLabels[i];
                    if (step != 0)
                    {
                        label = string.Format(Resources.RTReplicateGraphPane_UpdateGraph_Step__0__, step);
                    }
                    BarItem curveItem;
                    if (HiLowMiddleErrorBarItem.IsHiLoMiddleErrorList(pointPairList))
                    {
                        curveItem = new HiLowMiddleErrorBarItem(label, pointPairList, color, Color.Black);
                    }
                    else
                    {
                        curveItem = new MeanErrorBarItem(label, pointPairList, color, Color.Black);
                    }
                    if (selectedReplicateIndex != -1 && selectedReplicateIndex < pointPairList.Count)
                    {
                        PointPair pointPair = pointPairList[selectedReplicateIndex];
                        if (!pointPair.IsInvalid)
                        {
                            minRetentionTime = Math.Min(minRetentionTime, pointPair.Z);
                            maxRetentionTime = Math.Max(maxRetentionTime, pointPair.Y);
                        }
                    }
                    curveItem.Bar.Border.IsVisible = false;
                    curveItem.Bar.Fill.Brush       = new SolidBrush(color);
                    curveItem.Tag = new IdentityPath(identityPath, docNode.Id);
                    CurveList.Add(curveItem);
                }
            }
            // Draw a box around the currently selected replicate
            if (ShowSelection && minRetentionTime != double.MaxValue)
            {
                GraphObjList.Add(new BoxObj(selectedReplicateIndex + .5, maxRetentionTime, 1,
                                            maxRetentionTime - minRetentionTime, Color.Black, Color.Empty)
                {
                    IsClippedToChartRect = true,
                });
            }
            // Reset the scale when the parent node changes
            if (_parentNode == null || !ReferenceEquals(_parentNode.Id, parentNode.Id))
            {
                XAxis.Scale.MaxAuto = XAxis.Scale.MinAuto = true;
                YAxis.Scale.MaxAuto = YAxis.Scale.MinAuto = true;
            }
            _parentNode      = parentNode;
            Legend.IsVisible = Settings.Default.ShowRetentionTimesLegend;
            AxisChange();
        }
Exemplo n.º 35
0
 private List<DocNode> GetDocNodes(IdentityPath identityPath, SrmDocument document)
 {
     var result = new List<DocNode>();
     while (!identityPath.IsRoot)
     {
         result.Insert(0, document.FindNode(identityPath));
         identityPath = identityPath.Parent;
     }
     return result;
 }
Exemplo n.º 36
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);
            }
        }
Exemplo n.º 37
0
        private static PeptideGroupDocNode FindPeptideGroupDocNode(SrmDocument document, PeptideGroupDocNode nodePepGroup)
        {
            if (!nodePepGroup.IsPeptideList)
                return (PeptideGroupDocNode) document.FindNode(nodePepGroup.PeptideGroup);

            // Find peptide lists by name
            return FindPeptideGroupDocNode(document, nodePepGroup.Name);
        }
Exemplo n.º 38
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));
        }