public FileData3 ReadFromFile(string fileName) { FileData3 result = new FileData3(); result.FileName = new FileInfo(fileName).Name; rawFile.Open(fileName); try { for (int scan = rawFile.GetFirstSpectrumNumber(); scan <= rawFile.GetLastSpectrumNumber(); scan++) { PeakList <Peak> pkl = rawFile.GetPeakList(scan, minPeakMz - 1, maxPeakMz + 1); result.AddPeaks(minPeakMz, maxPeakMz, scan, pkl); } } finally { rawFile.Close(); } return(result); }
public override IEnumerable <string> Process(string fileName) { string resultFile = new FileInfo(targetDir + "\\" + FileUtils.ChangeExtension(new FileInfo(fileName).Name, ".txt")).FullName; reader.Open(fileName); try { using (StreamWriter sw = new StreamWriter(resultFile)) { sw.NewLine = "\n"; sw.WriteLine(); sw.WriteLine("FUNCTION 1"); int firstScan = reader.GetFirstSpectrumNumber(); int lastScan = reader.GetLastSpectrumNumber(); for (int i = firstScan; i <= lastScan; i++) { var pkl = reader.GetPeakList(i); sw.WriteLine(""); sw.WriteLine("Scan\t\t{0}", i); sw.WriteLine("Retention Time\t{0:0.000}", reader.ScanToRetentionTime(i)); sw.WriteLine(""); foreach (var peak in pkl) { sw.WriteLine("{0:0.0000}\t{1:0}", peak.Mz, peak.Intensity); } } } } finally { reader.Close(); } return(new string[] { resultFile }); }
public void Update(object sender, UpdateQuantificationItemEventArgs e) { var summary = e.Item as SilacQuantificationSummaryItem; if (summary == null) { throw new ArgumentNullException("UpdateQuantificationItemEventArgs.Item cannot be null"); } ZedGraphicExtension.ClearData(zgcGraph, false); try { var envelope = summary.ObservedEnvelopes.Find(m => m.IsSelected); if (envelope == null) { return; } double minMz = envelope.Light[0].Mz - 1.0; double maxMz = envelope.Heavy[envelope.Heavy.Count - 1].Mz + 1.0; zgcGraph.GraphPane.XAxis.Scale.Min = minMz; zgcGraph.GraphPane.XAxis.Scale.Max = maxMz; var pplLight = new PointPairList(); envelope.Light.ForEach(p => pplLight.Add(p.Mz, p.Intensity)); var pplHeavy = new PointPairList(); envelope.Heavy.ForEach(p => pplHeavy.Add(p.Mz, p.Intensity)); if (summary.SampleIsLight) { ZedGraphicExtension.AddIndividualLine(zgcGraph, "Sample", pplLight, SilacQuantificationConstants.SAMPLE_COLOR, false); ZedGraphicExtension.AddIndividualLine(zgcGraph, "Reference", pplHeavy, SilacQuantificationConstants.REFERENCE_COLOR, false); } else { ZedGraphicExtension.AddIndividualLine(zgcGraph, "Sample", pplHeavy, SilacQuantificationConstants.SAMPLE_COLOR, false); ZedGraphicExtension.AddIndividualLine(zgcGraph, "Reference", pplLight, SilacQuantificationConstants.REFERENCE_COLOR, false); } // Shift the text items up by 5 user scale units above the bars const float shift = 5; var ppl = new PointPairList(); ppl.AddRange(pplLight); ppl.AddRange(pplHeavy); for (int i = 0; i < ppl.Count; i++) { // format the label string to have 1 decimal place string lab = ppl[i].X.ToString("0.00"); // create the text item (assumes the x axis is ordinal or text) // for negative bars, the label appears just above the zero value var text = new TextObj(lab, ppl[i].X, ppl[i].Y + shift); // tell Zedgraph to use user scale units for locating the TextItem text.Location.CoordinateFrame = CoordType.AxisXYScale; // AlignH the left-center of the text to the specified point text.Location.AlignH = AlignH.Left; text.Location.AlignV = AlignV.Center; text.FontSpec.Border.IsVisible = false; text.FontSpec.Fill.IsVisible = false; // rotate the text 90 degrees text.FontSpec.Angle = 90; // add the TextItem to the list zgcGraph.GraphPane.GraphObjList.Add(text); } if (File.Exists(summary.RawFilename)) { if (rawFile == null) { rawFile = new RawFileImpl(summary.RawFilename); } else if (!rawFile.FileName.Equals(summary.RawFilename)) { rawFile.Open(summary.RawFilename); } PeakList <Peak> pkl = rawFile.GetPeakList(envelope.Light.ScanTimes[0].Scan); var pplRaw = new PointPairList(); pplRaw.Add(minMz, 0.0); for (int i = 0; i < pkl.Count; i++) { if (pkl[i].Mz < minMz) { continue; } else if (pkl[i].Mz > maxMz) { break; } pplRaw.Add(pkl[i].Mz, -pkl[i].Intensity); } pplRaw.Add(maxMz, 0.0); ZedGraphicExtension.AddIndividualLine(zgcGraph, "PeakList From RawFile", pplRaw, SilacQuantificationConstants.IDENTIFIED_COLOR, true); } } finally { ZedGraphicExtension.UpdateGraph(zgcGraph); } }
public void Quantify(string rawFileName, List <IIdentifiedSpectrum> spectra, string detailDir) { if (!Directory.Exists(detailDir)) { Directory.CreateDirectory(detailDir); } var experimental = RawFileFactory.GetExperimental(rawFileName); Dictionary <string, DifferentRetentionTimeEnvelopes> spectrumKeyMap = new Dictionary <string, DifferentRetentionTimeEnvelopes>(); Dictionary <SilacEnvelopes, List <IIdentifiedSpectrum> > envelopeSpectrumGroup = new Dictionary <SilacEnvelopes, List <IIdentifiedSpectrum> >(); double precursorPPM = GetPrecursorPPM(spectra); try { _rawReader.Open(rawFileName); int firstScanNumber = _rawReader.GetFirstSpectrumNumber(); int lastScanNumber = _rawReader.GetLastSpectrumNumber(); Progress.SetRange(1, spectra.Count); int pepCount = 0; for (int s = 0; s < spectra.Count; s++) { Console.WriteLine(s); IIdentifiedSpectrum spectrum = spectra[s]; SilacQuantificationSummaryItem.ClearAnnotation(spectrum); if (Progress.IsCancellationPending()) { throw new UserTerminatedException(); } int startScan = spectrum.Query.FileScan.FirstScan; if (startScan > lastScanNumber) { spectrum.GetOrCreateQuantificationItem().RatioStr = "OUT_OF_RANGE"; continue; } Progress.SetPosition(pepCount++); IIdentifiedPeptide sp = spectrum.Peptide; string seq = GetMatchSequence(spectrum); IPeptideInfo peptideInfo = new IdentifiedPeptideInfo(seq, spectrum.TheoreticalMH, spectrum.Query.Charge); SilacCompoundInfo sci = GetSilacCompoundInfo(peptideInfo); //如果轻重离子理论质荷比一样,忽略 if (!sci.IsSilacData()) { spectrum.GetOrCreateQuantificationItem().RatioStr = "NOT_SILAC"; continue; } //如果轻重离子理论质荷比与观测值不一致,忽略 if (!sci.IsMzEquals(spectrum.ObservedMz, MAX_DELTA_MZ)) { ValidateModifications(seq); spectrum.GetOrCreateQuantificationItem().RatioStr = "WRONG_IDENTIFICATION"; continue; } //如果没有找到相应的FullScan,忽略 int identifiedFullScan = _rawReader.FindPreviousFullScan(startScan, firstScanNumber); if (-1 == identifiedFullScan) { spectrum.GetOrCreateQuantificationItem().RatioStr = "NO_PROFILE"; continue; } DifferentRetentionTimeEnvelopes pkls = FindEnvelopes(spectrumKeyMap, spectrum, sci); SilacEnvelopes envelope = pkls.FindSilacEnvelope(identifiedFullScan); //如果该scan被包含在已经被定量的结果中,忽略 if (envelope != null) { envelope.SetScanIdentified(identifiedFullScan, spectrum.IsExtendedIdentification()); envelopeSpectrumGroup[envelope].Add(spectrum); continue; } //从原始文件中找出该spectrum的定量信息 int maxIndex = Math.Min(option.ProfileLength - 1, pkls.LightProfile.FindMaxIndex()); double mzTolerance = PrecursorUtils.ppm2mz(sci.Light.Mz, option.PPMTolerance); //如果FullScan没有相应的离子,忽略。(鉴定错误或者扩展定量时候,会出现找不到pair的现象) SilacPeakListPair splp = GetLightHeavyPeakList(_rawReader, sci, maxIndex, mzTolerance, identifiedFullScan); if (null == splp) { spectrum.GetOrCreateQuantificationItem().RatioStr = "NO_PROFILE"; continue; } splp.IsIdentified = true; splp.IsExtendedIdentification = spectrum.IsExtendedIdentification(); SilacEnvelopes envelopes = new SilacEnvelopes(); envelopes.Add(splp); //向前查找定量信息 int fullScan = identifiedFullScan; int scanNumber = 0; while ((fullScan = _rawReader.FindPreviousFullScan(fullScan - 1, firstScanNumber)) != -1) { if (_rawReader.IsBadDataScan(fullScan)) { continue; } scanNumber++; var item = GetLightHeavyPeakList(_rawReader, sci, maxIndex, mzTolerance, fullScan, scanNumber <= MinScanNumber); if (null == item) { break; } envelopes.Add(item); } envelopes.Reverse(); //向后查找定量信息 fullScan = identifiedFullScan; scanNumber = 0; while ((fullScan = _rawReader.FindNextFullScan(fullScan + 1, lastScanNumber)) != -1) { if (_rawReader.IsBadDataScan(fullScan)) { continue; } scanNumber++; var item = GetLightHeavyPeakList(_rawReader, sci, maxIndex, mzTolerance, fullScan, scanNumber <= MinScanNumber); if (null == item) { break; } envelopes.Add(item); } //对每个scan计算轻重的离子丰度 envelopes.ForEach(m => m.CalculateIntensity(pkls.LightProfile, pkls.HeavyProfile)); pkls.Add(envelopes); envelopeSpectrumGroup.Add(envelopes, new List <IIdentifiedSpectrum>()); envelopeSpectrumGroup[envelopes].Add(spectrum); } } finally { _rawReader.Close(); } foreach (string key in spectrumKeyMap.Keys) { DifferentRetentionTimeEnvelopes pkls = spectrumKeyMap[key]; foreach (SilacEnvelopes envelopes in pkls) { if (0 == envelopes.Count) { continue; } List <IIdentifiedSpectrum> mps = envelopeSpectrumGroup[envelopes]; double mzTolerance = PrecursorUtils.ppm2mz(mps[0].Query.ObservedMz, option.PPMTolerance); string scanStr = GetScanRange(envelopes); string resultFilename = detailDir + "\\" + mps[0].Query.FileScan.Experimental + "." + PeptideUtils.GetPureSequence(mps[0].Sequence) + "." + mps[0].Query.Charge + scanStr + ".silac"; IPeptideInfo peptideInfo = new IdentifiedPeptideInfo(mps[0].GetMatchSequence(), mps[0].TheoreticalMH, mps[0].Query.Charge); SilacCompoundInfo sci = GetSilacCompoundInfo(peptideInfo); SilacQuantificationSummaryItem item = new SilacQuantificationSummaryItem(sci.Light.IsSample); item.RawFilename = rawFileName; item.SoftwareVersion = this.SoftwareVersion; item.PeptideSequence = mps[0].Sequence; item.Charge = mps[0].Charge; item.LightAtomComposition = sci.Light.Composition.ToString(); item.HeavyAtomComposition = sci.Heavy.Composition.ToString(); item.LightProfile = pkls.LightProfile; item.HeavyProfile = pkls.HeavyProfile; item.ObservedEnvelopes = envelopes; item.ValidateScans(sci, precursorPPM); item.Smoothing(); item.CalculateRatio(); new SilacQuantificationSummaryItemXmlFormat().WriteToFile(resultFilename, item); int maxScoreItemIndex = FindMaxScoreItemIndex(mps); for (int i = 0; i < mps.Count; i++) { if (maxScoreItemIndex == i) { item.AssignToAnnotation(mps[i], resultFilename); } else { item.AssignDuplicationToAnnotation(mps[i], resultFilename); } } } } foreach (IIdentifiedSpectrum mph in spectra) { mph.InitializeRatioEnabled(); } }
public override IEnumerable <string> Process(string fileName) { var result = new List <string>(); QueryItemListFormat format = new QueryItemListFormat(); FileInfo rawFile = new FileInfo(rawFileName); Progress.SetMessage("Reading query product ion from " + fileName); var queryItems = format.ReadFromFile(fileName); using (IRawFile reader = RawFileFactory.GetRawFileReader(rawFileName)) { reader.Open(rawFileName); int firstSpectrumNumber = reader.GetFirstSpectrumNumber(); LipidPrecursorQuery queryFunc = new LipidPrecursorQuery(reader); queryFunc.Progress = this.Progress; char[] chars = new char[] { '\t' }; int curIndex = 0; foreach (var query in queryItems) { Progress.SetMessage(MyConvert.Format("{0}/{1} - Querying precursor ions for product ion {2} ...", ++curIndex, queryItems.Count, query.ProductIonMz)); string savedQueryFile = GetQueryFileName(rawFileName, query.ProductIonMz, productIonPPM, precursorPPM); PrecursorItemListXmlFormat pilFormat = new PrecursorItemListXmlFormat(); List <PrecursorItem> precursors; if (!File.Exists(savedQueryFile)) { precursors = queryFunc.QueryPrecursorFromProductIon(query, productIonPPM, precursorPPM); pilFormat.WriteToFile(savedQueryFile, precursors); } else { precursors = pilFormat.ReadFromFile(savedQueryFile); } result.Add(savedQueryFile); var precursorMzs = (from item in precursors group item by item.PrecursorMZ into mzGroup let count = mzGroup.Where(m => m.PrecursorIntensity > 0).Count() orderby count descending select new PrecursorArea { PrecursorMz = mzGroup.Key, ScanCount = count, Area = 0.0 }).ToList(); //去掉冗余的precursor for (int i = precursorMzs.Count - 1; i >= 0; i--) { if (precursorMzs[i].ScanCount >= 5) { break; } for (int j = 0; j < i; j++) { if (precursorMzs[j].ScanCount < 5) { break; } double ppm = PrecursorUtils.mz2ppm(precursorMzs[i].PrecursorMz, Math.Abs(precursorMzs[i].PrecursorMz - precursorMzs[j].PrecursorMz)); if (ppm < precursorPPM) { precursorMzs.RemoveAt(i); break; } } } string savedDetailDir = FileUtils.ChangeExtension(savedQueryFile, ""); if (!Directory.Exists(savedDetailDir)) { Directory.CreateDirectory(savedDetailDir); } for (int i = 0; i < precursorMzs.Count; i++) { Progress.SetMessage(MyConvert.Format("{0}/{1} {2} - {3}/{4} Get chromotograph for precursor {5} ...", curIndex, queryItems.Count, query.ProductIonMz, i + 1, precursorMzs.Count, precursorMzs[i].PrecursorMz)); string targetFile = savedDetailDir + "\\" + GetDetailFileName(rawFileName, precursorMzs[i].PrecursorMz); var itemFormat = new LabelFreeSummaryItemXmlFormat(); LabelFreeSummaryItem item; if (File.Exists(targetFile)) { item = itemFormat.ReadFromFile(targetFile); } else { var ions = queryFunc.QueryChromotograph(precursorMzs[i].PrecursorMz, precursorPPM); int continueCount = 0; int firstIndex = -1; for (int j = 0; j < ions.Count; j++) { if (ions[j].Intensity > 0) { if (firstIndex == -1) { firstIndex = j; continueCount = 1; } else { continueCount++; if (continueCount >= 5) { break; } } } else { firstIndex = -1; continueCount = 0; } } if (continueCount >= 5) { ions.RemoveRange(0, firstIndex); } continueCount = 0; int lastIndex = -1; for (int j = ions.Count - 1; j >= 0; j--) { if (ions[j].Intensity > 0) { if (lastIndex == -1) { lastIndex = j; continueCount = 1; } else { continueCount++; if (continueCount >= 5) { break; } } } else { lastIndex = -1; continueCount = 0; } } if (continueCount >= 5) { ions.RemoveRange(lastIndex + 1, ions.Count - lastIndex - 1); } //get full ms corresponding to identified ms/ms var identified = new HashSet <int>(); foreach (var p in precursors) { if (p.PrecursorMZ == precursorMzs[i].PrecursorMz) { for (int j = p.Scan - 1; j >= firstSpectrumNumber; j--) { if (reader.GetMsLevel(j) == 1) { identified.Add(j); break; } } } } ions.ForEach(m => { m.Identified = identified.Contains(m.Scan); m.Enabled = true; }); Debug.Assert(ions.FindAll(m => m.Identified == true).Count == identified.Count); item = new LabelFreeSummaryItem() { RawFilename = rawFileName, Sequence = MyConvert.Format("{0:0.0000}; {1:0.00}", query.ProductIonMz, query.MinRelativeIntensity) }; item.AddRange(ions); item.CalculatePPM(precursorMzs[i].PrecursorMz); new LabelFreeSummaryItemXmlFormat().WriteToFile(targetFile, item); } precursorMzs[i].Area = item.GetArea(); string savedAreaFile = GetAreaFileName(rawFileName, query.ProductIonMz, productIonPPM, precursorPPM); new PrecursorAreaListTextFormat().WriteToFile(savedAreaFile, precursorMzs); } } return(result); } }
public override IEnumerable <string> Process(string targetDir) { foreach (var raw in rawFiles) { List <SimplePeakChro> waitingPeaks = new List <SimplePeakChro>(); foreach (var peak in targetPeaks) { string file = GetTargetFile(targetDir, raw, peak); if (force || !File.Exists(file)) { waitingPeaks.Add(peak); } else { var p = new SimplePeakChroXmlFormat().ReadFromFile(file); peak.MaxRetentionTime = p.MaxRetentionTime; peak.Peaks = p.Peaks; } } if (waitingPeaks.Count == 0) { continue; } rawReader.Open(raw); try { int firstScan = rawReader.GetFirstSpectrumNumber(); int lastScan = rawReader.GetLastSpectrumNumber(); var lastRt = rawReader.ScanToRetentionTime(lastScan); waitingPeaks.ForEach(m => { m.Peaks.Clear(); m.MaxRetentionTime = lastRt; }); Progress.SetMessage("Processing chromotograph extracting..."); Progress.SetRange(firstScan, lastScan); for (int scan = firstScan; scan <= lastScan; scan++) { if (rawReader.GetMsLevel(scan) != 1) { continue; } Progress.SetPosition(scan); if (Progress.IsCancellationPending()) { throw new UserTerminatedException(); } PeakList <Peak> pkl = rawReader.GetPeakList(scan); double rt = rawReader.ScanToRetentionTime(scan); foreach (var peak in waitingPeaks) { var env = pkl.FindPeak(peak.Mz, peak.MzTolerance); Peak findPeak = new Peak(peak.Mz, 0.0, 0); if (env.Count > 0) { if (env.Count == 1) { findPeak = env[0]; } else { var charge = env.FindCharge(peak.Charge); if (charge.Count > 0) { if (charge.Count == 1) { findPeak = charge[0]; } else { findPeak = charge.FindMaxIntensityPeak(); } } else { findPeak = env.FindMaxIntensityPeak(); } } } peak.Peaks.Add(new ScanPeak() { Mz = findPeak.Mz, Intensity = findPeak.Intensity, Scan = scan, RetentionTime = rt, Charge = findPeak.Charge, PPMDistance = PrecursorUtils.mz2ppm(peak.Mz, findPeak.Mz - peak.Mz) }); } } waitingPeaks.ForEach(m => m.TrimPeaks(minRetentionTime)); } finally { rawReader.Close(); } Progress.SetMessage("Saving ... "); foreach (var peak in waitingPeaks) { string file = GetTargetFile(targetDir, raw, peak); new SimplePeakChroXmlFormat().WriteToFile(file, peak); } Progress.SetMessage("Finished."); Progress.End(); } return(new string[] { targetDir }); }
public override IEnumerable <string> Process(string rawFilename) { string ms1Filename = GetResultFilename(rawFilename); string ms1IndexFilename = ms1Filename + ".index"; rawFile.Open(rawFilename); try { int firstScan = rawFile.GetFirstSpectrumNumber(); int lastScan = rawFile.GetLastSpectrumNumber(); int firstFullScan = 0; for (firstFullScan = firstScan; firstFullScan < lastScan; firstFullScan++) { if (rawFile.GetMsLevel(firstFullScan) == 1) { break; } } if (firstFullScan >= lastScan) { return(new List <string>()); } Progress.SetRange(firstScan, lastScan); using (var sw = new StreamWriter(ms1Filename)) { //write header sw.Write("H\tCreationDate\t{0:m/dd/yyyy HH:mm:ss}\n", DateTime.Now); sw.Write("H\tExtractor\t{0}\n", GetProgramName()); sw.Write("H\tExtractorVersion\t{0}\n", GetProgramVersion()); sw.Write("H\tComments\t{0} written by Quanhu Sheng, 2008-2009\n", GetProgramName()); sw.Write("H\tExtractorOptions\tMS1\n"); sw.Write("H\tAcquisitionMethod\tData-Dependent\n"); sw.Write("H\tDataType\tCentriod\n"); sw.Write("H\tScanType\tMS1\n"); sw.Write("H\tFirstScan\t{0}\n", firstScan); sw.Write("H\tLastScan\t{0}\n", lastScan); using (var swIndex = new StreamWriter(ms1IndexFilename)) { for (int scan = firstScan; scan <= lastScan; scan++) { if (Progress.IsCancellationPending()) { throw new UserTerminatedException(); } Progress.SetPosition(scan); if (rawFile.GetMsLevel(scan) == 1) { sw.Flush(); swIndex.Write("{0}\t{1}\n", scan, sw.BaseStream.Position); sw.Write("S\t{0}\t{0}\n", scan); sw.Write("I\tRetTime\t{0:0.####}\n", rawFile.ScanToRetentionTime(scan)); PeakList <Peak> pkl = rawFile.GetPeakList(scan); foreach (Peak p in pkl) { sw.Write("{0:0.0000} {1:0.0} {2}\n", p.Mz, p.Intensity, p.Charge); } } } } } } finally { rawFile.Close(); } Progress.End(); return(new[] { ms1Filename }); }
public void LoadFile() { reader.Open(TestContext.CurrentContext.TestDirectory + "/../../../data//QTof_itraq.mzData"); }
public override IEnumerable <string> Process(string targetDir) { foreach (var raw in rawFiles) { List <RetentionTimePeak> waitingPeaks = new List <RetentionTimePeak>(); foreach (var peak in targetPeaks) { string file = GetTargetFile(targetDir, raw, peak); if (force || !File.Exists(file)) { waitingPeaks.Add(peak); } } if (waitingPeaks.Count == 0) { continue; } rawReader.Open(raw); try { int firstScan = rawReader.GetFirstSpectrumNumber(); int lastScan = rawReader.GetLastSpectrumNumber(); waitingPeaks.ForEach(m => m.Chromotographs.Clear()); for (int scan = firstScan; scan <= lastScan; scan++) { if (rawReader.GetMsLevel(scan) != 1) { continue; } if (Progress.IsCancellationPending()) { throw new UserTerminatedException(); } PeakList <Peak> pkl = rawReader.GetPeakList(scan); double rt = rawReader.ScanToRetentionTime(scan); var st = new ScanTime(scan, rt); foreach (var peak in waitingPeaks) { var env = pkl.FindEnvelopeDirectly(peak.PeakEnvelope, peak.MzTolerance, () => new Peak()); env.ScanTimes.Add(st); peak.Chromotographs.Add(env); } } waitingPeaks.ForEach(m => m.TrimPeaks()); } finally { rawReader.Close(); } foreach (var peak in waitingPeaks) { string file = GetTargetFile(targetDir, raw, peak); new RetentionTimePeakXmlFormat().WriteToFile(file, peak); } } return(new string[] { targetDir }); }