private void GetDataFromFavoriteChild(IqResult result)
        {
            var fav = result.FavoriteChild;

            if (fav == null)
            {
                result.LCScanSetSelected     = null;
                result.LcScanObs             = -1;
                result.MZObs                 = 0;
                result.MZObsCalibrated       = 0;
                result.Abundance             = 0;
                result.ElutionTimeObs        = -1;
                result.IsotopicProfileFound  = false;
                result.InterferenceScore     = 1;
                result.FitScore              = 1;
                result.MassErrorBefore       = 0;
                result.MassErrorAfter        = 0;
                result.MonoMassObs           = 0;
                result.MonoMassObsCalibrated = 0;
            }
            else
            {
                result.LCScanSetSelected     = fav.LCScanSetSelected;
                result.LcScanObs             = fav.LcScanObs;
                result.CorrelationData       = fav.CorrelationData;
                result.FitScore              = fav.FitScore;
                result.ChromPeakSelected     = fav.ChromPeakSelected;
                result.MZObs                 = fav.MZObs;
                result.MZObsCalibrated       = fav.MZObsCalibrated;
                result.MonoMassObs           = fav.MonoMassObs;
                result.MonoMassObsCalibrated = fav.MonoMassObsCalibrated;
                result.ElutionTimeObs        = fav.ElutionTimeObs;
                result.Abundance             = fav.ChromPeakSelected == null ? 0f : fav.ChromPeakSelected.Height;
            }
        }
Beispiel #2
0
        /// <summary>
        /// ChargeStateChildTopDownIqWorkflow
        /// Generates theoretical isotopic profile, XIC, and creates ChromPeakIqTargets based on peaks found
        /// </summary>
        /// <param name="result"></param>
        protected override void ExecuteWorkflow(IqResult result)
        {
            //Generate theoretical isotopic profile
            result.Target.TheorIsotopicProfile = TheorFeatureGen.GenerateTheorProfile(result.Target.EmpiricalFormula, result.Target.ChargeState);

            if (!Parser.CheckSequenceIntegrity(result.Target.Code))
            {
                ShiftIsotopicProfile(result.Target.TheorIsotopicProfile, result.Target.MonoMassTheor, result.Target.ChargeState);
            }

            //Generate XIC and smooth
            result.IqResultDetail.Chromatogram = ChromGen.GenerateChromatogram(Run, result.Target.TheorIsotopicProfile, result.Target.ElutionTimeTheor);
            result.IqResultDetail.Chromatogram = ChromSmoother.Smooth(result.IqResultDetail.Chromatogram);

            //Look for peaks in XIC
            result.ChromPeakList = ChromPeakDetector.FindPeaks(result.IqResultDetail.Chromatogram);
            ChromPeakDetector.CalculateElutionTimes(Run, result.ChromPeakList);
            ChromPeakDetector.FilterPeaksOnNET(WorkflowParameters.ChromNETTolerance, result.Target.ElutionTimeTheor, result.ChromPeakList);

            var tempMinScanWithinTol = (int)Run.NetAlignmentInfo.GetScanForNet(result.Target.ElutionTimeTheor - WorkflowParameters.ChromNETTolerance);
            var tempMaxScanWithinTol = (int)Run.NetAlignmentInfo.GetScanForNet(result.Target.ElutionTimeTheor + WorkflowParameters.ChromNETTolerance);
            var tempCenterTol        = (int)Run.NetAlignmentInfo.GetScanForNet(result.Target.ElutionTimeTheor);

            result.NumChromPeaksWithinTolerance = result.ChromPeakList.Count;

            //General peak information output written to console.
            Console.WriteLine("SmartPeakSelector --> NETTolerance= " + WorkflowParameters.ChromNETTolerance + ";  chromMinCenterMax= " +
                              tempMinScanWithinTol + "\t" + tempCenterTol + "" +
                              "\t" + tempMaxScanWithinTol);
            Console.WriteLine("MT= " + result.Target.ID + ";z= " + result.Target.ChargeState + "; mz= " + result.Target.MZTheor.ToString("0.000") +
                              ";  ------------------------- PeaksWithinTol = " + result.ChromPeakList.Count);

            //Creates a ChromPeakIqTarget for each peak found
            foreach (ChromPeak peak in result.ChromPeakList)
            {
                var target = new ChromPeakIqTarget(new ChromPeakAnalyzerIqWorkflow(Run, WorkflowParameters));
                TargetUtilities.CopyTargetProperties(result.Target, target, false);
                target.ChromPeak = peak;
                result.Target.AddTarget(target);
            }

            //Executes each grandchild ChromPeakAnalyzerIqWorkflow
            var children = result.Target.ChildTargets();

            foreach (var child in children)
            {
                child.DoWorkflow();
            }

            if (Utilities.SipperDataDump.OutputResults)
            {
                //Data Dump for use with Sipper
                children = result.Target.ChildTargets();
                foreach (var child in children)
                {
                    Utilities.SipperDataDump.DataDump(child, Run);
                }
            }
        }
        protected override void ExecuteWorkflow(IqResult result)
        {
            if (ChromPeakAnalyzerIqWorkflow == null)
            {
                InitializeChromPeakAnalyzerWorkflow();
            }

            result.Target.TheorIsotopicProfile = TheorFeatureGen.GenerateTheorProfile(result.Target.EmpiricalFormula, result.Target.ChargeState);

            result.IqResultDetail.Chromatogram = ChromGen.GenerateChromatogram(Run, result.Target.TheorIsotopicProfile, result.Target.ElutionTimeTheor);

            result.IqResultDetail.Chromatogram = ChromSmoother.Smooth(result.IqResultDetail.Chromatogram);

            result.ChromPeakList = ChromPeakDetector.FindPeaks(result.IqResultDetail.Chromatogram);

            ChromPeakDetector.CalculateElutionTimes(Run, result.ChromPeakList);

            ChromPeakDetector.FilterPeaksOnNET(WorkflowParameters.ChromNETTolerance, result.Target.ElutionTimeTheor, result.ChromPeakList);

            result.NumChromPeaksWithinTolerance = result.ChromPeakList.Count;


            //Creates a ChromPeakIqTarget for each peak found
            foreach (ChromPeak peak in result.ChromPeakList)
            {
                var target = new ChromPeakIqTarget(ChromPeakAnalyzerIqWorkflow);
                TargetUtilities.CopyTargetProperties(result.Target, target, false);
                target.ChromPeak = peak;
                result.Target.AddTarget(target);
            }

            //Executes each grandchild ChromPeakAnalyzerIqWorkflow
            var children          = result.Target.ChildTargets();
            var targetRemovalList = new List <IqTarget>();

            foreach (var child in children)
            {
                child.DoWorkflow();

                /*
                 * //Selects grandchildren with extremely poor metric scores for removal
                 * IqResult childResult = child.GetResult();
                 * if ((childResult.FitScore >= .8) || (childResult.CorrelationData.RSquaredValsMedian <= .15))
                 * {
                 *  targetRemovalList.Add(child);
                 * }
                 */
            }

            /*
             * //Removes the poorly scoring grandchild ChromPeakIqTargets
             * foreach (IqTarget iqTarget in targetRemovalList)
             * {
             *  result.RemoveResult(iqTarget.GetResult());
             *  result.Target.RemoveTarget(iqTarget);
             * }
             */
        }
