protected override GraphData CreateGraphData(SrmDocument document, PeptideGroupDocNode selectedProtein, TransitionGroupDocNode selectedGroup, DisplayTypeChrom displayType)
 {
     int? result = null;
     if (RTLinearRegressionGraphPane.ShowReplicate == ReplicateDisplay.single)
         result = GraphSummary.ResultsIndex;
     return new AreaGraphData(document, selectedGroup, selectedProtein, result, displayType, PaneKey);
 }
        protected override GraphData CreateGraphData(SrmDocument document, PeptideGroupDocNode selectedProtein, TransitionGroupDocNode selectedGroup, DisplayTypeChrom displayType)
        {
            int? result = null;
            if (RTLinearRegressionGraphPane.ShowReplicate == ReplicateDisplay.single)
                result = GraphSummary.ResultsIndex;

            return new RTGraphData(document, selectedGroup, selectedProtein, result, displayType, GraphSummary.StateProvider.GetRetentionTimeTransformOperation());
        }
 public AreaGraphData(SrmDocument document,
     TransitionGroupDocNode selectedGroup,
     PeptideGroupDocNode selectedProtein,
     int? result,
     DisplayTypeChrom displayType,
     PaneKey paneKey)
     : base(document, selectedGroup, selectedProtein, result, displayType, null, paneKey)
 {
 }
        public PeptideGroupDocNode Merge(PeptideGroupDocNode nodePepGroup)
        {
            var childrenNew = new List<PeptideDocNode>(Children.Cast<PeptideDocNode>());
            // Remember where all the existing children are
            var dictPepIndex = new Dictionary<PeptideModKey, int>();
            for (int i = 0; i < childrenNew.Count; i++)
            {
                var key = childrenNew[i].Key;
                if (!dictPepIndex.ContainsKey(key))
                    dictPepIndex[key] = i;
            }
            // Add the new children to the end, or merge when the peptide is already present
            foreach (PeptideDocNode nodePep in nodePepGroup.Children)
            {
                int i;
                if (dictPepIndex.TryGetValue(nodePep.Key, out i))
                    childrenNew[i] = childrenNew[i].Merge(nodePep);
                else
                    childrenNew.Add(nodePep);

            }
            // If it is a FASTA sequence, make sure new peptides are sorted into place
            if (PeptideGroup is FastaSequence && childrenNew.Count > Children.Count)
                childrenNew.Sort(FastaSequence.ComparePeptides);
            return (PeptideGroupDocNode) ChangeChildrenChecked(childrenNew.Cast<DocNode>().ToArray());
        }
Exemple #5
0
 public static int CompareNames(PeptideGroupDocNode p1, PeptideGroupDocNode p2)
 {
     return(string.Compare(p1.Name, p2.Name, StringComparison.CurrentCulture));
 }
 public RTGraphData(SrmDocument document,
     TransitionGroupDocNode selectedGroup,
     PeptideGroupDocNode selectedProtein,
     int? result,
     DisplayTypeChrom displayType,
     GraphValues.IRetentionTimeTransformOp retentionTimeTransformOp
     )
     : base(document, selectedGroup, selectedProtein, result, displayType, retentionTimeTransformOp, PaneKey.DEFAULT)
 {
 }
Exemple #7
0
 public static int CompareAccessions(PeptideGroupDocNode p1, PeptideGroupDocNode p2)
 {
     return(string.Compare(p1.ProteinMetadata.Accession ?? String.Empty, p2.ProteinMetadata.Accession ?? String.Empty, StringComparison.InvariantCultureIgnoreCase));
 }
 private static int CompareNames(PeptideGroupDocNode group1, PeptideGroupDocNode group2)
 {
     return String.Compare(group1.Name, group2.Name, CultureInfo.CurrentCulture, CompareOptions.None);
 }
Exemple #9
0
        private SrmDocument AddProteins(SrmDocument document, ref IdentityPath selectedPath)
        {
            if (tabControl1.SelectedTab != tabPageProteinList)
                return document;

            var backgroundProteome = GetBackgroundProteome(document);
            for (int i = gridViewProteins.Rows.Count - 1; i >= 0; i--)
            {
                var row = gridViewProteins.Rows[i];
                var proteinName = Convert.ToString(row.Cells[colProteinName.Index].Value);
                if (String.IsNullOrEmpty(proteinName))
                {
                    continue;
                }
                var pastedMetadata = new ProteinMetadata(proteinName,
                    Convert.ToString(row.Cells[colProteinDescription.Index].Value),
                    NullForEmpty(Convert.ToString(row.Cells[colProteinPreferredName.Index].Value)),
                    NullForEmpty(Convert.ToString(row.Cells[colProteinAccession.Index].Value)),
                    NullForEmpty(Convert.ToString(row.Cells[colProteinGene.Index].Value)),
                    NullForEmpty(Convert.ToString(row.Cells[colProteinSpecies.Index].Value)));
                FastaSequence fastaSequence = null;
                if (!backgroundProteome.IsNone)
                {
                    ProteinMetadata protdbMetadata;
                    fastaSequence = backgroundProteome.GetFastaSequence(proteinName, out protdbMetadata);
                    // Fill in any gaps in pasted metadata with that in protdb
                    pastedMetadata = pastedMetadata.Merge(protdbMetadata);
                }
                // Strip any whitespace (tab, newline etc) In case it was copied out of a FASTA file
                var fastaSequenceString = new string(Convert.ToString(row.Cells[colProteinSequence.Index].Value).Where(c => !Char.IsWhiteSpace(c)).ToArray());
                if (!string.IsNullOrEmpty(fastaSequenceString))
                {
                        try
                        {
                            if (fastaSequence == null) // Didn't match anything in protdb
                            {
                                fastaSequence = new FastaSequence(pastedMetadata.Name, pastedMetadata.Description,
                                                                  new ProteinMetadata[0], fastaSequenceString);
                            }
                            else
                            {
                                if (fastaSequence.Sequence != fastaSequenceString)
                                {
                                    fastaSequence = new FastaSequence(pastedMetadata.Name, pastedMetadata.Description,
                                                                      fastaSequence.Alternatives, fastaSequenceString);
                                }
                            }
                        }
                        catch (Exception exception)
                        {
                            ShowProteinError(new PasteError
                                                 {
                                                     Line = i,
                                                     Column = colProteinDescription.Index,
                                                     Message = string.Format(Resources.PasteDlg_AddProteins_Invalid_protein_sequence__0__, exception.Message)
                                                 });
                            return null;
                        }
                }
                if (fastaSequence == null)
                {
                    ShowProteinError(
                        new PasteError
                        {
                                             Line = i,
                                Message = backgroundProteome.IsNone
                                        ? Resources.PasteDlg_AddProteins_Missing_protein_sequence
                                        : Resources.PasteDlg_AddProteins_This_protein_was_not_found_in_the_background_proteome_database
                        });
                    return null;
                }
                var description = pastedMetadata.Description;
                if (!string.IsNullOrEmpty(description) && description != fastaSequence.Description)
                {
                    fastaSequence = new FastaSequence(fastaSequence.Name, description, fastaSequence.Alternatives, fastaSequence.Sequence);
                }
                pastedMetadata = pastedMetadata.ChangeName(fastaSequence.Name).ChangeDescription(fastaSequence.Description);  // Make sure these agree
                var nodeGroupPep = new PeptideGroupDocNode(fastaSequence, pastedMetadata, new PeptideDocNode[0]);
                nodeGroupPep = nodeGroupPep.ChangeSettings(document.Settings, SrmSettingsDiff.ALL);
                var to = selectedPath;
                if (to == null || to.Depth < (int)SrmDocument.Level.MoleculeGroups)
                    document = (SrmDocument)document.Add(nodeGroupPep);
                else
                {
                    Identity toId = selectedPath.GetIdentity((int)SrmDocument.Level.MoleculeGroups);
                    document = (SrmDocument)document.Insert(toId, nodeGroupPep);
                }
                selectedPath = new IdentityPath(nodeGroupPep.Id);
            }
            return document;
        }
