private void UpdateProteins()
        {
            tvResult.BeginUpdate();
            try
            {
                tvResult.Nodes.Clear();
                foreach (var g in proteins)
                {
                    var subNode = tvResult.Nodes.Add(string.Format("{0} ({1})", g[0].Name, g[0].Peptides.Count));
                    subNode.Tag = g;

                    var uniquePeptides = g[0].Peptides.GroupBy(m => PeptideUtils.GetMatchedSequence(m.Sequence)).OrderByDescending(n => n.Count()).ThenBy(n => n.Key);
                    foreach (var up in uniquePeptides)
                    {
                        var subPNode = subNode.Nodes.Add(string.Format("{0} ({1})", up.Key, up.Count()));
                        subPNode.Tag = new List <IIdentifiedSpectrum>(from p in up select p.Spectrum);

                        var peps = (from p in up
                                    orderby p.Spectrum.Query.FileScan.Experimental, p.Spectrum.Query.FileScan.FirstScan
                                    select p).ToList();

                        foreach (var p in peps)
                        {
                            var ppNode = subPNode.Nodes.Add(string.Format("{0}, {1:0.##}", p.Spectrum.Query.FileScan.LongFileName, p.Spectrum.Score));
                            ppNode.Tag = p.Spectrum;
                        }
                    }
                }
            }
            finally
            {
                tvResult.EndUpdate();
            }
        }
        public override IEnumerable <string> Process(string fileName)
        {
            var peptides = new MascotPeptideTextFormat().ReadFromFile(fileName);

            var seqs = (from p in peptides
                        let pep = p.Peptide
                                  select PeptideUtils.GetMatchedSequence(pep.Sequence)).ToList();

            var nmod = (from seq in seqs
                        where !char.IsLetter(seq[0])
                        select seq).Count();

            var kseqs = (from seq in seqs
                         where seq.Contains(modificationAminoacid)
                         select seq).Count();

            var kmod = (from seq in seqs
                        where seq.Contains(modificationAminoacid) && IsFullModifiedK(seq)
                        select seq).Count();

            var result = fileName + ".labelingEfficiency";

            using (StreamWriter sw = new StreamWriter(result))
            {
                sw.WriteLine("Total PSMs\t{0}", peptides.Count);
                sw.WriteLine("N-terminal modified PSMs\t{0}", nmod);
                sw.WriteLine("{0}-contained PSMs\t{1}", modificationAminoacid, kseqs);
                sw.WriteLine("{0}-full-modified PSMs\t{2}", modificationAminoacid, kmod);
            }

            return(new string[] { result });
        }
コード例 #3
0
        protected override void DoRealGo()
        {
            Aminoacids aas = Aminoacids.ParseModificationFromOutFileLine(modification.Text);

            IPeptideMassCalculator calc;

            if (isMonoisotopic.Checked)
            {
                calc = new MonoisotopicPeptideMassCalculator(aas);
            }
            else
            {
                calc = new AveragePeptideMassCalculator(aas);
            }

            string seq = PeptideUtils.GetMatchedSequence(sequence.Text);
            double value;

            if (isMH.Checked)
            {
                value = calc.GetMz(seq, 1);
            }
            else
            {
                value = calc.GetMass(seq);
            }
            txtResult.Text = value.ToString();
        }
コード例 #4
0
        private ResultCorrelationItem BuildResult(IIdentifiedResult ir)
        {
            var result = new ResultCorrelationItem();

            result.ClassificationTitles = ClassificationSet.Keys.ToArray();
            foreach (var g in ir)
            {
                var pro     = g[0];
                var protein = new ProteinCorrelationItem();
                result.Add(protein);

                protein.Index        = g.Index;
                protein.Protein      = ParseItem(pro.Peptides, result.ClassificationTitles);
                protein.Protein.Name = pro.Name;

                var peps = pro.Peptides.GroupBy(m => PeptideUtils.GetMatchedSequence(m.Sequence));
                foreach (var pep in peps)
                {
                    var pepitem = ParseItem(pep.ToList(), result.ClassificationTitles);
                    protein.Peptides.Add(pepitem);

                    pepitem.Name        = pep.Key;
                    pepitem.Correlation = Correlation.Pearson(pepitem.Values, protein.Protein.Values);
                }
            }

            result.ForEach(m =>
            {
                m.Peptides.Sort((m1, m2) => m2.Correlation.CompareTo(m1.Correlation));
            });
            return(result);
        }
