Ejemplo n.º 1
0
 static void Main(string[] args)
 {
     MSFileReader_XRawfile rawMSfile = new MSFileReader_XRawfile();
     rawMSfile.Open("L:\\Davi\\_QE\\BSAs\\20150512_BSA_The-PEG-envelope.raw");
     rawMSfile.SetCurrentController(0, 1); /* Controller type 0 means mass spec device; Controller 1 means first MS device */
     int nms = 0; /* ref int usrd with GetNumSpectra */
     int pbMSData=0;
     int pnLastSpectrum=0;
     rawMSfile.GetNumSpectra(ref nms);
     rawMSfile.IsThereMSData(ref pbMSData);
     rawMSfile.GetLastSpectrumNumber(ref pnLastSpectrum);
     Debug.WriteLine("Total Spectra: " + nms);
     Debug.WriteLine("MSdata: " + pbMSData);
     Debug.WriteLine("Last MSdata: " + pnLastSpectrum);
     double pkWidCentroid = 0.0;
     object mzList = null;
     object pkFlg = null;
     int arrLen = 0;
     for (int i = 1; i < 10; i++){
         rawMSfile.GetMassListFromScanNum(i, null, 1, 0, 0, 0, ref pkWidCentroid, ref mzList, ref pkFlg, ref arrLen);
         double[,] mslist = (double[,])mzList;
         //for (int j = 0; j < 2; j++){
             Debug.WriteLine("MSdata: " + mslist[0,i] + "MSdata: " + mslist[1,i] + "Scan:" + i);
         //}
     }
 }