Exemple #10
0
 private static bool IsPeptideListDocNode(PeptideGroupDocNode peptideGroupDocNode)
 {
     return peptideGroupDocNode != null && peptideGroupDocNode.IsPeptideList;
 }
        public SrmDocument ConvertToSmallMolecules(SrmDocument document, 
            ConvertToSmallMoleculesMode mode = ConvertToSmallMoleculesMode.formulas,
            bool invertCharges = false,
            bool ignoreDecoys=false)
        {
            if (mode == ConvertToSmallMoleculesMode.none)
                return document;
            var newdoc = new SrmDocument(document.Settings);
            var note = new Annotations(TestingConvertedFromProteomic, null, 1); // Mark this as a testing node so we don't sort it

            newdoc = (SrmDocument)newdoc.ChangeIgnoreChangingChildren(true); // Retain copied results

            foreach (var peptideGroupDocNode in document.MoleculeGroups)
            {
                if (!peptideGroupDocNode.IsProteomic)
                {
                    newdoc = (SrmDocument)newdoc.Add(peptideGroupDocNode); // Already a small molecule
                }
                else
                {
                    var newPeptideGroup = new PeptideGroup();
                    var newPeptideGroupDocNode = new PeptideGroupDocNode(newPeptideGroup,
                        peptideGroupDocNode.Annotations.Merge(note), peptideGroupDocNode.Name,
                        peptideGroupDocNode.Description, new PeptideDocNode[0],
                        peptideGroupDocNode.AutoManageChildren);
                    foreach (var mol in peptideGroupDocNode.Molecules)
                    {
                        var peptideSequence = mol.Peptide.Sequence;
                        // Create a PeptideDocNode with the presumably baseline charge and label
                        var precursorCharge = (mol.TransitionGroups.Any() ? mol.TransitionGroups.First().TransitionGroup.PrecursorCharge : 0) * (invertCharges ? -1 : 1);
                        var isotopeLabelType = mol.TransitionGroups.Any() ? mol.TransitionGroups.First().TransitionGroup.LabelType : IsotopeLabelType.light;
                        var moleculeCustomIon = ConvertToSmallMolecule(mode, document, mol, precursorCharge, isotopeLabelType);
                        var precursorCustomIon = moleculeCustomIon;
                        var newPeptide = new Peptide(moleculeCustomIon);
                        var newPeptideDocNode = new PeptideDocNode(newPeptide, newdoc.Settings, null, null,
                            null, null, mol.ExplicitRetentionTime, note, mol.Results, new TransitionGroupDocNode[0],
                            mol.AutoManageChildren);

                        foreach (var transitionGroupDocNode in mol.TransitionGroups)
                        {
                            if (transitionGroupDocNode.IsDecoy)
                            {
                                if (ignoreDecoys)
                                    continue;
                                throw new Exception("There is no translation from decoy to small molecules"); // Not L10N
                            }

                            if (transitionGroupDocNode.TransitionGroup.PrecursorCharge != Math.Abs(precursorCharge) ||
                                !Equals(isotopeLabelType, transitionGroupDocNode.TransitionGroup.LabelType))
                            {
                                // Different charges or labels mean different ion formulas
                                precursorCharge = transitionGroupDocNode.TransitionGroup.PrecursorCharge * (invertCharges ? -1 : 1);
                                isotopeLabelType = transitionGroupDocNode.TransitionGroup.LabelType;
                                precursorCustomIon = ConvertToSmallMolecule(mode, document, mol, precursorCharge, isotopeLabelType);
                            }

                            var newTransitionGroup = new TransitionGroup(newPeptide, precursorCustomIon, precursorCharge, isotopeLabelType);
                            // Remove any library info, since for the moment at least small molecules don't support this and it won't roundtrip
                            var resultsNew = RemoveTransitionGroupChromInfoLibraryInfo(transitionGroupDocNode);
                            var newTransitionGroupDocNode = new TransitionGroupDocNode(newTransitionGroup,
                                transitionGroupDocNode.Annotations.Merge(note), document.Settings,
                                null, null, transitionGroupDocNode.ExplicitValues, resultsNew, null,
                                transitionGroupDocNode.AutoManageChildren);
                            var mzShift = invertCharges ? 2.0 * BioMassCalc.MassProton : 0;  // We removed hydrogen rather than added
                            Assume.IsTrue((Math.Abs(newTransitionGroupDocNode.PrecursorMz + mzShift - transitionGroupDocNode.PrecursorMz) - Math.Abs(transitionGroupDocNode.TransitionGroup.PrecursorCharge * BioMassCalc.MassElectron)) <= 1E-5);

                            foreach (var transition in transitionGroupDocNode.Transitions)
                            {
                                double mass = 0;
                                var transitionCharge = transition.Transition.Charge * (invertCharges ? -1 : 1);
                                var ionType = IonType.custom;
                                CustomIon transitionCustomIon;
                                double mzShiftTransition = 0;
                                if (transition.Transition.IonType == IonType.precursor)
                                {
                                    ionType = IonType.precursor;
                                    transitionCustomIon = new DocNodeCustomIon(precursorCustomIon.Formula,
                                        string.IsNullOrEmpty(precursorCustomIon.Formula) ? precursorCustomIon.MonoisotopicMass : (double?) null,
                                        string.IsNullOrEmpty(precursorCustomIon.Formula) ? precursorCustomIon.AverageMass : (double?) null,
                                        SmallMoleculeNameFromPeptide(peptideSequence, transitionCharge));
                                    mzShiftTransition = invertCharges ? 2.0 * BioMassCalc.MassProton : 0;  // We removed hydrogen rather than added
                                }
                                else if (transition.Transition.IonType == IonType.custom)
                                {
                                    transitionCustomIon = transition.Transition.CustomIon;
                                    mass = transitionCustomIon.MonoisotopicMass;
                                }
                                else
                                {
                                    // TODO - try to get fragment formula?
                                    mass = BioMassCalc.CalculateIonMassFromMz(transition.Mz, transition.Transition.Charge);
                                    transitionCustomIon = new DocNodeCustomIon(mass, mass,// We can't really get at mono vs average mass from m/z, but for test purposes this is fine
                                        transition.Transition.FragmentIonName);
                                }
                                if (mode == ConvertToSmallMoleculesMode.masses_and_names)
                                {
                                    // Discard the formula if we're testing the use of mass-with-names (for matching in ratio calcs) target specification
                                    transitionCustomIon = new DocNodeCustomIon(transitionCustomIon.MonoisotopicMass, transitionCustomIon.AverageMass,
                                        transition.Transition.FragmentIonName);
                                }
                                else if (mode == ConvertToSmallMoleculesMode.masses_only)
                                {
                                    // Discard the formula and name if we're testing the use of mass-only target specification
                                    transitionCustomIon = new DocNodeCustomIon(transitionCustomIon.MonoisotopicMass, transitionCustomIon.AverageMass);
                                }

                                var newTransition = new Transition(newTransitionGroup, ionType,
                                    null, transition.Transition.MassIndex, transition.Transition.Charge * (invertCharges ? -1 : 1), null,
                                    transitionCustomIon);
                                if (ionType == IonType.precursor)
                                {
                                    mass = document.Settings.GetFragmentMass(transitionGroupDocNode.TransitionGroup.LabelType, null, newTransition, newTransitionGroupDocNode.IsotopeDist);
                                }
                                var newTransitionDocNode = new TransitionDocNode(newTransition, transition.Annotations.Merge(note),
                                    null, mass, transition.IsotopeDistInfo, null,
                                    transition.Results);
                                Assume.IsTrue((Math.Abs(newTransitionDocNode.Mz + mzShiftTransition - transition.Mz) - Math.Abs(transitionGroupDocNode.TransitionGroup.PrecursorCharge * BioMassCalc.MassElectron)) <= 1E-5, String.Format("unexpected mz difference {0}-{1}={2}", newTransitionDocNode.Mz , transition.Mz, newTransitionDocNode.Mz - transition.Mz)); // Not L10N
                                newTransitionGroupDocNode =
                                    (TransitionGroupDocNode)newTransitionGroupDocNode.Add(newTransitionDocNode);
                            }
                            if (newPeptideDocNode != null)
                                newPeptideDocNode = (PeptideDocNode)newPeptideDocNode.Add(newTransitionGroupDocNode);
                        }
                        newPeptideGroupDocNode =
                            (PeptideGroupDocNode)newPeptideGroupDocNode.Add(newPeptideDocNode);
                    }
                    newdoc = (SrmDocument)newdoc.Add(newPeptideGroupDocNode);
                }
            }

            // No retention time prediction for small molecules (yet?)
            newdoc = newdoc.ChangeSettings(newdoc.Settings.ChangePeptideSettings(newdoc.Settings.PeptideSettings.ChangePrediction(
                        newdoc.Settings.PeptideSettings.Prediction.ChangeRetentionTime(null))));

            return newdoc;
        }
 private string GetAcceptProteinKey(PeptideGroupDocNode nodePepGroup)
 {
     switch (AcceptProteinType)
     {
             case ProteinSpecType.accession:
                 return nodePepGroup.ProteinMetadata.Accession;
             case ProteinSpecType.preferred:
                 return nodePepGroup.ProteinMetadata.PreferredName;
     }
     return nodePepGroup.Name;
 }
 public bool Equals(PeptideGroupDocNode obj)
 {
     if (ReferenceEquals(null, obj)) return false;
     if (ReferenceEquals(this, obj)) return true;
     return base.Equals(obj) && Equals(obj._proteinMetadata, _proteinMetadata);
 }
 public static int ComparePreferredNames(PeptideGroupDocNode p1, PeptideGroupDocNode p2)
 {
     return string.Compare(p1.ProteinMetadata.PreferredName ?? String.Empty, p2.ProteinMetadata.PreferredName ?? String.Empty, StringComparison.InvariantCultureIgnoreCase);
 }
 public static int CompareNames(PeptideGroupDocNode p1, PeptideGroupDocNode p2)
 {
     return string.Compare(p1.Name, p2.Name, StringComparison.CurrentCulture);
 }
 public static int CompareAccessions(PeptideGroupDocNode p1, PeptideGroupDocNode p2)
 {
     return string.Compare(p1.ProteinMetadata.Accession ?? String.Empty, p2.ProteinMetadata.Accession ?? String.Empty, StringComparison.InvariantCultureIgnoreCase);
 }
        private PeptideGroupDocNode ExcludePeptides(PeptideGroupDocNode peptideGroupDocNode)
        {
            HashSet<PeptideDocNode> excludedPeptides = new HashSet<PeptideDocNode>();
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                var row = dataGridView1.Rows[i];
                if (!(bool) row.Cells[PeptideIncludedColumn.Name].Value)
                {
                    excludedPeptides.Add((PeptideDocNode) row.Tag);
                }
            }
            List<PeptideDocNode> children = new List<PeptideDocNode>();
            foreach (PeptideDocNode child in peptideGroupDocNode.Children)
            {
                if (excludedPeptides.Contains(child))
                {
                    continue;
                }
                children.Add(child);
            }

            return new PeptideGroupDocNode(
                peptideGroupDocNode.PeptideGroup,
                peptideGroupDocNode.Annotations,
                peptideGroupDocNode.ProteinMetadata,
                children.ToArray(),
                false);
        }
        private static SrmDocument GenerateDecoysFunc(SrmDocument document, int numDecoys, bool multiCycle,
            Func<SequenceMods, SequenceMods> genDecoySequence)
        {
            // Loop through the existing tree in random order creating decoys
            var settings = document.Settings;
            var enzyme = settings.PeptideSettings.Enzyme;

            var decoyNodePepList = new List<PeptideDocNode>();
            var setDecoyKeys = new HashSet<PeptideModKey>();
            while (numDecoys > 0)
            {
                int startDecoys = numDecoys;
                foreach (var nodePep in document.Peptides.ToArray().RandomOrder())
                {
                    if (numDecoys == 0)
                        break;

                    // Decoys should not be based on standard peptides
                    if (nodePep.GlobalStandardType != null)
                        continue;
                    // If the non-terminal end of the peptide sequence is all a single character, skip this peptide,
                    // since it can't support decoy generation.
                    var sequence = nodePep.Peptide.Sequence;
                    if (genDecoySequence != null && sequence.Substring(0, sequence.Length - 1).Distinct().Count() == 1)
                        continue;

                    var seqMods = new SequenceMods(nodePep);
                    if (genDecoySequence != null)
                    {
                        seqMods = genDecoySequence(seqMods);
                    }
                    var peptide = nodePep.Peptide;
                    var decoyPeptide = new Peptide(null, seqMods.Sequence, null, null, enzyme.CountCleavagePoints(seqMods.Sequence), true);
                    if (seqMods.Mods != null)
                        seqMods.Mods = seqMods.Mods.ChangePeptide(decoyPeptide);

                    foreach (var comparableGroups in PeakFeatureEnumerator.ComparableGroups(nodePep))
                    {
                        var decoyNodeTranGroupList = GetDecoyGroups(nodePep, decoyPeptide, seqMods.Mods, comparableGroups, document,
                                                                    Equals(seqMods.Sequence, peptide.Sequence));
                        if (decoyNodeTranGroupList.Count == 0)
                            continue;

                        var nodePepNew = new PeptideDocNode(decoyPeptide, settings, seqMods.Mods,
                            null, nodePep.ExplicitRetentionTime, decoyNodeTranGroupList.ToArray(), false);

                        if (!Equals(nodePep.ModifiedSequence, nodePepNew.ModifiedSequence))
                        {
                            var sourceKey = new ModifiedSequenceMods(nodePep.ModifiedSequence, nodePep.ExplicitMods);
                            nodePepNew = nodePepNew.ChangeSourceKey(sourceKey);
                        }

                        // Avoid adding duplicate peptides
                        if (setDecoyKeys.Contains(nodePepNew.Key))
                            continue;
                        setDecoyKeys.Add(nodePepNew.Key);

                        decoyNodePepList.Add(nodePepNew);
                        numDecoys--;
                    }
                }
                // Stop if not multi-cycle or the number of decoys has not changed.
                if (!multiCycle || startDecoys == numDecoys)
                    break;
            }
            var decoyNodePepGroup = new PeptideGroupDocNode(new PeptideGroup(true), Annotations.EMPTY, PeptideGroup.DECOYS,
                                                            null, decoyNodePepList.ToArray(), false);
            decoyNodePepGroup = decoyNodePepGroup.ChangeSettings(document.Settings, SrmSettingsDiff.ALL);

            return (SrmDocument)document.Add(decoyNodePepGroup);
        }
        private static SrmDocument AddPeptidesToLibraryGroup(SrmDocument document,
            ICollection<PeptideMatch> listMatches,
            ILongWaitBroker broker,
            IdentityPath toPath,
            out IdentityPath selectedPath)
        {
            // Get starting progress values
            int startPercent = (broker != null ? broker.ProgressValue : 0);
            int processedPercent = 0;
            int processedCount = 0;
            int totalMatches = listMatches.Count;

            var listPeptides = new List<PeptideDocNode>();
            foreach (var match in listMatches)
            {
                // Show progress, if in a long wait
                if (broker != null)
                {
                    if (broker.IsCanceled)
                    {
                        selectedPath = null;
                        return document;
                    }
                    processedCount++;
                    int processPercentNow = processedCount * (100 - startPercent) / totalMatches;
                    if (processedPercent != processPercentNow)
                    {
                        processedPercent = processPercentNow;
                        broker.ProgressValue = startPercent + processedPercent;
                    }
                }

                listPeptides.Add(match.NodePep.ChangeSettings(document.Settings, SrmSettingsDiff.ALL));
            }

            bool hasVariable =
                listPeptides.Contains(nodePep => nodePep.HasExplicitMods && nodePep.ExplicitMods.IsVariableStaticMods);

            // Use existing group by this name, if present.
            var nodePepGroupNew = FindPeptideGroupDocNode(document, Resources.ViewLibraryPepMatching_AddPeptidesToLibraryGroup_Library_Peptides);
            if(nodePepGroupNew != null)
            {
                var newChildren = nodePepGroupNew.Children.ToList();
                newChildren.AddRange(listPeptides.ConvertAll(nodePep => (DocNode) nodePep));
                selectedPath = (listPeptides.Count == 1 ? new IdentityPath(nodePepGroupNew.Id, listPeptides[0].Id) : toPath);
                nodePepGroupNew = (PeptideGroupDocNode) nodePepGroupNew.ChangeChildren(newChildren);
                if (hasVariable)
                    nodePepGroupNew = (PeptideGroupDocNode) nodePepGroupNew.ChangeAutoManageChildren(false);
                return (SrmDocument) document.ReplaceChild(nodePepGroupNew);
            }
            else
            {
                nodePepGroupNew = new PeptideGroupDocNode(new PeptideGroup(),
                                                          Resources.ViewLibraryPepMatching_AddPeptidesToLibraryGroup_Library_Peptides,
                                                          string.Empty, listPeptides.ToArray());
                if (hasVariable)
                    nodePepGroupNew = (PeptideGroupDocNode) nodePepGroupNew.ChangeAutoManageChildren(false);
                IdentityPath nextAdd;
                document = document.AddPeptideGroups(new[] { nodePepGroupNew }, true,
                    toPath, out selectedPath, out nextAdd);
                selectedPath = new IdentityPath(selectedPath, nodePepGroupNew.Children[0].Id);
                return document;
            }
        }
        private PeptideGroupDocNode Refine(PeptideGroupDocNode nodePepGroup,
            SrmDocument document,
            ICollection<int> outlierIds,
            ICollection<RefinementIdentity> includedPeptides,
            ICollection<RefinementIdentity> repeatedPeptides,
            Dictionary<RefinementIdentity, List<int>> acceptedPeptides,
            SrmSettingsChangeMonitor progressMonitor)
        {
            var listPeptides = new List<PeptideDocNode>();
            int minPrecursors = MinPrecursorsPerPeptide ?? 0;
            foreach (PeptideDocNode nodePep in nodePepGroup.Children)
            {
                if (progressMonitor != null)
                    progressMonitor.ProcessMolecule(nodePep);

                if (outlierIds.Contains(nodePep.Id.GlobalIndex))
                    continue;

                // If there is a set of accepted peptides, and this is not one of them
                // then skip it.
                List<int> acceptedCharges = null;
                if (acceptedPeptides != null &&
                    !acceptedPeptides.TryGetValue(AcceptModified ? new RefinementIdentity(nodePep.RawTextId) : new RefinementIdentity(nodePep.RawUnmodifiedTextId), out acceptedCharges))
                {
                    continue;
                }

                int bestResultIndex = (UseBestResult ? nodePep.BestResult : -1);
                float? peakFoundRatio = nodePep.GetPeakCountRatio(bestResultIndex);
                if (!peakFoundRatio.HasValue)
                {
                    if (RemoveMissingResults)
                        continue;
                }
                else
                {
                    if (MinPeakFoundRatio.HasValue)
                    {
                        if (peakFoundRatio < MinPeakFoundRatio.Value)
                            continue;
                    }
                    if (MaxPeakFoundRatio.HasValue)
                    {
                        if (peakFoundRatio > MaxPeakFoundRatio.Value)
                            continue;
                    }
                }

                PeptideDocNode nodePepRefined = nodePep;
                if (AutoPickPrecursorsAll && nodePep.AutoManageChildren == AutoPickChildrenOff)
                {
                    nodePepRefined = (PeptideDocNode) nodePepRefined.ChangeAutoManageChildren(!AutoPickChildrenOff);
                    var settings = document.Settings;
                    if (!settings.TransitionSettings.Filter.AutoSelect && !AutoPickChildrenOff)
                        settings = settings.ChangeTransitionFilter(filter => filter.ChangeAutoSelect(!AutoPickChildrenOff));
                    nodePepRefined = nodePepRefined.ChangeSettings(settings,
                        new SrmSettingsDiff(false, false, true, false, AutoPickTransitionsAll, false));
                }

                nodePepRefined = Refine(nodePepRefined, document, bestResultIndex, acceptedCharges);
                // Always remove peptides if all precursors have been removed by refinement
                if (!ReferenceEquals(nodePep, nodePepRefined) && nodePepRefined.Children.Count == 0)
                    continue;
                if (nodePepRefined.Children.Count < minPrecursors)
                    continue;

                if (includedPeptides != null)
                {
                    var identity = nodePepRefined.Peptide.IsCustomIon
                        ? new RefinementIdentity(nodePep.Peptide.CustomIon)
                        : new RefinementIdentity(document.Settings.GetModifiedSequence(nodePepRefined));
                    // Skip peptides already added
                    if (includedPeptides.Contains(identity))
                    {
                        // Record repeated peptides for removing duplicate peptides later
                        if (repeatedPeptides != null)
                            repeatedPeptides.Add(identity);
                        continue;
                    }
                    // Record all peptides seen
                    includedPeptides.Add(identity);
                }

                listPeptides.Add(nodePepRefined);
            }

            if (MaxPepPeakRank.HasValue)
            {
                // Calculate the average peak area for each peptide
                int countPeps = listPeptides.Count;
                var listAreaIndexes = new List<PepAreaSortInfo>();
                var internalStandardTypes = document.Settings.PeptideSettings.Modifications.InternalStandardTypes;
                for (int i = 0; i < countPeps; i++)
                {
                    var nodePep = listPeptides[i];
                    // Only peptides with children can possible be ranked by area
                    // Those without should be removed by this operation
                    if (nodePep.Children.Count == 0)
                        continue;
                    int bestResultIndex = (UseBestResult ? nodePep.BestResult : -1);
                    var sortInfo = new PepAreaSortInfo(nodePep, internalStandardTypes, bestResultIndex, listAreaIndexes.Count);
                    listAreaIndexes.Add(sortInfo);
                }

                listAreaIndexes.Sort((p1, p2) => Comparer.Default.Compare(p2.Area, p1.Area));

                // Store area ranks
                var arrayAreaIndexes = new PepAreaSortInfo[listAreaIndexes.Count];
                int iRank = 1;
                foreach (var areaIndex in listAreaIndexes)
                {
                    areaIndex.Rank = iRank++;
                    arrayAreaIndexes[areaIndex.Index] = areaIndex;
                }

                // Add back all peptides with low enough rank.
                listPeptides.Clear();
                foreach (var areaIndex in arrayAreaIndexes)
                {
                    if (areaIndex.Area == 0 || areaIndex.Rank > MaxPepPeakRank.Value)
                        continue;
                    listPeptides.Add(areaIndex.Peptide);
                }
            }

            // Change the children, but only change auto-management, if the child
            // identities have changed, not if their contents changed.
            var childrenNew = listPeptides.ToArray();
            bool updateAutoManage = !PeptideGroupDocNode.AreEquivalentChildren(nodePepGroup.Children, childrenNew);
            return (PeptideGroupDocNode)nodePepGroup.ChangeChildrenChecked(childrenNew, updateAutoManage);
        }
        /// <summary>
        /// Adds all peptides which can be matched to a background proteome to the
        /// proteins in the background proteins, and returns a new document with those
        /// proteins and peptides added.
        /// </summary>
        /// <param name="document">The starting document</param>
        /// <param name="dictCopy">A dictionary of peptides to peptide matches. All added
        /// peptides are removed</param>
        /// <param name="broker">For reporting long wait status</param>
        /// <param name="toPath">Path to the location in the document to add new items</param>
        /// <param name="selectedPath">Path to item in the document that should be selected
        /// after this operation is complete</param>
        /// <returns>A new document with matching peptides and their proteins addded</returns>
        private SrmDocument AddProteomePeptides(SrmDocument document,
            Dictionary<PeptideSequenceModKey, PeptideMatch> dictCopy,
            ILongWaitBroker broker,
            IdentityPath toPath,
            out IdentityPath selectedPath)
        {
            // Build a list of new PeptideGroupDocNodes to add to the document.
            var dictPeptideGroupsNew = new Dictionary<string, PeptideGroupDocNode>();

            // Get starting progress values
            int startPercent = (broker != null ? broker.ProgressValue : 0);
            int processedPercent = 0;
            int processedCount = 0;
            int totalMatches = dictCopy.Count;

            // Just to make sure this is set
            selectedPath = toPath;

            foreach (PeptideMatch pepMatch in dictCopy.Values)
            {
                // Show progress, if in a long wait
                if (broker != null)
                {
                    if (broker.IsCanceled)
                    {
                        selectedPath = toPath;
                        return document;
                    }
                    // All peptides with protein get processed in this loop.  Peptides
                    // without proteins get added later.
                    if (pepMatch.Proteins != null)
                        processedCount++;
                    int processPercentNow = processedCount * (100 - startPercent) / totalMatches;
                    if (processedPercent != processPercentNow)
                    {
                        processedPercent = processPercentNow;
                        broker.ProgressValue = startPercent + processedPercent;
                    }
                }
                // Peptide should be added to the document,
                // unless the NoDuplicates radio was selected and the peptide has more than 1 protein associated with it.
                if (pepMatch.Proteins == null ||
                    (FilterMultipleProteinMatches == BackgroundProteome.DuplicateProteinsFilter.NoDuplicates && pepMatch.Proteins.Count > 1))
                    continue;

                foreach (ProteinInfo protein in pepMatch.Proteins)
                {
                    // Look for the protein in the document.
                    string name = protein.ProteinMetadata.Name;
                    var peptideGroupDocNode = FindPeptideGroupDocNode(document, name);
                    bool foundInDoc = peptideGroupDocNode != null;
                    bool foundInList = false;
                    if (!foundInDoc)
                    {
                        // If the protein is not already in the document,
                        // check to see if we have already created a PeptideGroupDocNode for it.
                        if (dictPeptideGroupsNew.TryGetValue(name, out peptideGroupDocNode))
                            foundInList = true;
                        // If not, create a new PeptideGroupDocNode.
                        else
                        {
                            List<ProteinMetadata> alternativeProteins = new List<ProteinMetadata>(protein.Alternatives);
                            peptideGroupDocNode = new PeptideGroupDocNode(
                                    new FastaSequence(name, protein.ProteinMetadata.Description, alternativeProteins, protein.Sequence),
                                    null, null, new PeptideDocNode[0]);
                        }
                    }
                    // Create a new peptide that matches this protein.
                    var fastaSequence = peptideGroupDocNode.PeptideGroup as FastaSequence;
                    var peptideSequence = pepMatch.NodePep.Peptide.Sequence;
                    // ReSharper disable PossibleNullReferenceException
                    var begin = fastaSequence.Sequence.IndexOf(peptideSequence, StringComparison.Ordinal);
                    // ReSharper restore PossibleNullReferenceException
                    // Create a new PeptideDocNode using this peptide.
                    var newPeptide = new Peptide(fastaSequence, peptideSequence, begin, begin + peptideSequence.Length,
                                                 Settings.PeptideSettings.Enzyme.CountCleavagePoints(peptideSequence));
                    // Make sure we keep the same children.
                    PeptideMatch match = pepMatch;
                    var newNodePep = ((PeptideDocNode) new PeptideDocNode(newPeptide, pepMatch.NodePep.ExplicitMods, pepMatch.NodePep.ExplicitRetentionTime)
                            .ChangeChildren(pepMatch.NodePep.Children.ToList().ConvertAll(nodeGroup =>
                                {
                                    // Create copies of the children in order to prevent transition groups with the same
                                    // global indices.
                                    var nodeTranGroup = (TransitionGroupDocNode) nodeGroup;
                                    if(match.Proteins != null && match.Proteins.Count() > 1)
                                    {
                                        nodeTranGroup = (TransitionGroupDocNode) nodeTranGroup.CopyId();
                                        nodeTranGroup = (TransitionGroupDocNode) nodeTranGroup.ChangeChildren(
                                            nodeTranGroup.Children.ToList().ConvertAll(nodeTran => nodeTran.CopyId()));
                                    }
                                    return (DocNode) nodeTranGroup;
                                })).ChangeAutoManageChildren(false)).ChangeSettings(document.Settings, SrmSettingsDiff.ALL);
                    // If this PeptideDocNode is already a child of the PeptideGroupDocNode,
                    // ignore it.
                    if (peptideGroupDocNode.Children.Contains(nodePep => Equals(((PeptideDocNode) nodePep).Key, newNodePep.Key)))
                    {
                        Console.WriteLine(Resources.ViewLibraryPepMatching_AddProteomePeptides_Skipping__0__already_present, newNodePep.Peptide.Sequence);
                        continue;
                    }
                    // Otherwise, add it to the list of children for the PeptideGroupNode.
                    var newChildren = peptideGroupDocNode.Children.Cast<PeptideDocNode>().ToList();
                    newChildren.Add(newNodePep);
                    newChildren.Sort(FastaSequence.ComparePeptides);

                    // Store modified proteins by global index in a HashSet for second pass.
                    var newPeptideGroupDocNode = peptideGroupDocNode.ChangeChildren(newChildren.Cast<DocNode>().ToArray())
                        .ChangeAutoManageChildren(false);
                    // If the protein was already in the document, replace with the new PeptideGroupDocNode.
                    if (foundInDoc)
                        document = (SrmDocument)document.ReplaceChild(newPeptideGroupDocNode);
                    // Otherwise, update the list of new PeptideGroupDocNodes to add.
                    else
                    {
                        if (foundInList)
                            dictPeptideGroupsNew.Remove(peptideGroupDocNode.Name);
                        dictPeptideGroupsNew.Add(peptideGroupDocNode.Name, (PeptideGroupDocNode) newPeptideGroupDocNode);
                    }
                    // If we are only adding a single node, select it.
                    if (PeptideMatches.Count == 1)
                        selectedPath = new IdentityPath(new[] {peptideGroupDocNode.Id, newNodePep.Peptide});
                    // If the user only wants to add the first protein found,
                    // we break the foreach loop after peptide has been added to its first protein.)
                    if (FilterMultipleProteinMatches == BackgroundProteome.DuplicateProteinsFilter.FirstOccurence)
                        break;
                }
            }

            if (dictPeptideGroupsNew.Count == 0)
            {
                return document;
            }

            // Sort the peptides.
            var nodePepGroupsSortedChildren = new List<PeptideGroupDocNode>();
            foreach(PeptideGroupDocNode nodePepGroup in dictPeptideGroupsNew.Values)
            {
                var newChildren = nodePepGroup.Children.ToList();
                // Have to cast all children to PeptideDocNodes in order to sort.
                var newChildrenNodePeps = newChildren.Cast<PeptideDocNode>().ToList();
                newChildrenNodePeps.Sort(FastaSequence.ComparePeptides);
                nodePepGroupsSortedChildren.Add((PeptideGroupDocNode)
                    nodePepGroup.ChangeChildren(newChildrenNodePeps.Cast<DocNode>().ToArray()));
            }
            // Sort the proteins.
            nodePepGroupsSortedChildren.Sort((node1, node2) => Comparer<string>.Default.Compare(node1.Name, node2.Name));
            IdentityPath selPathTemp = selectedPath, nextAdd;
            document = document.AddPeptideGroups(nodePepGroupsSortedChildren, false,
                toPath, out selectedPath, out nextAdd);
            selectedPath = PeptideMatches.Count == 1 ? selPathTemp : selectedPath;
            return document;
        }
