示例#1
0
        /// <summary>
        /// Reads raw data. Puts spectra into a thread safe queue. Closes queue when done. Parses the rawfile-log into the statusLog object
        /// </summary>
        /// <param name="raw">Raw file</param>
        /// <param name="rawScanQueue">Thread safe queue</param>
        private void ReadRawFile(IXRawfile5 raw, BlockingCollection <RawScan> rawScanQueue)
        {
            int firstScanNumber = -1;

            raw.GetFirstSpectrumNumber(ref firstScanNumber);
            int lastScanNumber = -1;

            raw.GetLastSpectrumNumber(ref lastScanNumber);

            for (int scanNumber = firstScanNumber; scanNumber <= lastScanNumber; scanNumber++)
            {
                string scanFilter = null;
                raw.GetFilterForScanNum(scanNumber, ref scanFilter);

                //read scan header into key/value arrays
                object keyRef   = null;
                object valueRef = null;
                int    indexRef = 0;
                raw.GetTrailerExtraForScanNum(scanNumber, ref keyRef, ref valueRef, ref indexRef);
                string[] trailerKeys   = (string[])keyRef;
                string[] trailerValues = (string[])valueRef;

                //read tic and base peak mass using dummy variables
                double tic          = 0.0;
                int    int1         = 0;
                int    int2         = 0;
                int    int3         = 0;
                double double1      = 0.0;
                double double2      = 0.0;
                double double3      = 0.0;
                double basePeakMass = 0.0;
                double double5      = 0.0;
                double double6      = 0.0;
                raw.GetScanHeaderInfoForScanNum(scanNumber, ref int1, ref double1, ref double2, ref double3, ref tic, ref basePeakMass, ref double5, ref int2, ref int3, ref double6);

                //read data (mz,int,...) using dummy variables
                object labels_obj = null;
                object flags_obj  = null;
                raw.GetLabelData(ref labels_obj, ref flags_obj, ref scanNumber);
                double[,] data = (double[, ])labels_obj;

                //read precursorMz
                double precursorMz = 0.0;
                raw.GetPrecursorMassForScanNum(scanNumber, 2, ref precursorMz);

                RawScan rawScan = new RawScan(scanNumber, scanFilter, tic, trailerKeys, trailerValues, data, precursorMz, basePeakMass);
                rawScanQueue.Add(rawScan);

                //read status log
                double rtLog           = 0.0;
                object statuslogKeys   = null;
                object statuslogValues = null;
                int    statuslogN      = 0;
                raw.GetStatusLogForScanNum(scanNumber, ref rtLog, ref statuslogKeys, ref statuslogValues, ref statuslogN);
                statusLog.Add(rtLog, (string[])statuslogKeys, (string[])statuslogValues);
            }
            rawScanQueue.CompleteAdding();
            Log.Information("Read all spectra in base module");
        }
示例#2
0
        public double[,] GetLabeledData(int spectrumNumber)
        {
            object labels = null;
            object flags  = null;

            _rawConnection.GetLabelData(ref labels, ref flags, ref spectrumNumber);
            return((double[, ])labels);
        }
示例#3
0
        private double[,] GetLabeledData(int spectrumNumber)
        {
            object labels = null;
            object flags  = null;

            _rawConnection.GetLabelData(ref labels, ref flags, ref spectrumNumber);
            double[,] data = labels as double[, ];
            return(data == null || data.Length == 0 ? null : data);
        }
示例#4
0
        private double[,] GetLabeledData(int spectrumNumber)
        {
            object labels = null;
            object flags  = null;

            _rawConnection.GetLabelData(ref labels, ref flags, ref spectrumNumber);
            double[,] data = labels as double[, ];
            if (data == null || data.Length == 0)
            {
                throw new ArgumentNullException("For spectrum number " + spectrumNumber + " the data is null!");
            }
            return(data);
        }
