예제 #1
0
        /// <summary>
        /// Write the RAW file metadata to file.
        /// <param name="rawFile">the RAW file object</param>
        /// <param name="firstScanNumber">the first scan number</param>
        /// <param name="lastScanNumber">the last scan number</param>
        /// </summary>
        public void WriteJsonMetada(IRawDataPlus rawFile, int firstScanNumber, int lastScanNumber)
        {
            // Get the start and end time from the RAW file
            var startTime = rawFile.RunHeaderEx.StartTime;
            var endTime   = rawFile.RunHeaderEx.EndTime;

            var metadata = new Metadata();

            // File Properties
            metadata.addFileProperty(new CVTerm("NCIT:C47922", "NCIT", "Pathname", rawFile.FileName));
            metadata.addFileProperty(new CVTerm("NCIT:C25714", "NCIT", "Version",
                                                rawFile.FileHeader.Revision.ToString()));
            metadata.addFileProperty(new CVTerm("NCIT:C69199", "NCIT", "Content Creation Date",
                                                rawFile.FileHeader.CreationDate.ToString()));
            metadata.addFileProperty(new CVTerm("NCIT:C25365", "NCIT", "Description",
                                                rawFile.FileHeader.FileDescription));


            metadata.addScanSetting(new CVTerm("MS:1000016", "MS", "scan start time", startTime.ToString()));
            metadata.addScanSetting(new CVTerm("MS:1000011", "MS", "mass resolution",
                                               rawFile.RunHeaderEx.MassResolution.ToString()));
            metadata.addScanSetting(new CVTerm("UO:0000002", "MS", "mass unit",
                                               rawFile.GetInstrumentData().Units.ToString()));
            metadata.addScanSetting(new CVTerm("PRIDE:0000478", "PRIDE", "Number of scans",
                                               rawFile.RunHeaderEx.SpectraCount.ToString()));
            metadata.addScanSetting(new CVTerm("PRIDE:0000479", "PRIDE", "MS scan range",
                                               firstScanNumber + ":" + lastScanNumber));
            metadata.addScanSetting(new CVTerm("PRIDE:0000484", "PRIDE", "Retention time range",
                                               startTime + ":" + endTime));
            metadata.addScanSetting(new CVTerm("PRIDE:0000485", "PRIDE", "Mz range",
                                               rawFile.RunHeaderEx.LowMass + ":" + rawFile.RunHeaderEx.HighMass));

            metadata.addInstrumentProperty(new CVTerm("MS:1000494", "MS", "Thermo Scientific instrument model",
                                                      rawFile.GetInstrumentData().Model));
            metadata.addInstrumentProperty(new CVTerm("MS:1000496", "MS", "instrument attribute",
                                                      rawFile.GetInstrumentData().Name));
            metadata.addInstrumentProperty(new CVTerm("MS:1000529", "MS", "instrument serial number",
                                                      rawFile.GetInstrumentData().SerialNumber));

            var    msTypes   = new Dictionary <string, int>();
            double minTime   = 1000000000000000;
            double maxTime   = 0;
            double minMz     = 1000000000000000000;
            double maxMz     = 0;
            double minCharge = 100000000000000;
            double maxCharge = 0;

            ICollection <CVTerm> fragmentationType = new HashSet <CVTerm>(CVTerm.CvTermComparer);

            for (var scanNumber = firstScanNumber; scanNumber <= lastScanNumber; scanNumber++)
            {
                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 (msTypes.ContainsKey(scanFilter.MSOrder.ToString()))
                {
                    var value = msTypes[scanFilter.MSOrder.ToString()];
                    value = value + 1;
                    msTypes[scanFilter.MSOrder.ToString()] = value;
                }
                else
                {
                    msTypes.Add(scanFilter.MSOrder.ToString(), 1);
                }

                if (time > maxTime)
                {
                    maxTime = time;
                }
                if (time < minTime)
                {
                    minTime = time;
                }


                if (scanFilter.MSOrder == MSOrderType.Ms2)
                {
                    fragmentationType.Add(ParseActivationType(scanFilter.GetActivation(0)));

                    if (scanEvent.ScanData == ScanDataType.Centroid || (scanEvent.ScanData == ScanDataType.Profile))
                    {
                        try
                        {
                            var reaction      = scanEvent.GetReaction(0);
                            var precursorMass = reaction.PrecursorMass;
                            if (precursorMass > maxMz)
                            {
                                maxMz = precursorMass;
                            }
                            if (precursorMass < minMz)
                            {
                                minMz = precursorMass;
                            }
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            //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 (int.Parse(trailerData.Values[i]) > maxCharge)
                                {
                                    maxCharge = int.Parse(trailerData.Values[i]);
                                }

                                if (int.Parse(trailerData.Values[i]) < minCharge)
                                {
                                    minCharge = int.Parse(trailerData.Values[i]);
                                }
                            }
                        }
                    }
                }
            }

            if (minCharge == 100000000000000)
            {
                minCharge = 0;
            }

            foreach (KeyValuePair <string, int> entry in msTypes)
            {
                if (entry.Key.Equals(MSOrderType.Ms.ToString()))
                {
                    metadata.addMSData(new CVTerm("PRIDE:0000481", "PRIDE", "Number of MS1 spectra",
                                                  entry.Value.ToString()));
                }
                if (entry.Key.Equals(MSOrderType.Ms2.ToString()))
                {
                    metadata.addMSData(new CVTerm("PRIDE:0000482", "PRIDE", "Number of MS2 spectra",
                                                  entry.Value.ToString()));
                }
                if (entry.Key.Equals(MSOrderType.Ms3.ToString()))
                {
                    metadata.addMSData(new CVTerm("PRIDE:0000483", "PRIDE", "Number of MS3 spectra",
                                                  entry.Value.ToString()));
                }
            }

            metadata.addScanSetting(fragmentationType);

            metadata.addMSData(new CVTerm("PRIDE:0000472", "PRIDE", "MS min charge", minCharge.ToString()));
            metadata.addMSData(new CVTerm("PRIDE:0000473", "PRIDE", "MS max charge", maxCharge.ToString()));

            metadata.addMSData(new CVTerm("PRIDE:0000474", "PRIDE", "MS min RT", minTime.ToString()));
            metadata.addMSData(new CVTerm("PRIDE:0000475", "PRIDE", "MS max RT", maxTime.ToString()));

            metadata.addMSData(new CVTerm("PRIDE:0000476", "PRIDE", "MS min MZ", minMz.ToString()));
            metadata.addMSData(new CVTerm("PRIDE:0000477", "PRIDE", "MS max MZ", maxMz.ToString()));


            // Write the meta data to file
            var json = JsonConvert.SerializeObject(metadata);

            json.Replace("\r\n", "\n");

            string metadataOutputPath;

            if (_outputDirectory == null)
            {
                metadataOutputPath = _metadataFileName;
            }
            else
            {
                metadataOutputPath = _outputDirectory + "/" + _metadataFileName + "-metadata.json";
            }

            File.WriteAllText(metadataOutputPath, json);
        }
