/// <summary> /// /// Get top one peptide list from xtandem xml file /// /// </summary> /// <param name="fileName">xtandem xml filename</param> /// <returns>List of IIdentifiedSpectrum</returns> public List <IIdentifiedSpectrum> ReadFromFile(string fileName) { string sourceFilename = GetSourceFile(fileName); List <IIdentifiedSpectrum> result = new List <IIdentifiedSpectrum>(); XmlDocument doc = new XmlDocument(); doc.Load(fileName); this.xmlHelper = new XmlHelper(doc); XmlNode root = doc.DocumentElement; Match mSource = Regex.Match(sourceFilename, @"(.+)\.(?:RAW)", RegexOptions.IgnoreCase); if (mSource.Success) { sourceFilename = mSource.Groups[1].Value; } else { mSource = Regex.Match(sourceFilename, @"(.+?)\."); if (mSource.Success) { sourceFilename = mSource.Groups[1].Value; } } XmlNode parameters = xmlHelper.GetFirstChildByNameAndAttribute(root, "group", "label", "input parameters"); ParseParameters(parameters); int pos = sourceFilename.LastIndexOfAny(new char[] { '/', '\\' }); string rawFileName; if (pos > 0) { rawFileName = sourceFilename.Substring(pos + 1); } else { rawFileName = sourceFilename; } rawFileName = FileUtils.ChangeExtension(rawFileName, ""); List <XmlNode> groupNodes = xmlHelper.GetChildrenByNameAndAttribute(root, "group", "type", "model"); foreach (XmlNode groupNode in groupNodes) { Dictionary <string, IIdentifiedPeptide> pepmap = new Dictionary <string, IIdentifiedPeptide>(); IIdentifiedSpectrum spectrum = new IdentifiedSpectrum(); List <XmlNode> proteins = xmlHelper.GetChildren(groupNode, "protein"); foreach (XmlNode proteinNode in proteins) { XmlNode domainNode = xmlHelper.GetValidChild(xmlHelper.GetValidChild(proteinNode, "peptide"), "domain"); int numMissedCleavages = int.Parse(domainNode.Attributes["missed_cleavages"].Value); string preSeq = domainNode.Attributes["pre"].Value; if (preSeq.Equals("[")) { preSeq = "-"; } string postSeq = domainNode.Attributes["post"].Value; if (postSeq.Equals("]")) { postSeq = "-"; } StringBuilder pepSeqSB = new StringBuilder(domainNode.Attributes["seq"].Value); int start = int.Parse(domainNode.Attributes["start"].Value); int end = int.Parse(domainNode.Attributes["end"].Value); List <XmlNode> modifications = xmlHelper.GetChildren(domainNode, "aa"); if (modifications.Count > 0) { List <ModificationItem> items = new List <ModificationItem>(); foreach (XmlNode modification in modifications) { int at = int.Parse(modification.Attributes["at"].Value); if (at < start || at > end) { continue; } ModificationItem item = new ModificationItem(); item.Type = modification.Attributes["type"].Value; item.At = at; item.Modified = MyConvert.ToDouble(modification.Attributes["modified"].Value); if (!staticModifications.ContainsKey(item.Type[0])) { items.Add(item); } } spectrum.Modifications = ""; if (items.Count > 0) { items.Sort((m1, m2) => m1.At - m2.At); var mod = ""; foreach (ModificationItem item in items) { mod = mod + MyConvert.Format(",{0}({1:0.0000})", item.Type, item.Modified); } spectrum.Modifications = mod.Substring(1); items.Sort((m1, m2) => m2.At - m1.At); foreach (ModificationItem item in items) { var key = GetModifiedKey(item.Modified); if (!dynamicModificationChars.ContainsKey(key)) { AddDynamicModificationChar(key); } char modificationChar = dynamicModificationChars[key]; pepSeqSB.Insert(item.At - start + 1, modificationChar.ToString()); } spectrum.Modifications = mod.Substring(1); } } StringBuilder sb = new StringBuilder(); sb.Append(preSeq.Substring(preSeq.Length - 1)); sb.Append("."); sb.Append(pepSeqSB.ToString()); sb.Append("."); sb.Append(postSeq[0]); string pepSeq = sb.ToString(); if (!pepmap.ContainsKey(pepSeq)) { IdentifiedPeptide pep = new IdentifiedPeptide(spectrum); pep.Sequence = pepSeq; pepmap[pepSeq] = pep; spectrum.TheoreticalMH = MyConvert.ToDouble(domainNode.Attributes["mh"].Value); spectrum.Score = MyConvert.ToDouble(domainNode.Attributes["hyperscore"].Value); double nextScore = MyConvert.ToDouble(domainNode.Attributes["nextscore"].Value); spectrum.DeltaScore = (spectrum.Score - nextScore) / spectrum.Score; spectrum.NumMissedCleavages = int.Parse(domainNode.Attributes["missed_cleavages"].Value); } var noteNode = xmlHelper.GetValidChild(proteinNode, "note"); string proteinName = noteNode.InnerText.StringBefore(" ").StringBefore("\t"); pepmap[pepSeq].AddProtein(proteinName); } if (spectrum.Peptides.Count > 0) { spectrum.DigestProtease = protease; result.Add(spectrum); spectrum.Query.QueryId = int.Parse(groupNode.Attributes["id"].Value); spectrum.ExperimentalMH = MyConvert.ToDouble(groupNode.Attributes["mh"].Value); spectrum.ExpectValue = MyConvert.ToDouble(groupNode.Attributes["expect"].Value); XmlNode spectrumNode = xmlHelper.GetFirstChildByNameAndAttribute(groupNode, "group", "label", "fragment ion mass spectrum"); XmlNode labelNode = xmlHelper.GetFirstChildByNameAndAttribute(spectrumNode, "note", "label", "Description"); string title = labelNode.InnerText.Trim(); if (title.StartsWith("RTINSECONDS")) { var rtvalue = title.StringAfter("=").StringBefore(" ").StringBefore("-"); spectrum.Query.FileScan.RetentionTime = double.Parse(rtvalue); title = title.StringAfter(" ").Trim(); } SequestFilename sf = this.TitleParser.GetValue(title); if (sf.Experimental == null || sf.Experimental.Length == 0) { sf.Experimental = sourceFilename; } spectrum.Query.FileScan.LongFileName = sf.LongFileName; if (sf.RetentionTime > 0 && spectrum.Query.FileScan.RetentionTime == 0) { spectrum.Query.FileScan.RetentionTime = sf.RetentionTime; } spectrum.Query.Charge = int.Parse(groupNode.Attributes["z"].Value); spectrum.Query.Title = title; } } return(result); }
public override string ToString() { return(MyConvert.Format("SignalToNoise >= {0:0.0}", minSignalToNoise)); }
public override List <IIdentifiedSpectrum> ReadFromFile(string fileName) { var result = new List <IIdentifiedSpectrum>(); //检查dta文件与out文件数目是否匹配,以防止数据库搜索出错。 using (var s = new ZipInputStream(new FileInfo(fileName).OpenRead())) { int dtacount = 0; int outcount = 0; ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { var name = theEntry.Name.ToLower(); if (name.EndsWith(".out")) { outcount++; } else if (name.EndsWith(".dta")) { dtacount++; } } if (dtacount != 0 && outcount != dtacount) { throw new Exception(MyConvert.Format("Dta file count ({0}) in {1} is not equals to out file count ({2})", dtacount, fileName, outcount)); } } using (var s = new ZipInputStream(new FileInfo(fileName).OpenRead())) { Progress.SetRange(1, new FileInfo(fileName).Length); long length = 0; ZipEntry theEntry; while ((theEntry = s.GetNextEntry()) != null) { if (Progress.IsCancellationPending()) { throw new UserTerminatedException(); } if (theEntry.IsDirectory) { continue; } string entryFileName = Path.GetFileName(theEntry.Name); if (entryFileName != String.Empty && entryFileName.ToLower().EndsWith(".out")) { List <string> context = new List <string>(); StreamReader sr = new StreamReader(s); while (!sr.EndOfStream) { context.Add(sr.ReadLine()); } IIdentifiedSpectrum spectrum = this.parser.Parse(context); if (null != spectrum) { result.Add(spectrum); } } length += theEntry.Size; Progress.SetPosition(length); } Progress.End(); } return(result); }
public override void Update(object sender, UpdateQuantificationItemEventArgs e) { IQuantificationSummaryOption option = e.Option as IQuantificationSummaryOption; IIdentifiedResult mr = e.Item as IIdentifiedResult; panel.InitGraphPane(title, option.Func.ReferenceKey, option.Func.SampleKey, true, 0.0); try { var pplNormal = new PointPairList(); var pplSelected = new PointPairList(); var pplOutlier = new PointPairList(); var groups = (from g in mr where option.IsProteinRatioValid(g[0]) select g).ToList(); foreach (var group in groups) { PointPairList ppl; if (group.Selected) { ppl = pplSelected; } else if (option.IsProteinOutlier(group[0])) { ppl = pplOutlier; } else { ppl = pplNormal; } double sampleIntensity = option.Func.GetSampleIntensity(group[0]); double refIntensity = option.Func.GetReferenceIntensity(group[0]); ppl.Add(refIntensity, sampleIntensity); ppl[ppl.Count - 1].Tag = group; Debug.Assert(ppl[ppl.Count - 1].Tag == group); } this.panel.ClearData(); this.panel.AddPoints(pplOutlier, OutlierColor, "Outlier"); this.panel.AddPoints(pplSelected, GroupColor, "Current Protein"); this.panel.AddPoints(pplNormal, NormalColor, "Other"); var pplTotal = new PointPairList(); pplTotal.AddRange(pplSelected); pplTotal.AddRange(pplNormal); pplTotal.AddRange(pplOutlier); if (pplTotal.Count > 0) { var maxValue = (from p in pplTotal select Math.Max(p.X, p.Y)).Max() * 1.1; this.panel.XAxis.Scale.Max = maxValue; this.panel.YAxis.Scale.Max = maxValue; var lrrr = pplTotal.GetRegression(); PointPairList line = pplTotal.GetRegressionLine(lrrr.Ratio); var lineItem = this.panel.AddCurve(MyConvert.Format("Ratio={0:0.0000}", lrrr.Ratio), line, Color.Red, SymbolType.None); } } finally { ZedGraphicExtension.UpdateGraph(this.zgcGraph); } }
public override string ToString() { return(MyConvert.Format("MinimumEnabledScan >= {0}", minEnabledScan)); }
private static XElement PeakListToElement(PeakList <Peak> pkls, string pklName, bool isPeakInWindow) { var result = new XElement(pklName, from p in pkls select new XElement("Peak", new XAttribute("mz", MyConvert.Format("{0:0.#####}", p.Mz)), new XAttribute("intensity", MyConvert.Format("{0:0.0}", p.Intensity)), new XAttribute("charge", p.Charge), isPeakInWindow ? new XAttribute("tag", p.Tag) : null )); if (isPeakInWindow) { result.Add(new XElement("Precursor", new XElement("MasterScan", pkls.Precursor.MasterScan), new XElement("MonoIsotopicMass", string.Format("{0:0.00000}", pkls.Precursor.MonoIsotopicMass)), new XElement("IsolationMass", string.Format("{0:0.00000}", pkls.Precursor.IsolationMass)), new XElement("IsolationWidth", string.Format("{0:0.00}", pkls.Precursor.IsolationWidth)), new XElement("Charge", pkls.Precursor.Charge), new XElement("Intensity", string.Format("{0:0.0}", pkls.Precursor.Intensity)))); } return(result); }
public SimplePeakChro ReadFromFile(string fileName) { var result = new SimplePeakChro(); var root = XElement.Load(fileName); result.Sequence = root.Element("Sequence").Value; result.Mz = MyConvert.ToDouble(root.Element("Mz").Value); result.MzTolerance = MyConvert.ToDouble(root.Element("MzTolerance").Value); result.Charge = Convert.ToInt32(root.Element("Charge").Value); result.MaxRetentionTime = MyConvert.ToDouble(root.Element("MaxRT").Value); var chro = root.Element("Chro"); result.Peaks = (from p in chro.Elements("Peak") let scan = Convert.ToInt32(p.Attribute("s").Value) let mz = MyConvert.ToDouble(p.Attribute("m").Value) let intensity = MyConvert.ToDouble(p.Attribute("i").Value) let charge = Convert.ToInt32(p.Attribute("c").Value) let rt = MyConvert.ToDouble(p.Attribute("r").Value) let ioninjectiontime = MyConvert.ToDouble(p.Attribute("t").Value) let identified = Convert.ToBoolean(p.Attribute("d").Value) let ppmdistance = MyConvert.ToDouble(p.Attribute("p").Value) select new ScanPeak() { Scan = scan, Mz = mz, Intensity = intensity, Charge = charge, RetentionTime = rt, IonInjectionTime = ioninjectiontime, Identified = identified, PPMDistance = ppmdistance }).ToList(); return(result); }
public override IEnumerable <string> Process(string targetFilename) { Dictionary <string, List <CensusPeptideItem> > peptideMap = new Dictionary <string, List <CensusPeptideItem> >(); CensusResultFormat crf = new CensusResultFormat(true, isLabelFree); Progress.SetRange(1, sourceFilenames.Length + 1); for (int i = 0; i < sourceFilenames.Length; i++) { string f = sourceFilenames[i]; Progress.SetMessage("Reading from " + f + "..."); Progress.SetPosition(i + 1); List <CensusPeptideItem> peptides = crf.ReadPeptides(f); foreach (CensusPeptideItem cpi in peptides) { if (!peptideMap.ContainsKey(cpi.Sequence)) { peptideMap[cpi.Sequence] = new List <CensusPeptideItem>(); } peptideMap[cpi.Sequence].Add(cpi); } } List <string> sequences = new List <string>(peptideMap.Keys); sequences.Sort(delegate(string seq1, string seq2) { int result = peptideMap[seq2].Count - peptideMap[seq1].Count; if (0 == result) { result = seq1.CompareTo(seq2); } return(result); }); Progress.SetMessage("Writing to " + targetFilename + "..."); using (var sw = new StreamWriter(targetFilename)) { sw.WriteLine("PLINE\tSEQUENCE\tS_INT/R_INT\tINT(S)\tINT(R)"); sw.WriteLine(crf.PeptideFormat.GetHeader()); foreach (string seq in sequences) { List <CensusPeptideItem> items = peptideMap[seq]; double sInt = 0.0; double rInt = 0.0; foreach (CensusPeptideItem item in items) { sInt += item.SampleIntensity; rInt += item.ReferenceIntensity; } double ratio; if (rInt != 0.0) { ratio = sInt / rInt; } else { ratio = 0.0; } sw.WriteLine(MyConvert.Format("P\t{0}\t{1:0.00}\t{2:0.0}\t{3:0.0}", seq, ratio, sInt, rInt)); foreach (CensusPeptideItem item in items) { sw.WriteLine(crf.PeptideFormat.GetString(item)); } } } Progress.SetMessage("Write to " + targetFilename + " finished."); Progress.SetPosition(sourceFilenames.Length + 1); return(new[] { targetFilename }); }
} /* _nnls_g1 */ /****************************************************************************/ /****************************************************************************/ /** * Construction and/or application of a single Householder transformation: * Q = I + U*(U**T)/B * * Function returns 0 if succesful, or >0 in case of erroneous parameters. * */ private static int _nnls_h12( /** mode=1 to construct and apply a Householder transformation, or * mode=2 to apply a previously constructed transformation */ int mode, /** Index of the pivot element */ int lpivot, /** Transformation is constructed to zero elements indexed from l1 to M */ int l1, /** Transformation is constructed to zero elements indexed from l1 to M */ int m, /** With mode=1: On entry, u[] must contain the pivot vector. * On exit, u[] and up contain quantities defining the vector u[] of * the Householder transformation. * With mode=2: On entry, u[] and up should contain quantities previously * computed with mode=1. These will not be modified. */ double[] u, /** u_dim1 is the storage increment between elements. */ int u_dim1, /** With mode=1: On entry, u[] must contain the pivot vector. * On exit, u[] and up contain quantities defining the vector u[] of * the Householder transformation. * With mode=2: On entry, u[] and up should contain quantities previously * computed with mode=1. These will not be modified. */ ref double up, /** On entry, cm[] must contain the matrix (set of vectors) to which the * Householder transformation is to be applied. On exit, cm[] will contain * the set of transformed vectors */ double[] cm, /** Storage increment between elements of vectors in cm[] */ int ice, /** Storage increment between vectors in cm[] */ int icv, /** Nr of vectors in cm[] to be transformed; * if ncv<=0, then no operations will be done on cm[] */ int ncv) { double d1, d2, b, clinv, cl, sm; int incr, k, j, i2, i3, i4; /* Check parameters */ if (mode != 1 && mode != 2) { throw new ArgumentException("Mode should be in {0,1}, now is " + mode); } if (m < 1 || u_dim1 < 1) { throw new ArgumentException(MyConvert.Format("m and u_dim1 should larger than 1, now is {0} and {1}", m, u_dim1)); } if (lpivot < 0 || lpivot >= l1 || l1 >= m) { return(0); } /* Function Body */ d1 = u[lpivot * u_dim1]; cl = Math.Abs(d1); if (mode == 2) { /* Apply transformation I+U*(U**T)/B to cm[] */ if (cl <= 0.0) { return(0); } } else { /* Construct the transformation */ for (j = l1; j < m; j++) { /* Computing MAX */ d1 = u[j * u_dim1]; d2 = Math.Abs(d1); if (d2 > cl) { cl = d2; } } if (cl <= 0.0) { return(0); } clinv = 1.0 / cl; /* Computing 2nd power */ d1 = u[lpivot * u_dim1] * clinv; sm = d1 * d1; for (j = l1; j < m; j++) { d1 = u[j * u_dim1] * clinv; sm += d1 * d1; } cl *= Math.Sqrt(sm); if (u[lpivot * u_dim1] > 0.0) { cl = -cl; } up = u[lpivot * u_dim1] - cl; u[lpivot * u_dim1] = cl; } if (ncv <= 0) { return(0); } b = up * u[lpivot * u_dim1]; /* b must be nonpositive here; if b>=0., then return */ if (b >= 0.0) { return(0); } b = 1.0 / b; i2 = 1 - icv + ice * lpivot; incr = ice * (l1 - lpivot); for (j = 0; j < ncv; j++) { i2 += icv; i3 = i2 + incr; i4 = i3; sm = cm[i2 - 1] * up; for (k = l1; k < m; k++) { sm += cm[i3 - 1] * u[k * u_dim1]; i3 += ice; } if (sm != 0.0) { sm *= b; cm[i2 - 1] += sm * up; for (k = l1; k < m; k++) { cm[i4 - 1] += sm * u[k * u_dim1]; i4 += ice; } } } return(0); } /* _nnls_h12 */
public static void Read(this System.IO.Stream s, ref string value, int fixLength) { value = MyConvert.ToString(Common.Extensions.ReadBytes(s, fixLength)); }
public static void Write(this System.IO.Stream s, string value, int fixLength) { s.Write(MyConvert.ToBytes(value, fixLength)); }
static void Main(string[] args) { TKM.IO.IIO io; do { Console.WriteLine("Press 1 to console input/output mode"); Console.WriteLine("Press 0 to exit\n"); ConsoleKeyInfo kc = Console.ReadKey(true); switch (kc.KeyChar) { case '0': return; default: io = new TKM.IO.IOConsole(); break; } do { Function f = new Function(io.Get()); Analyzer ar = new Analyzer(f); io.Set( "Truth table\n\n" + MyConvert.StringArrayToString(f.Names) + "f\n" + MyConvert.BoolArrayToString(f.Table) + "\n" + "Pascal's triangle\n\n" + MyConvert.BoolArrayToString(ar.Triangle) + "\n" + "Gegalkin Polynom\n\n" + MyConvert.StringArrayToString(ar.GegalkinPolynome, "+") + "\n" ); io.Set("Derivatives weights"); for (int arg = 0; arg < f.Names.Length; arg++) { io.Set( "\n" + "|" + f.Names[arg] + "| = " + ar.DerivativesWeights[arg] ); } io.Set( "\nVariables priority\n\n" + MyConvert.StringArrayToString(ar.VarStek) + "\n\n" + "Values at nodes(in contact circuit)\n\n" + MyConvert.StringArrayToString(ar.Shannon.ValueInNodes, "\n", true) + "\n" + "Adjacency matrix\n\n" + MyConvert.StringArrayToString(ar.Shannon.AMatrix, " ") + "\n" ); Console.WriteLine("Press Y to main menu/N to continue"); kc = Console.ReadKey(true); if (kc.KeyChar == 'y' || kc.KeyChar == 'Y') { break; } } while (true); Console.WriteLine("Press Y to exit/N to continue"); kc = Console.ReadKey(true); if (kc.KeyChar == 'y' || kc.KeyChar == 'Y') { break; } } while (true); }
public override void SetProperty(T t, string value) { t.MolecularWeight = MyConvert.ToDouble(value); }
public override string GetProperty(T t) { return(MyConvert.Format("{0:0.00}", t.MolecularWeight)); }
private string GetNameAttributeXPath(string childName, string attributeName, string attributeValue) { return(MyConvert.Format("{0}[@{1}=\"{2}\"]", GetNameXPath(childName), attributeName, attributeValue)); }
private void WriteXmlHeader(StreamWriter sw, FileInfo sourceFile, List <int> scans) { /* * xml header and namespace info */ sw.Write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>" + lf + "<mzXML" + lf); sw.Write(" xmlns=\"http://sashimi.sourceforge.net/schema_revision/mzXML_2.0\"" + lf + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + lf + " xsi:schemaLocation=\"http://sashimi.sourceforge.net/schema_revision/mzXML_2.0 http://sashimi.sourceforge.net/schema_revision/mzXML_2.0/mzXML_idx_2.0.xsd\">" + lf); int firstScan = this.rawFile.GetFirstSpectrumNumber(); int lastScan = this.rawFile.GetLastSpectrumNumber(); double startTime = this.rawFile.ScanToRetentionTime(firstScan) * 60; double endTime = this.rawFile.ScanToRetentionTime(lastScan) * 60; /* * begin msRun */ sw.Write(MyConvert.Format(" <msRun scanCount=\"{0}\" startTime=\"PT{1:0.000}S\" endTime=\"PT{2:0.000}S\">" + lf, scans.Count, startTime, endTime)); string sha1; try { sha1 = HashUtils.GetSHA1Hash(sourceFile.FullName).ToLower(); } catch (Exception ex) { throw new Exception("Exception when calculating sha1 value of file " + sourceFile.Name, ex); } /* * parent (raw input) file */ sw.Write(" <parentFile fileName=\"file://" + sourceFile.Name + "\" fileType=\"RAWData\" fileSha1=\"" + sha1 + "\"/>" + lf); /* * mass spec instrument section */ // get the instrument model string instModel = this.rawFile.GetInstModel(); // get acquisition software version string instSoftVersion = this.rawFile.GetInstSoftwareVersion(); sw.Write(" <msInstrument>" + lf + " <msManufacturer category=\"msManufacturer\" value=\"Thermo Finnigan\"/>" + lf + " <msModel category=\"msModel\" value=\"" + instModel + "\"/>" + lf + " <msIonisation category=\"msIonisation\" value=\"ESI\"/>" + lf + " <msMassAnalyzer category=\"msMassAnalyzer\" value=\"Ion Trap\"/>" + lf + " <msDetector category=\"msDetector\" value=\"EMT\"/>" + lf); sw.Write(" <software type=\"acquisition\"" + lf + " name=\"Xcalibur\"" + lf + " version=\"" + instSoftVersion + "\"/>" + lf + " </msInstrument>" + lf); /* * data processing info */ sw.Write(" <dataProcessing centroided=\"" + (this.doCentroid ? 1 : 0) + "\">" + lf + " <software type=\"conversion\"" + lf + " name=\"" + this.dataProcessingSoftware + "\"" + lf + " version=\"" + this.dataProcessingSoftwareVersion + "\"/>" + lf); foreach (string dataProcessingOperationName in this.dataProcessingOperations.Keys) { sw.Write(MyConvert.Format(" <processingOperation name=\"{0}\"" + lf + " value=\"{1}\"/>" + lf, dataProcessingOperationName, this.dataProcessingOperations[dataProcessingOperationName])); } /* * if (MIN_PEAKS_PER_SPECTRA > 0) * { * // Note the use of the namevaluetype element! * m_fout << " <processingOperation name=\"min_peaks_per_spectra\"" << lf * << " value=\"" << MIN_PEAKS_PER_SPECTRA << "\"/>" << lf; * // And the comment field to give a little bit more information about the meaning of * // the last element. * m_fout << " <comment>Scans with total number of peaks less than min_peaks_per_spectra were not included in this XML file</comment>" << lf; * } */ sw.Write(" </dataProcessing>" + lf); // end data processing info }
public override void WriteToFile(string fileName, IsobaricResult t) { var xle = new XElement("ITraqResult", from item in t let ions = new XElement("Ions", from def in item.Definition.Items select new XElement(def.Name, MyConvert.Format("{0:0.0}", item[def.Index]))) select new XElement("ITraqScan", new XElement("PlexType", item.PlexType), new XElement("Experimental", item.Experimental), new XElement("ScanMode", item.ScanMode), new XElement("Scan", item.Scan.Scan), new XElement("IonInjectionTime", MyConvert.Format("{0:0.000}", item.Scan.IonInjectionTime)), new XElement("PrecursorPercentage", MyConvert.Format("{0:0.000}", item.PrecursorPercentage)), new XElement("RetentionTime", MyConvert.Format("{0:0.0}", item.Scan.RetentionTime)), ions, PeakListToElement(item.RawPeaks, "RawPeaks", false), PeakListToElement(item.PeakInIsolationWindow, "PeakInIsolationWindow", true) )); xle.Save(fileName); }
private void WriteXmlScan(StreamWriter sw, int scan, List <Pair <int, long> > scanIndeies) { sw.Flush(); scanIndeies.Add(new Pair <int, long>(scan, sw.BaseStream.Position)); var rcf = new RawScanFilter(); rcf.Filter = this.rawFile.GetFilterForScanNum(scan); double retentionTime = this.rawFile.ScanToRetentionTime(scan); PeakList <Peak> pkl = this.rawFile.GetMassListFromScanNum(scan, this.doCentroid); /* scan header info begin */ int numPakets = 0; double RT = 0; double lowMass = 0; double highMass = 0; double TIC = 0; double basePeakMass = 0; double basePeakIntensity = 0; int channel = 0; int uniformTime = 0; double frequency = 0; this.rawFile.GetScanHeaderInfoForScanNum( scan, ref numPakets, ref RT, ref lowMass, ref highMass, ref TIC, ref basePeakMass, ref basePeakIntensity, ref channel, ref uniformTime, ref frequency); sw.Write(MyConvert.Format(" <scan num=\"{0}\"" + lf + " msLevel=\"{1}\"" + lf + " peaksCount=\"{2}\"" + lf + " polarity=\"{3}\"" + lf + " scanType=\"{4}\"" + lf + " retentionTime=\"PT{5:0.00}S\"" + lf, scan, rcf.MsLevel, pkl.Count, rcf.Polarity, rcf.ScanType, retentionTime * 60)); if (rcf.MsLevel > 1) { sw.Write(" collisionEnergy=\"{0:0}\"" + lf, rcf.CollisionEnergy); } sw.Write(MyConvert.Format(" lowMz=\"{0:0}\"" + lf + " highMz=\"{1:0}\"" + lf + " basePeakMz=\"{2:0.000}\"" + lf + " basePeakIntensity=\"{3:0}\"" + lf + " totIonCurrent=\"{4}\">" + lf, lowMass, highMass, basePeakMass, basePeakIntensity, TIC)); if (rcf.MsLevel > 1) { this.rawFile.GetPeakListInfo(scan, pkl); sw.Write(MyConvert.Format(" <precursorMz precursorIntensity=\"{0:0.#####}\"", pkl.PrecursorIntensity)); if (pkl.PrecursorCharge > 0) { sw.Write(" precursorCharge=\"" + pkl.PrecursorCharge + "\""); } sw.Write(">"); sw.Write(MyConvert.Format("{0:0.######}</precursorMz>" + lf, pkl.PrecursorMZ)); } /* scan header info end */ /* peak list info begin */ sw.Write(" <peaks precision=\"32\"" + lf + " byteOrder=\"network\"" + lf + " pairOrder=\"m/z-int\">"); sw.Write(MzxmlHelper.PeakListToBase64(pkl) + "</peaks>" + lf); /* peak list info end */ //I don't care if this scan is an child of last scan, just close it sw.Write(" </scan>" + lf); }
public override string IsValidated() { var b = true; string validationResult = ""; var isCityOfToronto = false; //Leadtime if (BaseValue.Deadline <= DateTime.Today) { validationResult += "Lead time is 5 business days " + System.Environment.NewLine; b = false; } else { var endDate = Convert.ToDateTime(BaseValue.Deadline); if (MyDateTime.GetDiffHoursOfWeekday(DateTime.Today, endDate) < 24 * NLeadTime) { validationResult += "Lead time is 5 business days " + System.Environment.NewLine; b = false; } } if (MyConvert.ConvertToString(Value.OccupationTimeStart).Length < 3) { validationResult += "Occupation Start Time Required" + System.Environment.NewLine; b = false; } if (MyConvert.ConvertToString(Value.OccupationTimeEnd).Length < 3) { validationResult += "Occupation End Time Required" + System.Environment.NewLine; b = false; } // if (Value.TypeOfTruck == 0) { validationResult += "Please Fill out Type of Truck " + System.Environment.NewLine; b = false; } //Installation Address var msc = new MySalesJobMasterListCustomer(BaseValue.JobID); msc.SetInstallTo(); if (msc.CustomerID == 0) { validationResult += "No Installation Company Selected " + System.Environment.NewLine; b = false; } else { var mc = new MyCustomer(msc.CustomerID); var customer = mc.Value; if (MyConvert.ConvertToString(customer.ADDR_1).Length < 5) { validationResult += "No Installation Address " + System.Environment.NewLine; b = false; } if (MyConvert.ConvertToString(customer.CITY).Length < 3) { validationResult += "Landlord City Required " + System.Environment.NewLine; b = false; } else { isCityOfToronto = GetIsCityOfToronto(customer.CITY); } if (MyConvert.ConvertToString(customer.ZIPCODE).Length < 4) { validationResult += "Landlord Postcode Required " + System.Environment.NewLine; b = false; } } if (MyConvert.ConvertToString(Value.ForemanName).Length < 2) { validationResult += "Foreman Name Required" + System.Environment.NewLine; b = false; } if (MyConvert.ConvertToString(Value.ForemanPhone).Length < 9) { validationResult += "Foreman Name Required" + System.Environment.NewLine; b = false; } //301 Insurance 2 30 //302 Additional Insurance for City of Toronto 2 30 //Document Attached int docTypeID = 301; var docAttached = _db.PermitDocuments.Where(x => x.BaseAppID == BaseValue.BaseAppID & x.DocType == docTypeID).ToList(); if (!docAttached.Any( )) { var docType = _db.PermitDocumentTypes.Find(docTypeID); validationResult += "Document Required: " + docType.TypeName + System.Environment.NewLine; b = false; } //302 Additional Insurance for City of Toronto 2 30 if (isCityOfToronto) { docTypeID = 302; docAttached = _db.PermitDocuments.Where(x => x.BaseAppID == BaseValue.BaseAppID & x.DocType == docTypeID).ToList(); if (!docAttached.Any()) { var docType = _db.PermitDocumentTypes.Find(docTypeID); validationResult += "Document Required: " + docType.TypeName + System.Environment.NewLine; b = false; } } return(b ? "ok" : validationResult); }
public string GetOriginalITraqFileName(string rawFileName) { return(MyConvert.Format("{0}.oitraq.xml", rawFileName)); }
public void WriteToFile(string fileName, SimplePeakChro t) { XElement root = new XElement("SimplePeakChro", new XElement("Sequence", t.Sequence), new XElement("Mz", MyConvert.Format("{0:0.00000}", t.Mz)), new XElement("MzTolerance", MyConvert.Format("{0:0.00000}", t.MzTolerance)), new XElement("Charge", t.Charge), new XElement("MaxRT", MyConvert.Format("{0:0.0000}", t.MaxRetentionTime)), new XElement("Chro", from p in t.Peaks select new XElement("Peak", new XAttribute("s", p.Scan), new XAttribute("m", MyConvert.Format("{0:0.00000}", p.Mz)), new XAttribute("i", MyConvert.Format("{0:0.00000}", p.Intensity)), new XAttribute("c", p.Charge), new XAttribute("r", MyConvert.Format("{0:0.000}", p.RetentionTime)), new XAttribute("t", MyConvert.Format("{0:0.000}", p.IonInjectionTime)), new XAttribute("d", p.Identified.ToString()), new XAttribute("p", MyConvert.Format("{0:0.000}", p.PPMDistance)) ))); root.Save(fileName); }
public string GetITraqFileName(string rawFileName) { return(MyConvert.Format("{0}.{1}.itraq.xml", rawFileName, minPeakCount)); }
public override string ToString() { return(MyConvert.Format("mz={0:0.0000}, rt={1:0.00}, abundance={2:0.0}", Mz, RetentionTime, Abundance)); }
public IsobaricResult GetTraqResult(string rawFileName) { Progress.SetMessage("Processing " + rawFileName + " ..."); string experimental = FileUtils.ChangeExtension(new FileInfo(rawFileName).Name, ""); string originalFileName = GetOriginalITraqFileName(rawFileName); string paramFileName = originalFileName + ".param"; IsobaricResult result = null; ITraqFileBuilder builder = new ITraqFileBuilder(itraqReader.PlexType.GetDefinition()); if (!CheckOriginalFile(originalFileName) || !File.Exists(paramFileName)) { itraqReader.Progress = this.Progress; Progress.SetMessage("Reading isobaric tag channels from " + new FileInfo(rawFileName).Name + "..."); List <IsobaricItem> pkls = itraqReader.ReadFromFile(rawFileName); Progress.SetMessage("Reading isobaric tag channels finished."); if (pkls.Count == 0) { throw new Exception(MyConvert.Format("No isobaric tag information readed from file {0}, contact with author.", rawFileName)); } var accs = builder.GetDistances(from pkl in pkls select pkl.RawPeaks); if (accs.Count == 0) { throw new Exception(MyConvert.Format("No isobaric tag information readed from file {0}, contact with author.", rawFileName)); } result = builder.GetITraqResult(pkls, accs, SigmaFoldTolerance, 1); result.Mode = itraqReader.ToString(); result.ForEach(m => m.Experimental = experimental); ITraqResultFileFormatFactory.GetXmlFormat().WriteToFile(originalFileName, result); using (StreamWriter sw = new StreamWriter(paramFileName)) { sw.WriteLine("Ion\tDetectedIon\tDeltaMass\tDeltaPPM\tDetectedSigma"); var ions = builder.Definition.Items; for (int i = 0; i < ions.Length; i++) { sw.WriteLine("{0:0.00000}\t{1:0.00000}\t{2:0.00000}\t{3:0.00}\t{4:0.00000}", ions[i].Mass, ions[i].Mass + accs[i].Mean, accs[i].Mean, PrecursorUtils.mz2ppm(ions[i].Mass, accs[i].Mean), accs[i].StdDev); } } } else { Progress.SetMessage("Read xml information from " + originalFileName + " ..."); var format = ITraqResultFileFormatFactory.GetXmlFormat(); format.Progress = this.Progress; result = format.ReadFromFile(originalFileName); } result.RemoveAll(m => m.PeakCount() < minPeakCount); result.ForEach(m => calc.Correct(m)); result.RemoveAll(m => m.PeakCount() < minPeakCount); result.ForEach(m => m.PrecursorPercentage = m.PeakInIsolationWindow.GetPrecursorPercentage(this.precursorPPM)); if (NormalizationBuilder != null) { NormalizationBuilder.Normalize(result); } return(result); }
public override string ToString() { return(MyConvert.Format("Ratio >= 0")); }
public string GetProteinRatioDescription(IIdentifiedProtein ann) { var corr = ann.GetQuantificationItem().Correlation; return(MyConvert.Format("Ratio = {0:0.0000}; Correlation = {1:0.0000}", GetProteinRatio(ann), corr)); }
public override string ToString() { return(MyConvert.Format("RegressionCorrelation >= {0:0.0}", minCorrel)); }
public override string Build <T>(Spectrum.PeakList <T> pkl) { return(MyConvert.Format("{0} Spectrum{1} scans: {1}", pkl.Experimental, pkl.GetFirstScanTime().Scan)); }
protected override PeakList <T> DoReadNextPeakList(out bool hasNext) { var result = new PeakList <T>(); string lastLine = ""; List <string> headers = ReadHeader(ref lastLine); Dictionary <string, string> annotations = ReadAnnotation(ref lastLine); List <string> peaks = ReadPeak(ref lastLine); hasNext = CheckHasNext(this.reader); foreach (string line in headers) { if (line.StartsWith(MascotGenericFormatConstants.MS_SCAN_TAG)) { ParseScan(result, line); } else if (line.StartsWith(MascotGenericFormatConstants.MSMS_SCAN_TAG)) { ParseScan(result, line); } else if (line.StartsWith(MascotGenericFormatConstants.FILENAME_TAG)) { result.Experimental = line.Substring(line.IndexOf(':') + 1).Trim(); } } foreach (var de in annotations) { if (de.Key.Equals(MascotGenericFormatConstants.PEPMASS_TAG)) { string[] values = Regex.Split(de.Value, "\\s"); result.PrecursorMZ = MyConvert.ToDouble(values[0]); if (values.Length > 1) { result.PrecursorIntensity = MyConvert.ToDouble(values[1]); } } else if (de.Key.Equals(MascotGenericFormatConstants.CHARGE_TAG)) { string charge = de.Value; if (charge.Contains("and")) { result.Annotations.Add(de.Key, de.Value); continue; } if (charge.EndsWith("+")) { charge = charge.Substring(0, charge.Length - 1); } result.PrecursorCharge = int.Parse(charge); } else if (de.Key.Equals(MascotGenericFormatConstants.SCAN_TAG)) { ParseScan(result, de.Value); } else if (de.Key.Equals(MascotGenericFormatConstants.RETENTION_TIME_TAG)) { double rtInSecond = 0.0; if (MyConvert.TryParse(de.Value, out rtInSecond)) { var rtInMin = rtInSecond / 60.0; if (result.ScanTimes.Count == 0) { result.ScanTimes.Add(new ScanTime(0, rtInMin)); } else { result.ScanTimes[0].RetentionTime = rtInMin; } } } else { result.Annotations.Add(de.Key, de.Value); } } foreach (string line in peaks) { string[] values = Regex.Split(line, "\\s"); try { var peak = new T() { Mz = MyConvert.ToDouble(values[0]), Intensity = MyConvert.ToDouble(values[1]) }; result.Add(peak); } catch (Exception) { throw new Exception(string.Format("Format error, cannot read peak info from {0}", line)); } } return(result); }
private string GetModifiedKey(double mass) { return(MyConvert.Format("{0:0.0000}", mass)); }