Beispiel #4
0
 public void RemoveResult(IqResult result)
 {
     foreach (var childResult in result._childResults)
     {
         childResult.ParentResult = result.ParentResult;
         result.ParentResult._childResults.Add(childResult);
     }
     result.ParentResult._childResults.Remove(result);
 }
Beispiel #5
0
        protected override void ExecuteWorkflow(IqResult result)
        {
            //Executes the ChargeState level children workflows
            var children = result.Target.ChildTargets();

            foreach (var child in children)
            {
                child.DoWorkflow();
            }
        }
        private void ExportChromGraph(IqResult result)
        {
            if (result.IqResultDetail.Chromatogram == null)
            {
                return;
            }


            var minScan = result.LcScanObs - 1000;
            var maxScan = result.LcScanObs + 1000;


            _graphGenerator.GraphHeight = 600;
            _graphGenerator.GraphWidth  = 800;

            result.IqResultDetail.Chromatogram = result.IqResultDetail.Chromatogram.TrimData(minScan, maxScan);


            _graphGenerator.GenerateGraph(result.IqResultDetail.Chromatogram.Xvalues, result.IqResultDetail.Chromatogram.Yvalues);
            var line = _graphGenerator.GraphPane.CurveList[0] as LineItem;

            line.Line.IsVisible = true;
            line.Symbol.Size    = 3;
            line.Line.Width     = 2;
            line.Symbol.Type    = SymbolType.None;
            line.Color          = Color.Black;

            _graphGenerator.GraphPane.XAxis.Title.Text    = "scan";
            _graphGenerator.GraphPane.YAxis.Title.Text    = "intensity";
            _graphGenerator.GraphPane.XAxis.Scale.MinAuto = false;
            _graphGenerator.GraphPane.XAxis.Scale.MaxAuto = false;
            _graphGenerator.GraphPane.YAxis.Scale.MinAuto = false;
            _graphGenerator.GraphPane.YAxis.Scale.MaxAuto = false;
            _graphGenerator.GraphPane.YAxis.Scale.Min     = 0;
            _graphGenerator.GraphPane.YAxis.Scale.Max     = result.IqResultDetail.Chromatogram.getMaxY();
            _graphGenerator.GraphPane.YAxis.Scale.Format  = "0";

            _graphGenerator.GraphPane.XAxis.Scale.Min = minScan;
            _graphGenerator.GraphPane.XAxis.Scale.Max = maxScan;

            _graphGenerator.GraphPane.XAxis.Scale.FontSpec.Size = 12;
            var outputGraphFilename = Path.Combine(OutputFolderForGraphs,
                                                   result.Target.ID + "_" +
                                                   result.Target.ChargeState + "_" +
                                                   result.Target.MZTheor.ToString("0.000") + "_chrom.png");

            var graphInfoText = "ID= " + result.Target.ID + "; z= " + result.Target.ChargeState + "; m/z= " +
                                result.Target.MZTheor.ToString("0.000") + "; ScanLC= " + result.LcScanObs;

            _graphGenerator.AddAnnotationRelativeAxis(graphInfoText, 0.3, 0.02);
            _graphGenerator.AddVerticalLineToGraph(result.LcScanObs, 1);

            _graphGenerator.AddAnnotationAbsoluteXRelativeY("*", result.Target.MZTheor, 0.03);
            _graphGenerator.SaveGraph(outputGraphFilename);
        }
Beispiel #7
0
        /// <summary>
        /// Performs charge correlation on parent level target
        /// </summary>
        /// <param name="result"></param>
        private void PerformChargeCorrelation(IqResult result)
        {
            var iqChargeCorrelator = ChromatogramCorrelator as IqChargeCorrelator;
            var topDownIqResult    = result as TopDownIqResult;

            if (iqChargeCorrelator != null && topDownIqResult != null)
            {
                topDownIqResult.ChargeCorrelationData = iqChargeCorrelator.CorrelateData(GetAllChromPeakIqTargets(result), Run);
            }
            else
            {
                throw new Exception("IqChargeCorrelator and/or TopDownIqResult is not compatible");
            }
        }
        private void getRsquaredVal(IqResult result, out double?rsquaredVal, out double?slope)
        {
            if (result.CorrelationData != null && result.CorrelationData.CorrelationDataItems.Count > 0)
            {
                rsquaredVal = result.CorrelationData.RSquaredValsMedian;

                slope = result.CorrelationData.CorrelationDataItems.First().CorrelationSlope;
            }
            else
            {
                rsquaredVal = -1;
                slope       = -1;
            }
        }
        private void ExportGraphs(IqResult result)
        {
            if (string.IsNullOrEmpty(OutputFolderForGraphs))
            {
                OutputFolderForGraphs = Path.Combine(Run.DataSetPath, "OutputGraphs");
            }

            if (!Directory.Exists(OutputFolderForGraphs))
            {
                Directory.CreateDirectory(OutputFolderForGraphs);
            }

            ExportMassSpectrumGraph(result);
            ExportChromGraph(result);
        }
