//public void ExportCompoundModeHtml(string targetDir)
        //{
        //  if (pairedResults == null)
        //  {
        //    return;
        //  }

        //  btnCompoundMode.PerformClick();

        //  var oldViewDecoy = ViewDecoy;
        //  ViewDecoy = true;
        //  try
        //  {
        //    var mainFile = new FileInfo(targetDir + "\\compound.html").FullName;
        //    var imageDir = FileUtils.ChangeExtension(mainFile, ".images");

        //    try
        //    {
        //      var imageDirName = new DirectoryInfo(imageDir).Name;
        //      if (!Directory.Exists(imageDir))
        //      {
        //        Directory.CreateDirectory(imageDir);
        //      }

        //      using (StreamWriter sw = new StreamWriter(mainFile))
        //      {
        //        sw.WriteLine("<html>");
        //        sw.WriteLine("<head>");
        //        sw.WriteLine("<title>Compound Quantification Result</title>");
        //        sw.WriteLine("</head>");
        //        sw.WriteLine("<body>");

        //        Predicate<CompoundItem> accept = m => m.IsDecoy && m.Enabled;
        //        var validDecoy = GetCompoundCount(visibleCompounds, accept);
        //        if (validDecoy > 0)
        //        {
        //          sw.WriteLine("{0} valid decoy entries (blue highlighted)<br>", validDecoy);
        //          OutputCompound(sw, visibleCompounds, accept, imageDir, imageDirName, Color.Blue);
        //        }

        //        GC.Collect();
        //        GC.WaitForFullGCComplete();

        //        accept = pep => !pep.IsDecoy && !pep.Enabled;
        //        var invalidTarget = GetCount(pr, accept);
        //        if (invalidTarget > 0)
        //        {
        //          sw.WriteLine("{0} invalid target entries (red highlighted)<br>", invalidTarget);
        //          Output(sw, pr, accept, imageDir, imageDirName, Color.Red);
        //        }

        //        GC.Collect();
        //        GC.WaitForFullGCComplete();

        //        accept = pep => !pep.IsDecoy && pep.Enabled;
        //        var validTarget = GetCount(pr, accept);
        //        if (validTarget > 0)
        //        {
        //          sw.WriteLine("{0} valid target entries<br>", validTarget);
        //          Output(sw, pr, accept, imageDir, imageDirName, Color.Black);
        //        }

        //        GC.Collect();
        //        GC.WaitForFullGCComplete();

        //        sw.WriteLine("</body>");
        //        sw.WriteLine("</html>");
        //      }
        //    }
        //    catch (Exception ex)
        //    {
        //      Console.WriteLine(ex.StackTrace);
        //      MessageBox.Show(this, MyConvert.Format("Error when saving {0} : {1}", mainFile, ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //      return;
        //    }
        //  }
        //  finally
        //  {
        //    ViewDecoy = oldViewDecoy;
        //  }

        //  MessageBox.Show(this, "Srm result html format saved.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
        //}

        //private void OutputCompound(StreamWriter sw, List<CompoundItem> list, Predicate<CompoundItem> accept, string imageDir, string imageDirName, Color color)
        //{
        //  CurrencyManager cm = (CurrencyManager)this.BindingContext[visibleCompounds];
        //  var valid = new HashSet<CompoundItem>(from p in list
        //                                                where accept(p)
        //                                                select p);
        //  for (int index = 0; index < visibleCompounds.Count; index++)
        //  {
        //    var comp = visibleCompounds[index];

        //    if (valid.Contains(comp))
        //    {
        //      cm.Position = index;

        //      //gvCompounds.Refresh();
        //      //gvCompounds_SelectionChanged(null, null);

        //      //gvProductPair.Refresh();
        //      //gvProductPair_SelectionChanged(null, null);

        //      //MessageBox.Show(comp.ObjectName + " " + comp.PrecursurFormula);

        //      WritePeptide(sw, pep, color);

        //      WriteImage(imageDir, imageDirName, sw, pep);
        //    }
        //  }
        //}

        //private int GetCompoundCount(List<CompoundItem> list, Predicate<CompoundItem> accept)
        //{
        //  return list.Count(m => accept(m));
        //}

        private void Output(StreamWriter sw, SrmPairedResult node, Predicate <SrmPairedPeptideItem> accept, string imageDir, string imageDirName, Color color)
        {
            CurrencyManager cm    = (CurrencyManager)this.BindingContext[visibleCompounds];
            var             valid = new HashSet <SrmPairedPeptideItem>(from p in node
                                                                       where accept(p)
                                                                       select p);

            for (int index = 0; index < visibleCompounds.Count; index++)
            {
                var comp = visibleCompounds[index];
                var pep  = comp.GetPeptideItem(node.PureFileName);

                if (valid.Contains(pep))
                {
                    cm.Position = index;

                    //gvCompounds.Refresh();
                    //gvCompounds_SelectionChanged(null, null);

                    //gvProductPair.Refresh();
                    //gvProductPair_SelectionChanged(null, null);

                    //MessageBox.Show(comp.ObjectName + " " + comp.PrecursurFormula);

                    WritePeptide(sw, pep, color);

                    WriteImage(imageDir, imageDirName, sw, pep);
                }
            }
        }
 public SrmFileItem(SrmPairedResult result, SrmPairedPeptideItem peptide, SrmPairedProductIon production)
 {
     this.PairedResult     = result;
     this.PairedPeptide    = peptide;
     this.PairedProductIon = production;
     _precursorMz          = new Pair <double, double>(peptide.LightPrecursorMZ, peptide.HeavyPrecursorMZ);
     _productIonMz         = new Pair <double, double>(production.LightProductIon, production.HeavyProductIon);
 }
        public static SrmPairedResult ToPairedResult(this List <SrmTransition> transList)
        {
            SrmPairedResult result = new SrmPairedResult();

            //所有母离子有相同名称、相同质荷比认为是来自相同precursor,合并为一个peptide。
            var pepgroup = transList.GroupBy(m => m.PrecursorFormula + MyConvert.Format("{0:0.0000}", m.PrecursorMZ));
            var peptides = new List <SrmPeptideItem>();

            foreach (var g in pepgroup)
            {
                var pep = new SrmPeptideItem();
                pep.PrecursorMZ = g.First().PrecursorMZ;
                pep.ProductIons = new List <SrmTransition>(g);
                peptides.Add(pep);
            }

            //具有相同母离子名称和电荷的transition认为是轻重标。
            var lhgroup = peptides.GroupBy(m => m.ProductIons[0].PrecursorFormula + "_" + m.ProductIons[0].PrecursorCharge.ToString()).ToList();

//      var lhgroup = peptides.GroupBy(m => m.ProductIons[0].PrecursorFormula + "_" + m.ProductIons[0].PrecursorCharge.ToString()).ToList();
            foreach (var g in lhgroup)
            {
                if (g.Count() > 2)
                {
                    throw new Exception(string.Format("There are {0} transition with same precursor formula and precursor charge: {1}, {2}", g.Count(), g.First().ProductIons[0].PrecursorFormula, g.First().ProductIons[0].PrecursorCharge));
                }
                else if (g.Count() > 1)
                {
                    var items = g.ToList();
                    items.Sort((m1, m2) => m1.PrecursorMZ.CompareTo(m2.PrecursorMZ));
                    SrmPairedPeptideItem light = new SrmPairedPeptideItem(items[0]);
                    SrmPairedPeptideItem heavy = new SrmPairedPeptideItem(items[1]);

                    if (!string.IsNullOrEmpty(light.ProductIonPairs[0].Light.Ion))
                    {
                        light.SetHeavyPeptideItemByIon(heavy);
                    }
                    else
                    {
                        light.SetHeavyPeptideItem(heavy);
                    }
                    result.Add(light);
                }
                else
                {
                    SrmPairedPeptideItem light = new SrmPairedPeptideItem(g.First());
                    result.Add(light);
                }
            }

            return(result);
        }
        protected override void DoRealGo()
        {
            mrmFileName = GetOriginFile();

            btnGo.Enabled = false;
            try
            {
                lblProgress.Text = "Reading MRM Scans ...";
                mrmPairs         = new SrmPairedResultXmlFormat().ReadFromFile(mrmFileName);
                lblProgress.Text = "Finished.";

                DisplayMRMTree();
            }
            finally
            {
                btnGo.Enabled = true;
            }
        }
