public void deconWithRAPID_Then_ValidateTest1()
        {
            Run     run     = new XCaliburRun2(FileRefs.RawDataMSFiles.OrbitrapStdFile1);
            ScanSet scanSet = new ScanSet(6005);

            run.CurrentScanSet = scanSet;


            MSGenerator msgen = MSGeneratorFactory.CreateMSGenerator(run.MSFileType);

            DeconToolsPeakDetectorV2 peakDetector = new DeconToolsPeakDetectorV2(1.3, 2, DeconTools.Backend.Globals.PeakFitType.QUADRATIC, true);
            RapidDeconvolutor        decon        = new RapidDeconvolutor();
            ResultValidatorTask      validator    = new ResultValidatorTask();

            msgen.Execute(run.ResultCollection);
            peakDetector.Execute(run.ResultCollection);
            decon.Execute(run.ResultCollection);
            validator.Execute(run.ResultCollection);

            Assert.AreEqual(190, run.ResultCollection.ResultList.Count);
            IsosResult testResult = run.ResultCollection.ResultList[0];

            Assert.AreEqual(0.0213668719893332m, (decimal)testResult.InterferenceScore);

            //TestUtilities.DisplayMSFeatures(run.ResultCollection.ResultList);
        }
Example #2
0
        protected virtual void InitializeProcessingTasks()
        {
            MSGenerator  = MSGeneratorFactory.CreateMSGenerator(Run.MSFileType);
            PeakDetector = PeakDetectorFactory.CreatePeakDetector(NewDeconToolsParameters);
            Deconvolutor = DeconvolutorFactory.CreateDeconvolutor(NewDeconToolsParameters);

            //the new iThrash imports the _peaks.txt file
            if (Deconvolutor is DeconTools.Backend.ProcessingTasks.Deconvoluters.InformedThrashDeconvolutor)
            {
                _deconvolutorRequiresPeaksFile = true;
            }

            //Will initialize these but whether or not they are used are determined elsewhere
            ZeroFiller = new DeconToolsZeroFiller(NewDeconToolsParameters.MiscMSProcessingParameters.ZeroFillingNumZerosToFill);
            Smoother   = new SavitzkyGolaySmoother(NewDeconToolsParameters.MiscMSProcessingParameters.SavitzkyGolayNumPointsInSmooth,
                                                   NewDeconToolsParameters.MiscMSProcessingParameters.SavitzkyGolayOrder);

            FitScoreCalculator = new DeconToolsFitScoreCalculator();
            ScanResultUpdater  = new ScanResultUpdater(NewDeconToolsParameters.ScanBasedWorkflowParameters.ProcessMS2);
            ResultValidator    = new ResultValidatorTask();

            IsosResultExporter = IsosExporterFactory.CreateIsosExporter(Run.ResultCollection.ResultType, ExporterType,
                                                                        IsosOutputFileName);

            ScanResultExporter = ScansExporterFactory.CreateScansExporter(Run.MSFileType, ExporterType,
                                                                          ScansOutputFileName);

            if (!_deconvolutorRequiresPeaksFile)
            {
                PeakListExporter = PeakListExporterFactory.Create(ExporterType, Run.MSFileType, PeakListExporterTriggerValue,
                                                                  PeakListOutputFileName);
            }

            PeakToMSFeatureAssociator = new PeakToMSFeatureAssociator();
        }
        public SaturationIMSScanBasedWorkflow(DeconToolsParameters parameters, Run run, string outputFolderPath = null, BackgroundWorker backgroundWorker = null)
            : base(parameters, run, outputFolderPath, backgroundWorker)
        {
            Check.Require(run is UIMFRun, "Cannot create workflow. Run is required to be a UIMFRun for this type of workflow");

            PeakBRSaturatedPeakDetector = parameters.PeakDetectorParameters.PeakToBackgroundRatio * 0.75;

            _msGenerator  = new UIMF_MSGenerator();
            _peakDetector = new DeconToolsPeakDetectorV2(5, 3, Globals.PeakFitType.QUADRATIC, false);
            _zeroFiller   = new DeconToolsZeroFiller();

//#if Disable_DeconToolsV2
//            throw new NotImplementedException("Cannot use class SaturationIMSScanBasedWorkflow since support for C++ based DeconToolsV2 is disabled");
//#else
            _deconvolutor = new HornDeconvolutor(parameters)
            {
                MaxFitAllowed             = 0.9,
                MinPeptideBackgroundRatio = _peakDetector.PeakToBackgroundRatio
            };
//#endif

            AdjustMonoIsotopicMasses = true;

            Run.PeakList = new List <Peak>();
        }