예제 #2
0
        private void InitializeChromatogramPlot()
        {
            chromatogram = new PlotModel();

            chromatogram.Axes.Add(new LinearAxis {
                Position = AxisPosition.Left, AbsoluteMinimum = 0
            });
            chromatogram.Axes.Add(new LinearAxis {
                Position = AxisPosition.Bottom, AbsoluteMinimum = 0, AbsoluteMaximum = TotalTime
            });
            chromatogram.Axes[x].MajorGridlineStyle = LineStyle.Solid;
            chromatogram.Axes[y].MajorGridlineStyle = LineStyle.Solid;
            //chromatogram.Axes[y].IsZoomEnabled = false;

            var currentScanLine = new LineAnnotation()
            {
                Type  = LineAnnotationType.Vertical,
                X     = 0,
                Color = OxyColors.Black
            };

            var mouseLocationLine = new LineAnnotation()
            {
                Type  = LineAnnotationType.Vertical,
                X     = 0,
                Color = OxyColors.DimGray
            };

            var chroSeries = new AreaSeries();

            chroSeries.Color = Colors.ColorBrewer8ClassSet2(255).Last();

            for (int i = 0; i < ChromatogramData.PositionsArray[0].Length; i++)
            {
                chroSeries.Points.Add(new DataPoint(ChromatogramData.PositionsArray[0][i], ChromatogramData.IntensitiesArray[0][i]));
            }

            chromatogram.Series.Add(chroSeries);

            double max = (from i in ChromatogramData.IntensitiesArray[0] select i).Max() * 1.5;

            if (max <= 0)
            {
                max = 1000;
            }

            chromatogram.Axes[y].AbsoluteMaximum = max;
            chromatogram.Axes[y].Maximum         = chromatogram.Axes[y].AbsoluteMaximum;
            chromatogram.Axes[y].MajorStep       = chromatogram.Axes[y].Maximum / 3;
            chromatogram.Axes[y].StringFormat    = "0.00E00";

            chromatogram.Axes[y].TransformChanged += (object sender, EventArgs e) =>
            {
                chromatogram.Axes[y].MajorStep = (chromatogram.Axes[y].ActualMaximum - chromatogram.Axes[y].ActualMinimum) / 3;
            };

            plotViewChromatogram.MouseEnter += (s, e) =>
            {
                plotViewChromatogram.Cursor = Cursors.Cross;
            };

            chromatogram.MouseDown += (s, e) =>
            {
                if (e.ChangedButton == OxyMouseButton.Left)
                {
                    double rt = chromatogram.Axes[x].InverseTransform(e.Position.X, e.Position.Y, chromatogram.Axes[y]).X;

                    scanNumber.Text = RawData.ScanNumberFromRetentionTime(rt).ToString();

                    currentScanLine.X = RawData.RetentionTimeFromScanNumber(Convert.ToInt32(scanNumber.Text));

                    e.Handled = true;
                    chromatogram.InvalidatePlot(false);
                }
            };

            chromatogram.MouseMove += (s, e) =>
            {
                try
                {
                    mouseLocationLine.X = currentScanLine.InverseTransform(e.Position).X;
                }
                catch (Exception)
                {
                    //do nothing
                }

                e.Handled = false;
                chromatogram.InvalidatePlot(false);
            };


            chromatogram.MouseUp += (s, e) =>
            {
                plotViewChromatogram.Cursor = Cursors.Cross;
                chromatogram.InvalidatePlot(true);
                e.Handled = false;
            };

            chromatogram.MouseLeave += (s, e) =>
            {
                mouseLocationLine.X = 0;

                chromatogram.InvalidatePlot(false);
                e.Handled = true;
            };

            chromatogram.Annotations.Add(currentScanLine);
            chromatogram.Annotations.Add(mouseLocationLine);

            currentScanLine.MouseDown += (s, e) =>
            {
                if (e.ChangedButton != OxyMouseButton.Left)
                {
                    return;
                }

                plotViewChromatogram.Cursor = Cursors.SizeWE;
                chromatogram.InvalidatePlot(false);
                e.Handled = true;
            };

            currentScanLine.MouseMove += (s, e) =>
            {
                double rt = currentScanLine.InverseTransform(e.Position).X;

                currentScanLine.X   = rt;
                mouseLocationLine.X = rt;

                scanNumber.Text = RawData.ScanNumberFromRetentionTime(rt).ToString();

                chromatogram.InvalidatePlot(false);
                e.Handled = true;
            };

            currentScanLine.MouseUp += (s, e) =>
            {
                plotViewChromatogram.Cursor = Cursors.Cross;
                e.Handled = true;
            };


            chromatogram.InvalidatePlot(true);
        }
        /// <summary>
        /// Populate the scan list element
        /// </summary>
        /// <param name="scanNumber">the scan number</param>
        /// <param name="scan">the scan object</param>
        /// <param name="scanFilter">the scan filter</param>
        /// <param name="scanEvent">the scan event</param>
        /// <param name="monoisotopicMass">the monoisotopic mass</param>
        /// <returns></returns>
        private ScanListType ConstructScanList(int scanNumber, Scan scan, IScanFilter scanFilter, IScanEvent scanEvent,
                                               double?monoisotopicMass)
        {
            // Scan list
            var scanList = new ScanListType
            {
                count   = "1",
                scan    = new ScanType[1],
                cvParam = new CVParamType[1]
            };

            scanList.cvParam[0] = new CVParamType
            {
                accession = "MS:1000795",
                cvRef     = "MS",
                name      = "no combination",
                value     = ""
            };

            // Reference the right instrument configuration
            if (!_massAnalyzers.TryGetValue(scanFilter.MassAnalyzer, out var instrumentConfigurationRef))
            {
                instrumentConfigurationRef = "IC1";
            }

            var scanType = new ScanType
            {
                instrumentConfigurationRef = instrumentConfigurationRef,
                cvParam = new CVParamType[2]
            };

            scanType.cvParam[0] = new CVParamType
            {
                name          = "scan start time",
                accession     = "MS:1000016",
                value         = _rawFile.RetentionTimeFromScanNumber(scanNumber).ToString(CultureInfo.InvariantCulture),
                unitCvRef     = "UO",
                unitAccession = "UO:0000031",
                unitName      = "minute",
                cvRef         = "MS"
            };

            scanType.cvParam[1] = new CVParamType
            {
                name      = "filter string",
                accession = "MS:1000512",
                value     = scanEvent.ToString(),
                cvRef     = "MS"
            };

            if (monoisotopicMass.HasValue)
            {
                scanType.userParam    = new UserParamType[1];
                scanType.userParam[0] = new UserParamType
                {
                    name  = "[Thermo Trailer Extra]Monoisotopic M/Z:",
                    value = monoisotopicMass.ToString(),
                    type  = "xsd:float"
                };
            }

            // Scan window list
            scanType.scanWindowList = new ScanWindowListType
            {
                count      = 1,
                scanWindow = new ParamGroupType[1]
            };
            var scanWindow = new ParamGroupType
            {
                cvParam = new CVParamType[2]
            };

            scanWindow.cvParam[0] = new CVParamType
            {
                name          = "scan window lower limit",
                accession     = "MS:1000501",
                value         = scan.ScanStatistics.LowMass.ToString(CultureInfo.InvariantCulture),
                cvRef         = "MS",
                unitAccession = "MS:1000040",
                unitCvRef     = "MS",
                unitName      = "m/z"
            };
            scanWindow.cvParam[1] = new CVParamType
            {
                name          = "scan window upper limit",
                accession     = "MS:1000500",
                value         = scan.ScanStatistics.HighMass.ToString(CultureInfo.InvariantCulture),
                cvRef         = "MS",
                unitAccession = "MS:1000040",
                unitCvRef     = "MS",
                unitName      = "m/z"
            };

            scanType.scanWindowList.scanWindow[0] = scanWindow;

            scanList.scan[0] = scanType;

            return(scanList);
        }