Ejemplo n.º 2
0
        static int Main(string[] args)
        {
            //Параметры соответствуют вводу в форму RawtoMGF
            //args[0] - имя Raw-файла
            //args[1] - имя MGF-файла
            //args[2] - minimal MZ
            //args[3] - maximal MZ
            //args[4] - minimal RT
            //args[5] - maximal RT
            //args[6] - minimal Charge
            //args[7] - maximal Charge
            //args[8] - number of top peaks
            //args[9] - CleanETD:yes / CleanETD:no
            //args[10] - Instrument:yes / Instrument:no
            //дополнительно (к версии 2.0.6)
            //args[11] - CheckSpectra:yes / CheckSpectra:no
            try{
                Console.ReadLine();
                //Thread.Sleep(30000);
                string InFileName = args[0];
                string OutFileName = args[1];
                double MinMZ = Convert.ToDouble(args[2]);
                double MaxMZ = Convert.ToDouble(args[3]);
                double MinRT = Convert.ToDouble(args[4]);
                double MaxRT = Convert.ToDouble(args[5]);
                int MinCharge = Convert.ToInt32(args[6]);
                int MaxCharge = Convert.ToInt32(args[7]);
                int MaxPeakNumber = Convert.ToInt32(args[8]);
                bool CleanETD = args[9].Contains("CleanETD:yes");
                bool MarkInstrtument = args[10].Contains("Instrument:yes");
                bool CheckSpectra = args[11].Contains("CheckSpectra:yes");
                bool RTApex = args[12].Contains("RTApex:yes");

                string[] Refs = {"@cid","@hcd","@etd","@ecd","FTMS","ITMS"};

                MSFileReader_XRawfile RawFile;
                int Spectra,LocalCount = 0;
                string Filter;
                MGFFile MGF;
                MGFSpectrum ms;
                Childs ch;
                ChildbyIntensity ci = new ChildbyIntensity();
                ChildbyMass cm  = new ChildbyMass();

                int ArraySize = 0;
                Object MassList, EmptyRef;
                Object Labels,Values;
                double temp=0.0;
                int Progress = 0;
                int MSCount = 0;
                int MSMSCount = 0;

                if (RTApex){
                    MSFileBox = new RawFileBox();
                    MSFileBox.LoadIndex(InFileName);
                    RawFileBox.RepProgress = RepProgress;
                    RawFile = MSFileBox.RawFile;
                }else{
                    RawFile = new MSFileReader_XRawfile();
                    RawFile.Open(InFileName);
                    RawFile.SetCurrentController(0, 1);
                }
                Spectra = 0;
                RawFile.GetNumSpectra(ref Spectra);
                if (Spectra == 0) {
                    throw new Exception("Cannot get spectra from the file "+InFileName+", File is invalid, broken or empty");
                }
                MGF = new MGFFile();
                for (int j=1 ; j<=Spectra ; j++){
                    Filter = null;
                    RawFile.GetFilterForScanNum(j, ref Filter);
                    if (Filter.IndexOf("ms2") == -1) {
                        MSCount++;
                        if (!CheckSpectra){
                            continue;
                        }else{
                            ArraySize = 0;
                            MassList = null;
                            EmptyRef=null;
                            temp=0.0;
                            try {
                                RawFile.GetMassListFromScanNum(ref j, null, 0, 0, 0, 0,
                                    ref temp, ref MassList, ref EmptyRef, ref ArraySize);
                                continue;
                            }catch{
                                Exception e = new Exception(string.Format("Scan #{0} cannot be loaded, probably RAW file is corrupted!",j));
                                throw e;
                            }
                        }
                    }
                    MSMSCount++;
                    ms = new MGFSpectrum();
                    //определяем родительскую массу, заряд и RT
                    Labels = null;
                    Values = null;
                    ArraySize = 0;
                    LocalCount++;
                    RawFile.GetTrailerExtraForScanNum(j, ref Labels, ref Values, ref ArraySize);
                    for (int k = 0 ; k < ArraySize ; k++ ){
                        if ((Labels as Array).GetValue(k).ToString().Contains("Mono")){
                            ms.mz = Convert.ToDouble((Values as Array).GetValue(k).ToString());
                        }
                        if ((Labels as Array).GetValue(k).ToString().Contains("Charge State")){
                            ms.Charge = Convert.ToInt32((Values as Array).GetValue(k).ToString());
                        }
                    }
                    //Если не нашли в labels - берем из фильтра
                    if (ms.mz == 0.0) {
                        string  part= Filter.Substring(0,Filter.IndexOf('@'));
                        ms.mz = Convert.ToDouble(part.Substring(part.LastIndexOf(' ')));
                    }
                    Labels = null;
                    Values = null;
                    ArraySize = 0;
                    double RT = 0;
                    RawFile.GetStatusLogForScanNum(j,ref RT, ref Labels, ref Values, ref ArraySize);

                    RawFile.RTFromScanNum(j,ref ms.RT);
                    ms.ScanNumber = j;
                    //Фильтры
                    if (ms.Charge < MinCharge) continue;
                    if (ms.Charge > MaxCharge) continue;
                    if (ms.RT < MinRT) continue;
                    if (MaxRT != 0.0 && ms.RT > MaxRT) continue;
                    if (ms.mz < MinMZ) continue;
                    if (MaxMZ != 0.0 && ms.mz > MaxMZ) continue;
                    //забираем сам спектр
                    MassList = null;
                    EmptyRef=null;
                    ArraySize = 0;
                    temp=0.0;
                    try{
                        if (Filter.IndexOf("FTMS") != -1){
                            //извлекаем FTMS данные
                            (RawFile as IXRawfile2).GetLabelData(ref MassList, ref EmptyRef, ref  j);
                            ArraySize = (MassList as Array).GetLength(1);
                            for (int k = 0 ; k<ArraySize ; k++ ){
                                ch = new Childs();
                                ch.Mass = (double)(MassList as Array).GetValue(0, k);
                                ch.Intensity = (double)(MassList as Array).GetValue(1, k);
                                ms.Data.Add(ch);
                            }
                        }else{
                            //извлекаем ITMS данные
                            RawFile.GetMassListFromScanNum(ref j, null, 0, 0, 0, 1, ref temp, ref MassList, ref EmptyRef, ref ArraySize);
                            ArraySize = (MassList as Array).GetLength(1);
                            for ( int k = 0 ; k<ArraySize ; k++){
                                ch = new Childs();
                                ch.Mass = (double)(MassList as Array).GetValue(0, k);
                                ch.Intensity = (double)(MassList as Array).GetValue(1, k);
                                ms.Data.Add(ch);
                            }
                        }
                    }catch{
                        Exception e = new Exception(string.Format("Scan #{0} cannot be loaded, probably RAW file is corrupted!",j));
                        throw e;
                    }
                    if (RTApex){
                        ms.RTApex = CheckRTApex(ms.RT, ms.mz);
                    }

                    if (MarkInstrtument){
                        if (Filter.Contains("ecd") || Filter.Contains("etd")){
                                ms.Instrument = "ETD-TRAP";
                            }else{
                                ms.Instrument= "ESI-FTICR";
                            }
                        }
                    //очистить ETD если был такой запрос
                    if ( CleanETD ){
                        if (Filter.Contains("ecd") || Filter.Contains("etd")){
                            FilterETD(ref ms,  Filter.Contains("FTMS"));
                        }
                    }
                    //сбросить лишние сигналы
                    if (MaxPeakNumber > 0 && ms.Data.Count > MaxPeakNumber){
                        ms.Data.Sort(ci);
                        ms.Data.RemoveRange(0,ms.Data.Count-MaxPeakNumber);
                        ms.Data.Sort(cm);
                    }
                    //сформировать TITLE
                    if (RTApex){
                        ms.Title = String.Format("Elution from: {0:f4} to {0:f4} RT Apex: {1:f2} FinneganScanNumber: {2}",
                            ms.RT, ms.RTApex, ms.ScanNumber);
                    }else{
                        ms.Title = String.Format("Elution from: {0:f4} to {0:f4} FinneganScanNumber: {1}",
                            ms.RT,ms.ScanNumber);
                    }
                    MGF.Spectra.Add(ms);
                    // рапортовать прогресс
                    GC.Collect(2);

                    if ((int)(((double)j/(double)Spectra)*100.0) > Progress){
                        Progress = (int)(((double)j/(double)Spectra)*100.0);
                        Console.WriteLine("{0}%... {1} {2}",Progress,MSCount,MSMSCount);
                    }

                    //backgroundWorker1.ReportProgress((int)(((double)LocalCount/(double)SpCount)*100.0));
                }
                MGF.MGFComments.Add(String.Format("Created by RawToMGF 2.1.3; Spectra obtained from {0}",InFileName));
                MGF.MGFComments.Add(String.Format("Filters: Parent m/z from {0} Th to {1} Th;",MinMZ,MaxMZ));
                MGF.MGFComments.Add(String.Format("         RT from {0} min. to {1} min.;",MinRT,MaxRT));
                MGF.MGFComments.Add(String.Format("         Charge state of parent ions minimum {0}, maximum {1};",MinCharge,MaxCharge));
                MGF.MGFComments.Add(String.Format("         Max number of peaks in MS/MS spectra - {0}",MaxPeakNumber));
                if ( CleanETD ) {
                    MGF.MGFComments.Add("         ETD spectra cleaned from precursors and neutral losses");
                }
                MGF.MGFWrite(OutFileName,true);
            }catch(Exception e){
                Console.Write("Error:");
                Console.Write(e.Message);
                Console.WriteLine("STACKINFO:"+e.StackTrace);
                //Console.ReadKey();
                return 1;
            }
            Console.WriteLine("Completed");
            Console.ReadLine();
            return 0;
        }