Example #4
0
 public virtual void InitializeRunRelatedTasks()
 {
     if (Run != null)
     {
         MSGenerator = MSGeneratorFactory.CreateMSGenerator(this.Run.MSFileType);
     }
 }
        public SaturationIMSScanBasedWorkflow(DeconToolsParameters parameters, Run run, string outputDirectoryPath = null, BackgroundWorker backgroundWorker = null)
            : base(parameters, run, outputDirectoryPath, backgroundWorker)
        {
            Check.Require(run is UIMFRun, "Cannot create workflow. Run is required to be a UIMFRun for this type of workflow");

            PeakBRSaturatedPeakDetector = parameters.PeakDetectorParameters.PeakToBackgroundRatio * 0.75;

            _msGenerator  = new UIMF_MSGenerator();
            _peakDetector = new DeconToolsPeakDetectorV2(5, 3);
            _zeroFiller   = new DeconToolsZeroFiller();

            _deconvolutor = new HornDeconvolutor(parameters)
            {
                MaxFitAllowed             = 0.9,
                MinPeptideBackgroundRatio = _peakDetector.PeakToBackgroundRatio
            };

            AdjustMonoIsotopicMasses = true;

            Run.PeakList = new List <Peak>();
        }
        public void findMSFeaturesInOrbitrapData_Test1()
        {
            Run run = new XCaliburRun2(FileRefs.RawDataMSFiles.OrbitrapStdFile1);

            ScanSet scanSet = new ScanSet(6005);

            run.CurrentScanSet = scanSet;


            MSGenerator msgen = MSGeneratorFactory.CreateMSGenerator(run.MSFileType);

            DeconToolsPeakDetectorV2 peakDetector = new DeconToolsPeakDetectorV2(1.3, 2, DeconTools.Backend.Globals.PeakFitType.QUADRATIC, true);

            peakDetector.IsDataThresholded = true;

            RapidDeconvolutor decon = new RapidDeconvolutor();

            decon.IsNewFitCalculationPerformed = true;


            msgen.Execute(run.ResultCollection);
            peakDetector.Execute(run.ResultCollection);
            decon.Execute(run.ResultCollection);

            Assert.AreEqual(192, run.ResultCollection.ResultList.Count);

            //order and get the most intense msfeature
            run.ResultCollection.ResultList = run.ResultCollection.ResultList.OrderByDescending(p => p.IntensityAggregate).ToList();
            IsosResult testIso = run.ResultCollection.ResultList[0];

            Assert.AreEqual(20986588.375, testIso.IntensityAggregate);
            Assert.AreEqual(2, testIso.IsotopicProfile.ChargeState);
            Assert.AreEqual(0.00548633562231413m, (decimal)testIso.IsotopicProfile.Score);
            Assert.AreEqual(3, testIso.IsotopicProfile.Peaklist.Count);
            Assert.AreEqual(481.274105402604m, (decimal)testIso.IsotopicProfile.Peaklist[0].XValue);
            Assert.AreEqual(481.775412188198m, (decimal)testIso.IsotopicProfile.Peaklist[1].XValue);
            Assert.AreEqual(482.276820274024m, (decimal)testIso.IsotopicProfile.Peaklist[2].XValue);

            TestUtilities.DisplayMSFeatures(run.ResultCollection.ResultList);
        }
        public override void Execute()
        {
            InitializeWorkflow();

            PrepareOutputFolder(_workflowParameters.OutputFolder);

            string outputPeaksFileName = getOutputPeaksFilename();

            peakExporter = new PeakListTextExporter(Run.MSFileType, outputPeaksFileName);

            int numTotalScans = Run.ScanSetCollection.ScanSetList.Count;
            int scanCounter   = 0;

            if (Run.MSFileType == DeconTools.Backend.Globals.MSFileType.PNNL_UIMF)
            {
                var uimfrun = Run as UIMFRun;

                int numTotalFrames = uimfrun.ScanSetCollection.ScanSetList.Count;
                int frameCounter   = 0;

                foreach (var frameSet in uimfrun.ScanSetCollection.ScanSetList)
                {
                    frameCounter++;
                    uimfrun.CurrentScanSet = frameSet;
                    uimfrun.ResultCollection.MSPeakResultList.Clear();

                    foreach (var scanSet in uimfrun.IMSScanSetCollection.ScanSetList)
                    {
                        uimfrun.CurrentIMSScanSet = (IMSScanSet)scanSet;
                        MSGenerator.Execute(uimfrun.ResultCollection);
                        this._ms1PeakDetector.Execute(uimfrun.ResultCollection);
                    }
                    peakExporter.WriteOutPeaks(uimfrun.ResultCollection.MSPeakResultList);

                    if (frameCounter % 5 == 0 || scanCounter == numTotalFrames)
                    {
                        double percentProgress = frameCounter * 100 / numTotalFrames;
                        reportProgress(percentProgress);
                    }
                }
            }
            else
            {
                foreach (var scan in Run.ScanSetCollection.ScanSetList)
                {
                    scanCounter++;

                    Run.CurrentScanSet = scan;

                    Run.ResultCollection.MSPeakResultList.Clear();

                    MSGenerator.Execute(Run.ResultCollection);
                    if (Run.GetMSLevel(scan.PrimaryScanNumber) == 1)
                    {
                        this._ms1PeakDetector.Execute(Run.ResultCollection);
                    }
                    else
                    {
                        var dataIsCentroided = Run.IsDataCentroided(scan.PrimaryScanNumber);
                        if (dataIsCentroided)
                        {
                            _ms2PeakDetectorForCentroidedData.Execute(Run.ResultCollection);
                        }
                        else
                        {
                            _ms2PeakDetectorForProfileData.Execute(Run.ResultCollection);
                        }
                    }

                    peakExporter.WriteOutPeaks(Run.ResultCollection.MSPeakResultList);

                    if (scanCounter % 50 == 0 || scanCounter == numTotalScans)
                    {
                        double percentProgress = scanCounter * 100 / numTotalScans;
                        reportProgress(percentProgress);
                    }
                }
            }



            Run.ResultCollection.MSPeakResultList.Clear();
        }
        public List <ChromPeakQualityData> GetChromPeakQualityData(Run run, IqTarget target, List <Peak> chromPeakList)
        {
            var peakQualityList = new List <ChromPeakQualityData>();


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

            //iterate over peaks within tolerance and score each peak according to MSFeature quality
#if DEBUG
            var tempMinScanWithinTol = (int)run.NetAlignmentInfo.GetScanForNet(target.ElutionTimeTheor - Parameters.ChromNETTolerance);
            var tempMaxScanWithinTol = (int)run.NetAlignmentInfo.GetScanForNet(target.ElutionTimeTheor + Parameters.ChromNETTolerance);
            var tempCenterTol        = (int)run.NetAlignmentInfo.GetScanForNet(target.ElutionTimeTheor);


            Console.WriteLine("SmartPeakSelector --> NETTolerance= " + Parameters.ChromNETTolerance + ";  chromMinCenterMax= " +
                              tempMinScanWithinTol + "\t" + tempCenterTol + "" +
                              "\t" + tempMaxScanWithinTol);
            Console.WriteLine("MT= " + target.ID + ";z= " + target.ChargeState + "; mz= " + target.MZTheor.ToString("0.000") +
                              ";  ------------------------- PeaksWithinTol = " + chromPeakList.Count);
#endif



            //target.NumChromPeaksWithinTolerance = peaksWithinTol.Count;


            foreach (ChromPeak chromPeak in chromPeakList)
            {
                // TODO: Currently hard-coded to sum only 1 scan
                var lcscanset = _chromPeakUtilities.GetLCScanSetForChromPeak(chromPeak, run, 1);

                //generate a mass spectrum
                var massSpectrumXYData = MSGenerator.GenerateMS(run, lcscanset);

                //find isotopic profile
                var mspeakList  = new List <Peak>();
                var observedIso = TargetedMSFeatureFinder.IterativelyFindMSFeature(massSpectrumXYData, target.TheorIsotopicProfile, out mspeakList);

                double fitScore = 1;

                double iscore = 1;

                //get fit score
                fitScore = FitScoreCalc.CalculateFitScore(target.TheorIsotopicProfile, observedIso, massSpectrumXYData);

                //get i_score
                iscore = InterferenceScorer.GetInterferenceScore(target.TheorIsotopicProfile, mspeakList);

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


                var hasPeakTotheLeft = peakToTheLeft != null;

                //collect the results together


                var pq = new ChromPeakQualityData(chromPeak);

                if (observedIso == null)
                {
                    pq.IsotopicProfileFound = false;
                }
                else
                {
                    pq.IsotopicProfileFound     = true;
                    pq.Abundance                = observedIso.IntensityMostAbundant;
                    pq.FitScore                 = fitScore;
                    pq.InterferenceScore        = iscore;
                    pq.IsotopicProfile          = observedIso;
                    pq.IsIsotopicProfileFlagged = hasPeakTotheLeft;
                    pq.ScanLc = lcscanset.PrimaryScanNumber;
                }

                peakQualityList.Add(pq);
#if DEBUG
                pq.Display();
#endif
            }

            return(peakQualityList);
        }
