예제 #1
0
        private void initializeMassSpecData()
        {
            var massAnalyzer = RawData.GetScanEventForScanNumber(FirstScan).MassAnalyzer;

            if (massAnalyzer == MassAnalyzerType.MassAnalyzerFTMS)
            {
                spectrum = new Spectrum(RawData.GetCentroidStream(FirstScan, false));
            }
            else
            {
                spectrum = new Spectrum(RawData.GetSegmentedScanFromScanNumber(FirstScan, null));
            }
        }
예제 #2
0
        private static void WritePScans(string fileName,
                                        IRawDataPlus raw,
                                        List <PScan> scans)
        {
            var enumerator = raw.GetFilteredScanEnumerator(" ");

            foreach (var scanNumber in enumerator) // note in my tests serial is faster than Parallel.Foreach() (this involves disk access, so it makes sense)
            {
                //trailer iinformation is extracted via index
                var    trailers      = raw.GetTrailerExtraValues(scanNumber);
                var    trailerLabels = raw.GetTrailerExtraInformation(scanNumber);
                object chargeState   = 0;
                for (int i = 0; i < trailerLabels.Labels.Length; i++)
                {
                    if (trailerLabels.Labels[i] == "Charge State:")
                    {
                        chargeState = raw.GetTrailerExtraValue(scanNumber, i);
                        break;
                    }
                }
                var scanFilter = raw.GetFilterForScanNumber(scanNumber);
                var scanStats  = raw.GetScanStatsForScanNumber(scanNumber);

                CentroidStream centroidStream = new CentroidStream();

                //check for FT mass analyzer data
                if (scanFilter.MassAnalyzer == MassAnalyzerType.MassAnalyzerFTMS)
                {
                    centroidStream = raw.GetCentroidStream(scanNumber, false);
                }
                //check for IT mass analyzer data
                if (scanFilter.MassAnalyzer == MassAnalyzerType.MassAnalyzerITMS)
                {
                    var scanData = raw.GetSimplifiedScan(scanNumber);
                    centroidStream.Masses      = scanData.Masses;
                    centroidStream.Intensities = scanData.Intensities;
                }

                var msOrder = raw.GetScanEventForScanNumber(scanNumber).MSOrder;

                if (msOrder == MSOrderType.Ms)
                {
                    var pscan = GetPScan(scanStats, centroidStream, 1, fileName, Convert.ToInt32(chargeState));
                    scans.Add(pscan);
                }
                if (msOrder == MSOrderType.Ms2)
                {
                    var precursorMz = raw.GetScanEventForScanNumber(scanNumber).GetReaction(0).PrecursorMass;
                    var pscan       = GetPScan(scanStats, centroidStream, 2, fileName, precursorMz, Convert.ToInt32(chargeState));
                    scans.Add(pscan);
                }

                var t = raw.GetTrailerExtraValues(scanNumber);
            }

            WriteScans(scans, fileName);
        }
        /// <summary>
        /// Calculate the precursor peak intensity.
        /// </summary>
        /// <param name="rawFile">the RAW file object</param>
        /// <param name="precursorScanNumber">the precursor scan number</param>
        /// <param name="precursorMass">the precursor mass</param>
        protected static double?CalculatePrecursorPeakIntensity(IRawDataPlus rawFile, int precursorScanNumber,
                                                                double precursorMass)
        {
            double?precursorIntensity = null;

            // Get the scan from the RAW file
            var scan = Scan.FromFile(rawFile, precursorScanNumber);

            // Check if the scan has a centroid stream
            if (scan.HasCentroidStream)
            {
                var centroidStream = rawFile.GetCentroidStream(precursorScanNumber, false);
                if (scan.CentroidScan.Length > 0)
                {
                    for (var i = 0; i < centroidStream.Length; i++)
                    {
                        if (Math.Abs(precursorMass - centroidStream.Masses[i]) < Tolerance)
                        {
                            //Console.WriteLine(Math.Abs(precursorMass - centroidStream.Masses[i]));
                            //Console.WriteLine(precursorMass + " - " + centroidStream.Masses[i] + " - " +
                            //                  centroidStream.Intensities[i]);
                            precursorIntensity = centroidStream.Intensities[i];
                            break;
                        }
                    }
                }
            }
            else
            {
                rawFile.SelectInstrument(Device.MS, 1);

                IChromatogramSettings[] allSettings =
                {
                    new ChromatogramTraceSettings(TraceType.BasePeak)
                    {
                        Filter     = MsFilter,
                        MassRanges = new[]
                        {
                            new Range(precursorMass, precursorMass)
                        }
                    }
                };

                var data = rawFile.GetChromatogramData(allSettings, precursorScanNumber,
                                                       precursorScanNumber);
                var chromatogramTrace = ChromatogramSignal.FromChromatogramData(data);
                if (!chromatogramTrace.IsNullOrEmpty())
                {
                    precursorIntensity = chromatogramTrace[0].Intensities[0];
                }
            }

            return(precursorIntensity);
        }
예제 #4
0
        /// <summary>
        ///    implements
        ///    https://github.com/fgcz/rawrr/issues/43
        /// </summary>
        /// <param name="rawFile"></param>
        /// <param name="filename"></param>
        /// <param name="L"></param>
        public static void WriteCentroidSpectrumAsRcode(this IRawDataPlus rawFile, string filename, List <int> L)
        {
            int count         = 1;
            var trailerFields = rawFile.GetTrailerExtraHeaderInformation();
            int indexCharge   = rawFile.GetIndexOfPattern("Charge State");

            using (System.IO.StreamWriter file =
                       new System.IO.StreamWriter(filename))
            {
                foreach (int scanNumber in L)
                {
                    var scan           = Scan.FromFile(rawFile, scanNumber);
                    var scanStatistics = rawFile.GetScanStatsForScanNumber(scanNumber);
                    var centroidStream = rawFile.GetCentroidStream(scanNumber, false);
                    var scanEvent      = rawFile.GetScanEventForScanNumber(scanNumber);
                    var scanTrailer    = rawFile.GetTrailerExtraInformation(scanNumber);

                    file.WriteLine("e$Spectrum[[{0}]] <- list(", count++);
                    file.WriteLine("\tscan = {0},", scanNumber);
                    file.WriteLine("\trtinseconds = {0},", Math.Round(scanStatistics.StartTime * 60 * 1000) / 1000);
                    if (indexCharge > 0)
                    {
                        file.WriteLine("\tcharge = {0},", int.Parse(scanTrailer.Values.ToArray()[indexCharge]));
                    }
                    else
                    {
                        file.WriteLine("\tcharge = NA,");
                    }

                    try{
                        var reaction0 = scanEvent.GetReaction(0);
                        file.WriteLine("\tpepmass = {0},", reaction0.PrecursorMass);
                    }catch {
                        file.WriteLine("\tpepmass = NA,");
                    }

                    if (scanStatistics.IsCentroidScan && centroidStream.Length > 0)
                    {
                        file.WriteLine("\tmZ = c(" + string.Join(", ", centroidStream.Masses) + "),");
                        file.WriteLine("\tintensity = c(" + string.Join(", ", centroidStream.Intensities) + ")");
                    }
                    else
                    {
                        file.WriteLine("\tmZ = NULL,\n\tintensity = NULL");
                    }
                    file.WriteLine("\t)");
                }
            }
        }
