コード例 #1
0
        public void StartWriteDocument(XmlTextWriter w, IsobaricResult ir)
        {
            w.Formatting = Formatting.Indented;
            w.WriteStartDocument();
            w.WriteStartElement("IsobaricResult");
            w.WriteAttribute("IsobaricType", ir.PlexType.ToString());

            //Write used channels
            if (ir.UsedChannels != null && ir.UsedChannels.Count > 0)
            {
                w.WriteAttribute("HasUsedChannel", true.ToString());
                w.WriteStartElement("UsedChannels");
                foreach (var channel in ir.UsedChannels)
                {
                    w.WriteStartElement("UsedChannel");
                    w.WriteAttribute("Index", channel.Index);
                    w.WriteAttribute("Name", channel.Name);
                    w.WriteAttribute("Mz", channel.Mz);
                    w.WriteEndElement();
                }
                w.WriteEndElement();
            }

            //Write comments, including parameters
            w.WriteStartElement("Comments");
            foreach (var comment in ir.Comments)
            {
                w.WriteStartElement("Comment");
                w.WriteAttribute("Key", comment.Key);
                w.WriteAttribute("Value", comment.Value);
                w.WriteEndElement();
            }
            w.WriteEndElement();
        }
コード例 #2
0
        public override IsobaricResult ReadFromFile(string fileName)
        {
            IsobaricResult result = new IsobaricResult();

            result.PlexType     = IsobaricScanXmlUtils.GetIsobaricType(fileName);
            result.UsedChannels = IsobaricScanXmlUtils.GetUsedChannels(fileName, result.PlexType);
            result.Comments     = IsobaricScanXmlUtils.GetComments(fileName);

            using (var reader = new IsobaricResultXmlFormatReader())
            {
                reader.Progress      = this.Progress;
                reader.ReadReporters = this.HasReporters && result.UsedChannels != null;
                reader.ReadPeaks     = this.ReadPeaks;
                reader.Accept        = this.Accept;

                reader.OpenFile(fileName);
                IsobaricScan item;
                while (null != (item = reader.Next(result.UsedChannels)))
                {
                    result.Add(item);
                }
            }

            return(result);
        }
        public override IEnumerable <string> Process()
        {
            IsobaricResult result = BuildIsobaricResult();

            Progress.SetMessage("Saving data to {0} ...", options.OutputFile);
            IsobaricResultFileFormatFactory.GetXmlFormat().WriteToFile(options.OutputFile, result);

            Progress.SetMessage("Done.");
            return(new[] { options.OutputFile });
        }
コード例 #4
0
        public static void MatchPeptideWithIsobaric(IsobaricResult itraq, List <IIdentifiedSpectrum> spectra)
        {
            var itraqMap = itraq.ToDictionary(m => m.Experimental + "##" + m.Scan.Scan.ToString());

            spectra.ForEach(m =>
            {
                var key = m.Query.FileScan.Experimental + "##" + m.Query.FileScan.FirstScan.ToString();
                if (itraqMap.ContainsKey(key))
                {
                    m.SetIsobaricItem(itraqMap[key]);
                }
                else
                {
                    m.SetIsobaricItem(null);
                }
            });
        }
コード例 #5
0
        public override void WriteToFile(string fileName, IsobaricResult t)
        {
            using (XmlTextWriter w = XmlUtils.CreateWriter(fileName, Encoding.ASCII))
            {
                StartWriteDocument(w, t);

                foreach (var item in t)
                {
                    WriteIsobaricItem(w, t, item);
                }

                EndWriteDocument(w);
            }

            var indexBuilder = new IsobaricResultXmlIndexBuilder(true)
            {
                Progress = this.Progress
            };

            indexBuilder.Process(fileName);
        }
