Exemplo n.º 1
0
        public QuantificationResult GetQuantification()
        {
            var quantifier = PeptideQuantifier.GetPeptideQuantifier(SrmDocument.Settings, Peptide.Protein.DocNode, Peptide.DocNode);
            CalibrationCurveFitter curveFitter = new CalibrationCurveFitter(quantifier, SrmDocument.Settings);

            return(curveFitter.GetQuantificationResult(ResultFile.Replicate.ReplicateIndex));
        }
Exemplo n.º 2
0
        private string GetFormTitle(CalibrationCurveFitter curveFitter)
        {
            string title = TextUtil.SpaceSeparate(_originalFormTitle + ':', curveFitter.PeptideQuantifier.PeptideDocNode.ModifiedSequenceDisplay);

            if (curveFitter.SingleBatchReplicateIndex.HasValue)
            {
                var chromatogramSet = _skylineWindow.Document.Settings.MeasuredResults.Chromatograms[
                    curveFitter.SingleBatchReplicateIndex.Value];
                if (string.IsNullOrEmpty(chromatogramSet.BatchName))
                {
                    title = TextUtil.SpaceSeparate(title, string.Format(QuantificationStrings.CalibrationForm_GetFormTitle__Replicate___0__, chromatogramSet.Name));
                }
                else
                {
                    title = TextUtil.SpaceSeparate(title, string.Format(QuantificationStrings.CalibrationForm_GetFormTitle__Batch___0__, chromatogramSet.BatchName));
                }
            }
            else
            {
                if (_skylineWindow.Document.Settings.HasResults && _skylineWindow.Document.Settings.MeasuredResults
                    .Chromatograms.Select(c => c.BatchName).Distinct().Count() > 1)
                {
                    title = TextUtil.SpaceSeparate(title, QuantificationStrings.CalibrationForm_GetFormTitle__All_Replicates_);
                }
            }
            return(title);
        }
Exemplo n.º 3
0
        private void zedGraphControl_ContextMenuBuilder(ZedGraphControl sender, ContextMenuStrip menuStrip, Point mousePt, ZedGraphControl.ContextMenuObjectState objState)
        {
            var calibrationCurveOptions = Settings.Default.CalibrationCurveOptions;

            singleBatchContextMenuItem.Checked = calibrationCurveOptions.SingleBatch;
            if (IsEnableIsotopologResponseCurve())
            {
                singleBatchContextMenuItem.Visible     = true;
                showSampleTypesContextMenuItem.Visible = false;
            }
            else
            {
                singleBatchContextMenuItem.Visible     = CalibrationCurveFitter.AnyBatchNames(_skylineWindow.Document.Settings);
                showSampleTypesContextMenuItem.Visible = true;
            }
            var replicateIndexFromPoint = ReplicateIndexFromPoint(mousePt);

            if (replicateIndexFromPoint.HasValue && null == replicateIndexFromPoint.Value.LabelType)
            {
                ToolStripMenuItem excludeStandardMenuItem
                    = MakeExcludeStandardMenuItem(replicateIndexFromPoint.Value.ReplicateIndex);
                if (excludeStandardMenuItem != null)
                {
                    menuStrip.Items.Clear();
                    menuStrip.Items.Add(excludeStandardMenuItem);
                    return;
                }
            }

            showSampleTypesContextMenuItem.DropDownItems.Clear();
            foreach (var sampleType in SampleType.ListSampleTypes())
            {
                showSampleTypesContextMenuItem.DropDownItems.Add(MakeShowSampleTypeMenuItem(sampleType));
            }
            logXContextMenuItem.Checked               = Options.LogXAxis;
            logYAxisContextMenuItem.Checked           = Options.LogYAxis;
            showLegendContextMenuItem.Checked         = Options.ShowLegend;
            showSelectionContextMenuItem.Checked      = Options.ShowSelection;
            showFiguresOfMeritContextMenuItem.Checked = Options.ShowFiguresOfMerit;
            ZedGraphHelper.BuildContextMenu(sender, menuStrip, true);
            if (!menuStrip.Items.Contains(logXContextMenuItem))
            {
                int index = 0;
                menuStrip.Items.Insert(index++, logXContextMenuItem);
                menuStrip.Items.Insert(index++, logYAxisContextMenuItem);
                menuStrip.Items.Insert(index++, showSampleTypesContextMenuItem);
                menuStrip.Items.Insert(index++, singleBatchContextMenuItem);
                menuStrip.Items.Insert(index++, showLegendContextMenuItem);
                menuStrip.Items.Insert(index++, showSelectionContextMenuItem);
                menuStrip.Items.Insert(index++, showFiguresOfMeritContextMenuItem);
                menuStrip.Items.Insert(index++, new ToolStripSeparator());
            }
        }
Exemplo n.º 4
0
        private CalibrationCurveFitter GetCalibrationCurveFitter()
        {
            if (string.IsNullOrEmpty(ResultFile.Replicate.BatchName) && !Peptide.DocNode.HasPrecursorConcentrations)
            {
                return(Peptide.GetCalibrationCurveFitter());
            }

            var calibrationCurveFitter =
                new CalibrationCurveFitter(Peptide.GetPeptideQuantifier(), SrmDocument.Settings);

            calibrationCurveFitter.SingleBatchReplicateIndex = ResultFile.Replicate.ReplicateIndex;
            return(calibrationCurveFitter);
        }
Exemplo n.º 5
0
        public void TestSinglePointExternalCalibrationWithIsConcentration()
        {
            const double internalStandardConcentration = 80.0;
            var          srmDocument = LoadTestDocument();

            srmDocument = ChangeStandardConcentrationCount(srmDocument, 1);
            srmDocument = ChangeQuantificationSettings(srmDocument, QuantificationSettings.DEFAULT
                                                       .ChangeRegressionFit(RegressionFit.LINEAR_THROUGH_ZERO)
                                                       .ChangeNormalizationMethod(NormalizationMethod.GetNormalizationMethod(IsotopeLabelType.heavy)));
            PeptideGroupDocNode protein = srmDocument.MoleculeGroups.First();
            PeptideDocNode      peptide = protein.Peptides.First();

            peptide = peptide.ChangeInternalStandardConcentration(internalStandardConcentration);
            PeptideQuantifier      peptideQuantifier = PeptideQuantifier.GetPeptideQuantifier(srmDocument.Settings, protein, peptide);
            CalibrationCurveFitter curveFitter       = new CalibrationCurveFitter(peptideQuantifier, srmDocument.Settings);

            Assert.AreEqual(CalibrationCurveFitter.ConcentrationRatioText(IsotopeLabelType.light, IsotopeLabelType.heavy),
                            curveFitter.GetXAxisTitle());
            Assert.AreEqual(CalibrationCurveFitter.PeakAreaRatioText(IsotopeLabelType.light, IsotopeLabelType.heavy), curveFitter.GetYAxisTitle());
            var chromatograms = srmDocument.Settings.MeasuredResults.Chromatograms;

            for (int iReplicate = 0; iReplicate < chromatograms.Count; iReplicate++)
            {
                string msg       = string.Format("Replicate {0}", iReplicate);
                var    expectedY = peptide.Results[iReplicate].First().LabelRatios.First().Ratio.Ratio;
                double?actualY   = curveFitter.GetYValue(iReplicate).Value;
                Assert.IsNotNull(actualY);
                Assert.AreEqual(expectedY, actualY.Value, epsilon, msg);
                var calibrationCurve = curveFitter.GetCalibrationCurve();
                Assert.AreEqual(1, calibrationCurve.PointCount);
                var expectedConcentration = expectedY * internalStandardConcentration / calibrationCurve.Slope.Value;
                Assert.AreEqual(expectedConcentration / internalStandardConcentration,
                                curveFitter.GetCalculatedXValue(calibrationCurve, iReplicate).GetValueOrDefault(double.NaN), epsilon, msg);
                Assert.AreEqual(expectedConcentration,
                                curveFitter.GetCalculatedConcentration(calibrationCurve, iReplicate).GetValueOrDefault(double.NaN), epsilon, msg);
                var chromatogramSet = chromatograms[iReplicate];
                if (Equals(chromatogramSet.SampleType, SampleType.STANDARD) && chromatogramSet.AnalyteConcentration.HasValue)
                {
                    // Since there was only one standard, the regression line goes exactly through this sample.
                    Assert.AreEqual(expectedConcentration, chromatogramSet.AnalyteConcentration.Value * peptide.ConcentrationMultiplier.GetValueOrDefault(1.0), epsilon);
                }
            }
        }