예제 #5
0
        private static void Extract(this RawDataCollection rawData, IRawDataPlus rawFile, IEnumerable <int> scans, ProgressIndicator progress)
        {
            foreach (int scan in scans)
            {
                try
                {
                    rawData.centroidStreams.Add(scan, new CentroidStreamData(rawFile.GetCentroidStream(scan, false)));
                }
                catch (Exception e)
                {
                    Log.Error(e, "Failed during extraction of centroid stream {Scan}", scan);
                    throw e;
                }

                progress.Update();
            }
        }
        public double[] GetSpectrumNoises(int scanNumber)
        {
            var scanStatistics = rawFile.GetScanStatsForScanNumber(scanNumber);

            if (scanStatistics.IsCentroidScan)
            {
                var centroidStream = rawFile.GetCentroidStream(scanNumber, false);
                return(centroidStream.Noises.ToArray());
            }
            else
            {
                return(null);
            }
        }
예제 #7
0
        /// <summary>
        /// Get and set data from the mass spectrum
        /// </summary>
        /// <param name="inputRawFile"></param>
        private void GetSpectrumData(IRawDataPlus inputRawFile)
        {
            // Get the first and last scan from the RAW file
            int    firstScanNumber = inputRawFile.RunHeaderEx.FirstSpectrum;
            int    lastScanNumber  = inputRawFile.RunHeaderEx.LastSpectrum;
            string itHeaderParam   = "Ion Injection Time (ms)";

            // Set up empty variables to populate with mass spectrum data
            TICList           = new double[lastScanNumber];
            ITList            = new double[lastScanNumber];
            RetentionTimeList = new double[lastScanNumber];
            NoiseList         = new double[lastScanNumber];

            try
            {
                //get out information from mass spectra for each scan
                for (int scan = 0; scan <= (ScanNumList.Length - 1); scan++)
                {
                    int thisScan = ScanNumList[scan];
                    // get the scan statistics for this scan number
                    ScanStatistics scanStatistic = inputRawFile.GetScanStatsForScanNumber(thisScan);

                    //get the TIC
                    TICList[scan] = scanStatistic.TIC;
                    //get retention time
                    RetentionTimeList[scan] = inputRawFile.RetentionTimeFromScanNumber(thisScan);
                    ITList[scan]            = GetScanExtraDouble(inputRawFile, thisScan, itHeaderParam);

                    //get noise for peaks
                    LabelPeak[] labelPeaks = inputRawFile.GetCentroidStream(thisScan, true).GetLabelPeaks();
                    foreach (var labelPeak in labelPeaks)
                    {
                        NoiseList[scan] = labelPeak.Noise;
                        //todo: fix this for the loop
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write("Error in accessing spectrum data: " + ex);
            }
        }
예제 #8
0
        public static (CentroidStreamCollection centroids, SegmentScanCollection segments) MsData(IRawDataPlus rawFile, ScanIndex index)
        {
            rawFile.SelectInstrument(Device.MS, 1);
            CentroidStreamCollection centroids = new CentroidStreamCollection();
            SegmentScanCollection    segments  = new SegmentScanCollection();

            CentroidStream centroid;
            SegmentedScan  segment;

            var scans = index.allScans;
            //var lockTarget = new object(); // this is so we can keep track of progress in the parallel loop

            ProgressIndicator P = new ProgressIndicator(scans.Count(), "Extracting scan data");

            P.Start();

            foreach (int scan in scans.Keys)
            {
                // first get out the mass spectrum
                if (index.allScans[scan].MassAnalyzer == MassAnalyzerType.MassAnalyzerFTMS)
                {
                    centroid = rawFile.GetCentroidStream(scan, false);

                    centroids[scan] = new CentroidStreamData(centroid);
                }
                else
                {
                    segment = rawFile.GetSegmentedScanFromScanNumber(scan, null);

                    segments[scan] = new SegmentedScanData(segment);
                }
                //lock (lockTarget)
                //{
                //    P.Update();
                //}
                P.Update();
            }
            P.Done();

            return(centroids, segments);
        }
예제 #9
0
        private static MzSpectrum GetSpectrum(IRawDataPlus rawFile, IFilteringParams filterParams, int scanNumber, string scanFilter, int scanOrder)
        {
            MzSpectrum spectrum;

            double[] xArray;
            double[] yArray;

            if (string.IsNullOrEmpty(scanFilter))
            {
                return(new MzSpectrum(new double[0], new double[0], false));
            }

            var centroidStream = rawFile.GetCentroidStream(scanNumber, false);

            // PreferredMasses should be used if centroidStream data is null; it's probably ITMS data
            if (centroidStream.Masses == null || centroidStream.Intensities == null)
            {
                var scan = Scan.FromFile(rawFile, scanNumber);
                var mzs  = scan.PreferredMasses;
                xArray = scan.PreferredMasses;
                yArray = scan.PreferredIntensities;

                if (xArray == null || yArray == null)
                {
                    throw new MzLibException("Could not centroid data from scan " + scanNumber);
                }
            }
            else
            {
                xArray = centroidStream.Masses;
                yArray = centroidStream.Intensities;
            }

            if (filterParams != null &&
                xArray.Length > 0 &&
                (filterParams.MinimumAllowedIntensityRatioToBasePeakM.HasValue || filterParams.NumberOfPeaksToKeepPerWindow.HasValue) &&
                ((filterParams.ApplyTrimmingToMs1 && scanOrder == 1) || (filterParams.ApplyTrimmingToMsMs && scanOrder > 1)))
            {
                var count = xArray.Length;

                var mzArray        = new double[count];
                var intensityArray = new double[count];
                Array.Copy(xArray, mzArray, count);
                Array.Copy(yArray, intensityArray, count);

                var    scanStats     = rawFile.GetScanStatsForScanNumber(scanNumber);
                double scanRangeHigh = scanStats.HighMass;
                double scanRangeLow  = scanStats.LowMass;

                WindowModeHelper(ref intensityArray, ref mzArray, filterParams, scanRangeLow, scanRangeHigh);

                Array.Sort(mzArray, intensityArray);
                spectrum = new MzSpectrum(mzArray, intensityArray, false);
            }
            else
            {
                spectrum = new MzSpectrum(xArray, yArray, false);
            }

            return(spectrum);
        }
예제 #10
0
        /// <inheritdoc />
        public override void Write(IRawDataPlus rawFile, int firstScanNumber, int lastScanNumber)
        {
            ConfigureWriter(".mgf");
            using (Writer)
            {
                Log.Info("Processing " + (lastScanNumber - firstScanNumber + 1) + " scans");

                var lastScanProgress = 0;
                for (var scanNumber = firstScanNumber; scanNumber <= lastScanNumber; scanNumber++)
                {
                    if (!ParseInput.Verbose)
                    {
                        var scanProgress = (int)((double)scanNumber / (lastScanNumber - firstScanNumber + 1) * 100);
                        if (scanProgress % ProgressPercentageStep == 0)
                        {
                            if (scanProgress != lastScanProgress)
                            {
                                Console.Write("" + scanProgress + "% ");
                                lastScanProgress = scanProgress;
                            }
                        }
                    }

                    // Get each scan from the RAW file
                    var scan = Scan.FromFile(rawFile, scanNumber);

                    // Check to see if the RAW file contains label (high-res) data and if it is present
                    // then look for any data that is out of order
                    var time = rawFile.RetentionTimeFromScanNumber(scanNumber);

                    // Get the scan filter for this scan number
                    var scanFilter = rawFile.GetFilterForScanNumber(scanNumber);

                    // Get the scan event for this scan number
                    var scanEvent = rawFile.GetScanEventForScanNumber(scanNumber);

                    IReaction reaction = null;
                    switch (scanFilter.MSOrder)
                    {
                    case MSOrderType.Ms:
                        // Keep track of scan number for precursor reference
                        _precursorScanNumber = scanNumber;
                        break;

                    case MSOrderType.Ms2:
                        try
                        {
                            reaction = scanEvent.GetReaction(0);
                        }
                        catch (ArgumentOutOfRangeException exception)
                        {
                            Log.Warn("No reaction found for scan " + scanNumber);
                        }

                        goto default;

                    case MSOrderType.Ms3:
                    {
                        try
                        {
                            reaction = scanEvent.GetReaction(1);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            Log.Warn("No reaction found for scan " + scanNumber);
                        }

                        goto default;
                    }

                    default:
                        Writer.WriteLine("BEGIN IONS");
                        Writer.WriteLine($"TITLE={ConstructSpectrumTitle(scanNumber)}");
                        Writer.WriteLine($"SCANS={scanNumber}");
                        Writer.WriteLine(
                            $"RTINSECONDS={(time * 60).ToString(CultureInfo.InvariantCulture)}");

                        // trailer extra data list
                        var    trailerData    = rawFile.GetTrailerExtraInformation(scanNumber);
                        int?   charge         = null;
                        double?monoisotopicMz = null;
                        double?isolationWidth = null;
                        for (var i = 0; i < trailerData.Length; i++)
                        {
                            if (trailerData.Labels[i] == "Charge State:")
                            {
                                if (Convert.ToInt32(trailerData.Values[i]) > 0)
                                {
                                    charge = Convert.ToInt32(trailerData.Values[i]);
                                }
                            }

                            if (trailerData.Labels[i] == "Monoisotopic M/Z:")
                            {
                                monoisotopicMz = double.Parse(trailerData.Values[i], NumberStyles.Any,
                                                              CultureInfo.CurrentCulture);
                            }

                            if (trailerData.Labels[i] == "MS" + (int)scanFilter.MSOrder + " Isolation Width:")
                            {
                                isolationWidth = double.Parse(trailerData.Values[i], NumberStyles.Any,
                                                              CultureInfo.CurrentCulture);
                            }
                        }

                        if (reaction != null)
                        {
                            var selectedIonMz =
                                CalculateSelectedIonMz(reaction, monoisotopicMz, isolationWidth);

                            Writer.WriteLine("PEPMASS=" +
                                             selectedIonMz.ToString(CultureInfo.InvariantCulture));
                        }

                        // charge
                        if (charge != null)
                        {
                            // Scan polarity
                            var polarity = PositivePolarity;
                            if (scanFilter.Polarity == PolarityType.Negative)
                            {
                                polarity = NegativePolarity;
                            }

                            Writer.WriteLine($"CHARGE={charge}{polarity}");
                        }

                        // write the filter string
                        //Writer.WriteLine($"SCANEVENT={scanEvent.ToString()}");

                        // Check if the scan has a centroid stream
                        if (scan.HasCentroidStream && (scanEvent.ScanData == ScanDataType.Centroid ||
                                                       (scanEvent.ScanData == ScanDataType.Profile &&
                                                        !ParseInput.NoPeakPicking)))
                        {
                            var centroidStream = rawFile.GetCentroidStream(scanNumber, false);
                            if (scan.CentroidScan.Length > 0)
                            {
                                for (var i = 0; i < centroidStream.Length; i++)
                                {
                                    Writer.WriteLine(
                                        centroidStream.Masses[i].ToString("0.0000000",
                                                                          CultureInfo.InvariantCulture)
                                        + " "
                                        + centroidStream.Intensities[i].ToString("0.0000000000",
                                                                                 CultureInfo.InvariantCulture));
                                }
                            }
                        }
                        // Otherwise take the profile data
                        else
                        {
                            // Get the scan statistics from the RAW file for this scan number
                            var scanStatistics = rawFile.GetScanStatsForScanNumber(scanNumber);

                            // Get the segmented (low res and profile) scan data
                            var segmentedScan =
                                rawFile.GetSegmentedScanFromScanNumber(scanNumber, scanStatistics);
                            for (var i = 0; i < segmentedScan.Positions.Length; i++)
                            {
                                Writer.WriteLine(
                                    segmentedScan.Positions[i].ToString("0.0000000",
                                                                        CultureInfo.InvariantCulture)
                                    + " "
                                    + segmentedScan.Intensities[i].ToString("0.0000000000",
                                                                            CultureInfo.InvariantCulture));
                            }
                        }

                        Writer.WriteLine("END IONS");

                        Log.Debug("Spectrum written to file -- SCAN " + scanNumber);

                        break;
                    }
                }

                if (!ParseInput.Verbose)
                {
                    Console.WriteLine();
                }
            }
        }
예제 #11
0
        /// <summary>
        /// Construct a spectrum element for the given scan
        /// </summary>
        /// <param name="scanNumber">the scan number</param>
        /// <returns>The SpectrumType object</returns>
        private SpectrumType ConstructSpectrum(int scanNumber)
        {
            // Get each scan from the RAW file
            var scan = Scan.FromFile(_rawFile, scanNumber);

            // Get the scan filter for this scan number
            var scanFilter = _rawFile.GetFilterForScanNumber(scanNumber);

            // Get the scan event for this scan number
            var scanEvent = _rawFile.GetScanEventForScanNumber(scanNumber);
            var spectrum  = new SpectrumType
            {
                id = ConstructSpectrumTitle(scanNumber),
                defaultArrayLength = 0
            };

            // Add the ionization type if necessary
            if (!_ionizationTypes.ContainsKey(scanFilter.IonizationMode))
            {
                _ionizationTypes.Add(scanFilter.IonizationMode,
                                     OntologyMapping.IonizationTypes[scanFilter.IonizationMode]);
            }

            // Add the mass analyzer if necessary
            if (!_massAnalyzers.ContainsKey(scanFilter.MassAnalyzer) &&
                OntologyMapping.MassAnalyzerTypes.ContainsKey(scanFilter.MassAnalyzer))
            {
                _massAnalyzers.Add(scanFilter.MassAnalyzer, "IC" + (_massAnalyzers.Count + 1));
            }

            // Keep the CV params in a list and convert to array afterwards
            var spectrumCvParams = new List <CVParamType>
            {
                new CVParamType
                {
                    name      = "ms level",
                    accession = "MS:1000511",
                    value     = ((int)scanFilter.MSOrder).ToString(CultureInfo.InvariantCulture),
                    cvRef     = "MS"
                }
            };

            // Trailer extra data list
            var    trailerData      = _rawFile.GetTrailerExtraInformation(scanNumber);
            int?   charge           = null;
            double?monoisotopicMass = null;

            for (var i = 0; i < trailerData.Length; i++)
            {
                if (trailerData.Labels[i] == "Charge State:")
                {
                    if (Convert.ToInt32(trailerData.Values[i]) > 0)
                    {
                        charge = Convert.ToInt32(trailerData.Values[i]);
                    }
                }

                if (trailerData.Labels[i] == "Monoisotopic M/Z:")
                {
                    monoisotopicMass = double.Parse(trailerData.Values[i]);
                }
            }

            // Construct and set the scan list element of the spectrum
            var scanListType = ConstructScanList(scanNumber, scan, scanFilter, scanEvent, monoisotopicMass);

            spectrum.scanList = scanListType;

            switch (scanFilter.MSOrder)
            {
            case MSOrderType.Ms:
                spectrumCvParams.Add(new CVParamType
                {
                    accession = "MS:1000579",
                    cvRef     = "MS",
                    name      = "MS1 spectrum",
                    value     = ""
                });

                // Keep track of scan number for precursor reference
                _precursorScanNumber = scanNumber;

                break;

            case MSOrderType.Ms2:
                spectrumCvParams.Add(new CVParamType
                {
                    accession = "MS:1000580",
                    cvRef     = "MS",
                    name      = "MSn spectrum",
                    value     = ""
                });

                // Construct and set the precursor list element of the spectrum
                var precursorListType = ConstructPrecursorList(scanEvent, charge);
                spectrum.precursorList = precursorListType;
                break;

            case MSOrderType.Ng:
                break;

            case MSOrderType.Nl:
                break;

            case MSOrderType.Par:
                break;

            case MSOrderType.Any:
                break;

            case MSOrderType.Ms3:
                break;

            case MSOrderType.Ms4:
                break;

            case MSOrderType.Ms5:
                break;

            case MSOrderType.Ms6:
                break;

            case MSOrderType.Ms7:
                break;

            case MSOrderType.Ms8:
                break;

            case MSOrderType.Ms9:
                break;

            case MSOrderType.Ms10:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            // Scan polarity
            var polarityType = scanFilter.Polarity;

            switch (polarityType)
            {
            case PolarityType.Positive:
                spectrumCvParams.Add(new CVParamType
                {
                    accession = "MS:1000130",
                    cvRef     = "MS",
                    name      = "positive scan",
                    value     = ""
                });
                break;

            case PolarityType.Negative:
                spectrumCvParams.Add(new CVParamType
                {
                    accession = "MS:1000129",
                    cvRef     = "MS",
                    name      = "negative scan",
                    value     = ""
                });
                break;

            case PolarityType.Any:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            // Total ion current
            spectrumCvParams.Add(new CVParamType
            {
                name      = "total ion current",
                accession = "MS:1000285",
                value     = scan.ScanStatistics.TIC.ToString(CultureInfo.InvariantCulture),
                cvRef     = "MS"
            });

            double?basePeakMass      = null;
            double?basePeakIntensity = null;
            double?lowestObservedMz  = null;
            double?highestObservedMz = null;

            double[] masses      = null;
            double[] intensities = null;
            if (scan.HasCentroidStream)
            {
                var centroidStream = _rawFile.GetCentroidStream(scanNumber, false);
                if (scan.CentroidScan.Length > 0)
                {
                    basePeakMass      = centroidStream.BasePeakMass;
                    basePeakIntensity = centroidStream.BasePeakIntensity;
                    lowestObservedMz  = centroidStream.Masses[0];
                    highestObservedMz = centroidStream.Masses[centroidStream.Masses.Length - 1];
                    masses            = centroidStream.Masses;
                    intensities       = centroidStream.Intensities;

                    // Note that although the scan data type is profile,
                    // centroid data might be available
                    spectrumCvParams.Add(new CVParamType
                    {
                        accession = "MS:1000127",
                        cvRef     = "MS",
                        name      = "centroid spectrum",
                        value     = ""
                    });
                }
            }
            else
            {
                // Get the scan statistics from the RAW file for this scan number
                var scanStatistics = _rawFile.GetScanStatsForScanNumber(scanNumber);

                basePeakMass      = scanStatistics.BasePeakMass;
                basePeakIntensity = scanStatistics.BasePeakIntensity;

                // Get the segmented (low res and profile) scan data
                var segmentedScan = _rawFile.GetSegmentedScanFromScanNumber(scanNumber, scanStatistics);
                if (segmentedScan.Positions.Length > 0)
                {
                    lowestObservedMz  = segmentedScan.Positions[0];
                    highestObservedMz = segmentedScan.Positions[segmentedScan.Positions.Length - 1];
                    masses            = segmentedScan.Positions;
                    intensities       = segmentedScan.Intensities;

                    spectrumCvParams.Add(new CVParamType
                    {
                        accession = "MS:1000128",
                        cvRef     = "MS",
                        name      = "profile spectrum",
                        value     = ""
                    });
                }
            }

            // Base peak m/z
            if (basePeakMass != null)
            {
                spectrumCvParams.Add(new CVParamType
                {
                    name          = "base peak m/z",
                    accession     = "MS:1000504",
                    value         = basePeakMass.ToString(),
                    unitCvRef     = "MS",
                    unitName      = "m/z",
                    unitAccession = "MS:1000040",
                    cvRef         = "MS"
                });
            }

            // Base peak intensity
            if (basePeakMass != null)
            {
                spectrumCvParams.Add(new CVParamType
                {
                    name          = "base peak intensity",
                    accession     = "MS:1000505",
                    value         = basePeakIntensity.ToString(),
                    unitCvRef     = "MS",
                    unitName      = "number of detector counts",
                    unitAccession = "MS:1000131",
                    cvRef         = "MS"
                });
            }

            // Lowest observed mz
            if (lowestObservedMz != null)
            {
                spectrumCvParams.Add(new CVParamType
                {
                    name          = "lowest observed m/z",
                    accession     = "MS:1000528",
                    value         = lowestObservedMz.ToString(),
                    unitCvRef     = "MS",
                    unitAccession = "MS:1000040",
                    unitName      = "m/z",
                    cvRef         = "MS"
                });
            }

            // Highest observed mz
            if (highestObservedMz != null)
            {
                spectrumCvParams.Add(new CVParamType
                {
                    name          = "highest observed m/z",
                    accession     = "MS:1000527",
                    value         = highestObservedMz.ToString(),
                    unitAccession = "MS:1000040",
                    unitName      = "m/z",
                    unitCvRef     = "MS",
                    cvRef         = "MS"
                });
            }

            // Add the CV params to the spectrum
            spectrum.cvParam = spectrumCvParams.ToArray();

            // Binary data array list
            var binaryData = new List <BinaryDataArrayType>();

            // M/Z Data
            if (!masses.IsNullOrEmpty())
            {
                // Set the spectrum default array length
                spectrum.defaultArrayLength = masses.Length;

                var massesBinaryData =
                    new BinaryDataArrayType
                {
                    binary = GetZLib64BitArray(masses)
                };
                massesBinaryData.encodedLength =
                    (4 * Math.Ceiling((double)massesBinaryData
                                      .binary.Length / 3)).ToString(CultureInfo.InvariantCulture);
                massesBinaryData.cvParam =
                    new CVParamType[3];
                massesBinaryData.cvParam[0] =
                    new CVParamType
                {
                    accession     = "MS:1000514",
                    name          = "m/z array",
                    cvRef         = "MS",
                    unitName      = "m/z",
                    value         = "",
                    unitCvRef     = "MS",
                    unitAccession = "MS:1000040"
                };
                massesBinaryData.cvParam[1] =
                    new CVParamType
                {
                    accession = "MS:1000523",
                    name      = "64-bit float",
                    cvRef     = "MS",
                    value     = ""
                };
                massesBinaryData.cvParam[2] =
                    new CVParamType
                {
                    accession = "MS:1000574",
                    name      = "zlib compression",
                    cvRef     = "MS",
                    value     = ""
                };

                binaryData.Add(massesBinaryData);
            }

            // Intensity Data
            if (!intensities.IsNullOrEmpty())
            {
                // Set the spectrum default array length if necessary
                if (spectrum.defaultArrayLength == 0)
                {
                    spectrum.defaultArrayLength = masses.Length;
                }

                var intensitiesBinaryData =
                    new BinaryDataArrayType
                {
                    binary = GetZLib64BitArray(intensities)
                };
                intensitiesBinaryData.encodedLength =
                    (4 * Math.Ceiling((double)intensitiesBinaryData
                                      .binary.Length / 3)).ToString(CultureInfo.InvariantCulture);
                intensitiesBinaryData.cvParam =
                    new CVParamType[3];
                intensitiesBinaryData.cvParam[0] =
                    new CVParamType
                {
                    accession     = "MS:1000515",
                    name          = "intensity array",
                    cvRef         = "MS",
                    unitCvRef     = "MS",
                    unitAccession = "MS:1000131",
                    unitName      = "number of counts",
                    value         = ""
                };
                intensitiesBinaryData.cvParam[1] =
                    new CVParamType
                {
                    accession = "MS:1000523",
                    name      = "64-bit float",
                    cvRef     = "MS",
                    value     = ""
                };
                intensitiesBinaryData.cvParam[2] =
                    new CVParamType
                {
                    accession = "MS:1000574",
                    name      = "zlib compression",
                    cvRef     = "MS",
                    value     = ""
                };

                binaryData.Add(intensitiesBinaryData);
            }

            if (!binaryData.IsNullOrEmpty())
            {
                spectrum.binaryDataArrayList = new BinaryDataArrayListType
                {
                    count           = binaryData.Count.ToString(),
                    binaryDataArray = binaryData.ToArray()
                };
            }

            return(spectrum);
        }
        /// <inheritdoc />
        public override void Write(IRawDataPlus rawFile, int firstScanNumber, int lastScanNumber)
        {
            ConfigureWriter(".mgf");
            using (Writer)
            {
                for (var scanNumber = firstScanNumber; scanNumber <= lastScanNumber; scanNumber++)
                {
                    // Get each scan from the RAW file
                    var scan = Scan.FromFile(rawFile, scanNumber);

                    // Check to see if the RAW file contains label (high-res) data and if it is present
                    // then look for any data that is out of order
                    var time = rawFile.RetentionTimeFromScanNumber(scanNumber);

                    // Get the scan filter for this scan number
                    var scanFilter = rawFile.GetFilterForScanNumber(scanNumber);

                    // Get the scan event for this scan number
                    var scanEvent = rawFile.GetScanEventForScanNumber(scanNumber);

                    switch (scanFilter.MSOrder)
                    {
                    case MSOrderType.Ms:
                        // Keep track of scan number for precursor reference
                        _precursorScanNumber = scanNumber;
                        break;

                    case MSOrderType.Ms2:
                    {
                        if (scanEvent.ScanData == ScanDataType.Centroid ||
                            (scanEvent.ScanData == ScanDataType.Profile &&
                             (scan.HasCentroidStream || ParseInput.OutputFormat != OutputFormat.MGFNoProfileData)))
                        {
                            Writer.WriteLine("BEGIN IONS");
                            Writer.WriteLine($"TITLE={ConstructSpectrumTitle(scanNumber)}");
                            Writer.WriteLine($"SCANS={scanNumber}");
                            Writer.WriteLine($"RTINSECONDS={(time * 60).ToString(CultureInfo.InvariantCulture)}");
                            // Get the reaction information for the first precursor
                            try
                            {
                                var reaction      = scanEvent.GetReaction(0);
                                var precursorMass = reaction.PrecursorMass;
                                Writer.WriteLine("PEPMASS=" +
                                                 precursorMass.ToString("0.0000000", CultureInfo.InvariantCulture));
                                //var precursorIntensity = 0.0;
                                //GetPrecursorIntensity(rawFile, _precursorScanNumber, precursorMass);
                                //Writer.WriteLine(precursorIntensity != null
                                //    ? $"PEPMASS={precursorMass:F7} {precursorIntensity}"
                                //    : $"PEPMASS={precursorMass:F7}");
                            }
                            catch (ArgumentOutOfRangeException exception)
                            {
                                Log.Warn("No reaction found for scan " + scanNumber);
                            }

                            // trailer extra data list
                            var trailerData = rawFile.GetTrailerExtraInformation(scanNumber);
                            for (var i = 0; i < trailerData.Length; i++)
                            {
                                if (trailerData.Labels[i] == "Charge State:")
                                {
                                    if (Convert.ToInt32(trailerData.Values[i]) > 0)
                                    {
                                        Writer.WriteLine($"CHARGE={trailerData.Values[i]}+");
                                    }
                                }
                            }

                            // write the filter string
                            //Writer.WriteLine($"SCANEVENT={scanEvent.ToString()}");

                            // Check if the scan has a centroid stream
                            if (scan.HasCentroidStream)
                            {
                                var centroidStream = rawFile.GetCentroidStream(scanNumber, false);
                                if (scan.CentroidScan.Length > 0)
                                {
                                    for (var i = 0; i < centroidStream.Length; i++)
                                    {
                                        Writer.WriteLine(
                                            centroidStream.Masses[i].ToString("0.0000000",
                                                                              CultureInfo.InvariantCulture)
                                            + " "
                                            + centroidStream.Intensities[i].ToString("0.0000000",
                                                                                     CultureInfo.InvariantCulture));
                                    }
                                }
                            }
                            // Otherwise take the profile data
                            else
                            {
                                // Get the scan statistics from the RAW file for this scan number
                                var scanStatistics = rawFile.GetScanStatsForScanNumber(scanNumber);

                                // Get the segmented (low res and profile) scan data
                                var segmentedScan =
                                    rawFile.GetSegmentedScanFromScanNumber(scanNumber, scanStatistics);
                                for (var i = 0; i < segmentedScan.Positions.Length; i++)
                                {
                                    Writer.WriteLine(
                                        segmentedScan.Positions[i].ToString("0.0000000",
                                                                            CultureInfo.InvariantCulture)
                                        + " "
                                        + segmentedScan.Intensities[i].ToString("0.0000000000",
                                                                                CultureInfo.InvariantCulture));
                                }
                            }

                            Writer.WriteLine("END IONS");
                        }

                        break;
                    }
                    }
                }
            }
        }
예제 #13
0
        /// <inheritdoc />
        public override void Write(IRawDataPlus rawFile, int firstScanNumber, int lastScanNumber)
        {
            ConfigureWriter(".mgf");
            using (Writer)
            {
                for (var scanNumber = firstScanNumber; scanNumber <= lastScanNumber; scanNumber++)
                {
                    // Get each scan from the RAW file
                    var scan = Scan.FromFile(rawFile, scanNumber);

                    // Check to see if the RAW file contains label (high-res) data and if it is present
                    // then look for any data that is out of order
                    var time = rawFile.RetentionTimeFromScanNumber(scanNumber);

                    // Get the scan filter for this scan number
                    var scanFilter = rawFile.GetFilterForScanNumber(scanNumber);

                    // Get the scan event for this scan number
                    var scanEvent = rawFile.GetScanEventForScanNumber(scanNumber);

                    // Only consider MS2 spectra
                    if (scanFilter.MSOrder == MSOrderType.Ms2)
                    {
                        if (scanEvent.ScanData == ScanDataType.Centroid ||
                            (scanEvent.ScanData == ScanDataType.Profile && !ParseInput.ExcludeProfileData))
                        {
                            Writer.WriteLine("BEGIN IONS");
                            Writer.WriteLine($"TITLE={ConstructSpectrumTitle(scanNumber)}");
                            Writer.WriteLine($"SCAN={scanNumber}");
                            Writer.WriteLine($"RTINSECONDS={time * 60}");
                            // Get the reaction information for the first precursor
                            try
                            {
                                var reaction      = scanEvent.GetReaction(0);
                                var precursorMass = reaction.PrecursorMass;
                                Writer.WriteLine($"PEPMASS={precursorMass:F7}");
                            }
                            catch (ArgumentOutOfRangeException exception)
                            {
                                Log.Warn("No reaction found for scan " + scanNumber);
                            }

                            // trailer extra data list
                            var trailerData = rawFile.GetTrailerExtraInformation(scanNumber);
                            for (var i = 0; i < trailerData.Length; i++)
                            {
                                if (trailerData.Labels[i] == "Charge State:")
                                {
                                    if (Convert.ToInt32(trailerData.Values[i]) > 0)
                                    {
                                        Writer.WriteLine($"CHARGE={trailerData.Values[i]}+");
                                    }
                                }
                            }

                            // Check if the scan has a centroid stream
                            if (scan.HasCentroidStream)
                            {
                                var centroidStream = rawFile.GetCentroidStream(scanNumber, false);
                                if (scan.CentroidScan.Length > 0)
                                {
                                    for (var i = 0; i < centroidStream.Length; i++)
                                    {
                                        Writer.WriteLine(
                                            $"{centroidStream.Masses[i]:F7} {centroidStream.Intensities[i]:F10}");
                                    }
                                }
                            }
                            // Otherwise take the profile data
                            else
                            {
                                // Get the scan statistics from the RAW file for this scan number
                                var scanStatistics = rawFile.GetScanStatsForScanNumber(scanNumber);

                                // Get the segmented (low res and profile) scan data
                                var segmentedScan = rawFile.GetSegmentedScanFromScanNumber(scanNumber, scanStatistics);
                                for (var i = 0; i < segmentedScan.Positions.Length; i++)
                                {
                                    Writer.WriteLine(
                                        $"{segmentedScan.Positions[i]:F7} {segmentedScan.Intensities[i]:F10}");
                                }
                            }

                            Writer.WriteLine("END IONS");
                        }
                    }
                }
            }
        }
예제 #14
0
        /// <summary>
        /// Write the RAW files' spectra to a MGF file.
        /// </summary>
        /// <param name="rawFile">the RAW file interface</param>
        /// <param name="firstScanNumber">the first scan number</param>
        /// <param name="lastScanNumber">the last scan number</param>
        private void WriteSpectraToMgf(IRawDataPlus rawFile, int firstScanNumber, int lastScanNumber)
        {
            // Test centroid (high resolution/label) data
            using (var mgfFile =
                       File.CreateText(outputDirectory + "//" + rawFileNameWithoutExtension + ".mgf"))
            {
                for (int scanNumber = firstScanNumber; scanNumber <= lastScanNumber; scanNumber++)
                {
                    // Get each scan from the RAW file
                    var scan = Scan.FromFile(rawFile, scanNumber);

                    if (scan.HasCentroidStream)
                    {
                        // Check to see if the RAW file contains label (high-res) data and if it is present
                        // then look for any data that is out of order
                        double time = rawFile.RetentionTimeFromScanNumber(scanNumber);

                        // Get the scan filter for this scan number
                        var scanFilter = rawFile.GetFilterForScanNumber(scanNumber);

                        // Get the scan event for this scan number
                        var scanEvent = rawFile.GetScanEventForScanNumber(scanNumber);

                        // Get the ionizationMode, MS2 precursor mass, collision energy, and isolation width for each scan
                        if (scanFilter.MSOrder == ThermoFisher.CommonCore.Data.FilterEnums.MSOrderType.Ms2)
                        {
                            mgfFile.WriteLine("BEGIN IONS");
                            mgfFile.WriteLine($"TITLE={ConstructSpectrumTitle(scanNumber)}");
                            mgfFile.WriteLine($"SCAN={scanNumber}");
                            mgfFile.WriteLine($"RTINSECONDS={time * 60}");

                            // trailer extra data list
                            var trailerData = rawFile.GetTrailerExtraInformation(scanNumber);

                            for (int i = 0; i < trailerData.Length; i++)
                            {
                                if ((trailerData.Labels[i] == "Charge State:"))
                                {
                                    if (Convert.ToInt32(trailerData.Values[i]) > 0)
                                    {
                                        mgfFile.WriteLine($"CHARGE={trailerData.Values[i]}+");
                                    }
                                }
                            }

                            // Get the reaction information for the first precursor
                            var    reaction      = scanEvent.GetReaction(0);
                            double precursorMass = reaction.PrecursorMass;
                            mgfFile.WriteLine(
                                $"PEPMASS={precursorMass:F4}");
                            //$"PEPMASS={precursorMass:F2} {GetPrecursorIntensity(rawFile, scanNumber)}");
                            double collisionEnergy = reaction.CollisionEnergy;
                            mgfFile.WriteLine($"COLLISIONENERGY={collisionEnergy}");
                            var ionizationMode = scanFilter.IonizationMode;
                            mgfFile.WriteLine($"IONMODE={ionizationMode}");

                            var centroidStream = rawFile.GetCentroidStream(scanNumber, false);
                            if (scan.CentroidScan.Length > 0)
                            {
                                for (int i = 0; i < centroidStream.Length; i++)
                                {
                                    mgfFile.WriteLine(
                                        $"{centroidStream.Masses[i]:F7} {centroidStream.Intensities[i]:F10}");
                                }
                            }

                            mgfFile.WriteLine("END IONS");
                        }
                    }
                }
            }
        }
예제 #15
0
파일: Program.cs 프로젝트: Ykobe/metaCode
                    }
                }
                writer.Flush();
                startNum += 1;
            }
            writer.Close();

        }

        public static void getMSdataFromRT(double startRT, int endRT, string filePath, double lowMS = 0.00, double highMS = 0.00)
        {
            IRawDataPlus plus = RawFileReaderAdapter.FileFactory(filePath);

            plus.SelectInstrument(Device.MS, 1);
            if (highMS - 0.00 <= 0.01)
            {
                highMS = plus.RunHeaderEx.HighMass;
            }
            int startNum = plus.ScanNumberFromRetentionTime(startRT);
            int endNum = plus.ScanNumberFromRetentionTime(endRT);
            int maxNum = plus.RunHeaderEx.LastSpectrum > endNum ? endNum : plus.RunHeaderEx.LastSpectrum;

            string fileName = DateTime.Now.ToLocalTime().ToString().Replace("/", "").Replace(":", "").Replace(" ", "_") + ".csv";
            FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
            StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
            writer.WriteLine("ScanNumber, RT, Mass, Resolution, Intensity, Noise, Filter");
            while (startNum <= endNum)
            {
                Scan scan = Scan.FromFile(plus, startNum);
                string filter = plus.GetFilterForScanNumber(startNum).ToString();
                int cnt = 0;
                while (cnt < scan.PreferredMasses.Length)
                {
                    if (lowMS < scan.PreferredMasses[cnt] && scan.PreferredMasses[cnt] < highMS)
                    {
                        double rt = plus.RetentionTimeFromScanNumber(startNum);
                        double msval = scan.PreferredMasses[cnt];
                        double resolution = (scan.PreferredResolutions.Length == 0) ? 0.0 : scan.PreferredResolutions[cnt];
                        double intensity = (scan.PreferredIntensities.Length == 0) ? 0.0 : scan.PreferredIntensities[cnt];
                        double noise = (scan.PreferredNoises.Length == 0) ? 0.0 : scan.PreferredNoises[cnt];
                        //writer.WriteLine("{0},{1},{2},{3},{4},{5},{6}", startNum.ToString(), rt.ToString(), msval.ToString(), resolution.ToString(), intensity.ToString(), noise.ToString(), filter.ToString());

                        writer.WriteLine("{0},{1},{2},{3}", startNum.ToString(), rt.ToString(), msval.ToString(), intensity.ToString());
                    }
                    cnt += 1;
                }
                startNum += 1;
            }
            writer.Close();
        }

        public static void getSRMIacdMZ(string filePath, double valMS,int recVal)
        {
           IRawDataPlus plus = RawFileReaderAdapter.FileFactory(filePath);

            //////////////////////////////////
            plus.SelectInstrument(Device.MS, 1);
            /////////////////////////////////

            var startNum = plus.RunHeaderEx.FirstSpectrum;
            var endNum = plus.RunHeaderEx.LastSpectrum;

            string fileName = DateTime.Now.ToLocalTime().ToString().Replace("/", "").Replace(":", "").Replace(" ", "_") + ".csv";
            FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
            StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);

            double[] masses = null;
            double[] intensities = null;

            writer.WriteLine("ScanNumber, RT, Mass, Intensity");
            while (startNum <= endNum)
            {
                double rt = plus.RetentionTimeFromScanNumber(startNum);
                IScanFilter scanFilter = plus.GetFilterForScanNumber(startNum);
                if (scanFilter.MSOrder == MSOrderType.Ms)
                {
                    Scan scan = Scan.FromFile(plus, startNum);
                    IScanEvent scanEvent = plus.GetScanEventForScanNumber(startNum);
                    if (scan.HasCentroidStream && (scanEvent.ScanData == ScanDataType.Centroid || scanEvent.ScanData == ScanDataType.Profile))
                    {
                        var centroidStream = plus.GetCentroidStream(startNum, false);
                        if (scan.CentroidScan.Length > 0)
                        {
                            masses = centroidStream.Masses;
                            intensities = centroidStream.Intensities;
                        }
                    }
                    else
                    {
                        // Get the scan statistics from the RAW file for this scan number
                        var scanStatistics = plus.GetScanStatsForScanNumber(startNum);
                        // Get the segmented (low res and profile) scan data
                        var segmentedScan = plus.GetSegmentedScanFromScanNumber(startNum, scanStatistics);
                        if (segmentedScan.Positions.Length > 0)
                        {
                            masses = segmentedScan.Positions;
                            intensities = segmentedScan.Intensities;
                        }
                    }

                    for(int i = 0; i < masses.Length; ++ i)
                    {
                        masses[i] = Double.Parse(masses[i].ToString("n4"));
                    }

                    int front = 0;
                    int rear = masses.Length - 1;
                    int mid = front + ((rear - front) >> 1);
                    bool findVal = false;
                    while(front <= rear)
                    {
                        if (Double.Equals(masses[mid],valMS))
                        {
                            findVal = true;
                            break;
                        }
                        else if(masses[mid] < valMS)
                        {
                            front = mid + 1;
                        }
                        else
                        {
                            rear = mid  - 1;
                        }
                        mid = front + ((rear - front) >> 1);
                    }
                    if(findVal && intensities[mid] >= recVal)
                    {
                        writer.WriteLine("{0},{1},{2},{3}",startNum.ToString(), rt.ToString(), masses[mid].ToString(), intensities[mid].ToString());
                    }
                }
                writer.Flush();
                startNum += 1;
            }
            writer.Close();
        }
    }
}