コード例 #6
0
        public void WriteIsobaricItem(XmlTextWriter w, IsobaricResult ir, IsobaricScan item)
        {
            w.WriteStartElement("IsobaricScan");

            w.WriteElement("Experimental", item.Experimental);
            w.WriteElement("ScanMode", item.ScanMode);
            w.WriteElement("Scan", item.Scan.Scan);
            w.WriteElementFormat("RetentionTime", "{0:0.0}", item.Scan.RetentionTime);
            w.WriteElementFormat("IonInjectionTime", "{0:0.000}", item.Scan.IonInjectionTime);
            w.WriteElementFormat("PrecursorPercentage", "{0:0.000}", item.PrecursorPercentage);

            if (HasReporters)
            {
                WriteChannels(w, ir.UsedChannels, item);
            }

            WriteElementPeakList(w, item.RawPeaks, "RawPeaks", false);

            WriteElementPeakList(w, item.PeakInIsolationWindow, "PeakInIsolationWindow", true);

            w.WriteEndElement();

            w.Flush();
        }
        public virtual IsobaricResult BuildIsobaricResult()
        {
            Progress.SetMessage("Processing " + options.InputFile + " ...");

            string experimental = Path.GetFileNameWithoutExtension(options.InputFile);

            var format = IsobaricResultFileFormatFactory.GetXmlFormat();

            format.Progress     = this.Progress;
            format.HasReporters = false;

            IsobaricResult result = null;

            var reader = options.Reader;

            if (!File.Exists(options.OriginalXmlFileName))
            {
                reader.Progress = this.Progress;

                Progress.SetMessage("Reading isobaric tag channels from " + new FileInfo(options.InputFile).Name + "...");
                var pkls = reader.ReadFromFile(options.InputFile);
                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.", options.InputFile));
                }

                result = new IsobaricResult(pkls);
                result.Comments["Mode"]            = reader.ToString();
                result.PlexType                    = options.PlexType;
                result.ForEach(m => m.Experimental = experimental);

                format.WriteToFile(options.OriginalXmlFileName, result);
            }
            else
            {
                Progress.SetMessage("Reading xml information from " + options.OriginalXmlFileName + " ...");
                result = format.ReadFromFile(options.OriginalXmlFileName);
            }

            result.UsedChannels = (from ucha in options.UsedChannels
                                   let cha = options.PlexType.Channels[ucha.Index]
                                             select new UsedChannel()
            {
                Index = ucha.Index, Name = cha.Name, Mz = cha.Mz, MinMz = cha.Mz - IsobaricConsts.MAX_SHIFT, MaxMz = cha.Mz + IsobaricConsts.MAX_SHIFT
            }).ToList();

            if (options.PerformMassCalibration)
            {
                Progress.SetMessage("Performing mass calibration ...");
                var calPeaks = result.GetMassCalibrationPeaks();
                result.UsedChannels.CalibrateMass(calPeaks, options.OutputFile + ".calibration");
                result.Comments["PerformMassCalibration"] = true.ToString();
            }

            foreach (var channel in result.UsedChannels)
            {
                var mztolerance = PrecursorUtils.ppm2mz(channel.Mz, options.ProductPPMTolerance);
                channel.MinMz = channel.Mz - mztolerance;
                channel.MaxMz = channel.Mz + mztolerance;
            }

            Progress.SetMessage("Building isobaric result ...");
            result.ForEach(m => m.DetectReporter(result.UsedChannels));
            result.RemoveAll(m => m.PeakCount() < options.MinPeakCount);
            result.Comments["RequiredChannels"] = (from c in options.RequiredChannels select c.Name).Merge(",");

            if (options.RequiredChannels.Count > 0)
            {
                options.RequiredChannels.ForEach(m => m.Index = result.UsedChannels.FindIndex(l => l.Name.Equals(m.Name)));
                result.RemoveAll(m =>
                {
                    foreach (var channel in options.RequiredChannels)
                    {
                        if (channel.GetValue(m) <= IsobaricConsts.NULL_INTENSITY)
                        {
                            return(true);
                        }
                    }

                    return(false);
                });
            }

            if (options.PerformPurityCorrection)
            {
                Progress.SetMessage("Performing purity correction ...");
                var tempFilename = options.OutputFile + ".csv";
                new IsobaricPurityCorrectionRCalculator(options.PlexType, result.UsedChannels, options.RExecute, options.PerformPurityCorrection, true).Calculate(result, tempFilename);
                result.ForEach(m => m.Reporters.ForEach(p =>
                {
                    if (p.Intensity < IsobaricConsts.NULL_INTENSITY)
                    {
                        p.Intensity = IsobaricConsts.NULL_INTENSITY;
                    }
                }));
                result.Comments["PerformPurityCorrection"] = true.ToString();
            }

            result.RemoveAll(m => m.PeakCount() < options.MinPeakCount);

            Progress.SetMessage("Calculating precursor percentage ...");
            result.ForEach(m => m.PrecursorPercentage = m.PeakInIsolationWindow.GetPrecursorPercentage(options.PrecursorPPMTolerance));

            return(result);
        }
 public abstract void WriteToFile(string fileName, IsobaricResult t);
コード例 #9
0
 public virtual void BuildIsobaricResult(IsobaricResult result, int minPeakCount)
 {
 }
