Exemple #1
0
        private LineItem CreateInterpolatedLine(CalibrationCurve calibrationCurve, double[] xValues, int pointCount, bool logPlot)
        {
            PointPairList pointPairList = new PointPairList();

            for (int iRange = 0; iRange < xValues.Length - 1; iRange++)
            {
                double minX = xValues[iRange];
                double maxX = xValues[iRange + 1];
                for (int i = 0; i < pointCount; i++)
                {
                    double x;
                    if (logPlot)
                    {
                        x = Math.Exp((Math.Log(minX) * (pointCount - 1 - i) + Math.Log(maxX) * i) / (pointCount - 1));
                    }
                    else
                    {
                        x = (minX * (pointCount - 1 - i) + maxX * i) / (pointCount - 1);
                    }
                    double?y = calibrationCurve.GetY(x);
                    if (y.HasValue)
                    {
                        pointPairList.Add(x, y.Value);
                    }
                }
            }
            if (!pointPairList.Any())
            {
                return(null);
            }
            return(new LineItem(QuantificationStrings.Calibration_Curve, pointPairList, Color.Gray, SymbolType.None));
        }
Exemple #2
0
 private void saveToolStripMenuItem_Click(object sender, EventArgs e)
 {
     try {
         Co = new float[dataGridView1.Rows.Count];
         b1 = new float[dataGridView1.Rows.Count];
         int f = 0;
         foreach (DataGridViewRow dr in dataGridView1.Rows)
         {
             if (dataGridView1.Rows.Count > 0)
             {
                 Co[f] = float.Parse(dr.Cells[0].Value.ToString());
                 b1[f] = float.Parse(dr.Cells[1].Value.ToString());
             }
             f++;
         }
         SaveFileDialog saveFileDialog = new SaveFileDialog();
         saveFileDialog.Filter = "|*.ccu";
         CalibrationCurve ca = new CalibrationCurve();
         ca.cor = Co;
         ca.abs = b1;
         if (saveFileDialog.ShowDialog() == DialogResult.OK)
         {
             IFormatter formatter     = new BinaryFormatter();
             FileStream seryalization = new FileStream(saveFileDialog.FileName, FileMode.Create, FileAccess.Write);
             formatter.Serialize(seryalization, ca);
             seryalization.Close();
         }
     }catch (Exception ex)
     {
         MessageBox.Show(ex.ToString());
     }
 }
Exemple #3
0
        public void TestBilinearFit()
        {
            CalibrationCurve calcurve = RegressionFit.BILINEAR.Fit(LKPALAVILLER_POINTS);

            Assert.IsNotNull(calcurve.TurningPoint);
            Assert.AreEqual(11673.593881022069, calcurve.TurningPoint.Value, 1);
            Assert.AreEqual(1.2771070764E-12, calcurve.Slope.Value, 1E-15);
            Assert.AreEqual(-1.4118993633E-08, calcurve.Intercept.Value, 1E-12);
        }
Exemple #4
0
        private void TestAllQuantificationSettings()
        {
            RunUI(() => SkylineWindow.ShowCalibrationForm());
            var calibrationForm = FindOpenForm <CalibrationForm>();

            foreach (var quant in ListAllQuantificationSettings())
            {
                var quantValue = quant; // For ReSharper
                RunUI(() => SkylineWindow.ModifyDocument("Change Quantification Settings", doc => doc.ChangeSettings(
                                                             doc.Settings.ChangePeptideSettings(
                                                                 doc.Settings.PeptideSettings.ChangeAbsoluteQuantification(quantValue)))));
                WaitForGraphs();
                CalibrationCurve calibrationCurve = calibrationForm.CalibrationCurve;
                if (quant.MsLevel == 1 && quant.RegressionFit != RegressionFit.NONE)
                {
                    Assert.IsNotNull(calibrationCurve.ErrorMessage);
                }
                else
                {
                    Assert.IsNull(calibrationCurve.ErrorMessage);
                    if (quant.RegressionFit == RegressionFit.NONE)
                    {
                        Assert.AreEqual(0, calibrationCurve.PointCount);
                    }
                    else if (quant.RegressionFit == RegressionFit.LINEAR_THROUGH_ZERO)
                    {
                        Assert.IsNull(calibrationCurve.Intercept);
                        Assert.IsNotNull(calibrationCurve.Slope);
                        Assert.IsNull(calibrationCurve.QuadraticCoefficient);
                        Assert.IsNull(calibrationCurve.TurningPoint);
                    }
                    else if (quant.RegressionFit == RegressionFit.LINEAR)
                    {
                        Assert.IsNotNull(calibrationCurve.Intercept);
                        Assert.IsNotNull(calibrationCurve.Slope);
                        Assert.IsNull(calibrationCurve.QuadraticCoefficient);
                        Assert.IsNull(calibrationCurve.TurningPoint);
                    }
                    else if (quant.RegressionFit == RegressionFit.BILINEAR)
                    {
                        Assert.IsNotNull(calibrationCurve.Intercept);
                        Assert.IsNotNull(calibrationCurve.Slope);
                        Assert.IsNull(calibrationCurve.QuadraticCoefficient);
                        Assert.IsNotNull(calibrationCurve.TurningPoint);
                    }
                    else
                    {
                        Assert.AreEqual(RegressionFit.QUADRATIC, quant.RegressionFit);
                        Assert.IsNotNull(calibrationCurve.Intercept);
                        Assert.IsNotNull(calibrationCurve.Slope);
                        Assert.IsNotNull(calibrationCurve.QuadraticCoefficient);
                        Assert.IsNull(calibrationCurve.TurningPoint);
                    }
                }
            }
        }