예제 #4
0
        public static MsDataScan GetOneBasedScan(IRawDataPlus rawFile, IFilteringParams filteringParams, int scanNumber)
        {
            var filter = rawFile.GetFilterForScanNumber(scanNumber);

            string scanFilterString = filter.ToString();
            int    msOrder          = (int)filter.MSOrder;

            if (msOrder < 1 || msOrder > 10)
            {
                throw new MzLibException("Unknown MS Order (" + msOrder + ") for scan number " + scanNumber);
            }

            string     nativeId = "controllerType=0 controllerNumber=1 scan=" + scanNumber;
            MzSpectrum spectrum = GetSpectrum(rawFile, filteringParams, scanNumber, scanFilterString, msOrder);

            var     scanStats       = rawFile.GetScanStatsForScanNumber(scanNumber);
            double  scanRangeHigh   = scanStats.HighMass;
            double  scanRangeLow    = scanStats.LowMass;
            MzRange scanWindowRange = new MzRange(scanRangeLow, scanRangeHigh);

            double?        ionInjectionTime = null;
            double?        precursorSelectedMonoisotopicIonMz = null;
            int?           selectedIonChargeState             = null;
            double?        ms2IsolationWidth   = null;
            int?           precursorScanNumber = null;
            double?        isolationMz         = null;
            string         HcdEnergy           = null;
            ActivationType activationType      = ActivationType.Any;

            var trailer = rawFile.GetTrailerExtraInformation(scanNumber);

            string[] labels = trailer.Labels;
            string[] values = trailer.Values;

            for (int i = 0; i < trailer.Labels.Length; i++)
            {
                if (labels[i].StartsWith("Ion Injection Time (ms)", StringComparison.Ordinal))
                {
                    ionInjectionTime = double.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                       (double?)null :
                                       double.Parse(values[i], CultureInfo.InvariantCulture);
                }

                if (msOrder < 2)
                {
                    continue;
                }

                if (labels[i].StartsWith("MS" + msOrder + " Isolation Width", StringComparison.Ordinal))
                {
                    ms2IsolationWidth = double.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                        (double?)null :
                                        double.Parse(values[i], CultureInfo.InvariantCulture);
                }
                if (labels[i].StartsWith("Monoisotopic M/Z", StringComparison.Ordinal))
                {
                    precursorSelectedMonoisotopicIonMz = double.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                                         (double?)null :
                                                         double.Parse(values[i], CultureInfo.InvariantCulture);
                }
                if (labels[i].StartsWith("Charge State", StringComparison.Ordinal))
                {
                    selectedIonChargeState = int.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                             (int?)null :
                                             int.Parse(values[i], CultureInfo.InvariantCulture);
                }
                if (labels[i].StartsWith("Master Scan Number", StringComparison.Ordinal) ||
                    labels[i].StartsWith("Master Index", StringComparison.Ordinal))
                {
                    precursorScanNumber = int.Parse(values[i], CultureInfo.InvariantCulture) <= 1 ?
                                          (int?)null :
                                          int.Parse(values[i], CultureInfo.InvariantCulture);
                }
                if (labels[i].StartsWith("HCD Energy:", StringComparison.Ordinal))
                {
                    HcdEnergy = values[i];
                }
            }

            if (msOrder > 1)
            {
                var scanEvent = rawFile.GetScanEventForScanNumber(scanNumber);
                var reaction  = scanEvent.GetReaction(0);
                isolationMz    = reaction.PrecursorMass;
                activationType = reaction.ActivationType;

                if (ms2IsolationWidth == null)
                {
                    ms2IsolationWidth = reaction.IsolationWidth;
                }

                if (precursorScanNumber == null)
                {
                    // we weren't able to get the precursor scan number, so we'll have to guess;
                    // loop back to find precursor scan
                    // (assumed to be the first scan before this scan with an MS order of this scan's MS order - 1)
                    // e.g., if this is an MS2 scan, find the first MS1 scan before this and assume that's the precursor scan
                    for (int i = scanNumber; i >= 1; i--)
                    {
                        var possiblePrecursorScanFilter = rawFile.GetFilterForScanNumber(i);
                        int order = (int)possiblePrecursorScanFilter.MSOrder;
                        if (order == msOrder - 1)
                        {
                            precursorScanNumber = i;
                            break;
                        }
                    }

                    if (precursorScanNumber == null)
                    {
                        throw new MzLibException("Could not get precursor for scan #" + scanNumber);
                    }
                }
            }

            // at this point, we have the m/z value of the species that got fragmented, from the scan header
            // this section of the code finds that peak in the spectrum (it's actual intensity and centroided m/z values)
            // the intention is to remove any rounding issues caused by what is in the scan header and what is observable in the spectrum
            double?selectedIonIntensity = null;

            if (isolationMz.HasValue)
            {
                int?closest = spectrum.GetClosestPeakIndex(isolationMz.Value);

                if (closest.HasValue)
                {
                    double mz        = spectrum.XArray[closest.Value];
                    double intensity = spectrum.YArray[closest.Value];

                    if (Math.Abs(mz - isolationMz.Value) < 0.1)
                    {
                        selectedIonIntensity = intensity;
                        isolationMz          = mz;
                    }
                }
            }

            return(new MsDataScan(
                       massSpectrum: spectrum,
                       oneBasedScanNumber: scanNumber,
                       msnOrder: msOrder,
                       isCentroid: true,
                       polarity: GetPolarity(filter.Polarity),
                       retentionTime: rawFile.RetentionTimeFromScanNumber(scanNumber),
                       scanWindowRange: scanWindowRange,
                       scanFilter: scanFilterString,
                       mzAnalyzer: GetMassAnalyzerType(filter.MassAnalyzer),
                       totalIonCurrent: spectrum.SumOfAllY,
                       injectionTime: ionInjectionTime,
                       noiseData: null, //TODO: implement reading noise data. it's unused right now, so it's just left as null
                       nativeId: nativeId,
                       selectedIonMz: isolationMz,
                       selectedIonChargeStateGuess: selectedIonChargeState,
                       selectedIonIntensity: selectedIonIntensity,
                       isolationMZ: isolationMz,
                       isolationWidth: ms2IsolationWidth,
                       dissociationType: GetDissociationType(activationType),
                       oneBasedPrecursorScanNumber: precursorScanNumber,
                       selectedIonMonoisotopicGuessMz: precursorSelectedMonoisotopicIonMz,
                       hcdEnergy: HcdEnergy));
        }
        /// <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 && (scan.HasCentroidStream || !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");
                        }
                    }
                }
            }
        }