示例#5
0
        public static MsDataScan GetMsDataOneBasedScanFromThermoFile(IXRawfile5 theConnection, int nScanNumber, ThermoGlobalParams globalParams, IFilteringParams filterParams = null)
        {
            int    pnNumPackets        = 0;
            double pdLowMass           = 0;
            double pdHighMass          = 0;
            double pdTIC               = 0;
            double pdBasePeakMass      = 0;
            double pdBasePeakIntensity = 0;
            int    pnNumChannels       = 0;
            int    pbUniformTime       = 0;
            double pdFrequency         = 0;
            double pdStartTime         = 0;

            theConnection.GetScanHeaderInfoForScanNum(nScanNumber, ref pnNumPackets, ref pdStartTime, ref pdLowMass, ref pdHighMass, ref pdTIC, ref pdBasePeakMass, ref pdBasePeakIntensity, ref pnNumChannels, ref pbUniformTime, ref pdFrequency);

            double?ms2isolationWidthFromTrailerExtra        = null;
            double?injectionTimeFromTrailerExtra            = null;
            double?precursorMonoisotopicMZfromTrailierExtra = null;
            int?   chargeStatefromTrailierExtra             = null;
            int?   masterScanfromTrailierExtra = null;

            object pvarValues  = null;
            object pvarLables  = null;
            int    pnArraySize = 0;

            theConnection.GetTrailerExtraForScanNum(nScanNumber, ref pvarLables, ref pvarValues, ref pnArraySize);

            string[] labels = (string[])pvarLables;
            string[] values = (string[])pvarValues;
            for (int i = labels.GetLowerBound(0); i <= labels.GetUpperBound(0); i++)
            {
                if (labels[i].StartsWith("MS2 Isolation Width", StringComparison.Ordinal))
                {
                    ms2isolationWidthFromTrailerExtra = double.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                                        (double?)null :
                                                        double.Parse(values[i], CultureInfo.InvariantCulture);
                }
                if (labels[i].StartsWith("Ion Injection Time (ms)", StringComparison.Ordinal))
                {
                    injectionTimeFromTrailerExtra = double.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                                    (double?)null :
                                                    double.Parse(values[i], CultureInfo.InvariantCulture);
                }
                if (labels[i].StartsWith("Monoisotopic M/Z", StringComparison.Ordinal))
                {
                    precursorMonoisotopicMZfromTrailierExtra = double.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                                               (double?)null :
                                                               double.Parse(values[i], CultureInfo.InvariantCulture);
                }
                if (labels[i].StartsWith("Charge State", StringComparison.Ordinal))
                {
                    chargeStatefromTrailierExtra = int.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                                   (int?)null :
                                                   int.Parse(values[i], CultureInfo.InvariantCulture);
                }
                if (labels[i].StartsWith("Master Scan Number", StringComparison.Ordinal))
                {
                    masterScanfromTrailierExtra = int.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                                  (int?)null :
                                                  int.Parse(values[i], CultureInfo.InvariantCulture);
                }
            }

            string pbstrFilter = null;

            theConnection.GetFilterForScanNum(nScanNumber, ref pbstrFilter);

            int pnMSOrder = 0;

            theConnection.GetMSOrderForScanNum(nScanNumber, ref pnMSOrder);

            int pnMassAnalyzerType = 0;

            theConnection.GetMassAnalyzerTypeForScanNum(nScanNumber, ref pnMassAnalyzerType);

            object pvarNoisePacket = null;

            try //if there is no noise data
            {
                theConnection.GetNoiseData(ref pvarNoisePacket, nScanNumber);
            }
            catch
            {
                //pvarNoisePAcket is already null
            }
            double[,] noiseData = pvarNoisePacket as double[, ];

            double[,] data;
            try
            {
                object pvarFlags  = null;
                object pvarLabels = null;
                theConnection.GetLabelData(ref pvarLabels, ref pvarFlags, ref nScanNumber);
                data = pvarLabels as double[, ];
                if (data == null || data.Length == 0)
                {
                    throw new MzLibException("For spectrum number " + nScanNumber + " the data is null!");
                }
            }
            catch (MzLibException)
            {
                // Warning: the masses reported by GetMassListFromScanNum when centroiding are not properly calibrated and thus could be off by 0.3 m/z or more

                double pdCentroidPeakWidth = 0;
                object pvarnMassList       = null;
                object pvarPeakFlags       = null;
                theConnection.GetMassListFromScanNum(ref nScanNumber, null, 0, 0, 0, 1, ref pdCentroidPeakWidth, ref pvarnMassList, ref pvarPeakFlags, ref pnArraySize);
                data = (double[, ])pvarnMassList;
            }

            MzSpectrum thermoSpectrum;

            if (filterParams != null && data.GetLength(1) > 0 && (filterParams.MinimumAllowedIntensityRatioToBasePeakM.HasValue || filterParams.NumberOfPeaksToKeepPerWindow.HasValue) && ((filterParams.ApplyTrimmingToMs1 && pnMSOrder == 1) || (filterParams.ApplyTrimmingToMsMs && pnMSOrder > 1)))
            {
                var count = data.GetLength(1);

                var mzArray        = new double[count];
                var intensityArray = new double[count];
                Buffer.BlockCopy(data, 0, mzArray, 0, sizeof(double) * count);
                Buffer.BlockCopy(data, sizeof(double) * count, intensityArray, 0, sizeof(double) * count);
                if (filterParams.NumberOfWindows == null)
                {
                    int numPeaks = TopNpeakHelper(ref intensityArray, ref mzArray, filterParams);
                    //the following arrays are modified after TopN helper
                    Array.Resize(ref intensityArray, numPeaks);
                    Array.Resize(ref mzArray, numPeaks);
                }
                //Array reference passed by value, array calues will be modified after calling
                else
                {
                    WindowModeHelper(ref intensityArray, ref mzArray, filterParams);
                }
                Array.Sort(mzArray, intensityArray);
                thermoSpectrum = new MzSpectrum(mzArray, intensityArray, false);
            }
            else
            {
                thermoSpectrum = new MzSpectrum(data);
            }
            MZAnalyzerType mzAnalyzerType;

            if ((ThermoMzAnalyzer)pnMassAnalyzerType == ThermoMzAnalyzer.FTMS)
            {
                mzAnalyzerType = MZAnalyzerType.Orbitrap;
            }
            else
            {
                mzAnalyzerType = MZAnalyzerType.Unknown;
            }
            string nativeId = "controllerType=0 controllerNumber=1 scan=" + nScanNumber;

            if (pnMSOrder > 1)
            {
                int pnActivationType = 0;
                theConnection.GetActivationTypeForScanNum(nScanNumber, pnMSOrder, ref pnActivationType);

                // INITIALIZE globalParams.couldBePrecursor[nScanNumber - 1] (for dynamic connections that don't have it initialized yet)
                if (globalParams.CouldBePrecursor[nScanNumber - 1].Equals(default(ManagedThermoHelperLayer.PrecursorInfo)))
                {
                    var ok = new ManagedThermoHelperLayer.HelperClass();
                    globalParams.CouldBePrecursor[nScanNumber - 1] = ok.GetSingleScanPrecursorInfo(nScanNumber, globalParams.FilePath);
                }

                var precursorInfo = globalParams.CouldBePrecursor[nScanNumber - 1];

                // THIS METHOD IS BUGGY!!! DO NOT USE
                //theConnection.FindPrecursorMassInFullScan(nScanNumber, ref pnMasterScan, ref pdFoundMass, ref pdHeaderMass, ref pnChargeState);

                int oneBasedPrecursorScanNumber = -1;
                if (precursorInfo.nScanNumber > 0)
                {
                    oneBasedPrecursorScanNumber = precursorInfo.nScanNumber;
                }
                else if (masterScanfromTrailierExtra.HasValue && masterScanfromTrailierExtra > 0)
                {
                    oneBasedPrecursorScanNumber = masterScanfromTrailierExtra.Value;
                }
                else
                {
                    // 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
                    int scanOrder          = globalParams.MsOrderByScan[nScanNumber - 1];
                    int precursorScanOrder = scanOrder - 1;

                    for (int i = nScanNumber - 1; i >= 0; i--)
                    {
                        int msOrder = globalParams.MsOrderByScan[i];

                        if (msOrder == precursorScanOrder)
                        {
                            oneBasedPrecursorScanNumber = i + 1;
                            break;
                        }
                    }
                }
                if (oneBasedPrecursorScanNumber == -1)
                {
                    throw new MzLibException("Could not find precursor info for scan #" + nScanNumber);
                }

                int?selectedIonGuessChargeStateGuess = null;
                if (precursorInfo.nChargeState > 0)
                {
                    selectedIonGuessChargeStateGuess = precursorInfo.nChargeState;
                }
                else if (chargeStatefromTrailierExtra.HasValue)
                {
                    selectedIonGuessChargeStateGuess = chargeStatefromTrailierExtra;
                }

                double?selectedIonGuessMonoisotopicMz = null;
                if (precursorMonoisotopicMZfromTrailierExtra.HasValue && precursorMonoisotopicMZfromTrailierExtra.Value > 0)
                {
                    selectedIonGuessMonoisotopicMz = precursorMonoisotopicMZfromTrailierExtra;
                }
                if (precursorInfo.dMonoIsoMass > 0 && !selectedIonGuessMonoisotopicMz.HasValue)
                {
                    selectedIonGuessMonoisotopicMz = precursorInfo.dMonoIsoMass;
                }

                Regex matcher;
                if (pbstrFilter.ToLower().Contains("msx"))
                {
                    matcher = mFindParentIonOnlyMsx;
                }
                else
                {
                    matcher = mFindParentIonOnlyNonMsx;
                }
                double selectedIonGuessMZ = double.Parse(matcher.Match(pbstrFilter).Groups["ParentMZ"].Value);

                //   int? selectedIonChargeStateGuess, double? selectedIonIntensity, double? isolationMZ, double? isolationWidth, DissociationType dissociationType, int? oneBasedPrecursorScanNumber, double? selectedIonMonoisotopicGuessMz, double? injectionTime, double[,] noiseData, string nativeId)
                // double TotalIonCurrent, double selectedIonMZ, int? selectedIonChargeStateGuess, double? selectedIonIntensity, double? isolationMZ, double? isolationWidth, DissociationType dissociationType, int? oneBasedPrecursorScanNumber, double? selectedIonMonoisotopicGuessMz, double? injectionTime, double[,] noiseData, string nativeId)
                return(new MsDataScan(
                           thermoSpectrum,
                           nScanNumber,
                           pnMSOrder,
                           true,
                           PolarityRegex.IsMatch(pbstrFilter) ? Polarity.Positive : Polarity.Negative,
                           pdStartTime,
                           new MzRange(pdLowMass, pdHighMass),
                           pbstrFilter,
                           mzAnalyzerType,
                           pdTIC,
                           injectionTimeFromTrailerExtra,
                           noiseData,
                           nativeId,
                           selectedIonGuessMZ,
                           selectedIonGuessChargeStateGuess,
                           null,
                           selectedIonGuessMZ,
                           ms2isolationWidthFromTrailerExtra,
                           (DissociationType)pnActivationType,
                           oneBasedPrecursorScanNumber,
                           selectedIonGuessMonoisotopicMz
                           ));
            }
            else
            {
                return(new MsDataScan(
                           thermoSpectrum,
                           nScanNumber,
                           1,
                           true,
                           PolarityRegex.IsMatch(pbstrFilter) ? Polarity.Positive : Polarity.Negative,
                           pdStartTime,
                           new MzRange(pdLowMass, pdHighMass),
                           pbstrFilter,
                           mzAnalyzerType,
                           pdTIC,
                           injectionTimeFromTrailerExtra,
                           noiseData,
                           nativeId));
            }
        }
