private const string BULLET = "\u2022 "; // Not L10N #endregion Fields #region Constructors public ShareTypeDlg(SrmDocument document) { InitializeComponent(); int lineHeight = labelMessage.Height; StringBuilder sbLabel = new StringBuilder(); sbLabel.AppendLine(Resources.ShareTypeDlg_ShareTypeDlg_The_document_can_be_shared_either_in_its_complete_form_or_in_a_minimal_form_intended_for_read_only_use_with); var listMinimizations = new List<string>(); if (document.Settings.HasBackgroundProteome) listMinimizations.Add(BULLET + Resources.ShareTypeDlg_ShareTypeDlg_its_background_proteome_disconnected); if (document.Settings.HasRTCalcPersisted) listMinimizations.Add(BULLET + Resources.ShareTypeDlg_ShareTypeDlg_its_retention_time_calculator_minimized_to_contain_only_standard_peptides_and_library_peptides_used_in_the_document); if (document.Settings.HasLibraries) listMinimizations.Add(BULLET + Resources.ShareTypeDlg_ShareTypeDlg_all_libraries_minimized_to_contain_only_precursors_used_in_the_document); int lastIndex = listMinimizations.Count - 1; if (lastIndex < 0) { throw new InvalidOperationException( string.Format(Resources.ShareTypeDlg_ShareTypeDlg_Invalid_use_of__0__for_document_without_background_proteome_retention_time_calculator_or_libraries, typeof(ShareTypeDlg).Name)); } if (listMinimizations.Count > 0) sbLabel.AppendLine().Append(TextUtil.LineSeparate(listMinimizations)).AppendLine(); sbLabel.AppendLine().Append(Resources.ShareTypeDlg_ShareTypeDlg_Choose_the_appropriate_sharing_option_below); labelMessage.Text = sbLabel.ToString(); Height += Math.Max(0, labelMessage.Height - lineHeight * 3); }
public static void CheckAll(SrmDocument document) { using (var checkReportCompatibility = new CheckReportCompatibility(document)) { checkReportCompatibility.CheckAll(); } }
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 RemoteChromDataProvider(SrmDocument document, IRetentionTimePredictor retentionTimePredictor, ChromFileInfo chromFileInfo, ProgressStatus progressStatus, int startPercent, int endPercent, ILoadMonitor loader) : base(chromFileInfo, progressStatus, startPercent, endPercent, loader) { _document = document; ChorusUrl chorusUrl = (ChorusUrl)chromFileInfo.FilePath; _chorusAccount = chorusUrl.FindChorusAccount(Settings.Default.ChorusAccountList); var chromatogramRequestProviders = new List<ChromatogramRequestProvider>(); foreach (bool firstPass in new[] {true, false}) { if (null == retentionTimePredictor && !firstPass) { continue; } var chromatogramRequestProvider = new ChromatogramRequestProvider(document, chorusUrl, retentionTimePredictor, firstPass); if (0 == chromatogramRequestProvider.ChromKeys.Count) { continue; } chromatogramRequestProviders.Add(chromatogramRequestProvider); } _chromatogramRequestProviders = chromatogramRequestProviders.ToArray(); _chromTaskLists = new ChromTaskList[_chromatogramRequestProviders.Length]; }
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 LoadBackground(IDocumentContainer container, SrmDocument document, SrmDocument docCurrent) { var lib = GetOptimizationLibrary(docCurrent); if (lib != null && !lib.IsNone && !lib.IsUsable) lib = LoadLibrary(container, lib); if (lib == null || !ReferenceEquals(document.Id, container.Document.Id)) { // Loading was cancelled or document changed EndProcessing(document); return false; } SrmDocument docNew; do { // Change the document to use the new library docCurrent = container.Document; if (!ReferenceEquals(GetOptimizationLibrary(docCurrent), GetOptimizationLibrary(container.Document))) return false; docNew = docCurrent.ChangeSettings(docCurrent.Settings.ChangeTransitionPrediction(predict => predict.ChangeOptimizationLibrary(lib))); } while (!CompleteProcessing(container, docNew, docCurrent)); return true; }
public SrmDocumentSharing(SrmDocument document, string documentPath, string sharedPath, bool completeSharing) { Document = document; DocumentPath = documentPath; SharedPath = sharedPath; CompleteSharing = completeSharing; }
public RefineDlg(SrmDocument document) { _document = document; _settings = document.Settings; InitializeComponent(); Icon = Resources.Skyline; // Fill label type combo box comboRefineLabelType.Items.Add(string.Empty); comboRefineLabelType.Items.Add(IsotopeLabelType.LIGHT_NAME); foreach (var typedMods in _settings.PeptideSettings.Modifications.GetHeavyModifications()) comboRefineLabelType.Items.Add(typedMods.LabelType.Name); comboRefineLabelType.SelectedIndex = 0; comboReplicateUse.SelectedIndex = 0; var settings = document.Settings; if (!settings.HasResults) { tabControl1.TabPages.Remove(tabResults); } if (settings.PeptideSettings.Libraries.HasLibraries) { labelMinDotProduct.Enabled = textMinDotProduct.Enabled = groupLibCorr.Enabled = true; } if (settings.TransitionSettings.FullScan.IsHighResPrecursor) { labelMinIdotProduct.Enabled = textMinIdotProduct.Enabled = groupLibCorr.Enabled = true; } }
public static string IsNotLoadedDocumentExplained(SrmDocument document) { // Not loaded if the predictor is not usable var calc = GetIonMobilityLibrary(document); if (calc == null || calc.IsNone || calc.IsUsable) return null; return "IonMobilityLibraryManager : GetIonMobilityLibrary(document) not usable and not none"; // Not L10N }
protected override GraphData CreateGraphData(SrmDocument document, PeptideGroupDocNode selectedProtein, TransitionGroupDocNode selectedGroup, DisplayTypeChrom displayType) { int? result = null; if (RTLinearRegressionGraphPane.ShowReplicate == ReplicateDisplay.single) result = GraphSummary.ResultsIndex; return new RTGraphData(document, selectedGroup, selectedProtein, result, displayType, GraphSummary.StateProvider.GetRetentionTimeTransformOperation()); }
public CheckReportCompatibility(SrmDocument document) { IDocumentContainer documentContainer = new MemoryDocumentContainer(); Assert.IsTrue(documentContainer.SetDocument(document, null)); _database = new Database(document.Settings); _database.AddSrmDocument(document); _dataSchema = new SkylineDataSchema(documentContainer, DataSchemaLocalizer.INVARIANT); }
/// <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 PeakBoundaryImporter(SrmDocument document) { Document = document; AnnotationsAdded = new List<string>(); UnrecognizedFiles = new HashSet<string>(); UnrecognizedPeptides = new HashSet<string>(); UnrecognizedChargeStates = new HashSet<UnrecognizedChargeState>(); }
public ChromatogramExporter(SrmDocument document) { Document = document; _settings = Document.Settings; _measuredResults = _settings.MeasuredResults; _matchTolerance = (float)_settings.TransitionSettings.Instrument.MzMatchTolerance; _chromatogramSets = _measuredResults.Chromatograms; }
public ChromCacheMinimizer(SrmDocument document, ChromatogramCache chromatogramCache) { Document = document; ChromatogramCache = chromatogramCache; var chromGroupHeaderInfos = chromatogramCache.ChromGroupHeaderInfos.ToArray(); Array.Sort(chromGroupHeaderInfos, CompareLocation); ChromGroupHeaderInfos = Array.AsReadOnly(chromGroupHeaderInfos); _tolerance = (float) Document.Settings.TransitionSettings.Instrument.MzMatchTolerance; }
public AreaGraphData(SrmDocument document, TransitionGroupDocNode selectedGroup, PeptideGroupDocNode selectedProtein, int? result, DisplayTypeChrom displayType, PaneKey paneKey) : base(document, selectedGroup, selectedProtein, result, displayType, null, paneKey) { }
public static string IsNotLoadedDocumentExplained(SrmDocument document) { // Not loaded if the library is not usable var lib = GetOptimizationLibrary(document); if (lib == null || lib.IsUsable || lib.IsNone) { return null; } return "OptimizationDbManager: GetOptimizationLibrary(document) not usable and not none"; // Not L10N }
/// <summary> /// Creates a DocumentGridViewContext that can be used for exporting reports, importing report definitions, etc. /// </summary> public static DocumentGridViewContext CreateDocumentGridViewContext(SrmDocument document, DataSchemaLocalizer dataSchemaLocalizer) { if (document == null) { document = new SrmDocument(SrmSettingsList.GetDefault()); } var memoryDocumentContainer = new MemoryDocumentContainer(); memoryDocumentContainer.SetDocument(document, memoryDocumentContainer.Document); return new DocumentGridViewContext(new SkylineDataSchema(memoryDocumentContainer, dataSchemaLocalizer)); }
public static RCalcIrt ValidateDocAndIrt(SrmDocument doc, int peptides, int irtTotal, int irtStandards) { Assert.AreEqual(peptides, doc.PeptideCount); var calculator = doc.Settings.PeptideSettings.Prediction.RetentionTime.Calculator as RCalcIrt; Assert.IsNotNull(calculator); var peptideSeqs = calculator.PeptideScores.Select(item => item.Key).ToList(); Assert.AreEqual(irtTotal, peptideSeqs.Count); Assert.AreEqual(irtStandards, calculator.GetStandardPeptides(peptideSeqs).Count()); return calculator; }
public ExportChromatogramDlg(SrmDocument document, string documentPath) { InitializeComponent(); Icon = Resources.Skyline; Document = document; DocumentFilePath = documentPath; MakeCheckedList(); _chromExtractors = new List<ChromExtractor>(); _chromSources = new List<ChromSource>(); }
public ReplicateSummaries(SrmDocument document) { Document = document; int replicateCount = 0; if (Document.Settings.HasResults) { replicateCount = Document.Settings.MeasuredResults.Chromatograms.Count; } _allTotalAreas = new ImmutableSortedList<IsotopeLabelType, double>[replicateCount]; }
public ChromatogramRequestProvider(SrmDocument srmDocument, ChorusUrl chorusUrl, IRetentionTimePredictor retentionTimePredictor, bool firstPass) { _srmDocument = srmDocument; _chorusUrl = chorusUrl; _retentionTimePredictor = retentionTimePredictor; _firstPass = firstPass; // Create a SpectrumFilter without an IRetentionTimeProvider in order to get the list of ChromKeys that we will eventually provide. SpectrumFilter spectrumFilter = new SpectrumFilter(_srmDocument, _chorusUrl, null); _chromKeys = ImmutableList.ValueOf(ListChromKeys(GetChromatogramRequestDocument(spectrumFilter))); }
public ReintegrateDlg(SrmDocument document) { InitializeComponent(); Icon = Resources.Skyline; Document = document; _scoreAnnotation = false; _driverPeakScoringModel = new SettingsListComboDriver<PeakScoringModelSpec>(comboBoxScoringModel, Settings.Default.PeakScoringModelList); var peakScoringModel = document.Settings.PeptideSettings.Integration.PeakScoringModel; _driverPeakScoringModel.LoadList(peakScoringModel != null ? peakScoringModel.Name : null); }
/// <summary> /// If the Transition Full Scan settings are such that the time window for extracting /// chromatograms depends on a set of replicates, then this function shows the /// ChooseSchedulingReplicatesDlg. /// Returns false if the user cancels the dialog, or cannot import chromatograms. /// </summary> public bool CheckRetentionTimeFilter(SrmDocument document) { var settings = document.Settings; var fullScan = settings.TransitionSettings.FullScan; if (!fullScan.IsEnabled) { return true; } if (fullScan.RetentionTimeFilterType != RetentionTimeFilterType.scheduling_windows) { return true; } if (!fullScan.IsEnabledMsMs && !document.MoleculeTransitions.Any(transition => transition.IsMs1)) { return true; } var prediction = settings.PeptideSettings.Prediction; if (prediction.RetentionTime != null && prediction.RetentionTime.IsAutoCalculated) { return true; } bool anyImportedResults = settings.HasResults && settings.MeasuredResults.Chromatograms.Any(); bool canChooseReplicatesForCalibration = anyImportedResults && (prediction.UseMeasuredRTs || prediction.RetentionTime != null && prediction.RetentionTime.IsAutoCalculated); if (null == prediction.RetentionTime) { if (!prediction.UseMeasuredRTs || !anyImportedResults) { MessageDlg.Show(this, Resources.SkylineWindow_CheckRetentionTimeFilter_NoPredictionAlgorithm); return false; } } else if (!prediction.RetentionTime.IsUsable) { if (!canChooseReplicatesForCalibration) { if (MessageBox.Show(this, Resources.SkylineWindow_CheckRetentionTimeFilter_NoReplicatesAvailableForPrediction, Program.Name, MessageBoxButtons.OKCancel) == DialogResult.Cancel) { return false; } } } if (!canChooseReplicatesForCalibration) { return true; } using (var dlg = new ChooseSchedulingReplicatesDlg(this)) { return dlg.ShowDialog(this) == DialogResult.OK; } }
public static void IsDocumentResultsState(SrmDocument document, string replicateName, int peptides, int tranGroups, int tranGroupsHeavy, int transitions, int transitionsHeavy) { Assert.IsTrue(document.Settings.HasResults,"Expected document to have results."); int index; ChromatogramSet chromatogramSet; document.Settings.MeasuredResults.TryGetChromatogramSet(replicateName, out chromatogramSet, out index); Assert.AreNotEqual(-1, index, string.Format("Replicate {0} not found among -> {1} <-", replicateName, TextUtil.LineSeparate(document.Settings.MeasuredResults.Chromatograms.Select(c => c.Name)))); int peptidesActual = 0; foreach (var nodePep in document.Molecules.Where(nodePep => (nodePep.Results != null && nodePep.Results[index] != null))) { peptidesActual += nodePep.Results[index].Sum(chromInfo => chromInfo.PeakCountRatio >= 0.5 ? 1 : 0); } int transitionsActual = 0; int transitionsHeavyActual = 0; int tranGroupsActual = 0; int tranGroupsHeavyActual = 0; foreach (var nodeGroup in document.MoleculeTransitionGroups.Where(nodeGroup => ( nodeGroup.Results != null && nodeGroup.Results[index] != null))) { foreach (var chromInfo in nodeGroup.Results[index]) { if (chromInfo.PeakCountRatio < 0.5) continue; if (nodeGroup.TransitionGroup.LabelType.IsLight) tranGroupsActual++; else tranGroupsHeavyActual++; } foreach (var nodeTran in nodeGroup.Children.Cast<TransitionDocNode>().Where( nodeTran => (nodeTran.Results != null && nodeTran.Results[index] != null))) { foreach (var chromInfo in nodeTran.Results[index]) { if (chromInfo.Area == 0) continue; if (nodeGroup.TransitionGroup.LabelType.IsLight) transitionsActual++; else transitionsHeavyActual++; } } } var failMessage = CompareValues(peptides, peptidesActual, "peptide"); failMessage += CompareValues(tranGroups, tranGroupsActual, "transition group"); failMessage += CompareValues(tranGroupsHeavy, tranGroupsHeavyActual,"heavy transition group"); failMessage += CompareValues(transitions, transitionsActual, "transition"); failMessage += CompareValues(transitionsHeavy, transitionsHeavyActual, "heavy transition"); if (failMessage.Length > 0) Assert.Fail("IsDocumentResultsState failed for replicate " + replicateName + ": "+failMessage); }
public void MultiLabelExplicitSerialTest() { // Create a simple document and add two peptides SrmDocument document = new SrmDocument(SrmSettingsList.GetDefault()); const string pepSequence1 = "QFVLSCVILR"; const string pepSequence2 = "DIEVYCDGAITTK"; var reader = new StringReader(string.Join("\n", new[] {">peptides1", pepSequence1, pepSequence2})); IdentityPath path; document = document.ImportFasta(reader, true, IdentityPath.ROOT, out path); Assert.AreEqual(2, document.PeptideCount); // Add some modifications in two new label types var modCarb = new StaticMod("Carbamidomethyl Cysteine", "C", null, "C2H3ON"); var modOther = new StaticMod("Another Cysteine", "C", null, "CO8N2"); var staticMods = new[] {modCarb, modOther}; var mod15N = new StaticMod("All 15N", null, null, null, LabelAtoms.N15, null, null); var modK13C = new StaticMod("13C K", "K", ModTerminus.C, null, LabelAtoms.C13, null, null); var modR13C = new StaticMod("13C R", "R", ModTerminus.C, null, LabelAtoms.C13, null, null); var modV13C = new StaticMod("Heavy V", "V", null, null, LabelAtoms.C13 | LabelAtoms.N15, null, null); var heavyMods = new[] { mod15N, modK13C, modR13C, modV13C }; var labelTypeAA = new IsotopeLabelType("heavy AA", IsotopeLabelType.FirstHeavy); var labelTypeAll = new IsotopeLabelType("heavy All", IsotopeLabelType.FirstHeavy + 1); var settings = document.Settings; settings = settings.ChangePeptideModifications(mods => new PeptideModifications(mods.StaticModifications, new[] { new TypedModifications(labelTypeAA, new[] {modK13C, modR13C}), new TypedModifications(labelTypeAll, new[] {mod15N}) })); document = document.ChangeSettings(settings); Assert.AreEqual(6, document.PeptideTransitionGroupCount); // Add modifications to light and heavy AA in the first peptide path = document.GetPathTo((int) SrmDocument.Level.Molecules, 0); var nodePepMod = (PeptideDocNode) document.FindNode(path); var explicitMod = new ExplicitMods(nodePepMod.Peptide, new[] {new ExplicitMod(pepSequence1.IndexOf('C'), modOther)}, new[] {new TypedExplicitModifications(nodePepMod.Peptide, labelTypeAA, new ExplicitMod[0])}); document = document.ChangePeptideMods(path, explicitMod, staticMods, heavyMods); Assert.AreEqual(5, document.PeptideTransitionGroupCount); // Add a modification to heavy All in the second peptide path = document.GetPathTo((int)SrmDocument.Level.Molecules, 1); nodePepMod = (PeptideDocNode)document.FindNode(path); explicitMod = new ExplicitMods(nodePepMod.Peptide, null, new[] { new TypedExplicitModifications(nodePepMod.Peptide, labelTypeAll, new[] {new ExplicitMod(pepSequence2.IndexOf('V'), modV13C)}) }); document = document.ChangePeptideMods(path, explicitMod, staticMods, heavyMods); Assert.AreEqual(5, document.PeptideTransitionGroupCount); AssertEx.Serializable(document, 3, AssertEx.DocumentCloned); }
public static ChromatogramSet FindChromatogramSet(SrmDocument document, MsDataFileUri path) { if (document.Settings.HasResults) { foreach (var chromSet in document.Settings.MeasuredResults.Chromatograms) { if (chromSet.MSDataFilePaths.Contains(path)) return chromSet; } } return null; }
public TargetDecoyGenerator(SrmDocument document, IPeakScoringModel scoringModel, IProgressMonitor progressMonitor = null) { // Determine which calculators will be used to score peaks in this document. FeatureCalculators = scoringModel.PeakFeatureCalculators.ToArray(); _peakTransitionGroupFeaturesList = document.GetPeakFeatures(FeatureCalculators, progressMonitor); PopulateDictionary(); EligibleScores = new bool[FeatureCalculators.Count]; // Disable calculators that have only a single score value or any unknown scores. for (int i = 0; i < FeatureCalculators.Count; i++) EligibleScores[i] = IsValidCalculator(i); }
public void NeutralLossListTest() { TestSmallMolecules = false; // No concept of neutral loss for small molecules var phosphoLossMod = new StaticMod("Phospho Loss", "S, T, Y", null, false, "HPO3", LabelAtoms.None, RelativeRT.Matching, null, null, new[] { new FragmentLoss("H3PO4"), }); SrmDocument document = new SrmDocument(SrmSettingsList.GetDefault().ChangePeptideModifications(mods => mods.ChangeStaticModifications(new List<StaticMod>(mods.StaticModifications) { phosphoLossMod }))); IdentityPath path = IdentityPath.ROOT; SrmDocument docFasta = document.ImportFasta(new StringReader(TEXT_FASTA_YEAST_7), false, path, out path); Assert.AreEqual(0, GetLossCount(docFasta, 1)); // Insert losses into the first transition group var pathPeptide = docFasta.GetPathTo((int) SrmDocument.Level.Molecules, 0); var nodePep = (PeptideDocNode) docFasta.FindNode(pathPeptide); var nodeGroup = (TransitionGroupDocNode) nodePep.Children[0]; var listChildren = new List<DocNode>(nodeGroup.Children); foreach (var nodeTran in nodeGroup.GetTransitions(docFasta.Settings, nodePep.ExplicitMods, nodeGroup.PrecursorMz, null, null, null, false)) { if (!nodeTran.HasLoss) continue; var tran = nodeTran.Transition; int matchIndex = listChildren.IndexOf(node => Equals(tran, ((TransitionDocNode)node).Transition)); if (matchIndex == -1) continue; while (matchIndex < listChildren.Count && Equals(tran, ((TransitionDocNode)listChildren[matchIndex]).Transition)) { matchIndex++; } listChildren.Insert(matchIndex, nodeTran); } var docLosses = (SrmDocument) docFasta.ReplaceChild(pathPeptide, nodeGroup.ChangeChildren(listChildren)); int lossCount = GetLossCount(docLosses, 1); Assert.IsTrue(lossCount > 0); var docRoundTripped = AssertEx.RoundTripTransitionList(new ThermoMassListExporter(docLosses)); Assert.AreEqual(lossCount, GetLossCount(docRoundTripped, 1)); docRoundTripped = AssertEx.RoundTripTransitionList(new AgilentMassListExporter(docLosses)); Assert.AreEqual(lossCount, GetLossCount(docRoundTripped, 1)); }
public ViewLibraryPepMatching(SrmDocument document, Library library, LibrarySpec spec, byte[] lookupPool, LibKeyModificationMatcher matcher, ViewLibraryPepInfo[] peptides) { _document = document; _selectedLibrary = library; _selectedSpec = spec; _lookupPool = lookupPool; _matcher = matcher; _libraryPepInfos = peptides; _chargeSettingsMap = new SrmSettings[128]; }
public List <StandardPeptide> Recalculate(SrmDocument document, int peptideCount, ICollection <PeptideDocNode> exclude) { SetPeptides(FindBestPeptides(document, peptideCount, exclude)); return(Items.ToList()); }
private void DisplayCalibrationCurve() { CalibrationCurveOptions options = Settings.Default.CalibrationCurveOptions; zedGraphControl.GraphPane.YAxis.Type = zedGraphControl.GraphPane.XAxis.Type = options.LogPlot ? AxisType.Log : AxisType.Linear; zedGraphControl.GraphPane.Legend.IsVisible = options.ShowLegend; _scatterPlots = null; CalibrationCurve = null; FiguresOfMerit = FiguresOfMerit.EMPTY; SrmDocument document = DocumentUiContainer.DocumentUI; if (!document.Settings.HasResults) { zedGraphControl.GraphPane.Title.Text = QuantificationStrings.CalibrationForm_DisplayCalibrationCurve_No_results_available; return; } PeptideDocNode peptide; PeptideGroupDocNode peptideGroup; if (!TryGetSelectedPeptide(out peptideGroup, out peptide)) { zedGraphControl.GraphPane.Title.Text = QuantificationStrings .CalibrationForm_DisplayCalibrationCurve_Select_a_peptide_to_see_its_calibration_curve; return; } if (-1 == document.Children.IndexOf(peptideGroup)) { zedGraphControl.GraphPane.Title.Text = QuantificationStrings.CalibrationForm_DisplayCalibrationCurve_The_selected_peptide_is_no_longer_part_of_the_Skyline_document_; return; } PeptideQuantifier peptideQuantifier = PeptideQuantifier.GetPeptideQuantifier(document, peptideGroup, peptide); CalibrationCurveFitter curveFitter = new CalibrationCurveFitter(peptideQuantifier, document.Settings); if (peptideQuantifier.QuantificationSettings.RegressionFit == RegressionFit.NONE) { if (!(peptideQuantifier.NormalizationMethod is NormalizationMethod.RatioToLabel)) { zedGraphControl.GraphPane.Title.Text = QuantificationStrings.CalibrationForm_DisplayCalibrationCurve_Use_the_Quantification_tab_on_the_Peptide_Settings_dialog_to_control_the_conversion_of_peak_areas_to_concentrations_; } else { if (!peptide.InternalStandardConcentration.HasValue) { zedGraphControl.GraphPane.Title.Text = string.Format(QuantificationStrings.CalibrationForm_DisplayCalibrationCurve_To_convert_peak_area_ratios_to_concentrations__specify_the_internal_standard_concentration_for__0__, peptide); } else { zedGraphControl.GraphPane.Title.Text = null; } } } else { if (curveFitter.GetStandardConcentrations().Any()) { zedGraphControl.GraphPane.Title.Text = null; } else { zedGraphControl.GraphPane.Title.Text = QuantificationStrings.CalibrationForm_DisplayCalibrationCurve_To_fit_a_calibration_curve__set_the_Sample_Type_of_some_replicates_to_Standard__and_specify_their_concentration_; } } zedGraphControl.GraphPane.XAxis.Title.Text = curveFitter.GetXAxisTitle(); zedGraphControl.GraphPane.YAxis.Title.Text = curveFitter.GetYAxisTitle(); CalibrationCurve = curveFitter.GetCalibrationCurve(); FiguresOfMerit = curveFitter.GetFiguresOfMerit(CalibrationCurve); double minX = double.MaxValue, maxX = double.MinValue; double minY = double.MaxValue; _scatterPlots = new CurveList(); foreach (var sampleType in SampleType.ListSampleTypes()) { if (!Options.DisplaySampleType(sampleType)) { continue; } PointPairList pointPairList = new PointPairList(); PointPairList pointPairListExcluded = new PointPairList(); for (int iReplicate = 0; iReplicate < document.Settings.MeasuredResults.Chromatograms.Count; iReplicate++) { ChromatogramSet chromatogramSet = document.Settings.MeasuredResults.Chromatograms[iReplicate]; if (!Equals(sampleType, chromatogramSet.SampleType)) { continue; } double?y = curveFitter.GetYValue(iReplicate); double?xCalculated = curveFitter.GetCalculatedXValue(CalibrationCurve, iReplicate); double?x = curveFitter.GetSpecifiedXValue(iReplicate) ?? xCalculated; if (y.HasValue && x.HasValue) { PointPair point = new PointPair(x.Value, y.Value) { Tag = iReplicate }; if (sampleType.AllowExclude && peptide.IsExcludeFromCalibration(iReplicate)) { pointPairListExcluded.Add(point); } else { pointPairList.Add(point); } if (double.IsNaN(x.Value) || double.IsInfinity(x.Value) || double.IsNaN(y.Value) || double.IsInfinity(y.Value)) { continue; } if (!Options.LogPlot || x.Value > 0) { minX = Math.Min(minX, x.Value); } if (!Options.LogPlot || y.Value > 0) { minY = Math.Min(minY, y.Value); } maxX = Math.Max(maxX, x.Value); if (xCalculated.HasValue) { maxX = Math.Max(maxX, xCalculated.Value); if (!Options.LogPlot || xCalculated.Value > 0) { minX = Math.Min(minX, xCalculated.Value); } } } } if (pointPairList.Any()) { var lineItem = zedGraphControl.GraphPane.AddCurve(sampleType.ToString(), pointPairList, sampleType.Color, sampleType.SymbolType); lineItem.Line.IsVisible = false; lineItem.Symbol.Fill = new Fill(sampleType.Color); _scatterPlots.Add(lineItem); } if (pointPairListExcluded.Any()) { string curveLabel = pointPairList.Any() ? null : sampleType.ToString(); var lineItem = zedGraphControl.GraphPane.AddCurve(curveLabel, pointPairListExcluded, sampleType.Color, sampleType.SymbolType); lineItem.Line.IsVisible = false; _scatterPlots.Add(lineItem); } } List <string> labelLines = new List <String>(); RegressionFit regressionFit = document.Settings.PeptideSettings.Quantification.RegressionFit; if (regressionFit != RegressionFit.NONE) { if (minX <= maxX) { int interpolatedLinePointCount = 100; if (!options.LogPlot) { if (regressionFit == RegressionFit.LINEAR_THROUGH_ZERO) { minX = Math.Min(0, minX); } if (regressionFit != RegressionFit.QUADRATIC) { interpolatedLinePointCount = 2; } } double[] xValues; if (CalibrationCurve.TurningPoint.HasValue) { xValues = new[] { minX, CalibrationCurve.TurningPoint.Value, maxX }; } else { xValues = new[] { minX, maxX }; } Array.Sort(xValues); LineItem interpolatedLine = CreateInterpolatedLine(CalibrationCurve, xValues, interpolatedLinePointCount, Options.LogPlot); if (null != interpolatedLine) { zedGraphControl.GraphPane.CurveList.Add(interpolatedLine); } } labelLines.Add(CalibrationCurve.ToString()); if (CalibrationCurve.RSquared.HasValue) { labelLines.Add(QuantificationStrings.CalibrationForm_DisplayCalibrationCurve_ + CalibrationCurve.RSquared.Value.ToString("0.####")); // Not L10N } if (!Equals(curveFitter.QuantificationSettings.RegressionWeighting, RegressionWeighting.NONE)) { labelLines.Add(string.Format("{0}: {1}", // Not L10N QuantificationStrings.Weighting, curveFitter.QuantificationSettings.RegressionWeighting)); } string strFiguresOfMerit = FiguresOfMerit.ToString(); if (!string.IsNullOrEmpty(strFiguresOfMerit)) { labelLines.Add(strFiguresOfMerit); } } if (options.ShowSelection) { double?ySelected = curveFitter.GetYValue(_skylineWindow.SelectedResultsIndex); double?xSelected = curveFitter.GetCalculatedXValue(CalibrationCurve, _skylineWindow.SelectedResultsIndex); if (xSelected.HasValue && ySelected.HasValue) { const float selectedLineWidth = 2; ArrowObj arrow = new ArrowObj(xSelected.Value, ySelected.Value, xSelected.Value, ySelected.Value) { Line = { Color = GraphSummary.ColorSelected } }; zedGraphControl.GraphPane.GraphObjList.Insert(0, arrow); var selectedLineColor = Color.FromArgb(128, GraphSummary.ColorSelected); var verticalLine = new LineObj(xSelected.Value, ySelected.Value, xSelected.Value, options.LogPlot ? double.MinValue : 0) { Line = { Color = selectedLineColor, Width = selectedLineWidth }, Location = { CoordinateFrame = CoordType.AxisXYScale }, ZOrder = ZOrder.E_BehindCurves, IsClippedToChartRect = true }; zedGraphControl.GraphPane.GraphObjList.Add(verticalLine); double?xSpecified = curveFitter.GetSpecifiedXValue(_skylineWindow.SelectedResultsIndex); if (xSpecified.HasValue) { var horizontalLine = new LineObj(xSpecified.Value, ySelected.Value, xSelected.Value, ySelected.Value) { Line = { Color = selectedLineColor, Width = selectedLineWidth }, Location = { CoordinateFrame = CoordType.AxisXYScale }, ZOrder = ZOrder.E_BehindCurves, IsClippedToChartRect = true }; zedGraphControl.GraphPane.GraphObjList.Add(horizontalLine); } } var quantificationResult = curveFitter.GetQuantificationResult(_skylineWindow.SelectedResultsIndex); if (quantificationResult.CalculatedConcentration.HasValue) { labelLines.Add(string.Format("{0} = {1}", // Not L10N QuantificationStrings.Calculated_Concentration, quantificationResult)); } else if (!quantificationResult.NormalizedArea.HasValue) { labelLines.Add(QuantificationStrings.CalibrationForm_DisplayCalibrationCurve_The_selected_replicate_has_missing_or_truncated_transitions); } } if (labelLines.Any()) { TextObj text = new TextObj(TextUtil.LineSeparate(labelLines), .01, 0, CoordType.ChartFraction, AlignH.Left, AlignV.Top) { IsClippedToChartRect = true, ZOrder = ZOrder.E_BehindCurves, FontSpec = GraphSummary.CreateFontSpec(Color.Black), }; zedGraphControl.GraphPane.GraphObjList.Add(text); } }
private void DisplayCalibrationCurve() { Text = TabText = _originalFormTitle; CalibrationCurveOptions options = Settings.Default.CalibrationCurveOptions; zedGraphControl.GraphPane.YAxis.Type = options.LogYAxis ? AxisType.Log : AxisType.Linear; zedGraphControl.GraphPane.XAxis.Type = options.LogXAxis ? AxisType.Log : AxisType.Linear; bool logPlot = options.LogXAxis || options.LogYAxis; zedGraphControl.GraphPane.Legend.IsVisible = options.ShowLegend; _scatterPlots = null; CalibrationCurve = null; FiguresOfMerit = FiguresOfMerit.EMPTY; SrmDocument document = DocumentUiContainer.DocumentUI; if (!document.Settings.HasResults) { zedGraphControl.GraphPane.Title.Text = QuantificationStrings.CalibrationForm_DisplayCalibrationCurve_No_results_available; return; } PeptideDocNode peptide; PeptideGroupDocNode peptideGroup; if (!TryGetSelectedPeptide(out peptideGroup, out peptide)) { zedGraphControl.GraphPane.Title.Text = QuantificationStrings .CalibrationForm_DisplayCalibrationCurve_Select_a_peptide_to_see_its_calibration_curve; return; } if (-1 == document.Children.IndexOf(peptideGroup)) { zedGraphControl.GraphPane.Title.Text = QuantificationStrings.CalibrationForm_DisplayCalibrationCurve_The_selected_peptide_is_no_longer_part_of_the_Skyline_document_; return; } PeptideQuantifier peptideQuantifier = PeptideQuantifier.GetPeptideQuantifier(document, peptideGroup, peptide); CalibrationCurveFitter curveFitter = new CalibrationCurveFitter(peptideQuantifier, document.Settings); Text = TabText = TextUtil.SpaceSeparate(_originalFormTitle + ':', peptideQuantifier.PeptideDocNode.ModifiedSequenceDisplay); if (curveFitter.IsotopologResponseCurve && Settings.Default.CalibrationCurveOptions.SingleReplicate) { curveFitter.IsotopologReplicateIndex = _skylineWindow.SelectedResultsIndex; } if (peptideQuantifier.QuantificationSettings.RegressionFit == RegressionFit.NONE) { if (!(peptideQuantifier.NormalizationMethod is NormalizationMethod.RatioToLabel)) { zedGraphControl.GraphPane.Title.Text = QuantificationStrings.CalibrationForm_DisplayCalibrationCurve_Use_the_Quantification_tab_on_the_Peptide_Settings_dialog_to_control_the_conversion_of_peak_areas_to_concentrations_; } else { if (!peptide.InternalStandardConcentration.HasValue) { zedGraphControl.GraphPane.Title.Text = string.Format(QuantificationStrings.CalibrationForm_DisplayCalibrationCurve_To_convert_peak_area_ratios_to_concentrations__specify_the_internal_standard_concentration_for__0__, peptide); } else { zedGraphControl.GraphPane.Title.Text = null; } } } else { if (curveFitter.GetStandardConcentrations().Any()) { zedGraphControl.GraphPane.Title.Text = null; } else { zedGraphControl.GraphPane.Title.Text = QuantificationStrings.CalibrationForm_DisplayCalibrationCurve_To_fit_a_calibration_curve__set_the_Sample_Type_of_some_replicates_to_Standard__and_specify_their_concentration_; } } zedGraphControl.GraphPane.XAxis.Title.Text = curveFitter.GetXAxisTitle(); zedGraphControl.GraphPane.YAxis.Title.Text = curveFitter.GetYAxisTitle(); CalibrationCurve = curveFitter.GetCalibrationCurve(); FiguresOfMerit = curveFitter.GetFiguresOfMerit(CalibrationCurve); double minX = double.MaxValue, maxX = double.MinValue; double minY = double.MaxValue; _scatterPlots = new CurveList(); var sampleTypes = curveFitter.IsotopologResponseCurve ? new[] { SampleType.STANDARD } : SampleType.ListSampleTypes().Where(Options.DisplaySampleType); foreach (var sampleType in sampleTypes) { PointPairList pointPairList = new PointPairList(); PointPairList pointPairListExcluded = new PointPairList(); foreach (var standardIdentifier in curveFitter.EnumerateCalibrationPoints()) { if (null == standardIdentifier.LabelType) { ChromatogramSet chromatogramSet = document.Settings.MeasuredResults.Chromatograms[standardIdentifier.ReplicateIndex]; if (!Equals(sampleType, chromatogramSet.SampleType)) { continue; } } double?y = curveFitter.GetYValue(standardIdentifier); double?xCalculated = curveFitter.GetCalculatedXValue(CalibrationCurve, standardIdentifier); double?x = curveFitter.GetSpecifiedXValue(standardIdentifier) ?? xCalculated; if (y.HasValue && x.HasValue) { PointPair point = new PointPair(x.Value, y.Value) { Tag = standardIdentifier }; if (sampleType.AllowExclude && null == standardIdentifier.LabelType && peptide.IsExcludeFromCalibration(standardIdentifier.ReplicateIndex)) { pointPairListExcluded.Add(point); } else { pointPairList.Add(point); } if (!IsNumber(x) || !IsNumber(y)) { continue; } if (!logPlot || x.Value > 0) { minX = Math.Min(minX, x.Value); } if (!logPlot || y.Value > 0) { minY = Math.Min(minY, y.Value); } maxX = Math.Max(maxX, x.Value); if (IsNumber(xCalculated)) { maxX = Math.Max(maxX, xCalculated.Value); if (!logPlot || xCalculated.Value > 0) { minX = Math.Min(minX, xCalculated.Value); } } } } if (pointPairList.Any()) { var lineItem = zedGraphControl.GraphPane.AddCurve(sampleType.ToString(), pointPairList, sampleType.Color, sampleType.SymbolType); lineItem.Line.IsVisible = false; lineItem.Symbol.Fill = new Fill(sampleType.Color); _scatterPlots.Add(lineItem); } if (pointPairListExcluded.Any()) { string curveLabel = pointPairList.Any() ? null : sampleType.ToString(); var lineItem = zedGraphControl.GraphPane.AddCurve(curveLabel, pointPairListExcluded, sampleType.Color, sampleType.SymbolType); lineItem.Line.IsVisible = false; _scatterPlots.Add(lineItem); } } List <string> labelLines = new List <String>(); RegressionFit regressionFit = document.Settings.PeptideSettings.Quantification.RegressionFit; if (regressionFit != RegressionFit.NONE) { if (minX <= maxX) { int interpolatedLinePointCount = 100; if (!logPlot && regressionFit != RegressionFit.LINEAR_IN_LOG_SPACE) { if (regressionFit == RegressionFit.LINEAR_THROUGH_ZERO) { minX = Math.Min(0, minX); } if (regressionFit != RegressionFit.QUADRATIC) { interpolatedLinePointCount = 2; } } double[] xValues; if (CalibrationCurve.TurningPoint.HasValue) { xValues = new[] { minX, CalibrationCurve.TurningPoint.Value, maxX }; } else { xValues = new[] { minX, maxX }; } Array.Sort(xValues); LineItem interpolatedLine = CreateInterpolatedLine(CalibrationCurve, xValues, interpolatedLinePointCount, logPlot); if (null != interpolatedLine) { zedGraphControl.GraphPane.CurveList.Add(interpolatedLine); } } labelLines.Add(CalibrationCurve.ToString()); if (CalibrationCurve.RSquared.HasValue) { labelLines.Add(QuantificationStrings.CalibrationForm_DisplayCalibrationCurve_ + CalibrationCurve.RSquared.Value.ToString("0.####")); // Not L10N } if (!Equals(curveFitter.QuantificationSettings.RegressionWeighting, RegressionWeighting.NONE)) { labelLines.Add(string.Format("{0}: {1}", // Not L10N QuantificationStrings.Weighting, curveFitter.QuantificationSettings.RegressionWeighting)); } if (options.ShowFiguresOfMerit) { string strFiguresOfMerit = FiguresOfMerit.ToString(); if (!string.IsNullOrEmpty(strFiguresOfMerit)) { labelLines.Add(strFiguresOfMerit); } } } CalibrationPoint?selectionIdentifier = null; if (options.ShowSelection) { if (curveFitter.IsotopologResponseCurve) { var labelType = (_skylineWindow.SequenceTree.SelectedNode as SrmTreeNode) ?.GetNodeOfType <TransitionGroupTreeNode>()?.DocNode.LabelType; if (labelType != null) { selectionIdentifier = new CalibrationPoint(_skylineWindow.SelectedResultsIndex, labelType); } } else { selectionIdentifier = new CalibrationPoint(_skylineWindow.SelectedResultsIndex, null); } } if (selectionIdentifier.HasValue) { double?ySelected = curveFitter.GetYValue(selectionIdentifier.Value); if (IsNumber(ySelected)) { double? xSelected = curveFitter.GetCalculatedXValue(CalibrationCurve, selectionIdentifier.Value); var selectedLineColor = Color.FromArgb(128, GraphSummary.ColorSelected); const float selectedLineWidth = 2; double? xSpecified = curveFitter.GetSpecifiedXValue(selectionIdentifier.Value); if (IsNumber(xSelected)) { ArrowObj arrow = new ArrowObj(xSelected.Value, ySelected.Value, xSelected.Value, ySelected.Value) { Line = { Color = GraphSummary.ColorSelected } }; zedGraphControl.GraphPane.GraphObjList.Insert(0, arrow); var verticalLine = new LineObj(xSelected.Value, ySelected.Value, xSelected.Value, options.LogYAxis ? double.MinValue : 0) { Line = { Color = selectedLineColor, Width = selectedLineWidth }, Location = { CoordinateFrame = CoordType.AxisXYScale }, ZOrder = ZOrder.E_BehindCurves, IsClippedToChartRect = true }; zedGraphControl.GraphPane.GraphObjList.Add(verticalLine); if (IsNumber(xSpecified)) { var horizontalLine = new LineObj(xSpecified.Value, ySelected.Value, xSelected.Value, ySelected.Value) { Line = { Color = selectedLineColor, Width = selectedLineWidth }, Location = { CoordinateFrame = CoordType.AxisXYScale }, ZOrder = ZOrder.E_BehindCurves, IsClippedToChartRect = true }; zedGraphControl.GraphPane.GraphObjList.Add(horizontalLine); } } else { // We were not able to map the observed intensity back to the calibration curve, but we still want to // indicate where the currently selected point is. if (IsNumber(xSpecified)) { // If the point has a specified concentration, then use that. ArrowObj arrow = new ArrowObj(xSpecified.Value, ySelected.Value, xSpecified.Value, ySelected.Value) { Line = { Color = GraphSummary.ColorSelected } }; zedGraphControl.GraphPane.GraphObjList.Insert(0, arrow); } else { // Otherwise, draw a horizontal line at the appropriate y-value. var horizontalLine = new LineObj(minX, ySelected.Value, maxX, ySelected.Value) { Line = { Color = selectedLineColor, Width = selectedLineWidth }, Location = { CoordinateFrame = CoordType.AxisXYScale }, IsClippedToChartRect = true, }; ZedGraphControl.GraphPane.GraphObjList.Add(horizontalLine); } } } var quantificationResult = curveFitter.GetQuantificationResult(_skylineWindow.SelectedResultsIndex); if (quantificationResult.CalculatedConcentration.HasValue) { labelLines.Add(string.Format("{0} = {1}", // Not L10N QuantificationStrings.Calculated_Concentration, quantificationResult)); } else if (!quantificationResult.NormalizedArea.HasValue) { labelLines.Add(QuantificationStrings.CalibrationForm_DisplayCalibrationCurve_The_selected_replicate_has_missing_or_truncated_transitions); } } if (Options.ShowFiguresOfMerit) { if (IsNumber(FiguresOfMerit.LimitOfDetection)) { var lodLine = new LineObj(Color.DarkMagenta, FiguresOfMerit.LimitOfDetection.Value, 0, FiguresOfMerit.LimitOfDetection.Value, 1) { Location = { CoordinateFrame = CoordType.XScaleYChartFraction } }; zedGraphControl.GraphPane.GraphObjList.Add(lodLine); } if (IsNumber(FiguresOfMerit.LimitOfQuantification)) { var loqLine = new LineObj(Color.DarkCyan, FiguresOfMerit.LimitOfQuantification.Value, 0, FiguresOfMerit.LimitOfQuantification.Value, 1) { Location = { CoordinateFrame = CoordType.XScaleYChartFraction } }; zedGraphControl.GraphPane.GraphObjList.Add(loqLine); } } if (labelLines.Any()) { TextObj text = new TextObj(TextUtil.LineSeparate(labelLines), .01, 0, CoordType.ChartFraction, AlignH.Left, AlignV.Top) { IsClippedToChartRect = true, ZOrder = ZOrder.E_BehindCurves, FontSpec = GraphSummary.CreateFontSpec(Color.Black), }; zedGraphControl.GraphPane.GraphObjList.Add(text); } }
private void DoFullScanFilterTest(RefinementSettings.ConvertToSmallMoleculesMode asSmallMolecules, out List <SrmDocument> docCheckpoints, bool centroided = false) { docCheckpoints = new List <SrmDocument>(); TestSmallMolecules = false; // We test small molecules explicitly var testFilesDir = new TestFilesDir(TestContext, ZIP_FILE); string docPath = testFilesDir.GetTestPath("BSA_Protea_label_free_20100323_meth3_multi.sky"); var expectedPepCount = 7; var expectedTransGroupCount = 7; var expectedTransCount = 49; var doc = InitFullScanDocument(docPath, 2, ref expectedPepCount, ref expectedTransGroupCount, ref expectedTransCount, asSmallMolecules); if (centroided && ExtensionTestContext.CanImportThermoRaw) { const double ppm20 = 20.0; doc = doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(fs => fs.ChangePrecursorResolution(FullScanMassAnalyzerType.centroided, ppm20, 0))); } using (var docContainer = new ResultsTestDocumentContainer(doc, docPath)) { // Import the first RAW file (or mzML for international) string rawPath = testFilesDir.GetTestPath("ah_20101011y_BSA_MS-MS_only_5-2" + ExtensionTestContext.ExtThermoRaw); var measuredResults = new MeasuredResults(new[] { new ChromatogramSet("Single", new[] { new MsDataFilePath(rawPath) }) }); SrmDocument docResults = docContainer.ChangeMeasuredResults(measuredResults, 3, 3, 21); docCheckpoints.Add(docResults); // Refilter allowing multiple precursors per spectrum SrmDocument docMulti = doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan( fs => fs.ChangeAcquisitionMethod(FullScanAcquisitionMethod.DIA, new IsolationScheme("Test", 2)))); AssertEx.Serializable(docMulti, AssertEx.DocumentCloned); // Release data cache file Assert.IsTrue(docContainer.SetDocument(docMulti, docResults)); // And remove it FileEx.SafeDelete(Path.ChangeExtension(docPath, ChromatogramCache.EXT)); docCheckpoints.Add(docContainer.ChangeMeasuredResults(measuredResults, 6, 6, 38)); // Import full scan Orbi-Velos data docPath = testFilesDir.GetTestPath("BSA_Protea_label_free_20100323_meth3_long_acc_template.sky"); expectedPepCount = 3; expectedTransGroupCount = 3; expectedTransCount = 21; doc = InitFullScanDocument(docPath, 1, ref expectedPepCount, ref expectedTransGroupCount, ref expectedTransCount, asSmallMolecules); docCheckpoints.Add(doc); Assert.AreEqual(FullScanMassAnalyzerType.orbitrap, doc.Settings.TransitionSettings.FullScan.ProductMassAnalyzer); // Make sure saving this type of document works AssertEx.Serializable(doc, AssertEx.DocumentCloned); Assert.IsTrue(docContainer.SetDocument(doc, docContainer.Document)); rawPath = testFilesDir.GetTestPath("ah_20101029r_BSA_CID_FT_centroid_3uscan_3" + ExtensionTestContext.ExtThermoRaw); measuredResults = new MeasuredResults(new[] { new ChromatogramSet("Accurate", new[] { rawPath }) }); docCheckpoints.Add(docContainer.ChangeMeasuredResults(measuredResults, 3, 3, 21)); // Import LTQ data with MS1 and MS/MS docPath = testFilesDir.GetTestPath("BSA_Protea_label_free_20100323_meth3_test4.sky"); expectedPepCount = 3; expectedTransGroupCount = 4; expectedTransCount = 32; doc = InitFullScanDocument(docPath, 3, ref expectedPepCount, ref expectedTransGroupCount, ref expectedTransCount, asSmallMolecules); Assert.AreEqual(FullScanMassAnalyzerType.none, doc.Settings.TransitionSettings.FullScan.ProductMassAnalyzer); Assert.AreEqual(FullScanMassAnalyzerType.none, doc.Settings.TransitionSettings.FullScan.PrecursorMassAnalyzer); docCheckpoints.Add(doc); var docBoth = doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(fs => fs.ChangeAcquisitionMethod(FullScanAcquisitionMethod.Targeted, null) .ChangePrecursorResolution(FullScanMassAnalyzerType.qit, TransitionFullScan.DEFAULT_RES_QIT, null))); docCheckpoints.Add(docBoth); AssertEx.Serializable(docBoth, AssertEx.DocumentCloned); Assert.IsTrue(docContainer.SetDocument(docBoth, docContainer.Document)); string dataPath = testFilesDir.GetTestPath("klc_20100329v_Protea_Peptide_Curve_200fmol_uL_tech1.mzML"); var listResults = new List <ChromatogramSet> { new ChromatogramSet("MS1 and MS/MS", new[] { dataPath }), }; measuredResults = new MeasuredResults(listResults.ToArray()); docCheckpoints.Add(docContainer.ChangeMeasuredResults(measuredResults, expectedPepCount, expectedTransGroupCount, expectedTransCount - 6)); // The mzML was filtered for the m/z range 410 to 910. foreach (var nodeTran in docContainer.Document.PeptideTransitions) { Assert.IsTrue(nodeTran.HasResults); Assert.IsNotNull(nodeTran.Results[0]); if (410 > nodeTran.Mz || nodeTran.Mz > 910) { Assert.IsTrue(nodeTran.Results[0][0].IsEmpty); } else { Assert.IsFalse(nodeTran.Results[0][0].IsEmpty); } } // Import LTQ data with MS1 and MS/MS using multiple files for a single replicate listResults.Add(new ChromatogramSet("Multi-file", new[] { testFilesDir.GetTestPath("both_DRV.mzML"), testFilesDir.GetTestPath("both_KVP.mzML"), })); measuredResults = new MeasuredResults(listResults.ToArray()); docCheckpoints.Add(docContainer.ChangeMeasuredResults(measuredResults, expectedPepCount - 1, expectedTransGroupCount - 1, expectedTransCount - 6)); int indexResults = listResults.Count - 1; foreach (var nodeTran in docContainer.Document.PeptideTransitions) { Assert.IsTrue(nodeTran.HasResults); Assert.AreEqual(listResults.Count, nodeTran.Results.Count); var peptide = nodeTran.Transition.Group.Peptide; // DRV without FASTA sequence should not have data for non-precursor transitions if (!peptide.Sequence.StartsWith("DRV") || !peptide.Begin.HasValue) { Assert.IsNotNull(nodeTran.Results[indexResults]); Assert.IsFalse(nodeTran.Results[indexResults][0].IsEmpty); } else if (nodeTran.Transition.IonType != IonType.precursor) { Assert.IsNull(nodeTran.Results[indexResults]); } else { // Random, bogus peaks chosen in both files Assert.IsNotNull(nodeTran.Results[indexResults]); Assert.AreEqual(2, nodeTran.Results[indexResults].Count); Assert.IsFalse(nodeTran.Results[indexResults][0].IsEmpty); Assert.IsFalse(nodeTran.Results[indexResults][1].IsEmpty); } } if (asSmallMolecules == RefinementSettings.ConvertToSmallMoleculesMode.masses_only) { return; // Can't work with isotope distributions when we don't have ion formulas } // Verify handling of bad request for vendor centroided data - out-of-range PPM docPath = testFilesDir.GetTestPath("Yeast_HI3 Peptides_test.sky"); expectedPepCount = 2; expectedTransGroupCount = 2; expectedTransCount = 2; doc = InitFullScanDocument(docPath, 2, ref expectedPepCount, ref expectedTransGroupCount, ref expectedTransCount, asSmallMolecules); Assert.AreEqual(FullScanMassAnalyzerType.none, doc.Settings.TransitionSettings.FullScan.ProductMassAnalyzer); Assert.AreEqual(FullScanMassAnalyzerType.none, doc.Settings.TransitionSettings.FullScan.PrecursorMassAnalyzer); var docBad = doc; AssertEx.ThrowsException <InvalidDataException>(() => docBad.ChangeSettings(docBad.Settings.ChangeTransitionFullScan(fs => fs.ChangePrecursorIsotopes(FullScanPrecursorIsotopes.Count, 1, IsotopeEnrichments.DEFAULT) .ChangePrecursorResolution(FullScanMassAnalyzerType.centroided, 50 * 1000, 400))), string.Format(Resources.TransitionFullScan_ValidateRes_Mass_accuracy_must_be_between__0__and__1__for_centroided_data_, TransitionFullScan.MIN_CENTROID_PPM, TransitionFullScan.MAX_CENTROID_PPM)); // Verify relationship between PPM and resolving power const double ppm = 20.0; // Should yield same filter width as resolving power 50,000 in TOF var docNoCentroid = doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(fs => fs.ChangePrecursorIsotopes(FullScanPrecursorIsotopes.Count, 1, IsotopeEnrichments.DEFAULT) .ChangePrecursorResolution(FullScanMassAnalyzerType.centroided, ppm, 0))); AssertEx.Serializable(docNoCentroid, AssertEx.DocumentCloned); Assert.IsTrue(docContainer.SetDocument(docNoCentroid, docContainer.Document)); const double mzTest = 400.0; var filterWidth = docNoCentroid.Settings.TransitionSettings.FullScan.GetPrecursorFilterWindow(mzTest); Assert.AreEqual(mzTest * 2.0 * ppm * 1E-6, filterWidth); // Verify handling of bad request for vendor centroided data - ask for centroiding in mzML const string fileName = "S_2_LVN.mzML"; var filePath = testFilesDir.GetTestPath(fileName); AssertEx.ThrowsException <AssertFailedException>(() => { listResults = new List <ChromatogramSet> { new ChromatogramSet("rep1", new[] { new MsDataFilePath(filePath, null, true) }), }; docContainer.ChangeMeasuredResults(new MeasuredResults(listResults.ToArray()), 1, 1, 1); }, string.Format(Resources.NoCentroidedDataException_NoCentroidedDataException_No_centroided_data_available_for_file___0_____Adjust_your_Full_Scan_settings_, filePath)); // Import FT data with only MS1 docPath = testFilesDir.GetTestPath("Yeast_HI3 Peptides_test.sky"); expectedPepCount = 2; expectedTransGroupCount = 2; expectedTransCount = 2; doc = InitFullScanDocument(docPath, 2, ref expectedPepCount, ref expectedTransGroupCount, ref expectedTransCount, asSmallMolecules); Assert.AreEqual(FullScanMassAnalyzerType.none, doc.Settings.TransitionSettings.FullScan.ProductMassAnalyzer); Assert.AreEqual(FullScanMassAnalyzerType.none, doc.Settings.TransitionSettings.FullScan.PrecursorMassAnalyzer); var docMs1 = doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(fs => fs.ChangePrecursorIsotopes(FullScanPrecursorIsotopes.Count, 1, IsotopeEnrichments.DEFAULT) .ChangePrecursorResolution(FullScanMassAnalyzerType.tof, 50 * 1000, null))); Assert.AreEqual(filterWidth, docMs1.Settings.TransitionSettings.FullScan.GetPrecursorFilterWindow(mzTest)); docMs1 = doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(fs => fs.ChangePrecursorIsotopes(FullScanPrecursorIsotopes.Count, 1, IsotopeEnrichments.DEFAULT) .ChangePrecursorResolution(FullScanMassAnalyzerType.ft_icr, 50 * 1000, mzTest))); AssertEx.Serializable(docMs1, AssertEx.DocumentCloned); Assert.IsTrue(docContainer.SetDocument(docMs1, docContainer.Document)); const string rep1 = "rep1"; listResults = new List <ChromatogramSet> { new ChromatogramSet(rep1, new[] { filePath }), }; measuredResults = new MeasuredResults(listResults.ToArray()); docCheckpoints.Add(docContainer.ChangeMeasuredResults(measuredResults, 1, 1, 1)); // Because of the way the mzML files were filtered, all of the LVN peaks should be present // in the first replicate, and all of the NVN peaks should be present in the other. foreach (var nodeTranGroup in docContainer.Document.MoleculeTransitionGroups) { foreach (var docNode in nodeTranGroup.Children) { var nodeTran = (TransitionDocNode)docNode; Assert.IsTrue(nodeTran.HasResults); Assert.AreEqual(1, nodeTran.Results.Count); if ((nodeTran.Transition.Group.Peptide.IsCustomIon ? nodeTranGroup.CustomIon.Name : nodeTran.Transition.Group.Peptide.Sequence).StartsWith("LVN")) { Assert.IsFalse(nodeTran.Results[0][0].IsEmpty); } else { Assert.IsTrue(nodeTran.Results[0][0].IsEmpty); } } } const string rep2 = "rep2"; listResults.Add(new ChromatogramSet(rep2, new[] { testFilesDir.GetTestPath("S_2_NVN.mzML") })); measuredResults = new MeasuredResults(listResults.ToArray()); docCheckpoints.Add(docContainer.ChangeMeasuredResults(measuredResults, 1, 1, 1)); // Because of the way the mzML files were filtered, all of the LVN peaks should be present // in the first replicate, and all of the NVN peaks should be present in the other. foreach (var nodeTranGroup in docContainer.Document.MoleculeTransitionGroups) { foreach (var docNode in nodeTranGroup.Children) { var nodeTran = (TransitionDocNode)docNode; Assert.IsTrue(nodeTran.HasResults); Assert.AreEqual(2, nodeTran.Results.Count); if ((nodeTran.Transition.Group.Peptide.IsCustomIon ? nodeTranGroup.CustomIon.Name : nodeTran.Transition.Group.Peptide.Sequence).StartsWith("LVN")) { Assert.IsTrue(nodeTran.Results[1][0].IsEmpty); } else { Assert.IsFalse(nodeTran.Results[1][0].IsEmpty); } } } // Chromatograms should be present in the cache for a number of isotopes. var docMs1Isotopes = docContainer.Document.ChangeSettings(doc.Settings .ChangeTransitionFullScan(fs => fs.ChangePrecursorIsotopes(FullScanPrecursorIsotopes.Count, 3, IsotopeEnrichments.DEFAULT)) .ChangeTransitionFilter(filter => filter.ChangeIonTypes(new[] { IonType.precursor }))); docCheckpoints.Add(docMs1Isotopes); AssertEx.IsDocumentState(docMs1Isotopes, null, 2, 2, 2); // Need to reset auto-manage for transitions var refineAutoSelect = new RefinementSettings { AutoPickChildrenAll = PickLevel.transitions }; docMs1Isotopes = refineAutoSelect.Refine(docMs1Isotopes); AssertEx.IsDocumentState(docMs1Isotopes, null, 2, 2, 6); AssertResult.IsDocumentResultsState(docMs1Isotopes, rep1, 1, 1, 0, 3, 0); AssertResult.IsDocumentResultsState(docMs1Isotopes, rep2, 1, 1, 0, 3, 0); docCheckpoints.Add(docMs1Isotopes); // Add M-1 transitions, and verify that they have chromatogram data also, but // empty peaks in all cases var docMs1All = docMs1Isotopes.ChangeSettings(docMs1Isotopes.Settings .ChangeTransitionFullScan(fs => fs.ChangePrecursorIsotopes(FullScanPrecursorIsotopes.Percent, 0, IsotopeEnrichments.DEFAULT)) .ChangeTransitionIntegration(i => i.ChangeIntegrateAll(false))); // For compatibility with v2.5 and earlier docCheckpoints.Add(docMs1All); AssertEx.IsDocumentState(docMs1All, null, 2, 2, 10); AssertResult.IsDocumentResultsState(docMs1All, rep1, 1, 1, 0, 4, 0); AssertResult.IsDocumentResultsState(docMs1All, rep2, 1, 1, 0, 4, 0); var ms1AllTranstions = docMs1All.MoleculeTransitions.ToArray(); var tranM1 = ms1AllTranstions[0]; Assert.AreEqual(-1, tranM1.Transition.MassIndex); Assert.IsTrue(tranM1.Results[0] != null && tranM1.Results[1] != null); Assert.IsTrue(tranM1.Results[0][0].IsEmpty && tranM1.Results[1][0].IsEmpty); tranM1 = ms1AllTranstions[5]; Assert.AreEqual(-1, tranM1.Transition.MassIndex); Assert.IsTrue(tranM1.Results[0] != null && tranM1.Results[1] != null); Assert.IsTrue(tranM1.Results[0][0].IsEmpty && tranM1.Results[1][0].IsEmpty); } }
private SrmDocument GetDocumentFinal(CancellationToken cancellationToken, SrmDocument doc, int minPeptides, bool removeRepeated, bool removeDuplicate, out int?emptyProteins) { emptyProteins = null; // Remove repeated/duplicate peptides var newDoc = removeRepeated || removeDuplicate ? new RefinementSettings { RemoveRepeatedPeptides = removeRepeated, RemoveDuplicatePeptides = removeDuplicate }.Refine(doc) : doc; if (cancellationToken.IsCancellationRequested) { return(null); } // Remove proteins without enough peptides newDoc = ImportPeptideSearch.RemoveProteinsByPeptideCount(newDoc, minPeptides); if (cancellationToken.IsCancellationRequested) { return(null); } // Move iRT proteins to top var irtPeptides = new HashSet <Target>(RCalcIrt.IrtPeptides(newDoc)); var proteins = new List <PeptideGroupDocNode>(newDoc.PeptideGroups); var proteinsIrt = new List <PeptideGroupDocNode>(); for (var i = 0; i < proteins.Count; i++) { var nodePepGroup = proteins[i]; if (nodePepGroup.Peptides.All(nodePep => irtPeptides.Contains(new Target(nodePep.ModifiedSequence)))) { proteinsIrt.Add(nodePepGroup); proteins.RemoveAt(i--); } } if (proteinsIrt.Any()) { newDoc = (SrmDocument)newDoc.ChangeChildrenChecked(proteinsIrt.Concat(proteins).Cast <DocNode>().ToArray()); } if (cancellationToken.IsCancellationRequested) { return(null); } // Add decoys newDoc = AddDecoys(newDoc); if (cancellationToken.IsCancellationRequested) { return(null); } // Count empty proteins emptyProteins = newDoc.PeptideGroups.Count(pepGroup => pepGroup.PeptideCount == 0); if (cancellationToken.IsCancellationRequested) { return(null); } return(newDoc); }
protected override void DoTest() { // Clear all the settings lists that will be defined in this tutorial ClearSettingsLists(); // Open the file RunUI(() => SkylineWindow.OpenFile(GetTestPath(DIA_START_CHECKPOINT))); WaitForDocumentLoaded(); // Specify DIA acquisition scheme and machine settings var transitionSettings = ShowDialog <TransitionSettingsUI>(SkylineWindow.ShowTransitionSettingsUI); RunUI(() => { transitionSettings.SelectedTab = TransitionSettingsUI.TABS.FullScan; transitionSettings.AcquisitionMethod = FullScanAcquisitionMethod.DIA; transitionSettings.PrecursorIsotopesCurrent = FullScanPrecursorIsotopes.Count; transitionSettings.PrecursorMassAnalyzer = FullScanMassAnalyzerType.orbitrap; transitionSettings.PrecursorRes = 35000; transitionSettings.PrecursorResMz = 200; transitionSettings.ProductMassAnalyzer = FullScanMassAnalyzerType.orbitrap; transitionSettings.ProductRes = 17500; transitionSettings.ProductResMz = 200; }); PauseForScreenShot <TransitionSettingsUI.FullScanTab>("Transition Settings - Full-Scan", 4); // Set up isolation scheme var isolationSchemeDlg = ShowDialog <EditIsolationSchemeDlg>(transitionSettings.AddIsolationScheme); PauseForScreenShot <EditIsolationSchemeDlg>("Edit Isolation Scheme form", 5); RunUI(() => { isolationSchemeDlg.UseResults = false; }); var calculateIsolationDlg = ShowDialog <CalculateIsolationSchemeDlg>(isolationSchemeDlg.Calculate); RunUI(() => { calculateIsolationDlg.WindowWidth = 20; calculateIsolationDlg.Start = 500; calculateIsolationDlg.End = 900; calculateIsolationDlg.OptimizeWindowPlacement = true; }); PauseForScreenShot <CalculateIsolationSchemeDlg>("Calculate Isolation Scheme form", 6); OkDialog(calculateIsolationDlg, calculateIsolationDlg.OkDialog); PauseForScreenShot <EditIsolationSchemeDlg>("Edit Isolation Scheme Dialog Filled", 7); var isolationSchemeGraphDlg = ShowDialog <DiaIsolationWindowsGraphForm>(isolationSchemeDlg.OpenGraph); PauseForScreenShot <DiaIsolationWindowsGraphForm>("Graph of Isolation Scheme", 8); OkDialog(isolationSchemeGraphDlg, isolationSchemeGraphDlg.CloseButton); RunUI(() => isolationSchemeDlg.IsolationSchemeName = "500 to 900 by 20"); OkDialog(isolationSchemeDlg, isolationSchemeDlg.OkDialog); OkDialog(transitionSettings, transitionSettings.OkDialog); // Export isolation scheme var exportIsolationDlg = ShowDialog <ExportMethodDlg>(() => SkylineWindow.ShowExportMethodDialog(ExportFileType.IsolationList)); PauseForScreenShot <ExportMethodDlg>("Export Isolation List form", 9); OkDialog(exportIsolationDlg, () => exportIsolationDlg.OkDialog(GetTestPath("DIA_tutorial_isolation_list.csv"))); // Adjust modifications and filter var newPeptideSettings = ShowDialog <PeptideSettingsUI>(SkylineWindow.ShowPeptideSettingsUI); RunUI(() => newPeptideSettings.AutoSelectMatchingPeptides = true); OkDialog(newPeptideSettings, newPeptideSettings.OkDialog); // Set up chromatogram retention time restriction var newTransitionSettings = ShowDialog <TransitionSettingsUI>(SkylineWindow.ShowTransitionSettingsUI); RunUI(() => newTransitionSettings.SetRetentionTimeFilter(RetentionTimeFilterType.ms2_ids, 5.0)); PauseForScreenShot <TransitionSettingsUI.FullScanTab>("Retention time filtering options", 16); // Adjust library transition ranking RunUI(() => { newTransitionSettings.SelectedTab = TransitionSettingsUI.TABS.Library; newTransitionSettings.UseLibraryPick = true; newTransitionSettings.Filtered = true; }); PauseForScreenShot <TransitionSettingsUI.LibraryTab>("Transition Settings - Library tab", 22); OkDialog(newTransitionSettings, newTransitionSettings.OkDialog); PauseForScreenShot <SequenceTreeForm>("Targets pane with precursors and best 5 transitions only", 23); // Build spectral library using Import Peptide Search RunUI(() => SkylineWindow.SaveDocument(GetTestPath(DIA_TUTORIAL_CHECKPOINT))); // "Build Spectral Library" page var importPeptideSearchDlg = ShowDialog <ImportPeptideSearchDlg>(() => SkylineWindow.ShowImportPeptideSearchDlg()); RunUI(() => { Assert.IsTrue(importPeptideSearchDlg.CurrentPage == ImportPeptideSearchDlg.Pages.spectra_page); importPeptideSearchDlg.BuildPepSearchLibControl.AddSearchFiles(new[] { GetTestPath("interact-20130311_DDA_Pit01.pep.xml") }); // Not L10N importPeptideSearchDlg.BuildPepSearchLibControl.WorkflowType = ImportPeptideSearchDlg.Workflow.dia; }); PauseForScreenShot <BuildLibraryDlg>("Build Library form - input files", 24); const string prefixKeep = "DIA_Pit0"; if (IsFullImportMode) { SrmDocument doc = SkylineWindow.Document; RunUI(() => Assert.IsTrue(importPeptideSearchDlg.ClickNextButton())); doc = WaitForDocumentChange(doc); PauseForScreenShot <ImportPeptideSearchDlg.ChromatogramsDiaPage>("Import Results page", 25); // "Extract Chromatograms" page RunUI(() => { Assert.IsTrue(importPeptideSearchDlg.CurrentPage == ImportPeptideSearchDlg.Pages.chromatograms_page); importPeptideSearchDlg.ImportResultsControl.FoundResultsFiles = _importFiles.Select(f => new ImportPeptideSearch.FoundResultsFile(f, GetTestPath(f + ExtensionTestContext.ExtThermoRaw))).ToList(); }); var importResultsNameDlg = ShowDialog <ImportResultsNameDlg>(importPeptideSearchDlg.ClickNextButtonNoCheck); RunUI(() => { string prefix = importResultsNameDlg.Prefix; Assert.IsTrue(prefix.EndsWith(prefixKeep)); importResultsNameDlg.Prefix = prefix.Substring(0, prefix.Length - prefixKeep.Length); importResultsNameDlg.YesDialog(); }); WaitForClosedForm(importResultsNameDlg); // "Add Modifications" page RunUI(() => { const string modCarbamidomethyl = "Carbamidomethyl (C)"; const string modOxidation = "Oxidation (M)"; Assert.IsTrue(importPeptideSearchDlg.CurrentPage == ImportPeptideSearchDlg.Pages.match_modifications_page); // Define expected matched/unmatched modifications var expectedMatched = new[] { modCarbamidomethyl, modOxidation }; // Verify matched/unmatched modifications AssertEx.AreEqualDeep(expectedMatched, importPeptideSearchDlg.MatchModificationsControl.MatchedModifications.ToArray()); Assert.IsFalse(importPeptideSearchDlg.MatchModificationsControl.UnmatchedModifications.Any()); importPeptideSearchDlg.MatchModificationsControl.CheckedModifications = new[] { modCarbamidomethyl }; Assert.IsTrue(importPeptideSearchDlg.ClickNextButton()); }); WaitForDocumentChange(doc); // "Configure Transition Settings" page RunUI(() => { Assert.IsTrue(importPeptideSearchDlg.CurrentPage == ImportPeptideSearchDlg.Pages.transition_settings_page); importPeptideSearchDlg.TransitionSettingsControl.PeptidePrecursorCharges = Adduct.ProtonatedFromCharges(1, 2, 3, 4); importPeptideSearchDlg.TransitionSettingsControl.PeptideIonCharges = Adduct.ProtonatedFromCharges(1, 2); importPeptideSearchDlg.TransitionSettingsControl.PeptideIonTypes = new[] { IonType.y, IonType.b, IonType.precursor }; importPeptideSearchDlg.TransitionSettingsControl.ExclusionUseDIAWindow = true; importPeptideSearchDlg.TransitionSettingsControl.IonCount = 5; importPeptideSearchDlg.TransitionSettingsControl.IonMatchTolerance = 0.05; Assert.IsTrue(importPeptideSearchDlg.ClickNextButton()); }); // "Configure Full-Scan Settings" page RunUI(() => { Assert.IsTrue(importPeptideSearchDlg.CurrentPage == ImportPeptideSearchDlg.Pages.full_scan_settings_page); Assert.IsTrue(importPeptideSearchDlg.ClickNextButton()); }); // "Import FASTA" page RunUI(() => { importPeptideSearchDlg.ImportFastaControl.SetFastaContent(GetTestPath("pituitary_database.fasta")); Assert.IsTrue(importPeptideSearchDlg.ClickNextButton()); }); WaitForClosedForm(importPeptideSearchDlg); WaitForCondition(10 * 60 * 1000, () => SkylineWindow.Document.Settings.MeasuredResults.IsLoaded); // 10 minutes RunUI(() => { SkylineWindow.SaveDocument(GetTestPath(DIA_IMPORTED_CHECKPOINT)); SkylineWindow.SaveDocument(GetTestPath(DIA_TUTORIAL_CHECKPOINT)); }); } else { OkDialog(importPeptideSearchDlg, importPeptideSearchDlg.CancelDialog); RunUI(() => SkylineWindow.OpenFile(GetTestPath(DIA_IMPORTED_CHECKPOINT))); } WaitForDocumentLoaded(); WaitForGraphs(); RunUI(() => { SkylineWindow.ExpandPrecursors(); SkylineWindow.Size = new Size(750, 788); }); // Generate decoys // var decoysDlg = ShowDialog<GenerateDecoysDlg>(SkylineWindow.ShowGenerateDecoysDlg); // PauseForScreenShot<GenerateDecoysDlg>("Add Decoy Peptides form", 24); // RunUI(() => // { // decoysDlg.NumDecoys = 26; // Assert.AreEqual(decoysDlg.DecoysMethod, DecoyGeneration.SHUFFLE_SEQUENCE); // }); // OkDialog(decoysDlg, decoysDlg.OkDialog); // RunUI(() => SkylineWindow.SequenceTree.TopNode = SkylineWindow.SequenceTree.SelectedNode.PrevNode.Nodes[6]); // PauseForScreenShot<SequenceTreeForm>("Targets pane with decoys added", 25); RunUI(() => { SkylineWindow.CollapsePeptides(); SkylineWindow.SelectedPath = SkylineWindow.Document.GetPathTo((int)SrmDocument.Level.Molecules, 6); var nodePepTree = SkylineWindow.SelectedNode as PeptideTreeNode; Assert.IsNotNull(nodePepTree); Assert.AreEqual("VLQAVLPPLPQVVCTYR", nodePepTree.DocNode.Peptide.Sequence); SkylineWindow.ShowSplitChromatogramGraph(true); SkylineWindow.AutoZoomBestPeak(); var graphChrom = SkylineWindow.GetGraphChrom(prefixKeep + "1"); var labelStrings = graphChrom.GetAnnotationLabelStrings().ToArray(); Assert.IsTrue(labelStrings.Contains(string.Format("{0}\n+{1} ppm", 75.4, 3)), string.Format("Missing expected label in {0}", string.Join("|", labelStrings))); SkylineWindow.Width = 1250; }); RunDlg <ChromChartPropertyDlg>(SkylineWindow.ShowChromatogramProperties, dlg => { dlg.FontSize = GraphFontSize.NORMAL; dlg.OkDialog(); }); RestoreViewOnScreen(27); PauseForScreenShot <GraphChromatogram>("Chromatogram graph metafile", 26); RunUI(() => { SkylineWindow.SelectedNode.Expand(); var nodeTree = SkylineWindow.SelectedNode.Nodes[0].Nodes[0] as SrmTreeNode; Assert.IsNotNull(nodeTree); Assert.AreEqual((int)SequenceTree.StateImageId.no_peak, nodeTree.StateImageIndex); }); PauseForScreenShot <SequenceTreeForm>("Targets view - ", 27); RunUI(() => { SkylineWindow.SetIntegrateAll(true); var nodeTree = SkylineWindow.SelectedNode.Nodes[0].Nodes[0] as SrmTreeNode; Assert.IsNotNull(nodeTree); Assert.AreEqual((int)SequenceTree.StateImageId.peak, nodeTree.StateImageIndex); var nodeGroupTree = SkylineWindow.SelectedNode.Nodes[0] as TransitionGroupTreeNode; Assert.IsNotNull(nodeGroupTree); Assert.AreEqual(0.99, nodeGroupTree.DocNode.GetIsotopeDotProduct(0) ?? 0, 0.005); Assert.AreEqual(0.83, nodeGroupTree.DocNode.GetLibraryDotProduct(0) ?? 0, 0.005); SkylineWindow.ShowOtherRunPeptideIDTimes(true); }); PauseForScreenShot <GraphChromatogram>("Chromatogram graph metafile - with ID lines", 28); RunUI(() => { SkylineWindow.AutoZoomNone(); SkylineWindow.SelectedPath = SkylineWindow.Document.GetPathTo((int)SrmDocument.Level.Molecules, 1); }); PauseForScreenShot <GraphChromatogram>("Chromatogram graph metafile - zoomed out and small peak", 30); RunUI(SkylineWindow.AutoZoomBestPeak); PauseForScreenShot <GraphChromatogram>("Chromatogram graph metafile - zoomed to peak", 31); if (IsFullImportMode) { ClickChromatogram(74.9, 1.775E+7, PaneKey.PRECURSORS); RestoreViewOnScreen(33); PauseForScreenShot <GraphFullScan>("Full Scan graph with precursors - zoom manually", 32); ClickChromatogram(74.8, 1.753E+6, PaneKey.PRODUCTS); PauseForScreenShot <GraphFullScan>("Full Scan graph showing y7", 33); ClickChromatogram(74.9, 9.64E+5, PaneKey.PRODUCTS); PauseForScreenShot <GraphFullScan>("Full Scan graph showing b3 - zoom manually", 34); ClickChromatogram(74.9, 1.25E+5, PaneKey.PRODUCTS); PauseForScreenShot <GraphFullScan>("Full Scan graph showing y3 - zoom manually", 34); } RunUI(() => { SkylineWindow.SelectedPath = SkylineWindow.Document.GetPathTo((int)SrmDocument.Level.Molecules, 2); Assert.AreEqual("CNTDYSDCIHEAIK", ((PeptideTreeNode)SkylineWindow.SelectedNode).DocNode.Peptide.Sequence); }); PauseForScreenShot <GraphChromatogram>("Chromatogram graph metafile - split between two precursors", 35); RunUI(() => { SkylineWindow.SelectedNode.Expand(); SkylineWindow.SelectedPath = ((SrmTreeNode)SkylineWindow.SelectedNode.Nodes[0]).Path; }); PauseForScreenShot <GraphChromatogram>("Chromatogram graph metafile - double charged precursor", 36); RunUI(() => { SkylineWindow.SelectedPath = SkylineWindow.Document.GetPathTo((int)SrmDocument.Level.Molecules, 3); Assert.AreEqual("ELVYETVR", ((PeptideTreeNode)SkylineWindow.SelectedNode).DocNode.Peptide.Sequence); }); RunUI(() => { SkylineWindow.SelectedNode.Expand(); var nodeGroupTree = SkylineWindow.SelectedNode.Nodes[0] as TransitionGroupTreeNode; Assert.IsNotNull(nodeGroupTree); Assert.AreEqual(0.99, nodeGroupTree.DocNode.GetIsotopeDotProduct(0) ?? 0, 0.005); Assert.AreEqual(0.99, nodeGroupTree.DocNode.GetIsotopeDotProduct(0) ?? 0, 0.005); }); RestoreViewOnScreen(38); PauseForScreenShot <GraphSpectrum>("Library Match view - zoom manually", 37); RestoreViewOnScreen(39); PauseForScreenShot <GraphChromatogram>("Chromatogram graph metafile", 38); if (IsFullImportMode) { RestoreViewOnScreen(40); ClickChromatogram(41.9, 1.166E+8, PaneKey.PRECURSORS); PauseForScreenShot <GraphFullScan>("Full Scan graph showing precursor interference - zoom manually", 39); RunUI(() => SkylineWindow.GraphFullScan.ChangeScan(-12)); CheckFullScanSelection(41.7, 1.532E+8, PaneKey.PRECURSORS); PauseForScreenShot <GraphFullScan>("Full Scan graph showing transition between interference and real peak - zoom manually", 39); } // Clear all the settings lists that were defined in this tutorial ClearSettingsLists(); }
private bool IsCachedFile(SrmDocument doc, ChromFileInfo info) { return(doc.Settings.MeasuredResults.IsCachedFile(info.FilePath)); }
/// <summary> /// Method used to encapsulate the running of a executable for threading. /// </summary> /// <param name="document"> Contains the document to base reports off of, as well as to serve as the parent for args collector forms. </param> /// <param name="toolMacroProvider"> Interface for determining what to replace macros with. </param> /// <param name="textWriter"> A textWriter to write to if outputting to the immediate window. </param> /// <param name="progressMonitor"> Progress monitor. </param> /// <param name="parent">If there is an Args Collector form, it will be showed on this control. Can be null. </param> private void RunExecutableBackground(SrmDocument document, IToolMacroProvider toolMacroProvider, TextWriter textWriter, IProgressMonitor progressMonitor, Control parent) { // Need to know if $(InputReportTempPath) is an argument to determine if a report should be piped to stdin or not. bool containsInputReportTempPath = Arguments.Contains(ToolMacros.INPUT_REPORT_TEMP_PATH); string command = GetCommand(document, toolMacroProvider, progressMonitor); if (command == null) // Has already thrown the error. { return; } string args = GetArguments(document, toolMacroProvider, progressMonitor); string initDir = GetInitialDirectory(document, toolMacroProvider, progressMonitor); // If either of these fails an Exception is thrown. if (args != null && initDir != null) { ProcessStartInfo startInfo = new ProcessStartInfo(command, args) { WorkingDirectory = initDir }; if (OutputToImmediateWindow) { startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.CreateNoWindow = true; startInfo.UseShellExecute = false; startInfo.StandardOutputEncoding = Encoding.UTF8; startInfo.StandardErrorEncoding = Encoding.UTF8; } // if it has a selected report title and its doesn't have a InputReportTempPath macro then the report needs to be piped to stdin. string reportCsv = null; if (!string.IsNullOrEmpty(ReportTitle) && !containsInputReportTempPath) // Then pipe to stdin. { reportCsv = ToolDescriptionHelpers.GetReport(document, ReportTitle, Title, progressMonitor); startInfo.RedirectStandardInput = true; } //Consider: Maybe throw an error if one is not null but the other is? //If there is an IToolArgsCollector run it! if (!string.IsNullOrEmpty(ArgsCollectorDllPath) && !string.IsNullOrEmpty(ArgsCollectorClassName)) { string pathReportCsv = !string.IsNullOrEmpty(ReportTitle) && containsInputReportTempPath ? ToolMacros.GetReportTempPath(ReportTitle, Title) : null; if (!CallArgsCollector(parent, args, reportCsv, pathReportCsv, startInfo)) { return; } } Process p = new Process { StartInfo = startInfo }; if (OutputToImmediateWindow) { p.EnableRaisingEvents = true; TextBoxStreamWriterHelper boxStreamWriterHelper = textWriter as TextBoxStreamWriterHelper; if (boxStreamWriterHelper == null) { p.OutputDataReceived += (sender, dataReceivedEventArgs) => textWriter.WriteLine(p.Id + ">" + dataReceivedEventArgs.Data); // Not L10N p.ErrorDataReceived += (sender, dataReceivedEventArgs) => textWriter.WriteLine(p.Id + ">" + dataReceivedEventArgs.Data); // Not L10N } else { p.OutputDataReceived += (sender, dataReceivedEventArgs) => boxStreamWriterHelper.WriteLineWithIdentifier(p.Id, dataReceivedEventArgs.Data); p.ErrorDataReceived += (sender, dataReceivedEventArgs) => boxStreamWriterHelper.WriteLineWithIdentifier(p.Id, dataReceivedEventArgs.Data); //p.Refresh(); p.Exited += (sender, processExitedEventArgs) => boxStreamWriterHelper.HandleProcessExit(p.Id); } textWriter.WriteLine("\"" + p.StartInfo.FileName + "\" " + p.StartInfo.Arguments); // Not L10N } // else // { // startInfo.RedirectStandardOutput = true; // startInfo.RedirectStandardError = true; // startInfo.CreateNoWindow = true; // startInfo.UseShellExecute = false; // p.EnableRaisingEvents = true; // p.OutputDataReceived += // (sender, dataReceivedEventArgs) => Console.WriteLine(dataReceivedEventArgs.Data); // p.ErrorDataReceived += // (sender, dataReceivedEventArgs) => Console.WriteLine(dataReceivedEventArgs.Data); // } try { p.StartInfo.UseShellExecute = false; p.Start(); if (OutputToImmediateWindow) { p.BeginOutputReadLine(); p.BeginErrorReadLine(); } // write the reportCsv string to stdin. // need to only check one of these conditions. if (startInfo.RedirectStandardInput && (reportCsv != null)) { StreamWriter streamWriter = p.StandardInput; streamWriter.Write(reportCsv); streamWriter.Flush(); streamWriter.Close(); } } catch (Exception ex) { if (ex is Win32Exception) { throw new ToolExecutionException( TextUtil.LineSeparate( Resources.ToolDescription_RunTool_File_not_found_, Resources.ToolDescription_RunTool_Please_check_the_command_location_is_correct_for_this_tool_), ex); } else { throw new ToolExecutionException( TextUtil.LineSeparate( Resources.ToolDescription_RunTool_Please_reconfigure_that_tool__it_failed_to_execute__, ex.Message), ex); } } // CONSIDER: We don't delete the temp path here, because the file may be open // in a long running application like Excel. // if (ReportTempPath_toDelete != null) // { // FileEx.SafeDelete(ReportTempPath_toDelete, true); // ReportTempPath_toDelete = null; // } } }
private void SetDocument(SrmDocument document) { ChromCacheMinimizer = document.Settings.HasResults ? document.Settings.MeasuredResults.GetChromCacheMinimizer(document) : null; }
public ResultsTestDocumentContainer(SrmDocument docInitial, string pathInitial, bool wait) : base(docInitial, pathInitial, wait) { }
public override void UpdateGraph(bool selectionChanged) { SrmDocument document = GraphSummary.DocumentUIContainer.DocumentUI; var results = document.Settings.MeasuredResults; bool resultsAvailable = results != null; Clear(); if (!resultsAvailable) { Title.Text = Resources.RTReplicateGraphPane_UpdateGraph_No_results_available; EmptyGraph(document); return; } var selectedTreeNode = GraphSummary.StateProvider.SelectedNode as SrmTreeNode ?? GraphSummary.StateProvider.SelectedNodes.OfType <SrmTreeNode>().FirstOrDefault(); if (selectedTreeNode == null || document.FindNode(selectedTreeNode.Path) == null) { EmptyGraph(document); return; } Title.Text = null; DisplayTypeChrom displayType = GraphChromatogram.GetDisplayType(document, selectedTreeNode); DocNode selectedNode = selectedTreeNode.Model; IdentityPath selectedPath = selectedTreeNode.Path; DocNode parentNode = selectedNode; IdentityPath parentPath = selectedTreeNode.Path; // If the selected tree node is a transition, then its siblings are displayed. if (selectedTreeNode is TransitionTreeNode) { if (displayType != DisplayTypeChrom.single) { SrmTreeNode parentTreeNode = selectedTreeNode.SrmParent; parentNode = parentTreeNode.Model; selectedPath = parentTreeNode.Path; } } // If the selected node is a peptide with one child, then show the children, // unless chromatogram display type is total else if (selectedTreeNode is PeptideTreeNode) { var children = ((DocNodeParent)selectedNode).Children; if (children.Count == 1 && displayType != DisplayTypeChrom.total) { selectedNode = parentNode = children[0]; selectedPath = new IdentityPath(parentPath, children[0].Id); } } else if (!(selectedTreeNode is PeptideGroupTreeNode) && !(selectedTreeNode is TransitionGroupTreeNode)) { Title.Text = Resources.RTReplicateGraphPane_UpdateGraph_Select_a_peptide_to_see_the_retention_time_graph; CanShowRTLegend = false; return; } // If a precursor is going to be displayed with display type single if (parentNode is TransitionGroupDocNode && displayType == DisplayTypeChrom.single) { // If no optimization data, then show all the transitions if (!results.Chromatograms.Contains(chrom => chrom.OptimizationFunction != null)) { displayType = DisplayTypeChrom.all; } } var rtTransformOp = GraphSummary.StateProvider.GetRetentionTimeTransformOperation(); var rtValue = RTPeptideGraphPane.RTValue; ReplicateGroupOp replicateGroupOp; if (rtValue == RTPeptideValue.All) { replicateGroupOp = ReplicateGroupOp.FromCurrentSettings(document, GraphValues.AggregateOp.MEAN); } else { replicateGroupOp = ReplicateGroupOp.FromCurrentSettings(document); } var retentionTimeValue = new GraphValues.RetentionTimeTransform(rtValue, rtTransformOp, replicateGroupOp.AggregateOp); YAxis.Title.Text = retentionTimeValue.GetAxisTitle(); var peptidePaths = GetSelectedPeptides().GetUniquePeptidePaths().ToList(); // if PeptideGroupTreeNode is selected but has only one child isMultiSelect should still be true IsMultiSelect = peptidePaths.Count > 1 || (peptidePaths.Count == 1 && GraphSummary.StateProvider.SelectedNodes.FirstOrDefault() is PeptideGroupTreeNode); GraphData graphData = new RTGraphData(document, IsMultiSelect ? peptidePaths : new[] { selectedPath }.AsEnumerable(), displayType, retentionTimeValue, replicateGroupOp); CanShowRTLegend = graphData.DocNodes.Count != 0; InitFromData(graphData); int selectedReplicateIndex = SelectedIndex; double minRetentionTime = double.MaxValue; double maxRetentionTime = -double.MaxValue; int iColor = 0, iCharge = -1; var charge = Adduct.EMPTY; int countLabelTypes = document.Settings.PeptideSettings.Modifications.CountLabelTypes; int colorOffset = 0; var transitionGroupDocNode = parentNode as TransitionGroupDocNode; if (transitionGroupDocNode != null && displayType == DisplayTypeChrom.products) { // If we are only displaying product ions, we want to use an offset in the colors array // so that we do not re-use colors that would be used for any precursor ions. colorOffset = GraphChromatogram.GetDisplayTransitions(transitionGroupDocNode, DisplayTypeChrom.precursors).Count(); } for (int i = 0; i < graphData.DocNodes.Count; i++) { var docNode = graphData.DocNodes[i]; var identityPath = graphData.DocNodePaths[i]; var pointPairLists = graphData.PointPairLists[i]; int numSteps = pointPairLists.Count / 2; for (int iStep = 0; iStep < pointPairLists.Count; iStep++) { int step = iStep - numSteps; var pointPairList = pointPairLists[iStep]; Color color; var isSelected = false; var nodeGroup = docNode as TransitionGroupDocNode; if (IsMultiSelect) { var peptides = peptidePaths.Select(path => document.FindNode(path)) .Cast <PeptideDocNode>().ToArray(); var peptideDocNode = peptides.FirstOrDefault( peptide => 0 <= peptide.FindNodeIndex(docNode.Id)); if (peptideDocNode == null) { continue; } color = GraphSummary.StateProvider.GetPeptideGraphInfo(peptideDocNode).Color; if (identityPath.Equals(selectedTreeNode.Path) && step == 0) { color = ChromGraphItem.ColorSelected; isSelected = true; } } else if (parentNode is PeptideDocNode) { // Resharper code inspection v9.0 on TC gets this one wrong // ReSharper disable ExpressionIsAlwaysNull int iColorGroup = GetColorIndex(nodeGroup, countLabelTypes, ref charge, ref iCharge); // ReSharper restore ExpressionIsAlwaysNull color = COLORS_GROUPS[iColorGroup % COLORS_GROUPS.Count]; } else if (displayType == DisplayTypeChrom.total) { color = COLORS_GROUPS[iColor % COLORS_GROUPS.Count]; } else if (ReferenceEquals(docNode, selectedNode) && step == 0) { color = ChromGraphItem.ColorSelected; isSelected = true; } else { color = COLORS_TRANSITION[(iColor + colorOffset) % COLORS_TRANSITION.Count]; } iColor++; string label = graphData.DocNodeLabels[i]; if (step != 0) { label = string.Format(Resources.RTReplicateGraphPane_UpdateGraph_Step__0__, step); } CurveItem curveItem; if (IsMultiSelect) { if (rtValue != RTPeptideValue.All) { curveItem = CreateLineItem(label, pointPairList, color); } else { curveItem = CreateMultiSelectBarItem(label, pointPairList, color); } } else if (HiLowMiddleErrorBarItem.IsHiLoMiddleErrorList(pointPairList)) { curveItem = new HiLowMiddleErrorBarItem(label, pointPairList, color, Color.Black); BarSettings.Type = BarType.Cluster; } else if (rtValue == RTPeptideValue.All) { curveItem = new MeanErrorBarItem(label, pointPairList, color, Color.Black); BarSettings.Type = BarType.Cluster; } else { curveItem = CreateLineItem(label, pointPairList, color); } if (curveItem != null) { curveItem.Tag = identityPath; var barItem = curveItem as BarItem; if (barItem != null) { barItem.Bar.Border.IsVisible = false; barItem.Bar.Fill.Brush = GetBrushForNode(document.Settings, docNode, color); if (!isSelected) { barItem.SortedOverlayPriority = 1; } } CurveList.Add(curveItem); if (selectedReplicateIndex != -1 && selectedReplicateIndex < pointPairList.Count) { PointPair pointPair = pointPairList[selectedReplicateIndex]; if (!pointPair.IsInvalid) { minRetentionTime = Math.Min(minRetentionTime, pointPair.Z); maxRetentionTime = Math.Max(maxRetentionTime, pointPair.Y); } } } } } // Draw a box around the currently selected replicate if (ShowSelection && minRetentionTime != double.MaxValue) { AddSelection(selectedReplicateIndex, maxRetentionTime, minRetentionTime); } // Reset the scale when the parent node changes if (_parentNode == null || !ReferenceEquals(_parentNode.Id, parentNode.Id)) { XAxis.Scale.MaxAuto = XAxis.Scale.MinAuto = true; YAxis.Scale.MaxAuto = YAxis.Scale.MinAuto = true; } _parentNode = parentNode; Legend.IsVisible = !IsMultiSelect && Settings.Default.ShowRetentionTimesLegend; GraphSummary.GraphControl.Invalidate(); AxisChange(); }
public RTGraphData(SrmDocument document, IEnumerable <IdentityPath> selectedDocNodePaths, DisplayTypeChrom displayType, GraphValues.RetentionTimeTransform retentionTimeTransform, ReplicateGroupOp replicateGroupOp) : base(document, selectedDocNodePaths, displayType, replicateGroupOp, PaneKey.DEFAULT) { RetentionTimeTransform = retentionTimeTransform; }
public static PeptideQuantifier GetPeptideQuantifier(SrmDocument document, PeptideGroupDocNode peptideGroup, PeptideDocNode peptide) { return(GetPeptideQuantifier(() => NormalizationData.GetNormalizationData(document, false, null), document.Settings, peptideGroup, peptide)); }
public static void ReportToCsv(ReportSpec reportSpec, SrmDocument doc, string fileName) { CheckReportCompatibility.ReportToCsv(reportSpec, doc, fileName, CultureInfo.CurrentCulture); }
public void DoAsymmetricIsolationTest(RefinementSettings.ConvertToSmallMoleculesMode asSmallMolecules) { if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.none && !RunSmallMoleculeTestVersions) { Console.Write(MSG_SKIPPING_SMALLMOLECULE_TEST_VERSION); return; } LocalizationHelper.InitThread(); // TODO: All unit tests should be correctly initialized var testFilesDir = new TestFilesDir(TestContext, ZIP_FILE); string docPath = testFilesDir.GetTestPath("Asym_DIA.sky"); string cachePath = ChromatogramCache.FinalPathForName(docPath, null); FileEx.SafeDelete(cachePath); SrmDocument doc = ResultsUtil.DeserializeDocument(docPath); var refine = new RefinementSettings(); doc = refine.ConvertToSmallMolecules(doc, testFilesDir.FullPath, asSmallMolecules); const int expectedMoleculeCount = 1; // At first small molecules did not support multiple charge states, and this was 2 for that test mode AssertEx.IsDocumentState(doc, null, 1, expectedMoleculeCount, 2, 4); var fullScanInitial = doc.Settings.TransitionSettings.FullScan; Assert.IsTrue(fullScanInitial.IsEnabledMsMs); Assert.AreEqual(FullScanAcquisitionMethod.DIA, fullScanInitial.AcquisitionMethod); Assert.AreEqual(25, fullScanInitial.PrecursorFilter); AssertEx.Serializable(doc); using (var docContainer = new ResultsTestDocumentContainer(doc, docPath)) { // Import the first RAW file (or mzML for international) string rawPath = testFilesDir.GetTestPath("Asym_DIA_data.mzML"); var measuredResults = new MeasuredResults(new[] { new ChromatogramSet("Single", new[] { rawPath }) }); TransitionGroupDocNode nodeGroup; double ratio; const double poorRatio = 0.25; const double fixedRatio = 1.05; { // Import with symmetric isolation window SrmDocument docResults = docContainer.ChangeMeasuredResults(measuredResults, expectedMoleculeCount, 1, 1, 2, 2); nodeGroup = docResults.MoleculeTransitionGroups.First(); ratio = nodeGroup.Results[0][0].Ratio ?? 0; // The expected ratio is 1.0, but the symmetric isolation window should produce poor results if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.masses_only) // Can't use labels without a formula { Assert.AreEqual(poorRatio, ratio, 0.05); } // Revert to original document, and get rid of results cache Assert.IsTrue(docContainer.SetDocument(doc, docResults, false)); FileEx.SafeDelete(testFilesDir.GetTestPath("Asym_DIA.skyd")); } { // Import with asymmetric isolation window SrmDocument docAsym = doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(fullScan => fullScan.ChangeAcquisitionMethod(fullScan.AcquisitionMethod, new IsolationScheme("Test asym", 5, 20)))); AssertEx.Serializable(docAsym); Assert.IsTrue(docContainer.SetDocument(docAsym, doc, false)); SrmDocument docResults = docContainer.ChangeMeasuredResults(measuredResults, expectedMoleculeCount, 1, 1, 2, 2); nodeGroup = docResults.MoleculeTransitionGroups.First(); ratio = nodeGroup.Results[0][0].Ratio ?? 0; // Asymmetric should be a lot closer to 1.0 if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.masses_only) // Can't use labels without a formula { Assert.AreEqual(fixedRatio, ratio, 0.05); } // Revert to original document, and get rid of results cache Assert.IsTrue(docContainer.SetDocument(doc, docResults, false)); FileEx.SafeDelete(testFilesDir.GetTestPath("Asym_DIA.skyd")); } { // Import with prespecified isolation windows var windowList = new List <IsolationWindow> { new IsolationWindow(999.2702214, 1024.270221), new IsolationWindow(1024.27267, 1049.27267) }; SrmDocument docPrespecified = doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(fullScan => fullScan.ChangeAcquisitionMethod(fullScan.AcquisitionMethod, new IsolationScheme("Test prespecified", windowList)))); AssertEx.Serializable(docPrespecified); Assert.IsTrue(docContainer.SetDocument(docPrespecified, doc, false)); SrmDocument docResults = docContainer.ChangeMeasuredResults(measuredResults, expectedMoleculeCount, 1, 1, 2, 2); nodeGroup = docResults.MoleculeTransitionGroups.First(); ratio = nodeGroup.Results[0][0].Ratio ?? 0; // Asymmetric should be a lot closer to 1.0 if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.masses_only) // Can't use labels without a formula { Assert.AreEqual(fixedRatio, ratio, 0.05); } // Revert to original document, and get rid of results cache Assert.IsTrue(docContainer.SetDocument(doc, docResults, false)); FileEx.SafeDelete(testFilesDir.GetTestPath("Asym_DIA.skyd")); } { // Import with prespecified targets var windowList = new List <IsolationWindow> { new IsolationWindow(999.2702214, 1024.270221, 1004.27), new IsolationWindow(1024.27267, 1049.27267, 1029.27) }; SrmDocument docPrespecified = doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(fullScan => fullScan.ChangeAcquisitionMethod(fullScan.AcquisitionMethod, new IsolationScheme("Test target", windowList)))); AssertEx.Serializable(docPrespecified); Assert.IsTrue(docContainer.SetDocument(docPrespecified, doc, false)); SrmDocument docResults = docContainer.ChangeMeasuredResults(measuredResults, expectedMoleculeCount, 1, 1, 2, 2); nodeGroup = docResults.MoleculeTransitionGroups.First(); ratio = nodeGroup.Results[0][0].Ratio ?? 0; // Asymmetric should be a lot closer to 1.0 if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.masses_only) // Can't use labels without a formula { Assert.AreEqual(fixedRatio, ratio, 0.05); } // Revert to original document, and get rid of results cache Assert.IsTrue(docContainer.SetDocument(doc, docResults, false)); FileEx.SafeDelete(testFilesDir.GetTestPath("Asym_DIA.skyd")); } { // Import with ambiguous prespecified targets var windowList = new List <IsolationWindow> { new IsolationWindow(999.2702214, 1024.270221, 1004.27), new IsolationWindow(1000.0, 1049.27267, 1004.28) }; SrmDocument docAmbiguous = doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(fullScan => fullScan.ChangeAcquisitionMethod(fullScan.AcquisitionMethod, new IsolationScheme("Test ambiguous", windowList)))); AssertEx.Serializable(docAmbiguous); Assert.IsTrue(docContainer.SetDocument(docAmbiguous, doc, false)); try { docContainer.ChangeMeasuredResults(measuredResults, expectedMoleculeCount, 1, 1, 2, 2); Assert.Fail("Expected ambiguous isolation targets."); } catch (Exception x) { AssertEx.AreComparableStrings(Resources.SpectrumFilter_FindFilterPairs_Two_isolation_windows_contain_targets_which_match_the_isolation_target__0__, x.Message, 1); } // Revert to original document, and get rid of results cache Assert.IsTrue(docContainer.SetDocument(doc, docContainer.Document, false)); FileEx.SafeDelete(testFilesDir.GetTestPath("Asym_DIA.skyd")); } { // Import with one isolation window, so one result is discarded. var windowList = new List <IsolationWindow> { new IsolationWindow(999.2702214, 1024.270221), }; SrmDocument docOneWindow = doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(fullScan => fullScan.ChangeAcquisitionMethod(fullScan.AcquisitionMethod, new IsolationScheme("Test one window", windowList)))); AssertEx.Serializable(docOneWindow); Assert.IsTrue(docContainer.SetDocument(docOneWindow, doc, false)); SrmDocument docResults = docContainer.ChangeMeasuredResults(measuredResults, 1, 1, 0, 2, 0); nodeGroup = docResults.MoleculeTransitionGroups.First(); Assert.IsNull(nodeGroup.Results[0][0].Ratio); // Revert to original document, and get rid of results cache Assert.IsTrue(docContainer.SetDocument(doc, docResults, false)); FileEx.SafeDelete(testFilesDir.GetTestPath("Asym_DIA.skyd")); } } testFilesDir.Dispose(); }
/// <summary> /// Return a string that is the InitialDirectoy string with the macros replaced. /// </summary> /// <param name="doc"> Document for report data. </param> /// <param name="toolMacroProvider"> Interface to use to get the current macro values </param> /// <param name="progressMonitor">Progress monitor. </param> /// <returns> InitialDirectory with macros replaced or null if one of the macros was missing /// (eg. no document for $(DocumentDir) then the return value is null </returns> public string GetInitialDirectory(SrmDocument doc, IToolMacroProvider toolMacroProvider, IProgressMonitor progressMonitor) { return(ToolMacros.ReplaceMacrosInitialDirectory(doc, toolMacroProvider, this, progressMonitor)); }
private void AddDocument(SrmDocument document) { // var fileIndices = document.Settings.HasResults ? // document.Settings.MeasuredResults.Chromatograms.SelectMany(set => set.MSDataFileInfos).Select( // info => info.FileIndex).ToArray() : new int[0]; // Console.WriteLine("--->"); foreach (PeptideDocNode nodePep in document.Peptides) { if (nodePep.HasResults) { PeptideResults += nodePep.Results.Where(result => !result.IsEmpty) .SelectMany(info => info).Count(); } foreach (TransitionGroupDocNode nodeGroup in nodePep.Children) { if (nodeGroup.HasResults) { // int startSize = TransitionGroupResults; foreach (var chromInfo in nodeGroup.Results.Where(result => !result.IsEmpty) .SelectMany(info => info)) { TransitionGroupResults++; if (chromInfo.Annotations.Note != null) { NoteCount++; } if (chromInfo.Annotations.ListAnnotations().Length > 0) { AnnotationCount++; } } // if (TransitionGroupResults - startSize < fileIndices.Length) // { // var listIds = fileIndices.ToList(); // foreach (var chromInfo in nodeGroup.Results.Where(result => result != null) // .SelectMany(info => info)) // { // listIds.Remove(chromInfo.FileIndex); // } // Console.WriteLine("{0} ({1})", nodePep.Peptide.Sequence, String.Join(", ", listIds.Select(i => i.ToString()).ToArray())); // } } foreach (var nodeTran in nodeGroup.Children.Cast <TransitionDocNode>().Where(nodeTran => nodeTran.HasResults)) { foreach (var chromInfo in nodeTran.Results.Where(result => !result.IsEmpty) .SelectMany(info => info)) { TransitionResults++; if (chromInfo.Annotations.Note != null) { NoteCount++; } if (chromInfo.Annotations.ListAnnotations().Length > 0) { AnnotationCount++; } if (chromInfo.IsUserSetManual) { UserSetCount++; } } } } } }
public bool UseCompactFormat(SrmDocument document) { return(_useCompactFormatFunc(document)); }
public void OkDialog() { var helper = new MessageBoxHelper(this); double qCutoff = double.MaxValue; if (reintegrateQCutoff.Checked) { if (!helper.ValidateDecimalTextBox(textBoxCutoff, 0.0, 1.0, out qCutoff)) return; } using (var longWaitDlg = new LongWaitDlg { Text = Resources.ReintegrateDlg_OkDialog_Reintegrating, }) { try { var scoringModel = _driverPeakScoringModel.SelectedItem; if (Equals(scoringModel, LegacyScoringModel.DEFAULT_UNTRAINED_MODEL)) { scoringModel = LegacyScoringModel.DEFAULT_MODEL; } if (scoringModel == null || !scoringModel.IsTrained) { throw new InvalidDataException(Resources.ReintegrateDlg_OkDialog_You_must_train_and_select_a_model_in_order_to_reintegrate_peaks_); } PeakTransitionGroupFeatureSet featureScores = null; if (ArrayUtil.EqualsDeep(_cacheCalculators, scoringModel.PeakFeatureCalculators)) featureScores = _cachedFeatureScores; var resultsHandler = new MProphetResultsHandler(Document, scoringModel, featureScores) { QValueCutoff = qCutoff, OverrideManual = checkBoxOverwrite.Checked, }; longWaitDlg.PerformWork(this, 1000, pm => { resultsHandler.ScoreFeatures(pm); if (resultsHandler.IsMissingScores()) { throw new InvalidDataException(Resources.ReintegrateDlg_OkDialog_The_current_peak_scoring_model_is_incompatible_with_one_or_more_peptides_in_the_document___Please_train_a_new_model_); } Document = resultsHandler.ChangePeaks(pm); }); if (longWaitDlg.IsCanceled) return; } catch (Exception x) { var message = TextUtil.LineSeparate(string.Format(Resources.ReintegrateDlg_OkDialog_Failed_attempting_to_reintegrate_peaks_), x.Message); MessageDlg.ShowWithException(this, message, x); return; } } var newPeakScoringModel = _driverPeakScoringModel.SelectedItem; if (!Equals(newPeakScoringModel, Document.Settings.PeptideSettings.Integration.PeakScoringModel)) { Document = Document.ChangeSettings(Document.Settings.ChangePeptideIntegration( i => i.ChangePeakScoringModel(newPeakScoringModel))); } DialogResult = DialogResult.OK; }
public DocResultsState(SrmDocument document) { AddDocument(document); }
protected override void DoTest() { // Set up initial document quickly, without involving UI SrmDocument document = new SrmDocument(SrmSettingsList.GetDefault()); var staticMods = new List <StaticMod>(document.Settings.PeptideSettings.Modifications.StaticModifications); staticMods.AddRange(new[] { new StaticMod("Phospho", "S,T,Y", null, true, "PO3H", LabelAtoms.None, RelativeRT.Matching, null, null, new[] { new FragmentLoss("PO4H3") }), new StaticMod("K(GlyGly)", "K", null, true, "N2H6C4O2", LabelAtoms.None, RelativeRT.Matching, null, null, null), }); document = document.ChangeSettings(document.Settings.ChangePeptideModifications(mods => mods.ChangeStaticModifications(staticMods).ChangeMaxNeutralLosses(2))); Assert.IsTrue(SkylineWindow.SetDocument(document, SkylineWindow.Document)); PasteTransitionListSkipColumnSelect(TRANSITIONLIST_CSV_MODLOSS_CLIPBOARD_TEXT); var docPaste1 = WaitForDocumentChange(document); AssertEx.IsDocumentState(docPaste1, null, 3, 4, 12); // revision # is hard to predict with background loaders running Assert.AreEqual(4, GetVariableModCount(docPaste1)); Assert.AreEqual(6, GetLossCount(docPaste1, 1)); string insertListText = I18n(TRANSITIONS_MODLOSS_CLIPBOARD_TEXT); SetClipboardTextUI(insertListText); RunDlg <PasteDlg>(SkylineWindow.ShowPasteTransitionListDlg, insertTransDlg => { insertTransDlg.IsMolecule = false; // Make sure it's ready to accept peptides rather than small molecules insertTransDlg.PasteTransitions(); insertTransDlg.OkDialog(); }); WaitForProteinMetadataBackgroundLoaderCompletedUI(); // Nothing should have changed RunUI(() => Assert.AreSame(docPaste1, SkylineWindow.DocumentUI)); // Revert to the original empty document RunUI(SkylineWindow.Undo); Assert.AreSame(document, SkylineWindow.Document); RunDlg <PasteDlg>(SkylineWindow.ShowPasteTransitionListDlg, insertTransDlg => { insertTransDlg.PasteTransitions(); insertTransDlg.OkDialog(); }); var docInsert1 = WaitForDocumentChange(document); AssertEx.IsDocumentState(docInsert1, null, 3, 4, 12); // revision # is hard to predict with background loaders running Assert.AreEqual(4, GetVariableModCount(docInsert1)); Assert.AreEqual(6, GetLossCount(docInsert1, 1)); string insertPart1 = I18n(TRANSITIONS_PREC_PART1_CLIPBOARD_TEXT); string insertPart2 = I18n(TRANSITIONS_PREC_PART2_CLIPBOARD_TEXT); string insertSep = I18n(TRANSITIONS_PREC_SEP_CLIPBOARD_TEXT); RunDlg <PasteDlg>(SkylineWindow.ShowPasteTransitionListDlg, insertTransDlg => { // Check error and grid cell selection for a bad product m/z VerifyTransitionListError(insertTransDlg, insertListText, 757.420279, 888.8888, 8, 2); // Non-numeric product m/z VerifyTransitionListError(insertTransDlg, insertListText, 908.447222, "x", Resources.PasteDlg_AddTransitionList_The_product_m_z_must_be_a_number_, 1, 2); // Check error and grid cell selection for a bad precursor m/z VerifyTransitionListError(insertTransDlg, insertListText, 648.352161, 777.7777, 6, 1); // Non-numeric precursor m/z VerifyTransitionListError(insertTransDlg, insertListText, 762.033412, "x", Resources.PasteDlg_AddTransitionList_The_precursor_m_z_must_be_a_number_, 0, 1); // Empty peptide VerifyTransitionListError(insertTransDlg, insertListText, "TISQSSSLKSSSNSNK", "", Resources.PasteDlg_ListPeptideSequences_The_peptide_sequence_cannot_be_blank, 9, 0); // Bad peptide VerifyTransitionListError(insertTransDlg, insertListText, "TISQSSSLKSSSNSNK", "BBBbBBBR", Resources.PasteDlg_ListPeptideSequences_This_peptide_sequence_contains_invalid_characters, 9, 0); // No mods explain all transitions VerifyTransitionListError(insertTransDlg, insertPart1 + insertPart2, null, null, Resources.PeptideGroupBuilder_AppendTransition_Failed_to_explain_all_transitions_for_0__m_z__1__with_a_single_set_of_modifications, 3, 0, 2); // Finally a working set of transitions SetClipboardText(insertPart1 + insertSep + insertPart2); insertTransDlg.PasteTransitions(); insertTransDlg.OkDialog(); }); var docInsert2 = WaitForDocumentChange(docInsert1); AssertEx.IsDocumentState(docInsert2, null, 4, 7, 21); // revision # is hard to predict with background loaders running Assert.AreEqual(7, GetVariableModCount(docInsert2)); Assert.AreEqual(11, GetLossCount(docInsert2, 1)); }
public static void IsDocumentResultsState(SrmDocument document, string replicateName, int peptides, int tranGroups, int tranGroupsHeavy, int transitions, int transitionsHeavy) { Assert.IsTrue(document.Settings.HasResults, "Expected document to have results."); int index; ChromatogramSet chromatogramSet; document.Settings.MeasuredResults.TryGetChromatogramSet(replicateName, out chromatogramSet, out index); Assert.AreNotEqual(-1, index, string.Format("Replicate {0} not found among -> {1} <-", replicateName, TextUtil.LineSeparate(document.Settings.MeasuredResults.Chromatograms.Select(c => c.Name)))); int peptidesActual = 0; foreach (var nodePep in document.Molecules.Where(nodePep => (nodePep.Results != null && !nodePep.Results[index].IsEmpty))) { peptidesActual += nodePep.Results[index].Sum(chromInfo => chromInfo.PeakCountRatio >= 0.5 ? 1 : 0); } int transitionsActual = 0; int transitionsHeavyActual = 0; int tranGroupsActual = 0; int tranGroupsHeavyActual = 0; foreach (var nodeGroup in document.MoleculeTransitionGroups.Where(nodeGroup => (nodeGroup.Results != null && !nodeGroup.Results[index].IsEmpty))) { foreach (var chromInfo in nodeGroup.Results[index]) { if (chromInfo.PeakCountRatio < 0.5) { continue; } if (nodeGroup.TransitionGroup.LabelType.IsLight) { tranGroupsActual++; } else { tranGroupsHeavyActual++; } } foreach (var nodeTran in nodeGroup.Children.Cast <TransitionDocNode>().Where( nodeTran => (nodeTran.Results != null && !nodeTran.Results[index].IsEmpty))) { foreach (var chromInfo in nodeTran.Results[index]) { if (!chromInfo.IsGoodPeak(document.Settings.TransitionSettings.Integration.IsIntegrateAll)) { continue; } if (nodeGroup.TransitionGroup.LabelType.IsLight) { transitionsActual++; } else { transitionsHeavyActual++; } } } } var failMessage = CompareValues(peptides, peptidesActual, "peptide"); failMessage += CompareValues(tranGroups, tranGroupsActual, "transition group"); failMessage += CompareValues(tranGroupsHeavy, tranGroupsHeavyActual, "heavy transition group"); failMessage += CompareValues(transitions, transitionsActual, "transition"); failMessage += CompareValues(transitionsHeavy, transitionsHeavyActual, "heavy transition"); if (failMessage.Length > 0) { Assert.Fail("IsDocumentResultsState failed for replicate " + replicateName + ": " + failMessage); } }
public RTGraphData(SrmDocument document, DocNode docNode, DisplayTypeChrom displayType, GraphValues.RetentionTimeTransform retentionTimeTransform, GraphValues.ReplicateGroupOp replicateGroupOp) : base(document, docNode, displayType, replicateGroupOp, PaneKey.DEFAULT) { RetentionTimeTransform = retentionTimeTransform; }
public override void UpdateGraph(bool checkData) { SrmDocument document = GraphSummary.DocumentUIContainer.DocumentUI; var results = document.Settings.MeasuredResults; bool resultsAvailable = results != null; Clear(); if (!resultsAvailable) { Title.Text = Resources.RTReplicateGraphPane_UpdateGraph_No_results_available; EmptyGraph(document); return; } var selectedTreeNode = GraphSummary.StateProvider.SelectedNode as SrmTreeNode; if (selectedTreeNode == null || document.FindNode(selectedTreeNode.Path) == null) { EmptyGraph(document); return; } Title.Text = null; DisplayTypeChrom displayType = GraphChromatogram.GetDisplayType(document, selectedTreeNode); DocNode selectedNode = selectedTreeNode.Model; DocNode parentNode = selectedNode; IdentityPath identityPath = selectedTreeNode.Path; // If the selected tree node is a transition, then its siblings are displayed. if (selectedTreeNode is TransitionTreeNode) { if (displayType != DisplayTypeChrom.single) { SrmTreeNode parentTreeNode = selectedTreeNode.SrmParent; parentNode = parentTreeNode.Model; identityPath = parentTreeNode.Path; } } // If the selected node is a peptide with one child, then show the children, // unless chromatogram display type is total else if (selectedTreeNode is PeptideTreeNode) { var children = ((DocNodeParent)selectedNode).Children; if (children.Count == 1 && displayType != DisplayTypeChrom.total) { selectedNode = parentNode = children[0]; identityPath = new IdentityPath(identityPath, parentNode.Id); } } else if (!(selectedTreeNode is TransitionGroupTreeNode)) { Title.Text = Resources.RTReplicateGraphPane_UpdateGraph_Select_a_peptide_to_see_the_retention_time_graph; CanShowRTLegend = false; return; } // If a precursor is going to be displayed with display type single if (parentNode is TransitionGroupDocNode && displayType == DisplayTypeChrom.single) { // If no optimization data, then show all the transitions if (!results.Chromatograms.Contains(chrom => chrom.OptimizationFunction != null)) { displayType = DisplayTypeChrom.all; } } var rtTransformOp = GraphSummary.StateProvider.GetRetentionTimeTransformOperation(); var rtValue = RTPeptideGraphPane.RTValue; GraphValues.ReplicateGroupOp replicateGroupOp; if (rtValue == RTPeptideValue.All) { replicateGroupOp = GraphValues.ReplicateGroupOp.FromCurrentSettings(document.Settings, GraphValues.AggregateOp.MEAN); } else { replicateGroupOp = GraphValues.ReplicateGroupOp.FromCurrentSettings(document.Settings); } var retentionTimeValue = new GraphValues.RetentionTimeTransform(rtValue, rtTransformOp, replicateGroupOp.AggregateOp); YAxis.Title.Text = retentionTimeValue.GetAxisTitle(); GraphData graphData = new RTGraphData(document, parentNode, displayType, retentionTimeValue, replicateGroupOp); CanShowRTLegend = graphData.DocNodes.Count != 0; InitFromData(graphData); int selectedReplicateIndex = SelectedIndex; double minRetentionTime = double.MaxValue; double maxRetentionTime = -double.MaxValue; int iColor = 0, iCharge = -1; int? charge = null; int countLabelTypes = document.Settings.PeptideSettings.Modifications.CountLabelTypes; int colorOffset = 0; var transitionGroupDocNode = parentNode as TransitionGroupDocNode; if (transitionGroupDocNode != null && displayType == DisplayTypeChrom.products) { // If we are only displaying product ions, we want to use an offset in the colors array // so that we do not re-use colors that would be used for any precursor ions. colorOffset = GraphChromatogram.GetDisplayTransitions(transitionGroupDocNode, DisplayTypeChrom.precursors).Count(); } for (int i = 0; i < graphData.DocNodes.Count; i++) { var docNode = graphData.DocNodes[i]; var pointPairLists = graphData.PointPairLists[i]; int numSteps = pointPairLists.Count / 2; for (int iStep = 0; iStep < pointPairLists.Count; iStep++) { int step = iStep - numSteps; var pointPairList = pointPairLists[iStep]; Color color; var nodeGroup = docNode as TransitionGroupDocNode; if (parentNode is PeptideDocNode) { // Resharper code inspection v9.0 on TC gets this one wrong // ReSharper disable ExpressionIsAlwaysNull int iColorGroup = GetColorIndex(nodeGroup, countLabelTypes, ref charge, ref iCharge); // ReSharper restore ExpressionIsAlwaysNull color = COLORS_GROUPS[iColorGroup % COLORS_GROUPS.Length]; } else if (displayType == DisplayTypeChrom.total) { color = COLORS_GROUPS[iColor % COLORS_GROUPS.Length]; } else if (docNode.Equals(selectedNode) && step == 0) { color = ChromGraphItem.ColorSelected; } else { color = COLORS_TRANSITION[(iColor + colorOffset) % COLORS_TRANSITION.Length]; } iColor++; string label = graphData.DocNodeLabels[i]; if (step != 0) { label = string.Format(Resources.RTReplicateGraphPane_UpdateGraph_Step__0__, step); } BarItem curveItem; if (HiLowMiddleErrorBarItem.IsHiLoMiddleErrorList(pointPairList)) { curveItem = new HiLowMiddleErrorBarItem(label, pointPairList, color, Color.Black); } else { curveItem = new MeanErrorBarItem(label, pointPairList, color, Color.Black); } if (selectedReplicateIndex != -1 && selectedReplicateIndex < pointPairList.Count) { PointPair pointPair = pointPairList[selectedReplicateIndex]; if (!pointPair.IsInvalid) { minRetentionTime = Math.Min(minRetentionTime, pointPair.Z); maxRetentionTime = Math.Max(maxRetentionTime, pointPair.Y); } } curveItem.Bar.Border.IsVisible = false; curveItem.Bar.Fill.Brush = new SolidBrush(color); curveItem.Tag = new IdentityPath(identityPath, docNode.Id); CurveList.Add(curveItem); } } // Draw a box around the currently selected replicate if (ShowSelection && minRetentionTime != double.MaxValue) { GraphObjList.Add(new BoxObj(selectedReplicateIndex + .5, maxRetentionTime, 1, maxRetentionTime - minRetentionTime, Color.Black, Color.Empty) { IsClippedToChartRect = true, }); } // Reset the scale when the parent node changes if (_parentNode == null || !ReferenceEquals(_parentNode.Id, parentNode.Id)) { XAxis.Scale.MaxAuto = XAxis.Scale.MinAuto = true; YAxis.Scale.MaxAuto = YAxis.Scale.MinAuto = true; } _parentNode = parentNode; Legend.IsVisible = Settings.Default.ShowRetentionTimesLegend; AxisChange(); }
private string GetCommand(SrmDocument doc, IToolMacroProvider toolMacroProvider, IProgressMonitor progressMonitor) { return(ToolMacros.ReplaceMacrosCommand(doc, toolMacroProvider, this, progressMonitor)); }
public static long CacheSize(SrmDocument docInitial, long format3Size, int groupCount, int tranCount, int peakCount) { long cacheSize = format3Size; int fileCachedCount = docInitial.Settings.MeasuredResults.MSDataFileInfos.Count(); if (ChromatogramCache.FORMAT_VERSION_CACHE > ChromatogramCache.FORMAT_VERSION_CACHE_3) { // Cache version 4 stores instrument information, and is bigger in size. cacheSize += sizeof(int) * fileCachedCount; } if (ChromatogramCache.FORMAT_VERSION_CACHE > ChromatogramCache.FORMAT_VERSION_CACHE_4) { // Cache version 5 adds an int for flags for each file // Allow for a difference in sizes due to the extra information. int fileFlagsSize = sizeof(int) * fileCachedCount; // And SeqIndex, SeqCount, StartScoreIndex and padding var deltaSize5 = ChromGroupHeaderInfo.GetStructSize(CacheFormatVersion.Five) - ChromGroupHeaderInfo.GetStructSize(CacheFormatVersion.Four); int groupHeadersSize = deltaSize5 * groupCount; // And flags for each transition int transitionFlagsSize = ChromTransition5.DeltaSize5 * tranCount; // And num seq byte count, seq location, score types, num scores and score location const int headerScoreSize = sizeof(int) + sizeof(long) + sizeof(int) + sizeof(int) + sizeof(long); cacheSize += groupHeadersSize + fileFlagsSize + transitionFlagsSize + headerScoreSize; } if (ChromatogramCache.FORMAT_VERSION_CACHE > ChromatogramCache.FORMAT_VERSION_CACHE_5) { // Cache version 6 adds status graph dimensions for every file cacheSize += sizeof(float) * 2 * fileCachedCount; } if (ChromatogramCache.FORMAT_VERSION_CACHE > ChromatogramCache.FORMAT_VERSION_CACHE_6) { // Cache version 7 adds ion mobility information cacheSize += sizeof(float) * 2 * tranCount; } if (ChromatogramCache.FORMAT_VERSION_CACHE > ChromatogramCache.FORMAT_VERSION_CACHE_8) { // Cache version 9 adds scan id values for every file cacheSize += (sizeof(int) + sizeof(long)) * fileCachedCount; // And scan ids location to global header cacheSize += sizeof(long); } if (ChromatogramCache.FORMAT_VERSION_CACHE >= ChromatogramCache.FORMAT_VERSION_CACHE_11) { // Version 11 adds uncompressed buffer size for convenience, and some time span metadata cacheSize += ChromGroupHeaderInfo.DeltaSize11 * groupCount; } if (ChromatogramCache.FORMAT_VERSION_CACHE >= CacheFormatVersion.Twelve) { cacheSize += peakCount * (ChromPeak.GetStructSize(CacheFormatVersion.Twelve) - ChromPeak.GetStructSize(CacheFormatVersion.Eleven)); cacheSize += tranCount * (ChromTransition.GetStructSize(CacheFormatVersion.Twelve) - ChromTransition.GetStructSize(CacheFormatVersion.Eleven)); } cacheSize += fileCachedCount * (CachedFileHeaderStruct.GetStructSize(ChromatogramCache.FORMAT_VERSION_CACHE) - CachedFileHeaderStruct.GetStructSize(CacheFormatVersion.Nine)); cacheSize += CacheHeaderStruct.GetStructSize(ChromatogramCache.FORMAT_VERSION_CACHE) - CacheHeaderStruct.GetStructSize(ChromatogramCache.FORMAT_VERSION_CACHE_11); return(cacheSize); }
private static int GetVariableModCount(SrmDocument document) { return(document.Peptides.Count(nodePep => nodePep.ExplicitMods != null && nodePep.ExplicitMods.IsVariableStaticMods)); }
private static int GetLossCount(SrmDocument document, int minLosses) { return(document.PeptideTransitions.Count(nodeTran => nodeTran.HasLoss && nodeTran.Losses.Losses.Count >= minLosses)); }
/// <summary> /// Returns a string representation of the report based on the document. /// </summary> public string ReportToCsvString(SrmDocument doc, IProgressMonitor progressMonitor) { return(ReportToCsvString(doc, TextUtil.CsvSeparator, progressMonitor)); }
/// <summary> /// Return a string that is the Arguments string with the macros replaced. /// </summary> /// <param name="doc"> Document for report data. </param> /// <param name="toolMacroProvider"> Interface to use to get the current macro values </param> /// <param name="progressMonitor">Progress monitor. </param> /// <returns> Arguments with macros replaced or null if one of the macros was missing /// (eg. no selected peptide for $(SelPeptide) then the return value is null </returns> public string GetArguments(SrmDocument doc, IToolMacroProvider toolMacroProvider, IProgressMonitor progressMonitor) { return(ToolMacros.ReplaceMacrosArguments(doc, toolMacroProvider, this, progressMonitor)); }