コード例 #10
0
        public void Calculate(IsobaricResult ir, string tempFilename)
        {
            if (!this.performPurityCorrection && !this.performGraph)
            {
                return;
            }

            tempFilename = tempFilename.Replace("\\", "/");

            var dataFile = tempFilename + ".data";

            using (var sw = new StreamWriter(dataFile))
            {
                sw.WriteLine("Scan\t{0}", (from c in used select c.Name).Merge("\t"));
                foreach (var ii in ir)
                {
                    sw.WriteLine("{0}\t{1}", ii.Scan.Scan, (from rep in ii.Reporters select string.Format("{0:0.##}", rep.Intensity)).Merge("\t"));
                }
            }

            var purityFile = tempFilename + ".purity";

            using (var sw = new StreamWriter(purityFile))
            {
                var purity = plexType.IsotopicTable;
                sw.WriteLine("Channel\t{0}", (from c in used select c.Name).Merge("\t"));
                for (int i = 0; i < used.Count; i++)
                {
                    sw.Write(used[i].Name);
                    for (int j = 0; j < used.Count; j++)
                    {
                        sw.Write("\t{0:0.####}", purity[used[i].Index, used[j].Index] / 100);
                    }
                    sw.WriteLine();
                }
            }

            var rfile   = tempFilename + ".r";
            var pngFile = tempFilename + ".png";

            using (var sw = new StreamWriter(rfile))
            {
                sw.WriteLine(@"
data<-read.table(""" + dataFile + @""", header=T, row.names=1)
");

                if (this.performPurityCorrection)
                {
                    sw.WriteLine(@"
library(nnls)

table<-read.table(""" + purityFile + @""", header=T, row.names=1)
m<-as.matrix(table)
m=t(m)

correctedData<-apply(data, 1, function(x){
  v<-nnls(m, x)
  v$x
})

correctedData<-t(correctedData)
colnames(correctedData)<-colnames(data)

data<-data.frame(correctedData)
");
                }

                sw.WriteLine(@"
write.csv(data, file=""" + tempFilename + @""")
");

                if (this.performGraph)
                {
                    sw.WriteLine(@"

dd<-data.frame(data)
png(""" + pngFile + @""",
    width=1000 * ncol(dd), height=1000*ncol(dd), res=300)
split.screen(c(ncol(dd),ncol(dd)))
id<-0
cols<-rainbow(ncol(dd))
for(i in c(1:ncol(dd))){
  for(j in c(1:ncol(dd))){
    id<-id+1
    screen(id)
    if(i == j){
      dl<-list()
      maxy<-0
      for(k in c(1:ncol(dd))){
        if(k != i){
          notZero<-dd[,i] > 0 & dd[,k] > 0
          xx<-dd[notZero,i]
          yy<-dd[notZero,k]
          r<-log2(yy/xx)
          d<-density(r)
          dl[[colnames(dd)[k]]]<-d
          maxy<-max(maxy, max(d$y))
        }  
      }
      maxy<-floor(maxy) + 1
      s<-0
      for(k in c(1:ncol(dd))){
        if(k != i){
          s<-s+1
          if(s == 1){
            par(mar=c(2,2,3,2), new=TRUE)
            plot(dl[[colnames(dd)[k]]], xlim=c(-2,2), ylim=c(0,maxy), xlab="""", col=cols[k], main=colnames(dd)[i])
          }else{
            lines(dl[[colnames(dd)[k]]], col=cols[k])
          }
        }
      }
    }else{
      notZero<-dd[,i] > 0 & dd[,j] > 0
      xx<-dd[notZero,i]
      yy<-dd[notZero,j]
      m<-log2(yy/xx)
      a<-log2((yy+xx)/2)
      par(mar=c(2,2,3,2), new=TRUE)
      plot(x=a, y=m, col=cols[j],xlab="",ylab="",main=paste0(colnames(dd)[j], ""/"", colnames(dd)[i]), cex=0.1, pch=20, xlim=c(10,30), ylim=c(-5,5))
      abline(a=0, b=0)
    }
  }
}
close.screen()
dev.off()

");
                }
            }

            var roptions = new RProcessorOptions()
            {
                RExecute         = rExecute,
                RFile            = rfile,
                ExpectResultFile = tempFilename
            };

            new RProcessor(roptions).Process();

            if (!File.Exists(tempFilename))
            {
                throw new Exception(string.Format("Purity correction failed!\nMake sure that your R and R packages nnls, limma have been installed.\nOtherwise, send those three files to [email protected]\n{0}\n{1}\n{2}",
                                                  dataFile,
                                                  purityFile,
                                                  rfile));
            }

            //read back all corrected intensities
            using (var sr = new StreamReader(tempFilename))
            {
                var line  = sr.ReadLine();
                var index = 0;
                while ((line = sr.ReadLine()) != null)
                {
                    if (string.IsNullOrWhiteSpace(line))
                    {
                        break;
                    }

                    var parts = line.Split(',');
                    for (int i = 1; i < parts.Length; i++)
                    {
                        ir[index][i - 1].Intensity = double.Parse(parts[i]);
                    }
                    index++;
                }
            }

            //File.Delete(dataFile);
            //File.Delete(purityFile);
            //File.Delete(rfile);
            //File.Delete(tempFilename);
        }