public TurnoverCalculator GetTurnoverCalculator() { var turnoverCalculator = _turnoverCalculator; if (turnoverCalculator != null) { return(turnoverCalculator); } _turnoverCalculator = turnoverCalculator = new TurnoverCalculator(Workspace, Peptide.Sequence); return(turnoverCalculator); }
public TurnoverCalculator GetTurnoverCalculator(string peptideSequence) { peptideSequence = Peptide.TrimSequence(peptideSequence); TurnoverCalculator turnoverCalculator; if (_turnoverCalculators.TryGetValue(peptideSequence, out turnoverCalculator)) { return(turnoverCalculator); } turnoverCalculator = new TurnoverCalculator(Workspace, peptideSequence); _turnoverCalculators.Add(peptideSequence, turnoverCalculator); return(turnoverCalculator); }
public void Init(Workspace workspace) { Chromatograms = new List <ChromatogramGenerator.Chromatogram>(); var turnoverCalculator = new TurnoverCalculator(workspace, Sequence); for (int charge = MinCharge; charge <= MaxCharge; charge++) { var mzs = turnoverCalculator.GetMzs(charge); for (int massIndex = 0; massIndex < mzs.Count; massIndex++) { Chromatograms.Add(new ChromatogramGenerator.Chromatogram(new MzKey(charge, massIndex), mzs[massIndex])); } } ScanIndexes = new List <int>(); Times = new List <double>(); }
public void Test58Percent() { var path = Path.Combine(TestContext.TestDir, Guid.NewGuid().ToString() + ".tpg"); var workspace = CreateWorkspace(path, TracerDef.GetD3LeuEnrichment()); var turnoverCalculator = new TurnoverCalculator(workspace, "LL"); var dict = new Dictionary<TracerFormula, double>(); // initialize the dictionary with 70% newly synthesized from 58% precursor pool dict.Add(TracerFormula.Parse("Tracer2"), Math.Pow(.58, 2) * .7); dict.Add(TracerFormula.Parse("Tracer1"), 2 * .58 * .42 * .7); dict.Add(TracerFormula.Empty, 1- dict.Values.Sum()); double turnover; double turnoverScore; IDictionary<TracerFormula, double> bestMatch; var precursorEnrichment = turnoverCalculator.ComputePrecursorEnrichmentAndTurnover(dict, out turnover, out turnoverScore, out bestMatch); Assert.AreEqual(.7, turnover); Assert.AreEqual(58, precursorEnrichment["Tracer"]); }
public void Test58Percent() { var path = Path.Combine(TestContext.TestDir, Guid.NewGuid().ToString() + ".tpg"); var workspace = CreateWorkspace(path, TracerDef.GetD3LeuEnrichment()); var turnoverCalculator = new TurnoverCalculator(workspace, "LL"); var dict = new Dictionary <TracerFormula, double>(); // initialize the dictionary with 70% newly synthesized from 58% precursor pool dict.Add(TracerFormula.Parse("Tracer2"), Math.Pow(.58, 2) * .7); dict.Add(TracerFormula.Parse("Tracer1"), 2 * .58 * .42 * .7); dict.Add(TracerFormula.Empty, 1 - dict.Values.Sum()); double turnover; double turnoverScore; IDictionary <TracerFormula, double> bestMatch; var precursorEnrichment = turnoverCalculator.ComputePrecursorEnrichmentAndTurnover(dict, out turnover, out turnoverScore, out bestMatch); Assert.AreEqual(.7, turnover); Assert.AreEqual(58, precursorEnrichment["Tracer"]); }
public void Redisplay() { if (!IsHandleCreated) { return; } if (_inRedisplay) { return; } try { _inRedisplay = true; tbxMinCharge.Text = MinCharge.ToString(); tbxMaxCharge.Text = MaxCharge.ToString(); tbxPeptideSequence.Text = PeptideSequence; cbxShowPeptideMzs.Enabled = !string.IsNullOrEmpty(PeptideSequence); tbxMassAccuracy.Text = MassAccuracy.ToString(); TurnoverCalculator turnoverCalculator = null; if (!string.IsNullOrEmpty(PeptideSequence)) { turnoverCalculator = new TurnoverCalculator(Workspace, PeptideSequence); } msGraphControlEx1.GraphPane.GraphObjList.Clear(); msGraphControlEx1.GraphPane.CurveList.Clear(); if (_spectrumData == null || comboChromatogram.SelectedIndex >= 0 && null == _chromatogramDatas[comboChromatogram.SelectedIndex]) { using (var msDataFileImpl = new MsDataFileImpl(Workspace.GetDataFilePath(MsDataFile.Name))) { if (comboChromatogram.SelectedIndex >= 0 && null == _chromatogramDatas[comboChromatogram.SelectedIndex]) { string chromatogramName; float[] timeArray; float[] intensityArray; msDataFileImpl.GetChromatogram(comboChromatogram.SelectedIndex, out chromatogramName, out timeArray, out intensityArray); _chromatogramDatas[comboChromatogram.SelectedIndex] = new ChromatogramData(chromatogramName, timeArray, intensityArray); } _spectrumData = _spectrumData ?? new SpectrumData(msDataFileImpl, ScanIndex); } } ChromatogramData chromatogram = null; if (comboChromatogram.SelectedIndex >= 0) { chromatogram = _chromatogramDatas[comboChromatogram.SelectedIndex]; } tbxMsLevel.Text = _spectrumData.MsLevel.ToString(); tbxTime.Text = _spectrumData.Time.ToString(); if (chromatogram != null && ScanIndex < chromatogram.TimeArray.Length) { tbxChromatogramRetentionTime.Text = chromatogram.TimeArray[ScanIndex].ToString(); tbxChromatogramIonCurrent.Text = chromatogram.IntensityArray[ScanIndex].ToString(NumberFormat); } else { tbxChromatogramRetentionTime.Text = tbxChromatogramIonCurrent.Text = @"N/A"; } if (cbxShowProfile.Checked && _spectrumData.ProfileMzs != null) { msGraphControlEx1.AddGraphItem(msGraphControlEx1.GraphPane, new SpectrumGraphItem() { Points = new PointPairList(_spectrumData.ProfileMzs, _spectrumData.ProfileIntensities), GraphItemDrawMethod = MSGraphItemDrawMethod.line, Color = Color.Blue, }); } if (_spectrumData.ProfileIntensities != null) { tbxSumOfProfileIntensities.Text = _spectrumData.ProfileIntensities.Sum().ToString(NumberFormat); } else { tbxSumOfProfileIntensities.Text = ""; } tbxCentroidIntensitySum.Text = _spectrumData.CentroidIntensities.Sum().ToString(NumberFormat); var spectrum = new SpectrumGraphItem { Points = new PointPairList(_spectrumData.CentroidMzs, _spectrumData.CentroidIntensities), GraphItemDrawMethod = MSGraphItemDrawMethod.stick, Color = Color.Black }; if (turnoverCalculator != null) { var mzRanges = new Dictionary <MzRange, String>(); double monoisotopicMass = Workspace.GetAminoAcidFormulas().GetMonoisotopicMass(PeptideSequence); double peptideIntensity = 0.0; for (int charge = MinCharge; charge <= MaxCharge; charge++) { foreach (var mzRange in turnoverCalculator.GetMzs(charge)) { double mass = (mzRange.Center - AminoAcidFormulas.ProtonMass) * charge; double massDifference = mass - monoisotopicMass; var label = massDifference.ToString("0.#"); if (label[0] != '-') { label = "+" + label; } label = "M" + label; label += new string('+', charge); mzRanges.Add(mzRange, label); var chromatogramPoint = MsDataFileUtil.GetPoint(mzRange, _spectrumData.CentroidMzs, _spectrumData.CentroidIntensities); peptideIntensity += chromatogramPoint.GetIntensity(mzRange, MassAccuracy); } } spectrum.MassAccuracy = MassAccuracy; spectrum.MzRanges = mzRanges; tbxPeptideIntensity.Text = peptideIntensity.ToString(NumberFormat); } if (cbxShowCentroids.Checked) { msGraphControlEx1.AddGraphItem(msGraphControlEx1.GraphPane, spectrum); } if (turnoverCalculator != null && cbxShowPeptideMzs.Checked) { double massAccuracy = MassAccuracy; for (int charge = MinCharge; charge <= MaxCharge; charge++) { var mzs = turnoverCalculator.GetMzs(charge); var height = int.MaxValue; foreach (var mzRange in mzs) { double min = mzRange.MinWithMassAccuracy(massAccuracy); double max = mzRange.MaxWithMassAccuracy(massAccuracy); msGraphControlEx1.GraphPane.GraphObjList.Add(new BoxObj(min, height, max - min, height, Color.Goldenrod, Color.Goldenrod) { IsClippedToChartRect = true, ZOrder = ZOrder.F_BehindGrid }); } } } msGraphControlEx1.Invalidate(); } finally { _inRedisplay = false; } }
public void Redisplay() { if (!IsHandleCreated) { return; } if (_inRedisplay) { return; } try { _inRedisplay = true; tbxMinCharge.Text = MinCharge.ToString(); tbxMaxCharge.Text = MaxCharge.ToString(); tbxPeptideSequence.Text = PeptideSequence; cbxShowPeptideMzs.Enabled = !string.IsNullOrEmpty(PeptideSequence); tbxMassAccuracy.Text = MassAccuracy.ToString(); TurnoverCalculator turnoverCalculator = null; if (!string.IsNullOrEmpty(PeptideSequence)) { turnoverCalculator = new TurnoverCalculator(Workspace, PeptideSequence); } msGraphControlEx1.GraphPane.GraphObjList.Clear(); msGraphControlEx1.GraphPane.CurveList.Clear(); if (_spectrumData == null || comboChromatogram.SelectedIndex >= 0 && null == _chromatogramDatas[comboChromatogram.SelectedIndex]) { using (var msDataFileImpl = new MsDataFileImpl(Workspace.GetDataFilePath(MsDataFile.Name))) { if (comboChromatogram.SelectedIndex >= 0 && null == _chromatogramDatas[comboChromatogram.SelectedIndex]) { string chromatogramName; float[] timeArray; float[] intensityArray; msDataFileImpl.GetChromatogram(comboChromatogram.SelectedIndex, out chromatogramName, out timeArray, out intensityArray); _chromatogramDatas[comboChromatogram.SelectedIndex] = new ChromatogramData(chromatogramName, timeArray, intensityArray); } _spectrumData = _spectrumData ?? new SpectrumData(msDataFileImpl, ScanIndex); } } ChromatogramData chromatogram = null; if (comboChromatogram.SelectedIndex >= 0) { chromatogram = _chromatogramDatas[comboChromatogram.SelectedIndex]; } tbxMsLevel.Text = _spectrumData.MsLevel.ToString(); tbxTime.Text = _spectrumData.Time.ToString(); if (chromatogram != null && ScanIndex < chromatogram.TimeArray.Length) { tbxChromatogramRetentionTime.Text = chromatogram.TimeArray[ScanIndex].ToString(); tbxChromatogramIonCurrent.Text = chromatogram.IntensityArray[ScanIndex].ToString(NumberFormat); } else { tbxChromatogramRetentionTime.Text = tbxChromatogramIonCurrent.Text = @"N/A"; } if (cbxShowProfile.Checked && _spectrumData.ProfileMzs != null) { msGraphControlEx1.AddGraphItem(msGraphControlEx1.GraphPane, new SpectrumGraphItem() { Points = new PointPairList(_spectrumData.ProfileMzs, _spectrumData.ProfileIntensities), GraphItemDrawMethod = MSGraphItemDrawMethod.line, Color = Color.Blue, }); } if (_spectrumData.ProfileIntensities != null) { tbxSumOfProfileIntensities.Text = _spectrumData.ProfileIntensities.Sum().ToString(NumberFormat); } else { tbxSumOfProfileIntensities.Text = ""; } tbxCentroidIntensitySum.Text = _spectrumData.CentroidIntensities.Sum().ToString(NumberFormat); var spectrum = new SpectrumGraphItem { Points = new PointPairList(_spectrumData.CentroidMzs, _spectrumData.CentroidIntensities), GraphItemDrawMethod = MSGraphItemDrawMethod.stick, Color = Color.Black }; if (turnoverCalculator != null) { var mzRanges = new Dictionary<MzRange, String>(); double monoisotopicMass = Workspace.GetAminoAcidFormulas().GetMonoisotopicMass(PeptideSequence); double peptideIntensity = 0.0; for (int charge = MinCharge; charge <= MaxCharge; charge ++) { foreach (var mzRange in turnoverCalculator.GetMzs(charge)) { double mass = (mzRange.Center - AminoAcidFormulas.ProtonMass)* charge; double massDifference = mass - monoisotopicMass; var label = massDifference.ToString("0.#"); if (label[0] != '-') { label = "+" + label; } label = "M" + label; label += new string('+', charge); mzRanges.Add(mzRange, label); var chromatogramPoint = MsDataFileUtil.GetPoint(mzRange, _spectrumData.CentroidMzs, _spectrumData.CentroidIntensities); peptideIntensity += chromatogramPoint.GetIntensity(mzRange, MassAccuracy); } } spectrum.MassAccuracy = MassAccuracy; spectrum.MzRanges = mzRanges; tbxPeptideIntensity.Text = peptideIntensity.ToString(NumberFormat); } if (cbxShowCentroids.Checked) { msGraphControlEx1.AddGraphItem(msGraphControlEx1.GraphPane, spectrum); } if (turnoverCalculator != null && cbxShowPeptideMzs.Checked) { double massAccuracy = MassAccuracy; for (int charge = MinCharge; charge <= MaxCharge; charge++) { var mzs = turnoverCalculator.GetMzs(charge); var height = int.MaxValue; foreach (var mzRange in mzs) { double min = mzRange.MinWithMassAccuracy(massAccuracy); double max = mzRange.MaxWithMassAccuracy(massAccuracy); msGraphControlEx1.GraphPane.GraphObjList.Add(new BoxObj(min, height, max - min, height, Color.Goldenrod, Color.Goldenrod) { IsClippedToChartRect = true, ZOrder = ZOrder.F_BehindGrid }); } } } msGraphControlEx1.Invalidate(); } finally { _inRedisplay = false; } }
} // CreateLogicalOffer private int GetLogicalProposedAmount(GradeRangeSubproduct grsp) { decimal annualTurnover = 0; decimal freeCashFlow = 0; decimal valueAdded = 0; try { var turnoverCalc = new TurnoverCalculator(this.customerID, DateTime.UtcNow, DB, Log).LoadInputData(); if (turnoverCalc.OutOfDate) { Log.Debug("Out of date marketplaces detected for {0}.", OuterContextDescription); } else { turnoverCalc.Execute(); if (turnoverCalc.HasOnline) { Log.Debug("Online turnover for {0}.", OuterContextDescription); turnoverCalc.ExecuteOnline(); } else { Log.Debug("Offline turnover for {0}.", OuterContextDescription); } annualTurnover = turnoverCalc.Model.AnnualTurnover; freeCashFlow = turnoverCalc.Model.UseHmrc ? turnoverCalc.Model.FreeCashFlowValue : 0; valueAdded = turnoverCalc.Model.UseHmrc ? turnoverCalc.Model.ValueAdded : 0; } // if } catch (Exception e) { Log.Alert(e, "Failed to load turnover for {0}.", OuterContextDescription); } // try Log.Debug( "Turnover = {0}, FCF = {1}, VA = {2} for {3}.", annualTurnover, freeCashFlow, valueAdded, OuterContextDescription ); decimal[] allOffers = { annualTurnover *(grsp.TurnoverShare ?? 0), freeCashFlow *(grsp.FreeCashFlowShare ?? 0), valueAdded *(grsp.ValueAddedShare ?? 0), }; List <int> validOffers = allOffers.Where(v => v > 0).Select(grsp.LoanAmount).Where(v => v > 0).ToList(); Log.Debug( "Proposed amounts for {0}:\n\tAll offer amounts: {1}\n\tValid offer amounts: {2}", OuterContextDescription, string.Join(", ", allOffers), string.Join(", ", validOffers) ); if (validOffers.Count > 0) { int minOffer = validOffers.Min(); Log.Debug("Proposed offer amount for {0} is {1}.", OuterContextDescription, minOffer); return(minOffer); } // if Log.Debug("No valid offers found for {0}.", OuterContextDescription); return(0); } // GetLogicalProposedAmount
public void Init(Workspace workspace) { Chromatograms = new List<ChromatogramGenerator.Chromatogram>(); var turnoverCalculator = new TurnoverCalculator(workspace, Sequence); for (int charge = MinCharge; charge <= MaxCharge; charge++) { var mzs = turnoverCalculator.GetMzs(charge); for (int massIndex = 0; massIndex < mzs.Count; massIndex++) { Chromatograms.Add(new ChromatogramGenerator.Chromatogram(new MzKey(charge, massIndex), mzs[massIndex])); } } ScanIndexes = new List<int>(); Times = new List<double>(); }
private void BtnGoOnClick(object sender, EventArgs e) { graphDetails.GraphPane.CurveList.Clear(); int pointCount = PointCount; double precursorPool = PrecursorPool; double turnover = Turnover; int labelCount = LabelCount; double noise = Noise; var points = new PointPairList(); var tracerDef = Workspace.GetTracerDefs().FirstOrDefault(td => td.AminoAcidSymbol.HasValue); if (tracerDef == null) { MessageBox.Show( "The simulation cannot be run because there is no amino acid tracer defined in this workspace"); return; } Debug.Assert(tracerDef.AminoAcidSymbol.HasValue); string peptide = new string(tracerDef.AminoAcidSymbol.Value, labelCount); var turnoverCalculator = new TurnoverCalculator(Workspace, peptide); var initialTracerPercents = TracerPercentFormula.Parse("").SetElementCount(tracerDef.Name, tracerDef.InitialApe); var newTracerPercents = TracerPercentFormula.Parse("").SetElementCount(tracerDef.Name, precursorPool); var initialDistribution = turnoverCalculator.GetDistribution(initialTracerPercents); var newDistribution = turnoverCalculator.GetDistribution(newTracerPercents); var currentMixture = Mix(initialDistribution, (100.0 - turnover) / 100, newDistribution, turnover / 100); var keys = new List <TracerFormula>(); for (int i = 0; i <= labelCount; i++) { keys.Add(TracerFormula.Parse("").SetElementCount(tracerDef.Name, i)); } var bestMatches = new List <IDictionary <TracerFormula, double> >(); var precursorEnrichments = new List <TracerPercentFormula>(); var observedResults = new List <IDictionary <TracerFormula, double> >(); while (points.Count < pointCount) { var noisyMixture = Perturb(keys, currentMixture, noise / 100); double calcTurnover; double calcTurnoverScore; double calcPrecursorPool; IDictionary <TracerFormula, double> bestMatch; var calcMixture = turnoverCalculator.ComputePrecursorEnrichmentAndTurnover(noisyMixture, out calcTurnover, out calcTurnoverScore, out bestMatch); if (calcMixture == null) { continue; } calcMixture.TryGetValue(tracerDef.Name, out calcPrecursorPool); points.Add(new PointPair(calcTurnover * 100, calcPrecursorPool)); bestMatches.Add(bestMatch); precursorEnrichments.Add(calcMixture); observedResults.Add(noisyMixture); } graphResults.GraphPane.CurveList.Clear(); graphResults.GraphPane.GraphObjList.Clear(); var lineItem = graphResults.GraphPane.AddCurve(null, points, Color.Black); lineItem.Line.IsVisible = false; graphResults.GraphPane.XAxis.Title.Text = "% newly synthesized"; graphResults.GraphPane.YAxis.Title.Text = "Precursor pool"; graphResults.GraphPane.AxisChange(); graphResults.Invalidate(); dataGridView.Rows.Clear(); var row = dataGridView.Rows[dataGridView.Rows.Add()]; row.Cells[colQuantity.Index].Value = "% newly synthesized"; var statsTurnover = new Statistics(points.Select(p => p.X).ToArray()); row.Cells[colMean.Index].Value = statsTurnover.Mean(); row.Cells[colMedian.Index].Value = statsTurnover.Median(); row.Cells[colStdDev.Index].Value = statsTurnover.StdDev(); row = dataGridView.Rows[dataGridView.Rows.Add()]; var statsPrecursorPool = new Statistics(points.Select(p => p.Y).ToArray()); row.Cells[colQuantity.Index].Value = "Precursor Pool"; row.Cells[colMean.Index].Value = statsPrecursorPool.Mean(); row.Cells[colMedian.Index].Value = statsPrecursorPool.Median(); row.Cells[colStdDev.Index].Value = statsPrecursorPool.StdDev(); _precursorEnrichmentsByPoint = points.Select(p => p.Y).ToArray(); _bestMatches = bestMatches; _observedResults = observedResults; _scatterPlotCurve = lineItem; _expected = currentMixture; _turnovers = points.Select(p => p.X).ToArray(); _tracerFormulas = keys; ShowResult(-1); }
private void UpdateGraph() { if (_inUpdateGraph) { return; } try { _inUpdateGraph = true; _msGraphControl.GraphPane.GraphObjList.Clear(); _msGraphControl.GraphPane.CurveList.Clear(); dataGridView1.Rows.Clear(); int charge; try { charge = Convert.ToInt32(tbxCharge.Text); tbxCharge.BackColor = Color.White; } catch { charge = 0; tbxCharge.BackColor = Color.Red; } double massResolution; try { massResolution = double.Parse(tbxMassResolution.Text); tbxMassResolution.BackColor = Color.White; } catch { tbxMassResolution.BackColor = Color.Red; massResolution = .01; } var sequence = tbxSequence.Text; MassDistribution spectrum; if (string.IsNullOrEmpty(sequence)) { var formula = tbxFormula.Text; var molecule = Molecule.Parse(formula); if (molecule.Values.Sum() > 10000000) { tbxFormula.BackColor = Color.Red; return; } try { spectrum = Workspace.GetAminoAcidFormulas().GetMassDistribution(molecule, charge); tbxFormula.BackColor = Color.White; } catch { tbxFormula.BackColor = Color.Red; return; } } else { tbxFormula.Text = Workspace.GetAminoAcidFormulas().GetFormula(sequence).ToString(); var turnoverCalculator = new TurnoverCalculator(Workspace, sequence); var aminoAcidFormulas = Workspace.GetAminoAcidFormulasWithTracers(); aminoAcidFormulas = aminoAcidFormulas.SetMassResolution(massResolution); try { if (cbxTracerPercents.Checked) { var tracerPercentFormula = TracerPercentFormula.Parse(tbxTracerFormula.Text); spectrum = turnoverCalculator.GetAminoAcidFormulas(tracerPercentFormula) .GetMassDistribution(sequence, charge); } else { var tracerFormula = TracerFormula.Parse(tbxTracerFormula.Text); spectrum = aminoAcidFormulas.GetMassDistribution( turnoverCalculator.MoleculeFromTracerFormula(tracerFormula), charge); double massShift = aminoAcidFormulas.GetMassShift(sequence); if (charge > 0) { massShift /= charge; } spectrum = spectrum.OffsetAndDivide(massShift, 1); } tbxTracerFormula.BackColor = Color.White; } catch { tbxTracerFormula.BackColor = Color.Red; spectrum = aminoAcidFormulas.GetMassDistribution(sequence, charge); } } if (spectrum == null) { return; } var curveItem = _msGraphControl.AddGraphItem(_msGraphControl.GraphPane, new GraphItem { Title = "Intensity", Color = Color.Black, Points = new PointPairList( spectrum.Keys. ToArray(), spectrum.Values. ToArray()) }); curveItem.Label.IsVisible = false; _msGraphControl.AxisChange(); _msGraphControl.Invalidate(); var entries = spectrum.ToArray(); dataGridView1.Rows.Add(entries.Length); for (int i = 0; i < entries.Count(); i++) { var row = dataGridView1.Rows[i]; row.Cells[colMass.Index].Value = entries[i].Key; row.Cells[colIntensity.Index].Value = entries[i].Value; } } finally { _inUpdateGraph = false; } }
public TurnoverCalculator GetTurnoverCalculator(string peptideSequence) { peptideSequence = Peptide.TrimSequence(peptideSequence); TurnoverCalculator turnoverCalculator; if (_turnoverCalculators.TryGetValue(peptideSequence, out turnoverCalculator)) { return turnoverCalculator; } turnoverCalculator = new TurnoverCalculator(Workspace, peptideSequence); _turnoverCalculators.Add(peptideSequence, turnoverCalculator); return turnoverCalculator; }