示例#1
0
        public static IReaction GetReaction(IScanEvent scanEvent, int scanNumber)
        {
            IReaction reaction = null;

            try
            {
                var order = (int)scanEvent.MSOrder;
                reaction = scanEvent.GetReaction(order - 2);
            }
            catch (ArgumentOutOfRangeException)
            {
                Log.Warn("No reaction found for scan " + scanNumber);
            }

            return(reaction);
        }
示例#2
0
        public static (ScanIndex, PrecursorScanCollection, ScanDependentsCollections) ScanIndicesPrecursorsDependents(IRawFileThreadManager rawFileAccessor)
        {
            Log.Information("Extracting scan indices");
            ConcurrentDictionary <int, ScanData> allScans;

            allScans = new ConcurrentDictionary <int, ScanData>();
            Dictionary <int, ScanData> orphanScans = new Dictionary <int, ScanData>();
            MSOrderType AnalysisOrder;

            ConcurrentBag <int> ms1   = new ConcurrentBag <int>();
            ConcurrentBag <int> ms2   = new ConcurrentBag <int>();
            ConcurrentBag <int> ms3   = new ConcurrentBag <int>();
            ConcurrentBag <int> msAny = new ConcurrentBag <int>();

            ConcurrentDictionary <int, PrecursorScanData> precursorScans = new ConcurrentDictionary <int, PrecursorScanData>();
            ConcurrentDictionary <int, IScanDependents>   dependents     = new ConcurrentDictionary <int, IScanDependents>();



            var staticRawFile = rawFileAccessor.CreateThreadAccessor();

            staticRawFile.SelectMsData();

            // populate the scan indices
            IEnumerable <int> scans = staticRawFile.GetFilteredScanEnumerator(staticRawFile.GetFilterFromString("")); // get all scans

            // get ms order of experiment
            Console.Write("Determing MS analysis order... ");
            AnalysisOrder = (from x in scans select staticRawFile.GetScanEventForScanNumber(x).MSOrder).Max();
            Console.WriteLine("Done!");

            object lockTarget = new object();

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

            int chunkSize = Constants.MultiThreading.ChunkSize(scans.Count());

            var batches = scans.Chunk(chunkSize);

            Parallel.ForEach(batches, batch =>
            {
                ScanData ms1ScanData;
                ScanData ms2ScanData;
                ScanData ms3ScanData;
                foreach (int scan in batch)
                {
                    //var rawFile = rawFileAccessor.CreateThreadAccessor();

                    using (var rawFile = rawFileAccessor.CreateThreadAccessor())
                    {
                        rawFile.SelectMsData();

                        IScanEvent scanEvent     = rawFile.GetScanEventForScanNumber(scan);
                        ms1ScanData              = new ScanData();
                        ms2ScanData              = new ScanData();
                        ms3ScanData              = new ScanData();
                        ms1ScanData.MassAnalyzer = scanEvent.MassAnalyzer;
                        ms1ScanData.MSOrder      = scanEvent.MSOrder;

                        if (ms1ScanData.MSOrder == MSOrderType.Ms)
                        {
                            ms1.Add(scan);
                            msAny.Add(scan);

                            var scanDependents = rawFile.GetScanDependents(scan, 4);
                            dependents.TryAdd(scan, scanDependents);

                            // check if the ms1 scan has dependent scans
                            if (scanDependents == null)
                            {
                                // there are no scan dependents
                                ms1ScanData.HasDependents = false;
                                allScans.TryAdd(scan, ms1ScanData);
                                return;
                            }
                            else
                            {
                                ms1ScanData.HasDependents = true;
                                allScans.TryAdd(scan, ms1ScanData);
                            }

                            for (int i = 0; i < scanDependents.ScanDependentDetailArray.Length; i++)
                            {
                                int ms2Scan = scanDependents.ScanDependentDetailArray[i].ScanIndex;
                                ms2.Add(ms2Scan);
                                msAny.Add(ms2Scan);

                                if (AnalysisOrder == MSOrderType.Ms2) // it is ms2
                                {
                                    ms2ScanData = new ScanData();
                                    scanEvent   = rawFile.GetScanEventForScanNumber(ms2Scan);
                                    ms2ScanData.MassAnalyzer  = scanEvent.MassAnalyzer;
                                    ms2ScanData.MSOrder       = scanEvent.MSOrder;
                                    ms2ScanData.HasDependents = false;
                                    ms2ScanData.HasPrecursors = true;
                                    allScans.TryAdd(ms2Scan, ms2ScanData);

                                    precursorScans.TryAdd(ms2Scan, new PrecursorScanData(ms2scan: ms2Scan, masterScan: scan));
                                }
                                else // it is ms3
                                {
                                    var ms2Dependents = rawFile.GetScanDependents(ms2Scan, 4).ScanDependentDetailArray;

                                    ms2ScanData = new ScanData();
                                    scanEvent   = rawFile.GetScanEventForScanNumber(ms2Scan);
                                    ms2ScanData.MassAnalyzer  = scanEvent.MassAnalyzer;
                                    ms2ScanData.MSOrder       = scanEvent.MSOrder;
                                    ms2ScanData.HasPrecursors = true;

                                    if (ms2Dependents.Length != 0) // make sure there is ms3 data
                                    {
                                        int ms3Scan = ms2Dependents[0].ScanIndex;
                                        ms3.Add(ms3Scan);
                                        msAny.Add(ms3Scan);

                                        scanEvent = rawFile.GetScanEventForScanNumber(ms3Scan);
                                        precursorScans.TryAdd(ms2Scan, new PrecursorScanData(ms2scan: ms2Scan, masterScan: scan));
                                        precursorScans.TryAdd(ms3Scan, new PrecursorScanData(ms3scan: ms3Scan, ms2Scan: ms2Scan, masterScan: scan));
                                        ms2ScanData.HasDependents = true;

                                        ms3ScanData = new ScanData();
                                        ms3ScanData.HasPrecursors = true;
                                        ms3ScanData.MassAnalyzer  = scanEvent.MassAnalyzer;
                                        ms3ScanData.MSOrder       = scanEvent.MSOrder;
                                        allScans.TryAdd(ms3Scan, ms3ScanData);
                                    }
                                    else
                                    {
                                        // there is no ms3 scan, so we only add the ms2 scan
                                        precursorScans.TryAdd(ms2Scan, new PrecursorScanData(ms2scan: ms2Scan, masterScan: scan));
                                        ms2ScanData.HasDependents = false;
                                    }
                                    allScans.TryAdd(ms2Scan, ms2ScanData);
                                }
                            }
                        }
                        lock (lockTarget)
                        {
                            P.Update();
                        }
                    }
                }
            });
            P.Done();

            HashSet <int> allKeys = new HashSet <int>(allScans.Keys);

            P = new ProgressIndicator(scans.Count(), "Checking for orphaned scans");
            foreach (int scan in scans)
            {
                if (allKeys.Contains(scan))
                {
                    continue;
                }
                else
                {
                    ScanData scanData  = new ScanData();
                    var      scanEvent = staticRawFile.GetScanEventForScanNumber(scan);
                    scanData.MassAnalyzer = scanEvent.MassAnalyzer;
                    scanData.MSOrder      = scanEvent.MSOrder;
                    orphanScans.Add(scan, scanData);
                }
                P.Update();
            }
            P.Done();

            Console.WriteLine();
            Console.WriteLine("================ Scan indexing report ================");
            Console.WriteLine($"Total scans in file: {staticRawFile.RunHeaderEx.SpectraCount}");
            Console.WriteLine($"Scans linked: {allScans.Count()}");

            Console.WriteLine();
            Console.WriteLine("Orphan scans:");

            if (orphanScans.Count() > 0)
            {
                foreach (var scan in orphanScans)
                {
                    Console.WriteLine($"\tScan: {scan.Key}, MSOrder: {scan.Value.MSOrder}");
                }

                Console.WriteLine("\nThe above scans will not be present in the output data. You should");
                Console.WriteLine("manually check them to ensure they are not critical to you analysis.");
            }
            else
            {
                Console.WriteLine("None!");
            }
            Console.WriteLine();
            if (staticRawFile.RunHeaderEx.SpectraCount == allScans.Count() + orphanScans.Count())
            {
                Console.WriteLine("All scans accounted for!");
            }
            else
            {
                Console.WriteLine($"Number of scans unaccounted for: {staticRawFile.RunHeaderEx.SpectraCount - (allScans.Count() + orphanScans.Count())}");
                Console.WriteLine("If this number is alarming, please contact the RawTools authors\n" +
                                  "by posting an issue at:\n" +
                                  "https://github.com/kevinkovalchik/RawTools/issues");
            }
            Console.WriteLine("======================================================");
            Console.WriteLine();

            // we need to order the scan enumerators before sending them out
            var orderedMs1   = ms1.ToList();
            var orderedMs2   = ms2.ToList();
            var orderedMs3   = ms3.ToList();
            var orderedMsAny = msAny.ToList();

            orderedMs1.Sort();
            orderedMs2.Sort();
            orderedMs3.Sort();
            orderedMsAny.Sort();

            ScanIndex scanIndex = new ScanIndex();

            scanIndex.allScans      = allScans.ConvertToDictionary();
            scanIndex.AnalysisOrder = AnalysisOrder;
            scanIndex.ScanEnumerators.Add(MSOrderType.Any, orderedMsAny.ToArray());
            scanIndex.ScanEnumerators.Add(MSOrderType.Ms, orderedMs1.ToArray());
            scanIndex.ScanEnumerators.Add(MSOrderType.Ms2, orderedMs2.ToArray());
            scanIndex.ScanEnumerators.Add(MSOrderType.Ms3, orderedMs3.ToArray());
            scanIndex.TotalScans = staticRawFile.RunHeaderEx.SpectraCount;

            return(scanIndex, new PrecursorScanCollection(precursorScans), new ScanDependentsCollections(dependents));
        }
