public static void WriteToMSM(StreamWriter writer, MassSpectrum spec, String parentFileName, int mzDecimalPlace, int intensityDecimalPlace, bool showPeakChargeState, bool showPeakResolution) { writer.Write("BEGIN IONS\n"); writer.Write("PEPMASS=" + Math.Round(spec.Precursors[0].Item1, mzDecimalPlace) + "\n"); writer.Write("CHARGE=" + spec.Precursors[0].Item2); if (spec.Precursors[0].Item2 >= 0) { writer.Write("+\n"); } writer.Write("TITLE=" + parentFileName + " from: " + (spec.RetentionTime * 60) + " to " + (spec.RetentionTime * 60) + " period:" + parentFileName + " experiment: 1 cycles: 1" + " precIntensity: "); if (!double.IsNaN(spec.PrecursorIntensity)) { writer.Write(Math.Round(spec.PrecursorIntensity, intensityDecimalPlace)); } else { writer.Write("no"); } writer.Write(" FinneganScanNumber: " + spec.ScanNumber + "\n"); // write peaks; foreach (Ion peak in spec.Peaks) { writer.Write(Math.Round(peak.MZ, mzDecimalPlace) + " " + Math.Round(peak.Intensity, intensityDecimalPlace) + "\n"); } writer.Write("END IONS\n\n"); writer.Flush(); }
private bool SqlTrySelect(string spectrumID, out MassSpectrum ms) { SQLiteCommand cmd; if (!currentScope.TryGetCommand("SELECT_SPECTRUM_CMD", out cmd)) { cmd = currentScope.PrepareCommand("SELECT_SPECTRUM_CMD", "SELECT Description FROM Spectrum WHERE SpectrumID = @spectrumID"); } else { cmd.Parameters.Clear(); } cmd.Parameters.AddWithValue("@spectrumID", spectrumID); string desc = cmd.ExecuteScalar() as string; if (desc != null) { ms = MzLiteJson.FromJson <MassSpectrum>(desc); return(true); } else { ms = null; return(false); } }
public static void WriteToMS1(StreamWriter writer, MassSpectrum spec, int mzDecimalPlace, int intensityDecimalPlace, bool showPeakChargeState, bool showPeakResolution) { writer.Write("S\t" + String.Format("{0:000000}", spec.ScanNumber) + "\t" + String.Format("{0:000000}", spec.ScanNumber) + "\n" + "I\tRetTime\t" + spec.RetentionTime + "\n" + "I\tIonInjectionTime\t" + spec.IonInjectionTime + "\n" + "I\tInstrumentType\t" + spec.InstrumentType + "\n" ); foreach (Ion peak in spec.Peaks) { writer.Write(Math.Round(peak.MZ, mzDecimalPlace) + " " + Math.Round(peak.Intensity, intensityDecimalPlace)); if (showPeakChargeState && spec.InstrumentType == InstrumentType.FTMS) { writer.Write(" " + peak.Charge); } if (showPeakResolution && spec.InstrumentType == InstrumentType.FTMS) { writer.Write(" " + Math.Round(peak.Resolution, 2)); } writer.Write("\n"); } writer.Flush(); }
private static bool TryCreateEntry( MassSpectrum ms, int msLevel, out RtIndexEntry entry) { entry = default(RtIndexEntry); int _msLevel; if (!ms.TryGetMsLevel(out _msLevel) || _msLevel != msLevel) { return(false); } if (ms.Scans.Count < 1) { return(false); } double rt; Scan scan = ms.Scans[0]; if (scan.TryGetScanStartTime(out rt)) { entry = new RtIndexEntry(rt, ms.ID); return(true); } else { return(false); } }
/** * write to MSn file with duplicates. */ public static void WriteToMSnWithDuplicates(StreamWriter writer, MassSpectrum spec, int mzDecimalPlace, int intensityDecimalPlace, bool showPeakChargeState, bool showPeakResolution) { if (spec.Precursors == null || spec.Precursors.Count == 0) { return; } foreach (Tuple <double, int> prec in spec.Precursors) { double precMH = (prec.Item1 - Utils.PROTON_MASS) * prec.Item2 + Utils.PROTON_MASS; writer.Write("S\t" + String.Format("{0:000000}", spec.ScanNumber) + "\t" + String.Format("{0:000000}", spec.ScanNumber) + "\t" + Math.Round(prec.Item1, mzDecimalPlace + 1) + "\n" + "I\tRetTime\t" + Math.Round(spec.RetentionTime, 2) + "\n" + "I\tIonInjectionTime\t" + spec.IonInjectionTime + "\n" + "I\tActivationType\t" + spec.ActivationMethod + "\n" + "I\tInstrumentType\t" + spec.InstrumentType + "\n" + "I\tTemperatureFTAnalyzer\t" + spec.TemperatureFTAnalyzer + "\n" + "I\tFilter\t" + spec.Filter + "\n" + "I\tPrecursorScan\t" + spec.PrecursorScanNumber + "\n" + "I\tPrecursorInt\t" ); if (!double.IsNaN(spec.PrecursorIntensity)) { writer.Write(Math.Round(spec.PrecursorIntensity, intensityDecimalPlace) + "\n"); } else { writer.Write("\n"); } // if precursor(s) is/are corrected or prediected, write the corrected/predicted m/z's and charge states; if (spec.PrecursorRefined) { writer.Write("I\tPredicted Precursor: " + Math.Round(prec.Item1, mzDecimalPlace + 1) + " x " + prec.Item2 + "\n"); } writer.Write("Z\t" + prec.Item2 + "\t" + Math.Round(precMH, mzDecimalPlace + 1) + "\n"); foreach (Ion peak in spec.Peaks) { writer.Write(Math.Round(peak.MZ, mzDecimalPlace) + " " + Math.Round(peak.Intensity, intensityDecimalPlace)); if (showPeakChargeState && spec.ActivationMethod == Activation.HCD) { writer.Write(" " + peak.Charge); } if (showPeakResolution && spec.ActivationMethod == Activation.HCD) { writer.Write(" " + Math.Round(peak.Resolution, 2)); } writer.Write("\n"); } writer.Flush(); } }
private void WriteToOutFiles(MassSpectrum spec) { // MGF file; if (_mgfWriter != null) { TextFileWriter.WriteToMGF(_mgfWriter, spec, _ms2File, _mzDecimalPlace, _intensityDecimalPlace, false, false); } }
public static void SerializeSpecByScanNum(MassSpectrum spec, string tempFileFolder) { string tempFileName = tempFileFolder + "\\" + spec.ScanNumber + ".msd"; Stream stream = File.Open(tempFileName, FileMode.Create); var serializer = new BinaryFormatter(); serializer.Serialize(stream, spec); stream.Close(); }
/// <summary> /// Stages of ms achieved in a multi stage mass spectrometry experiment. [PSI:MS] /// </summary> public static MassSpectrum SetMsLevel( this MassSpectrum ms, int level) { if (level < 1) { throw new ArgumentOutOfRangeException("level"); } return(ms.SetCvParam(MsLevel, level).NoUnit()); }
private void WriteToOutFiles(MassSpectrum spec) { // MS1 file; if (_ms1Writer != null && spec.MsLevel == 1) { if (_isFirstMS1Scan) { TextFileWriter.WriteMSnHeader(_ms1Writer, "MS1", LastScanNum, spec); _isFirstMS1Scan = false; } TextFileWriter.WriteToMS1(_ms1Writer, spec, mzDecimalPlace, intensityDecimalPlace, showPeakChargeState, showPeakResolution); } // MS2 file; if (_ms2Writer != null && spec.MsLevel == 2) { if (_isFirstMS2Scan) { TextFileWriter.WriteMSnHeader(_ms2Writer, "MS2", LastScanNum, spec); _isFirstMS2Scan = false; } //TextFileWriter.WriteToMSn(_ms2Writer, spec, mzDecimalPlace, intensityDecimalPlace, showPeakChargeState, showPeakResolution,_verifyWriter); if (expType == ExperimentType.DIA && predictPrecursors) { TextFileWriter.WriteToMSnWithDuplicates(_ms2Writer, spec, mzDecimalPlace, intensityDecimalPlace, showPeakChargeState, showPeakResolution); } else { TextFileWriter.WriteToMSn(_ms2Writer, spec, mzDecimalPlace, intensityDecimalPlace, showPeakChargeState, showPeakResolution); } } // MS3 file; if (_ms3Writer != null && spec.MsLevel == 3) { if (_isFirstMS3Scan) { TextFileWriter.WriteMSnHeader(_ms3Writer, "MS3", LastScanNum, spec); _isFirstMS3Scan = false; } TextFileWriter.WriteToMSn(_ms3Writer, spec, mzDecimalPlace, intensityDecimalPlace, showPeakChargeState, showPeakResolution); } // MGF file; if (_mgfWriter != null && spec.MsLevel == 2) { TextFileWriter.WriteToMGF(_mgfWriter, spec, rawFileName, mzDecimalPlace, intensityDecimalPlace, showPeakChargeState, showPeakResolution); } // mzXML file; if (_mzXMLWriter != null) { _mzXMLWriter.WriteScan(spec); } }
//Perdicted monoisotopic with 3 MS1 private MassSpectrum CalCorrectPrecursor(MassSpectrum currentMS2, MassSpectrum currentMS1Spec) { if (currentMS1Spec == null || currentMS2 == null) { return(currentMS2); } List <MassSpectrum> currentMS1 = new List <MassSpectrum>(); //Add current MS1 currentMS1.Add(currentMS1Spec); CurrentIndexInMS1 = MS1ScanNum.IndexOf(currentMS1Spec.ScanNumber); //Add current MS1 - 1 if (CurrentIndexInMS1 - 1 > 0) { MassSpectrum MS1spec = GetSpectrumByScanNum(MS1ScanNum[CurrentIndexInMS1 - 1]); currentMS1.Add(MS1spec); } //Add current MS1 + 1 if (CurrentIndexInMS1 + 1 < MS1ScanNum.Count) { MassSpectrum MS1spec = GetSpectrumByScanNum(MS1ScanNum[CurrentIndexInMS1 + 1]); currentMS1.Add(MS1spec); } ////Add current MS1 - 2 //if (CurrentIndexInMS1 - 2 > 0) //{ // MassSpectrum MS1spec = GetSpectrumByScanNum(MS1ScanNum[CurrentIndexInMS1 - 2]); // currentMS1.Add(MS1spec); //} ////Add current MS1 + 2 //if (CurrentIndexInMS1 + 2 < MS1ScanNum.Count) //{ // MassSpectrum MS1spec = GetSpectrumByScanNum(MS1ScanNum[CurrentIndexInMS1 + 2]); // currentMS1.Add(MS1spec); //} PrecursorCorrector pc = new PrecursorCorrector(); // set the precursor scan number for current spectrum; currentMS2.PrecursorScanNumber = currentMS1Spec.ScanNumber; // get the precursor m/z from the scan filter; double precMz = currentMS2.Precursors.Count == 0 ? 0 : currentMS2.Precursors[0].Item1; int precZ = currentMS2.Precursors.Count == 0 ? 0 : currentMS2.Precursors[0].Item2; pc.CorrectPrecursor(ref currentMS2, precMz, precZ, currentMS1Spec.ScanNumber, currentMS1); return(currentMS2); }
public static MassSpectrum GetSpecByScanNum(int scanNum, string tempFileFolder) { string tempFileName = tempFileFolder + "\\" + scanNum + ".msd"; Stream stream = File.Open(tempFileName, FileMode.Open, FileAccess.Read, FileShare.Read); var serializer = new BinaryFormatter(); MassSpectrum spec = (MassSpectrum)serializer.Deserialize(stream); stream.Close(); return(spec); }
public void TransformMzs(Func <IMzPeak, double> convertorForSpectrum, Func <IMzPeak, double> convertorForPrecursor) { MassSpectrum.ReplaceXbyApplyingFunction(convertorForSpectrum); this.SelectedIonMZ = convertorForPrecursor(new MzPeak(SelectedIonMZ, SelectedIonIntensity.Value)); if (SelectedIonMonoisotopicGuessMz.HasValue) { this.SelectedIonMonoisotopicGuessMz = convertorForPrecursor(new MzPeak(SelectedIonMonoisotopicGuessMz.Value, SelectedIonMonoisotopicGuessIntensity.Value)); } this.IsolationMz = convertorForPrecursor(new MzPeak(IsolationMz, SelectedIonIntensity.Value)); // Will need to recompute this... isolationRange = null; }
private void WriteToOutFile(MassSpectrum spec) { // MS2 file; if (_ms2Writer != null) { WriteToMSn(_ms2Writer, spec); } // MS3 file; if (_ms3Writer != null) { WriteToMSn(_ms3Writer, spec); } }
public void Insert(string runID, MassSpectrum spectrum, Peak1DArray peaks) { RaiseDisposed(); RaiseNotInScope(); try { SqlInsert(runID, spectrum, peaks); } catch (Exception ex) { throw new MzLiteIOException(ex.Message, ex); } }
public long WriteScan(MassSpectrum spec) { // record the start position for later using of index; long startPos = _writer.Position + 1; _scanIdxList.Add(new Tuple <int, long>(spec.ScanNumber, startPos)); _writer.Write("\t<scan num=\"" + spec.ScanNumber + "\""); _writer.Write(" msLevel=\"" + spec.MsLevel + "\""); _writer.Write(" peaksCount=\"" + spec.Peaks.Count + "\""); if (spec.Filter.Contains("+")) { _writer.Write(" polarity=\"+\""); } else if (spec.Filter.Contains("-")) { _writer.Write(" polarity=\"-\""); } _writer.Write(" scanType=\"" + spec.ActivationMethod + "\""); _writer.Write(" filterLine=\"" + spec.Filter + "\""); _writer.Write(" retentionTime=\"PT" + spec.RetentionTime * 60 + "S\""); _writer.Write(" lowMz=\"" + (spec.Peaks.Count > 0 ? spec.Peaks.First().MZ : spec.LowMz) + "\""); _writer.Write(" highMz=\"" + (spec.Peaks.Count > 0 ? spec.Peaks.Last().MZ : spec.HighMz) + "\""); _writer.Write(" basePeakMz=\"" + spec.BasePeakMz + "\""); _writer.Write(" basePeakIntensity=\"" + spec.BasePeakIntensity + "\""); _writer.Write(" totIonCurrent=\"" + spec.TotIonCurrent + "\">\n"); if (spec.MsLevel > 1) { _writer.Write("\t\t<precursorMz precursorScanNum=\"" + spec.PrecursorScanNumber + "\""); _writer.Write(" precursorIntensity=\"" + spec.PrecursorIntensity + "\""); _writer.Write(" activationMethod=\"" + spec.ActivationMethod + "\""); _writer.Write(" precursorCharge=\"" + spec.Precursors[0].Item2 + "\">"); _writer.Write(spec.Precursors[0].Item1 + "</precursorMz>\n"); //foreach (Tuple<double, int> prec in spec.Precursors) //{ // _writer.Write(" precursorMz =\"" + prec.Item2 + "\">" + prec.Item1 + "</precursorMz>\n"); //} } _writer.Write("\t\t<peaks precision=\"32\" byteOrder=\"network\" pairOrder=\"m/z-int\">"); String strBase64 = ConvertPeaksToBase64(spec.Peaks, 32); _writer.Write(strBase64); _writer.Write("</peaks>\n\t</scan>\n"); _writer.Flush(); return(startPos); }
/// <summary> /// Stages of ms achieved in a multi stage mass spectrometry experiment. [PSI:MS] /// </summary> public static bool TryGetMsLevel(this MassSpectrum ms, out int msLevel) { CvParam p; if (ms.TryGetParam(MsLevel, out p)) { msLevel = p.GetInt32(); return(true); } else { msLevel = default(int); return(false); } }
public void UpdateAnnotations( MassSpectrum spectrum ) { if( currentSpectrum != spectrum ) { currentSpectrum = spectrum; Text = TabText = "Annotations for spectrum " + spectrum.Id; runOverrideToolStripButton.Text = "Override " + spectrum.Source.Source.Name + " Annotations"; annotationsListView.VirtualListSize = spectrum.AnnotationList.Count; if (spectrum.AnnotationList.Count > 0) selectIndex(spectrum.AnnotationList.Count - 1); } annotationsListView.Refresh(); }
private void WriteToMSn(StreamWriter writer, MassSpectrum spec) { writer.Write("S\t" + String.Format("{0:000000}", spec.ScanNumber) + "\t" + String.Format("{0:000000}", spec.ScanNumber) + "\t" + Math.Round(spec.Precursors[0].Item1, _mzDecimalPlace + 1) + "\n" + "I\tRetTime\t" + Math.Round(spec.RetentionTime, 2) + "\n" + "I\tIonInjectionTime\t" + spec.IonInjectionTime + "\n" + "I\tActivationType\t" + spec.ActivationMethod + "\n" + "I\tInstrumentType\t" + spec.InstrumentType + "\n" + "I\tTemperatureFTAnalyzer\t" + spec.TemperatureFTAnalyzer + "\n" + "I\tFilter\t" + spec.Filter + "\n" + "I\tPrecursorScan\t" + spec.PrecursorScanNumber + "\n" + "I\tPrecursorInt\t" ); if (!double.IsNaN(spec.PrecursorIntensity)) { writer.Write(Math.Round(spec.PrecursorIntensity, _intensityDecimalPlace) + "\n"); } else { writer.Write("\n"); } foreach (Tuple <double, int> prec in spec.Precursors) { if (prec.Item2 != 0) { double precMH = (prec.Item1 - Utils.PROTON_MASS) * prec.Item2 + Utils.PROTON_MASS; writer.Write("Z\t" + prec.Item2 + "\t" + Math.Round(precMH, _mzDecimalPlace + 1) + "\n"); } else { foreach (int charge in _ddaDataChargeStates) { double precMH = (prec.Item1 - Utils.PROTON_MASS) * charge + Utils.PROTON_MASS; writer.Write("Z\t" + charge + "\t" + Math.Round(precMH, _mzDecimalPlace + 1) + "\n"); } } } foreach (Ion peak in spec.Peaks) { writer.Write(Math.Round(peak.MZ, _mzDecimalPlace) + " " + Math.Round(peak.Intensity, _intensityDecimalPlace) + "\n"); } }
private void SqlInsert(string runID, MassSpectrum spectrum, Peak1DArray peaks) { SQLiteCommand cmd; if (!currentScope.TryGetCommand("INSERT_SPECTRUM_CMD", out cmd)) { cmd = currentScope.PrepareCommand("INSERT_SPECTRUM_CMD", "INSERT INTO Spectrum VALUES(@runID, @spectrumID, @description, @peakArray, @peakData);"); } cmd.Parameters.Clear(); cmd.Parameters.AddWithValue("@runID", runID); cmd.Parameters.AddWithValue("@spectrumID", spectrum.ID); cmd.Parameters.AddWithValue("@description", MzLiteJson.ToJson(spectrum)); cmd.Parameters.AddWithValue("@peakArray", MzLiteJson.ToJson(peaks)); cmd.Parameters.AddWithValue("@peakData", encoder.Encode(peaks)); cmd.ExecuteNonQuery(); }
public void WriteSpectrum(MassSpectrum ms, Peak1DArray peaks, int index) { try { if (ms == null) { throw new ArgumentNullException("ms"); } if (peaks == null) { throw new ArgumentNullException("peaks"); } if (index < 0) { throw new ArgumentOutOfRangeException("idx"); } EnsureWriteState(MzMLWriteState.SPECTRUM_LIST); writer.WriteStartElement("spectrum"); WriteXmlAttribute("id", ms.ID, true); WriteXmlAttribute("index", index.ToString(formatProvider), true); WriteXmlAttribute("dataProcessingRef", ms.DataProcessingReference, false); WriteXmlAttribute("sourceFileRef", ms.SourceFileReference, false); WriteXmlAttribute("defaultArrayLength", peaks.Peaks.Length.ToString(formatProvider), true); WriteParamGroup(ms); WriteList("scanList", ms.Scans, WriteScan); WriteList("precursorList", ms.Precursors, WritePrecursor); WriteList("productList", ms.Products, WriteProduct); WriteBinaryDataArrayList(peaks); writer.WriteEndElement(); } catch (Exception ex) { currentWriteState = MzMLWriteState.ERROR; throw new MzLiteIOException("Error writing mzml output file.", ex); } }
private void WriteToOutFiles(MassSpectrum spec, bool isFirstScan) { // MS1 file; if (_ms1Writer != null && spec.MsLevel == 1) { if (_isFirstMS1Scan) { TextFileWriter.WriteMSnHeader(_ms1Writer, "MS1", _scanCount, spec); _isFirstMS1Scan = false; } TextFileWriter.WriteToMS1(_ms1Writer, spec, _mzDecimalPlace, _intensityDecimalPlace, false, false); } // MS2 file; if (_ms2Writer != null && spec.MsLevel == 2) { if (_isFirstMS2Scan) { TextFileWriter.WriteMSnHeader(_ms2Writer, "MS2", _scanCount, spec); _isFirstMS2Scan = false; } TextFileWriter.WriteToMSn(_ms2Writer, spec, _mzDecimalPlace, _intensityDecimalPlace, false, false); } // MS3 file; if (_ms3Writer != null && spec.MsLevel == 3) { if (_isFirstMS3Scan) { TextFileWriter.WriteMSnHeader(_ms3Writer, "MS3", _scanCount, spec); _isFirstMS3Scan = false; } TextFileWriter.WriteToMSn(_ms3Writer, spec, _mzDecimalPlace, _intensityDecimalPlace, false, false); } // MGF file; if (_mgfWriter != null && spec.MsLevel == 2) { TextFileWriter.WriteToMGF(_mgfWriter, spec, _mzxmlFileName, _mzDecimalPlace, _intensityDecimalPlace, false, false); } }
private static SWATHIndexerItem CreateItem(MassSpectrum ms) { if (ms.BeginParamEdit().Get_MS_Level().GetInt32() != 2) { return(null); } if (ms.Precursors.Count < 1 || ms.Precursors[0].SelectedIons.Count < 1 || ms.Scans.Count < 1) { return(null); } IValueConverter rt = ms.Scans[0].BeginParamEdit().Get_MS_ScanStartTime(); IParamEdit isoWin = ms.Precursors[0].IsolationWindow.BeginParamEdit(); IValueConverter mz = isoWin.Get_MS_IsolationWindowTargetMz(); IValueConverter mzLow = isoWin.Get_MS_IsolationWindowLowerOffset(); IValueConverter mzHigh = isoWin.Get_MS_IsolationWindowUpperOffset(); if (rt.HasValue() && mz.HasValue() && mzLow.HasValue() && mzHigh.HasValue()) { double mzValue = mz.GetDouble(); return(new SWATHIndexerItem() { Mz = mz.GetDouble(), MzStart = SaveSubtract(mzValue, mzLow.GetDouble()), MzEnd = SaveAdd(mzValue, mzHigh.GetDouble()), Rt = rt.GetDouble(), SpectrumID = ms.ID }); } else { return(null); } }
public override SpectrumChartData CreateSpectrumDetails(MassSpectrumItem massSpectrumItem, MassSpectrum referenceSpectrum = null) { ArgumentHelper.AssertNotNull(massSpectrumItem, "massSpectrumItem"); // clone given spectrum var spectrum = massSpectrumItem.Spectrum.Clone(); if (spectrum == null){ return null; } //// get ions for respective polarity //var ions = spectrum.ScanEvent.Polarity == PolarityType.Negative // ? m_unknownFeatureIonInstanceItems.Where(w => w.Charge < 0) // : m_unknownFeatureIonInstanceItems.Where(w => w.Charge > 0); // annotate nearest centroids foreach (var ion in m_unknownFeatureIonInstanceItems){ // annotate isotopes foreach (var peak in m_chromatogramPeakItemsMap[ion.GetIDs()]){ var centroid = spectrum.PeakCentroids.FindClosestPeak(peak.Mass); if (centroid != null){ centroid.DisplayPriority = 2; } } } // create spectrum chart data var massRange = Range.Create(spectrum.Header.LowPosition, spectrum.Header.HighPosition); if (spectrum.ScanEvent.MSOrder == MSOrderType.MS1){ var peaks = m_chromatogramPeakItemsMap.SelectMany(s => s.Value).ToList(); massRange = Range.Create(Math.Max(0, peaks.Min(m => m.Mass)) - 4, peaks.Max(m => m.Mass) + 5); } return new SpectrumChartData{ MassRange = massRange, SpectrumDistanceDetails = null, Spectrum = spectrum, SpectrumHeaderText = CreateSpectrumChartHeader(spectrum, m_extraHeaderLine, m_fileNames[spectrum.Header.FileID]) }; }
private static bool TryCreateSwathSpectrum(MassSpectrum ms, out SwathSpectrumEntry sws) { sws = null; int msLevel; if (!ms.TryGetMsLevel(out msLevel) || msLevel != 2) { return(false); } if (ms.Precursors.Count < 1 || ms.Precursors[0].SelectedIons.Count < 1 || ms.Scans.Count < 1) { return(false); } double rt, mz, mzLow, mzHeigh; var isoWin = ms.Precursors[0].IsolationWindow; var scan = ms.Scans[0]; if (scan.TryGetScanStartTime(out rt) && isoWin.TryGetIsolationWindowTargetMz(out mz) && isoWin.TryGetIsolationWindowLowerOffset(out mzLow) && isoWin.TryGetIsolationWindowUpperOffset(out mzHeigh)) { sws = new SwathSpectrumEntry( ms.ID, mz, mz - mzLow, mz + mzHeigh, rt); return(true); } else { return(false); } }
public static void WriteToMGF(StreamWriter writer, MassSpectrum spec, String parentFileName, int mzDecimalPlace, int intensityDecimalPlace, bool showPeakChargeState, bool showPeakResolution) { writer.Write("BEGIN IONS\n"); writer.Write("TITLE=" + parentFileName + "\n"); writer.Write("SCANS=" + spec.ScanNumber + "\n"); writer.Write("RTINSECONDS=" + (spec.RetentionTime * 60) + "\n"); writer.Write("CHARGE=" + spec.Precursors[0].Item2); if (spec.Precursors[0].Item2 >= 0) { writer.Write("+\n"); } writer.Write("PEPMASS=" + Math.Round(spec.Precursors[0].Item1, mzDecimalPlace) + "\n"); // write peaks; foreach (Ion peak in spec.Peaks) { writer.Write(Math.Round(peak.MZ, mzDecimalPlace) + " " + Math.Round(peak.Intensity, intensityDecimalPlace) + "\n"); } writer.Write("END IONS\n\n"); writer.Flush(); }
private void initializeManagedDataSource( ManagedDataSource managedDataSource ) { try { DataSource source = managedDataSource.Source; MSDataFile msDataFile = source.MSDataFile; ChromatogramListForm chromatogramListForm = managedDataSource.ChromatogramListForm; SpectrumListForm spectrumListForm = managedDataSource.SpectrumListForm; chromatogramListForm.Text = source.Name + " chromatograms"; chromatogramListForm.TabText = source.Name + " chromatograms"; chromatogramListForm.ShowIcon = false; chromatogramListForm.CellDoubleClick += new ChromatogramListCellDoubleClickHandler( chromatogramListForm_CellDoubleClick ); spectrumListForm.Text = source.Name + " spectra"; spectrumListForm.TabText = source.Name + " spectra"; spectrumListForm.ShowIcon = false; spectrumListForm.CellDoubleClick += new SpectrumListCellDoubleClickHandler( spectrumListForm_CellDoubleClick ); bool firstChromatogramLoaded = false; bool firstSpectrumLoaded = false; GraphForm firstGraph = null; ChromatogramList cl = msDataFile.run.chromatogramList; SpectrumList sl = msDataFile.run.spectrumList; if( sl == null ) throw new Exception( "Error loading metadata: no spectrum list" ); int ticIndex = 0; if( cl != null ) { ticIndex = cl.findNative( "TIC" ); if( ticIndex < cl.size() ) { pwiz.CLI.msdata.Chromatogram tic = cl.chromatogram( ticIndex ); Chromatogram ticChromatogram = new Chromatogram( source, tic ); chromatogramListForm.Add( ticChromatogram ); source.Chromatograms.Add( ticChromatogram ); firstGraph = OpenGraph( true ); showData( firstGraph, managedDataSource, ticChromatogram ); firstChromatogramLoaded = true; chromatogramListForm.Show( mainForm.DockPanel, DockState.DockBottomAutoHide ); Application.DoEvents(); } } CVParam spectrumType = msDataFile.fileDescription.fileContent.cvParamChild( CVID.MS_spectrum_type ); if( spectrumType.cvid == CVID.CVID_Unknown && !sl.empty() ) spectrumType = sl.spectrum( 0 ).cvParamChild( CVID.MS_spectrum_type ); if( spectrumType.cvid == CVID.MS_SRM_spectrum ) { if( cl != null && cl.empty() ) throw new Exception( "Error loading metadata: SRM file contains no chromatograms" ); } else //if( spectrumType.cvid == CVID.MS_MS1_spectrum || // spectrumType.cvid == CVID.MS_MSn_spectrum ) { if( sl.empty() ) throw new Exception( "Error loading metadata: MSn file contains no spectra" ); }// else // throw new Exception( "Error loading metadata: unable to open files with spectrum type \"" + spectrumType.name + "\"" ); if( cl != null ) { // load the rest of the chromatograms for( int i = 0; i < cl.size(); ++i ) { if( i == ticIndex ) continue; pwiz.CLI.msdata.Chromatogram c = cl.chromatogram( i ); mainForm.SetStatusLabel( String.Format( "Loading chromatograms from source file ({0} of {1})...", ( i + 1 ), cl.size() ) ); mainForm.SetProgressPercentage( ( i + 1 ) * 100 / cl.size() ); Chromatogram chromatogram = new Chromatogram( source, c ); chromatogramListForm.Add( chromatogram ); source.Chromatograms.Add( chromatogram ); if( !firstChromatogramLoaded ) { firstChromatogramLoaded = true; chromatogramListForm.Show( mainForm.DockPanel, DockState.DockBottomAutoHide ); firstGraph = OpenGraph( true ); showData( firstGraph, managedDataSource, chromatogram ); } Application.DoEvents(); } } // get all scans by sequential access for( int i = 0; i < sl.size(); ++i ) { pwiz.CLI.msdata.Spectrum s = sl.spectrum( i ); if( ( ( i + 1 ) % 100 ) == 0 || ( i + 1 ) == sl.size() ) { mainForm.SetStatusLabel( String.Format( "Loading spectra from source file ({0} of {1})...", ( i + 1 ), sl.size() ) ); mainForm.SetProgressPercentage( ( i + 1 ) * 100 / sl.size() ); } MassSpectrum spectrum = new MassSpectrum( source, s ); spectrumListForm.Add( spectrum ); source.Spectra.Add( spectrum ); if( !firstSpectrumLoaded ) { firstSpectrumLoaded = true; spectrumListForm.Show( mainForm.DockPanel, DockState.DockBottomAutoHide ); if( firstChromatogramLoaded ) { GraphForm spectrumGraph = CreateGraph(); spectrumGraph.Show( firstGraph.Pane, DockPaneAlignment.Bottom, 0.5 ); showData( spectrumGraph, managedDataSource, spectrum ); } else { firstGraph = OpenGraph( true ); showData( firstGraph, managedDataSource, spectrum ); } } Application.DoEvents(); } mainForm.SetStatusLabel( "Finished loading source metadata." ); mainForm.SetProgressPercentage( 100 ); } catch( Exception ex ) { string message = "SeeMS encountered an error reading metadata from \"" + managedDataSource.Source.CurrentFilepath + "\" (" + ex.Message + ")"; if( ex.InnerException != null ) message += "\n\nAdditional information: " + ex.InnerException.Message; MessageBox.Show( message, "Error reading source metadata", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, 0, false ); mainForm.SetStatusLabel( "Failed to read source metadata." ); } }
private MassSpectrum Process(List <String> ms2Data) { List <Ion> peakList = new List <Ion>(); int scanNumber = 0; double retTime = 0; double precInt = 0; int precScan = 0; double ionInjectionTime = 0; String activationType = null; String instType = null; List <Tuple <double, int> > precursors = new List <Tuple <double, int> >(); String pepSeq = null; foreach (String line in ms2Data) { if (_startsWithNumber.IsMatch(line)) { // get peak list; string[] elems = Regex.Split(line, " "); if (elems.Length == 1) { elems = Regex.Split(line, "\t"); } peakList.Add(new Ion(double.Parse(elems[0]), double.Parse(elems[1]))); } else { string[] elems = Regex.Split(line, "\t"); if (elems[0].Equals("S")) { scanNumber = int.Parse(elems[1]); } else if (elems[1].Equals("RetTime")) { retTime = double.Parse(elems[2]); } else if (elems[1].Equals("PrecursorInt")) { precInt = double.Parse(elems[2]); } else if (elems[1].Equals("PrecursorScan")) { precScan = int.Parse(elems[2]); } else if (line.StartsWith("I\tIonInjectionTime")) { if (elems.Length >= 3 && elems[2] != null) { ionInjectionTime = double.Parse(elems[2]); } } else if (line.StartsWith("I\tActivationType")) { activationType = elems[2]; } else if (line.StartsWith("I\tInstrumentType")) { instType = elems[2]; } else if (line.StartsWith("I\tPeptide")) { pepSeq = elems[2]; } else if (line.StartsWith("Z")) { double precMH = double.Parse(elems[2]); int precZ = int.Parse(elems[1]); double precMz = (precMH + (precZ - 1) * Utils.PROTON_MASS) / precZ; precursors.Add(new Tuple <double, int>(precMz, precZ)); } } } peakList.Sort((a, b) => a.MZ.CompareTo(b.MZ)); MassSpectrum spec = new MassSpectrum(scanNumber, "", retTime, peakList, ionInjectionTime, InstrumentType.ELSE, "", 0, false); spec.Precursors = precursors; spec.PrecursorIntensity = precInt; spec.PrecursorScanNumber = precScan; spec.PeptideSequence = pepSeq; return(spec); }
public void Add( MassSpectrum spectrum ) { SpectrumDataSet.SpectrumTableRow row = spectrumDataSet.SpectrumTable.NewSpectrumTableRow(); row.Id = spectrum.Id; if( nativeIdFormat != CVID.CVID_Unknown ) { gridView.Columns["Id"].Visible = false; string[] nameValuePairs = spectrum.Id.Split( " ".ToCharArray() ); foreach( string nvp in nameValuePairs ) { string[] nameValuePair = nvp.Split( "=".ToCharArray() ); row[nameValuePair[0]] = nameValuePair[1]; } } row.Index = spectrum.Index; updateRow( row, spectrum ); spectrumDataSet.SpectrumTable.AddSpectrumTableRow( row ); //int rowIndex = gridView.Rows.Add(); //gridView.Rows[rowIndex].Tag = spectrum; spectrum.Tag = this; if( spectrum.Element.spotID.Length > 0 ) gridView.Columns["SpotId"].Visible = true; //UpdateRow( rowIndex ); }
public SpectrumViewer(string filename, object index, string interpretation) { // Prepare the annotation annotation = new PeptideFragmentationAnnotation(interpretation, 1, 2, false, true, false, false, true, false, false, true, false, true); annotation.OptionsPanel.Dock = DockStyle.None; annotation.OptionsPanel.Dock = DockStyle.Fill; // Get the mass spectrum spectrum = SpectrumCache.GetMassSpectrum(filename,index); if(spectrum == null) return; // Add annotation to the mass spectrum and get a new graph control spectrum.AnnotationList.Clear(); spectrum.AnnotationList.Add((IAnnotation)annotation); graph = new MSGraphControl(); graph.AddGraphItem(graph.GraphPane, spectrum); graph.Dock = DockStyle.Fill; // Create new panels and add the graph and annotations spectrumPanel = new Panel(); spectrumPanel.Controls.Add(graph); spectrumPanel.Dock = DockStyle.None; spectrumPanel.Dock = DockStyle.Fill; annotationPanel = new Panel(); annotationPanel.Controls.Add(annotation.OptionsPanel); annotationPanel.Dock = DockStyle.None; annotationPanel.Dock = DockStyle.Fill; fragmentationPanel = new Panel(); annotation.FragmentInfoGridView.Location = new Point(0,0); annotation.FragmentInfoGridView.ScrollBars = ScrollBars.Both; annotation.FragmentInfoGridView.Dock = DockStyle.None; annotation.FragmentInfoGridView.Dock = DockStyle.Fill; annotation.FragmentInfoGridView.BorderStyle = BorderStyle.FixedSingle; fragmentationPanel.Controls.Add(annotation.FragmentInfoGridView); fragmentationPanel.Dock = DockStyle.None; fragmentationPanel.Dock = DockStyle.Fill; // Add the call back for refreshing annotation.OptionsChanged += new EventHandler(OnOptionsChanged); }
private MassSpectrum getMetaSpectrum( MassSpectrum spectrum ) { return spectrum.OwningListForm.GetSpectrum( spectrum.OwningListForm.IndexOf( spectrum ) ); }
public MassSpectrum GetMassSpectrum( MassSpectrum metaSpectrum, SpectrumList spectrumList ) { MassSpectrum spectrum = new MassSpectrum( metaSpectrum, spectrumList.spectrum( metaSpectrum.Index, true ) ); //MassSpectrum realMetaSpectrum = ( metaSpectrum.Tag as DataGridViewRow ).Tag as MassSpectrum; //realMetaSpectrum.Element.dataProcessing = spectrum.Element.dataProcessing; //realMetaSpectrum.Element.defaultArrayLength = spectrum.Element.defaultArrayLength; return spectrum; }
internal SpectrumListCellDoubleClickEventArgs( SpectrumListForm sender, DataGridViewCellMouseEventArgs e ) : base(e.Button, e.Clicks, e.X, e.Y, e.Delta) { if( e.RowIndex > -1 && e.RowIndex < sender.GridView.RowCount ) spectrum = sender.GridView.Rows[e.RowIndex].Tag as MassSpectrum; }
public void Convert(TaskProgress progress) { string line = null; int scan = 0; bool started = false; List <String> mgfData = new List <String>(); while ((line = _mgfReader.ReadLine()) != null) { if (!started) { do { if (line.Contains("BEGIN IONS")) { started = true; break; } } while ((line = _mgfReader.ReadLine()) != null); } if (line.Length > 0) { //process each precursor if (line.Contains("BEGIN IONS")) { if (mgfData.Count > 0) { MassSpectrum spec = Process(mgfData); if (spec != null) { if (spec.ScanNumber == 0) { spec.ScanNumber = ++scan; } _lastScanNum = spec.ScanNumber; WriteToOutFile(spec); _processedSpecNum++; progress.CurrentProgress = (int)((double)_processedSpecNum / (_totalSpecNum) * 100); if (progress.CurrentProgress > _lastProgress) { _lastProgress = progress.CurrentProgress; //int currentLineCursor = Console.CursorTop; //Console.SetCursorPosition(0, Console.CursorTop); //Console.Write(" Reading MGF File: " + _lastProgress + "%"); //Console.SetCursorPosition(0, currentLineCursor); } } mgfData.Clear(); } } else if (!line.Contains("END IONS")) { mgfData.Add(line); } } } // process the last scan; MassSpectrum lastSpec = Process(mgfData); if (lastSpec != null) { if (lastSpec.ScanNumber == 0) { lastSpec.ScanNumber = ++scan; } _lastScanNum = lastSpec.ScanNumber; WriteToOutFile(lastSpec); _processedSpecNum++; progress.CurrentProgress = (int)((double)_processedSpecNum / (_totalSpecNum) * 100); if (progress.CurrentProgress > _lastProgress) { _lastProgress = progress.CurrentProgress; int currentLineCursor = Console.CursorTop; Console.SetCursorPosition(0, Console.CursorTop); Console.Write(" Reading MGF File: " + _lastProgress + "%"); Console.SetCursorPosition(0, currentLineCursor); } } mgfData.Clear(); // write the MSn header into the MSn file; FinishConversion(); }
public void Add( MassSpectrum spectrum ) { Spectrum s = spectrum.Element; SpectrumDescription sd = s.spectrumDescription; Scan scan = sd.scan; InstrumentConfiguration ic = scan.instrumentConfiguration; DataProcessing dp = s.dataProcessing; CVParam param; param = s.cvParam( CVID.MS_ms_level ); int msLevel = param.cvid != CVID.CVID_Unknown ? Convert.ToInt32( (string) param.value ) : 0; param = scan.cvParam( CVID.MS_scan_time ); double scanTime = param.cvid != CVID.CVID_Unknown ? Convert.ToDouble( (string) param.value ) : 0; param = sd.cvParam( CVID.MS_base_peak_m_z ); double bpmz = param.cvid != CVID.CVID_Unknown ? Convert.ToDouble( (string) param.value ) : 0; param = sd.cvParam( CVID.MS_base_peak_intensity ); double bpi = param.cvid != CVID.CVID_Unknown ? Convert.ToDouble( (string) param.value ) : 0; param = sd.cvParam( CVID.MS_total_ion_current ); double tic = param.cvid != CVID.CVID_Unknown ? Convert.ToDouble( (string) param.value ) : 0; param = scan.cvParamChild( CVID.MS_polarity ); string polarity = param.cvid != CVID.CVID_Unknown ? param.name : "unknown"; int rowIndex = gridView.Rows.Add( s.id, s.nativeID, s.index, s.cvParamChild( CVID.MS_spectrum_type ).name, msLevel, scanTime, s.defaultArrayLength, ( ic != null ? ic.id : "unknown" ), bpmz, bpi, tic, ( dp != null ? dp.id : "unknown" ), polarity, "", "" ); gridView.Rows[rowIndex].Tag = spectrum; spectrum.Tag = gridView.Rows[rowIndex]; }
public int IndexOf( MassSpectrum spectrum ) { return spectraSource.Find( "Id", spectrum.Id ); }
internal SpectrumListCellDoubleClickEventArgs( SpectrumListForm sender, DataGridViewCellMouseEventArgs e ) : base( e.ColumnIndex, e.RowIndex, e.X, e.Y, e ) { if( e.RowIndex > -1 && e.RowIndex < sender.GridView.RowCount ) spectrum = sender.GetSpectrum( e.RowIndex ); }
/// <summary> /// Parse the lines between a pair of "BEGIN IONS" and "END IONS" into an instance of MassSpectrum. /// </summary> /// <param name="mgfData"></param> /// <returns></returns> private MassSpectrum Process(List <String> mgfData) { int scanNumber = 0; double retTime = 0; Activation activationType; double precMz = 0; List <int> chargeList = new List <int>(); List <Tuple <double, int> > precursors = new List <Tuple <double, int> >(); List <Ion> peakList = new List <Ion>(); foreach (String row in mgfData) { if (_startsWithNumber.IsMatch(row)) //This test needs to be the first as it is the most frequent; { // set the precursors; foreach (int charge in chargeList) { precursors.Add(new Tuple <double, int>(precMz, charge)); } chargeList.Clear(); // get ion information; string[] cols = Regex.Split(row, " "); if (cols.Length == 1) { cols = Regex.Split(row, "\t"); } Ion ion = new Ion(double.Parse(cols[0]), double.Parse(cols[1])); peakList.Add(ion); } else { string[] cols = Regex.Split(row, "="); if (cols[0].Equals("SCANS")) { if (!cols[1].Contains("-")) { scanNumber = int.Parse(cols[1]); } else { string[] colsTemp = Regex.Split(cols[1], "-"); scanNumber = int.Parse(colsTemp[0]); } } else if (cols[0].Equals("RTINSECONDS")) { if (!cols[1].Contains("-")) { retTime = double.Parse(cols[1]); } else { string[] retTimeTemp = Regex.Split(cols[1], "-"); retTime = double.Parse(retTimeTemp[0]); } } else if (cols[0].Equals("TITLE")) { string[] titleValue = Regex.Split(cols[1], ":"); try { int fragmentationIndex = titleValue.Select((item, indx) => new { Item = item, Index = indx }).Where(x => x.Item.ToLower().Contains("fragmentation")).Select(x => x.Index).Single(); activationType = (Activation)Enum.Parse(typeof(Activation), titleValue[fragmentationIndex + 1].ToUpper()); } catch (Exception) { //If does not exists fragmentation field, CID is selected as ActivationType Console.WriteLine("WARNING: Not found fragmentation type information.\n"); activationType = (Activation)Enum.Parse(typeof(Activation), "CID"); } } else if (cols[0].Equals("CHARGE")) { string[] charges = Regex.Split(cols[1], "and"); foreach (string charge in charges) { string[] elems = Regex.Split(charge, "\\+"); if (elems[0].Equals("")) { chargeList.Add(int.Parse(elems[1])); } else { chargeList.Add(int.Parse(elems[0])); } } } else if (cols[0].Equals("PEPMASS")) { //Identify precursor intensity string massWithoutIntensity; try { string[] pepmassWithTAB = Regex.Split(cols[1], "\t"); if (pepmassWithTAB.Length == 1) { massWithoutIntensity = Regex.Split(cols[1], " ")[0]; } else { massWithoutIntensity = pepmassWithTAB[0]; } } catch (Exception) { Console.WriteLine("WARNING: Not found Mass field in PEPMASS. Default mass = 0.0"); massWithoutIntensity = "0"; } precMz = double.Parse(massWithoutIntensity); } } } peakList.Sort((a, b) => a.MZ.CompareTo(b.MZ)); MassSpectrum spec = new MassSpectrum(scanNumber, "", retTime, peakList, 0, InstrumentType.ELSE, "", 0, false); spec.Precursors = precursors; return(spec); }
public void Convert(TaskProgress progress) { List <MassSpectrum> specList = new List <MassSpectrum>(500); List <String> ms2Data = new List <String>(); string line = null; while ((line = _ms2Reader.ReadLine()) != null) { if (line.Length > 0) { if (line.StartsWith("S")) { if (ms2Data.Count == 0) { ms2Data.Add(line); } else { MassSpectrum spec = Process(ms2Data); WriteToOutFiles(spec); _spectrumProcessed++; if (progress.Aborted) { return; } progress.CurrentProgress = (int)((double)_spectrumProcessed / _totalSpecNum * 100); if (progress.CurrentProgress > _lastProgress) { _lastProgress = progress.CurrentProgress; int currentLineCursor = Console.CursorTop; Console.SetCursorPosition(0, Console.CursorTop); Console.Write(" Reading MS2 File: " + _lastProgress + "%"); Console.SetCursorPosition(0, currentLineCursor); } ms2Data.Clear(); ms2Data.Add(line); } } else if (ms2Data.Count > 0) { ms2Data.Add(line); } } } // process the last spectrum; MassSpectrum lastSpec = Process(ms2Data); _spectrumProcessed++; WriteToOutFiles(lastSpec); if (progress.Aborted) { return; } progress.CurrentProgress = (int)((double)_spectrumProcessed / _totalSpecNum * 100); if (progress.CurrentProgress > _lastProgress) { _lastProgress = progress.CurrentProgress; int currentLineCursor = Console.CursorTop; Console.SetCursorPosition(0, Console.CursorTop); Console.Write(" Reading MS2 File: " + _lastProgress + "%"); Console.SetCursorPosition(0, currentLineCursor); } }
//via vote to predict monoistopic by three MS1 scans public void CorrectPrecursor(ref MassSpectrum curSpec, double precMz, int precZ, int CurrentMS1ScanNum, List <MassSpectrum> MS1spec) { Dictionary <double, double> CorrectMZ = new Dictionary <double, double>(); double precMzFromFilter = curSpec.PrecMzFromFilter; int flag = 0; double PredictedMZ = 0.0; double precErr = curSpec.PrecMzFromFilter * RawFileConverter.FTMS_ERR_TOL / 1E6; bool debug = false; int debugNum = 2087; // get the peaks dropped in a designated window by current MS1; List <Ion> peaksInWindows = new List <Ion>(); if (precZ > 6) { return; } //*yychu Debug if (debug) { if (curSpec.ScanNumber == debugNum) { Console.WriteLine("MZ:" + precMz); foreach (var yy in MS1spec) { Console.WriteLine("MS1specNo: " + yy.ScanNumber + "\t"); } } } //*/ if (curSpec.ScanNumber == 26643) { Console.Write(""); } //caculate each MS2 with another MS1 for (int i = 0; i < MS1spec.Count; i++) { if (MS1spec[i] == null) { continue; } double tmpPrecMZ = 0.0; double tmpScore = 0.0; // get the precursor MS1 spectrum; List <Ion> peaks = MS1spec[i].Peaks; // get the peaks dropped in a designated window; List <Ion> peaksInWindow = new List <Ion>(); double err = RawFileConverter.FTMS_ERR_TOL * precMz / 1E6; double startMz = precMzFromFilter - MAX_CHECK_BACKWARD_MZ; startMz = Math.Min(startMz, precMz) - err; double endMz = precMzFromFilter + MAX_CHECK_FORWARD_MZ; foreach (Ion peak in peaks) { if (peak.MZ >= startMz && peak.MZ <= endMz) { peaksInWindow.Add(peak); } } // sort the peaks; peaksInWindow.Sort(delegate(Ion p1, Ion p2) { if (p1.MZ < p2.MZ) { return(-1); } else if (p1.MZ > p2.MZ) { return(1); } else { return(0); } }); // get all the possible envelopes; List <Envelope> envList = FindEnvelopesByLP(peaksInWindow, curSpec.PrecMzFromFilter, precZ); if (envList == null) { continue; } // rescore and re-sort the envList according to the scores decendingly; RescoreEnvelopes(envList); envList.Sort(delegate(Envelope e1, Envelope e2) { if (e1.Score < e2.Score) { return(1); } else if (e1.Score > e2.Score) { return(-1); } else { return(0); } }); Envelope env = (envList != null && envList.Count > 0) ? envList[0] : null; if (env != null && env.Score < double.MaxValue) { curSpec.PrecursorRefined = true; tmpPrecMZ = env.MonoisotPeak.MZ; tmpScore = env.Score; if (MS1spec[i].ScanNumber == CurrentMS1ScanNum) { peaksInWindows = peaksInWindow; } } else { continue; } //* yychu Debug if (debug) { if (curSpec.ScanNumber == debugNum) { Console.WriteLine("no:" + curSpec.ScanNumber); Console.WriteLine("oldMZ: " + tmpPrecMZ); } } //*/ // Vote monoisotopic foreach (var mz in CorrectMZ) { if (Math.Abs(mz.Key - tmpPrecMZ) <= precErr) { CorrectMZ[mz.Key] += tmpScore; flag = 1; break; } flag = 0; } if (flag == 0) { CorrectMZ.Add(tmpPrecMZ, tmpScore); } } //*yychu Debug if (debug) { if (curSpec.ScanNumber == debugNum) { foreach (var mz in CorrectMZ) { Console.WriteLine("CorrectMZ: " + mz); } } } //*/ PredictedMZ = CorrectMZ.FirstOrDefault(x => x.Value == CorrectMZ.Values.Max()).Key; if (PredictedMZ == 0) { PredictedMZ = curSpec.Precursors[0].Item1; } curSpec.Precursors.Clear(); curSpec.Precursors.Add(new Tuple <double, int>(PredictedMZ, precZ)); //To find prediected monoisotopic intensity in current MS1 foreach (Ion peak in peaksInWindows) { if (Math.Round(peak.MZ, 2) == Math.Round(PredictedMZ, 2)) { curSpec.PrecursorIntensity = peak.Intensity; break; } else { curSpec.PrecursorIntensity = 0; } } }
public void TransformByApplyingFunctionToSpectra(Func <IMzPeak, double> convertorForSpectrum) { MassSpectrum.ReplaceXbyApplyingFunction(convertorForSpectrum); }
private void showSpectrum( MassSpectrum spectrum, bool isOverlay ) { ZedGraph.GraphPane pane = zedGraphControl1.GraphPane; if( isOverlay && pane.CurveList.Count > overlayColors.Length ) MessageBox.Show( "SeeMS only supports up to " + overlayColors.Length + " simultaneous overlays.", "Too many overlays", MessageBoxButtons.OK, MessageBoxIcon.Stop ); // set form title if( !isOverlay ) Text = String.Format( "{0} - {1}", currentDataSource.Name, spectrum.Id ); else Text += "," + spectrum.Id; if( !isOverlay ) pane.CurveList.Clear(); if( currentGraphItem != null && !currentGraphItem.IsMassSpectrum ) { zedGraphControl1.RestoreScale( pane ); zedGraphControl1.ZoomOutAll( pane ); } bool isScaleAuto = !pane.IsZoomed; //pane.GraphObjList.Clear(); // the header does not have the data points pane.YAxis.Title.Text = "Intensity"; pane.XAxis.Title.Text = "m/z"; PointList pointList = spectrum.PointList; if( pointList.FullCount > 0 ) { int bins = (int) pane.CalcChartRect( zedGraphControl1.CreateGraphics() ).Width; if( isScaleAuto ) pointList.SetScale( bins, pointList[0].X, pointList[pointList.Count - 1].X ); else pointList.SetScale( bins, pane.XAxis.Scale.Min, pane.XAxis.Scale.Max ); if( spectrum.Element.spectrumDescription.hasCVParam(pwiz.CLI.msdata.CVID.MS_centroid_mass_spectrum) ) { ZedGraph.StickItem stick = pane.AddStick( spectrum.Id, pointList, Color.Gray ); stick.Symbol.IsVisible = false; stick.Line.Width = 1; } else pane.AddCurve( spectrum.Id, pointList, Color.Gray, ZedGraph.SymbolType.None ); } pane.AxisChange(); if( isOverlay ) { pane.Legend.IsVisible = true; pane.Legend.Position = ZedGraph.LegendPos.TopCenter; for( int i = 0; i < pane.CurveList.Count; ++i ) { pane.CurveList[i].Color = overlayColors[i]; ( pane.CurveList[i] as ZedGraph.LineItem ).Line.Width = 2; } } else { pane.Legend.IsVisible = false; currentGraphItem = spectrum; } SetDataLabelsVisible( true ); zedGraphControl1.Refresh(); }
public void UpdateProcessing( MassSpectrum spectrum ) { if( processingListView.VirtualListSize != spectrum.ProcessingList.Count ) { processingListView.VirtualListSize = spectrum.ProcessingList.Count; selectIndex( spectrum.ProcessingList.Count - 1 ); } if( currentSpectrum != spectrum ) { currentSpectrum = spectrum; Text = TabText = "Processing for spectrum " + spectrum.Id; runOverrideToolStripButton.Text = "Override " + spectrum.Source.Source.Name + " Processing"; processingListView_SelectedIndexChanged( this, EventArgs.Empty ); } processingListView.Refresh(); }
public void Add( MassSpectrum spectrum ) { SpectrumDataSet.SpectrumTableRow row = spectrumDataSet.SpectrumTable.NewSpectrumTableRow(); row.Id = spectrum.Id; if( nativeIdFormat != CVID.CVID_Unknown ) { gridView.Columns["Id"].Visible = false; // guard against case where input is mzXML which // is identified as, say, Agilent-derived, but // which uses "scan" (as mzXML must) instead // of the Agilent "scanID" (as this mzML-centric code expects) bool foundit = false; string[] nameValuePairs = spectrum.Id.Split(' '); foreach( string nvp in nameValuePairs ) { string[] nameValuePair = nvp.Split('='); if (row.Table.Columns.Contains(nameValuePair[0])) { row[nameValuePair[0]] = nameValuePair[1]; foundit = true; } } if (!foundit) { // mismatch between nativeID format and actual (probably mzXML) format // better to show an ill-fit match - eg "scan" (mzXML) and "scanID" (Agilent) // than no info at all string nativeIdDefinition = new CVTermInfo(nativeIdFormat).def; string[] idPair = nativeIdDefinition.Split('='); if (row.Table.Columns.Contains(idPair[0])) { string[] valPair = spectrum.Id.Split('='); row[idPair[0]] = (valPair.Length > 1) ? valPair[1] : spectrum.Id; foundit = true; } } } row.Index = spectrum.Index; updateRow( row, spectrum ); spectrumDataSet.SpectrumTable.AddSpectrumTableRow( row ); //int rowIndex = gridView.Rows.Add(); //gridView.Rows[rowIndex].Tag = spectrum; spectrum.Tag = this; if( spectrum.Element.spotID.Length > 0 ) gridView.Columns["SpotId"].Visible = true; //UpdateRow( rowIndex ); }
public MassSpectrum GetMassSpectrum( MassSpectrum metaSpectrum, string[] spectrumListFilters ) { var tmp = source.MSDataFile.run.spectrumList; try { SpectrumListFactory.wrap(source.MSDataFile, spectrumListFilters); return GetMassSpectrum(metaSpectrum, source.MSDataFile.run.spectrumList); } finally { source.MSDataFile.run.spectrumList = tmp; } }
public void updateRow( SpectrumDataSet.SpectrumTableRow row, MassSpectrum spectrum ) { spectrumList[spectrum.Index] = spectrum; Spectrum s = spectrum.Element; //GetElement(false); DataProcessing dp = spectrum.DataProcessing; Scan scan = null; InstrumentConfiguration ic = null; if(s.scanList.scans.Count > 0) { scan = s.scanList.scans[0]; ic = scan.instrumentConfiguration; } if( dp == null ) dp = s.dataProcessing; CVParam param; param = s.cvParam( CVID.MS_ms_level ); row.MsLevel = !param.empty() ? (int) param.value : 0; param = scan != null ? scan.cvParam( CVID.MS_scan_start_time ) : new CVParam(); row.ScanTime = !param.empty() ? (double) param.value : 0; param = s.cvParam( CVID.MS_base_peak_m_z ); row.BasePeakMz = !param.empty() ? (double) param.value : 0; param = s.cvParam( CVID.MS_base_peak_intensity ); row.BasePeakIntensity = !param.empty() ? (double) param.value : 0; param = s.cvParam( CVID.MS_total_ion_current ); row.TotalIonCurrent = !param.empty() ? (double) param.value : 0; StringBuilder precursorInfo = new StringBuilder(); if( row.MsLevel == 1 || s.precursors.Count == 0 ) precursorInfo.Append( "n/a" ); else { foreach( Precursor p in s.precursors ) { foreach( SelectedIon si in p.selectedIons ) { if( precursorInfo.Length > 0 ) precursorInfo.Append( "," ); precursorInfo.Append( (double) si.cvParam( CVID.MS_selected_ion_m_z ).value ); } } } if( precursorInfo.Length == 0 ) precursorInfo.Append( "unknown" ); row.PrecursorInfo = precursorInfo.ToString(); StringBuilder scanInfo = new StringBuilder(); foreach( Scan scan2 in s.scanList.scans ) { if( scan2.scanWindows.Count > 0 ) { foreach( ScanWindow sw in scan2.scanWindows ) { if( scanInfo.Length > 0 ) scanInfo.Append( "," ); scanInfo.AppendFormat( "[{0}-{1}]", (double) sw.cvParam( CVID.MS_scan_window_lower_limit ).value, (double) sw.cvParam( CVID.MS_scan_window_upper_limit ).value ); } } } if( scanInfo.Length == 0 ) scanInfo.Append( "unknown" ); row.ScanInfo = scanInfo.ToString(); row.SpotId = s.spotID; row.SpectrumType = s.cvParamChild( CVID.MS_spectrum_type ).name; row.DataPoints = s.defaultArrayLength; row.IcId = ( ic == null || ic.id.Length == 0 ? "unknown" : ic.id ); row.DpId = ( dp == null || dp.id.Length == 0 ? "unknown" : dp.id ); }
private MzLite.Model.MassSpectrum ReadMassSpectrum(int scanNo) { RaiseDisposed(); try { string spectrumID = GetSpectrumID(scanNo); MassSpectrum spectrum = new MassSpectrum(spectrumID); // spectrum int msLevel = GetMSLevel(rawFile, scanNo); spectrum.SetMsLevel(msLevel); if (IsCentroidSpectrum(rawFile, scanNo)) { spectrum.SetCentroidSpectrum(); } else { spectrum.SetProfileSpectrum(); } // scan Scan scan = new Scan(); scan.SetFilterString(GetFilterString(rawFile, scanNo)) .SetScanStartTime(GetRetentionTime(rawFile, scanNo)); //.UO_Minute(); spectrum.Scans.Add(scan); // precursor if (msLevel > 1) { Precursor precursor = new Precursor(); double isoWidth = GetIsolationWindowWidth(rawFile, scanNo, msLevel) * 0.5d; double targetMz = GetIsolationWindowTargetMz(rawFile, scanNo, msLevel); double precursorMz = GetPrecursorMz(rawFile, scanNo, msLevel); int chargeState = GetChargeState(rawFile, scanNo); precursor.IsolationWindow .SetIsolationWindowTargetMz(targetMz) .SetIsolationWindowUpperOffset(isoWidth) .SetIsolationWindowLowerOffset(isoWidth); SelectedIon selectedIon = new SelectedIon(); selectedIon .SetSelectedIonMz(precursorMz) .SetChargeState(chargeState); precursor.SelectedIons.Add(selectedIon); spectrum.Precursors.Add(precursor); } return(spectrum); } catch (Exception ex) { throw new MzLiteIOException(ex.Message, ex); } }
public MassSpectrum GetMassSpectrum( MassSpectrum metaSpectrum, SpectrumList spectrumList ) { MassSpectrum spectrum = new MassSpectrum( this, spectrumList.spectrum( metaSpectrum.Index, true ) ); spectrum.Tag = metaSpectrum.Tag; return spectrum; }