Example #9
0
        protected override void IterateOverScans()
        {
            DeconMSnResults.Clear();
            _scanCounter = 0;

            var resultCounter = 0;

            foreach (var scanSet in Run.ScanSetCollection.ScanSetList)
            {
                _scanCounter++;

                if (BackgroundWorker != null)
                {
                    if (BackgroundWorker.CancellationPending)
                    {
                        return;
                    }
                }

                //check ms level
                var currentMSLevel = Run.GetMSLevel(scanSet.PrimaryScanNumber);

                if (currentMSLevel == 1)
                {
                    Run.ResultCollection.IsosResultBin.Clear();

                    Run.CurrentScanSet = scanSet;

                    MSGenerator.Execute(Run.ResultCollection);

                    _currentMS1XYValues = new XYData
                    {
                        Xvalues = Run.XYData.Xvalues,
                        Yvalues = Run.XYData.Yvalues
                    };

                    _currentMS1TICIntensity = Run.GetTICFromInstrumentInfo(scanSet.PrimaryScanNumber);

                    PeakDetector.Execute(Run.ResultCollection);
                    _currentMS1Peaks = new List <Peak>(Run.PeakList);
                }
                else if (currentMSLevel == 2)
                {
                    if (_currentMS1Peaks == null || _currentMS1Peaks.Count == 0)
                    {
                        continue;
                    }

                    var precursorInfo = Run.GetPrecursorInfo(scanSet.PrimaryScanNumber);
                    Run.CurrentScanSet = scanSet;
                    var inaccurateParentMZ = precursorInfo.PrecursorMZ;

                    resultCounter++;
                    var deconMSnResult = new DeconMSnResult {
                        ParentScan = Run.GetParentScan(scanSet.PrimaryScanNumber)
                    };
                    deconMSnResult.IonInjectionTime       = Run.GetIonInjectionTimeInMilliseconds(deconMSnResult.ParentScan);
                    deconMSnResult.ScanNum                = scanSet.PrimaryScanNumber;
                    deconMSnResult.OriginalMZTarget       = inaccurateParentMZ;
                    deconMSnResult.ParentScanTICIntensity = _currentMS1TICIntensity;

                    MSGenerator.Execute(Run.ResultCollection);

                    var lowerMZ = inaccurateParentMZ - 1.1;
                    var upperMZ = inaccurateParentMZ + 1.1;

                    var dataIsCentroided = Run.IsDataCentroided(scanSet.PrimaryScanNumber);
                    if (dataIsCentroided)
                    {
                        _ms2PeakDetectorForCentroidData.Execute(Run.ResultCollection);
                    }
                    else
                    {
                        _ms2PeakDetectorForProfileData.Execute(Run.ResultCollection);
                    }
                    var ms2Peaks = new List <Peak>(Run.PeakList);

                    var filteredMS1Peaks = _currentMS1Peaks.Where(p => p.XValue > lowerMZ && p.XValue < upperMZ).ToList();

                    IsotopicProfile selectedMS1Feature = null;
                    for (var attemptNum = 0; attemptNum < NumMaxAttemptsAtLowIntensitySpecies; attemptNum++)
                    {
                        var candidateMS1Features = GetCandidateMS1Features(inaccurateParentMZ, filteredMS1Peaks);

                        //if none were found, will regenerate MS1 spectrum and find peaks again
                        if (candidateMS1Features.Count == 0)
                        {
                            var numSummed = attemptNum * 2 + 3;
                            var ms1Scan   = precursorInfo.PrecursorScan;

                            var ms1ScanSet = new ScanSetFactory().CreateScanSet(Run, ms1Scan, numSummed);

                            //get MS1 mass spectrum again. This time sum spectra
                            Run.CurrentScanSet = ms1ScanSet;
                            MSGenerator.Execute(Run.ResultCollection);

                            //run MS1 peak detector, with greater sensitivity
                            var isLastAttempt = attemptNum >= NumMaxAttemptsAtLowIntensitySpecies - 2;    //need to do -2 because of the way the loop advances the counter.

                            if (isLastAttempt)
                            {
                                _superSensitiveMS1PeakDetector.MinX = lowerMZ;
                                _superSensitiveMS1PeakDetector.MaxX = upperMZ;
                                _superSensitiveMS1PeakDetector.Execute(Run.ResultCollection);
                                filteredMS1Peaks = new List <Peak>(Run.PeakList);
                            }
                            else
                            {
                                _moreSensitiveMS1PeakDetector.Execute(Run.ResultCollection);
                                var moreSensitiveMS1Peaks = new List <Peak>(Run.PeakList);
                                filteredMS1Peaks = moreSensitiveMS1Peaks.Where(p => p.XValue > lowerMZ && p.XValue < upperMZ).ToList();
                            }
                        }
                        else if (candidateMS1Features.Count == 1)
                        {
                            selectedMS1Feature = candidateMS1Features.First();
                            break;   //we found something, so no need for any further attempts
                        }
                        else
                        {
                            var highQualityCandidates = candidateMS1Features.Where(p => p.Score < 0.15).ToList();
                            if (highQualityCandidates.Count == 0)
                            {
                                selectedMS1Feature = candidateMS1Features.OrderByDescending(p => p.IntensityMostAbundantTheor).First();
                            }
                            else if (highQualityCandidates.Count == 1)
                            {
                                selectedMS1Feature = highQualityCandidates.First();
                            }
                            else
                            {
                                selectedMS1Feature = highQualityCandidates.OrderByDescending(p => p.IntensityMostAbundantTheor).First();
                            }

                            deconMSnResult.ExtraInfo = "Warning - multiple MSFeatures found for target parent MZ";
                            break;   //we found something, so no need for any further attempts
                        }
                    }

                    if (selectedMS1Feature != null)
                    {
                        deconMSnResult.ParentMZ           = selectedMS1Feature.MonoPeakMZ;
                        deconMSnResult.ParentChargeState  = selectedMS1Feature.ChargeState;
                        deconMSnResult.ParentIntensity    = selectedMS1Feature.IntensityMostAbundantTheor;
                        deconMSnResult.IntensityAggregate = selectedMS1Feature.IntensityMostAbundantTheor;
                        deconMSnResult.IsotopicProfile    = selectedMS1Feature;
                    }
                    else
                    {
                        var candidatePeaks = new List <Peak>();

                        foreach (var peak in filteredMS1Peaks)
                        {
                            var currentDiff = Math.Abs(peak.XValue - inaccurateParentMZ);

                            var toleranceInMZ = ToleranceInPPM * peak.XValue / 1e6;

                            if (currentDiff < toleranceInMZ)
                            {
                                candidatePeaks.Add(peak);
                            }
                        }

                        Peak selectedPeak = null;

                        if (candidatePeaks.Count == 0)
                        {
                            //cannot even find a suitable MS1 peak. So can't do anything
                        }
                        else if (candidatePeaks.Count == 1)
                        {
                            selectedPeak = candidatePeaks.First();
                        }
                        else
                        {
                            selectedPeak = candidatePeaks.OrderByDescending(p => p.Height).First();
                        }

                        if (selectedPeak != null)
                        {
                            deconMSnResult.ParentMZ          = selectedPeak.XValue;
                            deconMSnResult.ParentChargeState = 1;   //not sure what charge I should assign... Ask SangTae
                            deconMSnResult.ParentIntensity   = selectedPeak.Height;
                            deconMSnResult.IsotopicProfile   = null;
                            deconMSnResult.ExtraInfo         = "Failure code 1: No MSFeature, but peak found";
                        }
                        else
                        {
                            deconMSnResult.ParentMZ          = precursorInfo.PrecursorMZ; //could not find the accurate parentMZ, so just report what the instrument found.
                            deconMSnResult.ParentChargeState = 1;                         //not sure what charge I should assign... Ask SangTae
                            deconMSnResult.ParentIntensity   = 0;
                            deconMSnResult.IsotopicProfile   = null;
                            deconMSnResult.ExtraInfo         = "Failure code 2: No MSFeature or peak found";
                        }
                    }

                    //Build export data.
                    var outputString = GetMGFOutputString(Run, scanSet.PrimaryScanNumber, deconMSnResult, ms2Peaks);

                    var includeHeader = resultCounter == 1;
                    var summaryString = GetSummaryString(deconMSnResult, includeHeader);

                    var parentProfileString = GetParentProfileString(deconMSnResult, includeHeader);

                    if (ExportData)
                    {
                        WriteOutMainData(outputString);

                        WriteOutDeconMSnSummary(summaryString);

                        if (IsParentProfileDataExported)
                        {
                            WriteOutParentProfileInfoString(parentProfileString);
                        }
                    }

                    if (deconMSnResult.ParentIntensity > 0)
                    {
                        DeconMSnResults.Add(deconMSnResult);
                    }
                }
                else
                {
                    throw new ApplicationException(
                              "DeconMSn only works on MS1 and MS2 data; You are attempting MS3");
                }

                ReportProgress();
            }
        }