Beispiel #10
0
        /// <summary>
        /// Returns a list of all ChromPeakIqTarget objects under a parent target
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        private List <ChromPeakIqTarget> GetAllChromPeakIqTargets(IqResult result)
        {
            var chromPeakTargets = new List <ChromPeakIqTarget>();
            var children         = result.Target.ChildTargets();

            foreach (var child in children)
            {
                var grandchildTargets = child.ChildTargets();
                foreach (ChromPeakIqTarget target in grandchildTargets)
                {
                    chromPeakTargets.Add(target);
                }
            }
            return(chromPeakTargets);
        }
Beispiel #11
0
        /// <summary>
        /// Parent level workflow for Top-Down IQ analysis
        /// </summary>
        /// <param name="result"></param>
        protected override void ExecuteWorkflow(IqResult result)
        {
            //Executes the ChargeState level children workflows
            var children = result.Target.ChildTargets();

            foreach (var child in children)
            {
                child.DoWorkflow();
            }

            PerformChargeCorrelation(result);
            var referenceTarget = TargetSelector((TopDownIqResult)result);

            ExpandChargeRange((TopDownIqTarget)result.Target, referenceTarget);
        }
Beispiel #12
0
        protected override void ExportResults(IqResult iqResult)
        {
            var resultsForExport = _iqResultUtilities.FlattenOutResultTree(iqResult);

            var orderedResults = resultsForExport.OrderBy(p => p.Target.ChargeState).ToList();

            var exportedResults = orderedResults.Where(orderedResult => orderedResult.IsExported).ToList();

            if (IqResultExporter == null)
            {
                IqResultExporter = iqResult.Target.Workflow.CreateExporter();
            }

            SetupResultsFolder();

            IqResultExporter.WriteOutResults(Path.Combine(_resultsFolder, Run.DatasetName), exportedResults);
        }
        private IqResult SelectBestChargeStateChildResult(IqResult result)
        {
            var filteredChargeStateResults = result.ChildResults().Where(p => p.FavoriteChild != null).ToList();

            if (filteredChargeStateResults.Count == 0)
            {
                return(null);
            }

            if (filteredChargeStateResults.Count == 1)
            {
                return(filteredChargeStateResults.First());
            }

            //now to deal with the tough issue of multiple charge states having a possible results.

            var filter2 = filteredChargeStateResults.Where(p => p.CorrelationData.CorrelationDataItems.First().CorrelationRSquaredVal > 0.7).ToList();

            if (filter2.Count == 0)
            {
                filter2 = filteredChargeStateResults.Where(p => p.CorrelationData.CorrelationDataItems.First().CorrelationRSquaredVal > 0.5).ToList();
            }

            if (filter2.Count == 0)
            {
                filter2 = filteredChargeStateResults.Where(p => p.CorrelationData.CorrelationDataItems.First().CorrelationRSquaredVal > 0.3).ToList();
            }

            if (filter2.Count == 0)
            {
                //correlation values are no good. Now will sort by fit score.
                filter2 = filteredChargeStateResults.OrderBy(p => p.FitScore).Take(1).ToList();   //sort by fit score let the first one be selected
            }

            if (filter2.Count == 1)
            {
                return(filter2.First());
            }
            else if (filter2.Count > 1)
            {
                //if we reached here, there are multiple charge state results with good correlation scores.  Take the one of highest intensity.
                return(filter2.OrderByDescending(p => p.Abundance).First());
            }

            return(null);
        }
        public List <IqResult> FlattenOutResultTree(IqResult iqResult)
        {
            var flattenedResults = new List <IqResult>();

            if (iqResult.HasChildren())
            {
                var childresults = iqResult.ChildResults();
                foreach (var childResult in childresults)
                {
                    var moreResults = FlattenOutResultTree(childResult);
                    flattenedResults.AddRange(moreResults);
                }
            }

            flattenedResults.Add(iqResult);


            return(flattenedResults);
        }
        private void ExportMassSpectrumGraph(IqResult result)
        {
            _graphGenerator.GraphHeight = 600;
            _graphGenerator.GraphWidth  = 800;

            _graphGenerator.GenerateGraph(result.IqResultDetail.MassSpectrum.Xvalues, result.IqResultDetail.MassSpectrum.Yvalues);
            var line = _graphGenerator.GraphPane.CurveList[0] as LineItem;

            line.Line.IsVisible = true;
            line.Symbol.Size    = 3;
            line.Line.Width     = 2;
            line.Symbol.Type    = SymbolType.None;
            line.Color          = Color.Black;

            _graphGenerator.GraphPane.XAxis.Title.Text    = "m/z";
            _graphGenerator.GraphPane.YAxis.Title.Text    = "intensity";
            _graphGenerator.GraphPane.XAxis.Scale.MinAuto = true;
            _graphGenerator.GraphPane.YAxis.Scale.MinAuto = false;
            _graphGenerator.GraphPane.YAxis.Scale.MaxAuto = false;

            _graphGenerator.GraphPane.YAxis.Scale.Min = 0;


            _graphGenerator.GraphPane.YAxis.Scale.Max    = result.IqResultDetail.MassSpectrum.getMaxY();
            _graphGenerator.GraphPane.YAxis.Scale.Format = "0";


            _graphGenerator.GraphPane.XAxis.Scale.FontSpec.Size = 12;
            var outputGraphFilename = Path.Combine(OutputFolderForGraphs,
                                                   result.Target.ID + "_" +
                                                   result.Target.ChargeState + "_" +
                                                   result.Target.MZTheor.ToString("0.000") + "_MS.png");


            var graphInfoText = "ID= " + result.Target.ID + "; z= " + result.Target.ChargeState + "; m/z= " +
                                result.Target.MZTheor.ToString("0.000") + "; ScanLC= " + result.LcScanObs;

            _graphGenerator.AddAnnotationRelativeAxis(graphInfoText, 0.3, 0.02);

            _graphGenerator.AddAnnotationAbsoluteXRelativeY("*", result.Target.MZTheor, 0.03);
            _graphGenerator.SaveGraph(outputGraphFilename);
        }