示例#6
0
        private MSScan GetScanFromFile(int argScanNo, float argMinSN = 2)
        {
            int isProfile = 0;

            _rawConnection.IsProfileScanForScanNum(argScanNo, ref isProfile);

            object labels = null;
            object flags  = null;

            _rawConnection.GetLabelData(ref labels, ref flags, ref argScanNo);
            double[,] LabeledPeaks = (double[, ])labels;


            //Start Read Scan
            MSScan scan = new MSScan(argScanNo);
            List <ThermoLabeledPeak> FullLabeledPeak = new List <ThermoLabeledPeak>();

            float[] mz        = new float[LabeledPeaks.GetLength(1)];
            float[] intensity = new float[LabeledPeaks.GetLength(1)];
            int     j         = 0;

            for (int i = 0; i < LabeledPeaks.GetLength(1); i++)
            {
                double sn = LabeledPeaks[1, i] / LabeledPeaks[4, i];
                if (sn >= argMinSN)
                {
                    mz[j]        = Convert.ToSingle(LabeledPeaks[0, i]);
                    intensity[j] = Convert.ToSingle(LabeledPeaks[1, i]);
                    j++;
                    FullLabeledPeak.Add(new ThermoLabeledPeak(
                                            Convert.ToSingle(LabeledPeaks[0, i]),
                                            Convert.ToSingle(LabeledPeaks[1, i]),
                                            Convert.ToInt32(LabeledPeaks[5, i]),
                                            Convert.ToSingle(LabeledPeaks[4, i])));
                }
            }
            Array.Resize(ref mz, j);
            Array.Resize(ref intensity, j);

            //scan.MZs = ConvertDoubleArrayToFloatArray(CSMSLScan.MassSpectrum.GetMasses());
            scan.MZs = mz;
            //scan.Intensities = ConvertDoubleArrayToFloatArray(CSMSLScan.MassSpectrum.GetIntensities());
            scan.Intensities = intensity;
            scan.MsLevel     = GetMsLevel(argScanNo);

            double retentionTime = 0;

            _rawConnection.RTFromScanNum(argScanNo, ref retentionTime);
            scan.Time       = retentionTime;
            scan.ScanHeader = GetScanDescription(argScanNo);

            if (scan.MsLevel != 1)
            {
                for (int chNum = 0; chNum < scan.MZs.Length; chNum++)
                {
                    scan.MSPeaks.Add(new MSPeak(
                                         Convert.ToSingle(scan.MZs[chNum]),
                                         Convert.ToSingle(scan.Intensities[chNum])));
                }

                // Get parent information
                object value = null;
                _rawConnection.GetTrailerExtraValueForScanNum(argScanNo, "Master Scan Number:", ref value);
                scan.ParentScanNo = Convert.ToInt32(value);
                string ParentDesc = GetScanDescription(scan.ParentScanNo);

                //_rawConnection.GetPrecursorInfoFromScanNum(argScanNo, ref PrecursorInfo, ref PrecursorInfoSize);


                //scan.ParentMonoMW = Convert.ToSingle(PrecurorArray.);
                //scan.ParentMZ = Convert.ToSingle(PrecurorArray[1,0]);
                //scan.ParentCharge = Convert.ToInt32(PrecurorArray.nChargeState);
                scan.IsCIDScan = IsCIDScan(argScanNo);
                scan.IsFTScan  = IsFTScan(argScanNo);

                //Array.Clear(_transformResult, 0, _transformResult.Length);
                //Array.Clear(_cidPeaks, 0, _cidPeaks.Length);
                //Array.Clear(_cidMzs, 0, _cidMzs.Length);
                //Array.Clear(_cidIntensities, 0, _cidIntensities.Length);
                //Array.Clear(_parentRawMzs, 0, _parentRawMzs.Length);
                //Array.Clear(_parentRawIntensitys, 0, _parentRawIntensitys.Length);
            }
            else //MS Scan
            {
                do
                {
                    ThermoLabeledPeak        BasePeak     = FullLabeledPeak[0];
                    List <ThermoLabeledPeak> clusterPeaks = new List <ThermoLabeledPeak>();
                    List <int> RemoveIdx = new List <int>();
                    RemoveIdx.Add(0);
                    clusterPeaks.Add(BasePeak);
                    double Interval = 1 / (double)BasePeak.Charge;
                    double FirstMZ  = BasePeak.MZ;
                    for (int i = 1; i < FullLabeledPeak.Count; i++)
                    {
                        if (FullLabeledPeak[i].MZ - FirstMZ > Interval * 10)
                        {
                            break;
                        }
                        if ((FullLabeledPeak[i].MZ - (BasePeak.MZ + Interval)) < 0.1 && (FullLabeledPeak[i].MZ - (BasePeak.MZ + Interval)) >= 0 && clusterPeaks[0].Charge == FullLabeledPeak[i].Charge)
                        {
                            BasePeak = FullLabeledPeak[i];
                            clusterPeaks.Add(FullLabeledPeak[i]);
                            RemoveIdx.Add(i);
                        }
                    }
                    if (clusterPeaks.Count < 3)
                    {
                        FullLabeledPeak.RemoveAt(RemoveIdx[0]);
                    }
                    else
                    {
                        float  MostIntenseMZ        = 0.0f;
                        double MostIntenseIntneisty = 0;
                        double ClusterIntensity     = 0;
                        RemoveIdx.Reverse();
                        for (int i = 0; i < RemoveIdx.Count; i++)
                        {
                            if (FullLabeledPeak[RemoveIdx[i]].Intensity > MostIntenseIntneisty)
                            {
                                MostIntenseIntneisty = FullLabeledPeak[RemoveIdx[i]].Intensity;
                                MostIntenseMZ        = FullLabeledPeak[RemoveIdx[i]].MZ;
                            }
                            ClusterIntensity = ClusterIntensity + FullLabeledPeak[RemoveIdx[i]].Intensity;
                            FullLabeledPeak.RemoveAt(RemoveIdx[i]);
                        }
                        scan.MSPeaks.Add(new MSPeak(clusterPeaks[0].Mass, clusterPeaks[0].Intensity, clusterPeaks[0].Charge, clusterPeaks[0].MZ, clusterPeaks[0].SN, MostIntenseMZ, MostIntenseIntneisty, ClusterIntensity));
                    }
                } while (FullLabeledPeak.Count != 0);


                //Array.Clear(_transformResult, 0, _transformResult.Length);
                //Array.Clear(_cidPeaks, 0, _cidPeaks.Length);
                //Array.Clear(_cidMzs, 0, _cidMzs.Length);
                //Array.Clear(_cidIntensities, 0, _cidIntensities.Length);
            }
            return(scan);
        }