コード例 #5
0
        public override IEnumerable <string> Process(string fileName)
        {
            MascotResultTextFormat format = new MascotResultTextFormat();

            IIdentifiedResult ir = format.ReadFromFile(fileName);

            List <IIdentifiedSpectrum> spectra = ir.GetSpectra();

            spectra.ForEach(m =>
            {
                for (int i = m.Peptides.Count - 1; i >= 0; i--)
                {
                    IIdentifiedPeptide peptide = m.Peptides[i];

                    string seq = PeptideUtils.GetMatchedSequence(peptide.Sequence);

                    if (!validator.Validate(seq))
                    {
                        m.RemovePeptideAt(i);
                        peptide.Spectrum = null;
                    }
                }
            });

            ir.Filter(m =>
            {
                return(m.Spectrum != null);
            });

            string result = fileName + ".Labeled";

            format.WriteToFile(result, ir);

            return(new[] { result });
        }
コード例 #6
0
        /// <summary>
        /// 根据序列构建氨基酸信息列表。该信息列表中已将修饰质量加到氨基酸上,可方便地用于构建离子列表。
        /// </summary>
        /// <param name="sequence">氨基酸序列,包含修饰字符。</param>
        /// <returns>氨基酸信息列表</returns>
        public List <AminoacidInfo> BuildInfo(string sequence)
        {
            var matchedSequence = PeptideUtils.GetMatchedSequence(sequence);

            var result = new List <AminoacidInfo>();

            foreach (char c in matchedSequence)
            {
                if (char.IsLetter(c) && char.IsUpper(c))
                {
                    var aai = new AminoacidInfo();
                    aai.Aminoacid    = c;
                    aai.Modification = ' ';
                    aai.Mass         = this[c].MonoMass;
                    result.Add(aai);
                }
                else
                {
                    AminoacidInfo aai = result.Last();
                    aai.Modification = c;
                    aai.Mass        += this[c].MonoMass;
                }
            }
            return(result);
        }
        private void init(String modifiedAminoacids, String sequence,
                          char modifiedSign)
        {
            String matchSequence = PeptideUtils.GetMatchedSequence(sequence);

            this.pureSequence = PeptideUtils.GetPureSequence(matchSequence);

            modifiedCount = 0;

            for (int i = 0; i < matchSequence.Length; i++)
            {
                char c = matchSequence[i];
                if (char.IsLetter(c) && char.IsUpper(c))
                {
                    sites.Add(new Pair <char, char>(c, ' '));
                }
                else if (isCandidateModifiedAminoacid(modifiedAminoacids,
                                                      getLastPair().First))
                {
                    if (modifiedSign == ' ')
                    {
                        getLastPair().Second = c;
                    }
                    else
                    {
                        getLastPair().Second = modifiedSign;
                    }
                    modifiedCount++;
                }
            }
            calculate();
        }
コード例 #8
0
        public string GetMatchSequence()
        {
            if (this.Peptides.Count == 0)
            {
                return("");
            }

            return(PeptideUtils.GetMatchedSequence(this.Peptides[0].Sequence));
        }