Beispiel #16
0
        //Writes IqResult Data to Console
        private void Display(IqResult result)
        {
            var target = result.Target as ChromPeakIqTarget;

            if (target == null)
            {
                throw new NullReferenceException("The ChromPeakAnalyzerIqWorkflow only works with the ChromPeakIqTarget. "
                                                 + "Due to an inherent shortcoming of the design pattern we used, we were unable to make this a compile time error instead of a runtime error. "
                                                 + "Please change the IqTarget to ChromPeakIqTarget for proper use of the ChromPeakAnalyzerIqWorkflow.");
            }

            if (!_headerLogged)
            {
                _headerLogged = true;
                IqLogger.Log.Debug(("\t\t" + "ChromPeak.XValue" + "\t" + "NETError" + "\t" + "MassError" + "\t" + "FitScore" + "\t" + "IsIsotopicProfileFlagged"));
            }

            IqLogger.Log.Debug(("\t\t" + target.ChromPeak.XValue.ToString("0.00") + "\t" + result.NETError.ToString("0.0000") + "\t" + result.MassErrorBefore.ToString("0.0000") + "\t" +
                                result.FitScore.ToString("0.0000") + "\t" + result.IsIsotopicProfileFlagged));
        }
Beispiel #17
0
        protected virtual float GetAbundance(IqResult result)
        {
            if (result.ObservedIsotopicProfile == null)
            {
                return(0);
            }

            var indexMostAbundantPeakTheor = result.Target.TheorIsotopicProfile.GetIndexOfMostIntensePeak();

            if (result.ObservedIsotopicProfile.Peaklist.Count > indexMostAbundantPeakTheor)
            {
                result.ObservedIsotopicProfile.IntensityMostAbundantTheor = result.ObservedIsotopicProfile.Peaklist[indexMostAbundantPeakTheor].Height;
            }
            else
            {
                result.ObservedIsotopicProfile.IntensityMostAbundantTheor = result.ObservedIsotopicProfile.IntensityMostAbundant;
            }

            return(result.ObservedIsotopicProfile.IntensityMostAbundantTheor);
        }
Beispiel #18
0
        protected virtual void ExecutePostWorkflowHook(IqResult result)
        {
            if (result != null && Success)
            {
                WorkflowStatusMessage = "IqTarget " + result.Target.ID + "; m/z= " + result.Target.Code;

                //if (Result.FailedResult == false)
                //{
                //    if (Result.IsotopicProfile != null)
                //    {
                //        WorkflowStatusMessage = WorkflowStatusMessage + "; Target FOUND!";

                //    }

                //}
                //else
                //{
                //    WorkflowStatusMessage = WorkflowStatusMessage + "; Target NOT found. Reason: " + Result.FailureType;
                //}
            }
        }
Beispiel #19
0
        public virtual void Execute(IqResult result)
        {
            Check.Require(this.Run != null, "Error in IqWorkflow.Execute: Run has not been defined.");


            if (!IsWorkflowInitialized)
            {
                InitializeWorkflow();
            }
            try
            {
                ExecuteWorkflow(result);
                ExecutePostWorkflowHook(result);
            }
            catch (Exception ex)
            {
                var errorMessage = "Critical error!!!! " + ex.Message + "; processing IqTargetID = " + result.Target.ID + "; charge = " + result.Target.ChargeState +
                                   "; sequence= " + result.Target.Code + "; ScanLC= " + result.Target.ScanLC;

                Console.WriteLine(errorMessage);
                throw new ApplicationException(errorMessage, ex);
            }
        }
Beispiel #20
0
        protected virtual void ExecuteWorkflow(IqResult result)
        {
            result.Target.TheorIsotopicProfile = TheorFeatureGen.GenerateTheorProfile(result.Target.EmpiricalFormula, result.Target.ChargeState);

            result.IqResultDetail.Chromatogram = ChromGen.GenerateChromatogram(Run, result.Target.TheorIsotopicProfile, result.Target.ElutionTimeTheor);

            result.IqResultDetail.Chromatogram = ChromSmoother.Smooth(result.IqResultDetail.Chromatogram);

            result.ChromPeakList = ChromPeakDetector.FindPeaks(result.IqResultDetail.Chromatogram);

            ChromPeakDetector.CalculateElutionTimes(Run, result.ChromPeakList);

            ChromPeakDetector.FilterPeaksOnNET(WorkflowParameters.ChromNETTolerance, result.Target.ElutionTimeTheor, result.ChromPeakList);

            result.IqResultDetail.ChromPeakQualityData = ChromPeakAnalyzer.GetChromPeakQualityData(Run, result.Target, result.ChromPeakList);

            var filterOutFlagged = result.Target.TheorIsotopicProfile.GetIndexOfMostIntensePeak() == 0;

            result.ChromPeakSelected = ChromPeakSelector.SelectBestPeak(result.IqResultDetail.ChromPeakQualityData, filterOutFlagged);


            result.LCScanSetSelected = ChromPeakUtilities.GetLCScanSetForChromPeak(result.ChromPeakSelected, Run,
                                                                                   WorkflowParameters.NumMSScansToSum);

            result.LcScanObs = result.LCScanSetSelected == null ? -1 : result.LCScanSetSelected.PrimaryScanNumber;

            result.IqResultDetail.MassSpectrum = MSGenerator.GenerateMS(Run, result.LCScanSetSelected);

            TrimData(result.IqResultDetail.MassSpectrum, result.Target.MZTheor, MsLeftTrimAmount, MsRightTrimAmount);

            List <Peak> mspeakList;

            result.ObservedIsotopicProfile = MsfeatureFinder.IterativelyFindMSFeature(result.IqResultDetail.MassSpectrum, result.Target.TheorIsotopicProfile, out mspeakList);


            result.FitScore = FitScoreCalc.CalculateFitScore(result.Target.TheorIsotopicProfile, result.ObservedIsotopicProfile,
                                                             result.IqResultDetail.MassSpectrum);

            result.InterferenceScore = InterferenceScorer.GetInterferenceScore(result.ObservedIsotopicProfile, mspeakList);

            //if (_workflowParameters.ChromatogramCorrelationIsPerformed)
            //{
            //    ExecuteTask(_chromatogramCorrelator);
            //}

            result.MonoMassObs = result.ObservedIsotopicProfile == null ? 0 : result.ObservedIsotopicProfile.MonoIsotopicMass;

            result.MZObs = result.ObservedIsotopicProfile == null ? 0 : result.ObservedIsotopicProfile.MonoPeakMZ;

            result.MZObsCalibrated       = result.ObservedIsotopicProfile == null ? 0 : Run.GetAlignedMZ(result.ObservedIsotopicProfile.MonoPeakMZ, result.LcScanObs);
            result.MonoMassObsCalibrated = result.ObservedIsotopicProfile == null
                                               ? 0
                                               : (result.MZObsCalibrated - DeconTools.Backend.Globals.PROTON_MASS) * result.Target.ChargeState;


            var elutionTime = result.ChromPeakSelected == null ? 0d : ((ChromPeak)result.ChromPeakSelected).NETValue;

            result.ElutionTimeObs = elutionTime;

            result.Abundance = GetAbundance(result);
        }