예제 #16
0
        public static void ExtractAll(this RawDataCollection rawData, IRawDataPlus rawFile)
        {
            Log.Information("Beginning extraction of all possible data");
            rawFile.SelectInstrument(Device.MS, 1);
            rawData.ExtractPrecursorScans(rawFile);
            ProgressIndicator   P       = new ProgressIndicator(rawData.scanIndex.allScans.Count(), "Extracting raw data");
            TrailerExtraIndices indices = new TrailerExtraIndices(rawFile);

            for (int i = 1; i <= rawData.scanIndex.allScans.Count(); i++)
            {
                try
                {
                    // first get out the mass spectrum
                    if (rawData.scanIndex.allScans[i].MassAnalyzer == MassAnalyzerType.MassAnalyzerFTMS)
                    {
                        rawData.centroidStreams.Add(i, new CentroidStreamData(rawFile.GetCentroidStream(i, false)));
                    }
                    else
                    {
                        rawData.segmentedScans.Add(i, new SegmentedScanData(rawFile.GetSegmentedScanFromScanNumber(i, null)));
                    }

                    // add the trailer extra data
                    rawData.trailerExtras.Add(i, TrailerExtras.ExtractTrailerExtra(rawData, rawFile, i, indices));
                    rawData.Performed.Add(Operations.TrailerExtras);

                    // add the retention time
                    rawData.retentionTimes.Add(i, rawFile.RetentionTimeFromScanNumber(i));
                    rawData.Performed.Add(Operations.RetentionTimes);

                    // add the precursor mass
                    PrecursorMasses.ExtractPrecursorMasses(rawData, rawFile, i);
                    rawData.Performed.Add(Operations.PrecursorMasses);

                    P.Update();
                }
                catch (Exception e)
                {
                    Log.Error("Extraction failed on scan {Scan}", i);
                    throw e;
                }
            }

            if (rawData.methodData.AnalysisOrder == MSOrderType.Ms2 | rawData.methodData.AnalysisOrder == MSOrderType.Ms3)
            {
                rawData.Performed.Add(Operations.Ms1CentroidStreams);
                if (rawData.methodData.MassAnalyzers[MSOrderType.Ms2] == MassAnalyzerType.MassAnalyzerFTMS)
                {
                    rawData.Performed.Add(Operations.Ms2CentroidStreams);
                }
                else
                {
                    rawData.Performed.Add(Operations.Ms2SegmentedScans);
                }
            }
            if (rawData.methodData.AnalysisOrder == MSOrderType.Ms3)
            {
                if (rawData.methodData.MassAnalyzers[MSOrderType.Ms3] == MassAnalyzerType.MassAnalyzerFTMS)
                {
                    rawData.Performed.Add(Operations.Ms3CentroidStreams);
                }
                else
                {
                    rawData.Performed.Add(Operations.Ms3SegmentedScans);
                }
            }

            P.Done();
        }