Exemple #5
0
        private void VerifyCalibrationCurve(CalibrationForm calibrationForm, double slope, double intercept, double rSquared)
        {
            var labels = calibrationForm.ZedGraphControl.GraphPane.GraphObjList.FirstOrDefault(o => o is TextObj) as TextObj;

            Assert.IsNotNull(labels);
            var lines = labels.Text.Split(new[] { Environment.NewLine }, StringSplitOptions.None);

            Assert.IsTrue(lines.Length >= 2);
            Assert.AreEqual(CalibrationCurve.Format(slope, intercept), lines[0]);
            Assert.AreEqual(CalibrationCurve.RSquaredDisplayText(rSquared), lines[1]);
        }
Exemple #6
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "|*.ccu";
            CalibrationCurve ca = new CalibrationCurve();

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                IFormatter formater   = new BinaryFormatter();
                FileStream filestream = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read);
                ca = formater.Deserialize(filestream) as CalibrationCurve;
                dataGridView1.Rows.Clear();
                for (int i = 0; i < ca.abs.Length; i++)
                {
                    dataGridView1.Rows.Add(ca.cor[i], ca.abs[i]);
                }
                filestream.Close();
            }
        }
Exemple #7
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);
            }
        }
Exemple #8
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);
            }
        }
Exemple #9
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);
            }
        }