Example #10
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);
        }
Example #11
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);
            }
        }
        public override void Execute(ResultCollection resultList)
        {
            Check.Require(resultList.Run.CurrentMassTag != null, this.Name + " failed. MassTag was not defined.");

            var currentResult = resultList.GetTargetedResult(resultList.Run.CurrentMassTag);

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

            var mt = resultList.Run.CurrentMassTag;

            float normalizedElutionTime;

            if (currentResult.Run.CurrentMassTag.ElutionTimeUnit == DeconTools.Backend.Globals.ElutionTimeUnit.ScanNum)
            {
                normalizedElutionTime = resultList.Run.CurrentMassTag.ScanLCTarget / (float)currentResult.Run.GetNumMSScans();
            }
            else
            {
                normalizedElutionTime = resultList.Run.CurrentMassTag.NormalizedElutionTime;
            }

            //collect Chrom peaks that fall within the NET tolerance
            var peaksWithinTol = new List <ChromPeak>(); //

            foreach (ChromPeak peak in resultList.Run.PeakList)
            {
                if (Math.Abs(peak.NETValue - normalizedElutionTime) <= Parameters.NETTolerance)     //peak.NETValue was determined by the ChromPeakDetector or a future ChromAligner Task
                {
                    peaksWithinTol.Add(peak);
                }
            }

            var peakQualityList = new List <ChromPeakQualityData>();

            //iterate over peaks within tolerance and score each peak according to MSFeature quality

            var tempMinScanWithinTol = (int)resultList.Run.NetAlignmentInfo.GetScanForNet(normalizedElutionTime - Parameters.NETTolerance);
            var tempMaxScanWithinTol = (int)resultList.Run.NetAlignmentInfo.GetScanForNet(normalizedElutionTime + Parameters.NETTolerance);
            var tempCenterTol        = (int)resultList.Run.NetAlignmentInfo.GetScanForNet(normalizedElutionTime);

            IqLogger.Log.Debug("SmartPeakSelector --> NETTolerance= " + Parameters.NETTolerance + ";  chromMinCenterMax= " + tempMinScanWithinTol + "\t" + tempCenterTol + "" +
                               "\t" + tempMaxScanWithinTol);
            IqLogger.Log.Debug("MT= " + currentResult.Target.ID + ";z= " + currentResult.Target.ChargeState + "; mz= " + currentResult.Target.MZ.ToString("0.000") + ";  ------------------------- PeaksWithinTol = " + peaksWithinTol.Count);

            currentResult.NumChromPeaksWithinTolerance = peaksWithinTol.Count;
            currentResult.NumQualityChromPeaks         = -1;

            ChromPeak bestChromPeak;

            if (currentResult.NumChromPeaksWithinTolerance > _parameters.NumChromPeaksAllowed)
            {
                bestChromPeak = null;
            }
            else
            {
                foreach (var chromPeak in peaksWithinTol)
                {
                    var pq = new ChromPeakQualityData(chromPeak);
                    peakQualityList.Add(pq);

                    var lcscanSet = ChromPeakUtilities.GetLCScanSetForChromPeak(chromPeak, resultList.Run, _parameters.NumMSSummedInSmartSelector);
                    resultList.Run.CurrentScanSet = lcscanSet;

                    //This resets the flags and the scores on a given result
                    currentResult.ResetResult();

                    //generate a mass spectrum
                    msgen.Execute(resultList);

                    //find isotopic profile
                    TargetedMSFeatureFinder.Execute(resultList);

                    try
                    {
                        //get fit score
                        fitScoreCalc.Execute(resultList);

                        //get i_score
                        resultValidator.Execute(resultList);
                    }
                    catch (Exception)
                    {
                        currentResult.FailedResult = true;
                    }

                    //collect the results together



                    AddScoresToPeakQualityData(pq, currentResult);
#if DEBUG
                    IqLogger.Log.Debug(pq.Display() + Environment.NewLine);
#endif
                }

                //run a algorithm that decides, based on fit score mostly.
                bestChromPeak = determineBestChromPeak(peakQualityList, currentResult);
            }

            currentResult.ChromPeakQualityList = peakQualityList;

            if (Parameters.SummingMode == SummingModeEnum.SUMMINGMODE_STATIC)
            {
                resultList.Run.CurrentScanSet = ChromPeakUtilities.GetLCScanSetForChromPeak(bestChromPeak, resultList.Run, Parameters.NumScansToSum);
            }
            else
            {
                resultList.Run.CurrentScanSet = ChromPeakUtilities.GetLCScanSetForChromPeakBasedOnPeakWidth(bestChromPeak, resultList.Run,
                                                                                                            Parameters.AreaOfPeakToSumInDynamicSumming, Parameters.MaxScansSummedInDynamicSumming);
            }

            UpdateResultWithChromPeakAndLCScanInfo(currentResult, bestChromPeak);
        }