示例#3
0
        public static ScanIndex ScanIndices(IRawDataPlus rawFile)
        {
            rawFile.SelectInstrument(Device.MS, 1);
            Log.Information("Extracting scan indices");
            Dictionary <int, ScanData> allScans;

            allScans = new Dictionary <int, ScanData>();
            MSOrderType AnalysisOrder;

            List <int> ms1   = new List <int>();
            List <int> ms2   = new List <int>();
            List <int> ms3   = new List <int>();
            List <int> msAny = new List <int>();

            // populate the scan indices
            IEnumerable <int> scans = rawFile.GetFilteredScanEnumerator(rawFile.GetFilterFromString("")); // get all scans

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

            foreach (int scan in scans)
            {
                IScanEvent scanEvent = rawFile.GetScanEventForScanNumber(scan);
                ScanData   scanData  = new ScanData();
                scanData.MassAnalyzer = scanEvent.MassAnalyzer;
                scanData.MSOrder      = scanEvent.MSOrder;

                allScans.Add(scan, scanData);
                msAny.Add(scan);

                if (allScans[scan].MSOrder == MSOrderType.Ms)
                {
                    ms1.Add(scan);
                }
                if (allScans[scan].MSOrder == MSOrderType.Ms2)
                {
                    ms2.Add(scan);
                }
                if (allScans[scan].MSOrder == MSOrderType.Ms3)
                {
                    ms3.Add(scan);
                }
                P.Update();
            }
            P.Done();

            // determine the msorder of the experiment
            if ((ms1.Count > 0) & (ms2.Count == 0) & (ms3.Count == 0))
            {
                AnalysisOrder = MSOrderType.Ms;
            }
            else
            {
                if ((ms1.Count > 0) & (ms2.Count > 0) & (ms3.Count == 0))
                {
                    AnalysisOrder = MSOrderType.Ms2;
                }
                else
                {
                    AnalysisOrder = MSOrderType.Ms3;
                }
            }

            ScanIndex scanIndex = new ScanIndex();

            scanIndex.allScans      = allScans;
            scanIndex.AnalysisOrder = AnalysisOrder;
            scanIndex.ScanEnumerators.Add(MSOrderType.Any, msAny.ToArray());
            scanIndex.ScanEnumerators.Add(MSOrderType.Ms, ms1.ToArray());
            scanIndex.ScanEnumerators.Add(MSOrderType.Ms2, ms2.ToArray());
            scanIndex.ScanEnumerators.Add(MSOrderType.Ms3, ms3.ToArray());

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

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

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

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

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

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

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

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

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

            scanType.scanWindowList.scanWindow[0] = scanWindow;

            scanList.scan[0] = scanType;

            return(scanList);
        }