示例#7
0
        private void SleepT()
        {
            if (filedirectory_array.Length != 0)
            {
                #region
                for (int i_filedirectory = 0; i_filedirectory < pathway.Items.Count; i_filedirectory++)
                {
                    SetTextMessage_rawfile_num(i_filedirectory + 1);

                    //Utilize the MSFileReader to obtain the information from the DIA data;
                    filedirectory = (string)pathway.Items[i_filedirectory];
                    MSFileReader_XRawfile rawfile  = new MSFileReader_XRawfile();
                    IXRawfile5            rawfile5 = (IXRawfile5) new MSFileReader_XRawfile();
                    string rawpath = filedirectory;
                    rawfile.Open(rawpath);
                    rawfile.SetCurrentController(0, 1);
                    string rawpath5 = filedirectory;
                    rawfile5.Open(rawpath5);
                    rawfile5.SetCurrentController(0, 1);

                    string filename    = Path.GetFileName(filedirectory);
                    string newfilepath = Path.GetDirectoryName(filedirectory);
                    #region
                    if (extracttype == "MS1MS2Data")
                    {
                        //creat the output file names
                        string       outfilems1 = newfilepath + "\\" + "MS1Data_" + filename + ".txt";
                        StreamWriter swms1      = File.AppendText(outfilems1);
                        string       outfilems2 = newfilepath + "\\" + "MS2Data_" + filename + ".txt";
                        StreamWriter swms2      = File.AppendText(outfilems2);

                        //write the 9 columns information in the .txt file
                        swms1.Write("ScanNum\tMSOrder\tPeakNumber\tPeakNumberAfter\tRT\tm/z\tIntensity\tNoise\tBaseline\n");
                        swms2.Write("ScanNum\tMSOrder\tPeakNumber\tPeakNumberAfter\tRT\tm/z\tIntensity\tNoise\tBaseline\n");

                        int specnum = 0;
                        rawfile5.GetNumSpectra(ref specnum);
                        for (int i = 1; i <= specnum; i++)
                        {
                            System.Threading.Thread.Sleep(0);
                            SetTextMessage(100 * i / specnum);

                            int nOrder = 0;
                            rawfile5.GetMSOrderForScanNum(i, ref nOrder);
                            double scanRT = 0;
                            rawfile5.RTFromScanNum(i, ref scanRT);
                            object varlabels = null;
                            object varflags  = null;
                            rawfile5.GetLabelData(ref varlabels, ref varflags, ref i);
                            var labels = (double[, ])varlabels;
                            int dim    = labels.GetLength(1);

                            double massNeutron      = 1.00335; // massC13 - massC12
                            double mztol            = Convert.ToDouble(ionmtoltextbox.Text);
                            double mzdecontol       = Convert.ToDouble(ionmtoltextbox.Text);
                            double ms1sonthreshold  = Convert.ToDouble(ms1sontextbox.Text);
                            double ms2sonthreshold  = Convert.ToDouble(ms2sontextbox.Text);
                            double ms1resolutiontol = Convert.ToDouble(ms1unitoltextbox.Text);
                            double ms2resolutiontol = Convert.ToDouble(ms2unitoltextbox.Text);

                            if (nOrder == 1)
                            {
                                swms1.Write("{0}\t", i);
                                swms1.Write("{0}\t", nOrder);
                                swms1.Write("{0}\t", dim);

                                List <double> ms1mzlist        = new List <double>();
                                List <double> ms1intensitylist = new List <double>();
                                List <double> ms1chargelist    = new List <double>();
                                List <double> ms1noiselist     = new List <double>();
                                List <double> ms1baselinelist  = new List <double>();

                                for (int inx = 0; inx < dim; inx++)
                                {
                                    double dMassjms1 = labels[0, inx];
                                    double dInms1    = labels[1, inx];
                                    double dBasems1  = labels[3, inx];
                                    double dNoisems1 = labels[4, inx];
                                    double dChams1   = labels[5, inx];
                                    double sonms1    = 0;
                                    if (ms1rms_checkbox == "ms1rms")
                                    {
                                        //if checked, the S/N is changed to RMS S/N(root mean square signal over noise);
                                        sonms1 = (dInms1 - dBasems1) / (dNoisems1 - dBasems1);
                                    }
                                    else
                                    {
                                        sonms1 = dInms1 / dNoisems1;
                                    }

                                    if (sonms1 >= ms1sonthreshold)
                                    {
                                        ms1chargelist.Add(dChams1);
                                        ms1mzlist.Add(dMassjms1);
                                        ms1intensitylist.Add(dInms1);
                                        ms1noiselist.Add(dNoisems1);
                                        ms1baselinelist.Add(dBasems1);
                                    }
                                    else
                                    {
                                        //if the S/N is too low, set their values to zero
                                        ms1chargelist.Add(0);
                                        ms1mzlist.Add(0);
                                        ms1intensitylist.Add(0);
                                        ms1noiselist.Add(0);
                                        ms1baselinelist.Add(0);
                                    }
                                }

                                //remove the peaks, whose values of (m/z, intensity, charge, noise, baseline) are equal to zero;
                                List <int> ms1mzzeroindex = new List <int>();
                                for (int izero = 0; izero < ms1mzlist.Count; izero++)
                                {
                                    if (ms1mzlist[izero] == 0)
                                    {
                                        ms1mzzeroindex.Add(izero);
                                    }
                                }
                                for (int izero1 = 0; izero1 < ms1mzzeroindex.Count(); izero1++)
                                {
                                    ms1mzlist.RemoveAt(ms1mzzeroindex[izero1] - izero1);
                                    ms1intensitylist.RemoveAt(ms1mzzeroindex[izero1] - izero1);
                                    ms1baselinelist.RemoveAt(ms1mzzeroindex[izero1] - izero1);
                                    ms1noiselist.RemoveAt(ms1mzzeroindex[izero1] - izero1);
                                    ms1chargelist.RemoveAt(ms1mzzeroindex[izero1] - izero1);
                                }

                                //keep only one peak in a tolerance;
                                for (int ims1reso = 0; ims1reso < ms1mzlist.Count; ims1reso++)
                                {
                                    if (ms1mzlist[ims1reso] != 0)
                                    {
                                        double ms1mzreso        = ms1mzlist[ims1reso] * ms1intensitylist[ims1reso];
                                        double ms1intensityreso = ms1intensitylist[ims1reso];
                                        double ms1baselinereso  = ms1baselinelist[ims1reso];
                                        for (int jms1reso = ims1reso + 1; jms1reso < ms1mzlist.Count; jms1reso++)
                                        {
                                            double ms1resodiff = ms1mzlist[jms1reso] - ms1mzlist[jms1reso - 1];
                                            if (ms1resodiff > ms1resolutiontol)
                                            {
                                                break;
                                            }
                                            if (ms1resodiff <= ms1resolutiontol)
                                            {
                                                ms1mzreso                  = ms1mzreso + ms1mzlist[jms1reso] * ms1intensitylist[jms1reso];
                                                ms1intensityreso           = ms1intensityreso + ms1intensitylist[jms1reso];
                                                ms1intensitylist[jms1reso] = 0;
                                            }
                                        }
                                        ms1mzlist[ims1reso]        = ms1mzreso / ms1intensityreso;
                                        ms1intensitylist[ims1reso] = ms1intensityreso;
                                    }
                                }

                                List <int> ms1intensityzeroafterresoindex = new List <int>();
                                for (int izero = 0; izero < ms1mzlist.Count; izero++)
                                {
                                    if (ms1intensitylist[izero] == 0)
                                    {
                                        ms1intensityzeroafterresoindex.Add(izero);
                                    }
                                }
                                for (int izero1 = 0; izero1 < ms1intensityzeroafterresoindex.Count(); izero1++)
                                {
                                    ms1mzlist.RemoveAt(ms1intensityzeroafterresoindex[izero1] - izero1);
                                    ms1intensitylist.RemoveAt(ms1intensityzeroafterresoindex[izero1] - izero1);
                                    ms1baselinelist.RemoveAt(ms1intensityzeroafterresoindex[izero1] - izero1);
                                    ms1noiselist.RemoveAt(ms1intensityzeroafterresoindex[izero1] - izero1);
                                    ms1chargelist.RemoveAt(ms1intensityzeroafterresoindex[izero1] - izero1);
                                }

                                //if checked, the peaks are deisotoped, which could remove the isotope peaks;
                                if (deisotope_checkbox == "deisotope")
                                {
                                    List <int> ms1deisotopindexbefore = new List <int>();

                                    for (int ims1 = 0; ims1 < ms1mzlist.Count; ims1++)
                                    {
                                        if (ms1chargelist[ims1] != 0)
                                        {
                                            for (int jms1 = ims1 + 1; jms1 < ms1mzlist.Count; jms1++)
                                            {
                                                double ms1mzdiff   = ms1mzlist[jms1] - ms1mzlist[ims1];
                                                double ms1tolvalue = Math.Abs(massNeutron / ms1chargelist[ims1] - ms1mzdiff);
                                                if (ms1tolvalue < mztol && ms1intensitylist[jms1] < ms1intensitylist[ims1])
                                                {
                                                    ms1deisotopindexbefore.Add(jms1);
                                                }
                                            }
                                        }
                                    }

                                    List <int> ms1deisotopindex = new List <int>();
                                    foreach (int ms1deiso in ms1deisotopindexbefore)
                                    {
                                        if (!ms1deisotopindex.Contains(ms1deiso))
                                        {
                                            ms1deisotopindex.Add(ms1deiso);
                                        }
                                    }
                                    ms1deisotopindex.Sort();
                                    for (int ide1 = 0; ide1 < ms1deisotopindex.Count; ide1++)
                                    {
                                        ms1mzlist.RemoveAt(ms1deisotopindex[ide1] - ide1);
                                        ms1intensitylist.RemoveAt(ms1deisotopindex[ide1] - ide1);
                                        ms1baselinelist.RemoveAt(ms1deisotopindex[ide1] - ide1);
                                        ms1noiselist.RemoveAt(ms1deisotopindex[ide1] - ide1);
                                        ms1chargelist.RemoveAt(ms1deisotopindex[ide1] - ide1);
                                    }
                                }

                                //if checked, the peaks are deconvoluted to one charge;
                                if (deconvolution_checkbox == "deconvolution")
                                {
                                    for (int idems1 = 0; idems1 < ms1mzlist.Count; idems1++)
                                    {
                                        if (ms1chargelist[idems1] != 0)
                                        {
                                            ms1mzlist[idems1] = ms1mzlist[idems1] * ms1chargelist[idems1] - ms1chargelist[idems1] * 1.0079;
                                        }
                                    }
                                    List <int> ms1deconvolutionindexbefore = new List <int>();
                                    for (int ideconms1 = 0; ideconms1 < ms1mzlist.Count; ideconms1++)
                                    {
                                        if (ms1mzlist[ideconms1] != 0)
                                        {
                                            double ms1mzdecon        = ms1mzlist[ideconms1];
                                            double ms1intensitydecon = ms1intensitylist[ideconms1];
                                            double ms1baselinedecon  = ms1baselinelist[ideconms1];
                                            int    ims1deconcount    = 1;
                                            for (int jdeconms1 = ideconms1 + 1; jdeconms1 < ms1mzlist.Count; jdeconms1++)
                                            {
                                                double ms1mzdecondiff = Math.Abs(ms1mzlist[jdeconms1] - ms1mzlist[ideconms1]);
                                                if (ms1mzdecondiff <= mzdecontol)
                                                {
                                                    ms1deconvolutionindexbefore.Add(jdeconms1);
                                                    ms1mzdecon        = ms1mzdecon + ms1mzlist[jdeconms1];
                                                    ms1intensitydecon = ms1intensitydecon + ms1intensitylist[jdeconms1];
                                                    ims1deconcount++;
                                                }
                                            }
                                            ms1mzlist[ideconms1]        = ms1mzdecon / ims1deconcount;
                                            ms1intensitylist[ideconms1] = ms1intensitydecon;
                                        }
                                    }

                                    List <int> ms1deconvolutionindex = new List <int>();
                                    foreach (int ms1deiso in ms1deconvolutionindexbefore)
                                    {
                                        if (!ms1deconvolutionindex.Contains(ms1deiso))
                                        {
                                            ms1deconvolutionindex.Add(ms1deiso);
                                        }
                                    }
                                    ms1deconvolutionindex.Sort();
                                    for (int ide1 = 0; ide1 < ms1deconvolutionindex.Count; ide1++)
                                    {
                                        ms1mzlist.RemoveAt(ms1deconvolutionindex[ide1] - ide1);
                                        ms1intensitylist.RemoveAt(ms1deconvolutionindex[ide1] - ide1);
                                        ms1baselinelist.RemoveAt(ms1deconvolutionindex[ide1] - ide1);
                                        ms1noiselist.RemoveAt(ms1deconvolutionindex[ide1] - ide1);
                                        ms1chargelist.RemoveAt(ms1deconvolutionindex[ide1] - ide1);
                                    }
                                }

                                //write the data into the .txt file;
                                swms1.Write("{0}\t", ms1mzlist.Count);
                                swms1.Write("{0}\t", scanRT);
                                for (int ims1mz = 0; ims1mz < ms1mzlist.Count; ims1mz++)
                                {
                                    swms1.Write("{0};", ms1mzlist[ims1mz]);
                                }
                                swms1.Write("\t");
                                for (int ims1in = 0; ims1in < ms1intensitylist.Count; ims1in++)
                                {
                                    swms1.Write("{0};", ms1intensitylist[ims1in]);
                                }
                                swms1.Write("\t");
                                for (int ims1in = 0; ims1in < ms1noiselist.Count; ims1in++)
                                {
                                    swms1.Write("{0};", ms1noiselist[ims1in]);
                                }
                                swms1.Write("\t");
                                for (int ims1base = 0; ims1base < ms1baselinelist.Count; ims1base++)
                                {
                                    swms1.Write("{0};", ms1baselinelist[ims1base]);
                                }
                                swms1.Write("\n");
                            }
                            else //extract the ms/ms data, the process is similar with above;
                            {
                                swms2.Write("{0}\t", i);
                                swms2.Write("{0}\t", nOrder);
                                swms2.Write("{0}\t", dim);

                                List <double> ms2mzlist        = new List <double>();
                                List <double> ms2intensitylist = new List <double>();
                                List <double> ms2noiselist     = new List <double>();
                                List <double> ms2chargelist    = new List <double>();
                                List <double> ms2baselinelist  = new List <double>();


                                for (int inx = 0; inx < dim; inx++)
                                {
                                    double dMassjms2 = labels[0, inx];
                                    double dInms2    = labels[1, inx];
                                    double dBasems2  = labels[3, inx];
                                    double dNoisems2 = labels[4, inx];
                                    double dChams2   = labels[5, inx];
                                    double sonms2    = 0;
                                    if (ms2rms_checkbox == "ms2rms")
                                    {
                                        sonms2 = (dInms2 - dBasems2) / (dNoisems2 - dBasems2);
                                    }
                                    else
                                    {
                                        sonms2 = dInms2 / dNoisems2;
                                    }

                                    if (sonms2 >= ms2sonthreshold)
                                    {
                                        ms2chargelist.Add(dChams2);
                                        ms2mzlist.Add(dMassjms2);
                                        ms2intensitylist.Add(dInms2);
                                        ms2noiselist.Add(dNoisems2);
                                        ms2baselinelist.Add(dBasems2);
                                    }
                                    else
                                    {
                                        ms2chargelist.Add(0);
                                        ms2mzlist.Add(0);
                                        ms2intensitylist.Add(0);
                                        ms2noiselist.Add(0);
                                        ms2baselinelist.Add(0);
                                    }
                                }

                                List <int> ms2mzzeroindex = new List <int>();
                                for (int izero = 0; izero < ms2mzlist.Count; izero++)
                                {
                                    if (ms2mzlist[izero] == 0)
                                    {
                                        ms2mzzeroindex.Add(izero);
                                    }
                                }
                                for (int izero1 = 0; izero1 < ms2mzzeroindex.Count(); izero1++)
                                {
                                    ms2mzlist.RemoveAt(ms2mzzeroindex[izero1] - izero1);
                                    ms2intensitylist.RemoveAt(ms2mzzeroindex[izero1] - izero1);
                                    ms2baselinelist.RemoveAt(ms2mzzeroindex[izero1] - izero1);
                                    ms2noiselist.RemoveAt(ms2mzzeroindex[izero1] - izero1);
                                    ms2chargelist.RemoveAt(ms2mzzeroindex[izero1] - izero1);
                                }

                                for (int ims2reso = 0; ims2reso < ms2mzlist.Count; ims2reso++)
                                {
                                    if (ms2mzlist[ims2reso] != 0)
                                    {
                                        double ms2mzreso        = ms2mzlist[ims2reso] * ms2intensitylist[ims2reso];
                                        double ms2intensityreso = ms2intensitylist[ims2reso];
                                        double ms2baselinereso  = ms2baselinelist[ims2reso];
                                        int    iresocount       = 1;
                                        for (int jms2reso = ims2reso + 1; jms2reso < ms2mzlist.Count; jms2reso++)
                                        {
                                            double ms2resodiff = ms2mzlist[jms2reso] - ms2mzlist[jms2reso - 1];
                                            if (ms2resodiff > ms2resolutiontol)
                                            {
                                                break;
                                            }
                                            if (ms2resodiff <= ms2resolutiontol)
                                            {
                                                ms2mzreso                  = ms2mzreso + ms2mzlist[jms2reso] * ms2intensitylist[jms2reso];
                                                ms2intensityreso           = ms2intensityreso + ms2intensitylist[jms2reso];
                                                ms2intensitylist[jms2reso] = 0;
                                                iresocount++;
                                            }
                                        }
                                        ms2mzlist[ims2reso]        = ms2mzreso / ms2intensityreso;
                                        ms2intensitylist[ims2reso] = ms2intensityreso;
                                    }
                                }

                                List <int> ms2intensityzeroafterresoindex = new List <int>();
                                for (int izero = 0; izero < ms2mzlist.Count; izero++)
                                {
                                    if (ms2intensitylist[izero] == 0)
                                    {
                                        ms2intensityzeroafterresoindex.Add(izero);
                                    }
                                }
                                for (int izero1 = 0; izero1 < ms2intensityzeroafterresoindex.Count(); izero1++)
                                {
                                    ms2mzlist.RemoveAt(ms2intensityzeroafterresoindex[izero1] - izero1);
                                    ms2intensitylist.RemoveAt(ms2intensityzeroafterresoindex[izero1] - izero1);
                                    ms2baselinelist.RemoveAt(ms2intensityzeroafterresoindex[izero1] - izero1);
                                    ms2noiselist.RemoveAt(ms2intensityzeroafterresoindex[izero1] - izero1);
                                    ms2chargelist.RemoveAt(ms2intensityzeroafterresoindex[izero1] - izero1);
                                }

                                if (deisotope_checkbox == "deisotope")
                                {
                                    List <int> ms2deisotopindexbefore = new List <int>();
                                    for (int ims2 = 0; ims2 < ms2mzlist.Count(); ims2++)
                                    {
                                        if (ms2chargelist[ims2] != 0)
                                        {
                                            for (int jms2 = ims2 + 1; jms2 < ms2mzlist.Count(); jms2++)
                                            {
                                                double ms2mzdiff   = ms2mzlist[jms2] - ms2mzlist[ims2];
                                                double ms2tolvalue = Math.Abs(massNeutron / ms2chargelist[ims2] - ms2mzdiff);
                                                if (ms2tolvalue <= mztol && ms2intensitylist[jms2] < ms2intensitylist[ims2])
                                                {
                                                    ms2deisotopindexbefore.Add(jms2);
                                                }
                                            }
                                        }
                                    }

                                    List <int> ms2deisotopindex = new List <int>();
                                    foreach (int ms2deiso in ms2deisotopindexbefore)
                                    {
                                        if (!ms2deisotopindex.Contains(ms2deiso))
                                        {
                                            ms2deisotopindex.Add(ms2deiso);
                                        }
                                    }
                                    ms2deisotopindex.Sort();
                                    for (int ide2 = 0; ide2 < ms2deisotopindex.Count(); ide2++)
                                    {
                                        ms2mzlist.RemoveAt(ms2deisotopindex[ide2] - ide2);
                                        ms2intensitylist.RemoveAt(ms2deisotopindex[ide2] - ide2);
                                        ms2noiselist.RemoveAt(ms2deisotopindex[ide2] - ide2);
                                        ms2baselinelist.RemoveAt(ms2deisotopindex[ide2] - ide2);
                                        ms2chargelist.RemoveAt(ms2deisotopindex[ide2] - ide2);
                                    }
                                }

                                if (deconvolution_checkbox == "deconvolution")
                                {
                                    for (int idems2 = 0; idems2 < ms2mzlist.Count; idems2++)
                                    {
                                        if (ms2chargelist[idems2] != 0)
                                        {
                                            ms2mzlist[idems2] = ms2mzlist[idems2] * ms2chargelist[idems2] - (ms2chargelist[idems2] - 1) * 1.0079;
                                        }
                                    }
                                    List <int> ms2deconvolutionindexbefore = new List <int>();
                                    for (int ideconms2 = 0; ideconms2 < ms2mzlist.Count; ideconms2++)
                                    {
                                        if (ms2mzlist[ideconms2] != 0)
                                        {
                                            double ms2mzdecon        = ms2mzlist[ideconms2];
                                            double ms2intensitydecon = ms2intensitylist[ideconms2];
                                            int    ims2deconcount    = 1;
                                            for (int jdeconms2 = ideconms2 + 1; jdeconms2 < ms2mzlist.Count; jdeconms2++)
                                            {
                                                double ms2mzdecondiff = Math.Abs(ms2mzlist[jdeconms2] - ms2mzlist[ideconms2]);
                                                if (ms2mzdecondiff <= mzdecontol)
                                                {
                                                    ms2deconvolutionindexbefore.Add(jdeconms2);
                                                    ms2mzdecon        = ms2mzdecon + ms2mzlist[jdeconms2];
                                                    ms2intensitydecon = ms2intensitydecon + ms2intensitylist[jdeconms2];
                                                    ims2deconcount++;
                                                }
                                            }
                                            ms2mzlist[ideconms2]        = ms2mzdecon / ims2deconcount;
                                            ms2intensitylist[ideconms2] = ms2intensitydecon;
                                        }
                                    }
                                    List <int> ms2deconvolutionindex = new List <int>();
                                    foreach (int ms2deiso in ms2deconvolutionindexbefore)
                                    {
                                        if (!ms2deconvolutionindex.Contains(ms2deiso))
                                        {
                                            ms2deconvolutionindex.Add(ms2deiso);
                                        }
                                    }
                                    ms2deconvolutionindex.Sort();
                                    for (int ide2 = 0; ide2 < ms2deconvolutionindex.Count; ide2++)
                                    {
                                        ms2mzlist.RemoveAt(ms2deconvolutionindex[ide2] - ide2);
                                        ms2intensitylist.RemoveAt(ms2deconvolutionindex[ide2] - ide2);
                                        ms2baselinelist.RemoveAt(ms2deconvolutionindex[ide2] - ide2);
                                        ms2noiselist.RemoveAt(ms2deconvolutionindex[ide2] - ide2);
                                        ms2chargelist.RemoveAt(ms2deconvolutionindex[ide2] - ide2);
                                    }
                                }

                                swms2.Write("{0}\t", ms2mzlist.Count);
                                swms2.Write("{0}\t", scanRT);

                                for (int ims2mz = 0; ims2mz < ms2mzlist.Count; ims2mz++)
                                {
                                    swms2.Write("{0};", ms2mzlist[ims2mz]);
                                }
                                swms2.Write("\t");
                                for (int ims2in = 0; ims2in < ms2intensitylist.Count; ims2in++)
                                {
                                    swms2.Write("{0};", ms2intensitylist[ims2in]);
                                }
                                swms2.Write("\t");
                                for (int ims2noise = 0; ims2noise < ms2noiselist.Count; ims2noise++)
                                {
                                    swms2.Write("{0};", ms2noiselist[ims2noise]);
                                }
                                swms2.Write("\t");
                                for (int ims2base = 0; ims2base < ms2baselinelist.Count; ims2base++)
                                {
                                    swms2.Write("{0};", ms2baselinelist[ims2base]);
                                }
                                swms2.Write("\n");
                            }
                        }
                        swms1.Flush();
                        swms1.Close();
                        swms2.Flush();
                        swms2.Close();
                    }
                    #endregion
                    #region
                    else if (extracttype == "LocalData(SMPR)")
                    {
                        // creat a new file name for "LocalData(SMPR)";
                        string       outfile = newfilepath + "\\" + "LocalData(SMPR)_" + filename + ".txt";
                        StreamWriter sw      = File.AppendText(outfile);

                        sw.Write("ScanNum\tMSOrder\tPeakNumber\tRT\n");

                        int specnum = 0;
                        rawfile.GetNumSpectra(ref specnum);
                        for (int i = 1; i <= specnum; i++)
                        {
                            System.Threading.Thread.Sleep(0);
                            SetTextMessage(100 * i / specnum);

                            int nOrder = 0;
                            rawfile5.GetMSOrderForScanNum(i, ref nOrder);
                            double scanRT = 0;
                            rawfile.RTFromScanNum(i, ref scanRT);

                            sw.Write("{0}\t", i);
                            sw.Write("{0}\t", nOrder);

                            object varlabels = null;
                            object varflags  = null;
                            rawfile5.GetLabelData(ref varlabels, ref varflags, ref i);
                            var labels = (double[, ])varlabels;
                            int dim    = labels.GetLength(1);
                            sw.Write("{0}\t", dim);
                            sw.Write("{0}\n", scanRT);
                        }
                        sw.Flush();
                        sw.Close();
                    }
                    //
                    else
                    {
                        MessageBox.Show("Please Select a type below!");
                    }
                    #endregion
                }
                MessageBox.Show("Extract Done!");
            }
            else
            {
                MessageBox.Show("Please Select a File!");
            }
            #endregion
        }