Example #13
0
 public override void InitializeRunRelatedTasks()
 {
     msgen = MSGeneratorFactory.CreateMSGenerator(this.Run.MSFileType);
 }
Example #14
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);
        }
        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);
                    }
                }
            }
        }
        public void NavigateToNextMs1MassSpectrum(Globals.ScanSelectionMode selectionMode = Globals.ScanSelectionMode.ASCENDING)
        {
            if (Run == null) return;

            if (Workflow == null) return;

            var workflowParameters = (TargetedWorkflowParameters)Workflow.WorkflowParameters;

            int nextPossibleMs;
            if (selectionMode == Globals.ScanSelectionMode.DESCENDING)
            {
                nextPossibleMs = CurrentLcScan - 1;
            }
            else
            {
                nextPossibleMs = CurrentLcScan + 1;
            }

            CurrentLcScan = Run.GetClosestMSScan(nextPossibleMs, selectionMode);

            if (_msGenerator == null)
            {
                _msGenerator = MSGeneratorFactory.CreateMSGenerator(Run.MSFileType);

            }

            var currentScanSet = _scanSetFactory.CreateScanSet(Run, CurrentLcScan, workflowParameters.NumMSScansToSum);
            MassSpecXyData = _msGenerator.GenerateMS(Run, currentScanSet);

            if (MassSpecXyData!=null)
            {
                MassSpecXyData = MassSpecXyData.TrimData(MsGraphMinX - 20, MsGraphMaxX + 20);
            }

            CreateMsPlotForScanByScanAnalysis(currentScanSet);
        }