Ejemplo n.º 3
0
        public MSFileReader_XRawfile RawFile; //instance of LC-MS run

        public override int LoadIndex(string FileName)
        {
            this.RawFileName = FileName;

            RawFile = new MSFileReader_XRawfile();
            RawFile.Open(FileName);
            RawFile.SetCurrentController(0, 1);
            Spectra = 0;
            RawFile.GetNumSpectra(ref Spectra);

            if (Spectra <= 0) //if there are no spectra available
            {
                return(0);
            }

            int i, LastFull = 0, Total = 0;

            //there will be fake [0] spectra with no data and fake last spectra with no data
            //it is made to make any chromatogram start and end with zero
            IndexDir   = new int[Spectra + 2];
            IndexRev   = new int[Spectra + 2];
            RawSpectra = new RawSpectrum[Spectra + 2];
            for (int j = 0; j <= Spectra + 1; j++)
            {
                RawSpectra[j] = new RawSpectrum();
            }

            TimeStamps = new double[Spectra + 2];
            TimeCoefs  = new double[Spectra + 2];

            string Filter = null;
            bool   PosMode = false, NegMode = false;

            LowRT  = 0.0;
            HighRT = 0.0;

            int Progress = 0;

            for (i = 1; i <= Spectra; i++)
            {
                if ((int)(100.0 * ((double)i / (double)Spectra)) > Progress) //report progress
                {
                    Progress = (int)(100.0 * ((double)i / (double)Spectra));
                    RepProgress?.Invoke(Progress);
                }

                RawFile.GetFilterForScanNum(i, ref Filter);                                          //to reveal spectra properties we parse filter string

                if (Filter.Contains(" Full ") && Filter.Contains(" ms ") && Filter.Contains("FTMS")) //is a FULL MS

                {
                    PosMode |= Filter.Contains(" + ");
                    NegMode |= Filter.Contains(" - ");

                    RawFile.RTFromScanNum(i, ref RawSpectra[i].RT);
                    RawSpectra[i].Scan = i;
                    TimeStamps[i]      = RawSpectra[i].RT - RawSpectra[LastFull].RT;

                    IndexDir[LastFull] = i;
                    IndexRev[i]        = LastFull;

                    LastFull = i;

                    Total++;
                }
                Filter = null;
            }
            IndexDir[LastFull]    = Spectra + 1; //boundaries of navigation arrays
            IndexDir[Spectra + 1] = -1;
            IndexRev[Spectra + 1] = LastFull;

            TotalRT          = RawSpectra[LastFull].RT;
            AverageTimeStamp = TotalRT / Total;

            //time interval bias coefficients
            for (i = IndexDir[0]; IndexDir[i] != -1; i = IndexDir[i])
            {
                TimeCoefs[i] = (TimeStamps[i] + TimeStamps[IndexDir[i]]) / (2.0 * AverageTimeStamp);
            }
            TimeCoefs[i] = 1.0;
            //Fake spectra number 0 has to have reasonable RT
            double FRT = RawSpectra[IndexDir[0]].RT;            //First full spectra RT
            double SRT = RawSpectra[IndexDir[IndexDir[0]]].RT;  //Second full spectra RT

            RawSpectra[0].RT = Math.Max(0, FRT - (SRT - FRT));  // 0 or make the same distance like between 1-st and 2-nd spectra
            //Last spectra also has to have reasonable RT
            FRT = RawSpectra[LastFull].RT;                      //the same for last spectra
            SRT = RawSpectra[IndexRev[LastFull]].RT;
            RawSpectra[Spectra + 1].RT   = FRT + (FRT - SRT);
            RawSpectra[Spectra + 1].Scan = RawSpectra[Spectra].Scan + 1;

            RawSpectra[0].Data           = new MZData[0];
            RawSpectra[Spectra + 1].Data = new MZData[0];

            if (PosMode && !NegMode)
            {
                Mode = 1;
            }
            if (!PosMode && NegMode)
            {
                Mode = -1;
            }

            return(Spectra);
        }