コード例 #9
0
        private void InitTheoreticalPeaks()
        {
            Aminoacids aas = new Aminoacids();

            aas.SetModification(StaticModification);
            aas.SetModification(DynamicModification);

            CIDFragmentationBuilder <MatchedPeak> builder = new CIDFragmentationBuilder <MatchedPeak> (ExperimentalPeakList.PrecursorCharge, aas);

            ionSeries = builder.GetIonSeries(PeptideUtils.GetMatchedSequence(Peptide));
        }
        private string GetModificationCount(IIdentifiedPeptide pep, string p)
        {
            var result     = 0;
            var matchedSeq = PeptideUtils.GetMatchedSequence(pep.Sequence);

            for (int i = 0; i < matchedSeq.Length - 1; i++)
            {
                if (p.Contains(matchedSeq[i]) && !Char.IsLetter(matchedSeq[i + 1]))
                {
                    result++;
                    i++;
                }
            }

            return(result.ToString());
        }
コード例 #11
0
        public void InitTerminalLoss(Aminoacids aa, int maxTerminalLossLength, int minSequenceLength)
        {
            this.TerminalLoss = new List <TerminalLossItem>();

            var seq     = PeptideUtils.GetMatchedSequence(this.Peptide);
            var pureseq = PeptideUtils.GetPureSequence(this.Peptide);

            var pos       = 0;
            var index     = 0;
            var maxIndex  = Math.Min(maxTerminalLossLength, pureseq.Length - minSequenceLength);
            var deltaMass = 0.0;

            while (index < maxIndex)
            {
                deltaMass += aa[seq[pos]].MonoMass;
                if (!char.IsUpper(seq[pos + 1]))
                {
                    pos++;
                    continue;
                }

                index++;
                pos++;

                var precursorLoss = this.Precursor - deltaMass / this.Charge;
                this.TerminalLoss.Add(new TerminalLossItem(true, pureseq.Substring(index), precursorLoss));
            }

            index     = 0;
            pos       = seq.Length - 1;
            deltaMass = 0.0;
            while (index < maxIndex)
            {
                deltaMass += aa[seq[pos]].MonoMass;
                if (!char.IsUpper(seq[pos]))
                {
                    pos--;
                    continue;
                }

                index++;
                pos--;

                var precursorLoss = this.Precursor - deltaMass / this.Charge;
                this.TerminalLoss.Add(new TerminalLossItem(false, pureseq.Substring(0, pureseq.Length - index), precursorLoss));
            }
        }
コード例 #12
0
        public string GetPhosphoModificationString(string peptide)
        {
            string        matchedSequence = PeptideUtils.GetMatchedSequence(peptide);
            StringBuilder result          = new StringBuilder();

            for (int i = 0; i < matchedSequence.Length; i++)
            {
                if (!PeptideUtils.IsAminoacid(matchedSequence[i]))
                {
                    continue;
                }

                if (IsPhospho(matchedSequence, i))
                {
                    result.Append(matchedSequence[i]);
                }
            }
            return(result.ToString());
        }
コード例 #13
0
        private void WriteModificationAndScore(StreamWriter sw, Dictionary <char, double> modChars, IIdentifiedSpectrum sph, IIdentifiedPeptide pep)
        {
            var matchSeq = PeptideUtils.GetMatchedSequence(pep.Sequence);

            if (matchSeq.Any(m => modChars.ContainsKey(m))) // modification
            {
                if (modChars.ContainsKey(matchSeq[0]))      //Nterminal
                {
                    sw.Write("          <modification_info mod_nterm_mass=\"{0:0.######}\"", modChars[matchSeq[0]]);
                }
                else
                {
                    sw.Write("          <modification_info ");
                }
                sw.WriteLine(" modified_peptide=\"{0}\">", matchSeq);
                int    pos = 1;
                double mass;
                for (int i = 0; i < matchSeq.Length; i++)
                {
                    if (modChars.TryGetValue(matchSeq[i], out mass))
                    {
                        if (i == 0)
                        {
                            continue;
                        }

                        sw.WriteLine("            <mod_aminoacid_mass position=\"{0}\" mass=\"{1:0.######}\"/>", pos, mass);
                    }
                    else
                    {
                        pos++;
                    }
                }
                sw.WriteLine("          </modification_info>");
            }

            WriteScore(sw, sph);
        }
        /// <summary>
        /// 根据序列,得到b系列对应的磷酸化修饰map。
        /// key是氨基酸的index,
        /// value是在该氨基酸N端断裂得到的b离子所对应多肽中磷酸化修饰的氨基酸列表。
        /// </summary>
        /// <param name="sr"></param>
        /// <returns></returns>
        public Dictionary <int, string> GetPhosphoModificationPositionMapB(string peptide)
        {
            Dictionary <int, string> result = new Dictionary <int, string>();
            string matchedSequence          = PeptideUtils.GetMatchedSequence(peptide);
            int    index        = -1;
            string lastModified = "";

            for (int i = 0; i < matchedSequence.Length; i++)
            {
                if (!PeptideUtils.IsAminoacid(matchedSequence[i]))
                {
                    continue;
                }

                index++;
                if (IsPhospho(matchedSequence, i))
                {
                    lastModified = lastModified + matchedSequence[i];
                }
                result[index] = lastModified;
            }
            return(result);
        }