예제 #6
0
        /// <summary>
        /// Open the given file and import scans into the reader.
        /// </summary>
        /// <returns></returns>
        public System.Collections.IEnumerator GetEnumerator()
        {
            rawFile.SelectInstrument(ThermoBiz.Device.MS, 1);

            // Get the first and last scan from the RAW file
            int FirstScan = rawFile.RunHeaderEx.FirstSpectrum;
            int LastScan  = rawFile.RunHeaderEx.LastSpectrum;

            for (int iScanNumber = FirstScan; iScanNumber <= LastScan; iScanNumber++)
            {
                ThermoBiz.Scan thermoScan = ThermoBiz.Scan.FromFile(rawFile, iScanNumber);
                IScanFilter    scanFilter = rawFile.GetFilterForScanNumber(iScanNumber);
                IScanEvent     scanEvent  = rawFile.GetScanEventForScanNumber(iScanNumber);

                if ((int)scanFilter.MSOrder == 1)
                {
                    LastMS1 = iScanNumber;
                }

                Data.Scan scan = new Data.Scan()
                {
                    ScanNumber        = iScanNumber,
                    ScanEvent         = (iScanNumber - LastMS1) + 1,
                    BasePeakIntensity = thermoScan.ScanStatistics.BasePeakIntensity,
                    BasePeakMz        = thermoScan.ScanStatistics.BasePeakMass,
                    TotalIonCurrent   = thermoScan.ScanStatistics.TIC,
                    LowestMz          = thermoScan.ScanStatistics.LowMass,
                    HighestMz         = thermoScan.ScanStatistics.HighMass,
                    StartMz           = scanFilter.GetMassRange(0).Low,
                    EndMz             = scanFilter.GetMassRange(0).High,
                    ScanType          = ReadScanType(scanFilter.ToString()),
                    MsOrder           = (int)scanFilter.MSOrder,
                    Polarity          = (scanFilter.Polarity == PolarityType.Positive) ? Data.Polarity.Positive : Data.Polarity.Negative,
                    FilterLine        = scanFilter.ToString(),
                    DetectorType      = readDetectorType(scanFilter.MassAnalyzer),
                    RetentionTime     = rawFile.RetentionTimeFromScanNumber(iScanNumber)
                };

                if (scan.MsOrder > 1)
                {
                    // Get the current scan's activation method while ignoring upstream activation
                    scan.PrecursorActivationMethod = ConvertActivationType(scanFilter.GetActivation(scan.MsOrder - 2));

                    // handle dependent scans and not SPS (processed below)
                    scan.Precursors.Clear();
                    for (int i = 0; i < scanEvent.MassCount; ++i)
                    {
                        var reaction = scanEvent.GetReaction(i);
                        scan.CollisionEnergy = reaction.CollisionEnergy;

                        var precursor = new Data.Precursor
                        {
                            IsolationWidth = reaction.IsolationWidth,
                            IsolationMz    = reaction.PrecursorMass,
                            Mz             = reaction.PrecursorMass,
                            OriginalMz     = reaction.PrecursorMass
                        };
                        scan.Precursors.Add(precursor);
                    }
                }

                ThermoBiz.RunHeader runHeader = rawFile.RunHeader;
                ThermoBiz.LogEntry  trailer   = rawFile.GetTrailerExtraInformation(iScanNumber);
                for (int i = 0; i < trailer.Length; i++)
                {
                    var value = trailer.Values[i];
                    if (value == null)
                    {
                        continue;
                    }
                    switch (trailer.Labels[i])
                    {
                    case "Access ID":
                        int access_id = Convert.ToInt32(value);
                        if (access_id > 0)
                        {
                            scan.PrecursorMasterScanNumber = access_id;
                        }
                        break;

                    case "Scan Description:":
                        scan.Description = value.Trim();
                        break;

                    case "Ion Injection Time (ms):":
                        scan.IonInjectionTime = double.Parse(value);
                        break;

                    case "Elapsed Scan Time (sec):":
                        scan.ElapsedScanTime = double.Parse(value);
                        break;

                    case "Charge State:":
                        int charge = int.Parse(value);
                        foreach (var precursor in scan.Precursors)
                        {
                            precursor.Charge         = charge;
                            precursor.OriginalCharge = precursor.Charge;
                        }
                        break;

                    case "Master Scan Number:":
                        scan.PrecursorMasterScanNumber = int.Parse(value);
                        break;

                    case "Master Index:":
                        scan.MasterIndex = int.Parse(value);
                        break;

                    case "Monoisotopic M/Z:":
                        if (Options.RawMonoMz && scan.Precursors.Count > 0)
                        {
                            double mz = double.Parse(value);
                            if (mz > 0)
                            {
                                scan.Precursors[0].Mz = mz;
                            }
                        }
                        break;

                    case "FAIMS CV:":
                        scan.FaimsCV = (int)double.Parse(value);
                        break;

                    case "FAIMS Voltage On:":
                        scan.FaimsState = (value == "No") ? Data.TriState.Off : Data.TriState.On;
                        break;

                    case "SPS Masses:":
                        string[] spsIonStringArray = value.TrimEnd(',').Split(',');
                        if (!string.IsNullOrWhiteSpace(spsIonStringArray[0]) && spsIonStringArray.Length > 0)
                        {
                            scan.Precursors.Clear();
                            for (int spsIndex = 0; spsIndex < spsIonStringArray.Length; spsIndex++)
                            {
                                if (double.TryParse(spsIonStringArray[spsIndex], out double spsIon))
                                {
                                    scan.Precursors.Add(new Data.Precursor(spsIon, 0, 1));
                                }
                            }
                        }
                        break;
                    }
                }

                if (scan.PrecursorMasterScanNumber <= 0 && scan.MsOrder > 1)
                {
                    // Try again to set the precursor scan.
                    SetPrecursorScanNumber(scan);
                }

                if (scan.MsOrder > 1 && scan.PrecursorMasterScanNumber > rawFile.RunHeader.FirstSpectrum && scan.PrecursorMasterScanNumber < rawFile.RunHeader.LastSpectrum)
                {
                    // Fill precursor information
                    var parentScan = ThermoBiz.Scan.FromFile(rawFile, scan.PrecursorMasterScanNumber);
                    if (parentScan != null)
                    {
                        foreach (var precursor in scan.Precursors)
                        {
                            precursor.Intensity = GetMaxIntensity(parentScan, precursor.IsolationMz, precursor.IsolationWidth);
                        }
                    }
                }

                if (thermoScan.HasCentroidStream)
                {
                    // High res data
                    CentroidsFromArrays(scan, thermoScan.CentroidScan.Masses, thermoScan.CentroidScan.Intensities, thermoScan.CentroidScan.Baselines, thermoScan.CentroidScan.Noises);
                }
                else
                {
                    // Low res data
                    CentroidsFromArrays(scan, thermoScan.PreferredMasses, thermoScan.PreferredIntensities);
                }

                if (scan.PeakCount > 0)
                {
                    scan.LowestMz  = scan.Centroids[0].Mz;
                    scan.HighestMz = scan.Centroids[scan.PeakCount - 1].Mz;
                }

                yield return(scan);
            }
        }