示例#5
0
        /// <summary>
        /// Open the given file and import scans into the reader.
        /// </summary>
        /// <returns></returns>
        public System.Collections.IEnumerator GetEnumerator()
        {
            rawFile.SelectInstrument(ThermoBiz.Device.MS, 1);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                yield return(scan);
            }
        }
示例#6
0
        public static void ExtractScanIndex(this RawDataCollection rawData, IRawDataPlus rawFile)
        {
            Log.Information("Extracting scan indices");
            Dictionary <int, (MSOrderType MSOrder, MassAnalyzerType MassAnalyzer)> allScans;

            allScans = new Dictionary <int, (MSOrderType MSOrder, MassAnalyzerType MassAnalyzer)>();
            MSOrderType AnalysisOrder;

            List <int> ms1   = new List <int>();
            List <int> ms2   = new List <int>();
            List <int> ms3   = new List <int>();
            List <int> msAny = new List <int>();

            // populate the scan indices
            IEnumerable <int> scans = rawFile.GetFilteredScanEnumerator(rawFile.GetFilterFromString("")); // get all scans

            foreach (int scan in scans)
            {
                IScanEvent scanEvent = rawFile.GetScanEventForScanNumber(scan);

                allScans.Add(scan, (scanEvent.MSOrder, scanEvent.MassAnalyzer));
                msAny.Add(scan);

                if (allScans[scan].MSOrder == MSOrderType.Ms)
                {
                    ms1.Add(scan);
                }
                if (allScans[scan].MSOrder == MSOrderType.Ms2)
                {
                    ms2.Add(scan);
                }
                if (allScans[scan].MSOrder == MSOrderType.Ms3)
                {
                    ms3.Add(scan);
                }
            }

            // determine the msorder of the experiment
            if ((ms1.Count > 0) & (ms2.Count == 0) & (ms3.Count == 0))
            {
                AnalysisOrder = MSOrderType.Ms;
            }
            else
            {
                if ((ms1.Count > 0) & (ms2.Count > 0) & (ms3.Count == 0))
                {
                    AnalysisOrder = MSOrderType.Ms2;
                }
                else
                {
                    AnalysisOrder = MSOrderType.Ms3;
                }
            }

            rawData.scanIndex               = new ScanIndex();
            rawData.scanIndex.allScans      = allScans;
            rawData.scanIndex.AnalysisOrder = AnalysisOrder;
            rawData.scanIndex.ScanEnumerators.Add(MSOrderType.Any, msAny.ToArray());
            rawData.scanIndex.ScanEnumerators.Add(MSOrderType.Ms, ms1.ToArray());
            rawData.scanIndex.ScanEnumerators.Add(MSOrderType.Ms2, ms2.ToArray());
            rawData.scanIndex.ScanEnumerators.Add(MSOrderType.Ms3, ms3.ToArray());

            // we need to check if it is a boxcar file because those have some scan index issues
            bool isBoxCar = rawFile.GetScanEventForScanNumber(1).MassRangeCount > 1;

            rawData.Performed.Add(Operations.ScanIndex);

            if (isBoxCar)
            {
                Log.Information("Raw file looks like a boxcar run. Scan indices being adjusted to account for missing scan dependents.");
                rawData.ExtractPrecursorScans(rawFile);
                rawData.scanIndex.ScanEnumerators[rawData.scanIndex.AnalysisOrder] = rawData.precursorScans.Keys.ToArray();
            }
        }