Exemple #22
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);
        }
 public static string ProteinModalDisplayText(PeptideGroupDocNode node)
 {
     return ProteinModalDisplayText(node.ProteinMetadata, Settings.Default.ShowPeptidesDisplayMode);
 }
Exemple #24
0
        private SrmDocument AddPeptides(SrmDocument document, bool validating, ref IdentityPath selectedPath)
        {
            if (tabControl1.SelectedTab != tabPagePeptideList)
                return document;

            var matcher = new ModificationMatcher();
            var listPeptideSequences = ListPeptideSequences();
            if (listPeptideSequences == null)
                return null;
            try
            {
                matcher.CreateMatches(document.Settings, listPeptideSequences, Settings.Default.StaticModList,
                                      Settings.Default.HeavyModList);
            }
            catch (FormatException e)
            {
                MessageDlg.ShowException(this, e);
                ShowPeptideError(new PasteError
                                     {
                                         Column = colPeptideSequence.Index,
                                         Message = Resources.PasteDlg_AddPeptides_Unable_to_interpret_peptide_modifications
                                     });
                return null;
            }
            var strNameMatches = matcher.FoundMatches;
            if (!validating && !string.IsNullOrEmpty(strNameMatches))
            {
                string message = TextUtil.LineSeparate(Resources.PasteDlg_AddPeptides_Would_you_like_to_use_the_Unimod_definitions_for_the_following_modifications,
                                                        string.Empty, strNameMatches);
                if (MultiButtonMsgDlg.Show(this, message, Resources.PasteDlg_AddPeptides_OK) == DialogResult.Cancel)
                    return null;
            }
            var backgroundProteome = GetBackgroundProteome(document);
            // Insert last to first so that proteins get inserted on top of each other
            // in the order they are added. Peptide insertion into peptide lists needs
            // to be carefully tracked to insert them in the order they are listed in
            // the grid.
            int lastGroupGlobalIndex = 0, lastPeptideIndex = -1;
            for (int i = gridViewPeptides.Rows.Count - 1; i >= 0; i--)
            {
                PeptideGroupDocNode peptideGroupDocNode;
                var row = gridViewPeptides.Rows[i];
                var pepModSequence = Convert.ToString(row.Cells[colPeptideSequence.Index].Value);
                pepModSequence = FastaSequence.NormalizeNTerminalMod(pepModSequence);
                var proteinName = Convert.ToString(row.Cells[colPeptideProtein.Index].Value);
                if (string.IsNullOrEmpty(pepModSequence) && string.IsNullOrEmpty(proteinName))
                    continue;
                if (string.IsNullOrEmpty(proteinName))
                {
                    peptideGroupDocNode = GetSelectedPeptideGroupDocNode(document, selectedPath);
                    if (!IsPeptideListDocNode(peptideGroupDocNode))
                    {
                        peptideGroupDocNode = null;
                    }
                }
                else
                {
                    peptideGroupDocNode = FindPeptideGroupDocNode(document, proteinName);
                }
                if (peptideGroupDocNode == null)
                {
                    if (string.IsNullOrEmpty(proteinName))
                    {
                        peptideGroupDocNode = new PeptideGroupDocNode(new PeptideGroup(),
                                                                      document.GetPeptideGroupId(true), null,
                                                                      new PeptideDocNode[0]);
                    }
                    else
                    {
                        ProteinMetadata metadata = null;
                        PeptideGroup peptideGroup = backgroundProteome.IsNone ? new PeptideGroup()
                            : (backgroundProteome.GetFastaSequence(proteinName, out metadata) ??
                                                    new PeptideGroup());
                        if (metadata != null)
                            peptideGroupDocNode = new PeptideGroupDocNode(peptideGroup, metadata, new PeptideDocNode[0]);
                        else
                            peptideGroupDocNode = new PeptideGroupDocNode(peptideGroup, proteinName,
                                                                      peptideGroup.Description, new PeptideDocNode[0]);
                    }
                    // Add to the end, if no insert node
                    var to = selectedPath;
                    if (to == null || to.Depth < (int)SrmDocument.Level.MoleculeGroups)
                        document = (SrmDocument)document.Add(peptideGroupDocNode);
                    else
                    {
                        Identity toId = selectedPath.GetIdentity((int) SrmDocument.Level.MoleculeGroups);
                        document = (SrmDocument) document.Insert(toId, peptideGroupDocNode);
                    }
                    selectedPath = new IdentityPath(peptideGroupDocNode.Id);
                }
                var peptides = new List<PeptideDocNode>();
                foreach (PeptideDocNode peptideDocNode in peptideGroupDocNode.Children)
                {
                    peptides.Add(peptideDocNode);
                }

                var fastaSequence = peptideGroupDocNode.PeptideGroup as FastaSequence;
                PeptideDocNode nodePepNew;
                if (fastaSequence != null)
                {
                    // Attempt to create node for error checking.
                    nodePepNew = fastaSequence.CreateFullPeptideDocNode(document.Settings,
                                                                        FastaSequence.StripModifications(pepModSequence));
                    if (nodePepNew == null)
                    {
                        ShowPeptideError(new PasteError
                                             {
                                                 Column = colPeptideSequence.Index,
                                                 Line = i,
                                                 Message = Resources.PasteDlg_AddPeptides_This_peptide_sequence_was_not_found_in_the_protein_sequence
                                             });
                        return null;
                    }
                }
                // Create node using ModificationMatcher.
                nodePepNew = matcher.GetModifiedNode(pepModSequence, fastaSequence).ChangeSettings(document.Settings,
                                                                                                  SrmSettingsDiff.ALL);
                // Avoid adding an existing peptide a second time.
                if (!peptides.Contains(nodePep => Equals(nodePep.Key, nodePepNew.Key)))
                {
                    if (nodePepNew.Peptide.FastaSequence != null)
                    {
                        peptides.Add(nodePepNew);
                        peptides.Sort(FastaSequence.ComparePeptides);
                    }
                    else
                    {
                        int groupGlobalIndex = peptideGroupDocNode.PeptideGroup.GlobalIndex;
                        if (groupGlobalIndex == lastGroupGlobalIndex && lastPeptideIndex != -1)
                        {
                            peptides.Insert(lastPeptideIndex, nodePepNew);
                        }
                        else
                        {
                            lastPeptideIndex = peptides.Count;
                            peptides.Add(nodePepNew);
                        }
                        lastGroupGlobalIndex = groupGlobalIndex;
                    }
                    var newPeptideGroupDocNode = new PeptideGroupDocNode(peptideGroupDocNode.PeptideGroup, peptideGroupDocNode.Annotations, peptideGroupDocNode.Name, peptideGroupDocNode.Description, peptides.ToArray(), false);
                    document = (SrmDocument)document.ReplaceChild(newPeptideGroupDocNode);
                }
            }
            if (!validating && listPeptideSequences.Count > 0)
            {
                var pepModsNew = matcher.GetDocModifications(document);
                document = document.ChangeSettings(document.Settings.ChangePeptideModifications(mods => pepModsNew));
                document.Settings.UpdateDefaultModifications(false);
            }
            return document;
        }
            "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // Not L10N

        #endregion Fields

        #region Constructors

        // ReSharper restore SuggestBaseTypeForParameter
        // ReSharper disable SuggestBaseTypeForParameter
        public PeptideGroupTreeNode(SequenceTree tree, PeptideGroupDocNode group)
            : base(tree, group)
        {
        }
 protected abstract GraphData CreateGraphData(SrmDocument document, PeptideGroupDocNode selectedProtein,
     TransitionGroupDocNode selectedGroup, DisplayTypeChrom displayType);
            protected GraphData(SrmDocument document, TransitionGroupDocNode selectedGroup, PeptideGroupDocNode selectedProtein, 
                int? iResult, DisplayTypeChrom displayType, GraphValues.IRetentionTimeTransformOp retentionTimeTransformOp,
                PaneKey paneKey)
            {
                RetentionTimeTransformOp = retentionTimeTransformOp;
                // Determine the shortest possible unique ID for each peptide or molecule
                var sequences = new List<Tuple<string, bool>>();
                foreach (var nodePep in document.Molecules)
                    sequences.Add(new Tuple<string, bool>(nodePep.RawTextId, nodePep.IsProteomic));
                var uniquePrefixGenerator = new UniquePrefixGenerator(sequences, 3);

                int pointListCount = 0;
                var dictTypeToSet = new Dictionary<IsotopeLabelType, int>();

                bool onePointPerPeptide = PeptideOrder == SummaryPeptideOrder.document &&
                                          null != paneKey.IsotopeLabelType;
                // Figure out how many point lists to create
                bool displayTotals = (displayType == DisplayTypeChrom.total);
                if (displayTotals)
                {
                    foreach (var nodeGroup in document.MoleculeTransitionGroups)
                    {
                        if (!paneKey.IncludesTransitionGroup(nodeGroup))
                        {
                            continue;
                        }
                        IsotopeLabelType labelType = nodeGroup.TransitionGroup.LabelType;
                        if (!dictTypeToSet.ContainsKey(labelType))
                            dictTypeToSet.Add(labelType, pointListCount++);
                    }
                }
                else
                {
                    foreach (var nodeGroup in document.MoleculeTransitionGroups)
                    {
                        if (!paneKey.IncludesTransitionGroup(nodeGroup))
                        {
                            continue;
                        }
                        pointListCount = Math.Max(pointListCount, GraphChromatogram.GetDisplayTransitions(nodeGroup, displayType).Count());
                    }
                }

                // Build the list of points to show.
                var listPoints = new List<GraphPointData>();
                foreach (PeptideGroupDocNode nodeGroupPep in document.MoleculeGroups)
                {
                    if (AreaGraphController.AreaScope == AreaScope.protein)
                    {
                        if (!ReferenceEquals(nodeGroupPep, selectedProtein))
                            continue;
                    }
                    foreach (PeptideDocNode nodePep in nodeGroupPep.Children)
                    {
                        bool addBlankPoint = onePointPerPeptide &&
                                             !nodePep.TransitionGroups.Any(paneKey.IncludesTransitionGroup);
                        foreach (TransitionGroupDocNode nodeGroup in nodePep.Children)
                        {
                            var path = new IdentityPath(nodeGroupPep.PeptideGroup,
                                                        nodePep.Peptide, nodeGroup.TransitionGroup);
                            var graphPointData = new GraphPointData(nodePep, nodeGroup, path);
                            if (addBlankPoint || paneKey.IncludesTransitionGroup(nodeGroup))
                            {
                                listPoints.Add(graphPointData);
                            }
                            if (addBlankPoint)
                            {
                                break;
                            }
                        }
                    }
                }

                // Sort into correct order
                var peptideOrder = PeptideOrder;
                if (peptideOrder == SummaryPeptideOrder.time)
                {
                    if (displayTotals)
                        listPoints.Sort(ComparePeptideTimes);
                    else
                        listPoints.Sort(CompareGroupTimes);
                }
                else if (peptideOrder == SummaryPeptideOrder.area)
                {
                    listPoints.Sort(CompareGroupAreas);
                }

                // Init calculated values
                var pointPairLists = new List<PointPairList>();
                var labels = new List<string>();
                var xscalePaths = new List<IdentityPath>();
                double maxY = 0;
                double minY = double.MaxValue;
                int selectedIndex = -1;

                for (int i = 0; i < pointListCount; i++)
                    pointPairLists.Add(new PointPairList());

                // Calculate lists and values
                PeptideDocNode nodePepCurrent = null;
                int chargeCount = 0, chargeCurrent = 0;
                foreach (var dataPoint in listPoints)
                {
                    var nodePep = dataPoint.NodePep;
                    var nodeGroup = dataPoint.NodeGroup;
                    if (!ReferenceEquals(nodePep, nodePepCurrent))
                    {
                        nodePepCurrent = nodePep;

                        chargeCount = GetChargeCount(nodePep);
                        chargeCurrent = 0;
                    }

                    bool addLabel = !displayTotals;
                    if (displayTotals && nodeGroup.TransitionGroup.PrecursorCharge != chargeCurrent)
                    {
                        LevelPointPairLists(pointPairLists);
                        addLabel = true;
                    }
                    chargeCurrent = nodeGroup.TransitionGroup.PrecursorCharge;

                    var transitionGroup = nodeGroup.TransitionGroup;
                    int iGroup = labels.Count;

                    if (addLabel)
                    {
                        string label = uniquePrefixGenerator.GetUniquePrefix(nodePep.RawTextId, nodePep.IsProteomic) +
                                       (chargeCount > 1
                                            ? Transition.GetChargeIndicator(transitionGroup.PrecursorCharge)
                                            : string.Empty);
                        if (!displayTotals && null == paneKey.IsotopeLabelType)
                            label += transitionGroup.LabelTypeText;
                        if (peptideOrder == SummaryPeptideOrder.time)
                        {
                            label += string.Format(" ({0:F01})", displayTotals ? // Not L10N
                                                                                   dataPoint.TimePepCharge : dataPoint.TimeGroup);
                        }
                        labels.Add(label);
                        xscalePaths.Add(dataPoint.IdentityPath);
                    }

                    double groupMaxY = 0;
                    double groupMinY = double.MaxValue;

                    // ReSharper disable DoNotCallOverridableMethodsInConstructor
                    int? resultIndex = iResult.HasValue && iResult >= 0 ? iResult : null;
                    if (RTLinearRegressionGraphPane.ShowReplicate == ReplicateDisplay.best && nodePep != null)
                    {
                        resultIndex = null;
                        int iBest = nodePep.BestResult;
                        if (iBest !=-1)
                            resultIndex = iBest;
                    }
                    if (displayTotals)
                    {
                        var labelType = nodeGroup.TransitionGroup.LabelType;
                        if (dictTypeToSet.ContainsKey(labelType))
                        {
                            if (paneKey.IncludesTransitionGroup(nodeGroup))
                            {
                                pointPairLists[dictTypeToSet[labelType]].Add(CreatePointPair(iGroup, nodeGroup,
                                                                                             ref groupMaxY, ref groupMinY,
                                                                                             resultIndex));
                            }
                            else
                            {
                                pointPairLists[dictTypeToSet[labelType]].Add(PointPairMissing(iGroup));
                            }
                        }
                    }
                    else
                    {
                        if (paneKey.IncludesTransitionGroup(nodeGroup))
                        {
                            var nodeTrans = GraphChromatogram.GetDisplayTransitions(nodeGroup, displayType).ToArray();
                            for (int i = 0; i < pointListCount; i++)
                            {
                                var pointPairList = pointPairLists[i];
                                pointPairList.Add(i >= nodeTrans.Length
                                                      ? CreatePointPairMissing(iGroup)
                                                      : CreatePointPair(iGroup, nodeTrans[i], ref groupMaxY,
                                                                        ref groupMinY,
                                                                        resultIndex));
                            }
                        }
                        else
                        {
                            for (int i = 0; i < pointListCount; i++)
                            {
                                pointPairLists[i].Add(CreatePointPairMissing(iGroup));
                            }
                        }
                    }
                    // ReSharper restore DoNotCallOverridableMethodsInConstructor

                    // Save the selected index and its y extent
                    if (ReferenceEquals(selectedGroup, nodeGroup))
                    {
                        selectedIndex = labels.Count - 1;
                        SelectedMaxY = groupMaxY;
                        SelectedMinY = groupMinY;
                    }
                        // If multiple groups in the selection, make sure y extent is max of them
                    else if (selectedIndex == labels.Count - 1)
                    {
                        SelectedMaxY = Math.Max(groupMaxY, SelectedMaxY);
                        SelectedMinY = Math.Min(groupMinY, SelectedMinY);
                    }
                    maxY = Math.Max(maxY, groupMaxY);
                    minY = Math.Min(minY, groupMinY);
                }

                PointPairLists = pointPairLists;
                Labels = labels.ToArray();
                XScalePaths = xscalePaths.ToArray();
                SelectedIndex = selectedIndex;
                MaxY = maxY;
                if (minY != double.MaxValue)
                    MinY = minY;
            }
 private static bool ContainsCommonIrts(PeptideGroupDocNode protein)
 {
     return protein.Peptides.Select(pep => pep.ModifiedSequence).Intersect(COMMON_IRT_STANDARDS).Count() > CalibrateIrtDlg.MIN_STANDARD_PEPTIDES;
 }