Beispiel #21
0
        protected void ReportProcessingProgress(string reportString, int progressCounter, IqResult result)
        {
            if (_backgroundWorker == null)
            {
                if (progressCounter % 100 == 0)
                {
                    Console.WriteLine(DateTime.Now + "\t" + reportString);
                }
            }
            else
            {
                //TODO: fix this
                int progressPercent = 0;
                _backgroundWorker.ReportProgress(progressPercent, result);
            }

            if (progressCounter % 100 == 0)
            {
                writeToLogFile(DateTime.Now + "\t" + reportString);
            }
        }
        protected override void ExecuteWorkflow(IqResult result)
        {
            var children = result.Target.ChildTargets().ToList();

            foreach (var child in children)
            {
                child.DoWorkflow();
                var childResult = child.GetResult();

                var chromPeakLevelResults = childResult.ChildResults();

                var filteredChromPeakResults = chromPeakLevelResults.Where(r => r.IsotopicProfileFound).ToList();

                childResult.FavoriteChild = SelectBestChromPeakIqResult(childResult, filteredChromPeakResults);

                GetDataFromFavoriteChild(childResult);
            }

            result.FavoriteChild = SelectBestChargeStateChildResult(result);
            GetDataFromFavoriteChild(result);

            var favResult = result.FavoriteChild;

            double?rsquaredVal, slope;

            getRsquaredVal(result, out rsquaredVal, out slope);
            var favChargeState = result.FavoriteChild == null ? 0 : result.FavoriteChild.Target.ChargeState;
            var favMz          = result.FavoriteChild == null ? 0 : result.FavoriteChild.Target.MZTheor;

            if (!_headerLogged)
            {
                _headerLogged = true;
                IqLogger.Log.Info("\t" + "TargetID" + "\t\t\t" + "M/Z" + "\t" + "Charge" + "\t" + "LCScan" + "\t" + "RSquared" + "\t" + "Slope");
            }

            IqLogger.Log.Info("\t" + result.Target.ID + "\t\t\t" + favMz.ToString("0.000") + "\t" + favChargeState + "\t" + result.LcScanObs + "\t" + rsquaredVal + "\t" + slope);

            //now get the mass spectrum given the info from the favorite child charge state result

            if (favResult != null)
            {
                var scanset = new ScanSetFactory().CreateScanSet(Run, favResult.LCScanSetSelected.PrimaryScanNumber,
                                                                 WorkflowParameters.NumMSScansToSum);

                var selectedChromPeak    = favResult.ChromPeakSelected;
                var sigma                = selectedChromPeak.Width / 2.35;
                var chromScanWindowWidth = 4 * sigma;

                //Determines where to start and stop chromatogram correlation
                var startScan = scanset.PrimaryScanNumber - (int)Math.Round(chromScanWindowWidth / 2, 0);
                var stopScan  = scanset.PrimaryScanNumber + (int)Math.Round(chromScanWindowWidth / 2, 0);

                var massSpectrum = MSGenerator.GenerateMS(Run, scanset);

                foreach (var iqTarget in children)
                {
                    var childStateIqResult = (O16O18IqResult)iqTarget.GetResult();

                    childStateIqResult.IqResultDetail.MassSpectrum = massSpectrum.TrimData(iqTarget.MZTheor - 3, iqTarget.MZTheor + 8);

                    var mspeakList = _mspeakDetector.FindPeaks(childStateIqResult.IqResultDetail.MassSpectrum.Xvalues,
                                                               childStateIqResult.IqResultDetail.MassSpectrum.Yvalues);


                    childStateIqResult.CorrelationData = ChromatogramCorrelator.CorrelateData(Run, childStateIqResult, startScan, stopScan);


                    childStateIqResult.CorrelationO16O18SingleLabel           = childStateIqResult.GetCorrelationO16O18SingleLabel();
                    childStateIqResult.CorrelationO16O18DoubleLabel           = childStateIqResult.GetCorrelationO16O18DoubleLabel();
                    childStateIqResult.CorrelationBetweenSingleAndDoubleLabel = childStateIqResult.GetCorrelationBetweenSingleAndDoubleLabel();

                    childStateIqResult.RatioO16O18DoubleLabel   = childStateIqResult.GetRatioO16O18DoubleLabel();
                    childStateIqResult.RatioO16O18SingleLabel   = childStateIqResult.GetRatioO16O18SingleLabel();
                    childStateIqResult.RatioSingleToDoubleLabel = childStateIqResult.GetRatioSingleToDoubleLabel();

                    childStateIqResult.ObservedIsotopicProfile = MsfeatureFinder.IterativelyFindMSFeature(childStateIqResult.IqResultDetail.MassSpectrum,
                                                                                                          iqTarget.TheorIsotopicProfile);


                    if (childStateIqResult.ObservedIsotopicProfile != null)
                    {
                        var observedIsoList = childStateIqResult.ObservedIsotopicProfile.Peaklist.Cast <Peak>().Take(4).ToList();    //first 4 peaks excludes the O18 double label peak (fifth peak)
                        var theorPeakList   = iqTarget.TheorIsotopicProfile.Peaklist.Select(p => (Peak)p).Take(4).ToList();
                        childStateIqResult.FitScore = PeakFitter.GetFit(theorPeakList, observedIsoList, 0.05, WorkflowParameters.MSToleranceInPPM);

                        var o18Iso = childStateIqResult.ConvertO16ProfileToO18(iqTarget.TheorIsotopicProfile, 4);
                        theorPeakList   = o18Iso.Peaklist.Select(p => (Peak)p).ToList();
                        observedIsoList = childStateIqResult.ObservedIsotopicProfile.Peaklist.Cast <Peak>().Skip(4).ToList();    //skips the first 4 peaks and thus includes the O18 double label isotopic profile
                        childStateIqResult.FitScoreO18Profile = PeakFitter.GetFit(theorPeakList, observedIsoList, 0.05, WorkflowParameters.MSToleranceInPPM);



                        childStateIqResult.InterferenceScore     = InterferenceScorer.GetInterferenceScore(childStateIqResult.ObservedIsotopicProfile, mspeakList);
                        childStateIqResult.MZObs                 = childStateIqResult.ObservedIsotopicProfile.MonoPeakMZ;
                        childStateIqResult.MonoMassObs           = childStateIqResult.ObservedIsotopicProfile.MonoIsotopicMass;
                        childStateIqResult.MZObsCalibrated       = Run.GetAlignedMZ(childStateIqResult.MZObs);
                        childStateIqResult.MonoMassObsCalibrated = (childStateIqResult.MZObsCalibrated - DeconTools.Backend.Globals.PROTON_MASS) * childStateIqResult.Target.ChargeState;
                        childStateIqResult.ElutionTimeObs        = ((ChromPeak)favResult.ChromPeakSelected).NETValue;
                    }
                    else
                    {
                        childStateIqResult.FitScore          = -1;
                        childStateIqResult.InterferenceScore = -1;
                    }


                    getRsquaredVal(childStateIqResult, out rsquaredVal, out slope);
                    IqLogger.Log.Info("\t\t\t" + childStateIqResult.Target.ID + "\t" + childStateIqResult.Target.MZTheor.ToString("0.000") + "\t" + childStateIqResult.Target.ChargeState
                                      + "\t" + childStateIqResult.LcScanObs + "\t" + childStateIqResult.FitScore.ToString("0.000") + "\t" + rsquaredVal + "\t" + slope);


                    childStateIqResult.LCScanSetSelected = favResult.LCScanSetSelected;
                    childStateIqResult.LcScanObs         = favResult.LcScanObs;

                    if (GraphsAreOutputted)
                    {
                        if (_graphGenerator == null)
                        {
                            _graphGenerator = new BasicGraphControl();
                        }

                        ExportGraphs(childStateIqResult);
                    }
                }
            }
        }
        private IqResult SelectBestChromPeakIqResult(IqResult childResult, List <IqResult> filteredChromPeakResults)
        {
            var      numCandidateResults = filteredChromPeakResults.Count;
            IqResult bestChromPeakResult = null;

            if (numCandidateResults == 0)
            {
                bestChromPeakResult = null;
            }
            else if (numCandidateResults == 1)
            {
                bestChromPeakResult = filteredChromPeakResults.First();
            }
            else
            {
                var    furtherFilteredResults = new List <IqResult>();
                double lowestFit = 1;
                foreach (O16O18IqResult r in filteredChromPeakResults)
                {
                    var currentLowFitVal = Math.Min(r.FitScore, r.FitScoreO18Profile);
                    if (currentLowFitVal < lowestFit)
                    {
                        lowestFit = currentLowFitVal;

                        if (lowestFit < 0.2)
                        {
                            furtherFilteredResults.Add(r);
                        }
                    }
                }

                if (furtherFilteredResults.Count == 0)    // all potential candidates were filtered out above. So need a plan B.
                {
                    bestChromPeakResult = filteredChromPeakResults.OrderBy(p => p.FitScore).Take(3).OrderByDescending(p => p.Abundance).FirstOrDefault();
                }
                else if (furtherFilteredResults.Count == 1)
                {
                    bestChromPeakResult = furtherFilteredResults.First();
                }
                else   //still more than one candidate.  Will try to use another filter
                {
                    var currentBestChromPeakResult = furtherFilteredResults.OrderByDescending(p => p.Abundance).FirstOrDefault();
                    var level3FilteredResults      = new List <IqResult>();

                    foreach (O16O18IqResult furtherFilteredResult in furtherFilteredResults)
                    {
                        var currentCorrVal = Math.Max(furtherFilteredResult.GetCorrelationO16O18DoubleLabel(), furtherFilteredResult.GetCorrelationBetweenSingleAndDoubleLabel());

                        if (currentCorrVal > 0.7)
                        {
                            level3FilteredResults.Add(furtherFilteredResult);
                        }
                    }


                    if (level3FilteredResults.Count == 0)
                    {
                        bestChromPeakResult = currentBestChromPeakResult;
                    }
                    else if (level3FilteredResults.Count == 1)
                    {
                        bestChromPeakResult = level3FilteredResults.First();
                    }
                    else
                    {
                        //fit score is good. Correlation good. But still have multiple possibilities
                        bestChromPeakResult = level3FilteredResults.OrderByDescending(p => p.Abundance).First();
                    }
                }
            }


            if (bestChromPeakResult != null)
            {
                childResult.CorrelationData   = bestChromPeakResult.CorrelationData;
                childResult.LcScanObs         = bestChromPeakResult.LcScanObs;
                childResult.ChromPeakSelected = bestChromPeakResult.ChromPeakSelected; //check this
                childResult.LCScanSetSelected = bestChromPeakResult.LCScanSetSelected;


                var elutionTime = childResult.ChromPeakSelected == null
                                      ? 0d
                                      : ((ChromPeak)bestChromPeakResult.ChromPeakSelected).NETValue;
                childResult.ElutionTimeObs = elutionTime;

                childResult.Abundance = (float)(childResult.ChromPeakSelected == null
                                                     ? 0d
                                                     : ((ChromPeak)bestChromPeakResult.ChromPeakSelected).Height);
            }

            return(bestChromPeakResult);
        }