Ejemplo n.º 4
0
        public Form2(double[] Values, string flname)
        {
            InitializeComponent();
            //this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            foreach (var item in Values)
            {
                Console.Write(item.ToString() + " ");
            }
            Console.WriteLine();
            this.Text = flname;
            TextBox t = new TextBox();

            t.Text     = "Spot Number: " + (Values[0]).ToString();
            t.Location = new Point(15, 15);
            this.Controls.Add(t);
            chart1.Series["MassSpectrum"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
            t.BringToFront();
            int[,] sample = new int[2, 10];

            MSFileReader_XRawfile rawfile = new MSFileReader_XRawfile();

            rawfile.Open(flname);
            rawfile.SetCurrentController(0, 1);
            int ScanNumber = Convert.ToInt32(Values[0]);

            double Centroid_Peak_Width = 0.0;
            object Mass_List           = null;
            object Peak_Flags          = null;
            int    Array_Size          = 0;

            rawfile.GetMassListFromScanNum(ref ScanNumber, null, 1, 0, 0, 0, ref Centroid_Peak_Width, ref Mass_List, ref Peak_Flags, ref Array_Size);
            double[,] ms_list = (double[, ])Mass_List;
            //Random rdn = new Random();
            //chart1.Series.Add("Series2");
            double[] found = new double[(Values.Length - 2) / 2];
            //int start = 2;
            for (int i = 0; i < ms_list.Length / 2; i++)
            {
                /*for(int j = start; j < Values.Length; j = j + 2)
                 * {
                 *  if ((ms_list[0,i] > Values[j]-0.005) && (ms_list[0, i] < Values[j] + 0.005))
                 *  {
                 *      found[(j - 2) / 2] = ms_list[0, i];
                 *      start = j + 2;
                 *  }
                 * }*/
                DataPoint dp2 = new DataPoint(ms_list[0, i], ms_list[1, i]);
                chart1.Series["MassSpectrum"].Points.Add(dp2);
                //  (rdn.Next(0, 10), rdn.Next(0, 10));
            }
            for (int j = 2; j < Values.Length; j = j + 2)
            {
                //chart1.Series["MassSpectrum"].Points.FindByValue(found[j], "X").IsValueShownAsLabel = true; // = "("+Values[2*j+2]+", "+Values[2*j+3]+")";
                DataPoint dtp = chart1.Series["MassSpectrum"].Points.Aggregate((x, y) => Math.Abs(x.XValue - Values[j]) < Math.Abs(y.XValue - Values[j]) ? x : y);
                //DataPoint dtp = chart1.Series["MassSpectrum"].Points.FindByValue(found[j], "X");
                double temp = new double();
                temp      = Math.Round(dtp.XValue, 2);
                dtp.Label = temp.ToString();               //"(" + Values[2 * j + 2] + ", " + Values[2 * j + 3] + ")";
            }
            //chart1.Series["Series2"].Enabled = false;
            //chart1.Series["Series2"].IsValueShownAsLabel = true;

            chart1.Series["MassSpectrum"].Color = Color.Blue;
        }
Ejemplo n.º 5
0
        public int LoadIndex(string FileName)
        {
            this.RawFileName = FileName;

            RawFile = new MSFileReader_XRawfile();

            RawFile.Open(FileName);
            RawFile.SetCurrentController(0, 1);

            Spectra = 0;
            RawFile.GetNumSpectra(ref Spectra);

            if (Spectra <= 0)
            {
                return(0);
            }

            int    i, lastfull = 0, total = 0;
            double TotalEsi = 0.0;

            ms2index   = new int[Spectra + 1];
            IndexDir   = new int[Spectra + 1];
            IndexRev   = new int[Spectra + 1];
            RawSpectra = new RawData[Spectra + 1];
            for (int j = 0; j <= Spectra; j++)
            {
                RawSpectra[j] = new RawData();
            }
            Buf = new MZData[1000000];

            ESICurrents = new double[Spectra + 1];
            TimeStamps  = new double[Spectra + 1];
            TimeCoefs   = new double[Spectra + 1];

            string Filter = null;

            LowRT  = 0.0;
            HighRT = 0.0;

            int Progress = 0;

            for (i = 1; i <= Spectra; i++)
            {
                if ((int)(100.0 * ((double)i / (double)Spectra)) > Progress)
                {
                    Progress = (int)(100.0 * ((double)i / (double)Spectra));
                    if (RepProgress != null)
                    {
                        RepProgress(Progress);
                    }
                }

                RawFile.GetFilterForScanNum(i, ref Filter);

                //YL - для спектров ms-only
                //Заплатка для MSX спектров
                if ((Filter.IndexOf(" ms ") != -1) && (Filter.IndexOf("FTMS") != -1))          //is a FULL MS

                {
                    TimeStamps[i] = RawSpectra[lastfull].RT;

                    IndexDir[lastfull] = i;
                    IndexRev[i]        = lastfull;

                    lastfull    = i;
                    ms2index[i] = lastfull;

                    ++total;

                    RawFile.RTFromScanNum(i, ref RawSpectra[i].RT);
                    RawSpectra[i].Filter = Filter;
                    TotalRT = RawSpectra[i].RT;

                    TimeStamps[i] = RawSpectra[i].RT - TimeStamps[i];

                    object Labels    = null;
                    object Values    = null;
                    int    ArraySize = 0;
                    double RT        = 0.0;

                    RawFile.GetStatusLogForScanNum(i, ref RT, ref Labels, ref Values, ref ArraySize);

                    for (int k = 0; k < ArraySize; k++)
                    {
                        if ((Labels as Array).GetValue(k).ToString().Contains("Source Current"))
                        {
                            ESICurrents[i] = Convert.ToDouble((Values as Array).GetValue(k).ToString());
                            TotalEsi      += ESICurrents[i];
                        }
                    }
                }
                else
                {
                    ms2index[i] = lastfull;
                }
                Filter = null;
            }
            IndexDir[lastfull] = -1;
            TotalRT            = RawSpectra[lastfull].RT;
            AverageTimeStamp   = TotalRT / total;

            //пересчитаем временные коэффициэнты
            for (i = IndexDir[0]; IndexDir[i] != -1; i = IndexDir[i])
            {
                TimeCoefs[i] = (TimeStamps[i] + TimeStamps[IndexDir[i]]) / (2.0 * AverageTimeStamp);

                ESICurrents[i] = ESICurrents[i] / (TotalEsi / (double)total);
            }
            TimeCoefs[i] = 1.0;

            return(Spectra);
        }
Ejemplo n.º 6
0
        static double MZError = 10; //ppm

        static int Main(string[] args)
        {
            //Параметры соответствуют вводу в форму RawtoMGF
            //args[0] - имя Raw-файла
            //args[1] - имя MGF-файла
            //args[2] - minimal MZ
            //args[3] - maximal MZ
            //args[4] - minimal RT
            //args[5] - maximal RT
            //args[6] - minimal Charge
            //args[7] - maximal Charge
            //args[8] - number of top peaks
            //args[9] - CleanETD:yes / CleanETD:no
            //args[10] - Instrument:yes / Instrument:no
            //дополнительно (к версии 2.0.6)
            //args[11] - CheckSpectra:yes / CheckSpectra:no
            try{
                Console.ReadLine();
                //Thread.Sleep(30000);
                string InFileName      = args[0];
                string OutFileName     = args[1];
                double MinMZ           = Convert.ToDouble(args[2]);
                double MaxMZ           = Convert.ToDouble(args[3]);
                double MinRT           = Convert.ToDouble(args[4]);
                double MaxRT           = Convert.ToDouble(args[5]);
                int    MinCharge       = Convert.ToInt32(args[6]);
                int    MaxCharge       = Convert.ToInt32(args[7]);
                int    MaxPeakNumber   = Convert.ToInt32(args[8]);
                bool   CleanETD        = args[9].Contains("CleanETD:yes");
                bool   MarkInstrtument = args[10].Contains("Instrument:yes");
                bool   CheckSpectra    = args[11].Contains("CheckSpectra:yes");
                bool   RTApex          = args[12].Contains("RTApex:yes");

                string[] Refs = { "@cid", "@hcd", "@etd", "@ecd", "FTMS", "ITMS" };

                MSFileReader_XRawfile RawFile;
                int              Spectra, LocalCount = 0;
                string           Filter;
                MGFFile          MGF;
                MGFSpectrum      ms;
                Childs           ch;
                ChildbyIntensity ci = new ChildbyIntensity();
                ChildbyMass      cm = new ChildbyMass();


                int    ArraySize = 0;
                Object MassList, EmptyRef;
                Object Labels, Values;
                double temp      = 0.0;
                int    Progress  = 0;
                int    MSCount   = 0;
                int    MSMSCount = 0;

                if (RTApex)
                {
                    MSFileBox = new RawFileBox();
                    MSFileBox.LoadIndex(InFileName);
                    RawFileBox.RepProgress = RepProgress;
                    RawFile = MSFileBox.RawFile;
                }
                else
                {
                    RawFile = new MSFileReader_XRawfile();
                    RawFile.Open(InFileName);
                    RawFile.SetCurrentController(0, 1);
                }
                Spectra = 0;
                RawFile.GetNumSpectra(ref Spectra);
                if (Spectra == 0)
                {
                    throw new Exception("Cannot get spectra from the file " + InFileName + ", File is invalid, broken or empty");
                }
                MGF = new MGFFile();
                for (int j = 1; j <= Spectra; j++)
                {
                    Filter = null;
                    RawFile.GetFilterForScanNum(j, ref Filter);
                    if (Filter.IndexOf("ms2") == -1)
                    {
                        MSCount++;
                        if (!CheckSpectra)
                        {
                            continue;
                        }
                        else
                        {
                            ArraySize = 0;
                            MassList  = null;
                            EmptyRef  = null;
                            temp      = 0.0;
                            try {
                                RawFile.GetMassListFromScanNum(ref j, null, 0, 0, 0, 0,
                                                               ref temp, ref MassList, ref EmptyRef, ref ArraySize);
                                continue;
                            }catch {
                                Exception e = new Exception(string.Format("Scan #{0} cannot be loaded, probably RAW file is corrupted!", j));
                                throw e;
                            }
                        }
                    }
                    MSMSCount++;
                    ms = new MGFSpectrum();
                    //определяем родительскую массу, заряд и RT
                    Labels    = null;
                    Values    = null;
                    ArraySize = 0;
                    LocalCount++;
                    RawFile.GetTrailerExtraForScanNum(j, ref Labels, ref Values, ref ArraySize);
                    for (int k = 0; k < ArraySize; k++)
                    {
                        if ((Labels as Array).GetValue(k).ToString().Contains("Mono"))
                        {
                            ms.mz = Convert.ToDouble((Values as Array).GetValue(k).ToString());
                        }
                        if ((Labels as Array).GetValue(k).ToString().Contains("Charge State"))
                        {
                            ms.Charge = Convert.ToInt32((Values as Array).GetValue(k).ToString());
                        }
                    }
                    //Если не нашли в labels - берем из фильтра
                    if (ms.mz == 0.0)
                    {
                        string part = Filter.Substring(0, Filter.IndexOf('@'));
                        ms.mz = Convert.ToDouble(part.Substring(part.LastIndexOf(' ')));
                    }
                    Labels    = null;
                    Values    = null;
                    ArraySize = 0;
                    double RT = 0;
                    RawFile.GetStatusLogForScanNum(j, ref RT, ref Labels, ref Values, ref ArraySize);

                    RawFile.RTFromScanNum(j, ref ms.RT);
                    ms.ScanNumber = j;
                    //Фильтры
                    if (ms.Charge < MinCharge)
                    {
                        continue;
                    }
                    if (ms.Charge > MaxCharge)
                    {
                        continue;
                    }
                    if (ms.RT < MinRT)
                    {
                        continue;
                    }
                    if (MaxRT != 0.0 && ms.RT > MaxRT)
                    {
                        continue;
                    }
                    if (ms.mz < MinMZ)
                    {
                        continue;
                    }
                    if (MaxMZ != 0.0 && ms.mz > MaxMZ)
                    {
                        continue;
                    }
                    //забираем сам спектр
                    MassList  = null;
                    EmptyRef  = null;
                    ArraySize = 0;
                    temp      = 0.0;
                    try{
                        if (Filter.IndexOf("FTMS") != -1)
                        {
                            //извлекаем FTMS данные
                            (RawFile as IXRawfile2).GetLabelData(ref MassList, ref EmptyRef, ref j);
                            ArraySize = (MassList as Array).GetLength(1);
                            for (int k = 0; k < ArraySize; k++)
                            {
                                ch           = new Childs();
                                ch.Mass      = (double)(MassList as Array).GetValue(0, k);
                                ch.Intensity = (double)(MassList as Array).GetValue(1, k);
                                ms.Data.Add(ch);
                            }
                        }
                        else
                        {
                            //извлекаем ITMS данные
                            RawFile.GetMassListFromScanNum(ref j, null, 0, 0, 0, 1, ref temp, ref MassList, ref EmptyRef, ref ArraySize);
                            ArraySize = (MassList as Array).GetLength(1);
                            for (int k = 0; k < ArraySize; k++)
                            {
                                ch           = new Childs();
                                ch.Mass      = (double)(MassList as Array).GetValue(0, k);
                                ch.Intensity = (double)(MassList as Array).GetValue(1, k);
                                ms.Data.Add(ch);
                            }
                        }
                    }catch {
                        Exception e = new Exception(string.Format("Scan #{0} cannot be loaded, probably RAW file is corrupted!", j));
                        throw e;
                    }
                    if (RTApex)
                    {
                        ms.RTApex = CheckRTApex(ms.RT, ms.mz);
                    }

                    if (MarkInstrtument)
                    {
                        if (Filter.Contains("ecd") || Filter.Contains("etd"))
                        {
                            ms.Instrument = "ETD-TRAP";
                        }
                        else
                        {
                            ms.Instrument = "ESI-FTICR";
                        }
                    }
                    //очистить ETD если был такой запрос
                    if (CleanETD)
                    {
                        if (Filter.Contains("ecd") || Filter.Contains("etd"))
                        {
                            FilterETD(ref ms, Filter.Contains("FTMS"));
                        }
                    }
                    //сбросить лишние сигналы
                    if (MaxPeakNumber > 0 && ms.Data.Count > MaxPeakNumber)
                    {
                        ms.Data.Sort(ci);
                        ms.Data.RemoveRange(0, ms.Data.Count - MaxPeakNumber);
                        ms.Data.Sort(cm);
                    }
                    //сформировать TITLE
                    if (RTApex)
                    {
                        ms.Title = String.Format("Elution from: {0:f4} to {0:f4} RT Apex: {1:f2} FinneganScanNumber: {2}",
                                                 ms.RT, ms.RTApex, ms.ScanNumber);
                    }
                    else
                    {
                        ms.Title = String.Format("Elution from: {0:f4} to {0:f4} FinneganScanNumber: {1}",
                                                 ms.RT, ms.ScanNumber);
                    }
                    MGF.Spectra.Add(ms);
                    // рапортовать прогресс
                    GC.Collect(2);

                    if ((int)(((double)j / (double)Spectra) * 100.0) > Progress)
                    {
                        Progress = (int)(((double)j / (double)Spectra) * 100.0);
                        Console.WriteLine("{0}%... {1} {2}", Progress, MSCount, MSMSCount);
                    }

                    //backgroundWorker1.ReportProgress((int)(((double)LocalCount/(double)SpCount)*100.0));
                }
                MGF.MGFComments.Add(String.Format("Created by RawToMGF 2.1.3; Spectra obtained from {0}", InFileName));
                MGF.MGFComments.Add(String.Format("Filters: Parent m/z from {0} Th to {1} Th;", MinMZ, MaxMZ));
                MGF.MGFComments.Add(String.Format("         RT from {0} min. to {1} min.;", MinRT, MaxRT));
                MGF.MGFComments.Add(String.Format("         Charge state of parent ions minimum {0}, maximum {1};", MinCharge, MaxCharge));
                MGF.MGFComments.Add(String.Format("         Max number of peaks in MS/MS spectra - {0}", MaxPeakNumber));
                if (CleanETD)
                {
                    MGF.MGFComments.Add("         ETD spectra cleaned from precursors and neutral losses");
                }
                MGF.MGFWrite(OutFileName, true);
            }catch (Exception e) {
                Console.Write("Error:");
                Console.Write(e.Message);
                Console.WriteLine("STACKINFO:" + e.StackTrace);
                //Console.ReadKey();
                return(1);
            }
            Console.WriteLine("Completed");
            Console.ReadLine();
            return(0);
        }
Ejemplo n.º 7
0
        private void Form1_Load(object sender, EventArgs e)
        {
            int loop_num = 0;

            this.grid.CellMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.grid_CellMouseClick);
            grid.Anchor = (AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Bottom | AnchorStyles.Right);
            grid.Show();
            // To Do
            IEnumerable <string> sample_files = Directory.GetFiles(fldrpath, "*.raw").OrderBy(f => f);
            string one_file = sample_files.First();
            MSFileReader_XRawfile rawfile = new MSFileReader_XRawfile();

            rawfile.Open(one_file);
            rawfile.SetCurrentController(0, 1);
            int last_scan = 0;

            rawfile.GetLastSpectrumNumber(ref last_scan);
            //
            for (int i = 0; i < last_scan; i++)
            {
                grid.Columns.Add("column" + i.ToString(), i.ToString());
                grid.Columns[i].MinimumWidth = 4;
            }
            Color[] colorSet = { Color.Green, Color.Blue, Color.Aqua, Color.Yellow, Color.Orange, Color.Purple, Color.LightSeaGreen };
            //foreach (string file in Directory.EnumerateFiles(fldrpath, "*.raw"))
            foreach (string file in Directory.GetFiles(fldrpath, "*.raw").OrderBy(f => f))
            {
                bool flag = Analytics.analytics(mass_ratio, file);
                while (flag != true)
                {
                    continue;
                }
                string text_file = file.Remove(file.Length - 4);
                list.Add(text_file);
                //int n = TotalLines(text_file+".txt"); // 50 scans in a file :)

                int             rowId = grid.Rows.Add();
                DataGridViewRow row   = grid.Rows[rowId];
                grid.Rows[rowId].MinimumHeight = 2;
                System.Collections.Generic.IEnumerable <String> lines = File.ReadLines(text_file + ".txt");
                //Button[] buttArray = new Button[n];
                int i = 0;
                foreach (string l in lines)
                {
                    char[]   delimiterChars = { ' ' };
                    string[] words          = l.Split(delimiterChars);
                    //Console.WriteLine(words[1]);
                    if (Int32.Parse(words[1]) == 0)
                    {
                        grid.Rows[rowId].Cells[i].Style.BackColor = Color.Red;
                    }
                    else
                    {
                        grid.Rows[rowId].Cells[i].Style.BackColor = colorSet[Int32.Parse(words[1])];
                    }
                    i++;
                }
                loop_num++;
                //if (loop_num >= 2) break;
            }
            //Console.WriteLine(loop_num);
            this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
            grid.Dock        = DockStyle.Fill;

            this.grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            grid.Columns[grid.ColumnCount - 1].MinimumWidth = 8;
            grid.CurrentCell.Selected = false;
            sw.Stop();
            //Console.WriteLine(sw.ElapsedMilliseconds);
            //Console.WriteLine(this.Height);

            //grid.AutoResizeRows(DataGridViewAutoSizeRowsMode.AllCells);
        }
