private int GetScanData(XRawFileIO reader, clsScanInfo scanInfo, out double[] mzList, out double[] intensityList)
        {
            if (scanInfo.IsFTMS)
            {
                var labelDataCount = reader.GetScanLabelData(scanInfo.ScanNumber, out var labelData);

                if (labelDataCount > 0)
                {
                    mzList        = new double[labelDataCount];
                    intensityList = new double[labelDataCount];

                    for (var i = 0; i < labelDataCount; i++)
                    {
                        mzList[i]        = labelData[i].Mass;
                        intensityList[i] = labelData[i].Intensity;
                    }

                    return(labelDataCount);
                }
            }

            var dataPointCount = reader.GetScanData(scanInfo.ScanNumber, out mzList, out intensityList, 0, true);

            return(dataPointCount);
        }
예제 #2
0
        private static void TestReader(string rawFilePath, bool centroid = false, bool testSumming = false, int scanStart = 0, int scanEnd = 0)
        {
            try
            {
                var rawFile = ResolveDataFile(rawFilePath);
                if (rawFile == null)
                {
                    return;
                }

                var options = new ThermoReaderOptions {
                    LoadMSMethodInfo = mLoadMethods
                };

                using (var reader = new XRawFileIO(rawFile.FullName, options, mTraceMode))
                {
                    RegisterEvents(reader);

                    var numScans = reader.GetNumScans();

                    var collisionEnergyList = string.Empty;

                    ShowMethod(reader);

                    var scanStep = 1;

                    if (scanStart < 1)
                    {
                        scanStart = 1;
                    }

                    if (scanEnd < 1)
                    {
                        scanEnd  = numScans;
                        scanStep = 21;
                    }
                    else
                    {
                        if (scanEnd < scanStart)
                        {
                            scanEnd = scanStart;
                        }
                    }

                    if (scanEnd > numScans)
                    {
                        scanEnd = numScans;
                    }

                    var msLevelStats = new Dictionary <int, int>();

                    Console.WriteLine();
                    Console.WriteLine("Reading data for scans {0} to {1}, step {2}", scanStart, scanEnd, scanStep);

                    for (var scanNum = scanStart; scanNum <= scanEnd; scanNum += scanStep)
                    {
                        if (scanNum > reader.ScanEnd)
                        {
                            ConsoleMsgUtils.ShowWarning("Exiting for loop since scan number {0} is greater than the max scan number, {1}", scanNum, reader.ScanEnd);
                            break;
                        }

                        if (mOnlyLoadMSLevelInfo)
                        {
                            var msLevel = reader.GetMSLevel(scanNum);

                            if (msLevelStats.TryGetValue(msLevel, out var msLevelObsCount))
                            {
                                msLevelStats[msLevel] = msLevelObsCount + 1;
                            }
                            else
                            {
                                msLevelStats.Add(msLevel, 1);
                            }
                            if (mScanInfoInterval <= 0 || scanNum % mScanInfoInterval == 0)
                            {
                                Console.WriteLine("Scan " + scanNum);
                            }

                            continue;
                        }

                        var success = reader.GetScanInfo(scanNum, out clsScanInfo scanInfo);

                        if (!success)
                        {
                            continue;
                        }

                        if (mScanInfoInterval <= 0 || scanNum % mScanInfoInterval == 0)
                        {
                            Console.WriteLine("Scan " + scanNum + " at " + scanInfo.RetentionTime.ToString("0.00") + " minutes: " + scanInfo.FilterText);
                        }

                        if (mLoadCollisionEnergies)
                        {
                            var collisionEnergies = reader.GetCollisionEnergy(scanNum);

                            if (collisionEnergies.Count == 0)
                            {
                                collisionEnergyList = string.Empty;
                            }
                            else if (collisionEnergies.Count >= 1)
                            {
                                collisionEnergyList = collisionEnergies[0].ToString("0.0");

                                if (collisionEnergies.Count > 1)
                                {
                                    for (var index = 1; index <= collisionEnergies.Count - 1; index++)
                                    {
                                        collisionEnergyList += ", " + collisionEnergies[index].ToString("0.0");
                                    }
                                }
                            }

                            if (string.IsNullOrEmpty(collisionEnergyList))
                            {
                                Console.WriteLine();
                            }
                            else
                            {
                                Console.WriteLine("; CE " + collisionEnergyList);
                            }
                        }

                        if (mGetScanEvents)
                        {
                            if (scanInfo.TryGetScanEvent("Monoisotopic M/Z:", out var monoMZ))
                            {
                                Console.WriteLine("Monoisotopic M/Z: " + monoMZ);
                            }

                            if (scanInfo.TryGetScanEvent("Charge State", out var chargeState, true))
                            {
                                Console.WriteLine("Charge State: " + chargeState);
                            }

                            if (scanInfo.TryGetScanEvent("MS2 Isolation Width", out var isolationWidth, true))
                            {
                                Console.WriteLine("MS2 Isolation Width: " + isolationWidth);
                            }
                        }

                        if (!mLoadScanData || (scanNum % 50 != 0 && scanEnd - scanStart > 50))
                        {
                            continue;
                        }

                        // Get the data for scan scanNum
                        Console.WriteLine();
                        Console.WriteLine("Spectrum for scan " + scanNum);

                        reader.GetScanData(scanNum, out var mzList, out var intensityList, 0, centroid);

                        var mzDisplayStepSize = 50;
                        if (centroid)
                        {
                            mzDisplayStepSize = 1;
                        }

                        for (var i = 0; i <= mzList.Length - 1; i += mzDisplayStepSize)
                        {
                            Console.WriteLine("  " + mzList[i].ToString("0.000") + " mz   " + intensityList[i].ToString("0"));
                        }
                        Console.WriteLine();

                        const int scansToSum = 15;

                        if (scanNum + scansToSum < numScans && testSumming)
                        {
                            // Get the data for scan scanNum through scanNum + 15

#pragma warning disable 618
                            reader.GetScanDataSumScans(scanNum, scanNum + scansToSum, out var massIntensityPairs, 0, centroid);
#pragma warning restore 618

                            Console.WriteLine("Summed spectrum, scans " + scanNum + " through " + (scanNum + scansToSum));

                            for (var i = 0; i <= massIntensityPairs.GetLength(1) - 1; i += 50)
                            {
                                Console.WriteLine("  " + massIntensityPairs[0, i].ToString("0.000") + " mz   " +
                                                  massIntensityPairs[1, i].ToString("0"));
                            }

                            Console.WriteLine();
                        }

                        if (!scanInfo.IsFTMS)
                        {
                            continue;
                        }

                        var dataCount = reader.GetScanLabelData(scanNum, out var ftLabelData);

                        Console.WriteLine();
                        Console.WriteLine("{0,12}{1,12}{2,12}{3,12}{4,12}{5,12}", "Mass", "Intensity", "Resolution", "Baseline", "Noise", "Charge");


                        for (var i = 0; i <= dataCount - 1; i += 50)
                        {
                            Console.WriteLine("{0,12:F3}{1,12:0}{2,12:0}{3,12:F1}{4,12:0}{5,12:0}",
                                              ftLabelData[i].Mass,
                                              ftLabelData[i].Intensity,
                                              ftLabelData[i].Resolution,
                                              ftLabelData[i].Baseline,
                                              ftLabelData[i].Noise,
                                              ftLabelData[i].Charge);
                        }

                        dataCount = reader.GetScanPrecisionData(scanNum, out var ftPrecisionData);

                        Console.WriteLine();
                        Console.WriteLine("{0,12}{1,12}{2,12}{3,12}{4,12}", "Mass", "Intensity", "AccuracyMMU", "AccuracyPPM", "Resolution");


                        for (var i = 0; i <= dataCount - 1; i += 50)
                        {
                            Console.WriteLine("{0,12:F3}{1,12:0}{2,12:F3}{3,12:F3}{4,12:0}",
                                              ftPrecisionData[i].Mass,
                                              ftPrecisionData[i].Intensity, ftPrecisionData[i].AccuracyMMU,
                                              ftPrecisionData[i].AccuracyPPM,
                                              ftPrecisionData[i].Resolution);
                        }
                    }

                    if (mOnlyLoadMSLevelInfo)
                    {
                        Console.WriteLine();
                        Console.WriteLine("{0,-10} {1}", "MSLevel", "Scans");
                        foreach (var item in msLevelStats)
                        {
                            Console.WriteLine("{0, -10} {1}", item.Key, item.Value);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ShowError("Error in TestReader: " + ex.Message, ex);
            }
        }
예제 #3
0
        /// <summary>
        /// Looks for the reporter ion m/z values, +/- a tolerance
        /// Calls AggregateIonsInRange with returnMax = True, meaning we're reporting the maximum ion abundance for each reporter ion m/z
        /// </summary>
        /// <param name="rawFileReader"></param>
        /// <param name="dataAggregation"></param>
        /// <param name="includeFtmsColumns"></param>
        /// <param name="sicOptions"></param>
        /// <param name="scanList"></param>
        /// <param name="spectraCache"></param>
        /// <param name="currentScan"></param>
        /// <param name="writer"></param>
        /// <param name="reporterIons"></param>
        /// <param name="delimiter"></param>
        /// <param name="saveUncorrectedIntensities"></param>
        /// <param name="saveObservedMasses"></param>
        /// <remarks></remarks>
        private void FindReporterIonsWork(
            XRawFileIO rawFileReader,
            clsDataAggregation dataAggregation,
            bool includeFtmsColumns,
            clsSICOptions sicOptions,
            clsScanList scanList,
            clsSpectraCache spectraCache,
            clsScanInfo currentScan,
            TextWriter writer,
            IList <clsReporterIonInfo> reporterIons,
            char delimiter,
            bool saveUncorrectedIntensities,
            bool saveObservedMasses)
        {
            const bool USE_MAX_ABUNDANCE_IN_WINDOW = true;

            // The following will be a value between 0 and 100
            // Using Absolute Value of percent change to avoid averaging both negative and positive values
            double parentIonMZ;

            if (currentScan.FragScanInfo.ParentIonInfoIndex >= 0 && currentScan.FragScanInfo.ParentIonInfoIndex < scanList.ParentIons.Count)
            {
                parentIonMZ = scanList.ParentIons[currentScan.FragScanInfo.ParentIonInfoIndex].MZ;
            }
            else
            {
                parentIonMZ = 0;
            }

            if (!spectraCache.GetSpectrum(currentScan.ScanNumber, out var spectrum, true))
            {
                SetLocalErrorCode(clsMASIC.eMasicErrorCodes.ErrorUncachingSpectrum);
                return;
            }

            // Initialize the arrays used to track the observed reporter ion values
            var reporterIntensities          = new double[reporterIons.Count];
            var reporterIntensitiesCorrected = new double[reporterIons.Count];
            var closestMZ = new double[reporterIons.Count];

            // Initialize the output variables
            var dataColumns = new List <string>()
            {
                sicOptions.DatasetID.ToString(),
                currentScan.ScanNumber.ToString(),
                currentScan.FragScanInfo.CollisionMode,
                StringUtilities.DblToString(parentIonMZ, 2),
                StringUtilities.DblToString(currentScan.BasePeakIonIntensity, 2),
                StringUtilities.DblToString(currentScan.BasePeakIonMZ, 4)
            };

            var reporterIntensityList    = new List <string>(reporterIons.Count);
            var obsMZList                = new List <string>(reporterIons.Count);
            var uncorrectedIntensityList = new List <string>(reporterIons.Count);

            var ftmsSignalToNoise = new List <string>(reporterIons.Count);
            var ftmsResolution    = new List <string>(reporterIons.Count);
            //var ftmsLabelDataMz = new List<string>(reporterIons.Count);

            double reporterIntensityMax = 0;

            // Find the reporter ion intensities
            // Also keep track of the closest m/z for each reporter ion
            // Note that we're using the maximum intensity in the range (not the sum)
            for (var reporterIonIndex = 0; reporterIonIndex < reporterIons.Count; reporterIonIndex++)
            {
                var ion = reporterIons[reporterIonIndex];
                // Search for the reporter ion MZ in this mass spectrum
                reporterIntensities[reporterIonIndex] = dataAggregation.AggregateIonsInRange(
                    spectrum,
                    ion.MZ,
                    ion.MZToleranceDa,
                    out _,
                    out closestMZ[reporterIonIndex],
                    USE_MAX_ABUNDANCE_IN_WINDOW);

                ion.SignalToNoise = 0;
                ion.Resolution    = 0;
                ion.LabelDataMZ   = 0;
            }

            if (includeFtmsColumns && currentScan.IsFTMS)
            {
                // Retrieve the label data for this spectrum

                rawFileReader.GetScanLabelData(currentScan.ScanNumber, out var ftLabelData);

                // Find each reporter ion in ftLabelData

                for (var reporterIonIndex = 0; reporterIonIndex < reporterIons.Count; reporterIonIndex++)
                {
                    var mzToFind         = reporterIons[reporterIonIndex].MZ;
                    var mzToleranceDa    = reporterIons[reporterIonIndex].MZToleranceDa;
                    var highestIntensity = 0.0;
                    var udtBestMatch     = new udtFTLabelInfoType();
                    var matchFound       = false;

                    foreach (var labelItem in ftLabelData)
                    {
                        // Compare labelItem.Mass (which is m/z of the ion in labelItem) to the m/z of the current reporter ion
                        if (Math.Abs(mzToFind - labelItem.Mass) > mzToleranceDa)
                        {
                            continue;
                        }

                        // m/z is within range
                        if (labelItem.Intensity > highestIntensity)
                        {
                            udtBestMatch     = labelItem;
                            highestIntensity = labelItem.Intensity;
                            matchFound       = true;
                        }
                    }

                    if (matchFound)
                    {
                        reporterIons[reporterIonIndex].SignalToNoise = udtBestMatch.SignalToNoise;
                        reporterIons[reporterIonIndex].Resolution    = udtBestMatch.Resolution;
                        reporterIons[reporterIonIndex].LabelDataMZ   = udtBestMatch.Mass;
                    }
                }
            }

            // Populate reporterIntensitiesCorrected with the data in reporterIntensities
            Array.Copy(reporterIntensities, reporterIntensitiesCorrected, reporterIntensities.Length);
            if (mOptions.ReporterIons.ReporterIonApplyAbundanceCorrection)
            {
                if (mOptions.ReporterIons.ReporterIonMassMode == clsReporterIons.eReporterIonMassModeConstants.ITraqFourMZ ||
                    mOptions.ReporterIons.ReporterIonMassMode == clsReporterIons.eReporterIonMassModeConstants.ITraqEightMZHighRes ||
                    mOptions.ReporterIons.ReporterIonMassMode == clsReporterIons.eReporterIonMassModeConstants.ITraqEightMZLowRes ||
                    mOptions.ReporterIons.ReporterIonMassMode == clsReporterIons.eReporterIonMassModeConstants.TMTTenMZ ||
                    mOptions.ReporterIons.ReporterIonMassMode == clsReporterIons.eReporterIonMassModeConstants.TMTElevenMZ ||
                    mOptions.ReporterIons.ReporterIonMassMode == clsReporterIons.eReporterIonMassModeConstants.TMTSixteenMZ)
                {
                    // Correct the reporter ion intensities using the Reporter Ion Intensity Corrector class

                    if (intensityCorrector.ReporterIonMode != mOptions.ReporterIons.ReporterIonMassMode ||
                        intensityCorrector.ITraq4PlexCorrectionFactorType != mOptions.ReporterIons.ReporterIonITraq4PlexCorrectionFactorType)
                    {
                        intensityCorrector.UpdateReporterIonMode(
                            mOptions.ReporterIons.ReporterIonMassMode,
                            mOptions.ReporterIons.ReporterIonITraq4PlexCorrectionFactorType);
                    }

                    // Count the number of non-zero data points in reporterIntensitiesCorrected()
                    var positiveCount = 0;
                    for (var reporterIonIndex = 0; reporterIonIndex < reporterIons.Count; reporterIonIndex++)
                    {
                        if (reporterIntensitiesCorrected[reporterIonIndex] > 0)
                        {
                            positiveCount += 1;
                        }
                    }

                    // Apply the correction if 2 or more points are non-zero
                    if (positiveCount >= 2)
                    {
                        intensityCorrector.ApplyCorrection(reporterIntensitiesCorrected);
                    }
                }
            }

            // Now construct the string of intensity values, delimited by delimiter
            // Will also compute the percent change in intensities

            // Initialize the variables used to compute the weighted average percent change
            double pctChangeSum         = 0;
            double originalIntensitySum = 0;

            for (var reporterIonIndex = 0; reporterIonIndex < reporterIons.Count; reporterIonIndex++)
            {
                if (!reporterIons[reporterIonIndex].ContaminantIon)
                {
                    // Update the PctChange variables and the IntensityMax variable only if this is not a Contaminant Ion

                    originalIntensitySum += reporterIntensities[reporterIonIndex];

                    if (reporterIntensities[reporterIonIndex] > 0)
                    {
                        // Compute the percent change, then update pctChangeSum
                        var pctChange =
                            (reporterIntensitiesCorrected[reporterIonIndex] - reporterIntensities[reporterIonIndex]) /
                            reporterIntensities[reporterIonIndex];

                        // Using Absolute Value here to prevent negative changes from cancelling out positive changes
                        pctChangeSum += Math.Abs(pctChange * reporterIntensities[reporterIonIndex]);
                    }

                    if (reporterIntensitiesCorrected[reporterIonIndex] > reporterIntensityMax)
                    {
                        reporterIntensityMax = reporterIntensitiesCorrected[reporterIonIndex];
                    }
                }

                if (!reporterIons[reporterIonIndex].ContaminantIon || saveUncorrectedIntensities)
                {
                    // Append the reporter ion intensity to reporterIntensityList
                    // We skip contaminant ions, unless saveUncorrectedIntensities is True, then we include them

                    reporterIntensityList.Add(StringUtilities.DblToString(reporterIntensitiesCorrected[reporterIonIndex], 2));

                    if (saveObservedMasses)
                    {
                        // Append the observed reporter mass value to obsMZList
                        obsMZList.Add(StringUtilities.DblToString(closestMZ[reporterIonIndex], 3));
                    }

                    if (saveUncorrectedIntensities)
                    {
                        // Append the original, uncorrected intensity value
                        uncorrectedIntensityList.Add(StringUtilities.DblToString(reporterIntensities[reporterIonIndex], 2));
                    }

                    if (includeFtmsColumns)
                    {
                        if (Math.Abs(reporterIons[reporterIonIndex].SignalToNoise) < float.Epsilon &&
                            Math.Abs(reporterIons[reporterIonIndex].Resolution) < float.Epsilon &&
                            Math.Abs(reporterIons[reporterIonIndex].LabelDataMZ) < float.Epsilon)
                        {
                            // A match was not found in the label data; display blanks (not zeroes)
                            ftmsSignalToNoise.Add(string.Empty);
                            ftmsResolution.Add(string.Empty);
                            //ftmsLabelDataMz.Add(string.Empty);
                        }
                        else
                        {
                            ftmsSignalToNoise.Add(StringUtilities.DblToString(reporterIons[reporterIonIndex].SignalToNoise, 2));
                            ftmsResolution.Add(StringUtilities.DblToString(reporterIons[reporterIonIndex].Resolution, 2));
                            //ftmsLabelDataMz.Add(StringUtilities.DblToString(reporterIons(reporterIonIndex).LabelDataMZ, 4));
                        }
                    }
                }
            }

            // Compute the weighted average percent intensity correction value
            float weightedAvgPctIntensityCorrection;

            if (originalIntensitySum > 0)
            {
                weightedAvgPctIntensityCorrection = (float)(pctChangeSum / originalIntensitySum * 100);
            }
            else
            {
                weightedAvgPctIntensityCorrection = 0;
            }

            // Resize the target list capacity to large enough to hold all data.
            dataColumns.Capacity = reporterIntensityList.Count + 3 + obsMZList.Count + uncorrectedIntensityList.Count +
                                   ftmsSignalToNoise.Count + ftmsResolution.Count;
            // Append the maximum reporter ion intensity then the individual reporter ion intensities
            dataColumns.Add(StringUtilities.DblToString(reporterIntensityMax, 2));
            dataColumns.AddRange(reporterIntensityList);

            // Append the weighted average percent intensity correction
            if (weightedAvgPctIntensityCorrection < float.Epsilon)
            {
                dataColumns.Add("0");
            }
            else
            {
                dataColumns.Add(StringUtilities.DblToString(weightedAvgPctIntensityCorrection, 1));
            }

            if (saveObservedMasses)
            {
                dataColumns.AddRange(obsMZList);
            }

            if (saveUncorrectedIntensities)
            {
                dataColumns.AddRange(uncorrectedIntensityList);
            }

            if (includeFtmsColumns)
            {
                dataColumns.AddRange(ftmsSignalToNoise);
                dataColumns.AddRange(ftmsResolution);

                // Uncomment to include the label data m/z value in the _ReporterIons.txt file
                //if (saveObservedMasses)
                //    dataColumns.AddRange(ftmsLabelDataMz)
            }

            writer.WriteLine(string.Join(delimiter.ToString(), dataColumns));
        }