Beispiel #24
0
        /// <summary>
        /// Calculates Metrics based on ChromPeakIqTarget
        /// NET Error, Mass Error, Isotopic Fit, & Isotope Correlation
        /// </summary>
        protected override void ExecuteWorkflow(IqResult result)
        {
            result.IsExported = false;

            if (MSGenerator == null)
            {
                MSGenerator = MSGeneratorFactory.CreateMSGenerator(Run.MSFileType);
                MSGenerator.IsTICRequested = false;
            }

            var target = result.Target as ChromPeakIqTarget;

            if (target == null)
            {
                throw new NullReferenceException("The ChromPeakAnalyzerIqWorkflow only works with the ChromPeakIqTarget.");
            }


            var lcscanset = _chromPeakUtilities.GetLCScanSetForChromPeak(target.ChromPeak, Run, WorkflowParameters.SmartChromPeakSelectorNumMSSummed);

            //Generate a mass spectrum
            var massSpectrumXYData = MSGenerator.GenerateMS(Run, lcscanset);

            massSpectrumXYData = massSpectrumXYData.TrimData(result.Target.MZTheor - 5, result.Target.MZTheor + 15);

            //Find isotopic profile
            List <Peak> mspeakList;

            result.ObservedIsotopicProfile = TargetedMSFeatureFinder.IterativelyFindMSFeature(massSpectrumXYData, target.TheorIsotopicProfile, out mspeakList);

            //Default Worst Scores
            double iscore = 1;

            //Get NET Error
            var netError = target.ChromPeak.NETValue - target.ElutionTimeTheor;


            var leftOfMonoPeakLooker = new LeftOfMonoPeakLooker();
            var peakToTheLeft        = leftOfMonoPeakLooker.LookforPeakToTheLeftOfMonoPeak(target.TheorIsotopicProfile.getMonoPeak(), target.ChargeState, mspeakList);

            var hasPeakTotheLeft = peakToTheLeft != null;

            if (result.ObservedIsotopicProfile == null)
            {
                result.IsotopicProfileFound = false;
                result.FitScore             = 1;
            }
            else
            {
                //Get fit score O16 profile
                var observedIsoList = result.ObservedIsotopicProfile.Peaklist.Cast <Peak>().Take(4).ToList();    //first 4 peaks excludes the O18 double label peak (fifth peak)
                var theorPeakList   = target.TheorIsotopicProfile.Peaklist.Select(p => (Peak)p).Take(4).ToList();
                result.FitScore = PeakFitter.GetFit(theorPeakList, observedIsoList, 0.05, WorkflowParameters.MSToleranceInPPM);

                // fit score O18 profile
                var o18Iso = ((O16O18IqResult)result).ConvertO16ProfileToO18(target.TheorIsotopicProfile, 4);
                theorPeakList   = o18Iso.Peaklist.Select(p => (Peak)p).ToList();
                observedIsoList = result.ObservedIsotopicProfile.Peaklist.Cast <Peak>().Skip(4).ToList();    //skips the first 4 peaks and thus includes the O18 double label isotopic profile
                ((O16O18IqResult)result).FitScoreO18Profile = PeakFitter.GetFit(theorPeakList, observedIsoList, 0.05, WorkflowParameters.MSToleranceInPPM);

                //get i_score
                iscore = InterferenceScorer.GetInterferenceScore(result.ObservedIsotopicProfile, mspeakList);

                //get ppm error
                var massErrorInDaltons = TheorMostIntensePeakMassError(target.TheorIsotopicProfile, result.ObservedIsotopicProfile, target.ChargeState);
                var ppmError           = (massErrorInDaltons / target.MonoMassTheor) * 1e6;

                //Get Isotope Correlation
                var scan = lcscanset.PrimaryScanNumber;

                var sigma = target.ChromPeak.Width / 2.35;
                var chromScanWindowWidth = 4 * sigma;

                //Determines where to start and stop chromatogram correlation
                var startScan = scan - (int)Math.Round(chromScanWindowWidth / 2, 0);
                var stopScan  = scan + (int)Math.Round(chromScanWindowWidth / 2, 0);

                result.CorrelationData          = ChromatogramCorrelator.CorrelateData(Run, result, startScan, stopScan);
                result.LcScanObs                = lcscanset.PrimaryScanNumber;
                result.ChromPeakSelected        = target.ChromPeak;
                result.LCScanSetSelected        = new ScanSet(lcscanset.PrimaryScanNumber);
                result.IsotopicProfileFound     = true;
                result.InterferenceScore        = iscore;
                result.IsIsotopicProfileFlagged = hasPeakTotheLeft;
                result.NETError                    = netError;
                result.MassErrorBefore             = ppmError;
                result.IqResultDetail.MassSpectrum = massSpectrumXYData;
                result.Abundance                   = GetAbundance(result);
            }
        }