Example #17
0
        public void GetUnsummedIntensitiesAndDetectSaturation(Run run, IEnumerable <IsosResult> resultList)
        {
            Check.Require(run != null, "SaturationDetector failed. Run is null");
            if (run == null)
            {
                return;
            }

            if (_msGenerator == null)
            {
                _msGenerator = MSGeneratorFactory.CreateMSGenerator(run.MSFileType);
            }

            if (run is UIMFRun uimfRun)
            {
                if (uimfRun.CurrentScanSet == null)
                {
                    throw new NullReferenceException("CurrentScanSet is null. You need to set it.");
                }
                if (uimfRun.CurrentIMSScanSet == null)
                {
                    throw new NullReferenceException("CurrentIMSScanSet is null. You need to set it.");
                }

                //this creates a FrameSet containing only the primary frame.  Therefore no summing will occur
                var lcScanSet = new ScanSet(uimfRun.CurrentScanSet.PrimaryScanNumber);

                //this creates a ScanSet containing only the primary scan.  Therefore no summing will occur
                var imsScanSet = new IMSScanSet(uimfRun.CurrentIMSScanSet.PrimaryScanNumber);

                //get the mass spectrum +/- 5 da from the range of the isotopicProfile

                uimfRun.CurrentScanSet    = lcScanSet;
                uimfRun.CurrentIMSScanSet = imsScanSet;
                _msGenerator.Execute(run.ResultCollection);
            }
            else
            {
                if (run.CurrentScanSet == null)
                {
                    throw new NullReferenceException("CurrentScanSet is null. You need to set it.");
                }

                //this creates a ScanSet containing only the primary scan.  Therefore no summing will occur
                var scanSet = new ScanSet(run.CurrentScanSet.PrimaryScanNumber);

                run.CurrentScanSet = scanSet;

                _msGenerator.Execute(run.ResultCollection);
            }

            foreach (var result in resultList)
            {
                var indexOfObsMostAbundant = result.IsotopicProfile.GetIndexOfMostIntensePeak();

                var mzOfMostAbundant = result.IsotopicProfile.Peaklist[indexOfObsMostAbundant].XValue;

                var indexOfUnsummedMostAbundantMZ = run.XYData.GetClosestXVal(mzOfMostAbundant);
                if (indexOfUnsummedMostAbundantMZ >= 0)
                {
                    result.IsotopicProfile.OriginalIntensity = run.XYData.Yvalues[indexOfUnsummedMostAbundantMZ];
                    result.IsotopicProfile.IsSaturated       = (result.IsotopicProfile.OriginalIntensity >=
                                                                SaturationThreshold);

                    if (result.IsotopicProfile.IsSaturated)
                    {
                        //problem is that with these saturated profiles, they are often truncated because another
                        //isotopic profile was falsely assigned to the back end of it. So we need to find more peaks that should
                        //belong to the saturated profile.
                        var theorTarget = new PeptideTarget
                        {
                            ChargeState      = (short)result.IsotopicProfile.ChargeState,
                            MonoIsotopicMass = result.IsotopicProfile.MonoIsotopicMass
                        };

                        theorTarget.MZ = (theorTarget.MonoIsotopicMass / theorTarget.ChargeState) + Globals.PROTON_MASS;

                        var averagineFormula = _tomIsotopicPatternGenerator.GetClosestAvnFormula(result.IsotopicProfile.MonoIsotopicMass, false);
                        theorTarget.IsotopicProfile  = _tomIsotopicPatternGenerator.GetIsotopePattern(averagineFormula, _tomIsotopicPatternGenerator.aafIsos);
                        theorTarget.EmpiricalFormula = averagineFormula;
                        theorTarget.CalculateMassesForIsotopicProfile(result.IsotopicProfile.ChargeState);

                        AssignMissingPeaksToSaturatedProfile(run.PeakList, result.IsotopicProfile, theorTarget.IsotopicProfile);

                        //goal is to find the index of the isotopic profile peaks of a peak that is not saturated

                        var indexOfGoodUnsaturatedPeak = -1;

                        for (var i = indexOfObsMostAbundant + 1; i < result.IsotopicProfile.Peaklist.Count; i++)
                        {
                            var indexUnsummedData = run.XYData.GetClosestXVal(result.IsotopicProfile.Peaklist[i].XValue);

                            var unsummedIntensity = run.XYData.Yvalues[indexUnsummedData];

                            if (unsummedIntensity < _minRelIntTheorProfile * SaturationThreshold)
                            {
                                indexOfGoodUnsaturatedPeak = i;
                                break;
                            }
                        }

                        AdjustSaturatedIsotopicProfile(result.IsotopicProfile, theorTarget.IsotopicProfile,
                                                       indexOfGoodUnsaturatedPeak);
                    }
                }

                //double summedIntensity = 0;
                //foreach (MSPeak peak in result.IsotopicProfile.Peaklist)
                //{
                //    int indexOfMZ = result.Run.XYData.GetClosestXVal(peak.XValue);
                //    if (indexOfMZ >= 0)
                //    {
                //        summedIntensity += result.Run.XYData.Yvalues[indexOfMZ];
                //    }
                //}

                //result.IsotopicProfile.OriginalTotalIsotopicAbundance = summedIntensity;
            }
        }