Exemplo n.º 6
0
        public void TestDilutionFactor()
        {
            var baseDocument = LoadTestDocument();

            baseDocument = ChangeQuantificationSettings(baseDocument,
                                                        QuantificationSettings.DEFAULT
                                                        .ChangeNormalizationMethod(NormalizationMethod.GetNormalizationMethod(IsotopeLabelType.heavy))
                                                        .ChangeRegressionFit(RegressionFit.LINEAR)
                                                        .ChangeUnits("ng/mL"));
            var baseCurveFitter = CalibrationCurveFitter.GetCalibrationCurveFitter(baseDocument.Settings,
                                                                                   baseDocument.MoleculeGroups.First(), baseDocument.Molecules.First());
            var baseCurve = baseCurveFitter.GetCalibrationCurve();
            // Set the dilution factor of each external standard to 2.0, and each unknown to 3.0
            var docWithDilutionFactor = baseDocument.ChangeMeasuredResults(
                baseDocument.MeasuredResults.ChangeChromatograms(baseDocument.MeasuredResults.Chromatograms.Select(
                                                                     chrom => Equals(chrom.SampleType, SampleType.STANDARD) ? chrom.ChangeDilutionFactor(2.0) :
                                                                     chrom.ChangeDilutionFactor(3.0)).ToArray()));
            var dilutionFactorCurveFitter = CalibrationCurveFitter.GetCalibrationCurveFitter(
                docWithDilutionFactor.Settings, docWithDilutionFactor.MoleculeGroups.First(),
                docWithDilutionFactor.Molecules.First());
            var dilutionFactorCurve = dilutionFactorCurveFitter.GetCalibrationCurve();

            Assert.AreEqual(2.0 * baseCurve.Slope, dilutionFactorCurve.Slope);
            Assert.AreEqual(baseCurve.Intercept, dilutionFactorCurve.Intercept);
            for (int replicateIndex = 0; replicateIndex < baseDocument.MeasuredResults.Chromatograms.Count; replicateIndex++)
            {
                var sampleType        = baseDocument.MeasuredResults.Chromatograms[replicateIndex].SampleType;
                var baseConcentration = baseCurveFitter.GetCalculatedConcentration(baseCurve, replicateIndex);
                Assert.IsNotNull(baseConcentration);
                var dilutionFactorConcentration =
                    dilutionFactorCurveFitter.GetCalculatedConcentration(dilutionFactorCurve, replicateIndex);
                Assert.IsNotNull(dilutionFactorConcentration);
                if (Equals(sampleType, SampleType.STANDARD))
                {
                    Assert.AreEqual(baseConcentration.Value, dilutionFactorConcentration.Value, epsilon);
                }
                else
                {
                    Assert.AreEqual(1.5 * baseConcentration.Value, dilutionFactorConcentration.Value, epsilon);
                }
            }
            AssertEx.ValidatesAgainstSchema(docWithDilutionFactor);
        }
Exemplo n.º 7
0
        public void TestMultipointExternalCalibrationWithoutNormalization()
        {
            var srmDocument = LoadTestDocument();

            srmDocument = ChangeQuantificationSettings(srmDocument,
                                                       QuantificationSettings.DEFAULT
                                                       .ChangeNormalizationMethod(NormalizationMethod.NONE)
                                                       .ChangeRegressionFit(RegressionFit.LINEAR)
                                                       .ChangeUnits("ng/mL"));
            PeptideGroupDocNode protein = srmDocument.MoleculeGroups.First();
            PeptideDocNode      peptide = srmDocument.Peptides.First();

            peptide = peptide.ChangeInternalStandardConcentration(null);
            CalibrationCurveFitter curveFitter = CalibrationCurveFitter.GetCalibrationCurveFitter(srmDocument.Settings, protein, peptide);
            string expectedXAxis = CalibrationCurveFitter.AppendUnits(QuantificationStrings.Analyte_Concentration, "ng/mL");

            Assert.AreEqual(expectedXAxis, curveFitter.GetXAxisTitle());
            string expectedYAxis = QuantificationStrings.CalibrationCurveFitter_GetYAxisTitle_Peak_Area;

            Assert.AreEqual(expectedYAxis, curveFitter.GetYAxisTitle());
            var chromatograms  = srmDocument.Settings.MeasuredResults.Chromatograms;
            var lightPrecursor = peptide.TransitionGroups
                                 .First(tg => IsotopeLabelType.light.Equals(tg.TransitionGroup.LabelType));

            for (int iReplicate = 0; iReplicate < chromatograms.Count; iReplicate++)
            {
                string msg       = string.Format("Replicate {0}", iReplicate);
                var    expectedY = lightPrecursor.Results[iReplicate].First().Area.Value;
                Assert.AreEqual(expectedY, curveFitter.GetYValue(iReplicate).Value, .01, msg);
                var calibrationCurve = curveFitter.GetCalibrationCurve();
                Assert.IsNotNull(calibrationCurve.Slope);
                Assert.IsNotNull(calibrationCurve.RSquared);
                double expectedConcentration = calibrationCurve.GetX(expectedY).Value;
                Assert.AreEqual(expectedConcentration,
                                curveFitter.GetCalculatedXValue(calibrationCurve, iReplicate).GetValueOrDefault(double.NaN), epsilon, msg);
                Assert.AreEqual(expectedConcentration,
                                curveFitter.GetCalculatedConcentration(calibrationCurve, iReplicate).GetValueOrDefault(double.NaN), epsilon, msg);
            }
        }
Exemplo n.º 8
0
        public void TestInternalCalibration()
        {
            const double internalStandardConcentration = 80.0;
            var          srmDocument = LoadTestDocument();

            AssertEx.IsDocumentState(srmDocument, null, 1, 1, 2, 10);
            srmDocument = ChangeStandardConcentrationCount(srmDocument, 0);
            srmDocument = ChangeQuantificationSettings(srmDocument,
                                                       QuantificationSettings.DEFAULT
                                                       .ChangeRegressionFit(RegressionFit.NONE)
                                                       .ChangeNormalizationMethod(NormalizationMethod.GetNormalizationMethod(IsotopeLabelType.heavy))
                                                       .ChangeUnits("ng/mL"));
            PeptideGroupDocNode protein = srmDocument.MoleculeGroups.First();
            PeptideDocNode      peptide = protein.Peptides.First();

            peptide = peptide.ChangeInternalStandardConcentration(internalStandardConcentration);
            CalibrationCurveFitter curveFitter = CalibrationCurveFitter.GetCalibrationCurveFitter(srmDocument.Settings, protein, peptide);
            string expectedXAxis = CalibrationCurveFitter.AppendUnits(QuantificationStrings.Analyte_Concentration, "ng/mL");

            Assert.AreEqual(expectedXAxis, curveFitter.GetXAxisTitle());
            string expectedYAxis = CalibrationCurveFitter.PeakAreaRatioText(IsotopeLabelType.light, IsotopeLabelType.heavy);

            Assert.AreEqual(expectedYAxis, curveFitter.GetYAxisTitle());
            var chromatograms = srmDocument.Settings.MeasuredResults.Chromatograms;

            for (int iReplicate = 0; iReplicate < chromatograms.Count; iReplicate++)
            {
                string msg       = string.Format("Replicate {0}", iReplicate);
                var    expectedY = peptide.Results[iReplicate].First().LabelRatios.First().Ratio.Ratio;
                Assert.AreEqual(expectedY, curveFitter.GetYValue(iReplicate).Value, epsilon, msg);
                var calibrationCurve = curveFitter.GetCalibrationCurve();
                Assert.AreEqual(1 / internalStandardConcentration, calibrationCurve.Slope);
                Assert.IsNull(calibrationCurve.RSquared);
                Assert.AreEqual(expectedY * internalStandardConcentration,
                                curveFitter.GetCalculatedXValue(calibrationCurve, iReplicate).GetValueOrDefault(double.NaN), epsilon, msg);
                Assert.AreEqual(expectedY * internalStandardConcentration,
                                curveFitter.GetCalculatedConcentration(calibrationCurve, iReplicate).GetValueOrDefault(double.NaN), epsilon, msg);
            }
        }
