public bool TrySetReplicateChecked(ChromatogramSet chromatogramSet, bool isChecked) { for (int index = 0; index < checkedListBoxResults.Items.Count; index ++) { ListBoxItem item = (ListBoxItem) checkedListBoxResults.Items[index]; if (ReferenceEquals(chromatogramSet, item.ChromatogramSet)) { checkedListBoxResults.SetItemChecked(index, isChecked); return true; } } return false; }
public bool Equals(ChromatogramSet obj) { if (ReferenceEquals(null, obj)) { return(false); } if (ReferenceEquals(this, obj)) { return(true); } // Why isn't "OptimizationFunction" included in "Equals"? if (!base.Equals(obj)) { return(false); } if (!ArrayUtil.EqualsDeep(obj.MSDataFileInfos, MSDataFileInfos)) { return(false); } if (!Equals(obj.Annotations, Annotations)) { return(false); } if (!obj.UseForRetentionTimeFilter == UseForRetentionTimeFilter) { return(false); } if (!Equals(obj.OptimizationFunction, OptimizationFunction)) { return(false); } if (obj._rescoreCount != _rescoreCount) { return(false); } if (!Equals(obj.AnalyteConcentration, AnalyteConcentration)) { return(false); } if (!Equals(obj.SampleType, SampleType)) { return(false); } return(true); }
/// <summary> /// Display summed transitions for multiple selected peptides. /// </summary> private void DisplayPeptides(IRegressionFunction timeRegressionFunction, ChromatogramSet chromatograms, float mzMatchTolerance, int countLabelTypes, IList<PeptideDocNode> peptideDocNodes, ref double bestStartTime, ref double bestEndTime, out double leftPeakWidth, out double rightPeakWidth) { leftPeakWidth = 0; rightPeakWidth = 0; // Construct and add graph items for all relevant transition groups. float fontSize = FontSize; int lineWidth = LineWidth; var chromGroupInfos = ChromGroupInfos; var lookupChromGroupInfoIndex = new Dictionary<int, int>(_nodeGroups.Length); for (int i = 0; i < _nodeGroups.Length; i++) lookupChromGroupInfoIndex[_nodeGroups[i].Id.GlobalIndex] = i; // Generate a unique short identifier for each peptide. var peptideNames = new Tuple<string,bool>[peptideDocNodes.Count]; for (int i = 0; i < peptideDocNodes.Count; i++) peptideNames[i] = new Tuple<string,bool>(peptideDocNodes[i].RawTextId, peptideDocNodes[i].IsProteomic); var uniqueNames = new UniquePrefixGenerator(peptideNames, 3); var displayPeptides = new List<DisplayPeptide>(); for (int peptideIndex = 0; peptideIndex < peptideDocNodes.Count; peptideIndex++) { var peptideDocNode = peptideDocNodes[peptideIndex]; TransitionChromInfo bestPeakInfo = null; ChromatogramInfo sumInfo = null; float maxPeakHeight = float.MinValue; foreach (var precursor in peptideDocNode.TransitionGroups) { int indexInfo; if (!lookupChromGroupInfoIndex.TryGetValue(precursor.Id.GlobalIndex, out indexInfo)) continue; var chromGroupInfo = chromGroupInfos[indexInfo]; if (chromGroupInfo == null) continue; ChromFileInfoId fileId = chromatograms.FindFile(chromGroupInfo); foreach (var nodeTran in precursor.Transitions) { var info = chromGroupInfo.GetTransitionInfo((float)nodeTran.Mz, mzMatchTolerance); if (info == null) continue; if (sumInfo == null) sumInfo = info; else { float[] sumTimes; float[] sumIntensities; if (!AddTransitions.Add( info.Times, info.Intensities, sumInfo.Times, sumInfo.Intensities, out sumTimes, out sumIntensities)) continue; sumInfo = new ChromatogramInfo(sumTimes, sumIntensities); } // Keep track of which chromatogram owns the tallest member of // the peak on the document tree. var transitionChromInfo = GetTransitionChromInfo(nodeTran, _chromIndex, fileId, 0); if (transitionChromInfo == null) continue; if (transitionChromInfo.Height > maxPeakHeight) { maxPeakHeight = transitionChromInfo.Height; bestPeakInfo = transitionChromInfo; } } } if (sumInfo != null && bestPeakInfo != null) { displayPeptides.Add(new DisplayPeptide { PeptideIndex = peptideIndex, SumInfo = sumInfo, BestPeakInfo = bestPeakInfo }); } } // Order the peptides by height of best peak. displayPeptides = displayPeptides.OrderByDescending(e => e.BestPeakInfo.Height).ToList(); // Display only the top peptides. int lastPeptideIndex = Math.Min(MaxPeptidesDisplayed, displayPeptides.Count); var graphItems = new List<ChromGraphItem>(); for (int i = lastPeptideIndex-1; i >= 0; i--) // smallest peaks first for good z-ordering in graph { var bestPeakInfo = displayPeptides[i].BestPeakInfo; var sumInfo = displayPeptides[i].SumInfo; var peptideDocNode = peptideDocNodes[displayPeptides[i].PeptideIndex]; // Intersect best peak with summed transition. if (bestPeakInfo != null && sumInfo.Times.Length > 0) { float startRetentionTime = Math.Max(bestPeakInfo.StartRetentionTime, sumInfo.Times[0]); float endRetentionTime = Math.Min(bestPeakInfo.EndRetentionTime, sumInfo.Times[sumInfo.Times.Length - 1]); if (endRetentionTime > startRetentionTime) { if (bestStartTime > startRetentionTime) { bestStartTime = startRetentionTime; leftPeakWidth = endRetentionTime - startRetentionTime; } if (bestEndTime < endRetentionTime) { bestEndTime = endRetentionTime; rightPeakWidth = endRetentionTime - startRetentionTime; } bestPeakInfo = new TransitionChromInfo(startRetentionTime, endRetentionTime); } } // Get peptide graph color from SequenceTree. var peptideGraphInfo = _stateProvider.GetPeptideGraphInfo(peptideDocNode); Color color = peptideGraphInfo.Color; sumInfo.Transform(Transform); bool[] annotateAll = new bool[sumInfo.NumPeaks]; ChromGraphItem graphItem = new ChromGraphItem(null, null, sumInfo, bestPeakInfo, timeRegressionFunction, annotateAll, null, 0, false, false, 0, color, fontSize, lineWidth) { CurveAnnotation = uniqueNames.GetUniquePrefix(peptideDocNode.RawTextId, peptideDocNode.IsProteomic), IdPath = _groupPaths[displayPeptides[i].PeptideIndex], GraphInfo = peptideGraphInfo }; if (peptideGraphInfo.IsSelected) graphItems.Insert(0, graphItem); else graphItems.Add(graphItem); } foreach (var graphItem in graphItems) { var curveItem = _graphHelper.AddChromatogram(new PaneKey(), graphItem); // Make the fill color under the curve more opaque if the curve is selected. var fillAlpha = graphItem.GraphInfo.IsSelected ? 60 : 15; ((LineItem)curveItem).Line.Fill = new Fill(Color.FromArgb(fillAlpha, graphItem.GraphInfo.Color)); } }
private void DisplayOptimizationTotals(IRegressionFunction timeRegressionFunction, ChromatogramSet chromatograms, float mzMatchTolerance, ref double bestStartTime, ref double bestEndTime) { // Construct and add graph items for all relevant transition groups. float fontSize = FontSize; int lineWidth = LineWidth; int iColor = 0; // Get the one and only group var nodeGroup = _nodeGroups[0]; var chromGroupInfo = ChromGroupInfos[0]; ChromFileInfoId fileId = chromatograms.FindFile(chromGroupInfo); int numPeaks = chromGroupInfo.NumPeaks; // Collect the chromatogram info for the transition children // of this transition group. var listChromInfoSets = new List<ChromatogramInfo[]>(); var listTranisitionChromInfoSets = new List<TransitionChromInfo[]>(); int totalOptCount = chromatograms.OptimizationFunction.StepCount*2 + 1; foreach (TransitionDocNode nodeTran in nodeGroup.Children) { var infos = chromGroupInfo.GetAllTransitionInfo((float) nodeTran.Mz, mzMatchTolerance, chromatograms.OptimizationFunction); if (infos.Length == 0) continue; // Make sure the total number of chrom info entries match the expected // no matter what, so that chromatogram colors will match up with peak // area charts. if (infos.Length != totalOptCount) infos = ResizeArrayChromInfo(infos, totalOptCount); listChromInfoSets.Add(infos); var transitionChromInfos = new TransitionChromInfo[totalOptCount]; int steps = infos.Length/2; int offset = totalOptCount/2 - steps; for (int i = 0; i < infos.Length; i++) { transitionChromInfos[i + offset] = GetTransitionChromInfo(nodeTran, _chromIndex, fileId, i - steps); } listTranisitionChromInfoSets.Add(transitionChromInfos); } if (listChromInfoSets.Count == 0 || totalOptCount == 0) throw new InvalidDataException(Resources.GraphChromatogram_DisplayOptimizationTotals_No_optimization_data_available); // Enumerate optimization steps, grouping the data into graph data by step var listGraphData = new List<OptimizationGraphData>(); for (int i = 0; i < listChromInfoSets.Count; i++) { var chromInfos = listChromInfoSets[i]; var transitionChromInfos = listTranisitionChromInfoSets[i]; for (int j = 0; j < chromInfos.Length; j++) { if (listGraphData.Count <= j) listGraphData.Add(new OptimizationGraphData(numPeaks)); listGraphData[j].Add(chromInfos[j], transitionChromInfos[j]); } } // Total and transform the data, and compute which optimization // set has the most intense peak for each peak group. int bestPeakData = -1; TransitionChromInfo tranPeakInfo = null; float maxPeakHeight = float.MinValue; var maxPeakData = new int[numPeaks]; var maxPeakHeights = new float[numPeaks]; for (int i = 0; i < numPeaks; i++) maxPeakHeights[i] = float.MinValue; var transform = Transform; for (int i = 0; i < listGraphData.Count; i++) { var graphData = listGraphData[i]; var infoPrimary = graphData.InfoPrimary; if (infoPrimary == null) continue; // Sum intensities of all transitions in this // optimization bucket infoPrimary.SumIntensities(graphData.ChromInfos); // Apply any transform the user has chosen infoPrimary.Transform(transform); for (int j = 0; j < numPeaks; j++) { float height = graphData.PeakHeights[j]; if (height > maxPeakHeights[j]) { maxPeakHeights[j] = height; maxPeakData[j] = i; } } if (maxPeakHeight < graphData.TotalHeight) { maxPeakHeight = graphData.TotalHeight; bestPeakData = i; tranPeakInfo = graphData.TransitionInfoPrimary; } AddBestPeakTimes(graphData.TransitionInfoPrimary, ref bestStartTime, ref bestEndTime); } // Hide all peaks between the best peak extents if (tranPeakInfo != null) { for (int j = 0; j < numPeaks; j++) { if (maxPeakHeights[j] == 0) continue; var graphData = listGraphData[maxPeakData[j]]; if (graphData.InfoPrimary == null) continue; ChromPeak peak = graphData.InfoPrimary.GetPeak(j); if (peak.IsForcedIntegration) continue; if (IntersectPeaks(peak, tranPeakInfo)) maxPeakHeights[j] = 0; } } // Create graph items int totalSteps = totalOptCount/2; for (int i = 0; i < listGraphData.Count; i++) { var graphData = listGraphData[i]; if (graphData.InfoPrimary != null) { int step = i - totalSteps; int width = lineWidth; Color color; if (step == 0) { color = ChromGraphItem.ColorSelected; width++; } else if (nodeGroup.HasLibInfo) color = COLORS_LIBRARY[iColor % COLORS_LIBRARY.Length]; else color = COLORS_LIBRARY[iColor % COLORS_LIBRARY.Length]; // color = COLORS_HEURISTIC[iColor % COLORS_HEURISTIC.Length]; TransitionChromInfo tranPeakInfoGraph = null; if (bestPeakData == i) tranPeakInfoGraph = tranPeakInfo; var graphItem = new ChromGraphItem(nodeGroup, null, graphData.InfoPrimary, tranPeakInfoGraph, timeRegressionFunction, GetAnnotationFlags(i, maxPeakData, maxPeakHeights), null, 0, false, false, step, color, fontSize, width); _graphHelper.AddChromatogram(PaneKey.PRECURSORS, graphItem); } iColor++; } }
private void AssertChromatogramWindow(SrmDocument document, ChromatogramSet chromatogramSet, double expectedStartTime, double expectedEndTime, params ChromatogramGroupInfo[] chromGroupInfos) { ChromatogramGroupInfo[] basePeakChromatograms; Assert.IsTrue(document.Settings.MeasuredResults.TryLoadAllIonsChromatogram(chromatogramSet, ChromExtractor.base_peak, true, out basePeakChromatograms)); if (basePeakChromatograms.Length > 0) { double runStartTime = basePeakChromatograms.Min(chromGroup => chromGroup.Times[0]); double runEndTime = basePeakChromatograms.Max(chromGroup => chromGroup.Times[chromGroup.Times.Length - 1]); expectedStartTime = Math.Max(runStartTime, expectedStartTime); expectedEndTime = Math.Min(runEndTime, expectedEndTime); } const double delta = .15; foreach (var chromGroupInfo in chromGroupInfos) { double startTime = chromGroupInfo.Times[0]; double endTime = chromGroupInfo.Times[chromGroupInfo.Times.Length - 1]; if (Math.Abs(expectedStartTime - startTime) > delta) { Assert.AreEqual(expectedStartTime, startTime, delta); } if (Math.Abs(expectedEndTime - endTime) > delta) { Assert.AreEqual(expectedEndTime, endTime, delta); } } }
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); } } }
private void SetRetentionTimeIndicators(ChromGraphItem chromGraphPrimary, SrmSettings settings, ChromatogramSet chromatograms, PeptideDocNode[] nodePeps, TransitionGroupDocNode[] nodeGroups, string lookupSequence, ExplicitMods lookupMods) { // FUTURE: Fix this when we can predict retention time for small molecules if (lookupSequence == null) { return; } SetRetentionTimePredictedIndicator(chromGraphPrimary, settings, chromatograms, nodePeps, lookupSequence, lookupMods); SetRetentionTimeIdIndicators(chromGraphPrimary, settings, nodeGroups, lookupSequence, lookupMods); }
private bool EnsureChromInfo(MeasuredResults results, ChromatogramSet chromatograms, TransitionGroupDocNode[] nodeGroups, IdentityPath[] groupPaths, ChromExtractor extractor, out bool changedGroups, out bool changedGroupIds) { if (UpdateGroups(nodeGroups, groupPaths, out changedGroups, out changedGroupIds) && _extractor == extractor) return true; _extractor = extractor; bool success = false; try { // Get chromatogram sets for all transition groups, recording unique // file paths in the process. var listArrayChromInfo = new List<ChromatogramGroupInfo[]>(); var listFiles = new List<MsDataFileUri>(); ChromatogramGroupInfo[] arrayAllIonsChromInfo; if (!results.TryLoadAllIonsChromatogram(chromatograms, extractor, true, out arrayAllIonsChromInfo)) { return false; } else { listArrayChromInfo.Add(arrayAllIonsChromInfo); foreach (var chromInfo in arrayAllIonsChromInfo) { var filePath = chromInfo.FilePath; if (!listFiles.Contains(filePath)) listFiles.Add(filePath); } } _hasMergedChromInfo = false; _arrayChromInfo = new ChromatogramGroupInfo[listFiles.Count][]; for (int i = 0; i < _arrayChromInfo.Length; i++) { var arrayNew = new ChromatogramGroupInfo[listArrayChromInfo.Count]; for (int j = 0; j < arrayNew.Length; j++) { var arrayChromInfo = listArrayChromInfo[j]; if (arrayChromInfo == null) continue; foreach (var chromInfo in arrayChromInfo) { if (arrayNew[j] == null && Equals(listFiles[i], chromInfo.FilePath)) arrayNew[j] = chromInfo; } } _arrayChromInfo[i] = arrayNew; } success = true; } finally { // Make sure the info array is set to null on failure. if (!success) _arrayChromInfo = null; } return true; }
public GroupIdentifier GetGroupIdentifier(SrmSettings settings, ChromatogramSet chromatogramSet) { AnnotationDef annotationDef = settings.DataSettings.AnnotationDefs.FirstOrDefault(a => a.Name == ControlAnnotation); if (annotationDef == null) { return default(GroupIdentifier); } return GroupIdentifier.MakeGroupIdentifier(chromatogramSet.Annotations.GetAnnotation(annotationDef)); }
private static PeakMatch GetPeakMatch(SrmDocument doc, ChromatogramSet chromSet, IPathContainer fileInfo, TransitionGroupDocNode nodeTranGroup, PeakMatchData referenceTarget, IEnumerable<PeakMatchData> referenceMatchData) { if (referenceTarget == null) return new PeakMatch(0, 0); var mzMatchTolerance = (float) doc.Settings.TransitionSettings.Instrument.MzMatchTolerance; ChromatogramGroupInfo[] loadInfos; if (!nodeTranGroup.HasResults || !doc.Settings.MeasuredResults.TryLoadChromatogram(chromSet, null, nodeTranGroup, mzMatchTolerance, true, out loadInfos)) return null; var chromGroupInfo = loadInfos.FirstOrDefault(info => Equals(info.FilePath, fileInfo.FilePath)); if (chromGroupInfo == null || chromGroupInfo.NumPeaks == 0 || !chromGroupInfo.Times.Any()) return null; var matchData = new List<PeakMatchData>(); double totalArea = chromGroupInfo.TransitionPointSets.Sum(chromInfo => chromInfo.Peaks.Sum(peak => peak.Area)); for (int i = 0; i < chromGroupInfo.NumPeaks; i++) matchData.Add(new PeakMatchData(nodeTranGroup, chromGroupInfo, mzMatchTolerance, i, totalArea)); // TODO: Try to improve this. Align peaks in area descending order until peaks do not match var alignments = new List<PeakAlignment>(); bool referenceAligned = false; var referenceIter = referenceMatchData.OrderByDescending(d => d.PercentArea).GetEnumerator(); var curIter = matchData.OrderByDescending(d => d.PercentArea).GetEnumerator(); while (referenceIter.MoveNext() && curIter.MoveNext()) { var alignAttempt = new PeakAlignment(referenceIter.Current, curIter.Current); if (!TryInsertPeakAlignment(alignments, alignAttempt)) break; if (referenceTarget == alignAttempt.ReferencePeak) { // Reference target aligned referenceAligned = true; matchData = new List<PeakMatchData> {alignAttempt.AlignedPeak}; break; } } PeakMatch manualMatch = null; if (!referenceAligned) { PeakAlignment prev, next; GetSurroundingAlignments(alignments, referenceTarget, out prev, out next); if (prev != null || next != null) { // At least one alignment occurred var chromGroupMinTime = chromGroupInfo.Times.First(); var chromGroupMaxTime = chromGroupInfo.Times.Last(); float scale = (chromGroupMaxTime - chromGroupMinTime)/(referenceTarget.MaxTime - referenceTarget.MinTime); manualMatch = MakePeakMatchBetween(scale, referenceTarget, prev, next); if (chromGroupMinTime >= manualMatch.EndTime || manualMatch.StartTime >= chromGroupMaxTime) manualMatch = null; float curMinTime = prev == null ? chromGroupMinTime : prev.AlignedPeak.RetentionTime; float curMaxTime = next == null ? chromGroupMaxTime : next.AlignedPeak.RetentionTime; matchData = matchData.Where(d => curMinTime < d.RetentionTime && d.RetentionTime < curMaxTime).ToList(); } } PeakMatchData bestMatch = null; double bestScore = double.MinValue; foreach (var other in matchData) { var score = referenceTarget.GetMatchScore(other); if (bestMatch == null || score > bestScore) { bestScore = score; bestMatch = other; } } // If no matching peak with high enough score was found, but there is a matching // peak or some peak with a low score. if (bestMatch == null || (!referenceAligned && bestScore < INTEGRATE_SCORE_THRESHOLD && manualMatch != null)) return manualMatch; if (referenceTarget.ShiftLeft == 0 && referenceTarget.ShiftRight == 0) return new PeakMatch(bestMatch.RetentionTime); var range = bestMatch.EndTime - bestMatch.StartTime; var startTime = bestMatch.StartTime + (referenceTarget.ShiftLeft*range); var endTime = bestMatch.EndTime + (referenceTarget.ShiftRight*range); return startTime <= bestMatch.RetentionTime && bestMatch.RetentionTime <= endTime ? new PeakMatch(startTime, endTime) : new PeakMatch(bestMatch.RetentionTime); // If the shifted boundaries exclude the peak itself, don't change the boundaries }
private ChromatogramSet StripPathInfo(ChromatogramSet chromatogramSet) { return chromatogramSet.ChangeMSDataFileInfos(chromatogramSet.MSDataFileInfos .Select(StripFilePathInfo).ToArray()); }
private SrmDocument ImportResults(SrmDocument doc, string nameResult, IEnumerable<MsDataFileUri> dataSources, OptimizableRegression optimizationFunction) { var results = doc.Settings.MeasuredResults; var chrom = GetChromatogramByName(nameResult, results); if (chrom == null) { // If the chromatogram, is not in the current set, then delete the cache // file to make sure it is not on disk before starting. FileEx.SafeDelete(ChromatogramCache.FinalPathForName(DocumentFilePath, nameResult), true); chrom = new ChromatogramSet(nameResult, dataSources, Annotations.EMPTY, optimizationFunction); if (results == null) results = new MeasuredResults(new[] {chrom}); else { // Add the new result to the end. var listChrom = new List<ChromatogramSet>(results.Chromatograms) {chrom}; results = results.ChangeChromatograms(listChrom.ToArray()); } } else { // Append to an existing chromatogram set var dataFilePaths = new List<MsDataFileUri>(chrom.MSDataFilePaths); foreach (var sourcePath in dataSources) { if (!dataFilePaths.Contains(sourcePath)) dataFilePaths.Add(sourcePath); } // If no new paths added, just return without changing. if (dataFilePaths.Count == chrom.FileCount) return doc; int replaceIndex = results.Chromatograms.IndexOf(chrom); var arrayChrom = results.Chromatograms.ToArray(); arrayChrom[replaceIndex] = chrom.ChangeMSDataFilePaths(dataFilePaths); results = results.ChangeChromatograms(arrayChrom); } if (results != null && Program.DisableJoining) results = results.ChangeIsJoiningDisabled(true); return doc.ChangeMeasuredResults(results); }
private IEnumerable<Tuple<PeptideDocNode, TransitionGroupDocNode, ChromatogramGroupInfo[]>> LoadAllChromatograms(SrmDocument document, ChromatogramSet chromatogramSet) { foreach (var peptide in document.Molecules) { foreach (var transitionGroup in peptide.TransitionGroups) { ChromatogramGroupInfo[] infos; document.Settings.MeasuredResults.TryLoadChromatogram(chromatogramSet, peptide, transitionGroup, (float) TransitionInstrument.DEFAULT_MZ_MATCH_TOLERANCE, true, out infos); yield return new Tuple<PeptideDocNode, TransitionGroupDocNode, ChromatogramGroupInfo[]>(peptide, transitionGroup, infos); } } }
private void DisplayTotals(IRegressionFunction timeRegressionFunction, ChromatogramSet chromatograms, float mzMatchTolerance, int countLabelTypes, ref double bestStartTime, ref double bestEndTime) { // Construct and add graph items for all relevant transition groups. float fontSize = FontSize; int lineWidth = LineWidth; int iCharge = -1; int? charge = null; var chromGroupInfos = ChromGroupInfos; for (int i = 0; i < _nodeGroups.Length; i++) { var nodeGroup = _nodeGroups[i]; var chromGroupInfo = chromGroupInfos[i]; if (chromGroupInfo == null) continue; ChromFileInfoId fileId = chromatograms.FindFile(chromGroupInfo); // Collect the chromatogram info for the transition children // of this transition group. ChromatogramInfo infoPrimary = null; TransitionChromInfo tranPeakInfo = null; float maxPeakHeight = float.MinValue; var listChromInfo = new List<ChromatogramInfo>(); foreach (TransitionDocNode nodeTran in nodeGroup.Children) { var info = chromGroupInfo.GetTransitionInfo((float)nodeTran.Mz, mzMatchTolerance); if (info == null) continue; listChromInfo.Add(info); // Keep track of which chromatogram owns the tallest member of // the peak on the document tree. var transitionChromInfo = GetTransitionChromInfo(nodeTran, _chromIndex, fileId, 0); if (transitionChromInfo == null) continue; if (transitionChromInfo.Height > maxPeakHeight) { maxPeakHeight = transitionChromInfo.Height; tranPeakInfo = transitionChromInfo; infoPrimary = info; } // Adjust best peak window used to zoom the graph to the best peak AddBestPeakTimes(transitionChromInfo, ref bestStartTime, ref bestEndTime); } // If any transitions are present for this group, add a graph item to // the graph for it. if (listChromInfo.Count > 0) { if (infoPrimary == null) infoPrimary = listChromInfo[0]; // Sum the intensities of all transitions into the first chromatogram infoPrimary.SumIntensities(listChromInfo); // Apply any transform the user has chosen infoPrimary.Transform(Transform); int iColor = GetColorIndex(nodeGroup, countLabelTypes, ref charge, ref iCharge); Color color = COLORS_GROUPS[iColor % COLORS_GROUPS.Length]; bool[] annotateAll = new bool[infoPrimary.NumPeaks]; for (int j = 0; j < annotateAll.Length; j++) { var peak = infoPrimary.GetPeak(j); if (peak.IsForcedIntegration) continue; // Exclude any peaks between the boundaries of the chosen peak. if (tranPeakInfo != null && tranPeakInfo.StartRetentionTime < peak.RetentionTime && peak.RetentionTime < tranPeakInfo.EndRetentionTime) continue; annotateAll[j] = true; } var graphItem = new ChromGraphItem(nodeGroup, null, infoPrimary, tranPeakInfo, timeRegressionFunction, annotateAll, null, 0, false, false, 0, color, fontSize, lineWidth); var graphPaneKey = new PaneKey(nodeGroup); _graphHelper.AddChromatogram(graphPaneKey, graphItem); } } }
public ManageResultsAction(ChromatogramSet chromatograms) { Chromatograms = chromatograms; }
private void DisplayTransitions(IRegressionFunction timeRegressionFunction, TransitionDocNode nodeTranSelected, ChromatogramSet chromatograms, float mzMatchTolerance, TransitionGroupDocNode nodeGroup, ChromatogramGroupInfo chromGroupInfo, PaneKey graphPaneKey, DisplayTypeChrom displayType, ref double bestStartTime, ref double bestEndTime) { var fileId = chromatograms.FindFile(chromGroupInfo); // Get points for all transitions, and pick maximum peaks. ChromatogramInfo[] arrayChromInfo; var displayTrans = GetDisplayTransitions(nodeGroup, displayType).ToArray(); int numTrans = displayTrans.Length; int numSteps = 0; bool allowEmpty = false; if (IsSingleTransitionDisplay && nodeTranSelected != null) { if (!displayTrans.Contains(nodeTranSelected)) { arrayChromInfo = new ChromatogramInfo[0]; displayTrans = new TransitionDocNode[0]; numTrans = 0; } else { arrayChromInfo = chromGroupInfo.GetAllTransitionInfo((float) nodeTranSelected.Mz, mzMatchTolerance, chromatograms.OptimizationFunction); if (chromatograms.OptimizationFunction != null) { // Make sure the number of steps matches what will show up in the summary // graphs, or the colors won't match up. int numStepsExpected = chromatograms.OptimizationFunction.StepCount*2 + 1; if (arrayChromInfo.Length != numStepsExpected) { arrayChromInfo = ResizeArrayChromInfo(arrayChromInfo, numStepsExpected); allowEmpty = true; } } numTrans = arrayChromInfo.Length; displayTrans = new TransitionDocNode[numTrans]; for (int i = 0; i < numTrans; i++) displayTrans[i] = nodeTranSelected; } numSteps = numTrans/2; } else { arrayChromInfo = new ChromatogramInfo[numTrans]; for (int i = 0; i < numTrans; i++) { var nodeTran = displayTrans[i]; // Get chromatogram info for this transition arrayChromInfo[i] = chromGroupInfo.GetTransitionInfo((float) nodeTran.Mz, mzMatchTolerance); } } int bestPeakTran = -1; TransitionChromInfo tranPeakInfo = null; float maxPeakHeight = float.MinValue; int numPeaks = chromGroupInfo.NumPeaks; var maxPeakTrans = new int[numPeaks]; var maxPeakHeights = new float[numPeaks]; for (int i = 0; i < numPeaks; i++) maxPeakHeights[i] = float.MinValue; var transform = Transform; // Prepare arrays of values for library dot-product double[] expectedIntensities = null; double[][] peakAreas = null; bool isShowingMs = displayTrans.Any(nodeTran => nodeTran.IsMs1); bool isShowingMsMs = displayTrans.Any(nodeTran => !nodeTran.IsMs1); bool isFullScanMs = DocumentUI.Settings.TransitionSettings.FullScan.IsEnabledMs && isShowingMs; if ((isFullScanMs && !isShowingMsMs && nodeGroup.HasIsotopeDist) || (!isFullScanMs && nodeGroup.HasLibInfo)) { expectedIntensities = new double[numTrans]; peakAreas = new double[numPeaks][]; for (int i = 0; i < numPeaks; i++) peakAreas[i] = new double[numTrans]; } // Find the transition with the maximum peak height for the best peak for (int i = 0; i < numTrans; i++) { var nodeTran = displayTrans[i]; int step = (numSteps > 0 ? i - numSteps : 0); var transitionChromInfo = GetTransitionChromInfo(nodeTran, _chromIndex, fileId, step); if (transitionChromInfo == null) continue; if (maxPeakHeight < transitionChromInfo.Height) { maxPeakHeight = transitionChromInfo.Height; bestPeakTran = i; tranPeakInfo = transitionChromInfo; } AddBestPeakTimes(transitionChromInfo, ref bestStartTime, ref bestEndTime); } for (int i = 0; i < numTrans; i++) { var nodeTran = displayTrans[i]; // Store library intensities for dot-product if (expectedIntensities != null) { if (isFullScanMs) expectedIntensities[i] = nodeTran.HasDistInfo ? nodeTran.IsotopeDistInfo.Proportion : 0; else expectedIntensities[i] = nodeTran.HasLibInfo ? nodeTran.LibInfo.Intensity : 0; } var info = arrayChromInfo[i]; if (info == null) continue; // Apply any active transform info.Transform(transform); for (int j = 0; j < numPeaks; j++) { var peak = info.GetPeak(j); // Exclude any peaks between the boundaries of the chosen peak. if (IntersectPeaks(peak, tranPeakInfo)) continue; // Store peak intensity for dot-product if (peakAreas != null) peakAreas[j][i] = peak.Area; // Keep track of which transition has the max height for each peak if (maxPeakHeights[j] < peak.Height) { maxPeakHeights[j] = peak.Height; maxPeakTrans[j] = i; } } } // Calculate library dot-products, if possible double[] dotProducts = null; double bestProduct = 0; int minProductTrans = isFullScanMs ? TransitionGroupDocNode.MIN_DOT_PRODUCT_MS1_TRANSITIONS : TransitionGroupDocNode.MIN_DOT_PRODUCT_TRANSITIONS; if (peakAreas != null && numTrans >= minProductTrans) { var tranGroupChromInfo = GetTransitionGroupChromInfo(nodeGroup, fileId, _chromIndex); double? dotProduct = null; if (tranGroupChromInfo != null) { dotProduct = isFullScanMs ? tranGroupChromInfo.IsotopeDotProduct : tranGroupChromInfo.LibraryDotProduct; } if (dotProduct.HasValue) { bestProduct = dotProduct.Value; var statExpectedIntensities = new Statistics(expectedIntensities); for (int i = 0; i < peakAreas.Length; i++) { var statPeakAreas = new Statistics(peakAreas[i]); double dotProductCurrent = statPeakAreas.NormalizedContrastAngleSqrt(statExpectedIntensities); // Only show products that are greater than the best peak product, // and by enough to be a significant improvement. Also the library product // on the group node is stored as a float, which means the version // hear calculated as a double can be larger, but really represent // the same number. if (dotProductCurrent > bestProduct && dotProductCurrent > 0.5 && dotProductCurrent - bestProduct > 0.05) { if (dotProducts == null) dotProducts = new double[numPeaks]; dotProducts[i] = dotProductCurrent; } } } } // Create graph items int iColor = 0; int lineWidth = LineWidth; float fontSize = FontSize; // 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 = GetDisplayType(DocumentUI, nodeGroup); int colorOffset = 0; if(displayType == DisplayTypeChrom.products && (nodeDisplayType != DisplayTypeChrom.single || (nodeDisplayType == DisplayTypeChrom.single && chromatograms.OptimizationFunction == null))) { colorOffset = GetDisplayTransitions(nodeGroup, DisplayTypeChrom.precursors).Count(); } for (int i = 0; i < numTrans; i++) { var info = arrayChromInfo[i]; if (info == null && !allowEmpty) continue; var nodeTran = displayTrans[i]; int step = numSteps != 0 ? i - numSteps : 0; Color color; bool shade = false; int width = lineWidth; if ((numSteps == 0 && ReferenceEquals(nodeTran, nodeTranSelected) || (numSteps > 0 && step == 0))) { color = ChromGraphItem.ColorSelected; shade = true; width++; } else { color = COLORS_LIBRARY[(iColor + colorOffset) % COLORS_LIBRARY.Length]; } TransitionChromInfo tranPeakInfoGraph = null; if (bestPeakTran == i) tranPeakInfoGraph = tranPeakInfo; var scanName = nodeTran.FragmentIonName; if (nodeTran.Transition.Charge != 1) // Positive singly charged is uninteresting scanName += Transition.GetChargeIndicator(nodeTran.Transition.Charge); if (nodeTran.Transition.MassIndex != 0) scanName += Environment.NewLine + Transition.GetMassIndexText(nodeTran.Transition.MassIndex); var fullScanInfo = new FullScanInfo { ChromInfo = info, ScanName = scanName }; if (fullScanInfo.ChromInfo != null && fullScanInfo.ChromInfo.ExtractionWidth > 0) _enableTrackingDot = true; var graphItem = new ChromGraphItem(nodeGroup, nodeTran, info, tranPeakInfoGraph, timeRegressionFunction, GetAnnotationFlags(i, maxPeakTrans, maxPeakHeights), dotProducts, bestProduct, isFullScanMs, false, step, color, fontSize, width, fullScanInfo); _graphHelper.AddChromatogram(graphPaneKey, graphItem); if (shade) { ShadeGraph(tranPeakInfo,info,timeRegressionFunction,dotProducts,bestProduct,isFullScanMs,step,fontSize,width,fullScanInfo,graphPaneKey); } iColor++; } var graphPane = _graphHelper.GetGraphPane(graphPaneKey); if (graphPane == null) _enableTrackingDot = false; if (_enableTrackingDot) { graphPane.CurveList.Insert(FULLSCAN_TRACKING_INDEX, CreateScanPoint(Color.Black)); graphPane.CurveList.Insert(FULLSCAN_SELECTED_INDEX, CreateScanPoint(Color.Red)); } }
public void MsDataFileUriEncodingTest() { var fname = "test.mzML"; var pathSample = SampleHelp.EncodePath(fname, null, -1, null, true, false); var lockmassParametersA = new LockMassParameters(1.23, 3.45, 4.56); var lockmassParametersB = new LockMassParameters(1.23, null, 4.56); Assert.IsTrue(lockmassParametersA.CompareTo(LockMassParameters.EMPTY) > 0); Assert.IsTrue(lockmassParametersA.CompareTo(null) < 0); Assert.IsTrue(lockmassParametersB.CompareTo(lockmassParametersA) < 0); Assert.IsTrue(lockmassParametersA.CompareTo(new LockMassParameters(1.23, 3.45, 4.56)) == 0); var c = new ChromatogramSet("test", new[] { MsDataFileUri.Parse(pathSample) }); Assert.AreEqual(fname, c.MSDataFilePaths.First().GetFilePath()); Assert.IsTrue(c.MSDataFilePaths.First().GetCentroidMs1()); Assert.IsFalse(c.MSDataFilePaths.First().GetCentroidMs2()); pathSample = SampleHelp.EncodePath(fname, null, -1, lockmassParametersA,false,true); c = new ChromatogramSet("test", new[] { MsDataFileUri.Parse(pathSample) }); Assert.AreEqual(lockmassParametersA, c.MSDataFilePaths.First().GetLockMassParameters()); Assert.IsTrue(c.MSDataFilePaths.First().GetCentroidMs2()); Assert.IsFalse(c.MSDataFilePaths.First().GetCentroidMs1()); pathSample = SampleHelp.EncodePath(fname, "test_0", 1, lockmassParametersB,false,false); c = new ChromatogramSet("test", new[] { MsDataFileUri.Parse(pathSample) }); Assert.AreEqual(lockmassParametersB, c.MSDataFilePaths.First().GetLockMassParameters()); Assert.AreEqual("test_0", c.MSDataFilePaths.First().GetSampleName()); Assert.AreEqual(1, c.MSDataFilePaths.First().GetSampleIndex()); Assert.IsFalse(c.MSDataFilePaths.First().GetCentroidMs1()); Assert.IsFalse(c.MSDataFilePaths.First().GetCentroidMs2()); }
private bool EnsureChromInfo(MeasuredResults results, ChromatogramSet chromatograms, PeptideDocNode[] nodePeps, TransitionGroupDocNode[] nodeGroups, IdentityPath[] groupPaths, float mzMatchTolerance, out bool changedGroups, out bool changedGroupIds) { if (UpdateGroups(nodeGroups, groupPaths, out changedGroups, out changedGroupIds) && !_extractor.HasValue) return true; _extractor = null; bool success = false; try { // Get chromatogram sets for all transition groups, recording unique // file paths in the process. var listArrayChromInfo = new List<ChromatogramGroupInfo[]>(); var listFiles = new List<MsDataFileUri>(); for (int i = 0; i < nodeGroups.Length; i++) { ChromatogramGroupInfo[] arrayChromInfo; if (!results.TryLoadChromatogram( chromatograms, nodePeps[i], nodeGroups[i], mzMatchTolerance, true, out arrayChromInfo)) { listArrayChromInfo.Add(null); continue; } listArrayChromInfo.Add(arrayChromInfo); foreach (var chromInfo in arrayChromInfo) { var filePath = chromInfo.FilePath; if (!listFiles.Contains(filePath)) listFiles.Add(filePath); } } // If no data was found, then return false if (listFiles.Count == 0) return false; // Make a list of chromatogram info by unique file path corresponding // to the groups passed in. _arrayChromInfo = new ChromatogramGroupInfo[listFiles.Count][]; for (int i = 0; i < _arrayChromInfo.Length; i++) { var arrayNew = new ChromatogramGroupInfo[listArrayChromInfo.Count]; for (int j = 0; j < arrayNew.Length; j++) { var arrayChromInfo = listArrayChromInfo[j]; if (arrayChromInfo == null) continue; foreach (var chromInfo in arrayChromInfo) { if (arrayNew[j] == null && Equals(listFiles[i], chromInfo.FilePath)) arrayNew[j] = chromInfo; } } _arrayChromInfo[i] = arrayNew; } // If multiple replicate files contain mutually exclusive data, create "all files" option. var mergedChromGroupInfo = GetMergedChromInfo(); _hasMergedChromInfo = (mergedChromGroupInfo != null); if (_hasMergedChromInfo) { var arrayNew = new ChromatogramGroupInfo[_arrayChromInfo.Length + 1][]; arrayNew[0] = mergedChromGroupInfo; for (int i = 1; i < arrayNew.Length; i++) arrayNew[i] = _arrayChromInfo[i - 1]; _arrayChromInfo = arrayNew; } success = true; } finally { // Make sure the info array is set to null on failure. if (!success) _arrayChromInfo = null; } return true; }
public void ChangeChromatogramSet(EditDescription editDescription, ChromatogramSet chromatogramSet) { ModifyDocument(editDescription, document => { var measuredResults = document.Settings.MeasuredResults; var chromatograms = measuredResults.Chromatograms.ToArray(); chromatograms[ReplicateIndex] = chromatogramSet; measuredResults = measuredResults.ChangeChromatograms(chromatograms); return document.ChangeMeasuredResults(measuredResults); } ); }
public ListBoxItem(ChromatogramSet chromatogramSet) { ChromatogramSet = chromatogramSet; }
private static void SetRetentionTimePredictedIndicator(ChromGraphItem chromGraphPrimary, SrmSettings settings, ChromatogramSet chromatograms, PeptideDocNode[] nodePeps, string lookupSequence, ExplicitMods lookupMods) { // Set predicted retention time on the first graph item to make // line, label and shading show. var regression = settings.PeptideSettings.Prediction.RetentionTime; if (regression != null && Settings.Default.ShowRetentionTimePred) { string modSeq = settings.GetModifiedSequence(lookupSequence, IsotopeLabelType.light, lookupMods); var fileId = chromatograms.FindFile(chromGraphPrimary.Chromatogram); double? predictedRT = regression.GetRetentionTime(modSeq, fileId); double window = regression.TimeWindow; chromGraphPrimary.RetentionPrediction = predictedRT; chromGraphPrimary.RetentionWindow = window; } chromGraphPrimary.RetentionExplicit = (nodePeps.Length == 1) ? nodePeps[0].ExplicitRetentionTime : null; }
public bool Equals(ChromatogramSet obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; // Why isn't "OptimizationFunction" included in "Equals"? if (!base.Equals(obj)) return false; if (!ArrayUtil.EqualsDeep(obj.MSDataFileInfos, MSDataFileInfos)) return false; if (!Equals(obj.Annotations, Annotations)) return false; if (!obj.UseForRetentionTimeFilter == UseForRetentionTimeFilter) return false; if (!Equals(obj.OptimizationFunction, OptimizationFunction)) return false; if (obj._rescoreCount != _rescoreCount) return false; if (!Equals(obj.AnalyteConcentration, AnalyteConcentration)) return false; if (!Equals(obj.SampleType, SampleType)) return false; return true; }
private void DisplayAllIonsSummary(IRegressionFunction timeRegressionFunction, TransitionDocNode nodeTranSelected, ChromatogramSet chromatograms, ChromExtractor extractor, ref double bestStartTime, ref double bestEndTime) { if (ChromGroupInfos.Length == 0) { return; } var chromGroupInfo = ChromGroupInfos[0]; var info = chromGroupInfo.GetTransitionInfo(0, 0); var fileId = chromatograms.FindFile(chromGroupInfo); var nodeGroup = _nodeGroups != null ? _nodeGroups[0] : null; if (nodeGroup == null) nodeTranSelected = null; TransitionChromInfo tranPeakInfo = null; if (nodeGroup != null) { float maxPeakHeight = float.MinValue; foreach (TransitionDocNode nodeTran in nodeGroup.Children) { // Keep track of which chromatogram owns the tallest member of // the peak on the document tree. var transitionChromInfo = GetTransitionChromInfo(nodeTran, _chromIndex, fileId, 0); if (transitionChromInfo == null) continue; if (nodeTranSelected != null) { if (ReferenceEquals(nodeTran, nodeTranSelected)) tranPeakInfo = transitionChromInfo; } else if (transitionChromInfo.Height > maxPeakHeight) { maxPeakHeight = transitionChromInfo.Height; tranPeakInfo = transitionChromInfo; } // Adjust best peak window used to zoom the graph to the best peak AddBestPeakTimes(transitionChromInfo, ref bestStartTime, ref bestEndTime); } } // Apply active transform info.Transform(Transform); int numPeaks = info.NumPeaks; var annotationFlags = new bool[numPeaks]; for (int i = 0; i < numPeaks; i++) { // Exclude any peaks between the boundaries of the chosen peak. annotationFlags[i] = !IntersectPeaks(info.GetPeak(i), tranPeakInfo); } var graphItem = new ChromGraphItem(nodeGroup, nodeTranSelected, info, tranPeakInfo, timeRegressionFunction, annotationFlags, null, 0, true, true, 0, COLORS_GROUPS[(int)extractor], FontSize, LineWidth); _graphHelper.AddChromatogram(new PaneKey(nodeGroup), graphItem); }
public DateTime? GetRunStartTime(ChromatogramSet chromatogramSet) { DateTime? runStartTime = null; foreach (var fileInfo in chromatogramSet.MSDataFileInfos) { if (!fileInfo.RunStartTime.HasValue) { continue; } if (!runStartTime.HasValue || runStartTime.Value > fileInfo.RunStartTime.Value) { runStartTime = fileInfo.RunStartTime; } } return runStartTime; }
public double? GetPeptideConcentration(ChromatogramSet chromatogramSet) { double concentrationMultiplier = PeptideQuantifier.PeptideDocNode.ConcentrationMultiplier.GetValueOrDefault(1.0); return chromatogramSet.AnalyteConcentration*concentrationMultiplier; }