예제 #7
0
        /// <inheritdoc />
        public override void Write(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.LogFormat == LogFormat.DEFAULT)
                    {
                        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);

                    // don't include MS1 spectra
                    if (scanFilter.MSOrder != MSOrderType.Ms)
                    {
                        IReaction reaction = GetReaction(scanEvent, scanNumber);

                        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()}");

                        if (!ParseInput.NoPeakPicking)
                        {
                            // check if the scan has a centroid stream
                            if (scan.HasCentroidStream)
                            {
                                if (scan.CentroidScan.Length > 0)
                                {
                                    for (var i = 0; i < scan.CentroidScan.Length; i++)
                                    {
                                        Writer.WriteLine(
                                            scan.CentroidScan.Masses[i].ToString("0.0000000",
                                                                                 CultureInfo.InvariantCulture)
                                            + " "
                                            + scan.CentroidScan.Intensities[i].ToString("0.0000000000",
                                                                                        CultureInfo.InvariantCulture));
                                    }
                                }
                            }
                            else // otherwise take segmented (low res) scan data
                            {
                                // if the spectrum is profile perform centroiding
                                var segmentedScan = scanEvent.ScanData == ScanDataType.Profile
                                    ? Scan.ToCentroid(scan).SegmentedScan
                                    : scan.SegmentedScan;

                                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));
                                }
                            }
                        }
                        else // use the segmented data as is
                        {
                            for (var i = 0; i < scan.SegmentedScan.Positions.Length; i++)
                            {
                                Writer.WriteLine(
                                    scan.SegmentedScan.Positions[i].ToString("0.0000000",
                                                                             CultureInfo.InvariantCulture)
                                    + " "
                                    + scan.SegmentedScan.Intensities[i].ToString("0.0000000000",
                                                                                 CultureInfo.InvariantCulture));
                            }
                        }

                        Writer.WriteLine("END IONS");

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

                if (ParseInput.LogFormat == LogFormat.DEFAULT)
                {
                    Console.WriteLine();
                }
            }
        }