Exemple #5
0
        public override IEnumerable <string> Process(string optionFile)
        {
            var targetDirectory = Path.GetDirectoryName(optionFile);

            options = new SrmOptions();
            options.FromXml(XElement.Load(optionFile));

            var keys = options.RawFiles.Keys.ToList();

            foreach (var key in keys)
            {
                if (string.IsNullOrEmpty(options.RawFiles[key]))
                {
                    this.options.RawFiles[key] = key;
                }
            }


            List <string> result = new List <string>();

            bool ignoreWarning = false;

            Dictionary <string, List <string> > map = GetGroupMap();

            int totalCount = options.RawFiles.Count;
            int curIndex   = 0;

            foreach (var groupKey in map.Keys)
            {
                var mrmFile = GetMrmFileName(targetDirectory, groupKey);

                SrmPairedResult taskResult = new SrmPairedResult()
                {
                    Options = this.options
                };

                var files = map[groupKey];
                foreach (var rawFile in files)
                {
                    curIndex++;
                    this.prefix = MyConvert.Format("Processing {0}/{1}", curIndex, totalCount);
                    SetProgressMessage(rawFile);

                    Console.WriteLine(rawFile);
                    if (Progress.IsCancellationPending())
                    {
                        throw new UserTerminatedException();
                    }

                    //读取所有scan信息
                    List <SrmScan> mrmIntensities = GetMRMScans(rawFile);

                    //mrmIntensities.RemoveAll(m => !( Math.Abs(m.PrecursorMz - 767.4) < 0.1 || Math.Abs(m.PrecursorMz - 770.9) < 0.1));

                    SetProgressMessage("building mrm groups ...");

                    var mrms = ScanToTransaction(mrmIntensities);

                    //将MRMPeptideItem转换为MRMPairedPeptideItem对象
                    SrmPairedResult mrmPairs;

                    if (File.Exists(options.DefinitionFile))
                    {
                        mrmPairs = BuildResultBasedOnDefinedFile(ref ignoreWarning, mrms);
                    }
                    else
                    {
                        mrmPairs = BuildResultBasedOnRealData(mrms);
                    }

                    mrmPairs.Options = this.options;
                    mrmPairs.PeakPicking();

                    //固定阈值筛选。
                    var filter = mrmPairs.Options.GetFilter();
                    mrmPairs.ForEach(m =>
                    {
                        m.ProductIonPairs.ForEach(n => n.Enabled = filter.Accept(n));
                    });

                    taskResult.AddRange(mrmPairs);
                }

                if (options.HasDecoy)
                {
                    //设置decoy标签
                    taskResult.AssignDecoy();

                    //是否有真实的decoy transition
                    var hasDecoy = taskResult.Any(m => m.ProductIonPairs.Any(n => n.IsDecoy));
                    if (hasDecoy)
                    {
                        //选取所有transition pairs,这些transition pairs有线性回归比值和回归系数
                        var pairs = (from m in taskResult
                                     from n in m.ProductIonPairs
                                     where n.IsPaired && n.Enabled
                                     orderby n.RegressionCorrelation descending
                                     select n).ToList();

                        //如果有这些pair,那么,那些不成pair的transition全部设置为disabled
                        if (pairs.Count > 0)
                        {
                            taskResult.ForEach(m => m.ProductIonPairs.ForEach(n => n.Enabled = n.Enabled && n.IsPaired));
                        }

                        //计算每个pair的qvalue
                        TargetFalseDiscoveryRateCalculator calc = new TargetFalseDiscoveryRateCalculator();
                        var decoyCount  = pairs.Count(m => m.IsDecoy);
                        var targetCount = pairs.Count - decoyCount;

                        for (int d = pairs.Count - 1; d >= 0; d--)
                        {
                            pairs[d].Qvalue = calc.Calculate(decoyCount, targetCount);
                            if (pairs[d].IsDecoy)
                            {
                                decoyCount--;
                            }
                            else
                            {
                                targetCount--;
                            }
                        }

                        //找到qvalue小于给定fdr的pair,qvalue大于该pair的全部设置为disable
                        for (int d = pairs.Count - 1; d >= 0; d--)
                        {
                            if (!pairs[d].IsDecoy && pairs[d].Qvalue <= options.TransitionFdr)
                            {
                                for (int d2 = d + 1; d2 < pairs.Count - 1; d2++)
                                {
                                    pairs[d2].Enabled = false;
                                }
                                break;
                            }
                        }
                    }
                }

                taskResult.ForEach(m =>
                {
                    m.CheckEnabled(this.options.OutlierEvalue, this.options.MinValidTransitionPair);
                });

                taskResult.CalculatePeptideRatio();

                taskResult.Sort((m1, m2) => m1.LightPrecursorMZ.CompareTo(m2.LightPrecursorMZ));

                new SrmPairedResultXmlFormat().WriteToFile(mrmFile, taskResult);
                result.Add(mrmFile);
            }

            Progress.End();

            return(result);
        }