Ejemplo n.º 8
0
        public int LoadIndex(string FileName)
        {
            this.RawFileName = FileName;

            RawFile = new MSFileReader_XRawfile();

            RawFile.Open(FileName);
            RawFile.SetCurrentController(0, 1);

            Spectra = 0;
            RawFile.GetNumSpectra(ref Spectra);

            if( Spectra <= 0)
                return 0;

            int i, lastfull = 0, total = 0;
            double TotalEsi = 0.0;

            ms2index = new int[Spectra+1];
            IndexDir = new int[Spectra+1];
            IndexRev = new int[Spectra+1];
            RawSpectra = new RawData[Spectra+1];
            for(int j = 0 ; j <= Spectra ; j++){
                RawSpectra[j] = new RawData();
            }
            Buf = new MZData[1000000];

            ESICurrents = new double[Spectra+1];
            TimeStamps = new double[Spectra+1];
            TimeCoefs = new double[Spectra+1];

            string Filter = null;

            LowRT = 0.0;
            HighRT = 0.0;

            int Progress = 0;
            for(i = 1; i <= Spectra; i++){

                if ((int)(100.0*((double)i/(double)Spectra)) > Progress) {
                    Progress = (int)(100.0*((double)i/(double)Spectra));
                    if (RepProgress != null){
                        RepProgress(Progress);
                    }
                }

                RawFile.GetFilterForScanNum(i, ref Filter);

                //YL - для спектров ms-only
                //Заплатка для MSX спектров
                if((Filter.IndexOf(" ms ") != -1) && (Filter.IndexOf("FTMS") != -1)) { //is a FULL MS

                    TimeStamps[i] = RawSpectra[lastfull].RT;

                    IndexDir[lastfull] = i;
                    IndexRev[i] = lastfull;

                    lastfull = i;
                    ms2index[i] = lastfull;

                    ++total;

                    RawFile.RTFromScanNum(i, ref RawSpectra[i].RT);
                    RawSpectra[i].Filter = Filter;
                    TotalRT = RawSpectra[i].RT;

                    TimeStamps[i] = RawSpectra[i].RT - TimeStamps[i];

                    object Labels = null;
                    object Values = null;
                    int ArraySize = 0;
                    double RT = 0.0;

                    RawFile.GetStatusLogForScanNum(i, ref RT, ref Labels, ref Values , ref ArraySize);

                    for (int k = 0 ; k < ArraySize ; k++ ){
                        if ((Labels as Array).GetValue(k).ToString().Contains("Source Current")){
                            ESICurrents[i] = Convert.ToDouble((Values as Array).GetValue(k).ToString());
                            TotalEsi+=ESICurrents[i];
                        }
                    }

                }
                else {
                    ms2index[i] = lastfull;
                }
                Filter = null ;
            }
            IndexDir[lastfull] = -1;
            TotalRT = RawSpectra[lastfull].RT;
            AverageTimeStamp = TotalRT/total;

            //пересчитаем временные коэффициэнты
            for (i = IndexDir[0] ; IndexDir[i] != -1 ; i = IndexDir[i]) {

                TimeCoefs[i] = (TimeStamps[i]+TimeStamps[IndexDir[i]])/(2.0*AverageTimeStamp);

                ESICurrents[i] = ESICurrents[i]/(TotalEsi/(double)total);
            }
            TimeCoefs[i] = 1.0;

            return Spectra;
        }
Ejemplo n.º 9
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
        }