コード例 #15
0
        public IEnumerable <string> Process(string filename)
        {
            List <string> result = new List <string>();

            List <string> proteins      = new List <string>();
            List <string> lightPeptides = new List <string>();
            List <string> heavyPeptides = new List <string>();

            Dictionary <string, Sequence> seqMap = new Dictionary <string, Sequence>();

            if (File.Exists(filename + ".fasta"))
            {
                List <Sequence> seqs = SequenceUtils.Read(ff, filename + ".fasta");
                foreach (Sequence seq in seqs)
                {
                    seqMap[seq.Name] = seq;
                }
            }

            string lightResult = filename + ".light";
            string heavyResult = filename + ".heavy";

            StreamWriter swLightFasta = null;
            StreamWriter swHeavyFasta = null;

            if (seqMap.Count > 0)
            {
                swLightFasta = new StreamWriter(lightResult + ".fasta");
                swHeavyFasta = new StreamWriter(heavyResult + ".fasta");
            }

            try
            {
                using (StreamWriter swLight = new StreamWriter(lightResult))
                {
                    using (StreamWriter swHeavy = new StreamWriter(heavyResult))
                    {
                        using (StreamReader sr = new StreamReader(filename))
                        {
                            string line = sr.ReadLine();
                            swLight.WriteLine(line);
                            swHeavy.WriteLine(line);

                            line = sr.ReadLine();
                            SequestPeptideTextFormat format = new SequestPeptideTextFormat(line);
                            swLight.WriteLine(line);
                            swHeavy.WriteLine(line);

                            bool bIsProtein = true;
                            while ((line = sr.ReadLine()) != null)
                            {
                                if (line.Trim().Length == 0)
                                {
                                    WriteGroup(proteins, lightPeptides, heavyPeptides, swLight, swHeavy, swLightFasta, swHeavyFasta, seqMap);
                                    break;
                                }

                                if (line.StartsWith("$"))
                                {
                                    if (bIsProtein)
                                    {
                                        proteins.Add(line);
                                        continue;
                                    }

                                    WriteGroup(proteins, lightPeptides, heavyPeptides, swLight, swHeavy, swLightFasta, swHeavyFasta, seqMap);

                                    proteins.Clear();
                                    lightPeptides.Clear();
                                    heavyPeptides.Clear();

                                    proteins.Add(line);
                                    bIsProtein = true;
                                    continue;
                                }

                                bIsProtein = false;

                                IIdentifiedSpectrum sph = format.PeptideFormat.ParseString(line);
                                string matchedSeq       = PeptideUtils.GetMatchedSequence(sph.Sequence);
                                double lightMass        = lightCalc.GetMass(matchedSeq);
                                double heavyMass        = heavyCalc.GetMass(matchedSeq);

                                if (Math.Abs(lightMass - sph.ExperimentalMass) < 0.1)
                                {
                                    lightPeptides.Add(line);
                                    continue;
                                }

                                if (Math.Abs(heavyMass - sph.ExperimentalMass) < 0.1)
                                {
                                    heavyPeptides.Add(line);
                                    continue;
                                }

                                throw new Exception(MyConvert.Format("Mass={0:0.0000}; {1:0.0000}; {2:0.0000}", sph.ExperimentalMass,
                                                                     lightMass, heavyMass));
                            }
                        }
                    }
                }
            }
            finally
            {
                if (seqMap.Count > 0)
                {
                    swLightFasta.Close();
                    swHeavyFasta.Close();
                }
            }

            result.Add(lightResult);
            result.Add(heavyResult);

            return(result);
        }
