/// <summary> /// Initiates a dynamic connection with a Thermo .raw file. Data can be "streamed" instead of loaded all at once. Use /// GetOneBasedScanFromDynamicConnection to get data from a particular scan. Use CloseDynamicConnection to close the /// dynamic connection after all desired data has been retrieved from the dynamic connection. /// </summary> private void InitiateDynamicConnection(string filePath) { Loaders.LoadElements(); if (dynamicConnection != null) { dynamicConnection.Dispose(); } dynamicConnection = RawFileReaderAdapter.FileFactory(filePath); if (!File.Exists(filePath)) { throw new FileNotFoundException(); } if (!dynamicConnection.IsOpen) { throw new MzLibException("Unable to access RAW file!"); } if (dynamicConnection.IsError) { throw new MzLibException("Error opening RAW file!"); } if (dynamicConnection.InAcquisition) { throw new MzLibException("RAW file still being acquired!"); } dynamicConnection.SelectInstrument(Device.MS, 1); GetMsOrdersByScanInDynamicConnection(); }
/// <summary> /// Get and set general information from the raw file /// </summary> /// <param name="inputRawFile"></param> /// <returns></returns> private IRawDataPlus GetSetRawFileData(string inputRawFile) { // Create the IRawDataPlus object for accessing the RAW file IRawDataPlus rawFile = RawFileReaderAdapter.FileFactory(inputRawFile); if (!rawFile.IsOpen || rawFile.IsError) { Console.WriteLine("Unable to access the RAW file using the RawFileReader class!"); } // Check for any errors in the RAW file if (rawFile.IsError) { Console.WriteLine("Error opening ({0})", rawFile.FileError); } // Check if the RAW file is being acquired if (rawFile.InAcquisition) { Console.WriteLine("RAW file still being acquired..."); } // Select instrument we are intereted in looking at data from rawFile.SelectInstrument(Device.MS, 1); return(rawFile); }
/// <summary> /// Open new Raw file with warning messages. /// </summary> /// <param name="path"></param> public void Open(string path) { rawFile = RawFileReaderAdapter.FileFactory(path); if (!rawFile.IsOpen) { Console.WriteLine(" RawFile Error: File could not be opened: " + path); Console.WriteLine(rawFile.FileError.WarningMessage); Console.WriteLine(rawFile.FileError.ErrorMessage); Console.WriteLine(rawFile.FileError.ErrorCode); throw new IOException("Failed to open RAW file."); } if (rawFile.IsError) { Console.WriteLine(" RawFile Error: reader error: " + path); throw new IOException("Error while opening RAW file."); } rawFile.SelectInstrument(ThermoBiz.Device.MS, 1); rawFile.IncludeReferenceAndExceptionData = true; }
/// <summary> /// Initiates a dynamic connection with a Thermo .raw file. Data can be "streamed" instead of loaded all at once. Use /// GetOneBasedScanFromDynamicConnection to get data from a particular scan. Use CloseDynamicConnection to close the /// dynamic connection after all desired data has been retrieved from the dynamic connection. /// </summary> protected override void InitiateDynamicConnection() { if (!File.Exists(FilePath)) { throw new FileNotFoundException(); } if (Path.GetExtension(FilePath).ToUpper() != ".RAW") { throw new InvalidDataException(); } Loaders.LoadElements(); if (dynamicConnection != null) { dynamicConnection.Dispose(); } dynamicConnection = RawFileReaderAdapter.FileFactory(FilePath); if (!dynamicConnection.IsOpen) { throw new MzLibException("Unable to access RAW file!"); } if (dynamicConnection.IsError) { throw new MzLibException("Error opening RAW file!"); } if (dynamicConnection.InAcquisition) { throw new MzLibException("RAW file still being acquired!"); } dynamicConnection.SelectInstrument(Device.MS, 1); GetMsOrdersByScanInDynamicConnection(); }
public Rawfile(string rawfile) { int deviceNumber = 1; _rawfile = rawfile; rawFile = RawFileReaderAdapter.FileFactory(_rawfile); // https://github.com/cpanse/MsBackendRawFileReader/issues/12 rawFile.IncludeReferenceAndExceptionData = false; rawFile.SelectInstrument(Device.MS, deviceNumber); dictInfo.Add("filename", rawFile.FileName); dictInfo.Add("creation date", rawFile.FileHeader.CreationDate.ToString()); dictInfo.Add("first scan", this.GetFirstScanNumber().ToString()); dictInfo.Add("last scan", this.GetLastScanNumber().ToString()); dictInfo.Add("model", rawFile.GetInstrumentData().Model.ToString()); dictInfo.Add("name", rawFile.GetInstrumentData().Name.ToString()); dictInfo.Add("SerialNumber", rawFile.GetInstrumentData().SerialNumber.ToString()); //dictInfo.Add("mass resolution", rawFile.RunHeaderEx.MassResolution.ToString()); var trailerData = rawFile.GetTrailerExtraInformation(rawFile.RunHeaderEx.FirstSpectrum); foreach (int i in Enumerable.Range(1, trailerData.Labels.ToArray().Length)) { try { if ((trailerData.Labels[i] == "Master Scan Number:") || (trailerData.Labels[i] == "Master Scan Number") || (trailerData.Labels[i] == "Master Index:")) { this.masterScanIdx = i; } } catch { } } }
/// <summary> /// Loads all scan data from a Thermo .raw file. /// </summary> public static ThermoRawFileReader LoadAllStaticData(string filePath, IFilteringParams filterParams = null, int maxThreads = -1) { if (!File.Exists(filePath)) { throw new FileNotFoundException(); } Loaders.LoadElements(); // I don't know why this line needs to be here, but it does... var temp = RawFileReaderAdapter.FileFactory(filePath); var threadManager = RawFileReaderFactory.CreateThreadManager(filePath); var rawFileAccessor = threadManager.CreateThreadAccessor(); if (!rawFileAccessor.IsOpen) { throw new MzLibException("Unable to access RAW file!"); } if (rawFileAccessor.IsError) { throw new MzLibException("Error opening RAW file!"); } if (rawFileAccessor.InAcquisition) { throw new MzLibException("RAW file still being acquired!"); } rawFileAccessor.SelectInstrument(Device.MS, 1); var msDataScans = new MsDataScan[rawFileAccessor.RunHeaderEx.LastSpectrum]; Parallel.ForEach(Partitioner.Create(0, msDataScans.Length), new ParallelOptions { MaxDegreeOfParallelism = maxThreads }, (fff, loopState) => { IRawDataPlus myThreadDataReader = threadManager.CreateThreadAccessor(); myThreadDataReader.SelectInstrument(Device.MS, 1); for (int s = fff.Item1; s < fff.Item2; s++) { try { var scan = GetOneBasedScan(myThreadDataReader, filterParams, s + 1); msDataScans[s] = scan; } catch (Exception ex) { throw new MzLibException("Error reading scan " + (s + 1) + ": " + ex.Message); } } }); rawFileAccessor.Dispose(); string sendCheckSum; using (FileStream stream = File.OpenRead(filePath)) { using (SHA1Managed sha = new SHA1Managed()) { byte[] checksum = sha.ComputeHash(stream); sendCheckSum = BitConverter.ToString(checksum) .Replace("-", string.Empty); } } SourceFile sourceFile = new SourceFile( @"Thermo nativeID format", @"Thermo RAW format", sendCheckSum, @"SHA-1", filePath, Path.GetFileNameWithoutExtension(filePath)); return(new ThermoRawFileReader(msDataScans, sourceFile)); }
private static void Main(string[] args) { // This local variable controls if the AnalyzeAllScans method is called // bool analyzeScans = false; const string rawR_version = "1.3.1"; string filename = string.Empty; string mode = string.Empty; string filterString = string.Empty; Hashtable hashtable = new Hashtable() { { "filter", "List all scan ids pass the filter string (option 2)." }, { "getFilters", "List all scan filters of a given raw file." }, { "isValidFilter", "Checks whether the provided argument string (option 2) is a valid filter." }, { "headerR", "Writes the raw file's meta data as R code to a file." }, { "chromatogram", "Extracts base peak and total ion count chromatograms into a file." }, { "xic", "Extracts filtered (option 2) ion chromatograms within a given mass and mass tolerance [in ppm] (option 3) xic of a given raw file as R code into a file." }, { "scans", "Extracts scans (spectra) of a given ID as Rcode." }, { "cscans", "Extracts 'barbone' scans (spectra), including only mZ, intensity , precursorMass, rtinsecodonds and charge state, of a given ID as Rcode." }, { "index", "Prints index as csv of all scans." } }; var helpOptions = new List <string>() { "help", "--help", "-h", "h", "/h" }; if (args.Length >= 2) { filename = args[0]; mode = args[1]; if (!hashtable.Contains(mode)) { Console.WriteLine("\nOption '{0}' is not defined. Please use one of the following options as argument:", mode); foreach (var k in hashtable.Keys) { Console.WriteLine(" {0,-15} {1}", k.ToString(), hashtable[k].ToString()); } Console.WriteLine(); Environment.Exit(1); } } else { if (args.Length == 0) { Console.WriteLine("No RAW file specified!"); return; Console.WriteLine("run 'rawrr.exe help'."); Environment.Exit(1); } else if (args[0] == "version") { Console.WriteLine(rawR_version); Environment.Exit(0); } else if (helpOptions.Contains(args[0])) { Console.WriteLine("\nUsage:\n"); Console.WriteLine(" rawrr.exe <raw file> <option>\n"); Console.WriteLine(" rawrr.exe <raw file> <option> <input file> <output file>\n"); Console.WriteLine( " rawrr.exe <raw file> <option 1> <option 2> <option 3> <input file> <output file>\n"); Console.WriteLine("\nOptions:\n"); foreach (var k in hashtable.Keys) { Console.WriteLine(" {0,-15} {1}", k.ToString(), hashtable[k].ToString()); } Console.WriteLine("\nReport bugs at <https://github.com/fgcz/rawrr/issues>.\n"); Environment.Exit(0); } else { Console.WriteLine("run 'rawrr.exe help'."); Environment.Exit(1); } } if (string.IsNullOrEmpty(filename)) { Console.WriteLine("No RAW file specified!"); return; } //Environment.Exit(0); // Get the memory used at the beginning of processing Process processBefore = Process.GetCurrentProcess(); long memoryBefore = processBefore.PrivateMemorySize64 / 1024; try { // Create the IRawDataPlus object for accessing the RAW file var rawFile = RawFileReaderAdapter.FileFactory(filename); if (!rawFile.IsOpen || rawFile.IsError) { Console.WriteLine("Unable to access the RAW file using the RawFileReader class!"); return; } // Check for any errors in the RAW file if (rawFile.IsError) { Console.WriteLine("Error opening ({0}) - {1}", rawFile.FileError, filename); return; } // Check if the RAW file is being acquired if (rawFile.InAcquisition) { Console.WriteLine("RAW file still being acquired - " + filename); return; } rawFile.SelectInstrument(Device.MS, 1); //Console.WriteLine("DEBUG {0}", rawFile.GetInstrumentMethod(3).ToString()); // Get the first and last scan from the RAW file int firstScanNumber = rawFile.RunHeaderEx.FirstSpectrum; int lastScanNumber = rawFile.RunHeaderEx.LastSpectrum; // Get the start and end time from the RAW file double startTime = rawFile.RunHeaderEx.StartTime; double endTime = rawFile.RunHeaderEx.EndTime; if (mode == "headerR") { var outputFilename = args[3]; rawFile.PrintHeaderAsRcode(outputFilename); return; } // Get the number of filters present in the RAW file int numberFilters = rawFile.GetFilters().Count; if (mode == "filter") { filterString = args[2].ToString(); int precision = int.Parse(args[3]); var outputFilename = args[4]; if (!IsValidFilter(rawFile, filterString)) { Environment.Exit(1); } using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputFilename)) { foreach (var ss in rawFile .GetFilteredScanEnumerator(rawFile.GetFilterFromString(filterString, precision)).ToArray()) { file.WriteLine(ss); } } Environment.Exit(0); } if (mode == "isValidFilter") { Console.WriteLine(IsValidFilter(rawFile, args[2].ToString()).ToString()); Environment.Exit(0); } if (mode == "getFilters") { foreach (var filter in rawFile.GetFilters()) { Console.WriteLine(filter.ToString()); } Environment.Exit(0); } if (mode == "version") { Console.WriteLine("version={}", rawR_version); Environment.Exit(0); } if (mode == "chromatogram") { // Get the BasePeak chromatogram for the MS data string filter = "ms"; string outputcsv = "chromatogram.csv"; try { filter = args[2]; } catch { } try { outputcsv = args[3]; } catch { } GetChromatogram(rawFile, firstScanNumber, lastScanNumber, outputcsv, filter); Environment.Exit(0); } if (mode == "index") { rawFile.GetIndex(); return; } if (mode == "scans") { List <int> scans = new List <int>(); var scanfile = args[2]; int scanNumber; foreach (var line in File.ReadAllLines(scanfile)) { try{ Int32.TryParse(line, out scanNumber); if (scanNumber > 0) { scans.Add(scanNumber); } } catch {} } if (scans.Count == 0) { rawFile.WriteSpectrumAsRcode0(args[3]); } else { rawFile.WriteSpectrumAsRcode(args[3], scans); } return; } if (mode == "cscans") { List <int> scans = new List <int>(); var scanfile = args[2]; int scanNumber; foreach (var line in File.ReadAllLines(scanfile)) { try{ Int32.TryParse(line, out scanNumber); if (scanNumber > 0) { scans.Add(scanNumber); } } catch {} } if (scans.Count == 0) { rawFile.WriteSpectrumAsRcode0(args[3]); } else { rawFile.WriteCentroidSpectrumAsRcode(args[3], scans); } return; } if (mode == "xic") { // Console.WriteLine("xic"); try { double ppmError = Convert.ToDouble(args[2]); // Console.WriteLine(ppmError); string filter = "ms"; try { filter = args[3]; } catch { } //Console.WriteLine(filter); var inputFilename = args[4]; var outputFilename = args[5]; List <double> massList = new List <double>(); if (File.Exists(inputFilename)) { foreach (var line in File.ReadAllLines(inputFilename)) { //Console.WriteLine(Convert.ToDouble(line)); massList.Add(Convert.ToDouble(line)); } ExtractIonChromatogramAsRcode(rawFile, -1, -1, massList, ppmError, outputFilename, filter); } return; } catch (Exception ex) { Console.Error.WriteLine("failed to catch configfile and itol"); Console.Error.WriteLine("{}", ex.Message); return; } } } catch (Exception ex) { Console.WriteLine("Error accessing RAWFileReader library! - " + ex.Message); } // Get the memory used at the end of processing Process processAfter = Process.GetCurrentProcess(); long memoryAfter = processAfter.PrivateMemorySize64 / 1024; Console.WriteLine(); Console.WriteLine("Memory Usage:"); Console.WriteLine(" Before {0} kb, After {1} kb, Extra {2} kb", memoryBefore, memoryAfter, memoryAfter - memoryBefore); }
private static void Main(string[] args) { // This local variable controls if the AnalyzeAllScans method is called // bool analyzeScans = false; string rawR_version = "0.0.1"; // Get the memory used at the beginning of processing Process processBefore = Process.GetCurrentProcess(); long memoryBefore = processBefore.PrivateMemorySize64 / 1024; try { // Check to see if the RAW file name was supplied as an argument to the program string filename = string.Empty; string mode = string.Empty; Hashtable hashtable = new Hashtable() { { "version", "print version information." }, { "scanFilter", "print scan filters." }, { "infoR", "print the raw file's meta data as R code." }, { "chromatogram", "base peak chromatogram." }, { "xic", "prints xic unfiltered." }, { "tic", "prints xic unfiltered." }, { "scans", "print spectrum of scanid as Rcode." }, { "index", "print index as csv of all scans." } }; if (args.Length > 0) { filename = args[0]; if (args.Length == 1) { Console.WriteLine("rawR version = {}", rawR_version); Console.WriteLine("missing mode argument. setting to mode = 'info'."); mode = "info"; } else { mode = args[1]; } if (!hashtable.Contains(mode)) { Console.WriteLine("rawR version = {}", rawR_version); Console.WriteLine("mode '{0}' not allowed. Please use one of the following modes:", mode); foreach (var k in hashtable.Keys) { Console.WriteLine("{0} - {1}", k.ToString(), hashtable[k].ToString()); } Environment.Exit(1); } } if (string.IsNullOrEmpty(filename)) { Console.WriteLine("No RAW file specified!"); return; } // Check to see if the specified RAW file exists if (!File.Exists(filename)) { Console.WriteLine("rawR version = {}", rawR_version); Console.WriteLine(@"The file doesn't exist in the specified location - {0}", filename); return; } // Create the IRawDataPlus object for accessing the RAW file var rawFile = RawFileReaderAdapter.FileFactory(filename); if (!rawFile.IsOpen || rawFile.IsError) { Console.WriteLine("Unable to access the RAW file using the RawFileReader class!"); return; } // Check for any errors in the RAW file if (rawFile.IsError) { Console.WriteLine("Error opening ({0}) - {1}", rawFile.FileError, filename); return; } // Check if the RAW file is being acquired if (rawFile.InAcquisition) { Console.WriteLine("RAW file still being acquired - " + filename); return; } rawFile.SelectInstrument(Device.MS, 1); //Console.WriteLine("DEBUG {0}", rawFile.GetInstrumentMethod(3).ToString()); // Get the first and last scan from the RAW file int firstScanNumber = rawFile.RunHeaderEx.FirstSpectrum; int lastScanNumber = rawFile.RunHeaderEx.LastSpectrum; // Get the start and end time from the RAW file double startTime = rawFile.RunHeaderEx.StartTime; double endTime = rawFile.RunHeaderEx.EndTime; if (mode == "systeminfo") { Console.WriteLine("raw file name: {0}", Path.GetFileName(filename)); // Print some OS and other information Console.WriteLine("System Information:"); Console.WriteLine(" OS Version: " + Environment.OSVersion); Console.WriteLine(" 64 bit OS: " + Environment.Is64BitOperatingSystem); Console.WriteLine(" Computer: " + Environment.MachineName); Console.WriteLine(" number Cores: " + Environment.ProcessorCount); Console.WriteLine(" Date: " + DateTime.Now); } if (mode == "infoR") { rawFile.PrintInfoAsRcode(); return; } // Display all of the trailer extra data fields present in the RAW file // Get the number of filters present in the RAW file int numberFilters = rawFile.GetFilters().Count; // Get the scan filter for the first and last spectrum in the RAW file //var firstFilter = rawFile.GetFilterForScanNumber(firstScanNumber); //var lastFilter = rawFile.GetFilterForScanNumber(lastScanNumber); if (mode == "scanFilter") { foreach (var filter in rawFile.GetFilters()) { Console.WriteLine(filter.ToString()); } Environment.Exit(0); } if (mode == "version") { Console.WriteLine("version={}", rawR_version); Environment.Exit(0); } if (mode == "chromatogram") { // Get the BasePeak chromatogram for the MS data string filter = "ms"; try { filter = args[2]; } catch { } GetChromatogram(rawFile, firstScanNumber, lastScanNumber, true, filter); Environment.Exit(0); } if (mode == "index") { rawFile.GetIndex(); return; } if (mode == "scans") { List <int> scans = new List <int>(); var scanfile = args[2]; int scanNumber; foreach (var line in File.ReadAllLines(scanfile)) { try{ Int32.TryParse(line, out scanNumber); if (scanNumber > 0) { scans.Add(scanNumber); } } catch {} } if (scans.Count == 0) { rawFile.WriteSpectrumAsRcode0(args[3]); } else { rawFile.WriteSpectrumAsRcode(args[3], scans); } return; } if (mode == "xic") { try { var inputFilename = args[2]; double ppmError = Convert.ToDouble(args[3]); var outputFilename = args[4]; string filter = "ms"; try { filter = args[5]; } catch { } List <double> massList = new List <double>(); if (File.Exists(args[2])) { foreach (var line in File.ReadAllLines(inputFilename)) { massList.Add(Convert.ToDouble(line)); } ExtractIonChromatogramAsRcode(rawFile, -1, -1, massList, ppmError, outputFilename, filter); } return; } catch (Exception ex) { Console.Error.WriteLine("failed to catch configfile and itol"); Console.Error.WriteLine("{}", ex.Message); return; } } } catch (Exception ex) { Console.WriteLine("Error accessing RAWFileReader library! - " + ex.Message); } // Get the memory used at the end of processing Process processAfter = Process.GetCurrentProcess(); long memoryAfter = processAfter.PrivateMemorySize64 / 1024; Console.WriteLine(); Console.WriteLine("Memory Usage:"); Console.WriteLine(" Before {0} kb, After {1} kb, Extra {2} kb", memoryBefore, memoryAfter, memoryAfter - memoryBefore); }
//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);
//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());
} } 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(); } } }
} } 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)
//int maxNum = plus.RunHeaderEx.LastSpectrum > endNum ? endNum : plus.RunHeaderEx.LastSpectrum; LimitedSizeDictionary<string, int> precursorMs2ScanNumbers = new LimitedSizeDictionary<string, int>(40); plus.SelectInstrument(Device.MS, 1); if(highMS - 0.00 <= 0.01) { highMS = plus.RunHeaderEx.HighMass; } double maxMs = plus.RunHeaderEx.HighMass; double minMs = plus.RunHeaderEx.LowMass; lowMS = minMs; highMS = maxMs; string fileName = DateTime.Now.ToLocalTime().ToString().Replace("/", "").Replace(":", "").Replace(" ", "_") + ".csv"; FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write); StreamWriter writer = new StreamWriter(stream, Encoding.UTF8); writer.WriteLine("ScanNumber, RT, Mass, Resolution, Intensity, Noise, Filter,MSLevel,collisionEnergy, precursorNum,precursorMS"); while (startNum <= endNum) { var levelInfo = ""; var spectrumRef = ""; Scan scan = Scan.FromFile(plus, startNum); IScanFilter scanFilter = plus.GetFilterForScanNumber(startNum); IScanEvent scanEvent = plus.GetScanEventForScanNumber(startNum); switch (scanFilter.MSOrder) { case MSOrderType.Ms: // Keep track of scan number for precursor reference precursorMs1ScanNumber = startNum; reaction = scanEvent.GetReaction(0); value = reaction.CollisionEnergy.ToString(CultureInfo.InvariantCulture).ToString(); levelInfo = scanFilter.MSOrder.ToString() + "," + "" + "," + "" + "," + ""; break; case MSOrderType.Ms2: // Keep track of scan number and isolation m/z for precursor reference var result = Regex.Match(scanEvent.ToString(), FilterStringIsolationMzPattern); if (result.Success) { if (precursorMs2ScanNumbers.ContainsKey(result.Groups[1].Value)) { precursorMs2ScanNumbers.Remove(result.Groups[1].Value); } precursorMs2ScanNumbers.Add(result.Groups[1].Value, startNum); } spectrumRef = precursorMs1ScanNumber.ToString(); reaction = scanEvent.GetReaction(0); value = reaction.CollisionEnergy.ToString(CultureInfo.InvariantCulture).ToString(); precursorMS = reaction.PrecursorMass; levelInfo = scanFilter.MSOrder.ToString() + "," + value + "," + spectrumRef.ToString() + "," + precursorMS.ToString() ; break; case MSOrderType.Ms3: var precursorMs2ScanNumber = precursorMs2ScanNumbers.Keys.FirstOrDefault(isolationMz => scanEvent.ToString().Contains(isolationMz)); spectrumRef = precursorMs2ScanNumbers[precursorMs2ScanNumber].ToString(); if (!precursorMs2ScanNumber.IsNullOrEmpty()) { reaction = scanEvent.GetReaction(1); } else { throw new InvalidOperationException("Couldn't find a MS2 precursor scan for MS3 scan " + scanEvent); } precursorMS = reaction.PrecursorMass; value = reaction.CollisionEnergy.ToString(CultureInfo.InvariantCulture).ToString(); levelInfo = scanFilter.MSOrder.ToString() + "," + value + "," + spectrumRef.ToString() + "," + precursorMS.ToString(); break; default: throw new ArgumentOutOfRangeException(); } //var scanStatistics = plus.GetScanStatsForScanNumber(startNum); //// Get the segmented (low res and profile) scan data //var segmentedScan = plus.GetSegmentedScanFromScanNumber(startNum, scanStatistics); //var masses = segmentedScan.Positions; //var intensitis = segmentedScan.Intensities; //Console.WriteLine(masses.Length); //Console.WriteLine(intensitis.Length); //Console.WriteLine(filterObj.MSOrder); int cnt = 0; while(cnt < scan.PreferredMasses.Length) { if(lowMS < scan.PreferredMasses[cnt] && scan.PreferredMasses[cnt] < highMS ) { double rt = plus.RetentionTimeFromScanNumber(startNum); double msval = scan.PreferredMasses[cnt]; double resolution = (scan.PreferredResolutions.Length == 0) ? 0.0 : scan.PreferredResolutions[cnt]; double intensity = (scan.PreferredIntensities.Length == 0) ? 0.0 : scan.PreferredIntensities[cnt]; double noise = (scan.PreferredNoises.Length == 0) ? 0.0 : scan.PreferredNoises[cnt]; writer.WriteLine("{0},{1},{2},{3},{4},{5},{6},{7}", startNum.ToString(), rt.ToString(), msval.ToString(), resolution.ToString(), intensity.ToString(), noise.ToString(), scanFilter.ToString(), levelInfo); } cnt += 1; } startNum += 1; } writer.Close(); } public static void getMSdataFromRT(double startRT, int endRT, string filePath, double lowMS = 0.00, double highMS = 0.00) { IRawDataPlus plus = RawFileReaderAdapter.FileFactory(filePath); plus.SelectInstrument(Device.MS, 1); if (highMS - 0.00 <= 0.01) { highMS = plus.RunHeaderEx.HighMass; } int startNum = plus.ScanNumberFromRetentionTime(startRT); int endNum = plus.ScanNumberFromRetentionTime(endRT); int maxNum = plus.RunHeaderEx.LastSpectrum > endNum ? endNum : plus.RunHeaderEx.LastSpectrum; string fileName = DateTime.Now.ToLocalTime().ToString().Replace("/", "").Replace(":", "").Replace(" ", "_") + ".csv"; FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write); StreamWriter writer = new StreamWriter(stream, Encoding.UTF8); writer.WriteLine("ScanNumber, RT, Mass, Resolution, Intensity, Noise, Filter"); while (startNum <= endNum) { Scan scan = Scan.FromFile(plus, startNum); string filter = plus.GetFilterForScanNumber(startNum).ToString(); int cnt = 0; while (cnt < scan.PreferredMasses.Length) { if (lowMS < scan.PreferredMasses[cnt] && scan.PreferredMasses[cnt] < highMS) { double rt = plus.RetentionTimeFromScanNumber(startNum); double msval = scan.PreferredMasses[cnt]; double resolution = (scan.PreferredResolutions.Length == 0) ? 0.0 : scan.PreferredResolutions[cnt]; double intensity = (scan.PreferredIntensities.Length == 0) ? 0.0 : scan.PreferredIntensities[cnt]; double noise = (scan.PreferredNoises.Length == 0) ? 0.0 : scan.PreferredNoises[cnt]; writer.WriteLine("{0},{1},{2},{3},{4},{5},{6}", startNum.ToString(), rt.ToString(), msval.ToString(), resolution.ToString(), intensity.ToString(), noise.ToString(), filter.ToString()); } cnt += 1; } startNum += 1; } writer.Close(); }
private static void Main(string[] args) { // This local variable controls if the AnalyzeAllScans method is called bool analyzeScans = false; string rawDiagVersion = "0.0.35"; // Get the memory used at the beginning of processing Process processBefore = Process.GetCurrentProcess(); long memoryBefore = processBefore.PrivateMemorySize64 / 1024; try { // Check to see if the RAW file name was supplied as an argument to the program string filename = string.Empty; string mode = string.Empty; Hashtable hashtable = new Hashtable() { { "version", "print version information." }, { "info", "print the raw file's meta data." }, { "xic", "prints xic unfiltered." }, }; if (args.Length > 0) { filename = args[0]; if (args.Length == 1) { Console.WriteLine("rawDiag version = {}", rawDiagVersion); Console.WriteLine("missing mode argument. setting to mode = 'info'."); mode = "info"; } else { mode = args[1]; } if (!hashtable.Contains(mode)) { Console.WriteLine("rawDiag version = {}", rawDiagVersion); Console.WriteLine("mode '{0}' not allowed. Please use one of the following modes:", mode); foreach (var k in hashtable.Keys) { Console.WriteLine("{0} - {1}", k.ToString(), hashtable[k].ToString()); } Environment.Exit(1); } } if (string.IsNullOrEmpty(filename)) { Console.WriteLine("No RAW file specified!"); return; } // Check to see if the specified RAW file exists if (!File.Exists(filename)) { Console.WriteLine("rawDiag version = {}", rawDiagVersion); Console.WriteLine(@"The file doesn't exist in the specified location - " + filename); return; } // Create the IRawDataPlus object for accessing the RAW file var rawFile = RawFileReaderAdapter.FileFactory(filename); if (!rawFile.IsOpen || rawFile.IsError) { Console.WriteLine("Unable to access the RAW file using the RawFileReader class!"); return; } // Check for any errors in the RAW file if (rawFile.IsError) { Console.WriteLine("Error opening ({0}) - {1}", rawFile.FileError, filename); return; } // Check if the RAW file is being acquired if (rawFile.InAcquisition) { Console.WriteLine("RAW file still being acquired - " + filename); return; } if (mode == "info") { // Get the number of instruments (controllers) present in the RAW file and set the // selected instrument to the MS instrument, first instance of it Console.WriteLine("Number of instruments: {0}", rawFile.InstrumentCount); } rawFile.SelectInstrument(Device.MS, 1); //Console.WriteLine("DEBUG {0}", rawFile.GetInstrumentMethod(3).ToString()); // Get the first and last scan from the RAW file int firstScanNumber = rawFile.RunHeaderEx.FirstSpectrum; int lastScanNumber = rawFile.RunHeaderEx.LastSpectrum; // Get the start and end time from the RAW file double startTime = rawFile.RunHeaderEx.StartTime; double endTime = rawFile.RunHeaderEx.EndTime; if (mode == "systeminfo") { Console.WriteLine("raw file name: {0}", Path.GetFileName(filename)); // Print some OS and other information Console.WriteLine("System Information:"); Console.WriteLine(" OS Version: " + Environment.OSVersion); Console.WriteLine(" 64 bit OS: " + Environment.Is64BitOperatingSystem); Console.WriteLine(" Computer: " + Environment.MachineName); Console.WriteLine(" number Cores: " + Environment.ProcessorCount); Console.WriteLine(" Date: " + DateTime.Now); } if (mode == "info") { // Get some information from the header portions of the RAW file and display that information. // The information is general information pertaining to the RAW file. Console.WriteLine("General File Information:"); Console.WriteLine(" RAW file: " + Path.GetFileName(rawFile.FileName)); Console.WriteLine(" RAW file version: " + rawFile.FileHeader.Revision); Console.WriteLine(" Creation date: " + rawFile.FileHeader.CreationDate); Console.WriteLine(" Operator: " + rawFile.FileHeader.WhoCreatedId); Console.WriteLine(" Number of instruments: " + rawFile.InstrumentCount); Console.WriteLine(" Description: " + rawFile.FileHeader.FileDescription); Console.WriteLine(" Instrument model: " + rawFile.GetInstrumentData().Model); Console.WriteLine(" Instrument name: " + rawFile.GetInstrumentData().Name); // Console.WriteLine(" Instrument method: {0}", rawFile.GetAllInstrumentFriendlyNamesFromInstrumentMethod().Length); Console.WriteLine(" Serial number: " + rawFile.GetInstrumentData().SerialNumber); Console.WriteLine(" Software version: " + rawFile.GetInstrumentData().SoftwareVersion); Console.WriteLine(" Firmware version: " + rawFile.GetInstrumentData().HardwareVersion); Console.WriteLine(" Units: " + rawFile.GetInstrumentData().Units); Console.WriteLine(" Mass resolution: {0:F3} ", rawFile.RunHeaderEx.MassResolution); Console.WriteLine(" Number of scans: {0}", rawFile.RunHeaderEx.SpectraCount); Console.WriteLine(" Number of ms2 scans: {0}", Enumerable .Range(1, lastScanNumber - firstScanNumber) .Count(x => rawFile.GetFilterForScanNumber(x) .ToString() .Contains("Full ms2"))); Console.WriteLine(" Scan range: [{0}, {1}]", firstScanNumber, lastScanNumber); Console.WriteLine(" Time range: [{0:F2}, {1:F2}]", startTime, endTime); Console.WriteLine(" Mass range: [{0:F4}, {1:F4}]", rawFile.RunHeaderEx.LowMass, rawFile.RunHeaderEx.HighMass); Console.WriteLine(); // Get information related to the sample that was processed Console.WriteLine("Sample Information:"); Console.WriteLine(" Sample name: " + rawFile.SampleInformation.SampleName); Console.WriteLine(" Sample id: " + rawFile.SampleInformation.SampleId); Console.WriteLine(" Sample type: " + rawFile.SampleInformation.SampleType); Console.WriteLine(" Sample comment: " + rawFile.SampleInformation.Comment); Console.WriteLine(" Sample vial: " + rawFile.SampleInformation.Vial); Console.WriteLine(" Sample volume: " + rawFile.SampleInformation.SampleVolume); Console.WriteLine(" Sample injection volume: " + rawFile.SampleInformation.InjectionVolume); Console.WriteLine(" Sample row number: " + rawFile.SampleInformation.RowNumber); Console.WriteLine(" Sample dilution factor: " + rawFile.SampleInformation.DilutionFactor); Console.WriteLine(); // Read the first instrument method (most likely for the MS portion of the instrument). // NOTE: This method reads the instrument methods from the RAW file but the underlying code // uses some Microsoft code that hasn't been ported to Linux or MacOS. Therefore this // method won't work on those platforms therefore the check for Windows. if (Environment.OSVersion.ToString().Contains("Windows")) { var deviceNames = rawFile.GetAllInstrumentNamesFromInstrumentMethod(); foreach (var device in deviceNames) { Console.WriteLine("Instrument method: " + device); } Console.WriteLine(); } } // Display all of the trailer extra data fields present in the RAW file // Get the number of filters present in the RAW file int numberFilters = rawFile.GetFilters().Count; // Get the scan filter for the first and last spectrum in the RAW file var firstFilter = rawFile.GetFilterForScanNumber(firstScanNumber); var lastFilter = rawFile.GetFilterForScanNumber(lastScanNumber); if (mode == "info") { Console.WriteLine("Filter Information:"); Console.WriteLine(" Scan filter (first scan): " + firstFilter.ToString()); Console.WriteLine(" Scan filter (last scan): " + lastFilter.ToString()); Console.WriteLine(" Total number of filters: " + numberFilters); Console.WriteLine(); // ListTrailerExtraFields(rawFile); Environment.Exit(0); } if (mode == "version") { Console.WriteLine("version={}", rawDiagVersion); Environment.Exit(0); } if (mode == "xic") { try { var inputFilename = args[2]; double ppmError = Convert.ToDouble(args[3]); var outputFilename = args[4]; List <double> massList = new List <double>(); if (File.Exists(args[2])) { foreach (var line in File.ReadAllLines(inputFilename)) { massList.Add(Convert.ToDouble(line)); } GetXIC(rawFile, -1, -1, massList, ppmError, outputFilename); } return; } catch (Exception ex) { Console.Error.WriteLine("failed to catch configfile and itol"); Console.Error.WriteLine("{}", ex.Message); return; } } } catch (Exception ex) { Console.WriteLine("Error accessing RAWFileReader library! - " + ex.Message); } // Get the memory used at the end of processing Process processAfter = Process.GetCurrentProcess(); long memoryAfter = processAfter.PrivateMemorySize64 / 1024; Console.WriteLine(); Console.WriteLine("Memory Usage:"); Console.WriteLine(" Before {0} kb, After {1} kb, Extra {2} kb", memoryBefore, memoryAfter, memoryAfter - memoryBefore); }