Example #18
0
        public void Execute()
        {
            InitializeWorkflow();

            if (Run.MSFileType == Globals.MSFileType.PNNL_UIMF)
            {
                IMSScanSetCollection = CreateIMSScanSetCollection();
            }

            LcScanSetCollection = CreateLcScanSetCollection();

            PrepareOutputDirectory(WorkflowParameters.OutputDirectory);

            var outputPeaksFilePath = getOutputPeaksFilename();

            peakExporter = new PeakListTextExporter(Run.MSFileType, outputPeaksFilePath);

            var numTotalScans = LcScanSetCollection.ScanSetList.Count;
            var lastProgress  = DateTime.UtcNow;

            using (var sw = new StreamWriter(new FileStream(outputPeaksFilePath, FileMode.Append, FileAccess.Write, FileShare.Read)))
            {
                if (Run.MSFileType == Globals.MSFileType.PNNL_UIMF && Run is UIMFRun uimfRun)
                {
                    var numTotalFrames = LcScanSetCollection.ScanSetList.Count;
                    var frameCounter   = 0;

                    foreach (var frameSet in LcScanSetCollection.ScanSetList)
                    {
                        frameCounter++;
                        uimfRun.CurrentScanSet = frameSet;
                        uimfRun.ResultCollection.MSPeakResultList.Clear();

                        foreach (var scanSet in IMSScanSetCollection.ScanSetList)
                        {
                            uimfRun.CurrentIMSScanSet = (IMSScanSet)scanSet;
                            MSGenerator.Execute(uimfRun.ResultCollection);
                            _ms1PeakDetector.Execute(uimfRun.ResultCollection);
                        }
                        peakExporter.WriteOutPeaks(sw, uimfRun.ResultCollection.MSPeakResultList);

                        if (DateTime.UtcNow.Subtract(lastProgress).TotalSeconds >= 1 || frameCounter == numTotalFrames)
                        {
                            lastProgress = DateTime.UtcNow;
                            var percentProgress = frameCounter * 100 / (double)numTotalFrames;
                            reportProgress(percentProgress);
                        }
                    }
                }
                else
                {
                    var scanCounter = 0;
                    foreach (var scan in LcScanSetCollection.ScanSetList)
                    {
                        scanCounter++;

                        Run.CurrentScanSet = scan;

                        Run.ResultCollection.MSPeakResultList.Clear();

                        MSGenerator.Execute(Run.ResultCollection);
                        if (Run.GetMSLevel(scan.PrimaryScanNumber) == 1)
                        {
                            _ms1PeakDetector.Execute(Run.ResultCollection);
                        }
                        else
                        {
                            var dataIsCentroided = Run.IsDataCentroided(scan.PrimaryScanNumber);
                            if (dataIsCentroided)
                            {
                                _ms2PeakDetectorForCentroidedData.Execute(Run.ResultCollection);
                            }
                            else
                            {
                                _ms2PeakDetectorForProfileData.Execute(Run.ResultCollection);
                            }
                        }

                        peakExporter.WriteOutPeaks(sw, Run.ResultCollection.MSPeakResultList);

                        if (DateTime.UtcNow.Subtract(lastProgress).TotalSeconds >= 1 || scanCounter == numTotalScans)
                        {
                            lastProgress = DateTime.UtcNow;
                            var percentProgress = scanCounter * 100 / (double)numTotalScans;
                            reportProgress(percentProgress);
                        }
                    }
                }
            }

            Run.ResultCollection.MSPeakResultList.Clear();
        }
        public void NavigateToNextMS1MassSpectrum(Globals.ScanSelectionMode selectionMode = Globals.ScanSelectionMode.ASCENDING)
        {
            if (Run == null) return;

            int nextPossibleMs;
            if (selectionMode == Globals.ScanSelectionMode.DESCENDING)
            {
                nextPossibleMs = CurrentLcScan - 1;
            }
            else if (selectionMode == Globals.ScanSelectionMode.ASCENDING)
            {
                nextPossibleMs = CurrentLcScan + 1;
            }
            else
            {
                nextPossibleMs = CurrentLcScan;
            }

            if (!ShowMsMsSpectra)
            {
                CurrentLcScan = Run.GetClosestMSScan(nextPossibleMs, selectionMode);
            }
            else
            {
                CurrentLcScan = nextPossibleMs;
            }

            if (_msGenerator == null)
            {
                _msGenerator = MSGeneratorFactory.CreateMSGenerator(Run.MSFileType);

            }

            CurrentScanSet = _scanSetFactory.CreateScanSet(Run, CurrentLcScan, NumMSScansToSum);
            MassSpecXYData = _msGenerator.GenerateMS(Run, CurrentScanSet);

            Peaks = new List<Peak>();
            if (MassSpecXYData != null)
            {
                if (Run.IsDataCentroided(CurrentLcScan))
                {

                    MassSpecXYData = ZeroFillCentroidData(MassSpecXYData);
                }

                //Trim the viewable mass spectrum, but leave some data so user can pan to the right and left
                MassSpecXYData = MassSpecXYData.TrimData(MSGraphMinX - 20, MSGraphMaxX + 20);

                //Use only the data within the viewing area for peak detection
                var xydataForPeakDetector = MassSpecXYData.TrimData(MSGraphMinX, MSGraphMaxX);
                Peaks = PeakDetector.FindPeaks(xydataForPeakDetector.Xvalues, xydataForPeakDetector.Yvalues);

            }

            CreateMSPlotForScanByScanAnalysis();

            _isInternalPeakListUpdate = true;
            SelectedPeak = Peaks.OrderByDescending(p => p.Height).FirstOrDefault();  //this triggers an XIC
            _isInternalPeakListUpdate = false;
        }