예제 #8
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();
        }
예제 #9
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();
        }
    }
}

예제 #10
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;
        }
예제 #11
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)
예제 #12
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");
                        }
                    }
                }
            }
        }
예제 #13
0
            //const String rawFile = @"E:\Python_1\meta\meta\bin\x64\Debug\10_Ile.RAW";

            String rawFile = "20190924_ISmix21_pos_1_0.RAW";

            //string resFilePath = "123kl.csv";
            //string paraIndex = "3,4";
            //const String filename = "E:/wamp/www/tp5/application/index/controller/21_Val.RAW";
            //string filename = args[0];
            //showheaderInfo(filename);

            //string resFilePath = args[0];
            //string rawFile = args[1];
            //string paraIndex = args[2];
            //string headerInfo = Encoding.UTF8.GetString(Encoding.Default.GetBytes(""));
            //for (int i = 3; i < args.Length; i++)
            //{
            //    headerInfo += Encoding.UTF8.GetString(Encoding.Default.GetBytes(args[i]));
            //}
            //getentityData(resFilePath, rawFile, headerInfo, paraIndex);

            //getTuneInfo(filename);


            getMSdataFromScanNum(46, 48, rawFile, 50, 500);
            Console.ReadKey();
        }

        public static void getentityData(string resFilePath, string rawFile, string headerInfo, string paraIndex)
        {
            IRawDataPlus plus = RawFileReaderAdapter.FileFactory(rawFile);
            plus.SelectInstrument(Device.MS, 1);

            ArrayList indexOfpara = new ArrayList();
            string[] selectIndex = paraIndex.Split(',');

            foreach (string ele in selectIndex)
            {
                int index = Int32.Parse(ele);
                indexOfpara.Add(index);
            }

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

            headerInfo = "RT," + headerInfo;
            headerInfo = "#," + headerInfo;
            writer.WriteLine(headerInfo);

            int offset = 0;
            int maxoffset = plus.GetStatusLogEntriesCount();
            while (offset < maxoffset)
            {
                string temp = "";
                IStatusLogEntry statusLogEntry = plus.GetStatusLogEntry(offset);
                temp += offset.ToString() + ",";
                temp += statusLogEntry.Time.ToString() + ",";

                foreach (int ele in indexOfpara)
                {
                    temp += Convert.ToString(statusLogEntry.Values[ele]) + ",";
                }

                writer.WriteLine(temp.Substring(0, temp.Length - 1));
                offset += 1;
            }

            writer.Close();
        }

        public static void showheaderInfo(string filePath)
        {
            IRawDataPlus plus = RawFileReaderAdapter.FileFactory(filePath);
            plus.SelectInstrument(Device.MS, 1);
            HeaderItem[] statuslogheaderinformation = plus.GetStatusLogHeaderInformation();
            int index = 0;

            Console.OutputEncoding = Encoding.UTF8;

            while (index < statuslogheaderinformation.Length)
            {
                Console.WriteLine(statuslogheaderinformation[index].Label);
                //headerInfo[index] = statuslogheaderinformation[index].Label;
                //writer.WriteLine(statuslogheaderinformation[index].Label);
                index += 1;
            }
            //writer.Close();

            //while (true)
            //{
            //if (index >= statuslogheaderinformation.Length)
            //{
            //    Console.WriteLine(plus.RunHeaderEx.FirstSpectrum.ToString());
            //    Console.WriteLine(plus.RunHeaderEx.LastSpectrum.ToString());
            //    Console.WriteLine(plus.RunHeaderEx.StartTime.ToString("F2"));
            //    Console.WriteLine(plus.RunHeaderEx.EndTime.ToString("F2"));
            //    Console.WriteLine(plus.RunHeaderEx.LowMass.ToString());
            //    Console.WriteLine(plus.RunHeaderEx.HighMass.ToString());
            //    break;
            //}
            //    Console.WriteLine(statuslogheaderinformation[index].Label);
            //    writer.WriteLine(statuslogheaderinformation[index].Label);
            //    index++;
            //}

            //writer.Close();

        }
        public static void getTuneInfo(string filePath)
        {
            IRawDataPlus plus = RawFileReaderAdapter.FileFactory(filePath);
            plus.SelectInstrument(Device.MS, 1);
            string fileName = DateTime.Now.ToLocalTime().ToString().Replace("/", "").Replace(":", "").Replace(" ", "_") + ".txt";
            FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
            StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
            writer.WriteLine("*********************InstrumentMethod(0)***************************");
            writer.WriteLine(plus.GetInstrumentMethod(0));

            writer.WriteLine("*********************InstrumentMethod(1)****************************");
            writer.WriteLine(plus.GetInstrumentMethod(1));

            HeaderItem[] tuneDataHeaderInfo = plus.GetTuneDataHeaderInformation();

            writer.WriteLine("*********************Tune DATA ****************************");
            int tuneCnt = plus.GetTuneDataCount();

            for (int i = 0; i < tuneDataHeaderInfo.Length; ++i)
            {
                writer.WriteLine(tuneDataHeaderInfo[i].Label);
            }
            writer.Close();
        }

        public static void getMSdataFromScanNum(int startNum, int endNum, string filePath, double lowMS = 0.00, double highMS = 0.00)
        {
            IRawDataPlus plus = RawFileReaderAdapter.FileFactory(filePath);

            //////////////////////////////////
            plus.SelectInstrument(Device.MS, 1);
            /////////////////////////////////
            
            const string FilterStringIsolationMzPattern = @"ms2 (.*?)@";
            int precursorMs1ScanNumber = 0;
            double precursorMS= 0.00;
            IReaction reaction = null;
            var value = "";

            var firstScanNumber = plus.RunHeaderEx.FirstSpectrum;
            var lastScanNumber = plus.RunHeaderEx.LastSpectrum;

            startNum = firstScanNumber;
            endNum = lastScanNumber;

            //int maxNum = plus.RunHeaderEx.LastSpectrum > endNum ? endNum : plus.RunHeaderEx.LastSpectrum;

            LimitedSizeDictionary<string, int> precursorMs2ScanNumbers = new LimitedSizeDictionary<string, int>(40);

            plus.SelectInstrument(Device.MS, 1);
            if(highMS - 0.00 <= 0.01)
            {
                highMS = plus.RunHeaderEx.HighMass;
            }

            double maxMs = plus.RunHeaderEx.HighMass;
            double minMs = plus.RunHeaderEx.LowMass;

            lowMS = minMs;
            highMS = maxMs;

            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,MSLevel,collisionEnergy, precursorNum,precursorMS");
            while (startNum <= endNum)
            {
                var levelInfo = "";
                var spectrumRef = "";
                Scan scan = Scan.FromFile(plus, startNum);
                IScanFilter scanFilter = plus.GetFilterForScanNumber(startNum);

                IScanEvent scanEvent = plus.GetScanEventForScanNumber(startNum);

                switch (scanFilter.MSOrder)
                {
                    case MSOrderType.Ms:
                        // Keep track of scan number for precursor reference
                        precursorMs1ScanNumber = startNum;
                        reaction = scanEvent.GetReaction(0);
                        value = reaction.CollisionEnergy.ToString(CultureInfo.InvariantCulture).ToString();
                        levelInfo = scanFilter.MSOrder.ToString() + "," + "" + "," + "" + "," + "";
                        break;
                    case MSOrderType.Ms2:

                        // Keep track of scan number and isolation m/z for precursor reference                   
                        var result = Regex.Match(scanEvent.ToString(), FilterStringIsolationMzPattern);
                        if (result.Success)
                        {
                            if (precursorMs2ScanNumbers.ContainsKey(result.Groups[1].Value))
                            {
                                precursorMs2ScanNumbers.Remove(result.Groups[1].Value);
                            }

                            precursorMs2ScanNumbers.Add(result.Groups[1].Value, startNum);
                        }
                        spectrumRef = precursorMs1ScanNumber.ToString();
                        reaction = scanEvent.GetReaction(0);
                        value = reaction.CollisionEnergy.ToString(CultureInfo.InvariantCulture).ToString();
                        precursorMS = reaction.PrecursorMass;
                        levelInfo = scanFilter.MSOrder.ToString() + "," + value + "," + spectrumRef.ToString() + "," +  precursorMS.ToString()  ;
                        break;
                    case MSOrderType.Ms3:
                        var precursorMs2ScanNumber = precursorMs2ScanNumbers.Keys.FirstOrDefault(isolationMz => scanEvent.ToString().Contains(isolationMz));
                        spectrumRef = precursorMs2ScanNumbers[precursorMs2ScanNumber].ToString();
                        if (!precursorMs2ScanNumber.IsNullOrEmpty())
                        {
                            reaction = scanEvent.GetReaction(1);
                        }
                        else
                        {
                            throw new InvalidOperationException("Couldn't find a MS2 precursor scan for MS3 scan " + scanEvent);
                        }
                        precursorMS = reaction.PrecursorMass;
                        value = reaction.CollisionEnergy.ToString(CultureInfo.InvariantCulture).ToString();
                        levelInfo = scanFilter.MSOrder.ToString() + "," + value +  "," + spectrumRef.ToString() + "," + precursorMS.ToString();
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                //var scanStatistics = plus.GetScanStatsForScanNumber(startNum);
                //// Get the segmented (low res and profile) scan data
                //var segmentedScan = plus.GetSegmentedScanFromScanNumber(startNum, scanStatistics);
                //var masses = segmentedScan.Positions;
                //var intensitis = segmentedScan.Intensities;
                //Console.WriteLine(masses.Length);
                //Console.WriteLine(intensitis.Length);
                //Console.WriteLine(filterObj.MSOrder);

                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},{7}", startNum.ToString(), rt.ToString(),
                            msval.ToString(), resolution.ToString(), intensity.ToString(), noise.ToString(),
                            scanFilter.ToString(), levelInfo);
                    }
                    cnt += 1;
                }
                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());
                    }
                    cnt += 1;
                }
                startNum += 1;
            }
            writer.Close();
        }