示例#7
0
文件: Program.cs 项目: Ykobe/metaCode
            //Console.ReadKey();
        }

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

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

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

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

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

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

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

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

            writer.Close();
        }

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

            Console.OutputEncoding = Encoding.UTF8;

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

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

            //writer.Close();

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

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

            HeaderItem[] tuneDataHeaderInfo = plus.GetTuneDataHeaderInformation();

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

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

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

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

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

            startNum = firstScanNumber;
            endNum = lastScanNumber;

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

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

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

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

            lowMS = minMs;
            highMS = maxMs;

            string fileName = DateTime.Now.ToLocalTime().ToString().Replace("/", "").Replace(":", "").Replace(" ", "_") + ".csv";
            FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
            StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
            
            writer.WriteLine("ScanNumber, RT, Mass, Resolution, Intensity, Noise, Filter,MSLevel,collisionEnergy, precursorNum,precursorMS");
            while (startNum <= endNum)
            {
                var levelInfo = "";
                var spectrumRef = "";
                Scan scan = Scan.FromFile(plus, startNum);
                IScanFilter scanFilter = plus.GetFilterForScanNumber(startNum);

                IScanEvent scanEvent = plus.GetScanEventForScanNumber(startNum);

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

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

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

                //var scanStatistics = plus.GetScanStatsForScanNumber(startNum);
                //// Get the segmented (low res and profile) scan data
                //var segmentedScan = plus.GetSegmentedScanFromScanNumber(startNum, scanStatistics);
                //double[] masses = segmentedScan.Positions;
                //double[] intensitis = segmentedScan.Intensities;

                //Console.WriteLine(masses.Length);
                //Console.WriteLine(intensitis.Length);

                int cnt = 0;

                if (scanFilter.MSOrder == MSOrderType.Ms)
                {
                    while (cnt < scan.PreferredMasses.Length)
                    {
                        if (lowMS < scan.PreferredMasses[cnt] && scan.PreferredMasses[cnt] < highMS)
                        {
                            double rt = plus.RetentionTimeFromScanNumber(startNum);
                            double msval = scan.PreferredMasses[cnt];
                            double resolution = (scan.PreferredResolutions.Length == 0) ? 0.0 : scan.PreferredResolutions[cnt];
                            double intensity = (scan.PreferredIntensities.Length == 0) ? 0.0 : scan.PreferredIntensities[cnt];
                            double noise = (scan.PreferredNoises.Length == 0) ? 0.0 : scan.PreferredNoises[cnt];

                            //msval.ToString("f4");Return a number to a given precision,carry bit
                            //msval.ToString("n4");Return a number to a given precision,not carry bit

                            //writer.WriteLine("{0},{1},{2},{3},{4},{5},{6},{7}", startNum.ToString(), rt.ToString(),
                            //    msval.ToString("n4"), resolution.ToString(), intensity.ToString(), noise.ToString(),
                            //    scanFilter.ToString(), levelInfo);

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

        }

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

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

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

        }

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

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

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

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

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

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

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

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

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

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

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

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