コード例 #16
0
        private void DrawSpectrum(IIdentifiedSpectrum spectrum)
        {
            if (spectrum.Annotations.ContainsKey("PepMutation"))
            {
                zgcPeaks.MasterPane.PaneList[0].Title.Text = string.Format("MH={0:0.00000},PPM={1:0.0},SEQ={2},MUT={3},COUNT={4}",
                                                                           spectrum.TheoreticalMH,
                                                                           PrecursorUtils.mz2ppm(spectrum.TheoreticalMH, spectrum.TheoreticalMinusExperimentalMass),
                                                                           spectrum.Sequence,
                                                                           spectrum.Annotations["PepMutation"],
                                                                           (from a in spectrum.Annotations
                                                                            where a.Key.EndsWith("_PepCount")
                                                                            select Convert.ToInt32(a.Value)).Sum());
            }
            else
            {
                zgcPeaks.MasterPane.PaneList[0].Title.Text = string.Format("MH={0:0.00000},PPM={1:0.0},SEQ={2}",
                                                                           spectrum.TheoreticalMH,
                                                                           PrecursorUtils.mz2ppm(spectrum.TheoreticalMH, spectrum.TheoreticalMinusExperimentalMass),
                                                                           spectrum.Sequence);
            }

            var mass = aas.MonoPeptideMass(PeptideUtils.GetMatchedSequence(spectrum.Sequence));

            if (Math.Abs(mass - spectrum.TheoreticalMass) > 0.1)
            {
                MessageBox.Show(string.Format("Error : {0} - {1}", mass, spectrum.TheoreticalMass));
                return;
            }

            var name = string.Format("{0}_{1}", spectrum.Query.FileScan.Experimental, spectrum.Query.FileScan.FirstScan);

            var peakPane = zgcPeaks.MasterPane.PaneList[0];

            peakPane.ClearData();

            var ppmPane = zgcPeaks.MasterPane.PaneList[1];

            ppmPane.ClearData();

            if (!mgfMap.ContainsKey(name))
            {
                MessageBox.Show("Cannot find peak list {0}", name);
                return;
            }

            var mgf = mgfMap[name];

            var maxIntensity = mgf.Max(m => m.Intensity);
            var maxMz        = Math.Min(2000, mgf.Max(m => m.Mz));

            var productTolerance = productIonPPM;
            var minIntensity     = maxIntensity * 0.05;

            AddIonSeries(peakPane, ppmPane, mgf, productTolerance, minIntensity, yBuilder, spectrum.Sequence, Color.Red);
            AddIonSeries(peakPane, ppmPane, mgf, productTolerance, minIntensity, bBuilder, spectrum.Sequence, Color.Blue);

            if (spectrum.Charge > 2)
            {
                AddIonSeries(peakPane, ppmPane, mgf, productTolerance, minIntensity, y2Builder, spectrum.Sequence, Color.Brown);
                AddIonSeries(peakPane, ppmPane, mgf, productTolerance, minIntensity, b2Builder, spectrum.Sequence, Color.GreenYellow);
            }

            AddUnmatchedIons(peakPane, mgf);

            foreach (var pane in zgcPeaks.MasterPane.PaneList)
            {
                pane.XAxis.Scale.Min = 0;
                pane.XAxis.Scale.Max = maxMz;
            }
            zgcPeaks.UpdateGraph();

            var targetpngfile = GetTargetFile(targetDir, spectrum);

            zgcPeaks.GetImage().Save(targetpngfile, ImageFormat.Png);
        }
