private void SetupSeries() { ChartXy chartXy = (ChartXy)chartControl1.ChartPanel.ChartContainers[0]; _ChartXy = chartXy; SetupChartStyle(chartXy); SetupContainerStyle(chartXy); SetupChartAxes(chartXy); SetupChartLegend(chartXy); chartXy.ChartSeries.Clear(); foreach (var item in Exchanges) { ChartSeries series = new ChartSeries(item.Key, SeriesType.Line); RegressionLine rl = new RegressionLine("RegLine"); rl.ShowInLegend = false; rl.Visible = false; series.ChartIndicators.Add(rl); chartXy.ChartSeries.Add(series); _TimeSeries.Add(item.Key, series); item.Value.DepthEvent += Value_DepthEvent; //+= Value_TickerEvent; } }
public void OkDialog() { double minIrt; double maxIrt; var helper = new MessageBoxHelper(this); if (!helper.ValidateDecimalTextBox(textMinIrt, null, null, out minIrt)) { return; } if (!helper.ValidateDecimalTextBox(textMaxIrt, minIrt, null, out maxIrt)) { return; } var peptide1 = (DbIrtPeptide)comboFixedPoint1.SelectedItem; var peptide2 = (DbIrtPeptide)comboFixedPoint2.SelectedItem; double minCurrent = Math.Min(peptide1.Irt, peptide2.Irt); double maxCurrent = Math.Max(peptide1.Irt, peptide2.Irt); var statX = new Statistics(minCurrent, maxCurrent); var statY = new Statistics(minIrt, maxIrt); LinearEquation = new RegressionLine(statY.Slope(statX), statY.Intercept(statX)); // Convert all of the peptides to the new scale. foreach (var peptide in _irtPeptides) { peptide.Irt = LinearEquation.GetY(peptide.Irt); } DialogResult = DialogResult.OK; }
private void Form1_Load(object sender, EventArgs e) { // Create an empty chart. ChartControl barChart = new ChartControl(); // Create a series and add points to it. Series series1 = new Series("Bar Series", ViewType.Bar); series1.Points.Add(new SeriesPoint("A", new double[] { 10 })); series1.Points.Add(new SeriesPoint("B", new double[] { 12 })); series1.Points.Add(new SeriesPoint("C", new double[] { 14 })); series1.Points.Add(new SeriesPoint("D", new double[] { 17 })); // Create an indicator (e.g. Regression Line), // and add it to the series' collection. RegressionLine myLine = new RegressionLine(ValueLevel.Value); ((SideBySideBarSeriesView)series1.View).Indicators.Add(myLine); // Add the series to the chart. barChart.Series.Add(series1); // Define the chart's appearance and palette. barChart.AppearanceName = "Dark"; barChart.PaletteName = "Opulent"; barChart.PaletteBaseColorNumber = 5; // Define a separate palette for the chart's indicators. barChart.IndicatorsPaletteName = "Default"; // Add the chart to the form. barChart.Dock = DockStyle.Fill; this.Controls.Add(barChart); }
public bool CalcRegressionWith(IRetentionTimeProvider retentionTimes, IEnumerable <DbIrtPeptide> standardPeptideList, DbIrtPeptide[] items) { if (items.Any()) { // Attempt to get a regression based on shared peptides var calculator = new CurrentCalculator(standardPeptideList, items); var peptidesTimes = retentionTimes.PeptideRetentionTimes.ToArray(); var regression = RetentionTimeRegression.FindThreshold(RCalcIrt.MIN_IRT_TO_TIME_CORRELATION, RetentionTimeRegression.ThresholdPrecision, peptidesTimes, new MeasuredRetentionTime[0], peptidesTimes, null, calculator, RegressionMethodRT.linear, () => false); var startingCount = peptidesTimes.Length; var regressionCount = regression != null ? regression.PeptideTimes.Count : 0; if (regression != null && RCalcIrt.IsAcceptableStandardCount(startingCount, regressionCount)) { // Finally must recalculate the regression, because it is transposed from what // we want. var statTimes = new Statistics(regression.PeptideTimes.Select(pt => pt.RetentionTime)); var statIrts = new Statistics(regression.PeptideTimes.Select(pt => calculator.ScoreSequence(pt.PeptideSequence) ?? calculator.UnknownScore)); RegressionRefined = new RegressionLine(statIrts.Slope(statTimes), statIrts.Intercept(statTimes)); RegressionSuccess = true; return(true); } } return(false); }
public ChooseIrtStandardPeptidesDlg(SrmDocument document, string documentFilePath, ICollection <DbIrtPeptide> dbIrtPeptides, IEnumerable <PeptideGroupDocNode> peptideGroups) { InitializeComponent(); Document = document; Regression = null; _documentFilePath = documentFilePath; _dbIrtPeptides = dbIrtPeptides; _librarySpectra = new List <SpectrumMzInfo>(); _irtAdd = new List <MeasuredRetentionTime>(); _irtTargets = null; comboExisting.Items.AddRange(IrtStandard.ALL.Where(standard => !standard.Name.Equals(IrtStandard.EMPTY.Name) && !standard.Name.Equals(IrtStandard.AUTO.Name)) .Cast <object>().ToArray()); comboExisting.SelectedIndex = 0; PeptideGroupDocNode[] proteinsContainingCommonIrts, proteinsNotContainingCommonIrts; CreateIrtCalculatorDlg.SeparateProteinGroups(peptideGroups, out proteinsContainingCommonIrts, out proteinsNotContainingCommonIrts); foreach (var protein in proteinsContainingCommonIrts.Concat(proteinsNotContainingCommonIrts)) { comboProteins.Items.Add(new PeptideGroupItem(protein)); } if (proteinsContainingCommonIrts.Any()) { comboProteins.SelectedIndex = 0; } UpdateSelection(this, null); }
public void OkDialog() { double minIrt; double maxIrt; var helper = new MessageBoxHelper(this); if (!helper.ValidateDecimalTextBox(textMinIrt, null, null, out minIrt)) { return; } if (!helper.ValidateDecimalTextBox(textMaxIrt, minIrt, null, out maxIrt)) { return; } int iFixed1 = -1, iFixed2 = -1; for (int i = 0; i < StandardPeptideList.Count; i++) { if (!StandardPeptideList[i].FixedPoint) { continue; } if (iFixed1 == -1) { iFixed1 = i; } else { iFixed2 = i; } } if (iFixed1 == -1 || iFixed2 == -1) { MessageDlg.Show(this, Resources.CalibrateIrtDlg_OkDialog_The_standard_must_have_two_fixed_points); return; } double fixedPt1 = StandardPeptideList[iFixed1].RetentionTime; double fixedPt2 = StandardPeptideList[iFixed2].RetentionTime; double minRt = Math.Min(fixedPt1, fixedPt2); double maxRt = Math.Max(fixedPt1, fixedPt2); var statRt = new Statistics(minRt, maxRt); var statIrt = new Statistics(minIrt, maxIrt); var linearEquation = new RegressionLine(statIrt.Slope(statRt), statIrt.Intercept(statRt)); CalibrationPeptides = new List <DbIrtPeptide>(); foreach (var peptide in StandardPeptideList) { double iRT = linearEquation.GetY(peptide.RetentionTime); CalibrationPeptides.Add(new DbIrtPeptide(peptide.Sequence, iRT, true, TimeSource.peak)); } DialogResult = DialogResult.OK; }
public LoessRegression(bool irtIndependent = false) { _linearFit = new RegressionLine(); _xMin = double.MinValue; _loess = null; _token = null; XValues = new double[0]; YValues = new double[0]; IrtIndependent = irtIndependent; }
public RegressionOption(string name, RegressionLine regressionLine, List <Tuple <DbIrtPeptide, PeptideDocNode> > matchedRegressionPeptides, List <StandardPeptide> standardPeptides, bool allowEditEquation, bool allowEditGrid) { Name = name; RegressionLine = regressionLine; MatchedRegressionPeptides = matchedRegressionPeptides; StandardPeptides = standardPeptides; AllowEditGrid = allowEditGrid; }
public LoessRegression(double[] x, double[] y, bool irtIndependent = false, CustomCancellationToken token = null) { _linearFit = new RegressionLine(x, y); _xMin = x.Min(); _xMax = x.Max(); _loess = new LoessAligner(0.4); _token = token; _loess.Train(x, y, _token ?? CustomCancellationToken.NONE); XValues = x; YValues = y; }
public bool TryGetCirtRegression(int count, out RegressionLine regression, out IEnumerable <Tuple <DbIrtPeptide, PeptideDocNode> > matchedPeptides) { matchedPeptides = null; var success = TryGetCirtRegression(count, out regression, out List <ScoredPeptide> peptides); if (success) { matchedPeptides = peptides.Select(pep => Tuple.Create( new DbIrtPeptide(pep.Peptide.Target, _cirtAll[pep.Peptide.Target], true, TimeSource.peak), pep.NodePep)); } return(success); }
public static bool TryGetRegressionLine(IList <double> listIndependent, IList <double> listDependent, int minPoints, out RegressionLine line, IList <Tuple <double, double> > removedValues = null) { line = null; if (removedValues != null) { removedValues.Clear(); } if (listIndependent.Count != listDependent.Count || listIndependent.Count < minPoints) { return(false); } var listX = new List <double>(listIndependent); var listY = new List <double>(listDependent); double correlation; while (true) { var statIndependent = new Statistics(listX); var statDependent = new Statistics(listY); line = new RegressionLine(statDependent.Slope(statIndependent), statDependent.Intercept(statIndependent)); correlation = statDependent.R(statIndependent); if (correlation >= MIN_IRT_TO_TIME_CORRELATION || listX.Count <= minPoints) { break; } var furthest = 0; var maxDistance = 0.0; for (var i = 0; i < listY.Count; i++) { var distance = Math.Abs(line.GetY(listX[i]) - listY[i]); if (distance > maxDistance) { furthest = i; maxDistance = distance; } } if (removedValues != null) { removedValues.Add(new Tuple <double, double>(listX[furthest], listY[furthest])); } listX.RemoveAt(furthest); listY.RemoveAt(furthest); } return(correlation >= MIN_IRT_TO_TIME_CORRELATION); }
public void GetCurvePoints(bool refined, int numPoints, out double[] x, out double[] y) { if (numPoints < 2) { throw new ArgumentOutOfRangeException(); } var min = double.MaxValue; var max = double.MinValue; foreach (var point in RegularPoints) { if (point.X < min) { min = point.X; } if (point.X > max) { max = point.X; } } if (!refined) { foreach (var point in OutlierPoints) { if (point.X < min) { min = point.X; } if (point.X > max) { max = point.X; } } } x = new double[numPoints]; x[0] = min; var interval = (max - min) / (numPoints - 1); for (var i = 1; i < numPoints - 1; i++) { x[i] = min + i * interval; } x[x.Length - 1] = max; y = refined ? x.Select(xValue => RegressionLine.GetY(xValue)).ToArray() : x.Select(xValue => RegressionLineCurrent.GetY(xValue)).ToArray(); }
private void Form1_Load(object sender, EventArgs e) { // Create a regression line for the Open value level. RegressionLine myLine = new RegressionLine(ValueLevel.Open); // Access the series collection of indicators, // and add the regression line to it. ((StockSeriesView)chartControl1.Series[0].View).Indicators.Add(myLine); // Customize the regression line's appearance. myLine.LineStyle.DashStyle = DashStyle.DashDot; myLine.LineStyle.Thickness = 2; myLine.Color = Color.Crimson; }
private bool ProcessStandard() { var standard = (IrtStandard)comboExisting.SelectedItem; if (ReferenceEquals(standard, IrtStandard.CIRT_SHORT)) { var knownIrts = new TargetMap <double>(IrtStandard.CIRT.Peptides.Select(pep => new KeyValuePair <Target, double>(pep.ModifiedTarget, pep.Irt))); var matchingPeptides = _dbIrtPeptides.Where(pep => knownIrts.ContainsKey(pep.ModifiedTarget)).ToArray(); var regression = GetRegression(knownIrts, matchingPeptides, RCalcIrt.MIN_PEPTIDES_COUNT, out var graphData); if (regression != null) { var numCirts = graphData.XValues.Length; int cirtCount; using (var dlg = new AddIrtStandardsDlg(numCirts, string.Format(Resources.LibraryBuildNotificationHandler_AddIrts__0__distinct_CiRT_peptides_were_found__How_many_would_you_like_to_use_as_iRT_standards_, numCirts), graphData)) { if (dlg.ShowDialog(this) != DialogResult.OK) { return(false); } cirtCount = dlg.StandardCount; } Regression = regression; var outlierTargets = graphData.OutlierIndices.Select(idx => new Target(graphData.Tooltips[idx])).ToArray(); SetStandards(IrtPeptidePicker.Pick(cirtCount, matchingPeptides, outlierTargets)); return(true); } } var irts = new TargetMap <double>(standard.Peptides.Select(pep => new KeyValuePair <Target, double>(pep.ModifiedTarget, pep.Irt))); var peptides = _dbIrtPeptides.Where(pep => irts.ContainsKey(pep.ModifiedTarget)).ToArray(); Regression = GetRegression(irts, peptides, null, out _); if (Regression != null) { SetStandards(standard.Peptides.Select(pep => pep.ModifiedTarget)); } else if (standard.HasDocument) { var missing = new TargetMap <bool>(standard.MissingFromDocument(Document).Select(target => new KeyValuePair <Target, bool>(target, true))); _irtAdd.AddRange(standard.Peptides.Where(pep => missing.ContainsKey(pep.ModifiedTarget)) .Select(pep => new MeasuredRetentionTime(pep.ModifiedTarget, pep.Irt, true, true))); Document = standard.ImportTo(Document); } return(true); }
public override void Train(double[] xArr, double[] yArr, CustomCancellationToken token) { var statX = new Statistics(xArr); var statY = new Statistics(yArr); _regressionLine = new RegressionLine(statX.Slope(statY), statX.Intercept(statY)); _reverseRegressionLine = new RegressionLine(statY.Slope(statX), statY.Intercept(statX)); _rmsd = 0; for (int i = 0; i < xArr.Length; i++) { var pred = GetValue(xArr[i]); var diff = pred - yArr[i]; _rmsd += diff * diff / xArr.Length; } _rmsd = Math.Sqrt(_rmsd); }
public void UseCurrentData() { CERegressionData[] arrayData = GetRegressionDatas(); if (arrayData == null) { return; } bool hasRegressionLines = false; var regressionLines = new RegressionLine[arrayData.Length]; for (int i = 0; i < arrayData.Length; i++) { if (arrayData[i] == null) { continue; } regressionLines[i] = arrayData[i].RegressionLine; if (regressionLines[i] != null) { hasRegressionLines = true; } } if (!hasRegressionLines) { MessageDlg.Show(this, Resources.EditCEDlg_UseCurrentData_Insufficient_data_found_to_calculate_a_new_regression); return; } gridRegression.Rows.Clear(); for (int i = 0; i < regressionLines.Length; i++) { var regressionLine = regressionLines[i]; if (regressionLine == null) { continue; } gridRegression.Rows.Add(new object[] { i.ToString(LocalizationHelper.CurrentCulture), string.Format("{0:F04}", regressionLine.Slope), // Not L10N string.Format("{0:F04}", regressionLine.Intercept) // Not L10N }); } }
static RegressionLine GetRegressionLine(Series series) { if (series != null) { SwiftPlotSeriesView swiftPlotView = series.View as SwiftPlotSeriesView; if (swiftPlotView != null) { foreach (Indicator indicator in swiftPlotView.Indicators) { RegressionLine regressionLine = indicator as RegressionLine; if (regressionLine != null) { return(regressionLine); } } } } return(null); }
private bool TryGetCirtRegression(int count, out RegressionLine regression, out List <ScoredPeptide> peptides) { peptides = new List <ScoredPeptide>(_cirtPeptides); var rts = _cirtPeptides.Select(pep => pep.Peptide.RetentionTime).ToList(); var irts = _cirtPeptides.Select(pep => _cirtAll[pep.Peptide.Target]).ToList(); var removedValues = new List <Tuple <double, double> >(); if (!RCalcIrt.TryGetRegressionLine(rts, irts, count, out regression, removedValues)) { return(false); } for (var i = peptides.Count - 1; i >= 0; i--) { if (removedValues.Contains(Tuple.Create(rts[i], irts[i]))) { peptides.RemoveAt(i); } } return(peptides.Count >= count); }
public static bool TryGetRegressionLine(IList <double> listIndependent, IList <double> listDependent, int minPoints, out RegressionLine line) { line = null; if (listIndependent.Count != listDependent.Count || listIndependent.Count < minPoints) { return(false); } double correlation; while (true) { var statIndependent = new Statistics(listIndependent); var statDependent = new Statistics(listDependent); line = new RegressionLine(statDependent.Slope(statIndependent), statDependent.Intercept(statIndependent)); correlation = statDependent.R(statIndependent); if (correlation >= MIN_IRT_TO_TIME_CORRELATION || listIndependent.Count <= minPoints) { break; } var furthest = 0; var maxDistance = 0.0; for (var i = 0; i < listDependent.Count; i++) { var distance = Math.Abs(line.GetY(listIndependent[i]) - listDependent[i]); if (distance > maxDistance) { furthest = i; maxDistance = distance; } } listIndependent.RemoveAt(furthest); listDependent.RemoveAt(furthest); } return(correlation >= MIN_IRT_TO_TIME_CORRELATION); }
public bool TryGetRegressionFunction(ChromFileInfoId chromFileInfoId, out RegressionLine regressionFunction) { if (ReferenceEquals(chromFileInfoId, ChromFileInfo.Id)) { regressionFunction = null; return(true); } Tuple <ChromatogramSet, ChromFileInfo> chromSetInfo; if (_chromSetInfos.TryGetValue(chromFileInfoId, out chromSetInfo)) { var retentionTimeAlignment = FileRetentionTimeAlignments.RetentionTimeAlignments.Find(chromSetInfo.Item2); if (null != retentionTimeAlignment) { regressionFunction = retentionTimeAlignment.RegressionLine; return(true); } } regressionFunction = null; return(false); }
public RetentionTimeProviderData(IRetentionTimeProvider retentionTimes, IEnumerable <DbIrtPeptide> standardPeptides) { RetentionTimeProvider = retentionTimes; Peptides = standardPeptides.Select(standardPeptide => new Peptide(standardPeptide.ModifiedTarget, retentionTimes.GetRetentionTime(standardPeptide.ModifiedTarget), standardPeptide.Irt)).ToList(); Peptides.Sort((x, y) => x.Irt.CompareTo(y.Irt)); if (!FilteredPeptides.Any()) { Regression = null; RegressionRefined = null; RegressionSuccess = false; } var filteredRt = FilteredPeptides.Select(pep => pep.RetentionTime.Value).ToList(); var filteredIrt = FilteredPeptides.Select(pep => pep.Irt).ToList(); var statTimes = new Statistics(filteredRt); var statIrts = new Statistics(filteredIrt); Regression = new RegressionLine(statIrts.Slope(statTimes), statIrts.Intercept(statTimes)); var removed = new List <Tuple <double, double> >(); RegressionSuccess = RCalcIrt.TryGetRegressionLine(filteredRt, filteredIrt, MinPoints, out _regressionRefined, removed); foreach (var remove in removed) { for (var i = 0; i < Peptides.Count; i++) { var peptide = Peptides[i]; if (peptide.RetentionTime.Equals(remove.Item1) && peptide.Irt.Equals(remove.Item2)) { Peptides[i] = new Peptide(peptide, true); } } } }
public static bool TryGetRegressionLine(IList<double> listIndependent, IList<double> listDependent, out RegressionLine line) { var minPoints = (int) Math.Round(Math.Max(MIN_PEPTIDES_COUNT, listIndependent.Count*MIN_PEPTIDES_PERCENT)); return TryGetRegressionLine(listIndependent, listDependent, minPoints, out line); }
protected void Button1_Click(object sender, EventArgs e) { string connStr = "Server=127.0.0.1;Database=edit;Trusted_Connection=True;"; string col1 = ""; string col2 = ""; List<double> col1Values = new List<double>(); List<double> col2Values = new List<double>(); WebChartControl1.Titles.Clear(); WebChartControl1.Series.Clear(); if (DropDownList1.SelectedValue.Equals(DropDownList2.SelectedValue)) { Literal1.Text = "The same columns cannot be compared because the correlation is always 100%"; return; } using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); // lookup friendlytext, get the real DB column name... using (SqlCommand cmd = new SqlCommand(String.Format("SELECT [DBColumn] FROM [edit].[dbo].[datawarehouseColumnMapping] WHERE FriendlyText = '{0}' OR FriendlyText = '{1}'",DropDownList1.SelectedValue, DropDownList2.SelectedValue),conn)) { using (SqlDataReader r = cmd.ExecuteReader()) { try { r.Read(); // move to first row col1 = r.GetString(0); r.Read(); col2 = r.GetString(0); } catch (Exception ex) { } } } using (SqlCommand cmd = new SqlCommand(String.Format("SELECT [{0}],[{1}] FROM [edit].[dbo].[datawarehouse]", col1, col2), conn)) { using (SqlDataReader r = cmd.ExecuteReader()) { DataTable dt = new DataTable(); dt.Load(r); if (dt.Columns[0].DataType != typeof(System.Double) || dt.Columns[1].DataType != typeof(System.Double)) { Literal1.Text = "These two columns cannot be compared!"; return; } double a = 0; double b = 0; for (int i = 0; i < dt.Rows.Count; i++) { if (dt.Rows[i].ItemArray.GetValue(0) != DBNull.Value && dt.Rows[i].ItemArray.GetValue(1) != DBNull.Value) { a = (double)dt.Rows[i].ItemArray.GetValue(0); b = (double)dt.Rows[i].ItemArray.GetValue(1); col1Values.Add(a); col2Values.Add(b); } } } } } double correlation = Math.Round(Correlation.Pearson(col1Values, col2Values), 5, MidpointRounding.ToEven); double percentageCorrelation = Math.Round(correlation * 100, 0); Literal1.Text = String.Format("The correlation is: {0}% ({1})<br/><p><strong>Please understand that high correlations do not necessarily imply causation -- only association!</strong></p><br/>", percentageCorrelation, correlation); SeriesPoint[] sp = new SeriesPoint[col1Values.Count]; Series s = new Series("Comparison", ViewType.Point); for (int i = 0; i < col1Values.Count; i++) { sp[i] = new SeriesPoint(col1Values[i], col2Values[i]); s.Points.Add(sp[i]); } RegressionLine rl = new RegressionLine("regression line"); rl.LineStyle.DashStyle = DashStyle.Dot; rl.LineStyle.Thickness = 2; rl.Color = System.Drawing.Color.Aqua; s.ArgumentScaleType = ScaleType.Numerical; s.ValueScaleType = ScaleType.Numerical; ChartTitle ct = new ChartTitle(); ct.Text = DropDownList1.SelectedValue + " compared to " + DropDownList2.SelectedValue; WebChartControl1.Titles.Add(ct); WebChartControl1.Series.Add(s); ((PointSeriesView)WebChartControl1.Series[0].View).Indicators.Clear(); ((PointSeriesView)WebChartControl1.Series[0].View).Indicators.Add(rl); ((XYDiagramSeriesViewBase)WebChartControl1.Series[0].View).AxisX.Title.Visible = true; ((XYDiagramSeriesViewBase)WebChartControl1.Series[0].View).AxisX.Title.Alignment = System.Drawing.StringAlignment.Center; ((XYDiagramSeriesViewBase)WebChartControl1.Series[0].View).AxisX.Title.Text = DropDownList1.SelectedValue; ((XYDiagramSeriesViewBase)WebChartControl1.Series[0].View).AxisX.Title.TextColor = System.Drawing.Color.Red; ((XYDiagramSeriesViewBase)WebChartControl1.Series[0].View).AxisX.Title.Antialiasing = true; ((XYDiagramSeriesViewBase)WebChartControl1.Series[0].View).AxisY.Title.Visible = true; ((XYDiagramSeriesViewBase)WebChartControl1.Series[0].View).AxisY.Title.Alignment = System.Drawing.StringAlignment.Center; ((XYDiagramSeriesViewBase)WebChartControl1.Series[0].View).AxisY.Title.Text = DropDownList2.SelectedValue; ((XYDiagramSeriesViewBase)WebChartControl1.Series[0].View).AxisY.Title.TextColor = System.Drawing.Color.Red; ((XYDiagramSeriesViewBase)WebChartControl1.Series[0].View).AxisY.Title.Antialiasing = true; }
public override void ReadXml(XmlReader reader) { base.ReadXml(reader); RegressionLine = RegressionLine.Deserialize(reader); reader.Read(); }
public DPRegressionData(RegressionLine regressionLineSetting) : base(regressionLineSetting) { }
private PointPair CalculatePointPair <TChromInfoData>(int iResult, IEnumerable <TChromInfoData> chromInfoDatas, Func <TChromInfoData, RetentionTimeValues> getRetentionTimeValues) where TChromInfoData : ChromInfoData { var startTimes = new List <double>(); var endTimes = new List <double>(); var retentionTimes = new List <double>(); var fwhms = new List <double>(); foreach (var chromInfoData in chromInfoDatas) { var retentionTimeValues = getRetentionTimeValues(chromInfoData); RegressionLine regressionFunction = null; if (null != RetentionTimeTransform.RtTransformOp) { RetentionTimeTransform.RtTransformOp.TryGetRegressionFunction(chromInfoData.ChromFileInfo.FileId, out regressionFunction); } if (regressionFunction == null) { startTimes.Add(retentionTimeValues.StartRetentionTime); endTimes.Add(retentionTimeValues.EndRetentionTime); retentionTimes.Add(retentionTimeValues.RetentionTime); fwhms.Add(retentionTimeValues.Fwhm ?? 0); } else { startTimes.Add(regressionFunction.GetY(retentionTimeValues.StartRetentionTime)); endTimes.Add(regressionFunction.GetY(retentionTimeValues.EndRetentionTime)); retentionTimes.Add(regressionFunction.GetY(retentionTimeValues.RetentionTime)); if (retentionTimeValues.Fwhm.HasValue) { fwhms.Add(regressionFunction.GetY(retentionTimeValues.RetentionTime + retentionTimeValues.Fwhm.Value / 2) - regressionFunction.GetY(retentionTimeValues.RetentionTime - retentionTimeValues.Fwhm.Value / 2)); } else { fwhms.Add(0); } } } if (RTPeptideValue.All == RTPeptideGraphPane.RTValue) { var point = HiLowMiddleErrorBarItem.MakePointPair(iResult, new Statistics(endTimes).Mean(), new Statistics(startTimes).Mean(), new Statistics(retentionTimes).Mean(), new Statistics(fwhms).Mean()); return(point.IsInvalid ? PointPairMissing(iResult) : point); } IEnumerable <double> values; switch (RTPeptideGraphPane.RTValue) { case RTPeptideValue.FWB: values = startTimes.Select((startTime, index) => endTimes[index] - startTime); break; case RTPeptideValue.FWHM: values = fwhms; break; default: values = retentionTimes; break; } return(RetentionTimeTransform.AggregateOp.MakeBarValue(iResult, values)); }
public List <DbIrtPeptide> RecalibrateStandards(DbIrtPeptide[] standardPeptideList) { var peptideAllIrtTimes = new Dictionary <Target, List <Tuple <double, double> > >(); // peptide -> list of (irt, time) foreach (var data in ProviderData) { foreach (var peptide in data.FilteredPeptides) { if (!peptideAllIrtTimes.TryGetValue(peptide.Target, out var pepTimes)) { pepTimes = new List <Tuple <double, double> >(); peptideAllIrtTimes[peptide.Target] = pepTimes; } pepTimes.Add(Tuple.Create(peptide.Irt, peptide.RetentionTime.Value)); } } var peptideBestIrtTimes = new Dictionary <Target, Tuple <double, double> >(); // peptide -> (percentile irt, percentile time) foreach (var peptide in peptideAllIrtTimes) { var statIrts = new Statistics(peptide.Value.Select(p => p.Item1)); var statTimes = new Statistics(peptide.Value.Select(p => p.Item2)); var percentile = IrtStandard.GetSpectrumTimePercentile(peptide.Key); peptideBestIrtTimes[peptide.Key] = Tuple.Create(statIrts.Percentile(percentile), statTimes.Percentile(percentile)); } DbIrtPeptide min = null, max = null; foreach (var standard in standardPeptideList) // loop over list of standard peptides to find min/max that we have values for { if ((min == null || standard.Irt < min.Irt) && peptideBestIrtTimes.ContainsKey(standard.ModifiedTarget)) { min = standard; } if ((max == null || standard.Irt > max.Irt) && peptideBestIrtTimes.ContainsKey(standard.ModifiedTarget)) { max = standard; } } if (min == null || max == null) { throw new Exception(Resources.EditIrtCalcDlg_RecalibrateStandards_Could_not_get_a_minimum_or_maximum_standard_peptide_); } var statX = new Statistics(peptideBestIrtTimes[min.ModifiedTarget].Item2, peptideBestIrtTimes[max.ModifiedTarget].Item2); var statY = new Statistics(peptideBestIrtTimes[min.ModifiedTarget].Item1, peptideBestIrtTimes[max.ModifiedTarget].Item1); var line = new RegressionLine(statY.Slope(statX), statY.Intercept(statX)); var newStandardPeptideList = new List <DbIrtPeptide>(); foreach (var peptide in standardPeptideList) { if (!peptideBestIrtTimes.TryGetValue(peptide.ModifiedTarget, out var times)) { throw new Exception(Resources.ProcessedIrtAverages_RecalibrateStandards_A_standard_peptide_was_missing_when_trying_to_recalibrate_); } newStandardPeptideList.Add(new DbIrtPeptide(peptide) { Irt = line.GetY(times.Item2) }); } return(newStandardPeptideList); }
private bool TryGetLine(bool showErrors, out RegressionLine line) { if (SelectedRegressionOption.RegressionLine != null) { line = SelectedRegressionOption.RegressionLine; return(true); } line = null; var helper = new MessageBoxHelper(this, showErrors); if (!helper.ValidateDecimalTextBox(textMinIrt, null, null, out var minIrt)) { return(false); } if (!helper.ValidateDecimalTextBox(textMaxIrt, minIrt, null, out var maxIrt)) { return(false); } if (!IsRecalibration && StandardPeptideList.Count == 0) { if (showErrors) { MessageDlg.Show(this, Resources.CalibrateIrtDlg_TryGetLine_Standard_calibration_peptides_are_required_); } return(false); } var comboMinIdx = comboMinPeptide.SelectedIndex; var comboMaxIdx = comboMaxPeptide.SelectedIndex; if (comboMinIdx < 0 || comboMaxIdx < 0) { if (showErrors) { MessageDlg.Show(this, Resources.CalibrateIrtDlg_TryGetLine_Invalid_fixed_point_peptides_); } return(false); } double minRt, maxRt; if (!IsRecalibration) { minRt = StandardPeptidesSorted[comboMinIdx].RetentionTime; maxRt = StandardPeptidesSorted[comboMaxIdx].RetentionTime; } else { minRt = _standardPeptidesSorted[comboMinIdx].Irt; maxRt = _standardPeptidesSorted[comboMaxIdx].Irt; } if (minRt >= maxRt) { if (showErrors) { MessageDlg.Show(this, Resources.CalibrateIrtDlg_TryGetLine_Maximum_fixed_point_peptide_must_have_a_greater_measured_retention_time_than_the_minimum_fixed_point_peptide_); } return(false); } var statRt = new Statistics(minRt, maxRt); var statIrt = new Statistics(minIrt, maxIrt); line = new RegressionLine(statIrt.Slope(statRt), statIrt.Intercept(statRt)); return(true); }
public void OkDialog() { double minIrt; double maxIrt; var helper = new MessageBoxHelper(this); if (!helper.ValidateDecimalTextBox(textMinIrt, null, null, out minIrt)) return; if (!helper.ValidateDecimalTextBox(textMaxIrt, minIrt, null, out maxIrt)) return; var peptide1 = (DbIrtPeptide) comboFixedPoint1.SelectedItem; var peptide2 = (DbIrtPeptide) comboFixedPoint2.SelectedItem; double minCurrent = Math.Min(peptide1.Irt, peptide2.Irt); double maxCurrent = Math.Max(peptide1.Irt, peptide2.Irt); var statX = new Statistics(minCurrent, maxCurrent); var statY = new Statistics(minIrt, maxIrt); LinearEquation = new RegressionLine(statY.Slope(statX), statY.Intercept(statX)); // Convert all of the peptides to the new scale. foreach (var peptide in _irtPeptides) { peptide.Irt = LinearEquation.GetY(peptide.Irt); } DialogResult = DialogResult.OK; }
protected RegressionData(RegressionLine regressionLineSetting) { RegressionLineSetting = regressionLineSetting; }
private void ShowGraph(string title, double[] xValues, double[] yValues, Dictionary <int, string> tooltips, RegressionLine line, bool xIrt) { var data = new RegressionGraphData { Title = title, LabelX = !xIrt ? Resources.CalibrateIrtDlg_ShowGraph_Measured : Resources.CalibrateIrtDlg_ShowGraph_Old_iRT, LabelY = !xIrt ? Resources.CalibrateIrtDlg_ShowGraph_iRT : Resources.CalibrateIrtDlg_ShowGraph_New_iRT, XValues = xValues, YValues = yValues, Tooltips = tooltips, RegressionLine = line, }; using (var graph = new GraphRegression(new[] { data }) { Width = 800, Height = 600 }) { graph.ShowDialog(this); } }
public static bool TryGetRegressionLine(IList<double> listIndependent, IList<double> listDependent, int minPoints, out RegressionLine line) { line = null; if (listIndependent.Count != listDependent.Count || listIndependent.Count < minPoints) return false; double correlation; while (true) { var statIndependent = new Statistics(listIndependent); var statDependent = new Statistics(listDependent); line = new RegressionLine(statDependent.Slope(statIndependent), statDependent.Intercept(statIndependent)); correlation = statDependent.R(statIndependent); if (correlation >= MIN_IRT_TO_TIME_CORRELATION || listIndependent.Count <= minPoints) break; var furthest = 0; var maxDistance = 0.0; for (var i = 0; i < listDependent.Count; i++) { var distance = Math.Abs(line.GetY(listDependent[i]) - listIndependent[i]); if (distance > maxDistance) { furthest = i; maxDistance = distance; } } listIndependent.RemoveAt(furthest); listDependent.RemoveAt(furthest); } return correlation >= MIN_IRT_TO_TIME_CORRELATION; }
private List <MeasuredPeptide> PickPeptides(SrmDocument doc, int count, ICollection <Target> exclude, RegressionOption currentRegression, out RegressionOption cirt) { cirt = null; if (!_picker.HasScoredPeptides) { using (var longWaitDlg = new LongWaitDlg { Text = Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_Calculating_scores }) { longWaitDlg.PerformWork(_parent, 1000, pm => _picker.ScorePeptides(doc, pm)); if (longWaitDlg.IsCanceled) { return(null); } } } RegressionLine cirtRegression = null; var useCirt = false; var cirtUsePredefined = false; if (_picker.TryGetCirtRegression(count, out var tryCirtRegression, out var matchedPeptides)) { var currentIsCirt = currentRegression != null && currentRegression.IsCirtDiscovered; switch (MultiButtonMsgDlg.Show(_parent, string.Format( Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_This_document_contains__0__CiRT_peptides__Would_you_like_to_use__1__of_them_as_your_iRT_standards_, _picker.CirtPeptideCount, count), MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, true)) { case DialogResult.Yes: cirtRegression = tryCirtRegression; useCirt = true; if (currentRegression?.RegressionLine == null || currentIsCirt) { switch (MultiButtonMsgDlg.Show(_parent, Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_Would_you_like_to_use_the_predefined_iRT_values_, Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_Predefined_values, Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_Calculate_from_regression, true)) { case DialogResult.Yes: cirtUsePredefined = true; break; case DialogResult.No: break; case DialogResult.Cancel: return(null); } } break; case DialogResult.No: if (currentIsCirt) { cirtRegression = tryCirtRegression; } break; case DialogResult.Cancel: return(null); } } var bestPeptides = _picker.Pick(count, exclude, useCirt); if (cirtRegression != null) { var standardPeptides = bestPeptides.Select(pep => new StandardPeptide { Irt = cirtUsePredefined ? _picker.CirtIrt(pep.Target).Value : double.NaN, RetentionTime = pep.RetentionTime, Target = pep.Target }).ToList(); cirt = new RegressionOption(Resources.CalibrationGridViewDriver_CiRT_option_name, cirtRegression, matchedPeptides.ToList(), standardPeptides, false, false); } return(bestPeptides); }
public RetentionTimeProviderData(IRetentionTimeProvider retentionTimes, IEnumerable <DbIrtPeptide> standardPeptides) { RetentionTimeProvider = retentionTimes; // Attempt to get regression based on standards var listPeptides = new List <Target>(); var listTimes = new List <double>(); var listIrts = new List <double>(); foreach (var standardPeptide in standardPeptides) { listPeptides.Add(standardPeptide.ModifiedTarget); listTimes.Add(retentionTimes.GetRetentionTime(standardPeptide.ModifiedTarget) ?? double.MaxValue); listIrts.Add(standardPeptide.Irt); } var arrayTimes = listTimes.ToArray(); // var libraryTimes = retentionTimes as LibraryRetentionTimes; // if (libraryTimes != null) // Trace.WriteLine(libraryTimes.Name); // Trace.WriteLine(string.Format("times = {0}", string.Join(", ", arrayTimes.Select(t => string.Format("{0:F02}", t))))); Peptides = listPeptides.ToArray(); Times = arrayTimes; Irts = listIrts.ToArray(); MissingIndices = new HashSet <int>(); for (var i = 0; i < Times.Length; i++) { if (Times[i] == double.MaxValue) { MissingIndices.Add(i); } } TimesFiltered = Times.Where((v, i) => !MissingIndices.Contains(i)).ToArray(); IrtsFiltered = Irts.Where((v, i) => !MissingIndices.Contains(i)).ToArray(); OutlierIndices = new HashSet <int>(); if (TimesFiltered.Any()) { var statTimes = new Statistics(TimesFiltered); var statIrts = new Statistics(IrtsFiltered); Regression = new RegressionLine(statIrts.Slope(statTimes), statIrts.Intercept(statTimes)); var removed = new List <Tuple <double, double> >(); RegressionSuccess = RCalcIrt.TryGetRegressionLine(TimesFiltered.ToList(), IrtsFiltered.ToList(), MinPoints, out _regressionRefined, removed); foreach (var remove in removed) { for (var i = 0; i < Times.Length && i < Irts.Length; i++) { if (Times[i] == remove.Item1 && Irts[i] == remove.Item2) { OutlierIndices.Add(i); } } } } else { Regression = null; RegressionRefined = null; RegressionSuccess = false; } }