Exemplo n.º 9
0
        protected override void DoTest()
        {
            var folderAbsoluteQuant = UseRawFiles ? "AbsoluteQuant" : "AbsoluteQuantMzml";
            // Generating a Transition List, p. 4
            {
                var doc = SkylineWindow.Document;
                var transitionSettingsUI = ShowDialog <TransitionSettingsUI>(SkylineWindow.ShowTransitionSettingsUI);
                RunUI(() =>
                {
                    // Predicition Settings
                    transitionSettingsUI.SelectedTab       = TransitionSettingsUI.TABS.Prediction;
                    transitionSettingsUI.PrecursorMassType = MassType.Monoisotopic;
                    transitionSettingsUI.FragmentMassType  = MassType.Monoisotopic;
                    transitionSettingsUI.RegressionCEName  = "Thermo TSQ Vantage";
                    transitionSettingsUI.RegressionDPName  = Resources.SettingsList_ELEMENT_NONE_None;
                });
                PauseForScreenShot <TransitionSettingsUI.PredictionTab>("Transition Settings - Prediction tab", 4);

                RunUI(() =>
                {
                    // Filter Settings
                    transitionSettingsUI.SelectedTab      = TransitionSettingsUI.TABS.Filter;
                    transitionSettingsUI.PrecursorCharges = "2";
                    transitionSettingsUI.ProductCharges   = "1";
                    transitionSettingsUI.FragmentTypes    = "y";
                    transitionSettingsUI.RangeFrom        = Resources.TransitionFilter_FragmentStartFinders_ion_3;
                    transitionSettingsUI.RangeTo          = Resources.TransitionFilter_FragmentEndFinders_last_ion_minus_1;
                    transitionSettingsUI.SpecialIons      = new string[0];
                });
                PauseForScreenShot <TransitionSettingsUI.FilterTab>("Transition Settings - Filter tab", 4);

                OkDialog(transitionSettingsUI, transitionSettingsUI.OkDialog);
                WaitForDocumentChange(doc);
            }

            // Configuring Peptide settings p. 4
            PeptideSettingsUI peptideSettingsUI = ShowDialog <PeptideSettingsUI>(SkylineWindow.ShowPeptideSettingsUI);

            RunUI(() => peptideSettingsUI.SelectedTab = PeptideSettingsUI.TABS.Modifications);
            PauseForScreenShot <PeptideSettingsUI.ModificationsTab>("Peptide Settings - Modification tab", 5);

            var modHeavyK = new StaticMod("Label:13C(6)15N(2) (C-term K)", "K", ModTerminus.C, false, null, LabelAtoms.C13 | LabelAtoms.N15,
                                          RelativeRT.Matching, null, null, null);

            AddHeavyMod(modHeavyK, peptideSettingsUI, "Edit Isotope Modification over Transition Settings", 5);
            RunUI(() => peptideSettingsUI.PickedHeavyMods = new[] { modHeavyK.Name });
            PauseForScreenShot <PeptideSettingsUI.ModificationsTab>("Peptide Settings - Modification tab with mod added", 5);

            OkDialog(peptideSettingsUI, peptideSettingsUI.OkDialog);

            // Inserting a peptide sequence p. 5
            using (new CheckDocumentState(1, 1, 2, 10))
            {
                RunUI(() => SetClipboardText("IEAIPQIDK\tGST-tag"));
                var pasteDlg = ShowDialog <PasteDlg>(SkylineWindow.ShowPastePeptidesDlg);
                RunUI(pasteDlg.PastePeptides);
                WaitForProteinMetadataBackgroundLoaderCompletedUI();
                PauseForScreenShot <PasteDlg.PeptideListTab>("Insert Peptide List", 6);

                OkDialog(pasteDlg, pasteDlg.OkDialog);
            }

            RunUI(SkylineWindow.ExpandPrecursors);
            RunUI(() => SkylineWindow.SaveDocument(TestFilesDir.GetTestPath(folderAbsoluteQuant + @"test_file.sky")));
            WaitForCondition(() => File.Exists(TestFilesDir.GetTestPath(folderAbsoluteQuant + @"test_file.sky")));
            PauseForScreenShot("Main window with Targets view", 6);

            // Exporting a transition list p. 6
            {
                var exportMethodDlg = ShowDialog <ExportMethodDlg>(() => SkylineWindow.ShowExportMethodDialog(ExportFileType.List));
                RunUI(() =>
                {
                    exportMethodDlg.InstrumentType = ExportInstrumentType.THERMO;
                    exportMethodDlg.ExportStrategy = ExportStrategy.Single;
                    exportMethodDlg.OptimizeType   = ExportOptimize.NONE;
                    exportMethodDlg.MethodType     = ExportMethodType.Standard;
                });
                PauseForScreenShot <ExportMethodDlg.TransitionListView>("Export Transition List", 7);

                OkDialog(exportMethodDlg, () =>
                         exportMethodDlg.OkDialog(TestFilesDir.GetTestPath("Quant_Abs_Thermo_TSQ_Vantage.csv")));
            }

            // Importing RAW files into Skyline p. 7
            var importResultsDlg = ShowDialog <ImportResultsDlg>(SkylineWindow.ImportResults);

            PauseForScreenShot <ImportResultsDlg>("Import Results - click OK to get shot of Import Results Files and then cancel", 8);

            RunUI(() =>
            {
                var rawFiles      = DataSourceUtil.GetDataSources(TestFilesDirs[0].FullPath).First().Value.Skip(1);
                var namedPathSets = from rawFile in rawFiles
                                    select new KeyValuePair <string, MsDataFileUri[]>(
                    rawFile.GetFileNameWithoutExtension(), new[] { rawFile });
                importResultsDlg.NamedPathSets = namedPathSets.ToArray();
            });
            RunDlg <ImportResultsNameDlg>(importResultsDlg.OkDialog,
                                          importResultsNameDlg => importResultsNameDlg.NoDialog());

            WaitForGraphs();

            RunUI(() =>
            {
                SkylineWindow.SelectedPath             = SkylineWindow.Document.GetPathTo((int)SrmDocument.Level.Molecules, 0);
                Settings.Default.ArrangeGraphsOrder    = GroupGraphsOrder.Document.ToString();
                Settings.Default.ArrangeGraphsReversed = false;
                SkylineWindow.ArrangeGraphsTiled();
                SkylineWindow.AutoZoomBestPeak();
            });
            WaitForCondition(() => Equals(8, SkylineWindow.GraphChromatograms.Count(graphChrom => !graphChrom.IsHidden)),
                             "unexpected visible graphChromatogram count");

            WaitForCondition(10 * 60 * 1000,    // ten minutes
                             () => SkylineWindow.Document.Settings.HasResults && SkylineWindow.Document.Settings.MeasuredResults.IsLoaded);
            PauseForScreenShot("Main window with imported data", 9);

            // Analyzing SRM Data from FOXN1-GST Sample p. 9
            RunDlg <ImportResultsDlg>(SkylineWindow.ImportResults,
                                      importResultsDlg1 =>
            {
                var rawFiles      = DataSourceUtil.GetDataSources(TestFilesDirs[0].FullPath).First().Value.Take(1);
                var namedPathSets = from rawFile in rawFiles
                                    select new KeyValuePair <string, MsDataFileUri[]>(
                    rawFile.GetFileNameWithoutExtension(), new[] { rawFile });
                importResultsDlg1.NamedPathSets = namedPathSets.ToArray();
                importResultsDlg1.OkDialog();
            });
            WaitForGraphs();
            CheckReportCompatibility.CheckAll(SkylineWindow.Document);
            WaitForCondition(5 * 60 * 1000, // five minutes
                             () =>
                             SkylineWindow.Document.Settings.HasResults &&
                             SkylineWindow.Document.Settings.MeasuredResults.IsLoaded);

            RunUI(() =>
            {
                SkylineWindow.ToggleIntegrateAll();
                SkylineWindow.ArrangeGraphsTabbed();
                SkylineWindow.ShowRTReplicateGraph();
                SkylineWindow.ShowPeakAreaReplicateComparison();
                // Total normalization
                SkylineWindow.NormalizeAreaGraphTo(AreaNormalizeToView.area_percent_view);
            });

            RunUI(() => SkylineWindow.ActivateReplicate("FOXN1-GST"));
            WaitForGraphs();
            RunUI(() => SkylineWindow.SelectedPath = SkylineWindow.DocumentUI.GetPathTo((int)SrmDocument.Level.TransitionGroups, 0));
            WaitForGraphs();
            RunUI(() =>
            {
                Assert.AreEqual(SkylineWindow.SelectedResultsIndex, SkylineWindow.GraphPeakArea.ResultsIndex);
                Assert.AreEqual(SkylineWindow.SelectedResultsIndex, SkylineWindow.GraphRetentionTime.ResultsIndex);
            });

            RunUI(() =>
            {
                int transitionCount = SkylineWindow.DocumentUI.PeptideTransitionGroups.First().TransitionCount;
                CheckGstGraphs(transitionCount, transitionCount);
            });
            PauseForScreenShot("Main window with Peak Areas, Retention Times and FOXN1-GST for light", 10);

            RunUI(() => SkylineWindow.SelectedPath = SkylineWindow.DocumentUI.GetPathTo((int)SrmDocument.Level.TransitionGroups, 1));
            WaitForGraphs();

            RunUI(() =>
            {
                int transitionCount = SkylineWindow.DocumentUI.PeptideTransitionGroups.ToArray()[1].TransitionCount;
                CheckGstGraphs(transitionCount, transitionCount);
            });
            PauseForScreenShot("Main window with Peak Areas, Retention Times and FOXN1-GST for heavy", 10);

            RunUI(() => SkylineWindow.SelectedPath = SkylineWindow.DocumentUI.GetPathTo((int)SrmDocument.Level.Molecules, 0));
            WaitForGraphs();
            // Heavy normalization
            RunUI(() => SkylineWindow.NormalizeAreaGraphTo(AreaNormalizeToView.area_ratio_view));
            WaitForGraphs();
            RunUI(() =>
            {
                int transitionGroupCount = SkylineWindow.DocumentUI.Peptides.First().TransitionGroupCount;
                CheckGstGraphs(transitionGroupCount, transitionGroupCount - 1);
            });
            PauseForScreenShot("Main window with totals graphs for light and heavy and FOXN1-GST", 11);

            // Peptide Quantitification Settings p. 11
            var          peptideSettingsUi = ShowDialog <PeptideSettingsUI>(SkylineWindow.ShowPeptideSettingsUI);
            const string quantUnits        = "fmol/ul";

            RunUI(() =>
            {
                peptideSettingsUi.SelectedTab              = PeptideSettingsUI.TABS.Quantification;
                peptideSettingsUi.QuantRegressionFit       = RegressionFit.LINEAR;
                peptideSettingsUi.QuantNormalizationMethod = new NormalizationMethod.RatioToLabel(IsotopeLabelType.heavy);
                peptideSettingsUi.QuantUnits = quantUnits;
            });
            PauseForScreenShot("Peptide Settings Quantification Tab", 12);
            OkDialog(peptideSettingsUi, peptideSettingsUi.OkDialog);

            // Specify analyte concentrations of external standards
            RunUI(() => SkylineWindow.ShowDocumentGrid(true));
            var documentGridForm = FindOpenForm <DocumentGridForm>();

            RunUI(() =>
            {
                documentGridForm.ChooseView(Resources.SkylineViewContext_GetDocumentGridRowSources_Replicates);
            });
            WaitForConditionUI(() => documentGridForm.IsComplete);
            var concentrations = new[] { 40, 12.5, 5, 2.5, 1, .5, .25, .1 };

            for (int iRow = 0; iRow < concentrations.Length; iRow++)
            {
                // ReSharper disable AccessToModifiedClosure
                RunUI(() =>
                {
                    var colSampleType = documentGridForm.FindColumn(PropertyPath.Root.Property("SampleType"));
                    documentGridForm.DataGridView.Rows[iRow].Cells[colSampleType.Index].Value = SampleType.STANDARD;
                });
                WaitForConditionUI(() => documentGridForm.IsComplete);
                RunUI(() =>
                {
                    var colAnalyteConcentration =
                        documentGridForm.FindColumn(PropertyPath.Root.Property("AnalyteConcentration"));
                    var cell = documentGridForm.DataGridView.Rows[iRow].Cells[colAnalyteConcentration.Index];
                    documentGridForm.DataGridView.CurrentCell = cell;
                    cell.Value = concentrations[iRow];
                });
                // ReSharper restore AccessToModifiedClosure
                WaitForConditionUI(() => documentGridForm.IsComplete);
            }
            PauseForScreenShot("Document grid with concentrations filled in", 13);

            // View the calibration curve p. 13
            RunUI(() => SkylineWindow.ShowCalibrationForm());
            var calibrationForm = FindOpenForm <CalibrationForm>();

            PauseForScreenShot("View calibration curve", 14);

            Assert.AreEqual(CalibrationCurveFitter.AppendUnits(QuantificationStrings.Analyte_Concentration, quantUnits), calibrationForm.ZedGraphControl.GraphPane.XAxis.Title.Text);
            Assert.AreEqual(string.Format(QuantificationStrings.CalibrationCurveFitter_PeakAreaRatioText__0___1__Peak_Area_Ratio, IsotopeLabelType.light.Title, IsotopeLabelType.heavy.Title),
                            calibrationForm.ZedGraphControl.GraphPane.YAxis.Title.Text);
        }