예제 #17
0
        /// <summary>
        /// </summary>
        /// <param name="rawFile"></param>
        /// <param name="filename"></param>
        /// <param name="L"></param>
        public static void WriteSpectrumAsRcode(this IRawDataPlus rawFile, string filename, List <int> L)
        {
            int count               = 1;
            var trailerFields       = rawFile.GetTrailerExtraHeaderInformation();
            int indexCharge         = rawFile.GetIndexOfPattern("Charge State");
            int indexMonoisotopicmZ = rawFile.GetIndexOfPattern("MonoisotopicmZ");

            using (System.IO.StreamWriter file =
                       new System.IO.StreamWriter(filename))
            {
                foreach (int scanNumber in L)
                {
                    var basepeakMass      = -1.0;
                    var basepeakIntensity = -1.0;

                    var scanStatistics = rawFile.GetScanStatsForScanNumber(scanNumber);
                    var centroidStream = rawFile.GetCentroidStream(scanNumber, false);
                    var scanTrailer    = rawFile.GetTrailerExtraInformation(scanNumber);
                    var scanEvent      = rawFile.GetScanEventForScanNumber(scanNumber);

                    var scan = Scan.FromFile(rawFile, scanNumber);

                    file.WriteLine("e$Spectrum[[{0}]] <- list(", count++);
                    file.WriteLine("\tscan = {0},", scanNumber);

                    try
                    {
                        basepeakMass      = (scanStatistics.BasePeakMass);
                        basepeakIntensity = Math.Round(scanStatistics.BasePeakIntensity);
                        file.WriteLine("\tbasePeak = c({0}, {1}),", basepeakMass, basepeakIntensity);
                    }
                    catch
                    {
                        file.WriteLine("\tbasePeak = c(NA, NA),");
                    }
                    file.WriteLine("\tTIC = {0},", scanStatistics.TIC.ToString());
                    file.WriteLine("\tmassRange = c({0}, {1}),", scanStatistics.LowMass.ToString(), scanStatistics.HighMass.ToString());
                    file.WriteLine("\tscanType = \"{0}\",", scanStatistics.ScanType.ToString());
                    file.WriteLine("\trtinseconds = {0},", Math.Round(scanStatistics.StartTime * 60 * 1000) / 1000);
                    try
                    {
                        var reaction0 = scanEvent.GetReaction(0);
                        file.WriteLine("\tpepmass = {0},", reaction0.PrecursorMass);
                    }
                    catch
                    {
                        file.WriteLine("\tpepmass = NA,");
                    }

                    if (scanStatistics.IsCentroidScan && centroidStream.Length > 0)
                    {
                        // Get the centroid (label) data from the RAW file for this scan
                        file.WriteLine("\tcentroidStream = TRUE,");

                        file.WriteLine("\tHasCentroidStream = '{0}, Length={1}',", scan.HasCentroidStream, scan.CentroidScan.Length);
                        if (scan.HasCentroidStream)
                        {
                            file.WriteLine("\tcentroid.mZ = c(" + string.Join(", ", scan.CentroidScan.Masses.ToArray()) + "),");
                            file.WriteLine("\tcentroid.intensity = c(" + string.Join(", ", scan.CentroidScan.Intensities.ToArray()) + "),");
                        }

                        file.WriteLine("\ttitle = \"File: {0}; SpectrumID: {1}; scans: {2}\",",
                                       Path.GetFileName(rawFile.FileName),
                                       null,
                                       scanNumber);

                        if (indexMonoisotopicmZ > 0)
                        {
                            file.WriteLine("\tmonoisotopicMz = {0},", Convert.ToDouble(scanTrailer.Values.ToArray()[indexMonoisotopicmZ]));
                        }
                        else
                        {
                            file.WriteLine("\tmonoisotopicMz = NA,");
                        }


                        if (indexCharge > 0)
                        {
                            file.WriteLine("\tcharge = {0},", int.Parse(scanTrailer.Values.ToArray()[indexCharge]));
                        }
                        else
                        {
                            file.WriteLine("\tcharge = NA,");
                        }

                        file.WriteLine("\tmZ = c(" + string.Join(", ", centroidStream.Masses) + "),");
                        file.WriteLine("\tintensity = c(" + string.Join(", ", centroidStream.Intensities) + "),");
                        file.WriteLine("\tnoises = c(" + string.Join(", ", centroidStream.Noises) + "),");
                        file.WriteLine("\tresolutions = c(" + string.Join(", ", centroidStream.Resolutions.ToArray()) + "),");
                        file.WriteLine("\tcharges = c(" + string.Join(", ", centroidStream.Charges) + "),");
                        file.WriteLine("\tbaselines = c(" + string.Join(", ", centroidStream.Baselines) + "),");
                    }
                    else
                    {
                        file.WriteLine("\tcentroidStream = FALSE,");

                        file.WriteLine("\tHasCentroidStream = '{0}, Length={1}',", scan.HasCentroidStream, scan.CentroidScan.Length);
                        if (scan.HasCentroidStream)
                        {
                            file.WriteLine("\tcentroid.mZ = c(" + string.Join(",", scan.CentroidScan.Masses.ToArray()) + "),");
                            file.WriteLine("\tcentroid.intensity = c(" + string.Join(",", scan.CentroidScan.Intensities.ToArray()) + "),");
                        }

                        file.WriteLine("\ttitle = \"File: {0}; SpectrumID: {1}; scans: {2}\",",
                                       Path.GetFileName(rawFile.FileName),
                                       null,
                                       scanNumber);

                        if (indexCharge > 0)
                        {
                            file.WriteLine("\tcharge = {0},", int.Parse(scanTrailer.Values.ToArray()[indexCharge]));
                        }
                        else
                        {
                            file.WriteLine("\tcharge = NA,");
                        }

                        if (indexMonoisotopicmZ > 0)
                        {
                            file.WriteLine("\tmonoisotopicMz = {0},", Convert.ToDouble(scanTrailer.Values.ToArray()[indexMonoisotopicmZ]));
                        }
                        else
                        {
                            file.WriteLine("\tmonoisotopicMz = NA,");
                        }

                        file.WriteLine("\tmZ = c(" + string.Join(",", scan.SegmentedScan.Positions) + "),");
                        file.WriteLine("\tintensity = c(" + string.Join(",", scan.SegmentedScan.Intensities) + "),");
                        // file.WriteLine("\tnoises = c(" + string.Join(",", scan.SegmentedScan.Noises) + "),");
                    }
                    // ============= Instrument Data =============
                    // write scan Trailer
                    var trailerValues = scanTrailer.Values;
                    var trailerLabels = scanTrailer.Labels;
                    var zipTrailer    = trailerLabels.ToArray().Zip(trailerValues, (a, b) => string.Format("\t\"{0}\" = \"{1}\"", a, b));
                    file.WriteLine(string.Join(", \n", zipTrailer));
                    file.WriteLine(")");
                }
            }

            return;
        }