Exemple #6
0
        private SrmPairedResult BuildResultBasedOnRealData(List <SrmTransition> mrms)
        {
            SrmPairedResult mrmPairs;
            //将Transaction转换为MRMPeptideItem
            var peptides = new List <SrmPeptideItem>();

            foreach (var mrm in mrms)
            {
                bool bFound = false;
                foreach (var pep in peptides)
                {
                    if (mrm.IsBrother(pep.ProductIons[0], this.options.RetentionTimeToleranceInSecond, 0.0001))
                    {
                        pep.ProductIons.Add(mrm);
                        bFound = true;
                        break;
                    }
                }

                if (!bFound)
                {
                    SrmPeptideItem item = new SrmPeptideItem();
                    item.PrecursorMZ = mrm.PrecursorMZ;
                    item.ProductIons.Add(mrm);
                    peptides.Add(item);
                }
            }

            //按照precursormz排序
            foreach (var pep in peptides)
            {
                pep.ProductIons.Sort((m1, m2) => m1.ProductIon.CompareTo(m2.ProductIon));
            }

            mrmPairs = new SrmPairedResult();
            mrmPairs.AddRange(from p in peptides
                              orderby p.PrecursorMZ
                              select new SrmPairedPeptideItem(p));

            //合并ProductIon完全一样或者差距相同的Item
            for (int i = 0; i < mrmPairs.Count; i++)
            {
                var iLight = mrmPairs[i];

                for (int j = i + 1; j < mrmPairs.Count; j++)
                {
                    var jLight = mrmPairs[j];

                    if (Math.Abs(iLight.LightPrecursorMZ - jLight.LightPrecursorMZ) > this.options.MaxPrecursorDistance)
                    {
                        continue;
                    }

                    if (iLight.AddPerfectPairedPeptideItem(jLight, this.options.AllowedGaps, this.options.MzTolerance, this.options.RetentionTimeToleranceInSecond))
                    {
                        mrmPairs.RemoveAt(j);
                        break;
                    }
                }
            }

            //容错情况下,合并ProductIon完全一样或者差距相同的Item
            for (int i = 0; i < mrmPairs.Count; i++)
            {
                var iLight = mrmPairs[i];
                if (iLight.IsPaired)
                {
                    continue;
                }

                for (int j = i + 1; j < mrmPairs.Count; j++)
                {
                    var jLight = mrmPairs[j];

                    if (jLight.IsPaired)
                    {
                        continue;
                    }

                    if (Math.Abs(iLight.LightPrecursorMZ - jLight.LightPrecursorMZ) > this.options.MaxPrecursorDistance)
                    {
                        continue;
                    }

                    if (iLight.AddErrorPairedPeptideItem(jLight, this.options.AllowedGaps, this.options.MzTolerance, this.options.RetentionTimeToleranceInSecond))
                    {
                        mrmPairs.RemoveAt(j);
                        break;
                    }
                }
            }
            return(mrmPairs);
        }
 private int GetCount(SrmPairedResult node, Predicate <SrmPairedPeptideItem> pred)
 {
     return(node.Count(m => pred(m)));
 }