Exemple #29
0
        public PeptideGroupDocNode ToDocNode()
        {
            PeptideGroupDocNode nodePepGroup;
            SrmSettingsDiff diff = SrmSettingsDiff.ALL;
            if (PeptideList)
            {
                if (_activePeptide != null)
                {
                    CompletePeptide(true);
                    diff = SrmSettingsDiff.PROPS;
                }
                nodePepGroup = new PeptideGroupDocNode(_activeFastaSeq ?? new PeptideGroup(_peptides.Any(p => p.IsDecoy)),
                    Name, Description, _peptides.ToArray());
            }
            else if (_customName) // name travels in the PeptideGroupDocNode instead of the FastaSequence
            {
                nodePepGroup = new PeptideGroupDocNode(
                    new FastaSequence(null, null, Alternatives, _sequence.ToString()),
                    Name, Description, new PeptideDocNode[0]);
            }
            else  // name travels with the FastaSequence
            {
                nodePepGroup = new PeptideGroupDocNode(
                    new FastaSequence(Name, Description, Alternatives, _sequence.ToString()),
                    null, null, new PeptideDocNode[0]);
            }
            // If this is a fasta file with no explicitly modified peptides, then apply
            // the usual peptide filtering rules.  Otherwise, keep all peptides the user input.
            if (!_autoManageChildren)
                nodePepGroup = (PeptideGroupDocNode) nodePepGroup.ChangeAutoManageChildren(false);
            // Materialize children, so that we have accurate accounting of
            // peptide and transition counts.
            nodePepGroup = nodePepGroup.ChangeSettings(_settings, diff);

            List<DocNode> newChildren = new List<DocNode>();
            foreach (PeptideDocNode nodePep in nodePepGroup.Children)
            {
                var nodePepAdd = nodePep;
                int charge;
                if (_charges.TryGetValue(nodePep.Id.GlobalIndex, out charge))
                {
                    var settingsCharge = _settings.ChangeTransitionFilter(f => f.ChangePrecursorCharges(new[] {charge}));
                    nodePepAdd = (PeptideDocNode) nodePep.ChangeSettings(settingsCharge, diff)
                                                         .ChangeAutoManageChildren(false);
                }
                newChildren.Add(nodePepAdd);
            }
            return (PeptideGroupDocNode) nodePepGroup.ChangeChildren(newChildren);
        }