Exemplo n.º 10
0
        public QuantificationResult GetQuantification()
        {
            CalibrationCurveFitter curveFitter = Peptide.GetCalibrationCurveFitter();

            return(curveFitter.GetQuantificationResult(ResultFile.Replicate.ReplicateIndex));
        }
Exemplo n.º 11
0
        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 =
                    ModeUIAwareStringFormat(QuantificationStrings
                                            .CalibrationForm_DisplayCalibrationCurve_Select_a_peptide_to_see_its_calibration_curve);
                return;
            }
            if (-1 == document.Children.IndexOf(peptideGroup))
            {
                zedGraphControl.GraphPane.Title.Text = ModeUIAwareStringFormat(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 (curveFitter.IsEnableSingleBatch && Settings.Default.CalibrationCurveOptions.SingleBatch)
            {
                curveFitter.SingleBatchReplicateIndex = _skylineWindow.SelectedResultsIndex;
            }

            Text = TabText = GetFormTitle(curveFitter);
            if (peptideQuantifier.QuantificationSettings.RegressionFit == RegressionFit.NONE)
            {
                if (!(peptideQuantifier.NormalizationMethod is NormalizationMethod.RatioToLabel))
                {
                    zedGraphControl.GraphPane.Title.Text =
                        ModeUIAwareStringFormat(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 =
                            ModeUIAwareStringFormat(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();

            IEnumerable <SampleType> sampleTypes = 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 (!Equals(sampleType, curveFitter.GetSampleType(standardIdentifier)))
                    {
                        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(CalibrationCurve.RSquaredDisplayText(CalibrationCurve.RSquared.Value));
                }
                if (!Equals(curveFitter.QuantificationSettings.RegressionWeighting, RegressionWeighting.NONE))
                {
                    labelLines.Add(string.Format(@"{0}: {1}",
                                                 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 ? minY / 10 : 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);
                        }
                    }
                }

                QuantificationResult quantificationResult = null;
                double?calculatedConcentration;
                if (curveFitter.IsotopologResponseCurve)
                {
                    calculatedConcentration =
                        curveFitter.GetCalculatedConcentration(CalibrationCurve, selectionIdentifier.Value);
                }
                else
                {
                    quantificationResult    = curveFitter.GetPeptideQuantificationResult(selectionIdentifier.Value.ReplicateIndex);
                    calculatedConcentration = quantificationResult?.CalculatedConcentration;
                }
                if (calculatedConcentration.HasValue)
                {
                    labelLines.Add(string.Format(@"{0} = {1}",
                                                 QuantificationStrings.Calculated_Concentration,
                                                 QuantificationResult.FormatCalculatedConcentration(calculatedConcentration.Value,
                                                                                                    curveFitter.QuantificationSettings.Units)));
                }
                else if (quantificationResult != null && !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);
            }
        }
Exemplo n.º 12
0
        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);
            }
        }
Exemplo n.º 13
0
        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;
            SrmDocument document = DocumentUiContainer.DocumentUI;

            if (!document.Settings.HasResults)
            {
                zedGraphControl.GraphPane.Title.Text =
                    QuantificationStrings.CalibrationForm_DisplayCalibrationCurve_No_results_available;
                return;
            }
            PeptideDocNode      peptide      = null;
            PeptideGroupDocNode peptideGroup = null;
            SequenceTree        sequenceTree = _skylineWindow.SequenceTree;

            if (null != sequenceTree)
            {
                PeptideTreeNode peptideTreeNode = sequenceTree.GetNodeOfType <PeptideTreeNode>();
                if (null != peptideTreeNode)
                {
                    peptide = peptideTreeNode.DocNode;
                }
                PeptideGroupTreeNode peptideGroupTreeNode = sequenceTree.GetNodeOfType <PeptideGroupTreeNode>();
                if (null != peptideGroupTreeNode)
                {
                    peptideGroup = peptideGroupTreeNode.DocNode;
                }
            }

            if (null == peptide)
            {
                zedGraphControl.GraphPane.Title.Text =
                    QuantificationStrings
                    .CalibrationForm_DisplayCalibrationCurve_Select_a_peptide_to_see_its_calibration_curve;
                return;
            }
            PeptideQuantifier peptideQuantifier = PeptideQuantifier.GetPeptideQuantifier(document.Settings, peptideGroup,
                                                                                         peptide);
            CalibrationCurveFitter curveFitter = new CalibrationCurveFitter(peptideQuantifier, document.Settings);

            if (peptideQuantifier.QuantificationSettings.RegressionFit == RegressionFit.NONE)
            {
                if (string.IsNullOrEmpty(
                        peptideQuantifier.QuantificationSettings.NormalizationMethod.IsotopeLabelTypeName))
                {
                    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();
            double minX = double.MaxValue, maxX = double.MinValue;

            _scatterPlots = new CurveList();
            foreach (var sampleType in SampleType.ListSampleTypes())
            {
                if (!Options.DisplaySampleType(sampleType))
                {
                    continue;
                }
                PointPairList pointPairList = 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?x = curveFitter.GetSpecifiedXValue(iReplicate)
                               ?? curveFitter.GetCalculatedXValue(CalibrationCurve, iReplicate);
                    if (y.HasValue && x.HasValue)
                    {
                        PointPair point = new PointPair(x.Value, y.Value)
                        {
                            Tag = iReplicate
                        };
                        pointPairList.Add(point);
                        if (!Options.LogPlot || x.Value > 0)
                        {
                            minX = Math.Min(minX, x.Value);
                        }
                        maxX = Math.Max(maxX, x.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);
                }
            }
            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;
                        }
                    }
                    LineItem interpolatedLine = CreateInterpolatedLine(CalibrationCurve, minX, maxX,
                                                                       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));
                }
            }

            if (options.ShowSelection)
            {
                double?ySelected = curveFitter.GetYValue(_skylineWindow.SelectedResultsIndex);
                double?xSelected = curveFitter.GetCalculatedXValue(CalibrationCurve, _skylineWindow.SelectedResultsIndex);
                if (xSelected.HasValue && ySelected.HasValue)
                {
                    ArrowObj arrow = new ArrowObj(xSelected.Value, ySelected.Value, xSelected.Value,
                                                  ySelected.Value)
                    {
                        Line = { Color = GraphSummary.ColorSelected }
                    };
                    zedGraphControl.GraphPane.GraphObjList.Insert(0, arrow);
                }

                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);
            }
        }