예제 #14
0
 //int maxNum = plus.RunHeaderEx.LastSpectrum > endNum ? endNum : plus.RunHeaderEx.LastSpectrum;

            LimitedSizeDictionary<string, int> precursorMs2ScanNumbers = new LimitedSizeDictionary<string, int>(40);

            plus.SelectInstrument(Device.MS, 1);
            if(highMS - 0.00 <= 0.01)
            {
                highMS = plus.RunHeaderEx.HighMass;
            }

            double maxMs = plus.RunHeaderEx.HighMass;
            double minMs = plus.RunHeaderEx.LowMass;

            lowMS = minMs;
            highMS = maxMs;

            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,MSLevel,collisionEnergy, precursorNum,precursorMS");
            while (startNum <= endNum)
            {
                var levelInfo = "";
                var spectrumRef = "";
                Scan scan = Scan.FromFile(plus, startNum);
                IScanFilter scanFilter = plus.GetFilterForScanNumber(startNum);

                IScanEvent scanEvent = plus.GetScanEventForScanNumber(startNum);

                switch (scanFilter.MSOrder)
                {
                    case MSOrderType.Ms:
                        // Keep track of scan number for precursor reference
                        precursorMs1ScanNumber = startNum;
                        reaction = scanEvent.GetReaction(0);
                        value = reaction.CollisionEnergy.ToString(CultureInfo.InvariantCulture).ToString();
                        levelInfo = scanFilter.MSOrder.ToString() + "," + "" + "," + "" + "," + "";
                        break;
                    case MSOrderType.Ms2:

                        // Keep track of scan number and isolation m/z for precursor reference                   
                        var result = Regex.Match(scanEvent.ToString(), FilterStringIsolationMzPattern);
                        if (result.Success)
                        {
                            if (precursorMs2ScanNumbers.ContainsKey(result.Groups[1].Value))
                            {
                                precursorMs2ScanNumbers.Remove(result.Groups[1].Value);
                            }

                            precursorMs2ScanNumbers.Add(result.Groups[1].Value, startNum);
                        }
                        spectrumRef = precursorMs1ScanNumber.ToString();
                        reaction = scanEvent.GetReaction(0);
                        value = reaction.CollisionEnergy.ToString(CultureInfo.InvariantCulture).ToString();
                        precursorMS = reaction.PrecursorMass;
                        levelInfo = scanFilter.MSOrder.ToString() + "," + value + "," + spectrumRef.ToString() + "," +  precursorMS.ToString()  ;
                        break;
                    case MSOrderType.Ms3:
                        var precursorMs2ScanNumber = precursorMs2ScanNumbers.Keys.FirstOrDefault(isolationMz => scanEvent.ToString().Contains(isolationMz));
                        spectrumRef = precursorMs2ScanNumbers[precursorMs2ScanNumber].ToString();
                        if (!precursorMs2ScanNumber.IsNullOrEmpty())
                        {
                            reaction = scanEvent.GetReaction(1);
                        }
                        else
                        {
                            throw new InvalidOperationException("Couldn't find a MS2 precursor scan for MS3 scan " + scanEvent);
                        }
                        precursorMS = reaction.PrecursorMass;
                        value = reaction.CollisionEnergy.ToString(CultureInfo.InvariantCulture).ToString();
                        levelInfo = scanFilter.MSOrder.ToString() + "," + value +  "," + spectrumRef.ToString() + "," + precursorMS.ToString();
                        break;
                    default:
                        throw new ArgumentOutOfRangeException();
                }

                //var scanStatistics = plus.GetScanStatsForScanNumber(startNum);
                //// Get the segmented (low res and profile) scan data
                //var segmentedScan = plus.GetSegmentedScanFromScanNumber(startNum, scanStatistics);
                //var masses = segmentedScan.Positions;
                //var intensitis = segmentedScan.Intensities;
                //Console.WriteLine(masses.Length);
                //Console.WriteLine(intensitis.Length);
                //Console.WriteLine(filterObj.MSOrder);

                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},{7}", startNum.ToString(), rt.ToString(),
                            msval.ToString(), resolution.ToString(), intensity.ToString(), noise.ToString(),
                            scanFilter.ToString(), levelInfo);
                    }
                    cnt += 1;
                }
                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());
                    }
                    cnt += 1;
                }
                startNum += 1;
            }
            writer.Close();
        }
예제 #15
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 exception)
                        {
                            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();
                }
            }
        }