コード例 #17
0
 public void SortPeptides()
 {
     this.peptides.Sort((m1, m2) => PeptideUtils.GetMatchedSequence(m1.Sequence).CompareTo(PeptideUtils.GetMatchedSequence(m2.Sequence)));
 }
コード例 #18
0
        public override IEnumerable <string> Process(string fileName)
        {
            SequestPeptideTextFormat format = new SequestPeptideTextFormat();

            List <IIdentifiedSpectrum> spectra = format.ReadFromFile(fileName);

            List <IIdentifiedSpectrum> positives = spectra.FindAll(m =>
            {
                if (IsAmbigiousSequence(m.Sequence))
                {
                    return(false);
                }

                if (m.DiffModificationSiteCandidates.Count == 0)
                {
                    return(true);
                }

                if (1 == m.DiffModificationSiteCandidates.Count)
                {
                    string matchedSeq = PeptideUtils.GetMatchedSequence(m.DiffModificationSiteCandidates[0].Sequence);
                    return(matchedSeq.Equals(m.Sequence));
                }

                return(false);
            });

            var ambigious = spectra.Except(positives);

            var positiveSeqs = new HashSet <string>(positives.ConvertAll(m => PeptideUtils.GetMatchedSequence(m.Sequence)));

            var keptAmbigious = new List <IIdentifiedSpectrum>();

            foreach (IIdentifiedSpectrum m in ambigious)
            {
                if (positiveSeqs.Contains(m.Sequence))
                {
                    continue;
                }

                string matchedSeq;
                if (IsAmbigiousSequence(m.Sequence))
                {
                    matchedSeq = PeptideUtils.GetMatchedSequence(m.DiffModificationSiteCandidates[0].Sequence);
                }
                else
                {
                    matchedSeq = PeptideUtils.GetMatchedSequence(m.Sequence);
                }

                if (positiveSeqs.Contains(matchedSeq))
                {
                    continue;
                }

                keptAmbigious.Add(m);
            }

            positives.AddRange(keptAmbigious);

            var bin =
                from p in positives
                group p by(p.Sequence + "_" + p.Charge);

            List <IIdentifiedSpectrum> final = new List <IIdentifiedSpectrum>();

            foreach (var b in bin)
            {
                var o = b.OrderByDescending(m => m.Score);
                final.Add(o.First());
            }

            string resultFileName = fileName + ".single";

            format.WriteToFile(resultFileName, final);
            return(new string[] { resultFileName });
        }