Exemplo n.º 14
0
        protected override void DoTest()
        {
            RunUI(() =>
            {
                SkylineWindow.ResetDefaultSettings();
                SkylineWindow.NewDocument();
            });
            ShowAndPositionAuditLog(false);
            PauseForScreenShot <AuditLogForm>("Empty Audit Log form.", 2);

            // Configuring Settings for Inserting a New Peptide, p. 3
            {
                var doc = SkylineWindow.Document;
                var transitionSettingsUI = ShowDialog <TransitionSettingsUI>(SkylineWindow.ShowTransitionSettingsUI);

                RunUI(() =>
                {
                    // Filter Settings
                    transitionSettingsUI.SelectedTab = TransitionSettingsUI.TABS.Filter;
                    transitionSettingsUI.RangeFrom   = Resources.TransitionFilter_FragmentStartFinders_ion_3;
                    transitionSettingsUI.RangeTo     = Resources.TransitionFilter_FragmentEndFinders_last_ion_minus_1;
                });
                OkDialog(transitionSettingsUI, transitionSettingsUI.OkDialog);
                WaitForDocumentChange(doc);
            }

            PeptideSettingsUI peptideSettingsUi = ShowDialog <PeptideSettingsUI>(SkylineWindow.ShowPeptideSettingsUI);

            RunUI(() => peptideSettingsUi.SelectedTab = PeptideSettingsUI.TABS.Modifications);

            var modHeavyK = new StaticMod("Label:13C(6)15N(2) (C-term K)", "K", ModTerminus.C, false, null, LabelAtoms.C13 | LabelAtoms.N15,
                                          RelativeRT.Matching, null, null, null);

            AddHeavyMod(modHeavyK, peptideSettingsUi);
            RunUI(() => peptideSettingsUi.PickedHeavyMods = new[] { modHeavyK.Name });

            OkDialog(peptideSettingsUi, peptideSettingsUi.OkDialog);

            PauseForScreenShot <AuditLogForm>("Audit Log form with settings modifications.", 4);

            RunUI(() =>
            {
                SkylineWindow.AuditLogForm.Close();
                SkylineWindow.Width = 1010;
            });

            PauseForScreenShot("Undo list expanded. (manual)", 4);

            RunUI(SkylineWindow.Undo);

            PauseForScreenShot("Redo list expanded. (manual)", 5);

            RunUI(SkylineWindow.Redo);

            // Inserting a peptide sequence p. 5
            using (new CheckDocumentState(1, 1, 2, 10))
            {
                WaitForProteinMetadataBackgroundLoaderCompletedUI();

                var pasteDlg = ShowDialog <PasteDlg>(SkylineWindow.ShowPastePeptidesDlg);
                RunUI(() => SetClipboardText("IEAIPQIDK\tGST-tag"));
                RunUI(pasteDlg.PastePeptides);
                RunUI(() =>
                {
                    pasteDlg.Size = new Size(700, 210);
                    pasteDlg.Top  = SkylineWindow.Bottom + 20;
                });
                PauseForScreenShot <PasteDlg.PeptideListTab>("Insert Peptide List", 6);

                using (new WaitDocumentChange())
                {
                    OkDialog(pasteDlg, pasteDlg.OkDialog);
                }

                WaitForConditionUI(() => SkylineWindow.SequenceTree.Nodes.Count > 0);
            }

            RunUI(() =>
            {
                SkylineWindow.ExpandPrecursors();
                SkylineWindow.Height = 390;
            });

            PauseForScreenShot("Main window with Targets view", 6);

            ShowAndPositionAuditLog(true);
            PauseForScreenShot <AuditLogForm>("Audit Log form with inserted peptide.", 7);

            ShowLastExtraInfo("Extra info form with inserted peptide info.", 7);

            string documentPath = GetTestPath("AuditLogTutorial" + SrmDocument.EXT);

            RunUI(() => SkylineWindow.SaveDocument(documentPath));
            WaitForCondition(() => File.Exists(documentPath));

            // Importing RAW files into Skyline p. 7
            var importResultsDlg = ShowDialog <ImportResultsDlg>(SkylineWindow.ImportResults);

            RunUI(() =>
            {
                var rawFiles      = DataSourceUtil.GetDataSources(TestFilesDirs[0].FullPath).First().Value;
                var namedPathSets = from rawFile in rawFiles
                                    select new KeyValuePair <string, MsDataFileUri[]>(
                    rawFile.GetFileNameWithoutExtension(), new[] { rawFile });
                importResultsDlg.NamedPathSets = namedPathSets.ToArray();
            });
            OkDialog(importResultsDlg, importResultsDlg.OkDialog);

            WaitForGraphs();

            RunUI(() =>
            {
                SkylineWindow.SelectedPath             = SkylineWindow.Document.GetPathTo((int)SrmDocument.Level.Molecules, 0);
                Settings.Default.ArrangeGraphsOrder    = GroupGraphsOrder.Document.ToString();
                Settings.Default.ArrangeGraphsReversed = false;
                SkylineWindow.ArrangeGraphsTabbed();
                SkylineWindow.AutoZoomBestPeak();
            });
            WaitForCondition(() => Equals(9, SkylineWindow.GraphChromatograms.Count(graphChrom => !graphChrom.IsHidden)),
                             "unexpected visible graphChromatogram count");

            WaitForCondition(10 * 60 * 1000,    // ten minutes
                             () => SkylineWindow.Document.Settings.HasResults && SkylineWindow.Document.Settings.MeasuredResults.IsLoaded);

            PauseForScreenShot <AuditLogForm>("Audit Log form with imported data files.", 9);

            ShowLastExtraInfo("Extra info form for the import.", 9);

            // Peptide Quantitification Settings p. 9
            peptideSettingsUi = ShowDialog <PeptideSettingsUI>(SkylineWindow.ShowPeptideSettingsUI);
            RunUI(() => peptideSettingsUi.SelectedTab = (PeptideSettingsUI.TABS) 5);
            const string quantUnits = "fmol/ul";

            RunUI(() =>
            {
                peptideSettingsUi.QuantRegressionFit       = RegressionFit.LINEAR;
                peptideSettingsUi.QuantNormalizationMethod = new NormalizationMethod.RatioToLabel(IsotopeLabelType.heavy);
                peptideSettingsUi.QuantUnits = quantUnits;
            });
            OkDialog(peptideSettingsUi, peptideSettingsUi.OkDialog);

            PauseForScreenShot <AuditLogForm>("Audit Log form with quantification settings.", 10);

            // Specify analyte concentrations of external standards
            RunUI(() =>
            {
                SkylineWindow.AuditLogForm.Close();
                SkylineWindow.ShowDocumentGrid(true);
            });
            var documentGridForm = FindOpenForm <DocumentGridForm>();

            RunUI(() =>
            {
                documentGridForm.ChooseView(Resources.SkylineViewContext_GetDocumentGridRowSources_Replicates);
            });
            WaitForConditionUI(() => documentGridForm.IsComplete);

            var concentrations = new[] { 40, 12.5, 5, 2.5, 1, .5, .25, .1 };

            string pasteString = TextUtil.LineSeparate(concentrations.Select((f, i) =>
                                                                             QuantificationStrings.SampleType_STANDARD_Standard + "\t" + f));

            ClipboardEx.SetText(pasteString);

            using (new WaitDocumentChange())
            {
                RunUI(() =>
                {
                    var colSampleType = documentGridForm.FindColumn(PropertyPath.Root.Property("SampleType"));
                    documentGridForm.DataGridView.CurrentCell = documentGridForm.DataGridView.Rows[1].Cells[colSampleType.Index];
                    documentGridForm.DataGridView.SendPaste();
                });
            }

            // ReSharper restore AccessToModifiedClosure
            WaitForConditionUI(() => documentGridForm.IsComplete);
            RunUI(() =>
            {
                var gridFloatingWindow  = documentGridForm.Parent.Parent;
                gridFloatingWindow.Size = new Size(370, 315);
                gridFloatingWindow.Top  = SkylineWindow.Bottom + 20;
            });
            PauseForScreenShot <DocumentGridForm>("Document grid with concentrations filled in", 11);
            RunUI(documentGridForm.Close);

            ShowAndPositionAuditLog(true);
            PauseForScreenShot <AuditLogForm>("Audit Log form with grid changes", 12);

            ShowLastExtraInfo("Extra Info for the analyte data import.", 12);
            RunUI(SkylineWindow.AuditLogForm.Close);

            const string unknownReplicate = "FOXN1-GST";

            RestoreViewOnScreen(13);
            ActivateReplicate(unknownReplicate);
            SelectNode(SrmDocument.Level.TransitionGroups, 1);
            RunUI(() => SkylineWindow.Size = new Size(936, 527));
            WaitForGraphs();

            PauseForScreenShot("Heavy precursor chromatogram", 13);

            RunUI(() =>
            {
                var pathHeavy = SkylineWindow.DocumentUI.GetPathTo((int)SrmDocument.Level.TransitionGroups, 1);

                var graphChrom = SkylineWindow.GetGraphChrom(unknownReplicate);
                Assert.IsNotNull(graphChrom);
                Assert.AreEqual(unknownReplicate, graphChrom.NameSet);

                var firstGroupInfo = graphChrom.ChromGroupInfos.FirstOrDefault();
                Assert.IsNotNull(firstGroupInfo, "Missing group info");
                var firstChromItem = graphChrom.GraphItems.FirstOrDefault(gci => gci.TransitionChromInfo != null);
                Assert.IsNotNull(firstChromItem, "Missing graph item");

                var listChanges = new List <ChangedPeakBoundsEventArgs>
                {
                    new ChangedPeakBoundsEventArgs(pathHeavy,
                                                   null,
                                                   graphChrom.NameSet,
                                                   firstGroupInfo.FilePath,
                                                   firstChromItem.GetValidPeakBoundaryTime(20.65),
                                                   firstChromItem.GetValidPeakBoundaryTime(21.15),
                                                   PeakIdentification.FALSE,
                                                   PeakBoundsChangeType.both)
                };
                graphChrom.SimulateChangedPeakBounds(listChanges);
            });

            ShowAndPositionAuditLog(true, 50, 200);
            WaitForConditionUI(500, () => SkylineWindow.AuditLogForm.DataGridView.Rows.Count > 0);

            PauseForScreenShot <AuditLogForm>("Audit Log form with changed integration boundary.", 14);
            int reasonIndex = 2;

            using (new WaitDocumentChange())
            {
                RunUI(() =>
                {
                    var pathReason = PropertyPath.Root.Property("Reason");
                    var colReason  = SkylineWindow.AuditLogForm.FindColumn(pathReason);
                    reasonIndex    = colReason.Index;
                    SetCellValue(SkylineWindow.AuditLogForm.DataGridView, 0, reasonIndex,
                                 "Changed peak integration as instructed by the tutorial");
                });
            }
            RunUI(() => SkylineWindow.AuditLogForm.DataGridView.AutoResizeColumn(reasonIndex));
            SetGridFormToFullWidth(SkylineWindow.AuditLogForm);
            PauseForScreenShot <AuditLogForm>("Audit Log form with updated reason.", 14);

            // View the calibration curve p. 15
            RunUI(() => SkylineWindow.ShowCalibrationForm());
            var calibrationForm = FindOpenForm <CalibrationForm>();
            var priorZoomState  = ZoomCalibrationCurve(calibrationForm, 0.52);

            RunUI(() =>
            {
                Assert.AreEqual(CalibrationCurveFitter.AppendUnits(QuantificationStrings.Analyte_Concentration, quantUnits), calibrationForm.ZedGraphControl.GraphPane.XAxis.Title.Text);
                Assert.AreEqual(string.Format(QuantificationStrings.CalibrationCurveFitter_PeakAreaRatioText__0___1__Peak_Area_Ratio, IsotopeLabelType.light.Title, IsotopeLabelType.heavy.Title),
                                calibrationForm.ZedGraphControl.GraphPane.YAxis.Title.Text);

                VerifyCalibrationCurve(calibrationForm, 5.4065E-1, -2.9539E-1, 0.999);
            });

            PauseForScreenShot <CalibrationForm>("Calibration curve zoomed", 15);
            RunUI(() =>
            {
                priorZoomState?.ApplyState(calibrationForm.ZedGraphControl.GraphPane);

                var chromatograms = SkylineWindow.DocumentUI.Settings.MeasuredResults.Chromatograms;
                new [] { 5, 6, 7, 8 }.ForEach((index) =>
                {
                    int replicateIdx = chromatograms.IndexOf((ch) => ch.Name.Equals("Standard_" + index));
                    Assert.IsTrue(replicateIdx >= 0);
                    using (var excludeStandardMenu = calibrationForm.MakeExcludeStandardMenuItem(replicateIdx))
                    {
                        excludeStandardMenu?.PerformClick();
                    }
                });
            });
            WaitForGraphs();
            RunUI(() => VerifyCalibrationCurve(calibrationForm, 5.52E-1, -6.3678E-1, 1));
            OkDialog(calibrationForm, calibrationForm.Close);

            PauseForScreenShot <AuditLogForm>("Audit Log with excluded standard records", 16);

            PauseForScreenShot <AuditLogForm>("Audit Log Reports menu (manual)", 16);

            // TODO(nicksh): Audit log reason field does not currently support fill down
//            RunUI(() =>
//            {
//                SetCellValue(SkylineWindow.AuditLogForm.DataGridView, 0, reasonIndex, "Excluded standard below LOD");
//                for (int i = 0; i < 4; i++)
//                    SkylineWindow.AuditLogForm.DataGridView.Rows[i].Cells[reasonIndex].Selected = true;
//            });
//            RunUI(() => SkylineWindow.AuditLogForm.DataboundGridControl.FillDown());
            RunUI(() =>
            {
                for (int i = 0; i < 4; i++)
                {
                    SetCellValue(SkylineWindow.AuditLogForm.DataGridView, i, reasonIndex, "Excluded standard below LOD");
                }
            });
            RunUI(() =>
            {
                SkylineWindow.AuditLogForm.ChooseView(AuditLogStrings.AuditLogForm_MakeAuditLogForm_Undo_Redo);
            });
            SetGridFormToFullWidth(SkylineWindow.AuditLogForm);
            RunUI(() =>
            {
                var floatingWindow    = SkylineWindow.AuditLogForm.Parent.Parent;
                floatingWindow.Height = 334;
                floatingWindow.Width -= 15;
            });
            PauseForScreenShot <AuditLogForm>("Audit Log with UndoRedo view.", 17);
            if (IsCoverShotMode)
            {
                RunUI(() =>
                {
                    SkylineWindow.ChangeTextSize(TreeViewMS.LRG_TEXT_FACTOR);
                });

                RestoreCoverViewOnScreen();

                var calibrationCoverForm = WaitForOpenForm <CalibrationForm>();
                ZoomCalibrationCurve(calibrationCoverForm, 0.53);
                var floatingLogWindow = SkylineWindow.AuditLogForm.Parent.Parent;
                var floatingCalWindow = calibrationCoverForm.Parent.Parent;
                RunUI(() =>
                {
                    floatingLogWindow.Top  = SkylineWindow.Bottom - floatingLogWindow.Height - 8;
                    floatingLogWindow.Left =
                        (SkylineWindow.Left + SkylineWindow.Right) / 2 - floatingLogWindow.Width / 2;
                    floatingCalWindow.Top  = SkylineWindow.Top + 8;
                    floatingCalWindow.Left = SkylineWindow.Right - floatingCalWindow.Width - 8;
                    SkylineWindow.AuditLogForm.DataGridView.AutoResizeColumn(reasonIndex);
                    SkylineWindow.AuditLogForm.DataGridView.AutoResizeColumn(reasonIndex - 1);
                });
                TakeCoverShot();
            }

            var customizeDialog = ShowDialog <ViewEditor>(SkylineWindow.AuditLogForm.NavBar.CustomizeView);

            RunUI(() =>
            {
                customizeDialog.ViewName = "Custom Columns";
                var columnsToAdd         = new[]
                {
                    PropertyPath.Parse("SkylineVersion"),
                    PropertyPath.Parse("User"),
                };
                foreach (var id in columnsToAdd)
                {
                    Assert.IsTrue(customizeDialog.ChooseColumnsTab.TrySelect(id), "Unable to select {0}", id);
                    customizeDialog.ChooseColumnsTab.AddSelectedColumn();
                }

                customizeDialog.Height = 370;
            });
            PauseForScreenShot <ViewEditor.ChooseColumnsView>("Custom Columns report template", 17);
            OkDialog(customizeDialog, customizeDialog.OkDialog);
            SetGridFormToFullWidth(SkylineWindow.AuditLogForm);
            RunUI(() => SkylineWindow.AuditLogForm.Parent.Parent.Height += 10); // Extra for 2-line headers
            PauseForScreenShot <AuditLogForm>("Audit Log with custom view.", 18);

            var registrationDialog = ShowDialog <MultiButtonMsgDlg>(() => SkylineWindow.ShowPublishDlg(null));

            PauseForScreenShot <MultiButtonMsgDlg>("Upload confirmation dialog.", 19);

            var loginDialog = ShowDialog <EditServerDlg>(registrationDialog.ClickNo);

            PauseForScreenShot <EditServerDlg>("Login dialog.", 20);

            RunUI(() =>
            {
                loginDialog.URL      = SERVER_URL;
                loginDialog.Username = PANORAMA_USER_NAME;
            });

            if (!IsPauseForScreenShots)
            {
                OkDialog(loginDialog, loginDialog.CancelButton.PerformClick);
            }
            else
            {
                PauseTest("Enter password. (manual) No screen shot.");

                var publishDialog = ShowDialog <PublishDocumentDlg>(loginDialog.OkDialog);
                WaitForCondition(() => publishDialog.IsLoaded);
                RunUI(() =>
                {
                    publishDialog.SelectItem(testFolderName);
                });
                PauseForScreenShot <PublishDocumentDlg>("Folder selection dialog.", 21);
                var browserConfirmationDialog = ShowDialog <MultiButtonMsgDlg>(publishDialog.OkDialog);

                OkDialog(browserConfirmationDialog, browserConfirmationDialog.ClickYes);

                PauseForScreenShot("Uploaded document in Panorama (in browser).");

                Regex reDocId = new Regex(@"\?id=([0-9]+)");
                Assert.IsTrue(reDocId.IsMatch(publishDialog.PanoramaPublishClient.UploadedDocumentUri.ToString()));

                string docId      = reDocId.Match(publishDialog.PanoramaPublishClient.UploadedDocumentUri.ToString()).Groups[1].Captures[0].Value;
                Uri    serverUri  = new Uri(SERVER_URL);
                Uri    requestUri = PanoramaUtil.Call(serverUri, "targetedms", String.Format("{0}/{1}", PANORAMA_FOLDER, testFolderName),
                                                      "showSkylineAuditLog", "id=" + docId);
                Process.Start(requestUri.ToString());
                PauseForScreenShot("Uploaded document audit log in Panorama (in browser).");
            }
        }
