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); }
public static SrmDocument ApplyPeak(SrmDocument doc, PeptideTreeNode nodePepTree, TransitionGroupDocNode nodeTranGroup, int resultsIndex, int? resultsFile, bool subsequent, ILongWaitBroker longWaitBroker) { nodeTranGroup = nodeTranGroup ?? PickTransitionGroup(doc, nodePepTree, resultsIndex); PeakMatchData referenceTarget; PeakMatchData[] referenceMatchData; DateTime? runTime; GetReferenceData(doc, nodePepTree.DocNode, nodeTranGroup, resultsIndex, resultsFile, out referenceTarget, out referenceMatchData, out runTime); var chromatograms = doc.Settings.MeasuredResults.Chromatograms; for (int i = 0; i < chromatograms.Count; i++) { var chromSet = chromatograms[i]; for (int j = 0; j < chromSet.MSDataFileInfos.Count; j++) { var fileInfo = chromSet.MSDataFileInfos[j]; if ((i == resultsIndex && (!resultsFile.HasValue || resultsFile.Value == j)) || (subsequent && runTime != null && fileInfo.RunStartTime < runTime)) { continue; } var bestMatch = GetPeakMatch(doc, chromSet, fileInfo, nodeTranGroup, referenceTarget, referenceMatchData); if (bestMatch != null) doc = bestMatch.ChangePeak(doc, nodePepTree, nodeTranGroup, chromSet.Name, fileInfo.FilePath); } longWaitBroker.SetProgressCheckCancel(i + 1, chromatograms.Count); } return doc; }
protected override bool IsMatch(TransitionGroupDocNode nodeGroup, TransitionDocNode nodeTran) { TransitionMatchInfo matchInfo; if (!_dictChargeToMatchInfo.TryGetValue(nodeGroup.TransitionGroup.PrecursorCharge, out matchInfo)) return true; // Unexpected missing charge state return !matchInfo.IsFullyMatched(nodeTran, nodeGroup); }
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()); }
/// <summary> /// Finds drift times by examining loaded results in a document. /// </summary> /// <param name="document">The document to be inspected</param> /// <param name="documentFilePath">Aids in locating the raw files</param> /// <param name="existing">If non-null, will be examined for any existing drift time measurements (which may be overwritten) </param> /// <param name="progressMonitor">Optional progress monitor for this potentially long operation</param> public DriftTimeFinder(SrmDocument document, string documentFilePath, DriftTimePredictor existing, IProgressMonitor progressMonitor) { _document = document; _documentFilePath = documentFilePath; _existing = existing; _currentDisplayedTransitionGroupDocNode = null; _progressMonitor = progressMonitor; }
public AreaGraphData(SrmDocument document, TransitionGroupDocNode selectedGroup, PeptideGroupDocNode selectedProtein, int? result, DisplayTypeChrom displayType, PaneKey paneKey) : base(document, selectedGroup, selectedProtein, result, displayType, null, paneKey) { }
private static ChromPeak GetLargestPeak(TransitionGroupDocNode nodeTranGroup, ChromatogramGroupInfo chromGroupInfo, int peakIndex, float mzMatchTolerance) { var largestPeak = ChromPeak.EMPTY; foreach (var peak in from transitionDocNode in nodeTranGroup.Transitions select chromGroupInfo.GetTransitionInfo((float) transitionDocNode.Mz, mzMatchTolerance) into chromInfo where chromInfo != null select chromInfo.GetPeak(peakIndex)) { if (peak.Height > largestPeak.Height) largestPeak = peak; } return largestPeak; }
public PickTransitionGroupTip(PeptideDocNode nodePep, TransitionGroupDocNode nodeGroup, SrmSettings settings) { _nodePep = nodePep; _nodeGroup = nodeGroup; _settings = settings; }
protected override bool IsMatch(TransitionGroupDocNode nodeGroup, TransitionDocNode nodeTran) { return(nodeTran != null && nodeTran.HasResults && nodeTran.Results.All(chromInfo => chromInfo.IsEmpty)); }
private static void ValidateDecoys(SrmDocument document, SrmDocument decoysDoc, bool modifiesSequences) { AssertEx.IsDocumentState(decoysDoc, 1, document.PeptideGroupCount + 1, document.PeptideCount * 2, document.PeptideTransitionGroupCount * 2, document.PeptideTransitionCount * 2); // Check for the existence of the Decoys peptide group and that everything under it is marked as a decoy. var nodePeptideGroupDecoy = decoysDoc.PeptideGroups.Single(nodePeptideGroup => nodePeptideGroup.IsDecoy); var dictModsToPep = document.Peptides.ToDictionary(nodePep => nodePep.ModifiedTarget); foreach (var nodePep in nodePeptideGroupDecoy.Peptides) { Assert.AreEqual(true, nodePep.IsDecoy); PeptideDocNode nodePepSource = null; if (!modifiesSequences) { Assert.IsNull(nodePep.SourceKey); } else { Assert.IsNotNull(nodePep.SourceKey, string.Format("Source key for {0}{1} is null", nodePep.ModifiedSequence, nodePep.IsDecoy ? " - decoy" : string.Empty)); Assert.IsTrue(FastaSequence.IsExSequence(nodePep.SourceKey.Sequence)); Assert.AreEqual(nodePep.SourceKey.ModifiedSequence, SequenceMassCalc.NormalizeModifiedSequence(nodePep.SourceKey.ModifiedSequence)); if (nodePep.HasExplicitMods) { Assert.IsNotNull(nodePep.SourceKey.ExplicitMods); } Assert.IsTrue(dictModsToPep.TryGetValue(nodePep.SourceModifiedTarget, out nodePepSource)); var sourceKey = new ModifiedSequenceMods(nodePepSource.Peptide.Sequence, nodePepSource.ExplicitMods); Assert.AreEqual(sourceKey.ExplicitMods, nodePep.SourceExplicitMods); } for (int i = 0; i < nodePep.TransitionGroupCount; i++) { var nodeGroup = nodePep.TransitionGroups.ElementAt(i); Assert.AreEqual(true, nodeGroup.IsDecoy); TransitionGroupDocNode nodeGroupSource = null; double shift = SequenceMassCalc.GetPeptideInterval(nodeGroup.TransitionGroup.DecoyMassShift); if (nodePepSource != null && nodeGroup.TransitionGroup.DecoyMassShift.HasValue) { nodeGroupSource = nodePepSource.TransitionGroups.ElementAt(i); Assert.AreEqual(nodeGroupSource.PrecursorMz + shift, nodeGroup.PrecursorMz, SequenceMassCalc.MassTolerance); } for (int j = 0; j < nodeGroup.TransitionCount; j++) { var nodeTran = nodeGroup.Transitions.ElementAt(j); Assert.IsTrue(nodeTran.IsDecoy); if (nodeTran.Transition.IsPrecursor()) { Assert.AreEqual(nodeGroup.TransitionGroup.DecoyMassShift, nodeTran.Transition.DecoyMassShift); if (nodeGroupSource != null) { Assert.AreEqual(nodeGroupSource.Transitions.ElementAt(j).Mz + shift, nodeTran.Mz, SequenceMassCalc.MassTolerance); } } } } } // Check that the resulting document persists correctly by passing the SrmDocument to AssertEx.IsSerializable(). AssertEx.Serializable(decoysDoc); }
public RemovePeakHandler(SkylineWindow skyline, IdentityPath groupPath, TransitionGroupDocNode nodeGroup, TransitionDocNode nodeTran) { _skyline = skyline; _groupPath = groupPath; _nodeGroup = nodeGroup; _nodeTran = nodeTran; }
protected override bool IsMatch(TransitionGroupDocNode nodeGroup, TransitionDocNode nodeTran) { return nodeTran != null && nodeTran.HasResults && nodeTran.Results.All(chromInfo => chromInfo == null); }
private PeptideDocNode CreateDocNodeFromSettings(string seq, PeptideDocNode nodePep, SrmSettingsDiff diff, out TransitionGroupDocNode nodeGroupMatched) { PeptideDocNode nodePepMod = nodePep.ChangeSettings(Settings, diff ?? SrmSettingsDiff.ALL, false); TransitionGroupDocNode nodeGroupMatchedFound; if (IsMatch(seq, nodePepMod, out nodeGroupMatchedFound)) { nodeGroupMatched = nodeGroupMatchedFound; return nodePepMod; } nodeGroupMatched = null; return null; }
public TransitionLossEquivalentKey EquivalentKey(TransitionGroupDocNode parent) { return(new TransitionLossEquivalentKey(parent, this, Losses)); }
public IEnumerable <TransitionDocNode> GetTransitions(SrmSettings settings, TransitionGroupDocNode groupDocNode, ExplicitMods mods, double precursorMz, IsotopeDistInfo isotopeDist, SpectrumHeaderInfo libInfo, IDictionary <double, LibraryRankedSpectrumInfo.RankedMI> transitionRanks, bool useFilter) { Assume.IsTrue(ReferenceEquals(groupDocNode.TransitionGroup, this)); // Get necessary mass calculators and masses var calcFilterPre = settings.GetPrecursorCalc(IsotopeLabelType.light, mods); var calcFilter = settings.GetFragmentCalc(IsotopeLabelType.light, mods); var calcPredict = settings.GetFragmentCalc(LabelType, mods); string sequence = Peptide.Sequence; // Save the true precursor m/z for TranstionSettings.Accept() now that all isotope types are // checked. This is more correct than just using the light precursor m/z for precursor window // exclusion. double precursorMzAccept = precursorMz; if (!ReferenceEquals(calcFilter, calcPredict)) { // Get the normal precursor m/z for filtering, so that light and heavy ion picks will match. precursorMz = IsCustomIon ? BioMassCalc.CalculateIonMz(calcFilterPre.GetPrecursorMass(groupDocNode.CustomIon), groupDocNode.TransitionGroup.PrecursorCharge) : SequenceMassCalc.GetMZ(calcFilterPre.GetPrecursorMass(sequence), groupDocNode.TransitionGroup.PrecursorCharge); } if (!IsAvoidMismatchedIsotopeTransitions) { precursorMzAccept = precursorMz; } var tranSettings = settings.TransitionSettings; var filter = tranSettings.Filter; var charges = filter.ProductCharges; var startFinder = filter.FragmentRangeFirst; var endFinder = filter.FragmentRangeLast; double precursorMzWindow = filter.PrecursorMzWindow; var types = filter.IonTypes; MassType massType = tranSettings.Prediction.FragmentMassType; int minMz = tranSettings.Instrument.GetMinMz(precursorMzAccept); int maxMz = tranSettings.Instrument.MaxMz; var pepMods = settings.PeptideSettings.Modifications; var potentialLosses = CalcPotentialLosses(sequence, pepMods, mods, massType); // A start m/z will need to be calculated if the start fragment // finder uses m/z and their are losses to consider. If the filter // is set to only consider fragments with m/z greater than the // precursor, the code below needs to also prevent loss fragments // from being under that m/z. double startMz = 0; // Get library settings var pick = tranSettings.Libraries.Pick; if (!useFilter) { pick = TransitionLibraryPick.all; var listAll = Transition.ALL_CHARGES.ToList(); listAll.AddRange(charges.Where(c => !Transition.ALL_CHARGES.Contains(c))); listAll.Sort(); charges = listAll.ToArray(); types = Transition.ALL_TYPES; } // If there are no libraries or no library information, then // picking cannot use library information else if (!settings.PeptideSettings.Libraries.HasLibraries || libInfo == null) { pick = TransitionLibraryPick.none; } // If filtering without library picking if (potentialLosses != null) { if (pick == TransitionLibraryPick.none) { // Only include loss combinations where all losses are included always potentialLosses = potentialLosses.Where(losses => losses.All(loss => loss.TransitionLoss.Loss.Inclusion == LossInclusion.Always)).ToArray(); } else if (useFilter) { // Exclude all losses which should never be included by default potentialLosses = potentialLosses.Where(losses => losses.All(loss => loss.TransitionLoss.Loss.Inclusion != LossInclusion.Never)).ToArray(); } if (!potentialLosses.Any()) { potentialLosses = null; } } // Return precursor ions if (!useFilter || types.Contains(IonType.precursor)) { bool libraryFilter = (pick == TransitionLibraryPick.all || pick == TransitionLibraryPick.filter); foreach (var nodeTran in GetPrecursorTransitions(settings, mods, calcFilterPre, calcPredict, precursorMz, isotopeDist, potentialLosses, transitionRanks, libraryFilter, useFilter)) { if (minMz <= nodeTran.Mz && nodeTran.Mz <= maxMz) { yield return(nodeTran); } } } // Return special ions from settings, if this is a peptide if (!IsCustomIon) { // This is a peptide, but it may have custom transitions (reporter ions), check those foreach (var measuredIon in tranSettings.Filter.MeasuredIons.Where(m => m.IsCustom)) { if (useFilter && measuredIon.IsOptional) { continue; } var tran = new Transition(this, measuredIon.Charge, null, measuredIon.CustomIon); double mass = settings.GetFragmentMass(IsotopeLabelType.light, null, tran, null); var nodeTran = new TransitionDocNode(tran, null, mass, null, null); if (minMz <= nodeTran.Mz && nodeTran.Mz <= maxMz) { yield return(nodeTran); } } } // For small molecules we can't generate new nodes, so just mz filter those we have foreach (var nodeTran in groupDocNode.Transitions.Where(tran => tran.Transition.IsNonPrecursorNonReporterCustomIon())) { if (minMz <= nodeTran.Mz && nodeTran.Mz <= maxMz) { yield return(nodeTran); } } if (sequence == null) // Completely custom { yield break; } // If picking relies on library information if (useFilter && pick != TransitionLibraryPick.none) { // If it is not yet loaded, or nothing got ranked, return an empty enumeration if (!settings.PeptideSettings.Libraries.IsLoaded || (transitionRanks != null && transitionRanks.Count == 0)) { yield break; } } double[,] massesPredict = calcPredict.GetFragmentIonMasses(sequence); int len = massesPredict.GetLength(1); if (len == 0) { yield break; } double[,] massesFilter = massesPredict; if (!ReferenceEquals(calcFilter, calcPredict)) { // Get the normal m/z values for filtering, so that light and heavy // ion picks will match. massesFilter = calcFilter.GetFragmentIonMasses(sequence); } // Get types other than this to make sure matches are possible for all types var listOtherTypes = new List <Tuple <TransitionGroupDocNode, IFragmentMassCalc> >(); foreach (var labelType in settings.PeptideSettings.Modifications.GetModificationTypes()) { if (Equals(labelType, LabelType)) { continue; } var calc = settings.GetFragmentCalc(labelType, mods); if (calc == null) { continue; } var tranGroupOther = new TransitionGroup(Peptide, PrecursorCharge, labelType, false, DecoyMassShift); var nodeGroupOther = new TransitionGroupDocNode(tranGroupOther, Annotations.EMPTY, settings, mods, libInfo, ExplicitTransitionGroupValues.EMPTY, null, new TransitionDocNode[0], false); listOtherTypes.Add(new Tuple <TransitionGroupDocNode, IFragmentMassCalc>(nodeGroupOther, calc)); } // Loop over potential product ions picking transitions foreach (IonType type in types) { // Precursor type is handled above. if (type == IonType.precursor) { continue; } foreach (int charge in charges) { // Precursor charge can never be lower than product ion charge. if (Math.Abs(PrecursorCharge) < Math.Abs(charge)) { continue; } int start = 0, end = 0; if (pick != TransitionLibraryPick.all) { start = startFinder.FindStartFragment(massesFilter, type, charge, precursorMz, precursorMzWindow, out startMz); end = endFinder.FindEndFragment(type, start, len); if (Transition.IsCTerminal(type)) { Helpers.Swap(ref start, ref end); } } for (int i = 0; i < len; i++) { // Get the predicted m/z that would be used in the transition double massH = massesPredict[(int)type, i]; foreach (var losses in CalcTransitionLosses(type, i, massType, potentialLosses)) { double ionMz = SequenceMassCalc.GetMZ(Transition.CalcMass(massH, losses), charge); // Make sure the fragment m/z value falls within the valid instrument range. // CONSIDER: This means that a heavy transition might excede the instrument // range where a light one is accepted, leading to a disparity // between heavy and light transtions picked. if (minMz > ionMz || ionMz > maxMz) { continue; } TransitionDocNode nodeTranReturn = null; bool accept = true; if (pick == TransitionLibraryPick.all || pick == TransitionLibraryPick.all_plus) { if (!useFilter) { nodeTranReturn = CreateTransitionNode(type, i, charge, massH, losses, transitionRanks); accept = false; } else { if (IsMatched(transitionRanks, ionMz, type, charge, losses)) { nodeTranReturn = CreateTransitionNode(type, i, charge, massH, losses, transitionRanks); accept = false; } // If allowing library or filter, check the filter to decide whether to accept else if (pick == TransitionLibraryPick.all_plus && tranSettings.Accept(sequence, precursorMzAccept, type, i, ionMz, start, end, startMz)) { nodeTranReturn = CreateTransitionNode(type, i, charge, massH, losses, transitionRanks); } } } else if (tranSettings.Accept(sequence, precursorMzAccept, type, i, ionMz, start, end, startMz)) { if (pick == TransitionLibraryPick.none) { nodeTranReturn = CreateTransitionNode(type, i, charge, massH, losses, transitionRanks); } else { if (IsMatched(transitionRanks, ionMz, type, charge, losses)) { nodeTranReturn = CreateTransitionNode(type, i, charge, massH, losses, transitionRanks); } } } if (nodeTranReturn != null) { if (IsAvoidMismatchedIsotopeTransitions && !OtherLabelTypesAllowed(settings, minMz, maxMz, start, end, startMz, accept, groupDocNode, nodeTranReturn, listOtherTypes)) { continue; } Assume.IsTrue(minMz <= nodeTranReturn.Mz && nodeTranReturn.Mz <= maxMz); yield return(nodeTranReturn); } } } } } }
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); }
private void ExportGroupNode(PeptideDocNode peptideNode, TransitionGroupDocNode groupNode, ChromatogramSet chromatograms, ICollection <string> filesToExport, ICollection <ChromSource> chromSources, TextWriter writer, CultureInfo cultureInfo) { string peptideModifiedSequence = _settings.GetDisplayName(peptideNode); var precursorCharge = groupNode.TransitionGroup.PrecursorAdduct; string labelType = groupNode.TransitionGroup.LabelType.Name; var filesInChrom = chromatograms.MSDataFilePaths.Select(path => path.GetFileName()).ToList(); // Don't load the chromatogram group if none of its files are being exported if (!filesInChrom.Where(filesToExport.Contains).Any()) { return; } ChromatogramGroupInfo[] arrayChromInfo; if (!_measuredResults.TryLoadChromatogram(chromatograms, peptideNode, groupNode, _matchTolerance, true, out arrayChromInfo)) { // TODO: Determine if this is a real error or just a missing node for this file // If the former throw an exception, if the latter continue return; } if (arrayChromInfo.Length != chromatograms.FileCount) { throw new InvalidDataException(string.Format(Resources.ChromatogramExporter_ExportGroupNode_One_or_more_missing_chromatograms_at_charge_state__0__of__1_, precursorCharge, peptideModifiedSequence)); } foreach (var chromGroupInfo in arrayChromInfo) { string fileName = chromGroupInfo.FilePath.GetFileName(); // Skip the files that have not been selected for export if (!filesToExport.Contains(fileName)) { continue; } foreach (var nodeTran in groupNode.Transitions) { // TODO: Check a source attribute on the transition chrom info bool isMs1 = nodeTran.Transition.IsPrecursor() && !nodeTran.HasLoss; if (isMs1 && !chromSources.Contains(ChromSource.ms1)) { continue; } if (!isMs1 && !chromSources.Contains(ChromSource.fragment)) { continue; } int productCharge = nodeTran.Transition.Charge; float productMz = (float)nodeTran.Mz; var chromInfo = chromGroupInfo.GetTransitionInfo(nodeTran.Mz, _matchTolerance); // Sometimes a transition in the transition group does not have results for a particular file // If this happens just skip it for that file if (chromInfo == null) { continue; } IList <float> times = chromInfo.Times; IList <float> intensities = chromInfo.Intensities; if (times.Count != intensities.Count || intensities.Count == 0) { throw new InvalidDataException(string.Format(Resources.ChromatogramExporter_Export_Bad_chromatogram_data_for_charge__0__state_of_peptide__1_, precursorCharge, peptideModifiedSequence)); } float tic = CalculateTic(times, intensities); string[] fieldArray = { fileName, peptideModifiedSequence, System.Convert.ToString(precursorCharge, cultureInfo), System.Convert.ToString(productMz, cultureInfo), nodeTran.GetFragmentIonName(CultureInfo.InvariantCulture), System.Convert.ToString(productCharge, cultureInfo), labelType, System.Convert.ToString(tic, cultureInfo) }; FormatChromLine(writer, fieldArray, times, intensities, cultureInfo); } } }
private readonly string _customIonEquivalenceTestText; // For use with small molecules public TransitionEquivalentKey(TransitionGroupDocNode parent, TransitionDocNode nodeTran) { _nodeTran = nodeTran.Transition; _customIonEquivalenceTestText = new TransitionLossKey(parent, nodeTran, null).CustomIonEquivalenceTestValue; }
/// <summary> /// In the case of small molecule transitions specified by mass only, position within /// the parent's list of transitions is the only meaningful key. So we need to know our parent. /// </summary> public TransitionLossEquivalentKey(TransitionGroupDocNode parent, TransitionDocNode transition, TransitionLosses losses) { Key = new TransitionEquivalentKey(parent, transition); Losses = losses; }
private IList <SpectrumDisplayInfo> GetSpectra(TransitionGroupDocNode nodeGroup, string lookupSequence, ExplicitMods lookupMods) { var settings = DocumentUI.Settings; var charge = nodeGroup.PrecursorCharge; var spectra = settings.GetBestSpectra(lookupSequence, charge, lookupMods).Select(s => new SpectrumDisplayInfo(s)).ToList(); // Showing redundant spectra is only supported for full-scan filtering when // the document has results files imported. if (!settings.TransitionSettings.FullScan.IsEnabled || !settings.HasResults) { return(spectra); } try { var spectraRedundant = new List <SpectrumDisplayInfo>(); var dictReplicateNameFiles = new Dictionary <string, HashSet <string> >(); foreach (var spectrumInfo in settings.GetRedundantSpectra(lookupSequence, charge, nodeGroup.TransitionGroup.LabelType, lookupMods).Concat( settings.GetMidasSpectra(nodeGroup.PrecursorMz))) { var matchingFile = settings.MeasuredResults.FindMatchingMSDataFile(MsDataFileUri.Parse(spectrumInfo.FilePath)); if (matchingFile == null) { continue; } string replicateName = matchingFile.Chromatograms.Name; spectraRedundant.Add(new SpectrumDisplayInfo(spectrumInfo, replicateName, matchingFile.FilePath, matchingFile.FileOrder, spectrumInfo.RetentionTime, false)); // Include the best spectrum twice, once displayed in the normal // way and once displayed with its replicate and retetion time. if (spectrumInfo.IsBest) { string libName = spectrumInfo.LibName; var labelType = spectrumInfo.LabelType; int iBest = spectra.IndexOf(s => Equals(s.LibName, libName) && Equals(s.LabelType, labelType)); if (iBest != -1) { spectra[iBest] = new SpectrumDisplayInfo(spectra[iBest].SpectrumInfo, replicateName, matchingFile.FilePath, 0, spectrumInfo.RetentionTime, true); } } HashSet <string> setFiles; if (!dictReplicateNameFiles.TryGetValue(replicateName, out setFiles)) { setFiles = new HashSet <string>(); dictReplicateNameFiles.Add(replicateName, setFiles); } setFiles.Add(spectrumInfo.FilePath); } // Determine if replicate name is sufficient to uniquely identify the file foreach (var spectrumInfo in spectraRedundant) { string replicateName = spectrumInfo.ReplicateName; if (replicateName != null && dictReplicateNameFiles[replicateName].Count < 2) { spectrumInfo.IsReplicateUnique = true; } } spectraRedundant.Sort(); spectra.AddRange(spectraRedundant); return(spectra); } catch (Exception) { return(spectra); } }
public NotFoundChromGraphItem(TransitionGroupDocNode nodeGroup) : base(string.Format(Resources.NotFoundChromGraphItem_NotFoundChromGraphItem__0__not_found, ChromGraphItem.GetTitle(nodeGroup))) { }
public PaneKey[] CalcPaneKeys(GraphTypeSummary graphType) { PaneKey[] paneKeys = null; if (Settings.Default.SplitChromatogramGraph) { if (graphType == GraphTypeSummary.replicate) { var selectedTreeNode = StateProvider.SelectedNode as SrmTreeNode; if (null != selectedTreeNode) { TransitionGroupDocNode[] transitionGroups; bool transitionSelected = false; // ReSharper disable once CanBeReplacedWithTryCastAndCheckForNull if (selectedTreeNode.Model is PeptideDocNode) { transitionGroups = ((PeptideDocNode)selectedTreeNode.Model).TransitionGroups.ToArray(); } // ReSharper disable once CanBeReplacedWithTryCastAndCheckForNull else if (selectedTreeNode.Model is TransitionGroupDocNode) { transitionGroups = new[] { (TransitionGroupDocNode)selectedTreeNode.Model }; } else if (selectedTreeNode.Model is TransitionDocNode) { transitionGroups = new[] { (TransitionGroupDocNode)((SrmTreeNode)selectedTreeNode.Parent).Model }; transitionSelected = true; } else { transitionGroups = new TransitionGroupDocNode[0]; } if (transitionGroups.Length == 1) { if (GraphChromatogram.DisplayType == DisplayTypeChrom.all || (GraphChromatogram.DisplayType == DisplayTypeChrom.single && !transitionSelected)) { var transitionGroup = transitionGroups[0]; bool hasPrecursors = transitionGroup.Transitions.Any(transition => transition.IsMs1); bool hasProducts = transitionGroup.Transitions.Any(transition => !transition.IsMs1); if (hasPrecursors && hasProducts) { paneKeys = new[] { PaneKey.PRECURSORS, PaneKey.PRODUCTS }; } } } else if (transitionGroups.Length > 1) { paneKeys = transitionGroups.Select(group => new PaneKey(@group)) .Distinct().ToArray(); } } } else { paneKeys = StateProvider.SelectionDocument.MoleculeTransitionGroups.Select( group => new PaneKey(@group.TransitionGroup.LabelType)).Distinct().ToArray(); } } paneKeys = paneKeys ?? new[] { PaneKey.DEFAULT }; Array.Sort(paneKeys); return(paneKeys); }
public static string GetTitle(TransitionGroupDocNode transitionGroup, TransitionDocNode transition) { if (null == transition) { return GetTitle(transitionGroup); } return string.Format("{0}{1} - {2:F04}{3}{4}", transition.FragmentIonName, // Not L10N Transition.GetMassIndexText(transition.Transition.MassIndex), transition.Mz, Transition.GetChargeIndicator(transition.Transition.Charge), transitionGroup.TransitionGroup.LabelTypeText); }
public ToolOptionsUI(SrmSettings settings) { InitializeComponent(); checkBoxShowWizard.Checked = Settings.Default.ShowStartupForm; powerOfTenCheckBox.Checked = Settings.Default.UsePowerOfTen; Icon = Resources.Skyline; _driverServers = new SettingsListBoxDriver <Server>(listboxServers, Settings.Default.ServerList); _driverServers.LoadList(); _driverRemoteAccounts = new SettingsListBoxDriver <RemoteAccount>(listBoxRemoteAccounts, Settings.Default.RemoteAccountList); _driverRemoteAccounts.LoadList(); _driverColorSchemes = new SettingsListComboDriver <ColorScheme>(comboColorScheme, Settings.Default.ColorSchemes, true); _driverColorSchemes.LoadList(Settings.Default.CurrentColorScheme); var pingPep = new Peptide(@"PING"); var peptide = new PeptideDocNode(pingPep); var precursor = new TransitionGroupDocNode(new TransitionGroup(pingPep, Adduct.SINGLY_PROTONATED, IsotopeLabelType.light), new TransitionDocNode[0]); _pingInput = new PrositIntensityModel.PeptidePrecursorNCE(peptide, precursor, IsotopeLabelType.light, 32); _settingsNoMod = settings.ChangePeptideModifications( pm => new PeptideModifications(new StaticMod[0], new TypedModifications[0])); // Hide ability to turn off live reports //tabControl.TabPages.Remove(tabMisc); // Populate the languages list with the languages that Skyline has been localized to string defaultDisplayName = string.Format(Resources.ToolOptionsUI_ToolOptionsUI_Default___0__, CultureUtil.GetDisplayLanguage(CultureInfo.InstalledUICulture).DisplayName); listBoxLanguages.Items.Add(new DisplayLanguageItem(string.Empty, defaultDisplayName)); foreach (var culture in CultureUtil.AvailableDisplayLanguages()) { listBoxLanguages.Items.Add(new DisplayLanguageItem(culture.Name, culture.DisplayName)); } for (int i = 0; i < listBoxLanguages.Items.Count; i++) { var displayLanguageItem = (DisplayLanguageItem)listBoxLanguages.Items[i]; if (Equals(displayLanguageItem.Key, Settings.Default.DisplayLanguage)) { listBoxLanguages.SelectedIndex = i; } } comboCompactFormatOption.Items.AddRange(CompactFormatOption.ALL_VALUES.ToArray()); comboCompactFormatOption.SelectedItem = CompactFormatOption.FromSettings(); var iModels = PrositIntensityModel.Models.ToList(); iModels.Insert(0, string.Empty); var rtModels = PrositRetentionTimeModel.Models.ToList(); rtModels.Insert(0, string.Empty); tbxPrositServer.Text = PrositConfig.GetPrositConfig().Server; intensityModelCombo.Items.AddRange(iModels.ToArray()); iRTModelCombo.Items.AddRange(rtModels.ToArray()); prositServerStatusLabel.Text = string.Empty; if (iModels.Contains(Settings.Default.PrositIntensityModel)) { intensityModelCombo.SelectedItem = Settings.Default.PrositIntensityModel; } if (rtModels.Contains(Settings.Default.PrositRetentionTimeModel)) { iRTModelCombo.SelectedItem = Settings.Default.PrositRetentionTimeModel; } ceCombo.Items.AddRange( Enumerable.Range(PrositConstants.MIN_NCE, PrositConstants.MAX_NCE - PrositConstants.MIN_NCE + 1).Select(c => (object)c) .ToArray()); ceCombo.SelectedItem = Settings.Default.PrositNCE; }
public PeptideDocNode CreateDocNodeFromSettings(string seq, Peptide peptide, SrmSettingsDiff diff, out TransitionGroupDocNode nodeGroupMatched) { seq = Transition.StripChargeIndicators(seq, TransitionGroup.MIN_PRECURSOR_CHARGE, TransitionGroup.MAX_PRECURSOR_CHARGE); if (peptide == null) { string seqUnmod = FastaSequence.StripModifications(seq); try { peptide = new Peptide(null, seqUnmod, null, null, Settings.PeptideSettings.Enzyme.CountCleavagePoints(seqUnmod)); } catch (InvalidDataException) { nodeGroupMatched = null; return null; } } // Use the number of modifications as the maximum, if it is less than the current // settings to keep from over enumerating, which can be slow. var filter = new MaxModFilter(Math.Min(seq.Count(c => c == '[' || c == '('), Settings.PeptideSettings.Modifications.MaxVariableMods)); foreach (var nodePep in peptide.CreateDocNodes(Settings, filter)) { var nodePepMod = CreateDocNodeFromSettings(seq, nodePep, diff, out nodeGroupMatched); if (nodePepMod != null) return nodePepMod; } nodeGroupMatched = null; return null; }
protected override void DoTest() { RunUI(() => SkylineWindow.OpenFile(TestFilesDir.GetTestPath("CE_Vantage_15mTorr_scheduled_mini_withMod.sky"))); WaitForGraphs(); RunUI(() => { SequenceTree sequenceTree = SkylineWindow.SequenceTree; // Test single node copy. sequenceTree.ExpandAll(); sequenceTree.KeysOverride = Keys.None; sequenceTree.SelectedNode = sequenceTree.Nodes[0]; SkylineWindow.Copy(); CheckCopiedNodes(0, 1); // Test multiple selection copy. sequenceTree.KeysOverride = Keys.Shift; sequenceTree.SelectedNode = sequenceTree.Nodes[1]; SkylineWindow.Copy(); // Test multiple selection disjoint, reverse order copy. CheckCopiedNodes(0, 1); Assert.AreSame(sequenceTree, SkylineWindow.SequenceTree); sequenceTree.KeysOverride = Keys.None; sequenceTree.SelectedNode = sequenceTree.Nodes[1].Nodes[0]; sequenceTree.KeysOverride = Keys.Control; sequenceTree.SelectedNode = sequenceTree.Nodes[0].Nodes[0]; SkylineWindow.Copy(); // After copying in reverse order, reselect the nodes in sorted order so we don't have to // sort them in the test code. sequenceTree.KeysOverride = Keys.None; sequenceTree.SelectedNode = sequenceTree.Nodes[0]; sequenceTree.SelectedNode = sequenceTree.Nodes[0].Nodes[0]; sequenceTree.KeysOverride = Keys.Control; sequenceTree.SelectedNode = sequenceTree.Nodes[1].Nodes[0]; Assert.AreSame(sequenceTree, SkylineWindow.SequenceTree); CheckCopiedNodes(1, 2); // Test no space between parent and descendents if immediate child is not selected. sequenceTree.KeysOverride = Keys.None; sequenceTree.SelectedNode = sequenceTree.Nodes[0]; sequenceTree.KeysOverride = Keys.Control; sequenceTree.SelectedNode = sequenceTree.Nodes[0].Nodes[0].Nodes[0].Nodes[0]; sequenceTree.SelectedNode = sequenceTree.Nodes[0].Nodes[0].Nodes[0].Nodes[2]; SkylineWindow.Copy(); CheckCopiedNodes(0, 1); // Test paste menu item enabled, copy menu item disabled when dummy node is selected. sequenceTree.KeysOverride = Keys.None; sequenceTree.SelectedNode = sequenceTree.Nodes[SkylineWindow.SequenceTree.Nodes.Count - 1]; Assert.IsFalse(SkylineWindow.CopyMenuItemEnabled(), "Copy menu should not be enabled"); Assert.IsTrue(SkylineWindow.PasteMenuItemEnabled()); // Test FASTA sequence copy HTML formatting sequenceTree.SelectedNode = sequenceTree.Nodes[0]; SkylineWindow.Copy(); string clipboardHtml = GetClipboardHtml(); Assert.AreEqual(4, Regex.Matches(clipboardHtml, "<font style=\"font-weight: bold").Count); Assert.AreEqual(4, Regex.Matches(clipboardHtml, "</font>").Count); Assert.AreEqual(1, Regex.Matches(clipboardHtml, "color: blue").Count); sequenceTree.SelectedNode = sequenceTree.Nodes[1]; SkylineWindow.Copy(); clipboardHtml = GetClipboardHtml(); Assert.AreEqual(19, Regex.Matches(clipboardHtml, "<font style=\"font-weight: bold").Count); Assert.AreEqual(19, Regex.Matches(clipboardHtml, "</font>").Count); Assert.AreEqual(2, Regex.Matches(clipboardHtml, "color: blue").Count); sequenceTree.SelectedNode = sequenceTree.Nodes[2]; SkylineWindow.Copy(); clipboardHtml = GetClipboardHtml(); Assert.AreEqual(18, Regex.Matches(clipboardHtml, "<font style=\"font-weight: bold").Count); Assert.AreEqual(18, Regex.Matches(clipboardHtml, "</font>").Count); Assert.AreEqual(2, Regex.Matches(clipboardHtml, "color: blue").Count); // Test clipboard HTML contains formatting for modified peptides. sequenceTree.SelectedNode = sequenceTree.Nodes[3].Nodes[0]; SkylineWindow.Copy(); clipboardHtml = GetClipboardHtml(); Assert.IsTrue(clipboardHtml.Contains("font") && clipboardHtml.Contains("color")); }); // Paste a protein list var document = WaitForDocumentLoaded(); RunUI(() => { SetClipboardText(PROTEINLIST_CLIPBOARD_TEXT); SkylineWindow.Paste(); }); var docPaste = WaitForDocumentChange(document); Assert.AreEqual(document.PeptideGroupCount + 3, docPaste.PeptideGroupCount); Assert.AreEqual("P23978", docPaste.PeptideGroups.Last().ProteinMetadata.Accession); // Did builtin IPI conversion work? // Paste an invalid protein list RunDlg <MessageDlg>(() => { SetClipboardText(PROTEINLIST_CLIPBOARD_TEXT.Replace("MDAL", "***")); SkylineWindow.Paste(); }, msgDlg => msgDlg.OkDialog()); Assert.AreSame(docPaste, WaitForProteinMetadataBackgroundLoaderCompletedUI()); // Test border case where protein/peptide/transition list contains a blank line // Should give generic error, not crash RunDlg <MessageDlg>(() => { SetClipboardText(PROTEIN_LIST_BAD_FORMAT); SkylineWindow.Paste(); }, msgDlg => { Assert.AreEqual(msgDlg.Message, Resources.CopyPasteTest_DoTest_Could_not_read_the_pasted_transition_list___Transition_list_must_be_in_separated_columns_and_cannot_contain_blank_lines_); msgDlg.OkDialog(); }); // Paste peptides var precursorAdduct = Adduct.DOUBLY_PROTONATED; List <Tuple <string, int> > peptidePaste = new List <Tuple <string, int> > { new Tuple <string, int>("FVEGLPINDFSR", 3), new Tuple <string, int>("FVEGLPINDFSR", 2), new Tuple <string, int>("FVEGLPINDFSR", 0), new Tuple <string, int>("DLNELQALIEAHFENR", 0), new Tuple <string, int>(string.Format("C[+{0:F01}]QPLELAGLGFAELQDLC[+{1:F01}]R", 57.0, 57.0), 3), new Tuple <string, int>("PEPTIDER", 5), new Tuple <string, int>("PEPTIDER", 15) }; var peptidePasteSb = new StringBuilder(); foreach (var pep in peptidePaste) { peptidePasteSb.AppendLine(pep.Item1 + Transition.GetChargeIndicator(Adduct.FromChargeProtonated(pep.Item2))); } RunUI(() => { SkylineWindow.NewDocument(true); document = SkylineWindow.Document; document = document.ChangeSettings(document.Settings.ChangeTransitionFilter(f => f.ChangePeptidePrecursorCharges(new[] { precursorAdduct }))); SetClipboardText(peptidePasteSb.ToString()); SkylineWindow.Paste(); }); document = WaitForDocumentChange(document); Assert.AreEqual(peptidePaste.Count, document.PeptideTransitionGroupCount); for (int i = 0; i < document.PeptideTransitionGroupCount; i++) { TransitionGroupDocNode transition = document.PeptideTransitionGroups.ElementAt(i); string seq = transition.TransitionGroup.Peptide.Sequence; var charge = transition.PrecursorAdduct.AdductCharge; Assert.AreEqual(FastaSequence.StripModifications(peptidePaste[i].Item1), seq); var pastedCharge = peptidePaste[i].Item2; Assert.AreEqual(pastedCharge != 0 ? pastedCharge : precursorAdduct.AdductCharge, charge); } // Undo paste RunUI(() => SkylineWindow.Undo()); document = WaitForDocumentChange(document); // Change precursor charges Adduct[] precursorCharges = { Adduct.DOUBLY_PROTONATED, Adduct.TRIPLY_PROTONATED, Adduct.QUADRUPLY_PROTONATED }; RunUI(() => SkylineWindow.ModifyDocument("Change precursor charges", doc => doc.ChangeSettings((document.Settings.ChangeTransitionFilter(f => f.ChangePeptidePrecursorCharges(precursorCharges)))))); document = WaitForDocumentChange(document); // Re-paste in peptides RunUI(() => SkylineWindow.Paste()); document = WaitForDocumentChange(document); int curTransitionGroup = 0; foreach (var peptide in peptidePaste) { if (peptide.Item2 > 0) { // Pasted peptides with a charge indicator should have a single precursor with the specified charge state TransitionGroupDocNode group = document.PeptideTransitionGroups.ElementAt(curTransitionGroup++); string seq = group.TransitionGroup.Peptide.Sequence; var charge = group.PrecursorAdduct.AdductCharge; Assert.AreEqual(FastaSequence.StripModifications(peptide.Item1), seq); var pastedCharge = peptide.Item2; Assert.AreEqual(pastedCharge, charge); } else { // Pasted peptides with no charge indicator should have a precursor for every charge state in transition filter settings for (int j = 0; j < precursorCharges.Count(); j++) { TransitionGroupDocNode group = document.PeptideTransitionGroups.ElementAt(curTransitionGroup++); string seq = group.TransitionGroup.Peptide.Sequence; var charge = group.PrecursorAdduct; Assert.AreEqual(FastaSequence.StripModifications(peptide.Item1), seq); Assert.AreEqual(precursorCharges[j], charge); } } } Assert.AreEqual(curTransitionGroup, document.PeptideTransitionGroupCount); }
public void UpdateUI(bool selectionChanged = true) { // Only worry about updates, if the graph is visible // And make sure it is not disposed, since rendering happens on a timer if (!Visible || IsDisposed) { return; } // Clear existing data from the graph pane var graphPane = (MSGraphPane)graphControl.MasterPane[0]; graphPane.CurveList.Clear(); graphPane.GraphObjList.Clear(); GraphItem = null; GraphHelper.FormatGraphPane(graphControl.GraphPane); GraphHelper.FormatFontSize(graphControl.GraphPane, Settings.Default.SpectrumFontSize); // Try to find a tree node with spectral library info associated // with the current selection. var nodeTree = _stateProvider.SelectedNode as SrmTreeNode; var nodeGroupTree = nodeTree as TransitionGroupTreeNode; var nodeTranTree = nodeTree as TransitionTreeNode; if (nodeTranTree != null) { nodeGroupTree = nodeTranTree.Parent as TransitionGroupTreeNode; } var nodeGroup = (nodeGroupTree != null ? nodeGroupTree.DocNode : null); PeptideTreeNode nodePepTree; if (nodeGroup == null) { nodePepTree = nodeTree as PeptideTreeNode; if (nodePepTree != null) { var listInfoGroups = GetLibraryInfoChargeGroups(nodePepTree); if (listInfoGroups.Length == 1) { nodeGroup = listInfoGroups[0]; } else if (listInfoGroups.Length > 1) { _nodeGroup = null; toolBar.Visible = false; _graphHelper.SetErrorGraphItem(new NoDataMSGraphItem( Resources.GraphSpectrum_UpdateUI_Multiple_charge_states_with_library_spectra)); return; } } } else { nodePepTree = nodeGroupTree.Parent as PeptideTreeNode; } // Check for appropriate spectrum to load SrmSettings settings = DocumentUI.Settings; PeptideLibraries libraries = settings.PeptideSettings.Libraries; bool available = false; if (nodeGroup == null || (!nodeGroup.HasLibInfo && !libraries.HasMidasLibrary)) { _spectra = null; } else { TransitionGroup group = nodeGroup.TransitionGroup; TransitionDocNode transition = (nodeTranTree == null ? null : nodeTranTree.DocNode); string lookupSequence = group.Peptide.TextId; // Sequence or custom ion id ExplicitMods lookupMods = null; if (nodePepTree != null) { lookupSequence = nodePepTree.DocNode.SourceUnmodifiedTextId; lookupMods = nodePepTree.DocNode.SourceExplicitMods; } try { // Try to load a list of spectra matching the criteria for // the current node group. if (libraries.HasLibraries && libraries.IsLoaded) { if (NodeGroupChanged(nodeGroup)) { try { UpdateSpectra(nodeGroup, lookupSequence, lookupMods); UpdateToolbar(); } catch (Exception) { _spectra = null; UpdateToolbar(); throw; } _nodeGroup = nodeGroup; if (settings.TransitionSettings.Instrument.IsDynamicMin) { ZoomSpectrumToSettings(); } } var spectrum = SelectedSpectrum; if (spectrum != null) { IsotopeLabelType typeInfo = spectrum.LabelType; var types = _stateProvider.ShowIonTypes; var charges = _stateProvider.ShowIonCharges; var rankTypes = settings.TransitionSettings.Filter.IonTypes; var rankCharges = settings.TransitionSettings.Filter.ProductCharges; // Make sure the types and charges in the settings are at the head // of these lists to give them top priority, and get rankings correct. int i = 0; foreach (IonType type in rankTypes) { if (types.Remove(type)) { types.Insert(i++, type); } } i = 0; foreach (int charge in rankCharges) { if (charges.Remove(charge)) { charges.Insert(i++, charge); } } SpectrumPeaksInfo spectrumInfo = spectrum.SpectrumPeaksInfo; var spectrumInfoR = new LibraryRankedSpectrumInfo(spectrumInfo, typeInfo, group, settings, lookupSequence, lookupMods, charges, types, rankCharges, rankTypes); GraphItem = new SpectrumGraphItem(nodeGroup, transition, spectrumInfoR, spectrum.LibName) { ShowTypes = types, ShowCharges = charges, ShowRanks = Settings.Default.ShowRanks, ShowMz = Settings.Default.ShowIonMz, ShowObservedMz = Settings.Default.ShowObservedMz, ShowDuplicates = Settings.Default.ShowDuplicateIons, FontSize = Settings.Default.SpectrumFontSize, LineWidth = Settings.Default.SpectrumLineWidth }; LibraryChromGroup chromatogramData = null; if (Settings.Default.ShowLibraryChromatograms) { chromatogramData = spectrum.LoadChromatogramData(); } if (null == chromatogramData) { _graphHelper.ResetForSpectrum(new[] { nodeGroup.TransitionGroup }); _graphHelper.AddSpectrum(GraphItem); _graphHelper.ZoomSpectrumToSettings(DocumentUI, nodeGroup); } else { _graphHelper.ResetForChromatograms(new[] { nodeGroup.TransitionGroup }); var displayType = GraphChromatogram.GetDisplayType(DocumentUI, nodeGroup); IList <TransitionDocNode> displayTransitions = GraphChromatogram.GetDisplayTransitions(nodeGroup, displayType).ToArray(); int numTrans = displayTransitions.Count; var allChromDatas = chromatogramData.ChromDatas.Where( chromData => DisplayTypeMatches(chromData, displayType)).ToList(); var chromDatas = new List <LibraryChromGroup.ChromData>(); for (int iTran = 0; iTran < numTrans; iTran++) { var displayTransition = displayTransitions[iTran]; var indexMatch = allChromDatas.IndexOf(chromData => IonMatches(displayTransition.Transition, chromData)); if (indexMatch >= 0) { chromDatas.Add(allChromDatas[indexMatch]); allChromDatas.RemoveAt(indexMatch); } else { chromDatas.Add(null); } } allChromDatas.Sort((chromData1, chromData2) => chromData1.Mz.CompareTo(chromData2.Mz)); chromDatas.AddRange(allChromDatas); double maxHeight = chromDatas.Max(chromData => null == chromData ? double.MinValue : chromData.Height); int iChromDataPrimary = chromDatas.IndexOf(chromData => null != chromData && maxHeight == chromData.Height); int colorOffset = displayType == DisplayTypeChrom.products ? GraphChromatogram.GetDisplayTransitions(nodeGroup, DisplayTypeChrom. precursors).Count() : 0; for (int iChromData = 0; iChromData < chromDatas.Count; iChromData++) { var chromData = chromDatas[iChromData]; if (chromData == null) { continue; } string label; var pointAnnotation = GraphItem.AnnotatePoint(new PointPair(chromData.Mz, 1.0)); if (null != pointAnnotation) { label = pointAnnotation.Label; } else { label = chromData.Mz.ToString("0.####"); // Not L10N } TransitionDocNode matchingTransition; Color color; if (iChromData < numTrans) { matchingTransition = displayTransitions[iChromData]; color = GraphChromatogram.COLORS_LIBRARY[ (iChromData + colorOffset) % GraphChromatogram.COLORS_LIBRARY.Length]; } else { matchingTransition = null; color = GraphChromatogram.COLORS_GROUPS[ iChromData % GraphChromatogram.COLORS_GROUPS.Length]; } TransitionChromInfo tranPeakInfo; ChromatogramInfo chromatogramInfo; MakeChromatogramInfo(nodeGroup.PrecursorMz, chromatogramData, chromData, out chromatogramInfo, out tranPeakInfo); var graphItem = new ChromGraphItem(nodeGroup, matchingTransition, chromatogramInfo, iChromData == iChromDataPrimary ? tranPeakInfo : null, null, new[] { iChromData == iChromDataPrimary }, null, 0, false, false, 0, color, Settings.Default.ChromatogramFontSize, 1); LineItem curve = (LineItem)_graphHelper.AddChromatogram(PaneKey.DEFAULT, graphItem); if (matchingTransition == null) { curve.Label.Text = label; } curve.Line.Width = Settings.Default.ChromatogramLineWidth; if (null != transition) { if (IonMatches(transition.Transition, chromData)) { color = ChromGraphItem.ColorSelected; } } curve.Color = color; } graphPane.Title.IsVisible = false; graphPane.Legend.IsVisible = true; _graphHelper.FinishedAddingChromatograms(chromatogramData.StartTime, chromatogramData.EndTime, false); graphControl.Refresh(); } graphControl.IsEnableVPan = graphControl.IsEnableVZoom = !Settings.Default.LockYAxis; available = true; } } } catch (Exception) { _graphHelper.SetErrorGraphItem(new NoDataMSGraphItem( Resources.GraphSpectrum_UpdateUI_Failure_loading_spectrum__Library_may_be_corrupted)); return; } } // Show unavailable message, if no spectrum loaded if (!available) { UpdateToolbar(); _nodeGroup = null; _graphHelper.SetErrorGraphItem(new UnavailableMSGraphItem()); } }
public void AddRemoveExplicitModTest() { SrmDocument docStudy7 = CreateStudy7Doc(); string transitionList = ExportCsv(docStudy7); Assert.AreEqual(69 + (TestSmallMolecules ? 2 : 0), 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.HeavyModifications; 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.HeavyModifications.Count); Assert.AreEqual(0, modifications.HeavyModifications.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.PrecursorCharge == nodeGroupLight.TransitionGroup.PrecursorCharge && !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.HeavyModifications.Count(mod => mod.IsExplicit && mod.Label13C)); Assert.AreEqual(2, modifications.HeavyModifications.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)); }
protected override bool IsMatch(string seqMod, PeptideDocNode nodePepMod, out TransitionGroupDocNode nodeGroup) { foreach(TransitionGroupDocNode nodeGroupChild in nodePepMod.Children) { nodeGroup = nodeGroupChild; var calc = Settings.TryGetPrecursorCalc(nodeGroupChild.TransitionGroup.LabelType, nodePepMod.ExplicitMods); if (calc == null) return false; string modSequence = calc.GetModifiedSequence(nodePepMod.Peptide.Sequence, false); // If this sequence matches the sequence of the library peptide, a match has been found. if (Equals(seqMod, modSequence)) return true; } nodeGroup = null; return false; }
/// <summary> /// Given a high scoring peak precursor peak group, find other lower scoring precursor peak /// groups from different precursors for the same peptide, which overlap in time with the /// high scoring peak. /// </summary> /// <param name="dataSets">Chromatogram data sets from which to create peptide peaks</param> /// <param name="dataPeakMax">High scoring precursor peak group</param> /// <param name="allPeakGroups">List of all lower scoring precursor peak groups for the same peptide</param> /// <returns>A list of coeluting precursor peak groups for this peptide</returns> private PeptideChromDataPeakList FindCoelutingPeptidePeaks(IEnumerable <ChromDataSet> dataSets, PeptideChromDataPeak dataPeakMax, IList <PeptideChromDataPeak> allPeakGroups) { TransitionGroupDocNode nodeGroupMax = dataPeakMax.Data.NodeGroup; int startMax = dataPeakMax.StartIndex; int endMax = dataPeakMax.EndIndex; int timeMax = dataPeakMax.TimeIndex; // Initialize the collection of peaks with this peak var listPeaks = new PeptideChromDataPeakList(NodePep, FileInfo, dataPeakMax); // Enumerate the precursors for this peptide foreach (var chromData in dataSets) { // Skip the precursor for the max peak itself if (ReferenceEquals(chromData, dataPeakMax.Data)) { continue; } int iPeakBest = -1; double bestProduct = 0; // Find nearest peak in remaining set that is less than 1/4 length // from the primary peak's center for (int i = 0, len = allPeakGroups.Count; i < len; i++) { var peakGroup = allPeakGroups[i]; // Consider only peaks for the current precursor if (!ReferenceEquals(peakGroup.Data, chromData)) { continue; } // Exclude peaks that do not overlap with the maximum peak TransitionGroupDocNode nodeGroup = peakGroup.Data.NodeGroup; int startPeak = peakGroup.StartIndex; int endPeak = peakGroup.EndIndex; if (Math.Min(endPeak, endMax) - Math.Max(startPeak, startMax) <= 0) { continue; } int timeIndex = peakGroup.TimeIndex; if ((nodeGroup.RelativeRT == RelativeRT.Matching && nodeGroupMax.RelativeRT == RelativeRT.Matching) || // Matching label types (i.e. different charge states of same label type should always match) ReferenceEquals(nodeGroup.TransitionGroup.LabelType, nodeGroupMax.TransitionGroup.LabelType)) { // If the peaks are supposed to have the same elution time, // then be more strict about how they overlap if (startMax >= timeIndex || timeIndex >= endMax) { continue; } } else if (nodeGroup.RelativeRT == RelativeRT.Matching && nodeGroupMax.RelativeRT == RelativeRT.Preceding) { // If the maximum is supposed to precede this, look for any // indication that this relationship holds, by testing the peak apex // and the peak center. if (timeIndex < timeMax && (startPeak + endPeak) / 2 < (startMax + endMax) / 2) { continue; } } else if (nodeGroup.RelativeRT == RelativeRT.Preceding && nodeGroupMax.RelativeRT == RelativeRT.Matching) { // If this peak is supposed to precede the maximum, look for any // indication that this relationship holds, by testing the peak apex // and the peak center. if (timeIndex > timeMax && (startPeak + endPeak) / 2 > (startMax + endMax) / 2) { continue; } } // Choose the next best peak that overlaps if (peakGroup.PeakGroup.CombinedScore > bestProduct) { iPeakBest = i; bestProduct = peakGroup.PeakGroup.CombinedScore; } } // If no coeluting peaks found, add an empty peak group if (iPeakBest == -1) { listPeaks.Add(new PeptideChromDataPeak(chromData, null)); } // Otherwise, add the found coeluting peak group, and remove it from the full list else { listPeaks.Add(new PeptideChromDataPeak(chromData, allPeakGroups[iPeakBest].PeakGroup)); allPeakGroups.RemoveAt(iPeakBest); } } return(listPeaks); }
public PeptideAnnotationPair(PeptideGroupDocNode peptideGroup, PeptideDocNode peptide, TransitionGroupDocNode tranGroup, string annotation, double cvRaw) { PeptideGroup = peptideGroup; Peptide = peptide; TransitionGroup = tranGroup; Annotation = annotation; CVRaw = cvRaw; }
private bool HasEquivalentGroupNode(TransitionGroupDocNode nodeGroup) { return(DataSets.Any(d => AreEquivalentGroupNodes(d.NodeGroup, nodeGroup))); }
protected void VerifyStartEndTime(SrmDocument document, PeptideDocNode peptideDocNode, TransitionGroupDocNode transitionGroupDocNode, int fileIndex, double startTime, double endTime) { ChromatogramGroupInfo[] infoSet; document.Settings.MeasuredResults.TryLoadChromatogram(fileIndex, peptideDocNode, transitionGroupDocNode, (float)TransitionInstrument.DEFAULT_MZ_MATCH_TOLERANCE, true, out infoSet); Assert.AreNotEqual(0, infoSet.Length); foreach (var chromatogramGroupInfo in infoSet) { Assert.AreEqual(startTime, chromatogramGroupInfo.Times.First(), .1); Assert.AreEqual(endTime, chromatogramGroupInfo.Times.Last(), .1); } }
private static bool AreEquivalentGroupNodes(TransitionGroupDocNode nodeGroup1, TransitionGroupDocNode nodeGroup2) { return(AreEquivalentGroups(nodeGroup1, nodeGroup2) && nodeGroup1.EquivalentChildren(nodeGroup2)); }
private DocNode CreateChoice(Identity childId, ExplicitMods mods) { TransitionGroup tranGroup = (TransitionGroup)childId; TransitionDocNode[] transitions = DocNode.GetMatchingTransitions( tranGroup, DocSettings, mods); var nodeGroup = new TransitionGroupDocNode(tranGroup, transitions); return nodeGroup.ChangeSettings(DocSettings, DocNode, mods, SrmSettingsDiff.ALL); }
public PaneKey(TransitionGroupDocNode nodeGroup) : this(nodeGroup != null ? nodeGroup.TransitionGroup.PrecursorAdduct : Adduct.EMPTY, nodeGroup != null ? nodeGroup.TransitionGroup.LabelType : null, false) { }
public FailedChromGraphItem(TransitionGroupDocNode nodeGroup, Exception x) : base(string.Format(Resources.FailedChromGraphItem_FailedChromGraphItem__0__load_failed__1__, ChromGraphItem.GetTitle(nodeGroup), x.Message)) { }
public ChromGraphItem(TransitionGroupDocNode transitionGroupNode, TransitionDocNode transition, ChromatogramInfo chromatogram, TransitionChromInfo tranPeakInfo, IRegressionFunction timeRegressionFunction, bool[] annotatePeaks, double[] dotProducts, double bestProduct, bool isFullScanMs, bool isSummary, int step, Color color, float fontSize, int width, FullScanInfo fullScanInfo = null) { TransitionGroupNode = transitionGroupNode; TransitionNode = transition; Chromatogram = chromatogram; TransitionChromInfo = tranPeakInfo; TimeRegressionFunction = timeRegressionFunction; Color = color; FullScanInfo = fullScanInfo; _step = step; _fontSpec = CreateFontSpec(color, fontSize); _width = width; _dotProducts = dotProducts; _bestProduct = bestProduct; _isFullScanMs = isFullScanMs; _isSummary = isSummary; _arrayLabelIndexes = new int[annotatePeaks.Length]; if (chromatogram == null) { _measuredTimes = new double[0]; _displayTimes = _measuredTimes; _intensities = new double[0]; } else { // Cache values early to avoid accessing slow enumerators // which show up under profiling. Chromatogram.AsArrays(out _measuredTimes, out _intensities); if (TimeRegressionFunction == null) { _displayTimes = _measuredTimes; } else { _displayTimes = _measuredTimes.Select(TimeRegressionFunction.GetY).ToArray(); } // Add peak times to hash set for labeling int iLastStart = 0; for (int i = 0; i < chromatogram.NumPeaks; i++) { int maxIndex = -1; if (annotatePeaks[i]) { ChromPeak peak = chromatogram.GetPeak(i); maxIndex = GetMaxIndex(peak.StartTime, peak.EndTime, ref iLastStart); } _arrayLabelIndexes[i] = maxIndex; if (maxIndex != -1 && !_annotatedTimes.ContainsKey(maxIndex)) { _annotatedTimes.Add(maxIndex, i); } } // Calculate best peak index if (tranPeakInfo != null) { iLastStart = 0; _bestPeakTimeIndex = GetMaxIndex(tranPeakInfo.StartRetentionTime, tranPeakInfo.EndRetentionTime, ref iLastStart); } } }
public ChromGraphItem(TransitionGroupDocNode transitionGroupNode, TransitionDocNode transition, ChromatogramInfo chromatogram, TransitionChromInfo tranPeakInfo, IRegressionFunction timeRegressionFunction, bool[] annotatePeaks, double[] dotProducts, double bestProduct, bool isFullScanMs, bool isSummary, int step, Color color, float fontSize, int width, FullScanInfo fullScanInfo = null) { TransitionGroupNode = transitionGroupNode; TransitionNode = transition; Chromatogram = chromatogram; TransitionChromInfo = tranPeakInfo; TimeRegressionFunction = timeRegressionFunction; Color = color; FullScanInfo = fullScanInfo; _step = step; _fontSpec = CreateFontSpec(color, fontSize); _width = width; _dotProducts = dotProducts; _bestProduct = bestProduct; _isFullScanMs = isFullScanMs; _isSummary = isSummary; _arrayLabelIndexes = new int[annotatePeaks.Length]; if (chromatogram == null) { _measuredTimes = new double[0]; _displayTimes = _measuredTimes; _intensities = new double[0]; } else { // Cache values early to avoid accessing slow enumerators // which show up under profiling. Chromatogram.AsArrays(out _measuredTimes, out _intensities); if (TimeRegressionFunction == null) { _displayTimes = _measuredTimes; } else { _displayTimes = _measuredTimes.Select(TimeRegressionFunction.GetY).ToArray(); } // Add peak times to hash set for labeling int iLastStart = 0; for (int i = 0; i < chromatogram.NumPeaks; i++) { int maxIndex = -1; if (annotatePeaks[i]) { ChromPeak peak = chromatogram.GetPeak(i); maxIndex = GetMaxIndex(peak.StartTime, peak.EndTime, ref iLastStart); } _arrayLabelIndexes[i] = maxIndex; if (maxIndex != -1 && !_annotatedTimes.ContainsKey(maxIndex)) _annotatedTimes.Add(maxIndex, i); } // Calculate best peak index if (tranPeakInfo != null) { iLastStart = 0; _bestPeakTimeIndex = GetMaxIndex(tranPeakInfo.StartRetentionTime, tranPeakInfo.EndRetentionTime, ref iLastStart); } } }
public static string GetTitle(TransitionGroupDocNode nodeGroup) { if (nodeGroup == null) return string.Empty; var seq = nodeGroup.TransitionGroup.Peptide.Sequence; // Not using Peptide.RawTextId, see comment below if (nodeGroup.TransitionGroup.IsCustomIon) { // Showing precursor m/z, so avoid showing ion masses as in DisplayName var customIon = nodeGroup.CustomIon; seq = customIon.Name ?? customIon.Formula; } string prefix = string.Empty; if (seq != null) prefix = seq + " - "; // Not L10N return string.Format("{0}{1:F04}{2}{3}", prefix, nodeGroup.PrecursorMz, // Not L10N Transition.GetChargeIndicator(nodeGroup.TransitionGroup.PrecursorCharge), nodeGroup.TransitionGroup.LabelTypeText); }
public double GetRegressionMz(PeptideDocNode nodePep, TransitionGroupDocNode nodeGroup) { double mz = nodeGroup.PrecursorMz; // Always use the light m/z value to ensure regression values are consistent between light and heavy if (!nodeGroup.TransitionGroup.LabelType.IsLight) { if (nodePep.Peptide.IsCustomIon) { double mass = nodeGroup.TransitionGroup.CustomIon.GetMass(TransitionSettings.Prediction.PrecursorMassType); mz = BioMassCalc.CalculateIonMz(mass, nodeGroup.TransitionGroup.PrecursorCharge); } else { double massH = GetPrecursorMass(IsotopeLabelType.light, nodePep.Peptide.Sequence, nodePep.ExplicitMods); mz = SequenceMassCalc.GetMZ(massH, nodeGroup.TransitionGroup.PrecursorCharge); } } return mz; }
private void RemovePeak(string chromName, IdentityPath pathGroupRemove, TransitionGroupDocNode nodeGroupRemove) { RunUI(() => { int resultsIndex = GetChromIndex(chromName); SkylineWindow.ActivateReplicate(chromName); Assert.AreEqual(resultsIndex, SkylineWindow.SelectedResultsIndex); SkylineWindow.RemovePeak(pathGroupRemove, nodeGroupRemove, null); // Confirm that peak has been removed from the right replicate var nodeGroupAfter = SkylineWindow.DocumentUI.FindNode(pathGroupRemove) as TransitionGroupDocNode; Assert.IsNotNull(nodeGroupAfter); Assert.AreSame(nodeGroupRemove.Id, nodeGroupAfter.Id); Assert.IsNotNull(nodeGroupRemove.Results[resultsIndex]); Assert.IsTrue(nodeGroupRemove.Results[resultsIndex][0].Area.HasValue); Assert.IsNotNull(nodeGroupAfter.Results[resultsIndex]); Assert.IsFalse(nodeGroupAfter.Results[resultsIndex][0].Area.HasValue); }); }
public static double?FindOptimizedValueFromResults(SrmSettings settings, PeptideDocNode nodePep, TransitionGroupDocNode nodeGroup, TransitionDocNode nodeTran, OptimizedMethodType methodType, GetRegressionValue getRegressionValue) { // Collect peak area for var dictOptTotals = new Dictionary <TReg, Dictionary <int, OptimizationStep <TReg> > >(); if (settings.HasResults) { var chromatograms = settings.MeasuredResults.Chromatograms; for (int i = 0; i < chromatograms.Count; i++) { var chromSet = chromatograms[i]; var regression = chromSet.OptimizationFunction as TReg; if (regression == null) { continue; } Dictionary <int, OptimizationStep <TReg> > stepAreas; if (!dictOptTotals.TryGetValue(regression, out stepAreas)) { dictOptTotals.Add(regression, stepAreas = new Dictionary <int, OptimizationStep <TReg> >()); } if (methodType == OptimizedMethodType.Precursor) { TransitionGroupDocNode[] listGroups = FindCandidateGroups(nodePep, nodeGroup); foreach (var nodeGroupCandidate in listGroups) { AddOptimizationStepAreas(nodeGroupCandidate, i, regression, stepAreas); } } else if (methodType == OptimizedMethodType.Transition) { IEnumerable <TransitionDocNode> listTransitions = FindCandidateTransitions(nodePep, nodeGroup, nodeTran); foreach (var nodeTranCandidate in listTransitions) { AddOptimizationStepAreas(nodeTranCandidate, i, regression, stepAreas); } } } } // If no candidate values were found, use the document regressor. if (dictOptTotals.Count == 0) { return(null); } // Get the CE value with the maximum total peak area double maxArea = 0; double bestValue = 0; foreach (var optTotals in dictOptTotals.Values) { foreach (var optStep in optTotals.Values) { if (maxArea < optStep.TotalArea) { maxArea = optStep.TotalArea; bestValue = getRegressionValue(settings, nodePep, nodeGroup, nodeTran, optStep.Regression, optStep.Step); } } } // Use value for candidate with the largest area return(bestValue); }
protected abstract bool IsMatch(string seq, PeptideDocNode nodePep, out TransitionGroupDocNode nodeGroup);
/// <summary> /// Finds the TransitionGroupChromInfo that matches the specified ChromatogramSet name and file path. /// </summary> public static TransitionGroupChromInfo FindChromInfo(SrmDocument document, TransitionGroupDocNode transitionGroupDocNode, string nameChromatogramSet, MsDataFileUri filePath) { ChromatogramSet chromatogramSet; int indexSet; if (!document.Settings.MeasuredResults.TryGetChromatogramSet(nameChromatogramSet, out chromatogramSet, out indexSet)) { return null; } var chromFileInfoId = chromatogramSet.FindFile(filePath); if (null == chromFileInfoId) { return null; } var results = transitionGroupDocNode.Results[indexSet]; if (null == results) { return null; } return results.FirstOrDefault(chromInfo => ReferenceEquals(chromFileInfoId, chromInfo.FileId)); }
public void AddRemoveExplicitModTest() { SrmDocument docStudy7 = CreateStudy7Doc(); string transitionList = ExportCsv(docStudy7); Assert.AreEqual(69 + (TestSmallMolecules ? 2 : 0), 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.HeavyModifications; 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.HeavyModifications.Count); Assert.AreEqual(0, modifications.HeavyModifications.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.PrecursorCharge == nodeGroupLight.TransitionGroup.PrecursorCharge && !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.HeavyModifications.Count(mod => mod.IsExplicit && mod.Label13C)); Assert.AreEqual(2, modifications.HeavyModifications.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)); }
private bool NodeGroupChanged(TransitionGroupDocNode nodeGroup) { return((_nodeGroup == null) || (!ReferenceEquals(_nodeGroup.Id, nodeGroup.Id))); }
private static TransitionGroupChromInfo GetTransitionGroupChromInfo(TransitionGroupDocNode nodeGroup, int iResults) { if (iResults == -1 || !nodeGroup.HasResults || iResults >= nodeGroup.Results.Count) return null; var listChromInfo = nodeGroup.Results[iResults]; if (listChromInfo == null) return null; return listChromInfo[0]; }
private void ExportGroupNode(PeptideDocNode peptideNode, TransitionGroupDocNode groupNode, ChromatogramSet chromatograms, ICollection<string> filesToExport, ICollection<ChromSource> chromSources, TextWriter writer, CultureInfo cultureInfo) { string peptideModifiedSequence = _settings.GetDisplayName(peptideNode); int precursorCharge = groupNode.TransitionGroup.PrecursorCharge; string labelType = groupNode.TransitionGroup.LabelType.Name; var filesInChrom = chromatograms.MSDataFilePaths.Select(path=>path.GetFileName()).ToList(); // Don't load the chromatogram group if none of its files are being exported if (!filesInChrom.Where(filesToExport.Contains).Any()) return; ChromatogramGroupInfo[] arrayChromInfo; if (!_measuredResults.TryLoadChromatogram(chromatograms, peptideNode, groupNode, _matchTolerance, true, out arrayChromInfo)) { // TODO: Determine if this is a real error or just a missing node for this file // If the former throw an exception, if the latter continue return; } if (arrayChromInfo.Length != chromatograms.FileCount) { throw new InvalidDataException(string.Format(Resources.ChromatogramExporter_ExportGroupNode_One_or_more_missing_chromatograms_at_charge_state__0__of__1_, precursorCharge, peptideModifiedSequence)); } foreach (var chromGroupInfo in arrayChromInfo) { string fileName = chromGroupInfo.FilePath.GetFileName(); // Skip the files that have not been selected for export if (!filesToExport.Contains(fileName)) continue; foreach (var nodeTran in groupNode.Transitions) { // TODO: Check a source attribute on the transition chrom info bool isMs1 = nodeTran.Transition.IsPrecursor() && !nodeTran.HasLoss; if (isMs1 && !chromSources.Contains(ChromSource.ms1)) continue; if (!isMs1 && !chromSources.Contains(ChromSource.fragment)) continue; int productCharge = nodeTran.Transition.Charge; float productMz = (float)nodeTran.Mz; var chromInfo = chromGroupInfo.GetTransitionInfo(productMz, _matchTolerance); // Sometimes a transition in the transition group does not have results for a particular file // If this happens just skip it for that file if (chromInfo == null) continue; IList<float> times = chromInfo.Times; IList<float> intensities = chromInfo.Intensities; if (times.Count != intensities.Count || intensities.Count == 0) { throw new InvalidDataException(string.Format(Resources.ChromatogramExporter_Export_Bad_chromatogram_data_for_charge__0__state_of_peptide__1_, precursorCharge, peptideModifiedSequence)); } float tic = CalculateTic(times, intensities); string[] fieldArray = { fileName, peptideModifiedSequence, System.Convert.ToString(precursorCharge, cultureInfo), System.Convert.ToString(productMz, cultureInfo), nodeTran.GetFragmentIonName(CultureInfo.InvariantCulture), System.Convert.ToString(productCharge, cultureInfo), labelType, System.Convert.ToString(tic, cultureInfo) }; FormatChromLine(writer, fieldArray, times, intensities, cultureInfo); } } }
/// <summary> /// Serializes the contents of a single <see cref="TransitionGroupDocNode"/> /// to XML. /// </summary> /// <param name="writer">The XML writer</param> /// <param name="nodePep">The parent peptide document node</param> /// <param name="node">The transition group document node</param> private void WriteTransitionGroupXml(XmlWriter writer, PeptideDocNode nodePep, TransitionGroupDocNode node) { TransitionGroup group = node.TransitionGroup; var isCustomIon = nodePep.Peptide.IsCustomMolecule; writer.WriteAttribute(ATTR.charge, group.PrecursorAdduct.AdductCharge); if (!group.LabelType.IsLight) { writer.WriteAttribute(ATTR.isotope_label, group.LabelType); } if (!isCustomIon) { writer.WriteAttribute(ATTR.calc_neutral_mass, node.GetPrecursorIonPersistentNeutralMass()); } writer.WriteAttribute(ATTR.precursor_mz, SequenceMassCalc.PersistentMZ(node.PrecursorMz)); WriteExplicitTransitionGroupValuesAttributes(writer, node.ExplicitValues); writer.WriteAttribute(ATTR.auto_manage_children, node.AutoManageChildren, true); writer.WriteAttributeNullable(ATTR.decoy_mass_shift, group.DecoyMassShift); writer.WriteAttributeNullable(ATTR.precursor_concentration, node.PrecursorConcentration); TransitionPrediction predict = Settings.TransitionSettings.Prediction; double regressionMz = Settings.GetRegressionMz(nodePep, node); var ce = predict.CollisionEnergy.GetCollisionEnergy(node.TransitionGroup.PrecursorAdduct, regressionMz); writer.WriteAttribute(ATTR.collision_energy, ce); var dpRegression = predict.DeclusteringPotential; if (dpRegression != null) { var dp = dpRegression.GetDeclustringPotential(regressionMz); writer.WriteAttribute(ATTR.declustering_potential, dp); } if (!isCustomIon) { // modified sequence if (nodePep.ExplicitMods != null && nodePep.ExplicitMods.HasCrosslinks) { writer.WriteAttribute(ATTR.modified_sequence, Settings.GetCrosslinkModifiedSequence(nodePep.Target, node.TransitionGroup.LabelType, nodePep.ExplicitMods, false)); } else { var calcPre = Settings.GetPrecursorCalc(node.TransitionGroup.LabelType, nodePep.ExplicitMods); var seq = node.TransitionGroup.Peptide.Target; writer.WriteAttribute(ATTR.modified_sequence, calcPre.GetModifiedSequence(seq, false)); // formatNarrow = false; We want InvariantCulture, not the local format } Assume.IsTrue(group.PrecursorAdduct.IsProteomic); } else { // Custom ion node.CustomMolecule.WriteXml(writer, group.PrecursorAdduct); } // Write child elements WriteAnnotations(writer, node.Annotations); if (node.HasLibInfo) { var helpers = PeptideLibraries.SpectrumHeaderXmlHelpers; writer.WriteElements(new[] { node.LibInfo }, helpers); } if (node.HasResults) { WriteResults(writer, Settings, node.Results, EL.precursor_results, EL.precursor_peak, WriteTransitionGroupChromInfo); } if (UseCompactFormat()) { writer.WriteStartElement(EL.transition_data); var transitionData = new SkylineDocumentProto.Types.TransitionData(); transitionData.Transitions.AddRange(node.Transitions.Select(transition => transition.ToTransitionProto(Settings))); byte[] bytes = transitionData.ToByteArray(); writer.WriteBase64(bytes, 0, bytes.Length); writer.WriteEndElement(); if (WroteTransitions != null) { WroteTransitions(node.TransitionCount); } } else { foreach (TransitionDocNode nodeTransition in node.Children) { writer.WriteStartElement(EL.transition); WriteTransitionXml(writer, nodePep, node, nodeTransition); writer.WriteEndElement(); } } }
// ReSharper restore SuggestBaseTypeForParameter // ReSharper disable SuggestBaseTypeForParameter private static bool HasPeak(int iResult, TransitionGroupDocNode nodeGroup) { foreach (TransitionDocNode nodeTran in nodeGroup.Children) { if (HasPeak(iResult, nodeTran)) return true; } return false; }
/// <summary> /// Serializes the contents of a single <see cref="TransitionDocNode"/> /// to XML. /// </summary> /// <param name="writer">The XML writer</param> /// <param name="nodePep">The transition group's parent peptide node</param> /// <param name="nodeGroup">The transition node's parent group node</param> /// <param name="nodeTransition">The transition document node</param> private void WriteTransitionXml(XmlWriter writer, PeptideDocNode nodePep, TransitionGroupDocNode nodeGroup, TransitionDocNode nodeTransition) { Transition transition = nodeTransition.Transition; writer.WriteAttribute(ATTR.fragment_type, transition.IonType); writer.WriteAttribute(ATTR.quantitative, nodeTransition.ExplicitQuantitative, true); WriteExplicitTransitionValuesAttributes(writer, nodeTransition.ExplicitValues); if (transition.IsCustom()) { if (!(transition.CustomIon is SettingsCustomIon)) { transition.CustomIon.WriteXml(writer, transition.Adduct); } else { writer.WriteAttributeString(ATTR.measured_ion_name, transition.CustomIon.Name); } } writer.WriteAttributeNullable(ATTR.decoy_mass_shift, transition.DecoyMassShift); // NOTE: MassIndex is the peak index in the isotopic distribution of the precursor. // 0 for monoisotopic peaks and for non "precursor" ion types. if (transition.MassIndex != 0) { writer.WriteAttribute(ATTR.mass_index, transition.MassIndex); } if (nodeTransition.HasDistInfo) { writer.WriteAttribute(ATTR.isotope_dist_rank, nodeTransition.IsotopeDistInfo.Rank); writer.WriteAttribute(ATTR.isotope_dist_proportion, nodeTransition.IsotopeDistInfo.Proportion); } if (transition.IsPrecursor()) { writer.WriteAttribute(ATTR.product_charge, transition.Charge, nodeGroup.PrecursorCharge); } else { if (!transition.IsCustom()) { writer.WriteAttribute(ATTR.fragment_ordinal, transition.Ordinal); writer.WriteAttribute(ATTR.calc_neutral_mass, nodeTransition.GetMoleculePersistentNeutralMass()); } writer.WriteAttribute(ATTR.product_charge, transition.Charge); if (!transition.IsCustom()) { writer.WriteAttribute(ATTR.cleavage_aa, transition.AA.ToString(CultureInfo.InvariantCulture)); writer.WriteAttribute(ATTR.loss_neutral_mass, nodeTransition.LostMass); //po } } if (nodeTransition.ComplexFragmentIon.IsOrphan) { writer.WriteAttribute(ATTR.orphaned_crosslink_ion, true); } // Order of elements matters for XSD validation WriteAnnotations(writer, nodeTransition.Annotations); writer.WriteElementString(EL.precursor_mz, SequenceMassCalc.PersistentMZ(nodeGroup.PrecursorMz)); writer.WriteElementString(EL.product_mz, SequenceMassCalc.PersistentMZ(nodeTransition.Mz)); TransitionPrediction predict = Settings.TransitionSettings.Prediction; var optimizationMethod = predict.OptimizedMethodType; double?ce = null; double?dp = null; var lib = predict.OptimizedLibrary; if (lib != null && !lib.IsNone) { var optimization = lib.GetOptimization(OptimizationType.collision_energy, Settings.GetSourceTarget(nodePep), nodeGroup.PrecursorAdduct, nodeTransition.FragmentIonName, nodeTransition.Transition.Adduct); if (optimization != null) { ce = optimization.Value; } } double regressionMz = Settings.GetRegressionMz(nodePep, nodeGroup); var ceRegression = predict.CollisionEnergy; var dpRegression = predict.DeclusteringPotential; if (optimizationMethod == OptimizedMethodType.None) { if (ceRegression != null && !ce.HasValue) { ce = ceRegression.GetCollisionEnergy(nodeGroup.PrecursorAdduct, regressionMz); } if (dpRegression != null) { dp = dpRegression.GetDeclustringPotential(regressionMz); } } else { if (!ce.HasValue) { ce = OptimizationStep <CollisionEnergyRegression> .FindOptimizedValue(Settings, nodePep, nodeGroup, nodeTransition, optimizationMethod, ceRegression, SrmDocument.GetCollisionEnergy); } dp = OptimizationStep <DeclusteringPotentialRegression> .FindOptimizedValue(Settings, nodePep, nodeGroup, nodeTransition, optimizationMethod, dpRegression, SrmDocument.GetDeclusteringPotential); } if (nodeTransition.ExplicitValues.CollisionEnergy.HasValue) { ce = nodeTransition.ExplicitValues.CollisionEnergy; // Explicitly imported, overrides any calculation } if (ce.HasValue) { writer.WriteElementString(EL.collision_energy, ce.Value); } if (dp.HasValue) { writer.WriteElementString(EL.declustering_potential, dp.Value); } WriteTransitionLosses(writer, nodeTransition.Losses); foreach (var linkedIon in nodeTransition.ComplexFragmentIon.Children) { WriteLinkedIon(writer, linkedIon.Key, linkedIon.Value); } if (nodeTransition.HasLibInfo) { writer.WriteStartElement(EL.transition_lib_info); writer.WriteAttribute(ATTR.rank, nodeTransition.LibInfo.Rank); writer.WriteAttribute(ATTR.intensity, nodeTransition.LibInfo.Intensity); writer.WriteEndElement(); } if (nodeTransition.HasResults) { if (nodeTransition.HasResults) { if (UseCompactFormat()) { var protoResults = new SkylineDocumentProto.Types.TransitionResults(); protoResults.Peaks.AddRange(nodeTransition.GetTransitionPeakProtos(Settings.MeasuredResults)); byte[] bytes = protoResults.ToByteArray(); writer.WriteStartElement(EL.results_data); writer.WriteBase64(bytes, 0, bytes.Length); writer.WriteEndElement(); } else { WriteResults(writer, Settings, nodeTransition.Results, EL.transition_results, EL.transition_peak, WriteTransitionChromInfo); } } } if (WroteTransitions != null) { WroteTransitions(1); } }
private SrmDocument RemovePeakInternal(SrmDocument document, int resultsIndex, IdentityPath groupPath, TransitionGroupDocNode nodeGroup, TransitionDocNode nodeTran) { ChromInfo chromInfo; Transition transition; if (nodeTran == null) { chromInfo = GetTransitionGroupChromInfo(nodeGroup, resultsIndex); transition = null; } else { chromInfo = GetTransitionChromInfo(nodeTran, resultsIndex); transition = nodeTran.Transition; } if (chromInfo == null) return document; MsDataFileUri filePath; string name = GetGraphChromStrings(resultsIndex, chromInfo.FileId, out filePath); return name == null ? document : document.ChangePeak(groupPath, name, filePath, transition, 0, 0, UserSet.TRUE, PeakIdentification.FALSE, false); }
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)); }
public void RemovePeak(IdentityPath groupPath, TransitionGroupDocNode nodeGroup, TransitionDocNode nodeTran) { string message = nodeTran == null ? string.Format(Resources.SkylineWindow_RemovePeak_Remove_all_peaks_from__0__, ChromGraphItem.GetTitle(nodeGroup)) : string.Format(Resources.SkylineWindow_RemovePeak_Remove_peak_from__0__, ChromGraphItem.GetTitle(nodeTran)); ModifyDocument(message, doc => RemovePeakInternal(doc, SelectedResultsIndex, groupPath, nodeGroup, nodeTran)); }
public virtual void AddToInternalData(ICollection <InternalData> data, List <AreaInfo> areas, PeptideGroupDocNode peptideGroup, PeptideDocNode peptide, TransitionGroupDocNode tranGroup, string annotation) { var normalizedStatistics = new Statistics(areas.Select(a => a.NormalizedArea)); var normalizedMean = normalizedStatistics.Mean(); var normalizedStdDev = normalizedStatistics.StdDev(); // If the mean is 0 or NaN or the standard deviaiton is NaN the cv would also be NaN if (normalizedMean == 0.0 || double.IsNaN(normalizedMean) || double.IsNaN(normalizedStdDev)) { return; } // Round cvs so that the smallest difference between two cv's is BinWidth var cv = normalizedStdDev / normalizedMean; data.Add(new InternalData { Peptide = peptide, PeptideGroup = peptideGroup, TransitionGroup = tranGroup, Annotation = annotation, CV = cv, CVBucketed = cv, Area = 0.0 }); }
/// <summary> /// Collects statistics on how much space savings minimizing will achieve, and (if outStream /// is not null) writes out the minimized cache file. /// </summary> public void Minimize(Settings settings, ProgressCallback progressCallback, Stream outStream, FileStream outStreamScans = null, FileStream outStreamPeaks = null, FileStream outStreamScores = null) { var writer = outStream == null ? null : new Writer(ChromatogramCache, outStream, outStreamScans, outStreamPeaks, outStreamScores); var statisticsCollector = new MinStatisticsCollector(this); bool readChromatograms = settings.NoiseTimeRange.HasValue || writer != null; var chromGroupHeaderToIndex = ChromGroupHeaderInfos .Select((cghi, index) => new KeyValuePair<ChromGroupHeaderInfo5, int>(cghi, index)) .ToDictionary(kvp => kvp.Key, kvp=>kvp.Value); var chromGroups = new ChromatogramGroupInfo[ChromGroupHeaderInfos.Count]; var transitionGroups = new List<TransitionGroupDocNode>[ChromGroupHeaderInfos.Count]; foreach (var nodePep in Document.Molecules) { foreach (var nodeGroup in nodePep.TransitionGroups) { ChromatogramGroupInfo[] groupInfos; ChromatogramCache.TryLoadChromatogramInfo(nodePep, nodeGroup, _tolerance, out groupInfos); foreach (var chromGroupInfo in groupInfos) { int headerIndex = chromGroupHeaderToIndex[chromGroupInfo.Header]; if (chromGroups[headerIndex] == null) { chromGroups[headerIndex] = chromGroupInfo; transitionGroups[headerIndex] = new List<TransitionGroupDocNode>(); } transitionGroups[headerIndex].Add(nodeGroup); } } } for (int iHeader = 0; iHeader < ChromGroupHeaderInfos.Count; iHeader++) { var chromGroupInfo = chromGroups[iHeader]; IList<TransitionGroupDocNode> transitionGroupDocNodes; if (chromGroupInfo == null) { chromGroupInfo = ChromatogramCache.LoadChromatogramInfo(ChromGroupHeaderInfos[iHeader]); transitionGroupDocNodes = new TransitionGroupDocNode[0]; } else { transitionGroupDocNodes = transitionGroups[iHeader]; } if (readChromatograms) { try { chromGroupInfo.ReadChromatogram(ChromatogramCache); } catch (Exception exception) { Trace.TraceWarning("Unable to read chromatogram {0}", exception); // Not L10N } } MinimizedChromGroup minimizedChromGroup = MinimizeChromGroup(settings, chromGroupInfo, transitionGroupDocNodes); statisticsCollector.ProcessChromGroup(minimizedChromGroup); if (progressCallback != null) { progressCallback.Invoke(statisticsCollector.GetStatistics()); } if (writer != null) { writer.WriteChromGroup(chromGroupInfo, minimizedChromGroup); } // Null out the ChromGroup in our array so it can be garbage collected. chromGroups[iHeader] = null; } if (progressCallback != null) { progressCallback.Invoke(statisticsCollector.GetStatistics()); } if (writer != null) { writer.WriteEndOfFile(); } }
private void AddToInternalData(ICollection <InternalData> data, List <AreaInfo> areas, PeptideGroupDocNode peptideGroup, PeptideDocNode peptide, TransitionGroupDocNode tranGroup, string annotation) { var normalizedStatistics = new Statistics(areas.Select(a => a.NormalizedArea)); var normalizedMean = normalizedStatistics.Mean(); var normalizedStdDev = normalizedStatistics.StdDev(); var unnormalizedStatistics = new Statistics(areas.Select(a => a.Area)); var unnomarlizedMean = unnormalizedStatistics.Mean(); // If the mean is 0 or NaN or the standard deviaiton is NaN the cv would also be NaN if (normalizedMean == 0.0 || double.IsNaN(normalizedMean) || double.IsNaN(normalizedStdDev)) { return; } // Round cvs so that the smallest difference between two cv's is BinWidth var cv = normalizedStdDev / normalizedMean; var cvBucketed = Math.Floor(cv / _graphSettings.BinWidth) * _graphSettings.BinWidth; var log10Mean = _graphSettings.GraphType == GraphTypeSummary.histogram2d ? Math.Floor(Math.Log10(unnomarlizedMean) / 0.05) * 0.05 : 0.0; data.Add(new InternalData { Peptide = peptide, PeptideGroup = peptideGroup, TransitionGroup = tranGroup, Annotation = annotation, CV = cv, CVBucketed = cvBucketed, Area = log10Mean }); }