コード例 #19
0
        public void WriteToFile(string fileName, List <IIdentifiedSpectrum> t)
        {
            var resultFile = new FileInfo(fileName);

            using (var sw = new StreamWriter(fileName))
            {
                sw.NewLine = "\n";
                sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                DateTime dt = DateTime.Now;
                sw.WriteLine("<msms_pipeline_analysis date=\"{0}\" xmlns=\"http://regis-web.systemsbiology.net/pepXML\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://sashimi.sourceforge.net/schema_revision/pepXML/pepXML_v117.xsd\" summary_xml=\"{1}\">",
                             dt.ToString("yyyy-MM-dd\\THH:mm:ss"),
                             Path.GetFileName(fileName));

                //Start of msms_run_summary
                sw.WriteLine("  <msms_run_summary base_name=\"{0}\" raw_data_type=\"raw\" raw_data=\"{1}\">",
                             FileUtils.ChangeExtension(this.parameters.SourceFile, ""),
                             Path.GetExtension(parameters.SourceFile));

                //Export protease information
                sw.WriteLine(@"  <sample_enzyme name=""{0}"">
    <specificity cut=""{1}"" no_cut=""{2}"" sense=""{3}""/>
  </sample_enzyme>",
                             parameters.Protease.Name,
                             parameters.Protease.CleaveageResidues,
                             parameters.Protease.NotCleaveResidues,
                             parameters.Protease.IsEndoProtease ? "C" : "N");

                //search_summary
                sw.WriteLine("    <search_summary base_name=\"{0}\" search_engine=\"{1}\" precursor_mass_type=\"{2}\" fragment_mass_type=\"{3}\" search_id=\"1\">",
                             parameters.SourceFile,
                             parameters.SearchEngine,
                             parameters.MassTypeParentAnnotation,
                             parameters.MassTypeFragmentAnnotation);

                sw.WriteLine("      <search_database local_path=\"{0}\" type=\"AA\"/>",
                             parameters.SearchDatabase);

                sw.WriteLine("      <enzymatic_search_constraint enzyme=\"{0}\" max_num_internal_cleavages=\"{1}\" min_number_termini=\"{2}\"/>",
                             parameters.Protease.Name,
                             t.Max(l => l.NumMissedCleavages),
                             t.Min(l => l.NumProteaseTermini));

                WriteModifications(sw, parameters.Modifications);

                var modChars = parameters.Modifications.Where(m => m.IsVariable).ToDictionary(m => m.Symbol[0], m => m.Mass);

                WriteParameters(sw, parameters.Parameters);

                //End of search_summary
                sw.WriteLine("    </search_summary>");

                var spectrumId = 0;
                foreach (var sph in t)
                {
                    spectrumId++;

                    sw.WriteLine(
                        "    <spectrum_query spectrum=\"{0}.{1}.{2}.{4}\" start_scan=\"{1}\" end_scan=\"{2}\" precursor_neutral_mass=\"{3:0.0000}\" assumed_charge=\"{4}\" index=\"{5}\">",
                        sph.Query.FileScan.Experimental,
                        sph.Query.FileScan.FirstScan,
                        sph.Query.FileScan.LastScan,
                        sph.ExperimentalMH - Atom.H.AverageMass,
                        sph.Query.Charge,
                        spectrumId);

                    sw.WriteLine("      <search_result>");

                    double massDiff = sph.TheoreticalMinusExperimentalMass;

                    if (!parameters.NotCombineRank1PSMs)
                    {
                        var pep = sph.Peptide;
                        WritePeptide(sw, sph, pep);

                        if (pep.Proteins.Count > 1)
                        {
                            for (int iProtein = 1; iProtein < pep.Proteins.Count; iProtein++)
                            {
                                WritePeptideProtein(sw, pep, iProtein);
                            }
                        }

                        for (int i = 1; i < sph.Peptides.Count; i++)
                        {
                            for (int iProtein = 0; iProtein < sph.Peptides[i].Proteins.Count; iProtein++)
                            {
                                WritePeptideProtein(sw, sph.Peptides[i], iProtein);
                            }
                        }
                        WriteModificationAndScore(sw, modChars, sph, pep);
                        sw.WriteLine("        </search_hit>");
                    }
                    else
                    {
                        var peps = sph.Peptides.GroupBy(m => PeptideUtils.GetMatchedSequence(m.Sequence)).ToList().ConvertAll(m => m.ToArray()).ToList();

                        foreach (var pepList in peps)
                        {
                            var pep = pepList.First();
                            WritePeptide(sw, sph, pep);

                            if (pep.Proteins.Count > 1)
                            {
                                for (int iProtein = 1; iProtein < pep.Proteins.Count; iProtein++)
                                {
                                    WritePeptideProtein(sw, pep, iProtein);
                                }
                            }

                            for (int i = 1; i < pepList.Length; i++)
                            {
                                for (int iProtein = 0; iProtein < pepList[i].Proteins.Count; iProtein++)
                                {
                                    WritePeptideProtein(sw, pepList[i], iProtein);
                                }
                            }
                            WriteModificationAndScore(sw, modChars, sph, pep);

                            sw.WriteLine("        </search_hit>");
                        }
                    }
                    sw.WriteLine("      </search_result>");
                    sw.WriteLine("    </spectrum_query>");
                }

                //End of msms_run_summary
                sw.WriteLine("  </msms_run_summary>");
                sw.WriteLine("</msms_pipeline_analysis>");
            }
        }
        private void iIdentifiedSpectrumDataGridView_SelectionChanged(object sender, EventArgs e)
        {
            CurrencyManager cm       = (CurrencyManager)this.BindingContext[peptides];
            var             spectrum = cm.Current as IIdentifiedSpectrum;

            if (spectrum.Annotations.ContainsKey("PepMutation"))
            {
                zgcPeaks.MasterPane.Title.Text = string.Format("MH={0:0.00000},PPM={1:0.0},SEQ={2},MUT={3},COUNT={4}",
                                                               spectrum.TheoreticalMH,
                                                               PrecursorUtils.mz2ppm(spectrum.TheoreticalMH, spectrum.TheoreticalMinusExperimentalMass),
                                                               spectrum.Sequence,
                                                               spectrum.Annotations["PepMutation"],
                                                               (from a in spectrum.Annotations
                                                                where a.Key.EndsWith("_PepCount")
                                                                select Convert.ToInt32(a.Value)).Sum());
            }
            else
            {
                zgcPeaks.MasterPane.Title.Text = string.Format("MH={0:0.00000},PPM={1:0.0},SEQ={2}",
                                                               spectrum.TheoreticalMH,
                                                               PrecursorUtils.mz2ppm(spectrum.TheoreticalMH, spectrum.TheoreticalMinusExperimentalMass),
                                                               spectrum.Sequence);
            }

            var mass = aas.MonoPeptideMass(PeptideUtils.GetMatchedSequence(spectrum.Sequence));

            if (Math.Abs(mass - spectrum.TheoreticalMass) > 0.1)
            {
                MessageBox.Show(string.Format("Error : {0} - {1}", mass, spectrum.TheoreticalMass));
                return;
            }

            var name = string.Format("{0}_{1}", spectrum.Query.FileScan.Experimental, spectrum.Query.FileScan.FirstScan);

            var peakPane = zgcPeaks.MasterPane.PaneList[0];

            peakPane.ClearData();

            var ppmPane = zgcPeaks.MasterPane.PaneList[1];

            ppmPane.ClearData();

            if (!mgfMap.ContainsKey(name))
            {
                MessageBox.Show("Cannot find peak list {0}", name);
                return;
            }

            var mgf = mgfMap[name];

            var maxIntensity = mgf.Max(m => m.Intensity);
            var maxMz        = Math.Min(2000, mgf.Max(m => m.Mz));

            var mzTolerance  = 0.02;
            var minIntensity = maxIntensity * 0.05;

            AddIonSeries(peakPane, ppmPane, mgf, mzTolerance, minIntensity, yBuilder, spectrum.Sequence, Color.Red);
            AddIonSeries(peakPane, ppmPane, mgf, mzTolerance, minIntensity, bBuilder, spectrum.Sequence, Color.Blue);

            if (spectrum.Charge > 2)
            {
                AddIonSeries(peakPane, ppmPane, mgf, mzTolerance, minIntensity, y2Builder, spectrum.Sequence, Color.Brown);
                AddIonSeries(peakPane, ppmPane, mgf, mzTolerance, minIntensity, b2Builder, spectrum.Sequence, Color.GreenYellow);
            }

            AddUnmatchedIons(peakPane, mgf);

            foreach (var pane in zgcPeaks.MasterPane.PaneList)
            {
                pane.XAxis.Scale.Min = 0;
                pane.XAxis.Scale.Max = maxMz;
            }
            zgcPeaks.UpdateGraph();
        }