Exemplo n.º 15
0
        protected override void DoTest()
        {
            RunUI(() => SkylineWindow.OpenFile(TestFilesDir.GetTestPath("p180test_calibration_DukeApril2016.sky")));
            var surrogateStandards = new Dictionary <string, string>
            {
                { "Leu", "Ile" },
                { "Lys", "Orn" },
                { "Ac-Orn", "Orn" },
                { "SDMA", "ADMA" },
                { "alpha-AAA", "Orn" },
                { "Carnosine", "His" },
                { "Histamine", "His" },
                { "Kynurenine", "Tyr" },
                { "Met-SO", "Met" },
                { "Nitro-Tyr", "Tyr" },
                { "c4-OH-Pro", "Pro" },
                { "t4-OH-Pro", "Pro" },
            };

            // Set the standard type of the surrogate standards to StandardType.SURROGATE_STANDARD
            RunUI(() =>
            {
                List <IdentityPath> pathsToSelect = SkylineWindow.SequenceTree.Nodes.OfType <PeptideGroupTreeNode>()
                                                    .SelectMany(peptideGroup => peptideGroup.Nodes.OfType <PeptideTreeNode>())
                                                    .Where(peptideTreeNode => surrogateStandards.Values.Contains(peptideTreeNode.DocNode.RawTextId))
                                                    .Select(treeNode => treeNode.Path)
                                                    .ToList();
                SkylineWindow.SequenceTree.SelectedPaths = pathsToSelect;
                SkylineWindow.SetStandardType(StandardType.SURROGATE_STANDARD);
            });

            // Use the document grid to set the Normalization Method of the molecules that have surrogate standards
            var documentGrid = ShowDialog <DocumentGridForm>(() => SkylineWindow.ShowDocumentGrid(true));

            RunUI(() => documentGrid.ChooseView(Resources.Resources_ReportSpecList_GetDefaults_Peptide_Quantification));
            IDataGridViewEditingControl editingControl = null;
            DataGridViewEditingControlShowingEventHandler onEditingControlShowing =
                (sender, args) => editingControl = args.Control as IDataGridViewEditingControl;

            documentGrid.DataGridView.EditingControlShowing += onEditingControlShowing;

            // ReSharper disable AccessToForEachVariableInClosure
            foreach (var entry in surrogateStandards)
            {
                WaitForConditionUI(() => documentGrid.IsComplete);
                RunUI(() =>
                {
                    var colPeptide = documentGrid.FindColumn(PropertyPath.Root);
                    for (int iRow = 0; iRow < documentGrid.RowCount; iRow++)
                    {
                        var row = documentGrid.DataGridView.Rows[iRow];
                        if (!entry.Key.Equals(row.Cells[colPeptide.Index].FormattedValue))
                        {
                            continue;
                        }
                        var colNormalizationMethod            = documentGrid.FindColumn(PropertyPath.Root.Property("NormalizationMethod"));
                        documentGrid.DataGridView.CurrentCell = row.Cells[colNormalizationMethod.Index];
                        documentGrid.DataGridView.BeginEdit(false);
                        editingControl.EditingControlFormattedValue =
                            string.Format(Resources.RatioToSurrogate_ToString_Ratio_to_surrogate__0____1__, entry.Value,
                                          "Heavy");
                        documentGrid.DataGridView.EndEdit();
                    }
                });
            }

            // Make sure that the Y-Axis on the CalibrationForm reflects the normalization method of the selected molecule
            var calibrationForm = ShowDialog <CalibrationForm>(() => SkylineWindow.ShowCalibrationForm());

            foreach (var peptideGroupTreeNode in SkylineWindow.SequenceTree.Nodes.OfType <PeptideGroupTreeNode>())
            {
                foreach (var peptideTreeNode in peptideGroupTreeNode.Nodes.OfType <PeptideTreeNode>())
                {
                    RunUI(() => SkylineWindow.SequenceTree.SelectedPath = peptideTreeNode.Path);
                    WaitForGraphs();
                    string yAxisText = calibrationForm.ZedGraphControl.GraphPane.YAxis.Title.Text;
                    if (null != peptideTreeNode.DocNode.NormalizationMethod)
                    {
                        Assert.IsInstanceOfType(peptideTreeNode.DocNode.NormalizationMethod, typeof(NormalizationMethod.RatioToSurrogate));
                        Assert.AreEqual(QuantificationStrings.CalibrationCurveFitter_GetYAxisTitle_Normalized_Peak_Area,
                                        yAxisText);
                    }
                    else
                    {
                        Assert.IsInstanceOfType(SkylineWindow.Document.Settings.PeptideSettings.Quantification.NormalizationMethod, typeof(NormalizationMethod.RatioToLabel));
                        string expectedTitle = CalibrationCurveFitter.PeakAreaRatioText(IsotopeLabelType.light,
                                                                                        IsotopeLabelType.heavy);
                        Assert.AreEqual(expectedTitle, yAxisText);
                    }
                }
            }
        }