Exemple #10
0
        private void button4_Click(object sender, EventArgs e)
        {
            Excel.Application xlApp;
            Excel.Workbook    xlWorkBook;
            Excel.Worksheet   xlWorkSheet_Parameters;
            Excel.Worksheet   xlWorkSheet_Signals;
            Excel.Worksheet   xlWorkSheet_Defines;
            Excel.Worksheet   xlWorkSheet_States;
            string            Line;
            int  LineNum;
            int  RetVal = 0;
            int  index;
            bool ScalingExists = false;
            bool GroupExists   = false;

            XLSECTParameter       XLSECTParameter1       = new XLSECTParameter();
            XLSECTSignal          XLSECTSignal1          = new XLSECTSignal();
            SignalValue           SignalValue1           = new SignalValue();
            CalibrationValue      CalibrationValue1      = new CalibrationValue();
            CalibrationSharedAxis CalibrationSharedAxis1 = new CalibrationSharedAxis();
            CalibrationCurve      CalibrationCurve1      = new CalibrationCurve();
            CalibrationMap        CalibrationMap1        = new CalibrationMap();

            System.IO.StreamWriter fileXML;
            /* Scaling IDs */
            CalibrationScaling CScalingNew = new CalibrationScaling();
            //            CalibrationScaling CS;
            Group GroupNew = new Group();


            GroupList    = new List <Group>();
            CScalingList = new List <CalibrationScaling>();

            object misValue = System.Reflection.Missing.Value;

            xlApp                  = new Excel.Application();
            xlWorkBook             = xlApp.Workbooks.Open(filePath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            xlWorkSheet_Parameters = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            xlWorkSheet_Signals    = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(2);
            xlWorkSheet_Defines    = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(3);
            xlWorkSheet_States     = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(4);

            if (File.Exists(BasefilePath))
            {
                // Copy the XML base file as a header for the new file

                CopyBaseFileToTarget();

                fileXML = new System.IO.StreamWriter(XMLfilePath, true);

                // Generate the signals and write them in the new XML file
                Line    = "2";
                LineNum = 2;
                while (-2 != RetVal)
                {
                    // Elaborate the signals sheet
                    RetVal = XLSECTSignal1.upload(ref xlWorkSheet_Signals, Line);

                    // Build the Scaling IDs list

                    CScalingNew.upload(ref XLSECTSignal1);
                    ScalingExists = false;

                    foreach (CalibrationScaling CS in CScalingList)
                    {
                        if (CS.ID == CScalingNew.ID)
                        {
                            ScalingExists = true;
                        }
                    }

                    if (ScalingExists == false)
                    {
                        CScalingList.Add(CScalingNew);
                        CScalingNew = new CalibrationScaling();
                    }

                    // Build the Group IDs list
                    GroupNew.upload(ref XLSECTSignal1);
                    GroupExists = false;

                    foreach (Group GP in GroupList)
                    {
                        if (GP.ID == GroupNew.ID)
                        {
                            GroupExists = true;
                        }
                    }

                    if (GroupExists == false)
                    {
                        GroupList.Add(GroupNew);
                        GroupNew = new Group();
                    }

                    // If it is a Signal (Channel in ECT XML nomenclature)
                    if ((RetVal == 0) || (RetVal == 123456789))
                    {
                        SignalValue1.upload(ref XLSECTSignal1, false, 0, ref Containr);
                        SignalValue1.AppendToFile(ref fileXML);
                        //                        SignalValue1.Show();
                    }
                    else
                    {
                        if (RetVal > 1)
                        {
                            if (RetVal > 123456789)
                            {
                                RetVal -= 123456789;
                            }
                            for (index = 0; index < RetVal; index++)
                            {
                                SignalValue1.upload(ref XLSECTSignal1, true, index, ref Containr);
                                SignalValue1.AppendToFile(ref fileXML);
                            }
                        }
                    }
                    LineNum++;
                    Line = Convert.ToString(LineNum);
                }

                // Generate the calibrations and write them in the new XML file
                Line    = "2";
                LineNum = 2;
                RetVal  = 0;
                while (-2 != RetVal)
                {
                    // Elaborate the parameters sheet
                    RetVal = XLSECTParameter1.upload(ref xlWorkSheet_Parameters, Line);

                    CScalingNew.upload(ref XLSECTParameter1);
                    ScalingExists = false;

                    foreach (CalibrationScaling CS in CScalingList)
                    {
                        if (CS.ID == CScalingNew.ID)
                        {
                            ScalingExists = true;
                        }
                    }

                    if (ScalingExists == false)
                    {
                        CScalingList.Add(CScalingNew);
                        CScalingNew = new CalibrationScaling();
                    }

                    // Build the Group IDs list
                    GroupNew.upload(ref XLSECTParameter1);
                    GroupExists = false;

                    foreach (Group GP in GroupList)
                    {
                        if (GP.ID == GroupNew.ID)
                        {
                            GroupExists = true;
                        }
                    }

                    if (GroupExists == false)
                    {
                        GroupList.Add(GroupNew);
                        GroupNew = new Group();
                    }

                    // If it is a CalibrationValue
                    if (RetVal == 0)
                    {
                        CalibrationValue1.upload(ref XLSECTParameter1, ref Containr);
                        CalibrationValue1.AppendToFile(ref fileXML);
                        //                        CalibrationValue1.Show();
                    }

                    // If it is a CalibrationSharedAxis
                    if (RetVal == 1)
                    {
                        CalibrationSharedAxis1.upload(ref XLSECTParameter1, ref Containr);
                        CalibrationSharedAxis1.AppendToFile(ref fileXML);
                        //                        CalibrationSharedAxis1.Show();
                    }

                    // If it is a CalibrationCurve
                    if (RetVal == 2)
                    {
                        CalibrationCurve1.upload(ref XLSECTParameter1, ref Containr);
                        CalibrationCurve1.AppendToFile(ref fileXML);
                        //                        CalibrationCurve1.Show();
                    }

                    // If it is a CalibrationMap
                    if (RetVal == 3)
                    {
                        CalibrationMap1.upload(ref XLSECTParameter1, ref Containr);
                        CalibrationMap1.AppendToFile(ref fileXML);
                        //                        CalibrationMap1.Show();
                    }

                    LineNum++;
                    Line = Convert.ToString(LineNum);
                }
                foreach (Group GP in GroupList)
                {
                    GP.AppendToFile(ref fileXML);
                }

                foreach (CalibrationScaling CS in CScalingList)
                {
                    CS.AppendToFile(ref fileXML);
                }

                fileXML.WriteLine("</LIE00V12PARTIAL>");
                fileXML.Close();
            }
            else
            {
                MessageBox.Show(" Base File doesn't exist");
            }


            /*
             *
             *          MessageBox.Show(
             *              xlWorkSheet_Parameters.get_Range("A2", "A2").Value2.ToString() + "\r\n" +
             *              xlWorkSheet_Parameters.get_Range("A3", "A3").Value2.ToString() + "\r\n" +
             *              xlWorkSheet_Parameters.get_Range("A4", "A4").Value2.ToString() + "\r\n" +
             *              xlWorkSheet_Parameters.get_Range("A5", "A5").Value2.ToString() + "\r\n" +
             *              xlWorkSheet_Parameters.get_Range("A6", "A6").Value2.ToString() + "\r\n"
             *                         );
             */
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet_Parameters);
            releaseObject(xlWorkSheet_Signals);
            releaseObject(xlWorkSheet_Defines);
            releaseObject(xlWorkSheet_States);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
            MessageBox.Show("Finished!");
        }
        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));
        }