diff --git a/MainClass.cs b/MainClass.cs index 7ece9cf..df49e70 100644 --- a/MainClass.cs +++ b/MainClass.cs @@ -63,15 +63,15 @@ private static void XicParametersParsing(string[] args) "h|help", "Prints out the options.", h => parameters.help = h != null }, - { - "i=|input=", "The raw file input (Required). Specify this or an input directory -d", - v => singleFile = v - }, { "d=|input_directory=", "The directory containing the raw files (Required). Specify this or an input file -i.", v => fileDirectory = v }, + { + "i=|input=", "The raw file input (Required). Specify this or an input directory -d", + v => singleFile = v + }, { "j=|json=", "The json input file (Required).", @@ -83,12 +83,12 @@ private static void XicParametersParsing(string[] args) v => parameters.printJsonExample = v != null }, { - "o=|output=", + "o=|output_directory=", "The output directory. Specify this or an output file. Specifying neither writes to the input directory.", v => outputDirectory = v }, { - "b=|output_file", + "b=|output=", "The output file. Specify this or an output directory. Specifying neither writes to the input directory.", v => outputFile = v }, diff --git a/RawFileParser.cs b/RawFileParser.cs old mode 100755 new mode 100644 index c233af1..2d94031 --- a/RawFileParser.cs +++ b/RawFileParser.cs @@ -146,12 +146,6 @@ private static void ProcessFile(ParseInput parseInput) // Get the first and last scan from the RAW file firstScanNumber = rawFile.RunHeaderEx.FirstSpectrum; lastScanNumber = rawFile.RunHeaderEx.LastSpectrum; - - // Check for empty file - if (lastScanNumber < 1) - { - throw new RawFileParserException("Empty RAW file, no output will be produced"); - } } if (parseInput.MetadataFormat != MetadataFormat.NONE) diff --git a/Writer/MetadataWriter.cs b/Writer/MetadataWriter.cs index 5de86a2..95654ee 100644 --- a/Writer/MetadataWriter.cs +++ b/Writer/MetadataWriter.cs @@ -111,7 +111,7 @@ public void WriteMetadata(IRawDataPlus rawFile, int firstScanNumber, int lastSca } } } - + if (minCharge == 100000000000000) { minCharge = 0; @@ -178,58 +178,57 @@ private void WriteJsonMetada(IRawDataPlus rawFile, int firstScanNumber, int last // MS Data - foreach (KeyValuePair entry in msTypes) - { - if (entry.Key.Equals(MSOrderType.Ms.ToString())) - metadata.addMSData(new CVTerm("PRIDE:0000481", "PRIDE", "Number of MS1 spectra", - entry.Value.ToString())); - if (entry.Key.Equals(MSOrderType.Ms2.ToString())) - metadata.addMSData(new CVTerm("PRIDE:0000482", "PRIDE", "Number of MS2 spectra", - entry.Value.ToString())); - if (entry.Key.Equals(MSOrderType.Ms3.ToString())) - metadata.addMSData(new CVTerm("PRIDE:0000483", "PRIDE", "Number of MS3 spectra", - entry.Value.ToString())); - } - - metadata.addMSData(new CVTerm("PRIDE:0000472", "PRIDE", "MS min charge", - minCharge.ToString(CultureInfo.InvariantCulture))); - metadata.addMSData(new CVTerm("PRIDE:0000473", "PRIDE", "MS max charge", - maxCharge.ToString(CultureInfo.InvariantCulture))); - - metadata.addMSData(new CVTerm("PRIDE:0000474", "PRIDE", "MS min RT", - minTime.ToString(CultureInfo.InvariantCulture))); - metadata.addMSData(new CVTerm("PRIDE:0000475", "PRIDE", "MS max RT", - maxTime.ToString(CultureInfo.InvariantCulture))); - - metadata.addMSData(new CVTerm("PRIDE:0000476", "PRIDE", "MS min MZ", - minMz.ToString(CultureInfo.InvariantCulture))); - metadata.addMSData(new CVTerm("PRIDE:0000477", "PRIDE", "MS max MZ", - maxMz.ToString(CultureInfo.InvariantCulture))); - - // Scan Settings - // Get the start and end time from the RAW file - if (rawFile.SelectMsData()) { - var runHeader = rawFile.RunHeader; - var runHeaderEx = rawFile.RunHeaderEx; - var startTime = runHeaderEx.StartTime; - var endTime = runHeaderEx.EndTime; + foreach (KeyValuePair entry in msTypes) + { + if (entry.Key.Equals(MSOrderType.Ms.ToString())) + metadata.addMSData(new CVTerm("PRIDE:0000481", "PRIDE", "Number of MS1 spectra", + entry.Value.ToString())); + if (entry.Key.Equals(MSOrderType.Ms2.ToString())) + metadata.addMSData(new CVTerm("PRIDE:0000482", "PRIDE", "Number of MS2 spectra", + entry.Value.ToString())); + if (entry.Key.Equals(MSOrderType.Ms3.ToString())) + metadata.addMSData(new CVTerm("PRIDE:0000483", "PRIDE", "Number of MS3 spectra", + entry.Value.ToString())); + } + + metadata.addMSData(new CVTerm("PRIDE:0000472", "PRIDE", "MS min charge", + minCharge.ToString(CultureInfo.InvariantCulture))); + metadata.addMSData(new CVTerm("PRIDE:0000473", "PRIDE", "MS max charge", + maxCharge.ToString(CultureInfo.InvariantCulture))); + + metadata.addMSData(new CVTerm("PRIDE:0000474", "PRIDE", "MS min RT", + minTime.ToString(CultureInfo.InvariantCulture))); + metadata.addMSData(new CVTerm("PRIDE:0000475", "PRIDE", "MS max RT", + maxTime.ToString(CultureInfo.InvariantCulture))); + + metadata.addMSData(new CVTerm("PRIDE:0000476", "PRIDE", "MS min MZ", + minMz.ToString(CultureInfo.InvariantCulture))); + metadata.addMSData(new CVTerm("PRIDE:0000477", "PRIDE", "MS max MZ", + maxMz.ToString(CultureInfo.InvariantCulture))); + + // Scan Settings + // Get the start and end time from the RAW file + var startTime = rawFile.RunHeaderEx.StartTime; + var endTime = rawFile.RunHeaderEx.EndTime; metadata.addScanSetting(new CVTerm("MS:1000016", "MS", "scan start time", startTime.ToString(CultureInfo.InvariantCulture))); + metadata.addScanSetting(new CVTerm("", "", "expected runtime", + rawFile.RunHeader.ExpectedRuntime.ToString(CultureInfo.InvariantCulture))); metadata.addScanSetting(new CVTerm("MS:1000011", "MS", "mass resolution", - runHeaderEx.MassResolution.ToString(CultureInfo.InvariantCulture))); + rawFile.RunHeaderEx.MassResolution.ToString(CultureInfo.InvariantCulture))); metadata.addScanSetting(new CVTerm("UO:0000002", "MS", "mass unit", rawFile.GetInstrumentData().Units.ToString())); metadata.addScanSetting(new CVTerm("PRIDE:0000478", "PRIDE", "Number of scans", - runHeaderEx.SpectraCount.ToString())); + rawFile.RunHeaderEx.SpectraCount.ToString())); + metadata.addScanSetting(new CVTerm("PRIDE:0000479", "PRIDE", "MS scan range", + firstScanNumber + ":" + lastScanNumber)); metadata.addScanSetting(new CVTerm("PRIDE:0000484", "PRIDE", "Retention time range", startTime + ":" + endTime)); metadata.addScanSetting(new CVTerm("PRIDE:0000485", "PRIDE", "Mz range", - runHeaderEx.LowMass + ":" + runHeaderEx.HighMass)); + rawFile.RunHeaderEx.LowMass + ":" + rawFile.RunHeaderEx.HighMass)); metadata.addScanSetting(fragmentationTypes); - metadata.addScanSetting(new CVTerm("PRIDE:0000479", "PRIDE", "MS scan range", - firstScanNumber + ":" + lastScanNumber)); } // Sample Data @@ -373,31 +372,31 @@ private void WriteTextMetadata(IRawDataPlus rawFile, int firstScanNumber, int la } // MS Data - output.Add("#MsData"); - foreach (KeyValuePair entry in msTypes) + if (rawFile.SelectMsData()) { - if (entry.Key.Equals(MSOrderType.Ms.ToString())) - output.Add("Number of MS1 spectra=" + entry.Value); - if (entry.Key.Equals(MSOrderType.Ms2.ToString())) - output.Add("Number of MS2 spectra=" + entry.Value); - if (entry.Key.Equals(MSOrderType.Ms3.ToString())) - output.Add("Number of MS3 spectra=" + entry.Value); - } - - output.AddRange(new List + output.Add("#MsData"); + foreach (KeyValuePair entry in msTypes) { - "MS min charge=" + minCharge.ToString(CultureInfo.InvariantCulture), - "MS max charge=" + maxCharge.ToString(CultureInfo.InvariantCulture), - $"MS min RT={minTime.ToString(CultureInfo.InvariantCulture)}", - $"MS max RT={maxTime.ToString(CultureInfo.InvariantCulture)}", - $"MS min MZ={minMz.ToString(CultureInfo.InvariantCulture)}", - $"MS max MZ={maxMz.ToString(CultureInfo.InvariantCulture)}" + if (entry.Key.Equals(MSOrderType.Ms.ToString())) + output.Add("Number of MS1 spectra=" + entry.Value); + if (entry.Key.Equals(MSOrderType.Ms2.ToString())) + output.Add("Number of MS2 spectra=" + entry.Value); + if (entry.Key.Equals(MSOrderType.Ms3.ToString())) + output.Add("Number of MS3 spectra=" + entry.Value); } - ); - // Scan Settings - if (rawFile.SelectMsData()) - { + output.AddRange(new List + { + "MS min charge=" + minCharge.ToString(CultureInfo.InvariantCulture), + "MS max charge=" + maxCharge.ToString(CultureInfo.InvariantCulture), + $"MS min RT={minTime.ToString(CultureInfo.InvariantCulture)}", + $"MS max RT={maxTime.ToString(CultureInfo.InvariantCulture)}", + $"MS min MZ={minMz.ToString(CultureInfo.InvariantCulture)}", + $"MS max MZ={maxMz.ToString(CultureInfo.InvariantCulture)}" + } + ); + + // Scan Settings // Get the start and end time from the RAW file var startTime = rawFile.RunHeaderEx.StartTime; var endTime = rawFile.RunHeaderEx.EndTime; @@ -415,6 +414,7 @@ private void WriteTextMetadata(IRawDataPlus rawFile, int firstScanNumber, int la } ); } + // Sample Data output.Add("#SampleData"); diff --git a/Writer/MgfSpectrumWriter.cs b/Writer/MgfSpectrumWriter.cs index c347944..abc07ff 100644 --- a/Writer/MgfSpectrumWriter.cs +++ b/Writer/MgfSpectrumWriter.cs @@ -41,208 +41,211 @@ public override void Write(IRawDataPlus rawFile, int firstScanNumber, int lastSc ConfigureWriter(".mgf"); using (Writer) { - Log.Info("Processing " + (lastScanNumber - firstScanNumber + 1) + " scans"); - - var lastScanProgress = 0; - for (var scanNumber = firstScanNumber; scanNumber <= lastScanNumber; scanNumber++) + if (rawFile.SelectMsData()) { - if (ParseInput.LogFormat == LogFormat.DEFAULT) + Log.Info("Processing " + (lastScanNumber - firstScanNumber + 1) + " scans"); + + var lastScanProgress = 0; + for (var scanNumber = firstScanNumber; scanNumber <= lastScanNumber; scanNumber++) { - var scanProgress = (int) ((double) scanNumber / (lastScanNumber - firstScanNumber + 1) * 100); - if (scanProgress % ProgressPercentageStep == 0) + if (ParseInput.LogFormat == LogFormat.DEFAULT) { - if (scanProgress != lastScanProgress) + var scanProgress = (int)((double)scanNumber / (lastScanNumber - firstScanNumber + 1) * 100); + if (scanProgress % ProgressPercentageStep == 0) { - Console.Write("" + scanProgress + "% "); - lastScanProgress = scanProgress; + if (scanProgress != lastScanProgress) + { + Console.Write("" + scanProgress + "% "); + lastScanProgress = scanProgress; + } } } - } - _precursorScanNumber = 0; + _precursorScanNumber = 0; - // Get the scan from the RAW file - var scan = Scan.FromFile(rawFile, scanNumber); + // Get the scan from the RAW file + var scan = Scan.FromFile(rawFile, scanNumber); - // Get the retention time - var retentionTime = rawFile.RetentionTimeFromScanNumber(scanNumber); + // Get the retention time + var retentionTime = rawFile.RetentionTimeFromScanNumber(scanNumber); - // Get the scan filter for this scan number - var scanFilter = rawFile.GetFilterForScanNumber(scanNumber); + // Get the scan filter for this scan number + var scanFilter = rawFile.GetFilterForScanNumber(scanNumber); - // Get the scan event for this scan number - var scanEvent = rawFile.GetScanEventForScanNumber(scanNumber); + // Get the scan event for this scan number + var scanEvent = rawFile.GetScanEventForScanNumber(scanNumber); - // Trailer extra data list - ScanTrailer trailerData; + // Trailer extra data list + ScanTrailer trailerData; - try - { - trailerData = new ScanTrailer(rawFile.GetTrailerExtraInformation(scanNumber)); - } - catch (Exception ex) - { - Log.WarnFormat("Cannot load trailer infromation for scan {0} due to following exception\n{1}", scanNumber, ex.Message); - ParseInput.NewWarn(); - trailerData = new ScanTrailer(); - } - - // Get scan ms level - var msLevel = (int)scanFilter.MSOrder; - - // Construct the precursor reference string for the title - var precursorReference = ""; - - if (ParseInput.MgfPrecursor) - { - if (msLevel == 1) + try { - // Keep track of the MS1 scan number for precursor reference - _precursorScanNumbers[""] = scanNumber; + trailerData = new ScanTrailer(rawFile.GetTrailerExtraInformation(scanNumber)); } - else + catch (Exception ex) { - // Keep track of scan number and isolation m/z for precursor reference - var result = _filterStringIsolationMzPattern.Match(scanEvent.ToString()); - if (result.Success) - { - if (_precursorScanNumbers.ContainsKey(result.Groups[1].Value)) - { - _precursorScanNumbers.Remove(result.Groups[1].Value); - } + Log.WarnFormat("Cannot load trailer infromation for scan {0} due to following exception\n{1}", scanNumber, ex.Message); + ParseInput.NewWarn(); + trailerData = new ScanTrailer(); + } - _precursorScanNumbers.Add(result.Groups[1].Value, scanNumber); - } + // Get scan ms level + var msLevel = (int)scanFilter.MSOrder; + + // Construct the precursor reference string for the title + var precursorReference = ""; - //update precursor scan if it is provided in trailer data - var trailerMasterScan = trailerData.AsPositiveInt("Master Scan Number:"); - if (trailerMasterScan.HasValue) + if (ParseInput.MgfPrecursor) + { + if (msLevel == 1) { - _precursorScanNumber = trailerMasterScan.Value; + // Keep track of the MS1 scan number for precursor reference + _precursorScanNumbers[""] = scanNumber; } - else //try getting it from the scan filter + else { - var parts = Regex.Split(result.Groups[1].Value, " "); - - //find the position of the first (from the end) precursor with a different mass - //to account for possible supplementary activations written in the filter - var lastIonMass = parts.Last().Split('@').First(); - int last = parts.Length; - while (last > 0 && - parts[last - 1].Split('@').First() == lastIonMass) + // Keep track of scan number and isolation m/z for precursor reference + var result = _filterStringIsolationMzPattern.Match(scanEvent.ToString()); + if (result.Success) { - last--; + if (_precursorScanNumbers.ContainsKey(result.Groups[1].Value)) + { + _precursorScanNumbers.Remove(result.Groups[1].Value); + } + + _precursorScanNumbers.Add(result.Groups[1].Value, scanNumber); } - string parentFilter = String.Join(" ", parts.Take(last)); - if (_precursorScanNumbers.ContainsKey(parentFilter)) + //update precursor scan if it is provided in trailer data + var trailerMasterScan = trailerData.AsPositiveInt("Master Scan Number:"); + if (trailerMasterScan.HasValue) { - _precursorScanNumber = _precursorScanNumbers[parentFilter]; + _precursorScanNumber = trailerMasterScan.Value; + } + else //try getting it from the scan filter + { + var parts = Regex.Split(result.Groups[1].Value, " "); + + //find the position of the first (from the end) precursor with a different mass + //to account for possible supplementary activations written in the filter + var lastIonMass = parts.Last().Split('@').First(); + int last = parts.Length; + while (last > 0 && + parts[last - 1].Split('@').First() == lastIonMass) + { + last--; + } + + string parentFilter = String.Join(" ", parts.Take(last)); + if (_precursorScanNumbers.ContainsKey(parentFilter)) + { + _precursorScanNumber = _precursorScanNumbers[parentFilter]; + } + } + + if (_precursorScanNumber > 0) + { + precursorReference = ConstructSpectrumTitle((int)Device.MS, 1, _precursorScanNumber); + } + else + { + Log.Error($"Failed finding precursor for {scanNumber}"); + ParseInput.NewError(); } } + } - if (_precursorScanNumber > 0) + if (ParseInput.MsLevel.Contains(msLevel)) + { + var reaction = GetReaction(scanEvent, scanNumber); + + Writer.WriteLine("BEGIN IONS"); + if (!ParseInput.MgfPrecursor) { - precursorReference = ConstructSpectrumTitle((int)Device.MS, 1, _precursorScanNumber); + Writer.WriteLine($"TITLE={ConstructSpectrumTitle((int)Device.MS, 1, scanNumber)}"); } else { - Log.Error($"Failed finding precursor for {scanNumber}"); - ParseInput.NewError(); + Writer.WriteLine( + $"TITLE={ConstructSpectrumTitle((int)Device.MS, 1, scanNumber)} [PRECURSOR={precursorReference}]"); } - } - } - if (ParseInput.MsLevel.Contains(msLevel)) - { - var reaction = GetReaction(scanEvent, scanNumber); - - Writer.WriteLine("BEGIN IONS"); - if (!ParseInput.MgfPrecursor) - { - Writer.WriteLine($"TITLE={ConstructSpectrumTitle((int) Device.MS, 1, scanNumber)}"); - } - else - { + Writer.WriteLine($"SCANS={scanNumber}"); Writer.WriteLine( - $"TITLE={ConstructSpectrumTitle((int) Device.MS, 1, scanNumber)} [PRECURSOR={precursorReference}]"); - } - - Writer.WriteLine($"SCANS={scanNumber}"); - Writer.WriteLine( - $"RTINSECONDS={(retentionTime * 60).ToString(CultureInfo.InvariantCulture)}"); + $"RTINSECONDS={(retentionTime * 60).ToString(CultureInfo.InvariantCulture)}"); - int? charge = trailerData.AsPositiveInt("Charge State:"); - double? monoisotopicMz = trailerData.AsDouble("Monoisotopic M/Z:"); - double? isolationWidth = - trailerData.AsDouble("MS" + msLevel + " Isolation Width:"); + int? charge = trailerData.AsPositiveInt("Charge State:"); + double? monoisotopicMz = trailerData.AsDouble("Monoisotopic M/Z:"); + double? isolationWidth = + trailerData.AsDouble("MS" + msLevel + " Isolation Width:"); - if (reaction != null) - { - var selectedIonMz = - CalculateSelectedIonMz(reaction, monoisotopicMz, isolationWidth); + if (reaction != null) + { + var selectedIonMz = + CalculateSelectedIonMz(reaction, monoisotopicMz, isolationWidth); - Writer.WriteLine("PEPMASS=" + - selectedIonMz.ToString(CultureInfo.InvariantCulture)); - } + Writer.WriteLine("PEPMASS=" + + selectedIonMz.ToString(CultureInfo.InvariantCulture)); + } - // Charge - if (charge != null) - { - // Scan polarity - var polarity = PositivePolarity; - if (scanFilter.Polarity == PolarityType.Negative) + // Charge + if (charge != null) { - polarity = NegativePolarity; - } + // Scan polarity + var polarity = PositivePolarity; + if (scanFilter.Polarity == PolarityType.Negative) + { + polarity = NegativePolarity; + } - Writer.WriteLine($"CHARGE={charge}{polarity}"); - } + Writer.WriteLine($"CHARGE={charge}{polarity}"); + } - // Write the filter string - //Writer.WriteLine($"SCANEVENT={scanEvent.ToString()}"); + // Write the filter string + //Writer.WriteLine($"SCANEVENT={scanEvent.ToString()}"); - double[] masses; - double[] intensities; + double[] masses; + double[] intensities; - if (!ParseInput.NoPeakPicking.Contains(msLevel)) - { - // Check if the scan has a centroid stream - if (scan.HasCentroidStream) + if (!ParseInput.NoPeakPicking.Contains(msLevel)) { - masses = scan.CentroidScan.Masses; - intensities = scan.CentroidScan.Intensities; + // Check if the scan has a centroid stream + if (scan.HasCentroidStream) + { + masses = scan.CentroidScan.Masses; + intensities = scan.CentroidScan.Intensities; + } + else // Otherwise take segmented (low res) scan data + { + // If the spectrum is profile perform centroiding + var segmentedScan = scanEvent.ScanData == ScanDataType.Profile + ? Scan.ToCentroid(scan).SegmentedScan + : scan.SegmentedScan; + + masses = segmentedScan.Positions; + intensities = segmentedScan.Intensities; + } } - else // Otherwise take segmented (low res) scan data + else // Use the segmented data as is { - // If the spectrum is profile perform centroiding - var segmentedScan = scanEvent.ScanData == ScanDataType.Profile - ? Scan.ToCentroid(scan).SegmentedScan - : scan.SegmentedScan; - - masses = segmentedScan.Positions; - intensities = segmentedScan.Intensities; + masses = scan.SegmentedScan.Positions; + intensities = scan.SegmentedScan.Intensities; } - } - else // Use the segmented data as is - { - masses = scan.SegmentedScan.Positions; - intensities = scan.SegmentedScan.Intensities; - } - - if (!(masses is null) && masses.Length > 0) - { - Array.Sort(masses, intensities); - for (var i = 0; i < masses.Length; i++) + if (!(masses is null) && masses.Length > 0) { - Writer.WriteLine(String.Format("{0:f5} {1:f3}", masses[i], intensities[i])); + Array.Sort(masses, intensities); + + for (var i = 0; i < masses.Length; i++) + { + Writer.WriteLine(String.Format("{0:f5} {1:f3}", masses[i], intensities[i])); + } } - } - Writer.WriteLine("END IONS"); + Writer.WriteLine("END IONS"); - Log.Debug("Spectrum written to file -- SCAN# " + scanNumber); + Log.Debug("Spectrum written to file -- SCAN# " + scanNumber); + } } } diff --git a/Writer/MzMlSpectrumWriter.cs b/Writer/MzMlSpectrumWriter.cs index cae5dce..81071d1 100644 --- a/Writer/MzMlSpectrumWriter.cs +++ b/Writer/MzMlSpectrumWriter.cs @@ -83,7 +83,7 @@ public override void Write(IRawDataPlus rawFile, int firstScanNumber, int lastSc ConfigureWriter(".mzML"); XmlSerializer serializer; - var settings = new XmlWriterSettings {Indent = true, Encoding = new UTF8Encoding()}; + var settings = new XmlWriterSettings { Indent = true, Encoding = new UTF8Encoding() }; var sha1 = SHA1.Create(); CryptoStream cryptoStream = null; if (_doIndexing) @@ -143,29 +143,32 @@ public override void Write(IRawDataPlus rawFile, int firstScanNumber, int lastSc // fileContent _writer.WriteStartElement("fileContent"); // MS1 - SerializeCvParam(new CVParamType - { - accession = "MS:1000579", - name = "MS1 spectrum", - cvRef = "MS", - value = "" - }); - // MSn - SerializeCvParam(new CVParamType + if (rawFile.SelectMsData()) { - accession = "MS:1000580", - name = "MSn spectrum", - cvRef = "MS", - value = "" - }); - // Ion current chromatogram - SerializeCvParam(new CVParamType - { - accession = "MS:1000810", - name = "ion current chromatogram", - cvRef = "MS", - value = "" - }); + SerializeCvParam(new CVParamType + { + accession = "MS:1000579", + name = "MS1 spectrum", + cvRef = "MS", + value = "" + }); + // MSn + SerializeCvParam(new CVParamType + { + accession = "MS:1000580", + name = "MSn spectrum", + cvRef = "MS", + value = "" + }); + // Ion current chromatogram + SerializeCvParam(new CVParamType + { + accession = "MS:1000810", + name = "ion current chromatogram", + cvRef = "MS", + value = "" + }); + } // Other detector data if (ParseInput.AllDetectors) @@ -194,6 +197,25 @@ public override void Write(IRawDataPlus rawFile, int firstScanNumber, int lastSc value = "" }); } + + // Pressure chromatogram + if (_rawFile.GetInstrumentCountOfType(Device.Analog) > 0) + { + SerializeCvParam(new CVParamType + { + accession = "MS:1003019", + name = "pressure chromatogram", + cvRef = "MS", + value = "" + }); + } + + // MSAnalog chromatogram + if (_rawFile.GetInstrumentCountOfType(Device.MSAnalog) > 0) + { + // TODO Write MSAnalog fileContent + // e.g. Front FID or Back FID + } } _writer.WriteEndElement(); // fileContent @@ -231,27 +253,32 @@ public override void Write(IRawDataPlus rawFile, int firstScanNumber, int lastSc _writer.WriteEndElement(); // sourceFileList _writer.WriteEndElement(); // fileDescription - var instrumentData = _rawFile.GetInstrumentData(); + if (_rawFile.SelectedInstrument.DeviceType != Device.None && _rawFile.SelectedInstrument.InstrumentIndex != -1) + { + var instrumentData = _rawFile.GetInstrumentData(); - // ReferenceableParamGroupList - _writer.WriteStartElement("referenceableParamGroupList"); - _writer.WriteAttributeString("count", "1"); - // ReferenceableParamGroup - _writer.WriteStartElement("referenceableParamGroup"); - _writer.WriteAttributeString("id", "commonInstrumentParams"); + // ReferenceableParamGroupList + _writer.WriteStartElement("referenceableParamGroupList"); + _writer.WriteAttributeString("count", "1"); + // ReferenceableParamGroup + _writer.WriteStartElement("referenceableParamGroup"); + _writer.WriteAttributeString("id", "commonInstrumentParams"); - var instrumentModel = OntologyMapping.getInstrumentModel(instrumentData.Name); - SerializeCvParam(instrumentModel); + var instrumentModel = OntologyMapping.getInstrumentModel(instrumentData.Name); + SerializeCvParam(instrumentModel); - SerializeCvParam(new CVParamType - { - cvRef = "MS", - accession = "MS:1000529", - name = "instrument serial number", - value = instrumentData.SerialNumber - }); - _writer.WriteEndElement(); // referenceableParamGroup - _writer.WriteEndElement(); // referenceableParamGroupList + SerializeCvParam(new CVParamType + { + cvRef = "MS", + accession = "MS:1000529", + name = "instrument serial number", + value = instrumentData.SerialNumber + }); + _writer.WriteEndElement(); // referenceableParamGroup + _writer.WriteEndElement(); // referenceableParamGroupList + + PopulateInstrumentConfigurationList(firstScanNumber, lastScanNumber, instrumentModel); + } // SoftwareList _writer.WriteStartElement("softwareList"); @@ -269,7 +296,6 @@ public override void Write(IRawDataPlus rawFile, int firstScanNumber, int lastSc _writer.WriteEndElement(); // software _writer.WriteEndElement(); // softwareList - PopulateInstrumentConfigurationList(firstScanNumber, lastScanNumber, instrumentModel); // DataProcessingList _writer.WriteStartElement("dataProcessingList"); @@ -326,64 +352,68 @@ public override void Write(IRawDataPlus rawFile, int firstScanNumber, int lastSc var index = 0; var lastScanProgress = 0; - Log.Info(String.Format("Processing {0} MS scans", +(1 + lastScanNumber - firstScanNumber))); - - for (var scanNumber = firstScanNumber; scanNumber <= lastScanNumber; scanNumber++) + if (_rawFile.SelectMsData()) { - if (ParseInput.LogFormat == LogFormat.DEFAULT) + Log.Info(String.Format("Processing {0} MS scans", +(1 + lastScanNumber - firstScanNumber))); + + for (var scanNumber = firstScanNumber; scanNumber <= lastScanNumber; scanNumber++) { - var scanProgress = (int) ((double) scanNumber / (lastScanNumber - firstScanNumber + 1) * 100); - if (scanProgress % ProgressPercentageStep == 0) + if (ParseInput.LogFormat == LogFormat.DEFAULT) { - if (scanProgress != lastScanProgress) + var scanProgress = (int)((double)scanNumber / (lastScanNumber - firstScanNumber + 1) * 100); + if (scanProgress % ProgressPercentageStep == 0) { - Console.Write("" + scanProgress + "% "); - lastScanProgress = scanProgress; + if (scanProgress != lastScanProgress) + { + Console.Write("" + scanProgress + "% "); + lastScanProgress = scanProgress; + } } } - } - SpectrumType spectrum = null; + SpectrumType spectrum = null; - try - { - spectrum = ConstructMSSpectrum(scanNumber); - } - catch (Exception ex) - { - Log.Error($"Scan #{scanNumber} cannot be processed because of the following exception: {ex.Message}\n{ex.StackTrace}"); - ParseInput.NewError(); - } + try + { + spectrum = ConstructMSSpectrum(scanNumber); + } + catch (Exception ex) + { + Log.Error($"Scan #{scanNumber} cannot be processed because of the following exception: {ex.Message}\n{ex.StackTrace}"); + ParseInput.NewError(); + } - var level = spectrum != null ? int.Parse(spectrum.cvParam.Where(p => p.accession == "MS:1000511").First().value) : 0; - - if (spectrum != null && ParseInput.MsLevel.Contains(level)) //applying MS level filter - { - spectrum.index = index.ToString(); - if (_doIndexing) + var level = spectrum != null ? int.Parse(spectrum.cvParam.Where(p => p.accession == "MS:1000511").First().value) : 0; + + if (spectrum != null && ParseInput.MsLevel.Contains(level)) //applying MS level filter { - // flush the writers before getting the position - _writer.Flush(); - Writer.Flush(); - if (spectrumOffSets.Count != 0) - { - spectrumOffSets.Add(spectrum.id, Writer.BaseStream.Position + 6 + _osOffset); - } - else + spectrum.index = index.ToString(); + if (_doIndexing) { - spectrumOffSets.Add(spectrum.id, Writer.BaseStream.Position + 7 + _osOffset); + // flush the writers before getting the position + _writer.Flush(); + Writer.Flush(); + if (spectrumOffSets.Count != 0) + { + spectrumOffSets.Add(spectrum.id, Writer.BaseStream.Position + 6 + _osOffset); + } + else + { + spectrumOffSets.Add(spectrum.id, Writer.BaseStream.Position + 7 + _osOffset); + } } - } - Serialize(serializer, spectrum); + Serialize(serializer, spectrum); - Log.Debug("Spectrum added to list of spectra -- ID " + spectrum.id); + Log.Debug("Spectrum added to list of spectra -- ID " + spectrum.id); - index++; + index++; + } } } + if (ParseInput.LogFormat == LogFormat.DEFAULT) { Console.WriteLine(); @@ -407,7 +437,7 @@ public override void Write(IRawDataPlus rawFile, int firstScanNumber, int lastSc if (ParseInput.LogFormat == LogFormat.DEFAULT) { var scanProgress = - (int) ((double) scanNumber / (lastScanNumber - firstScanNumber + 1) * 100); + (int)((double)scanNumber / (lastScanNumber - firstScanNumber + 1) * 100); if (scanProgress % ProgressPercentageStep == 0) { if (scanProgress != lastScanProgress) @@ -466,7 +496,7 @@ public override void Write(IRawDataPlus rawFile, int firstScanNumber, int lastSc _writer.WriteEndElement(); // spectrumList index = 0; - var chromatograms = ConstructChromatograms(firstScanNumber, lastScanNumber); + var chromatograms = ConstructChromatograms(); if (!chromatograms.IsNullOrEmpty()) { // ChromatogramList @@ -634,20 +664,21 @@ private string GetTotalScanNumber() var lastSelectedInstrument = _rawFile.SelectedInstrument; var numScans = 0; - _rawFile.SelectInstrument(Device.MS, 1); - - var levelFilter = _rawFile.GetFilterFromString(""); - - foreach (var level in ParseInput.MsLevel) + if (_rawFile.GetInstrumentCountOfType(Device.MS) != 0) { - levelFilter.MSOrder = (MSOrderType) level; + _rawFile.SelectInstrument(Device.MS, 1); + var levelFilter = _rawFile.GetFilterFromString(""); - var filteredScans = _rawFile.GetFilteredScansListByScanRange(levelFilter, - _rawFile.RunHeader.FirstSpectrum, _rawFile.RunHeader.LastSpectrum); + foreach (var level in ParseInput.MsLevel) + { + levelFilter.MSOrder = (MSOrderType)level; - numScans += filteredScans.Count; - } + var filteredScans = _rawFile.GetFilteredScansListByScanRange(levelFilter, + _rawFile.RunHeader.FirstSpectrum, _rawFile.RunHeader.LastSpectrum); + numScans += filteredScans.Count; + } + } if (ParseInput.AllDetectors) { @@ -659,7 +690,7 @@ private string GetTotalScanNumber() } // Return instrument to last selected one - if (lastSelectedInstrument != null) + if (lastSelectedInstrument != null && lastSelectedInstrument.DeviceType != Device.None && lastSelectedInstrument.InstrumentIndex != -1) _rawFile.SelectInstrument(lastSelectedInstrument.DeviceType, lastSelectedInstrument.InstrumentIndex); return numScans.ToString(); @@ -841,53 +872,57 @@ private void Serialize(XmlSerializer serializer, T t) /// the first scan number /// the last scan number /// a list of chromatograms - private List ConstructChromatograms(int firstScanNumber, int lastScanNumber) + private List ConstructChromatograms() { var chromatograms = new List(); // MS chromatograms // Reselect MS device - _rawFile.SelectInstrument(Device.MS, 1); - // Define the settings for getting the Base Peak chromatogram - var settings = new ChromatogramTraceSettings(TraceType.BasePeak); + if (_rawFile.GetInstrumentCountOfType(Device.MS) != 0) + { + _rawFile.SelectInstrument(Device.MS, 1); - // Get the chromatogram from the RAW file. - var data = _rawFile.GetChromatogramData(new IChromatogramSettings[] {settings}, -1, -1); + // Define the settings for getting the Base Peak chromatogram + var settings = new ChromatogramTraceSettings(TraceType.BasePeak); - // Split the data into the chromatograms - var trace = ChromatogramSignal.FromChromatogramData(data); + // Get the chromatogram from the RAW file. + var data = _rawFile.GetChromatogramData(new IChromatogramSettings[] { settings }, -1, -1); - for (var i = 0; i < trace.Length; i++) - { - if (trace[i].Length > 0) + // Split the data into the chromatograms + var trace = ChromatogramSignal.FromChromatogramData(data); + + for (var i = 0; i < trace.Length; i++) { - // CV Data for Base Peak Chromatogram - var chroType = new CVParamType + if (trace[i].Length > 0) { - accession = "MS:1000628", - name = "basepeak chromatogram", - cvRef = "MS", - value = "" - }; + // CV Data for Base Peak Chromatogram + var chroType = new CVParamType + { + accession = "MS:1000628", + name = "basepeak chromatogram", + cvRef = "MS", + value = "" + }; - var intensType = new CVParamType - { - accession = "MS:1000515", - name = "intensity array", - cvRef = "MS", - unitName = "number of counts", - value = "", - unitCvRef = "MS", - unitAccession = "MS:1000131" - }; + var intensType = new CVParamType + { + accession = "MS:1000515", + name = "intensity array", + cvRef = "MS", + unitName = "number of counts", + value = "", + unitCvRef = "MS", + unitAccession = "MS:1000131" + }; - var chromatogram = TraceToChromatogram(trace[i], "BasePeak_" + i.ToString(), chroType, intensType); + var chromatogram = TraceToChromatogram(trace[i], "BasePeak_" + i.ToString(), chroType, intensType); - chromatograms.Add(chromatogram); + chromatograms.Add(chromatogram); + } } } - // Chromatograms from other devices: UV, PDA + // Chromatograms from other devices: UV, PDA, Analog, MSAnalog if (ParseInput.AllDetectors) { for (int nrI = 1; nrI < _rawFile.GetInstrumentCountOfType(Device.Pda) + 1; nrI++) @@ -896,11 +931,11 @@ private List ConstructChromatograms(int firstScanNumber, int l var instData = _rawFile.GetInstrumentData(); - settings = new ChromatogramTraceSettings(TraceType.TotalAbsorbance); + var settings = new ChromatogramTraceSettings(TraceType.TotalAbsorbance); - data = _rawFile.GetChromatogramData(new IChromatogramSettings[] {settings}, -1, -1); + var data = _rawFile.GetChromatogramData(new IChromatogramSettings[] { settings }, -1, -1); - trace = ChromatogramSignal.FromChromatogramData(data); + var trace = ChromatogramSignal.FromChromatogramData(data); for (var i = 0; i < trace.Length; i++) { @@ -942,11 +977,11 @@ private List ConstructChromatograms(int firstScanNumber, int l { var channelName = instData.ChannelLabels[channel]; - settings = new ChromatogramTraceSettings(TraceType.StartUVChromatogramTraces + channel + 1); + var settings = new ChromatogramTraceSettings(TraceType.StartUVChromatogramTraces + channel + 1); - data = _rawFile.GetChromatogramData(new IChromatogramSettings[] {settings}, -1, -1); + var data = _rawFile.GetChromatogramData(new IChromatogramSettings[] { settings }, -1, -1); - trace = ChromatogramSignal.FromChromatogramData(data); + var trace = ChromatogramSignal.FromChromatogramData(data); for (var i = 0; i < trace.Length; i++) { @@ -991,16 +1026,16 @@ private List ConstructChromatograms(int firstScanNumber, int l if (channelName.ToLower().Contains("pressure")) { - settings = new ChromatogramTraceSettings(TraceType.StartPCA2DChromatogramTraces + channel + + var settings = new ChromatogramTraceSettings(TraceType.StartPCA2DChromatogramTraces + channel + 1); - data = _rawFile.GetChromatogramData(new IChromatogramSettings[] {settings}, -1, -1); + var data = _rawFile.GetChromatogramData(new IChromatogramSettings[] { settings }, -1, -1); - trace = ChromatogramSignal.FromChromatogramData(data); + var trace = ChromatogramSignal.FromChromatogramData(data); for (var i = 0; i < trace.Length; i++) { - // CV Data for Absorbance Chromatogram + // CV Data for Pressure Chromatogram var chroType = new CVParamType { accession = "MS:1003019", @@ -1029,6 +1064,67 @@ private List ConstructChromatograms(int firstScanNumber, int l } } } + + var channelNameIndex = 0; + for (int nrI = 1; nrI < _rawFile.GetInstrumentCountOfType(Device.MSAnalog) + 1; nrI++) + { + _rawFile.SelectInstrument(Device.MSAnalog, nrI); + + var instData = _rawFile.GetInstrumentData(); + + for (int channel = 0; channel < instData.ChannelLabels.Length; channel++) + { + var channelName = instData.ChannelLabels[channel]; + + if (channelName.IsNullOrEmpty()) + { + channelName = "Channel " + channelNameIndex++; + } + + var settings = new ChromatogramTraceSettings(TraceType.StartAnalogChromatogramTraces + channel + + 1); + + var data = _rawFile.GetChromatogramData(new IChromatogramSettings[] { settings }, -1, -1); + + var trace = ChromatogramSignal.FromChromatogramData(data); + + for (var i = 0; i < trace.Length; i++) + { + // CV Data for Chromatogram + var chroType = new CVParamType + { + name = channelName + " chromatogram", + value = "" + }; + + var intensType = new CVParamType(); + if (instData.Units.ToString().Equals("Volts")) + { + intensType = new CVParamType + { + name = channelName + " array", + unitAccession = "UO:0000218", + unitName = "volt", + unitCvRef = "UO" + }; + } + else + { + intensType = new CVParamType + { + name = channelName + " array", + value = instData.Units.ToString(), + }; + } + + var chromatogram = TraceToChromatogram(trace[i], + String.Format("MSAD#{0}_{1}_{2}", nrI, channelName.Replace(" ", "_"), i), + chroType, intensType); + + chromatograms.Add(chromatogram); + } + } + } } return chromatograms; @@ -1068,7 +1164,7 @@ private ChromatogramType TraceToChromatogram(ChromatogramSignal trace, string ch : GetZLib64BitArray(trace.Times) }; timesBinaryData.encodedLength = - (4 * Math.Ceiling((double) timesBinaryData + (4 * Math.Ceiling((double)timesBinaryData .binary.Length / 3)).ToString(CultureInfo.InvariantCulture); var timesBinaryDataCvParams = new List { @@ -1133,7 +1229,7 @@ private ChromatogramType TraceToChromatogram(ChromatogramSignal trace, string ch : GetZLib64BitArray(trace.Intensities) }; intensitiesBinaryData.encodedLength = - (4 * Math.Ceiling((double) intensitiesBinaryData + (4 * Math.Ceiling((double)intensitiesBinaryData .binary.Length / 3)).ToString(CultureInfo.InvariantCulture); var intensitiesBinaryDataCvParams = new List { @@ -1206,7 +1302,7 @@ private SpectrumType ConstructMSSpectrum(int scanNumber) var scanEvent = _rawFile.GetScanEventForScanNumber(scanNumber); var spectrum = new SpectrumType { - id = ConstructSpectrumTitle((int) Device.MS, 1, scanNumber), + id = ConstructSpectrumTitle((int)Device.MS, 1, scanNumber), defaultArrayLength = 0 }; @@ -1239,7 +1335,7 @@ private SpectrumType ConstructMSSpectrum(int scanNumber) int? charge = trailerData.AsPositiveInt("Charge State:"); double? monoisotopicMz = trailerData.AsDouble("Monoisotopic M/Z:"); double? ionInjectionTime = trailerData.AsDouble("Ion Injection Time (ms):"); - double? isolationWidth = trailerData.AsDouble("MS" + (int) scanFilter.MSOrder + " Isolation Width:"); + double? isolationWidth = trailerData.AsDouble("MS" + (int)scanFilter.MSOrder + " Isolation Width:"); double? FAIMSCV = null; if (trailerData.AsBool("FAIMS Voltage On:").GetValueOrDefault(false)) FAIMSCV = trailerData.AsDouble("FAIMS CV:"); @@ -1251,7 +1347,7 @@ private SpectrumType ConstructMSSpectrum(int scanNumber) foreach (var label in trailerData.MatchKeys(_spSentry)) { var mass = trailerData.AsDouble(label).GetValueOrDefault(0); - if (mass > 0) SPSMasses.Add((double) mass); //zero means mass does not exist + if (mass > 0) SPSMasses.Add((double)mass); //zero means mass does not exist } } @@ -1261,7 +1357,7 @@ private SpectrumType ConstructMSSpectrum(int scanNumber) foreach (var labelvalue in trailerData.MatchValues(_spSentry3)) { foreach (var mass in labelvalue.Trim() - .Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries)) + .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) { SPSMasses.Add(double.Parse(mass)); } @@ -1290,14 +1386,14 @@ private SpectrumType ConstructMSSpectrum(int scanNumber) } else if (msLevel > 1) - { + { spectrumCvParams.Add(new CVParamType - { - accession = "MS:1000580", - cvRef = "MS", - name = "MSn spectrum", - value = "" - }); + { + accession = "MS:1000580", + cvRef = "MS", + name = "MSn spectrum", + value = "" + }); // Keep track of scan number and isolation m/z for precursor reference var result = _filterStringIsolationMzPattern.Match(scanEvent.ToString()); @@ -1431,7 +1527,7 @@ private SpectrumType ConstructMSSpectrum(int scanNumber) double[] masses; double[] intensities; - if (!ParseInput.NoPeakPicking.Contains((int) scanFilter.MSOrder)) + if (!ParseInput.NoPeakPicking.Contains((int)scanFilter.MSOrder)) { //Spectrum will be centroided spectrumCvParams.Add(new CVParamType @@ -1594,7 +1690,7 @@ private SpectrumType ConstructMSSpectrum(int scanNumber) binary = ParseInput.NoZlibCompression ? Get64BitArray(masses) : GetZLib64BitArray(masses) }; massesBinaryData.encodedLength = - (4 * Math.Ceiling((double) massesBinaryData + (4 * Math.Ceiling((double)massesBinaryData .binary.Length / 3)).ToString(CultureInfo.InvariantCulture); var massesBinaryDataCvParams = new List { @@ -1656,7 +1752,7 @@ private SpectrumType ConstructMSSpectrum(int scanNumber) : GetZLib64BitArray(intensities) }; intensitiesBinaryData.encodedLength = - (4 * Math.Ceiling((double) intensitiesBinaryData + (4 * Math.Ceiling((double)intensitiesBinaryData .binary.Length / 3)).ToString(CultureInfo.InvariantCulture); var intensitiesBinaryDataCvParams = new List { @@ -1938,7 +2034,7 @@ private SpectrumType ConstructPDASpectrum(int scanNumber, int instrumentNumber) var spectrum = new SpectrumType { - id = ConstructSpectrumTitle((int) Device.Pda, instrumentNumber, scanNumber), + id = ConstructSpectrumTitle((int)Device.Pda, instrumentNumber, scanNumber), defaultArrayLength = 0 }; @@ -2057,7 +2153,7 @@ private SpectrumType ConstructPDASpectrum(int scanNumber, int instrumentNumber) binary = ParseInput.NoZlibCompression ? Get64BitArray(positions) : GetZLib64BitArray(positions) }; positionsBinaryData.encodedLength = - (4 * Math.Ceiling((double) positionsBinaryData + (4 * Math.Ceiling((double)positionsBinaryData .binary.Length / 3)).ToString(CultureInfo.InvariantCulture); var positionsBinaryDataCvParams = new List { @@ -2118,7 +2214,7 @@ private SpectrumType ConstructPDASpectrum(int scanNumber, int instrumentNumber) : GetZLib64BitArray(intensities) }; intensitiesBinaryData.encodedLength = - (4 * Math.Ceiling((double) intensitiesBinaryData + (4 * Math.Ceiling((double)intensitiesBinaryData .binary.Length / 3)).ToString(CultureInfo.InvariantCulture); var intensitiesBinaryDataCvParams = new List { @@ -2215,7 +2311,7 @@ private PrecursorListType ConstructPrecursorList(int precursorScanNumber, IScanE var precursor = new PrecursorType { selectedIonList = - new SelectedIonListType {count = "1", selectedIon = new ParamGroupType[1]}, + new SelectedIonListType { count = "1", selectedIon = new ParamGroupType[1] }, spectrumRef = spectrumRef }; @@ -2425,7 +2521,7 @@ private PrecursorListType ConstructPrecursorList(int precursorScanNumber, IScanE var SPSPrecursor = new PrecursorType { selectedIonList = - new SelectedIonListType {count = "1", selectedIon = new ParamGroupType[1]}, + new SelectedIonListType { count = "1", selectedIon = new ParamGroupType[1] }, spectrumRef = spectrumRef }; @@ -2778,7 +2874,7 @@ private static byte[] Get64BitArray(ICollection array) memoryStream.Position = 0; bytes = memoryStream.ToArray(); } - } + } return (byte[])bytes; } @@ -2798,8 +2894,8 @@ private static byte[] GetZLib64BitArray(ICollection array) using (var memoryStream = new MemoryStream()) using (var outZStream = new ZOutputStream(memoryStream, zlibConst.Z_DEFAULT_COMPRESSION)) { - outZStream.Write(bytes, 0, bytes.Length); - + outZStream.Write(bytes, 0, bytes.Length); + outZStream.finish(); memoryStream.Position = 0; bytes = memoryStream.ToArray(); diff --git a/Writer/ParquetSpectrumWriter.cs b/Writer/ParquetSpectrumWriter.cs index ced94be..f2ad5c1 100644 --- a/Writer/ParquetSpectrumWriter.cs +++ b/Writer/ParquetSpectrumWriter.cs @@ -43,64 +43,68 @@ private static void WritePScans(string outputDirectory, string fileName, IRawDataPlus raw, List scans) { - var enumerator = raw.GetFilteredScanEnumerator(" "); - - foreach (var scanNumber in enumerator - ) // note in my tests serial is faster than Parallel.Foreach() (this involves disk access, so it makes sense) + if (raw.SelectMsData()) { - //trailer information is extracted via index - var trailers = raw.GetTrailerExtraValues(scanNumber); - var trailerLabels = raw.GetTrailerExtraInformation(scanNumber); - object chargeState = 0; - for (int i = 0; i < trailerLabels.Labels.Length; i++) + var enumerator = raw.GetFilteredScanEnumerator(" "); + + foreach (var scanNumber in enumerator + ) // note in my tests serial is faster than Parallel.Foreach() (this involves disk access, so it makes sense) { - if (trailerLabels.Labels[i] == "Charge State:") + //trailer information is extracted via index + var trailers = raw.GetTrailerExtraValues(scanNumber); + var trailerLabels = raw.GetTrailerExtraInformation(scanNumber); + object chargeState = 0; + for (int i = 0; i < trailerLabels.Labels.Length; i++) { - chargeState = raw.GetTrailerExtraValue(scanNumber, i); - break; + if (trailerLabels.Labels[i] == "Charge State:") + { + chargeState = raw.GetTrailerExtraValue(scanNumber, i); + break; + } } - } - var scanFilter = raw.GetFilterForScanNumber(scanNumber); - var scanStats = raw.GetScanStatsForScanNumber(scanNumber); + var scanFilter = raw.GetFilterForScanNumber(scanNumber); + var scanStats = raw.GetScanStatsForScanNumber(scanNumber); - CentroidStream centroidStream = new CentroidStream(); + CentroidStream centroidStream = new CentroidStream(); - //check for FT mass analyzer data - if (scanFilter.MassAnalyzer == MassAnalyzerType.MassAnalyzerFTMS) - { - centroidStream = raw.GetCentroidStream(scanNumber, false); - } + //check for FT mass analyzer data + if (scanFilter.MassAnalyzer == MassAnalyzerType.MassAnalyzerFTMS) + { + centroidStream = raw.GetCentroidStream(scanNumber, false); + } - //check for IT mass analyzer data - if (scanFilter.MassAnalyzer == MassAnalyzerType.MassAnalyzerITMS) - { - var scanData = raw.GetSimplifiedScan(scanNumber); - centroidStream.Masses = scanData.Masses; - centroidStream.Intensities = scanData.Intensities; - } + //check for IT mass analyzer data + if (scanFilter.MassAnalyzer == MassAnalyzerType.MassAnalyzerITMS) + { + var scanData = raw.GetSimplifiedScan(scanNumber); + centroidStream.Masses = scanData.Masses; + centroidStream.Intensities = scanData.Intensities; + } - var msOrder = raw.GetScanEventForScanNumber(scanNumber).MSOrder; + var msOrder = raw.GetScanEventForScanNumber(scanNumber).MSOrder; - if (msOrder == MSOrderType.Ms) - { - var pscan = GetPScan(scanStats, centroidStream, fileName, Convert.ToInt32(chargeState)); - scans.Add(pscan); - } + if (msOrder == MSOrderType.Ms) + { + var pscan = GetPScan(scanStats, centroidStream, fileName, Convert.ToInt32(chargeState)); + scans.Add(pscan); + } - if (msOrder == MSOrderType.Ms2) - { - var precursorMz = raw.GetScanEventForScanNumber(scanNumber).GetReaction(0).PrecursorMass; - var pscan = GetPScan(scanStats, centroidStream, fileName, precursorMz, - Convert.ToInt32(chargeState)); - scans.Add(pscan); + if (msOrder == MSOrderType.Ms2) + { + var precursorMz = raw.GetScanEventForScanNumber(scanNumber).GetReaction(0).PrecursorMass; + var pscan = GetPScan(scanStats, centroidStream, fileName, precursorMz, + Convert.ToInt32(chargeState)); + scans.Add(pscan); + } + + var t = raw.GetTrailerExtraValues(scanNumber); } - var t = raw.GetTrailerExtraValues(scanNumber); + WriteScans(outputDirectory, scans, fileName); } - - WriteScans(outputDirectory, scans, fileName); } + private static PScan GetPScan(ScanStatistics scanStats, CentroidStream centroidStream, string fileName, double? precursorMz = null, int? precursorCharge = null)