Exemplo n.º 16
0
        public AreaCVRefinementData(SrmDocument document, AreaCVRefinementSettings settings,
                                    CancellationToken token, SrmSettingsChangeMonitor progressMonitor = null)
        {
            _settings = settings;
            if (document == null || !document.Settings.HasResults)
            {
                return;
            }

            var replicates  = document.MeasuredResults.Chromatograms.Count;
            var areas       = new List <AreaInfo>(replicates);
            var annotations = AnnotationHelper.GetPossibleAnnotations(document, settings.Group).ToArray();

            if (!annotations.Any() && settings.Group == null)
            {
                annotations = new string[] { null }
            }
            ;

            _internalData = new List <InternalData>();
            var hasHeavyMods       = document.Settings.PeptideSettings.Modifications.HasHeavyModifications;
            var hasGlobalStandards = document.Settings.HasGlobalStandardArea;
            var ms1 = settings.MsLevel == AreaCVMsLevel.precursors;

            // Avoid using not-MS1 with a document that is only MS1
            if (!ms1 && document.MoleculeTransitions.All(t => t.IsMs1))
            {
                ms1 = true;
            }
            double?qvalueCutoff = null;

            if (ShouldUseQValues(document))
            {
                qvalueCutoff = _settings.QValueCutoff;
            }

            int?minDetections = null;

            if (_settings.MinimumDetections != -1)
            {
                minDetections = _settings.MinimumDetections;
            }

            MedianInfo medianInfo = null;
            int?       ratioIndex = null;

            if (settings.NormalizeOption.IsRatioToLabel)
            {
                var isotopeLabelTypeName = (settings.NormalizeOption.NormalizationMethod as NormalizationMethod.RatioToLabel)
                                           ?.IsotopeLabelTypeName;
                ratioIndex =
                    document.Settings.PeptideSettings.Modifications.RatioInternalStandardTypes.IndexOf(type =>
                                                                                                       type.Name == isotopeLabelTypeName);
            }
            if (_settings.NormalizeOption.Is(NormalizationMethod.EQUALIZE_MEDIANS))
            {
                medianInfo = CalculateMedianAreas(document);
            }
            NormalizationData normalizationData = null;

            foreach (var peptideGroup in document.MoleculeGroups)
            {
                foreach (var peptide in peptideGroup.Molecules)
                {
                    if (progressMonitor != null)
                    {
                        progressMonitor.ProcessMolecule(peptide);
                    }

                    if (_settings.PointsType == PointsTypePeakArea.decoys != peptide.IsDecoy)
                    {
                        continue;
                    }

                    CalibrationCurveFitter calibrationCurveFitter = null;
                    CalibrationCurve       calibrationCurve       = null;
                    IEnumerable <TransitionGroupDocNode> transitionGroups;
                    if (_settings.NormalizeOption == NormalizeOption.CALIBRATED ||
                        _settings.NormalizeOption == NormalizeOption.DEFAULT)
                    {
                        if (!peptide.TransitionGroups.Any())
                        {
                            continue;
                        }
                        var peptideQuantifier = PeptideQuantifier.GetPeptideQuantifier(() =>
                        {
                            return(normalizationData = normalizationData ?? NormalizationData.GetNormalizationData(document, false, null));
                        }, document.Settings, peptideGroup, peptide);
                        calibrationCurveFitter = new CalibrationCurveFitter(peptideQuantifier, document.Settings);
                        transitionGroups       = new[] { peptide.TransitionGroups.First() };
                        if (_settings.NormalizeOption == NormalizeOption.CALIBRATED)
                        {
                            calibrationCurve = calibrationCurveFitter.GetCalibrationCurve();
                            if (calibrationCurve == null)
                            {
                                continue;
                            }
                        }
                    }
                    else
                    {
                        transitionGroups = peptide.TransitionGroups;
                    }
                    foreach (var transitionGroupDocNode in transitionGroups)
                    {
                        foreach (var a in annotations)
                        {
                            areas.Clear();

                            if (!Equals(a, _settings.Annotation) && (_settings.Group == null || _settings.Annotation != null))
                            {
                                continue;
                            }

                            foreach (var replicateIndex in AnnotationHelper.GetReplicateIndices(document,
                                                                                                _settings.Group, a))
                            {
                                if (progressMonitor != null && progressMonitor.IsCanceled())
                                {
                                    throw new OperationCanceledException();
                                }

                                token.ThrowIfCancellationRequested();
                                var groupChromInfo = transitionGroupDocNode.GetSafeChromInfo(replicateIndex)
                                                     .FirstOrDefault(c => c.OptimizationStep == 0);
                                if (groupChromInfo == null)
                                {
                                    continue;
                                }

                                if (qvalueCutoff.HasValue)
                                {
                                    if (!(groupChromInfo.QValue.HasValue &&
                                          groupChromInfo.QValue.Value < qvalueCutoff.Value))
                                    {
                                        continue;
                                    }
                                }

                                double sumArea, normalizedArea;
                                if (calibrationCurveFitter != null)
                                {
                                    double?value;
                                    if (calibrationCurve != null)
                                    {
                                        value = calibrationCurveFitter.GetCalculatedConcentration(calibrationCurve,
                                                                                                  replicateIndex);
                                    }
                                    else
                                    {
                                        value = calibrationCurveFitter.GetNormalizedPeakArea(
                                            new CalibrationPoint(replicateIndex, null));
                                    }
                                    if (!value.HasValue)
                                    {
                                        continue;
                                    }

                                    sumArea        = value.Value;
                                    normalizedArea = value.Value;
                                }
                                else
                                {
                                    if (!groupChromInfo.Area.HasValue)
                                    {
                                        continue;
                                    }
                                    var index = replicateIndex;
                                    sumArea = transitionGroupDocNode.Transitions.Where(t =>
                                    {
                                        if (ms1 != t.IsMs1 || !t.ExplicitQuantitative)
                                        {
                                            return(false);
                                        }

                                        var chromInfo = t.GetSafeChromInfo(index)
                                                        .FirstOrDefault(c => c.OptimizationStep == 0);
                                        if (chromInfo == null)
                                        {
                                            return(false);
                                        }
                                        if (_settings.Transitions == AreaCVTransitions.best)
                                        {
                                            return(chromInfo.RankByLevel == 1);
                                        }
                                        if (_settings.Transitions == AreaCVTransitions.all)
                                        {
                                            return(true);
                                        }

                                        return(chromInfo.RankByLevel <= _settings.CountTransitions);
                                        // ReSharper disable once PossibleNullReferenceException
                                    }).Sum(t => (double)t.GetSafeChromInfo(index)
                                           .FirstOrDefault(c => c.OptimizationStep == 0).Area);

                                    normalizedArea = sumArea;
                                    if (_settings.NormalizeOption.Is(NormalizationMethod.EQUALIZE_MEDIANS))
                                    {
                                        normalizedArea /= medianInfo.Medians[replicateIndex] / medianInfo.MedianMedian;
                                    }
                                    else if (_settings.NormalizeOption.Is(NormalizationMethod.GLOBAL_STANDARDS) &&
                                             hasGlobalStandards)
                                    {
                                        normalizedArea =
                                            NormalizeToGlobalStandard(document, transitionGroupDocNode, replicateIndex,
                                                                      sumArea);
                                    }
                                    else if (_settings.NormalizeOption.Is(NormalizationMethod.TIC))
                                    {
                                        var denominator = document.Settings.GetTicNormalizationDenominator(
                                            replicateIndex, groupChromInfo.FileId);
                                        if (!denominator.HasValue)
                                        {
                                            continue;
                                        }

                                        normalizedArea /= denominator.Value;
                                    }
                                    else if (hasHeavyMods &&
                                             _settings.NormalizeOption.NormalizationMethod is NormalizationMethod
                                             .RatioToLabel)
                                    {
                                        var ci = transitionGroupDocNode.GetSafeChromInfo(replicateIndex)
                                                 .FirstOrDefault(c => c.OptimizationStep == 0);
                                        RatioValue ratioValue = null;
                                        if (ratioIndex.HasValue && ratioIndex.Value >= 0 &&
                                            ratioIndex.Value < ci.Ratios.Count)
                                        {
                                            ratioValue = ci.Ratios[ratioIndex.Value];
                                        }

                                        if (ratioValue == null)
                                        {
                                            continue;
                                        }

                                        normalizedArea = ratioValue.Ratio;
                                    }
                                }
                                areas.Add(new AreaInfo(sumArea, normalizedArea));
                            }

                            if (qvalueCutoff.HasValue && minDetections.HasValue && areas.Count < minDetections.Value)
                            {
                                continue;
                            }

                            _settings.AddToInternalData(_internalData, areas, peptideGroup, peptide, transitionGroupDocNode, a);
                        }
                    }
                }
            }
            Data = ImmutableList <CVData> .ValueOf(_internalData.GroupBy(i => i, (key, grouped) =>
            {
                var groupedArray = grouped.ToArray();
                return(new CVData(
                           groupedArray.Select(idata => new PeptideAnnotationPair(idata.PeptideGroup, idata.Peptide, idata.TransitionGroup, idata.Annotation, idata.CV)),
                           key.CVBucketed, key.Area, groupedArray.Length));
            }).OrderBy(d => d.CV));
        }