예제 #18
0
        /// <summary>
        /// Get the spectrum intensity.
        /// </summary>
        /// <param name="rawFile">the RAW file object</param>
        /// <param name="precursorScanNumber">the precursor scan number</param>
        /// <param name="precursorMass">the precursor mass</param>
        /// <param name="retentionTime">the retention time</param>
        /// <param name="isolationWidth">the isolation width</param>
        protected static double? GetPrecursorIntensity(IRawDataPlus rawFile, int precursorScanNumber,
            double precursorMass, double retentionTime, double? isolationWidth)
        {
            double? precursorIntensity = null;

            // Get the scan from the RAW file
            var scan = Scan.FromFile(rawFile, precursorScanNumber);

            // Check if the scan has a centroid stream
            if (scan.HasCentroidStream)
            {
                var centroidStream = rawFile.GetCentroidStream(precursorScanNumber, false);
                if (scan.CentroidScan.Length > 0)
                {
                    for (var i = 0; i < centroidStream.Length; i++)
                    {
                        if (Math.Abs(precursorMass - centroidStream.Masses[i]) < Tolerance)
                        {
                            //Console.WriteLine(Math.Abs(precursorMass - centroidStream.Masses[i]));
                            //Console.WriteLine(precursorMass + " - " + centroidStream.Masses[i] + " - " +
                            //                  centroidStream.Intensities[i]);
                            precursorIntensity = centroidStream.Intensities[i];
                            break;
                        }
                    }
                }
            }
            else
            {
                rawFile.SelectInstrument(Device.MS, 1);

                var component = new Component
                {
                    MassRange = new Limit
                    {
                        Low = (double) (precursorMass - isolationWidth / 2),
                        High = (double) (precursorMass + isolationWidth / 2)
                    },
                    RtRange = new Limit
                    {
                        Low = rawFile.RetentionTimeFromScanNumber(precursorScanNumber),
                        High = rawFile.RetentionTimeFromScanNumber(precursorScanNumber)
                    }
                };
                ;

                IChromatogramSettings[] allSettings =
                {
                    new ChromatogramTraceSettings(TraceType.MassRange)
                    {
                        Filter = Component.Filter,
                        MassRanges = new[]
                        {
                            new Range(component.MassRange.Low, component.MassRange.High)
                        }
                    }
                };

                var rtFilteredScans = rawFile.GetFilteredScansListByTimeRange("",
                    component.RtRange.Low,
                    component.RtRange.High);
                var data = rawFile.GetChromatogramData(allSettings, rtFilteredScans[0],
                    rtFilteredScans[rtFilteredScans.Count - 1]);

                var chromatogramTrace = ChromatogramSignal.FromChromatogramData(data);
            }

            return precursorIntensity;
        }