Beispiel #25
0
 public void DoWorkflow()
 {
     _result = CreateResult(this);
     DoWorkflow(_result);
 }
Beispiel #26
0
 protected void DoWorkflow(IqResult iqResult)
 {
     Workflow.Execute(iqResult);
 }
Beispiel #27
0
 public void AddResult(IqResult result)
 {
     result.ParentResult = this;
     _childResults.Add(result);
 }
Beispiel #28
0
        /// <summary>
        /// Calculates Metrics based on ChromPeakIqTarget
        /// NET Error, Mass Error, Isotopic Fit, & Isotope Correlation
        /// </summary>
        protected override void ExecuteWorkflow(IqResult result)
        {
            result.IsExported = false;

            if (MSGenerator == null)
            {
                MSGenerator = MSGeneratorFactory.CreateMSGenerator(Run.MSFileType);
                MSGenerator.IsTICRequested = false;
            }

            var target = result.Target as ChromPeakIqTarget;

            if (target == null)
            {
                throw new NullReferenceException("The ChromPeakAnalyzerIqWorkflow only works with the ChromPeakIqTarget.");
            }

            MSGenerator.MinMZ = target.MZTheor - 2;
            MSGenerator.MaxMZ = target.MZTheor + 5;

            //Sums Scan

            var lcscanset = _chromPeakUtilities.GetLCScanSetForChromPeak(target.ChromPeak, Run, WorkflowParameters.NumMSScansToSum);

            //Generate a mass spectrum
            var massSpectrumXYData = MSGenerator.GenerateMS(Run, lcscanset);

            //massSpectrumXYData = massSpectrumXYData.TrimData(result.Target.MZTheor - 5, result.Target.MZTheor + 15);

            //Find isotopic profile
            List <Peak> mspeakList;

            result.ObservedIsotopicProfile = TargetedMSFeatureFinder.IterativelyFindMSFeature(massSpectrumXYData, target.TheorIsotopicProfile, out mspeakList);


            //Get NET Error
            var netError = target.ChromPeak.NETValue - target.ElutionTimeTheor;


            var leftOfMonoPeakLooker = new LeftOfMonoPeakLooker();
            var peakToTheLeft        = leftOfMonoPeakLooker.LookforPeakToTheLeftOfMonoPeak(target.TheorIsotopicProfile.getMonoPeak(), target.ChargeState, mspeakList);

            var hasPeakTotheLeft = peakToTheLeft != null;

            if (result.ObservedIsotopicProfile == null)
            {
                result.IsotopicProfileFound = false;
                result.FitScore             = 1;
            }
            else
            {
                //Get fit score
                var observedIsoList      = result.ObservedIsotopicProfile.Peaklist.Cast <Peak>().ToList();
                var minIntensityForScore = 0.05;
                var fitScore             = PeakFitter.GetFit(target.TheorIsotopicProfile.Peaklist.Select(p => (Peak)p).ToList(), observedIsoList, minIntensityForScore, WorkflowParameters.MSToleranceInPPM);

                //get i_score
                var iscore = InterferenceScorer.GetInterferenceScore(result.ObservedIsotopicProfile, mspeakList);

                //get ppm error
                var massErrorInDaltons = TheorMostIntensePeakMassError(target.TheorIsotopicProfile, result.ObservedIsotopicProfile, target.ChargeState);
                var ppmError           = (massErrorInDaltons / target.MonoMassTheor) * 1e6;

                //Get Isotope Correlation
                var    scan = lcscanset.PrimaryScanNumber;
                double chromScanWindowWidth = target.ChromPeak.Width * 2;

                //Determines where to start and stop chromatogram correlation
                var startScan = scan - (int)Math.Round(chromScanWindowWidth / 2, 0);
                var stopScan  = scan + (int)Math.Round(chromScanWindowWidth / 2, 0);

                result.CorrelationData             = ChromatogramCorrelator.CorrelateData(Run, result, startScan, stopScan);
                result.LcScanObs                   = lcscanset.PrimaryScanNumber;
                result.ChromPeakSelected           = target.ChromPeak;
                result.LCScanSetSelected           = new ScanSet(lcscanset.PrimaryScanNumber);
                result.IsotopicProfileFound        = true;
                result.FitScore                    = fitScore;
                result.InterferenceScore           = iscore;
                result.IsIsotopicProfileFlagged    = hasPeakTotheLeft;
                result.NETError                    = netError;
                result.MassErrorBefore             = ppmError;
                result.IqResultDetail.MassSpectrum = massSpectrumXYData;
                result.Abundance                   = GetAbundance(result);
            }

            Display(result);
        }
        //Captured what the original IqWorkflow does
        protected override void ExecuteWorkflow(IqResult result)
        {
            var peakSelector = ChromPeakSelector as IqSmartChromPeakSelector;

            //Executes the ChargeState level children workflows
            var children = result.Target.ChildTargets();

            foreach (var child in children)
            {
                child.DoWorkflow();
                var childResult = child.GetResult();

                var peakTargetList = new List <ChromPeakIqTarget>();
                var peakTargets    = child.ChildTargets();
                foreach (ChromPeakIqTarget target in peakTargets)
                {
                    peakTargetList.Add(target);
                }

                var filterOutFlagged = childResult.Target.TheorIsotopicProfile.GetIndexOfMostIntensePeak() == 0;

                var chromPeakTarget = peakSelector.SelectBestPeak(peakTargetList, filterOutFlagged);

                if (chromPeakTarget != null)
                {
                    var chromPeakResult = chromPeakTarget.GetResult();

                    childResult.ChromPeakSelected = chromPeakTarget.ChromPeak;

                    childResult.LcScanObs = chromPeakResult.LcScanObs;

                    childResult.LCScanSetSelected = chromPeakResult.LCScanSetSelected;

                    childResult.IqResultDetail.MassSpectrum = chromPeakResult.IqResultDetail.MassSpectrum;

                    TrimData(childResult.IqResultDetail.MassSpectrum, childResult.Target.MZTheor, MsLeftTrimAmount, MsRightTrimAmount);

                    childResult.ObservedIsotopicProfile = chromPeakResult.ObservedIsotopicProfile;

                    childResult.FitScore = chromPeakResult.FitScore;

                    childResult.NETError = chromPeakResult.NETError;

                    childResult.InterferenceScore = chromPeakResult.InterferenceScore;

                    childResult.CorrelationData = chromPeakResult.CorrelationData;

                    childResult.MonoMassObs = chromPeakResult.ObservedIsotopicProfile == null
                                                  ? 0
                                                  : chromPeakResult.ObservedIsotopicProfile.MonoIsotopicMass;

                    childResult.MZObs = chromPeakResult.ObservedIsotopicProfile == null
                                            ? 0
                                            : chromPeakResult.ObservedIsotopicProfile.MonoPeakMZ;


                    childResult.MZObsCalibrated = chromPeakResult.ObservedIsotopicProfile == null
                                            ? 0
                                            : Run.GetAlignedMZ(childResult.MZObs, chromPeakResult.LcScanObs);


                    childResult.MonoMassObsCalibrated = (childResult.MZObsCalibrated - DeconTools.Backend.Globals.PROTON_MASS) * childResult.Target.ChargeState;

                    childResult.MassErrorBefore = chromPeakResult.ObservedIsotopicProfile == null
                                            ? 0
                                            : chromPeakResult.MassErrorBefore;


                    childResult.MassErrorAfter = (childResult.MZObsCalibrated - childResult.Target.MZTheor) / childResult.Target.MZTheor * 1e6;


                    var elutionTime = childResult.ChromPeakSelected == null ? 0d : ((ChromPeak)childResult.ChromPeakSelected).NETValue;
                    childResult.ElutionTimeObs = elutionTime;

                    childResult.Abundance = GetAbundance(childResult);
                }
            }
        }