Esempio n. 1
0
 // Returns molecule mass (or massH, for peptides)
 public TypedMass GetMoleculeMass()
 {
     Assume.IsTrue(Transition.IsCustom() || MzMassType.IsMassH());
     return(Transition.IsCustom()
         ? Transition.Adduct.MassFromMz(Mz, MzMassType)
         : new TypedMass(SequenceMassCalc.GetMH(Mz, Transition.Charge), MzMassType));
 }
Esempio n. 2
0
 public void Validate()
 {
     if (!string.IsNullOrEmpty(Formula))
     {
         try
         {
             MonoisotopicMass = SequenceMassCalc.FormulaMass(BioMassCalc.MONOISOTOPIC, Formula);
             AverageMass      = SequenceMassCalc.FormulaMass(BioMassCalc.AVERAGE, Formula);
         }
         catch (ArgumentException x)
         {
             throw new InvalidDataException(x.Message, x);  // Pass original as inner exception
         }
     }
     if (AverageMass == 0 || MonoisotopicMass == 0)
     {
         throw new InvalidDataException(Resources.CustomMolecule_Validate_Custom_molecules_must_specify_a_formula_or_valid_monoisotopic_and_average_masses_);
     }
     if (AverageMass > MAX_MASS || MonoisotopicMass > MAX_MASS)
     {
         throw new InvalidDataException(string.Format(Resources.CustomMolecule_Validate_The_mass__0__of_the_custom_molecule_exceeeds_the_maximum_of__1__,
                                                      AverageMass > MAX_MASS ? AverageMass : MonoisotopicMass, MAX_MASS));
     }
     if (AverageMass < MIN_MASS || MonoisotopicMass < MIN_MASS)
     {
         throw new InvalidDataException(string.Format(Resources.CustomMolecule_Validate_The_mass__0__of_the_custom_molecule_is_less_than_the_minimum_of__1__,
                                                      AverageMass < MIN_MASS ? AverageMass : MonoisotopicMass, MIN_MASS));
     }
 }
Esempio n. 3
0
 public ElibSpectrumInfo(String peptideModSeq, int charge, int bestFileId, IEnumerable <KeyValuePair <int, FileData> > fileDatas)
 {
     PeptideModSeq = peptideModSeq;
     Key           = new LibKey(SequenceMassCalc.NormalizeModifiedSequence(peptideModSeq), charge);
     BestFileId    = bestFileId;
     FileDatas     = ImmutableSortedList.FromValues(fileDatas);
 }
Esempio n. 4
0
        private void WriteExplicitMods(XmlWriter writer, string name,
                                       string nameElMod, IsotopeLabelType labelType, IEnumerable <ExplicitMod> mods,
                                       string sequence)
        {
            if (mods == null || (labelType == null && string.IsNullOrEmpty(sequence)))
            {
                return;
            }
            writer.WriteStartElement(name);
            if (labelType != null)
            {
                writer.WriteAttribute(ATTR.isotope_label, labelType);
            }

            if (!string.IsNullOrEmpty(sequence))
            {
                SequenceMassCalc massCalc = Settings.TransitionSettings.Prediction.PrecursorMassType == MassType.Monoisotopic ?
                                            SrmSettings.MonoisotopicMassCalc : SrmSettings.AverageMassCalc;
                foreach (ExplicitMod mod in mods)
                {
                    writer.WriteStartElement(nameElMod);
                    writer.WriteAttribute(ATTR.index_aa, mod.IndexAA);
                    writer.WriteAttribute(ATTR.modification_name, mod.Modification.Name);

                    double massDiff = massCalc.GetModMass(sequence[mod.IndexAA], mod.Modification);

                    writer.WriteAttribute(ATTR.mass_diff,
                                          string.Format(CultureInfo.InvariantCulture, @"{0}{1}", (massDiff < 0 ? string.Empty : @"+"),
                                                        Math.Round(massDiff, 1)));

                    writer.WriteEndElement();
                }
            }
            writer.WriteEndElement();
        }
Esempio n. 5
0
        public void TestSingleAminoAcidLinkedPeptide()
        {
            var srmSettings                = SrmSettingsList.GetDefault();
            var mainPeptide                = new Peptide("A");
            var staticMod                  = new StaticMod("crosslinker", null, null, "-C2");
            var linkedPeptide              = new LinkedPeptide(new Peptide("D"), 0, null);
            var mainTransitionGroup        = new TransitionGroup(mainPeptide, Adduct.SINGLY_PROTONATED, IsotopeLabelType.light);
            var mainTransitionGroupDocNode = new TransitionGroupDocNode(mainTransitionGroup,
                                                                        Annotations.EMPTY, srmSettings, null, null,
                                                                        ExplicitTransitionGroupValues.EMPTY, null, new TransitionDocNode[0], false);
            var modsWithoutLinkedPeptide = new ExplicitMods(mainPeptide, new[] { new ExplicitMod(0, staticMod), }, new TypedExplicitModifications[0]);

            Assert.AreEqual("C3H7NO2", AminoAcidFormulas.Default.GetFormula("A").ToString());
            Assert.AreEqual("C3H7NO2", mainTransitionGroupDocNode.GetNeutralFormula(srmSettings, null).Molecule.ToString());
            Assert.AreEqual("CH7NO2", mainTransitionGroupDocNode.GetNeutralFormula(srmSettings, modsWithoutLinkedPeptide).Molecule.ToString());
            Assert.AreEqual("C4H7NO4", AminoAcidFormulas.Default.GetFormula("D").ToString());
            var modsWithLinkedPeptide = new ExplicitMods(mainPeptide,
                                                         new[] { new ExplicitMod(0, staticMod).ChangeLinkedPeptide(linkedPeptide) },
                                                         new TypedExplicitModifications[0]);

            Assert.AreEqual("C5H14N2O6", mainTransitionGroupDocNode.GetNeutralFormula(srmSettings, modsWithLinkedPeptide).Molecule.ToString());
            var mainComplexFragmentIon   = new ComplexFragmentIon(new Transition(mainTransitionGroup, IonType.precursor, mainPeptide.Length - 1, 0, Adduct.SINGLY_PROTONATED), null, modsWithLinkedPeptide.Crosslinks);
            var linkedComplexFragmentIon = new ComplexFragmentIon(
                new Transition(linkedPeptide.GetTransitionGroup(IsotopeLabelType.light, Adduct.SINGLY_PROTONATED),
                               IonType.precursor, linkedPeptide.Peptide.Length - 1, 0, Adduct.SINGLY_PROTONATED), null, LinkedPeptide.EMPTY_CROSSLINK_STRUCTURE);
            var complexFragmentIon =
                mainComplexFragmentIon.AddChild(new ModificationSite(0, staticMod.Name), linkedComplexFragmentIon);
            var transition       = complexFragmentIon.MakeTransitionDocNode(srmSettings, modsWithLinkedPeptide, null);
            var sequenceMassCalc = new SequenceMassCalc(MassType.Monoisotopic);
            var expectedMz       = sequenceMassCalc.GetPrecursorMass("A") + sequenceMassCalc.GetPrecursorMass("D") - 24 - BioMassCalc.MassProton;

            Assert.AreEqual(expectedMz, transition.Mz, .00001);
        }
Esempio n. 6
0
        public void TestGetIonFormula()
        {
            SequenceMassCalc sequenceMassCalc = new SequenceMassCalc(MassType.Monoisotopic);

            Assert.AreEqual(147.11, sequenceMassCalc.GetPrecursorMass("K"), .1);
            Assert.AreEqual("C6H14N2O2", sequenceMassCalc.GetMolecularFormula("K"));

            var label13C6K = new StaticMod("label13C6K", "K", null, LabelAtoms.C13);

            sequenceMassCalc.AddStaticModifications(new [] { label13C6K });
            Assert.AreEqual(153.11, sequenceMassCalc.GetPrecursorMass("K"), .1);
            Assert.AreEqual("C'6H14N2O2", sequenceMassCalc.GetMolecularFormula("K"));

            var label15N2K = new StaticMod("label15N2K", "K", null, LabelAtoms.N15);

            sequenceMassCalc.AddStaticModifications(new[] { label15N2K });
            Assert.AreEqual(155.11, sequenceMassCalc.GetPrecursorMass("K"), .1);
            Assert.AreEqual("C'6H14N'2O2", sequenceMassCalc.GetMolecularFormula("K"));

            var labelLaK = new StaticMod("labelLaK", "K", null, "La");

            sequenceMassCalc.AddStaticModifications(new[] { labelLaK });
            Assert.AreEqual(294.033, sequenceMassCalc.GetPrecursorMass("K"), .1);
            Assert.AreEqual("C'6H14LaN'2O2", sequenceMassCalc.GetMolecularFormula("K"));

            // Check our ability to handle strangely constructed chemical formulas
            Assert.AreEqual(Molecule.Parse("C12H9S2P0").ToString(), Molecule.Parse("C12H9S2").ToString());  // P0 is weird
            Assert.AreEqual(Molecule.Parse("C12H9S2P1").ToString(), Molecule.Parse("C12H9S2P").ToString()); // P1 is weird
            Assert.AreEqual(Molecule.Parse("C12H9S0P").ToString(), Molecule.Parse("C12H9P").ToString());    // S0 is weird, and not at end
        }
Esempio n. 7
0
        private void UpdateAverageAndMonoTextsForFormula()
        {
            string formula = textFormula.Text;

            if (string.IsNullOrEmpty(formula))
            {
                // Leave any precalculated masses in place for user convenience
                textMono.Enabled = textAverage.Enabled = true;
            }
            else
            {
                // Formula drives mass, no direct edit allowed
                textMono.Enabled = textAverage.Enabled = false;
                try
                {
                    var monoMass    = SequenceMassCalc.ParseModMass(BioMassCalc.MONOISOTOPIC, formula);
                    var averageMass = SequenceMassCalc.ParseModMass(BioMassCalc.AVERAGE, formula);
                    GetTextFromMass(monoMass);     // Just to see if it throws or not
                    GetTextFromMass(averageMass);  // Just to see if it throws or not
                    MonoMass              = monoMass;
                    AverageMass           = averageMass;
                    textFormula.ForeColor = Color.Black;
                }
                catch (ArgumentException)
                {
                    textFormula.ForeColor = Color.Red;
                    textMono.Text         = textAverage.Text = string.Empty;
                }
            }
        }
Esempio n. 8
0
        private static CellDesc CreateIon(IonType type, int ordinal, TypedMass massH, Adduct charge,
                                          IEnumerable <DocNode> choices, ICollection <DocNode> chosen, Transition tranSelected,
                                          RenderTools rt)
        {
            double   mz   = SequenceMassCalc.GetMZ(massH, charge);
            CellDesc cell = CreateData(string.Format(@"{0:F02}", mz), rt);

            foreach (TransitionDocNode nodeTran in choices)
            {
                Transition tran = nodeTran.Transition;
                if (tran.IonType == type &&
                    tran.Ordinal == ordinal &&
                    tran.Adduct == charge)
                {
                    cell.Font = rt.FontBold;
                    if (Equals(tran, tranSelected))
                    {
                        cell.Brush = rt.BrushSelected; // Stop after selected
                        break;
                    }
                    if (!chosen.Contains(nodeTran))
                    {
                        cell.Brush = rt.BrushChoice;  // Keep looking
                    }
                    else
                    {
                        cell.Brush = rt.BrushChosen;  // Stop after chosen
                        break;
                    }
                }
            }

            return(cell);
        }
Esempio n. 9
0
        private void LoadPeptides(IEnumerable <DbIonMobilityPeptide> peptides)
        {
            var dictLibrary = new Dictionary <String, DbIonMobilityPeptide>();

            foreach (var pep in peptides)
            {
                var dict = dictLibrary;
                try
                {
                    // Unnormalized modified sequences will not match anything.  The user interface
                    // attempts to enforce only normalized modified sequences, but this extra protection
                    // handles IonMobilitydb files edited outside Skyline.  TODO - copied from iRT code - is this an issue here?
                    var peptide = SequenceMassCalc.NormalizeModifiedSequence(pep.PeptideModSeq);
                    DbIonMobilityPeptide ignored;
                    if (!dict.TryGetValue(peptide, out ignored))
                    {
                        dict.Add(peptide, pep);
                    }
                }
                catch (ArgumentException)
                {
                }
            }

            DictLibrary = dictLibrary;
        }
Esempio n. 10
0
        public void TestGetFragmentFormula()
        {
            var pepseq           = "PEPTIDE";
            var sequenceMassCalc = new SequenceMassCalc(MassType.Monoisotopic);
            var precursor        = FragmentedMolecule.EMPTY.ChangeModifiedSequence(
                new ModifiedSequence(pepseq, new ModifiedSequence.Modification[0], MassType.Monoisotopic));
            var peptide                = new Peptide(precursor.UnmodifiedSequence);
            var transitionGroup        = new TransitionGroup(peptide, Adduct.SINGLY_PROTONATED, IsotopeLabelType.light);
            var settings               = SrmSettingsList.GetDefault();
            var transitionGroupDocNode = new TransitionGroupDocNode(transitionGroup, Annotations.EMPTY, settings,
                                                                    ExplicitMods.EMPTY, null, null, null, new TransitionDocNode[0], false);

            foreach (var ionType in new[] { IonType.a, IonType.b, IonType.c, IonType.x, IonType.y, IonType.z })
            {
                for (int ordinal = 1; ordinal < pepseq.Length; ordinal++)
                {
                    var transition             = new Transition(transitionGroup, ionType, Transition.OrdinalToOffset(ionType, ordinal, pepseq.Length), 0, Adduct.SINGLY_PROTONATED);
                    var fragment               = precursor.ChangeFragmentIon(ionType, ordinal);
                    var actualMassDistribution = FragmentedMolecule.Settings.DEFAULT.GetMassDistribution(
                        fragment.FragmentFormula, 0, 0);
                    var expectedMz = sequenceMassCalc.GetFragmentMass(transition, transitionGroupDocNode.IsotopeDist);
                    if (expectedMz.IsMassH())
                    {
                        expectedMz = new TypedMass(expectedMz.Value - BioMassCalc.MassProton, expectedMz.MassType & ~MassType.bMassH);
                    }
                    var actualMz = actualMassDistribution.MostAbundanceMass;
                    if (Math.Abs(expectedMz - actualMz) > .001)
                    {
                        Assert.AreEqual(expectedMz, actualMz, .001, "Ion type {0} Ordinal {1}", ionType, ordinal);
                    }
                }
            }
        }
Esempio n. 11
0
 public TransitionDocNode(Transition id,
                          Annotations annotations,
                          TransitionLosses losses,
                          double massH,
                          TransitionIsotopeDistInfo isotopeDistInfo,
                          TransitionLibInfo libInfo,
                          Results <TransitionChromInfo> results)
     : base(id, annotations)
 {
     Losses = losses;
     if (losses != null)
     {
         massH -= losses.Mass;
     }
     if (id.IsCustom())
     {
         Mz = new SignedMz(BioMassCalc.CalculateIonMz(massH, id.Charge), id.IsNegative());
     }
     else
     {
         Mz = new SignedMz(SequenceMassCalc.GetMZ(massH, id.Charge) + SequenceMassCalc.GetPeptideInterval(id.DecoyMassShift), id.IsNegative());
     }
     IsotopeDistInfo = isotopeDistInfo;
     LibInfo         = libInfo;
     Results         = results;
 }
Esempio n. 12
0
        private MatchedFragmentIon MakeMatchedFragmentIon(IonType ionType, int ionIndex, Adduct adduct, TransitionLosses transitionLosses, out double matchMz)
        {
            var       moleculeMasses = MoleculeMassesObj;
            int       ordinal;
            int       peptideLength = TargetInfoObj.LookupSequence.Sequence?.Length ?? 0;
            TypedMass matchMass, predictedMass;

            if (ionType == IonType.precursor)
            {
                matchMass     = moleculeMasses.MatchIonMasses.PrecursorMass;
                predictedMass = moleculeMasses.PredictIonMasses.PrecursorMass;
                ordinal       = peptideLength;
            }
            else
            {
                matchMass     = moleculeMasses.MatchIonMasses.GetIonMass(ionType, ionIndex);
                predictedMass = moleculeMasses.PredictIonMasses.GetIonMass(ionType, ionIndex);
                ordinal       = Transition.OffsetToOrdinal(ionType, ionIndex, peptideLength);
            }

            if (transitionLosses != null)
            {
                matchMass     -= transitionLosses.Mass;
                predictedMass -= transitionLosses.Mass;
            }

            double predictedMz = SequenceMassCalc.GetMZ(predictedMass, adduct);

            matchMz = SequenceMassCalc.GetMZ(matchMass, adduct);
            return(new MatchedFragmentIon(ionType, ordinal, adduct, null, transitionLosses, predictedMz));
        }
Esempio n. 13
0
        public static Modification MakeModification(string unmodifiedSequence, ExplicitMod explicitMod)
        {
            var staticMod = explicitMod.Modification;
            int i         = explicitMod.IndexAA;
            var monoMass  = staticMod.MonoisotopicMass ??
                            SrmSettings.MonoisotopicMassCalc.GetAAModMass(unmodifiedSequence[i], i,
                                                                          unmodifiedSequence.Length);
            var avgMass = staticMod.AverageMass ??
                          SrmSettings.AverageMassCalc.GetAAModMass(unmodifiedSequence[i], i,
                                                                   unmodifiedSequence.Length);

            if (monoMass == 0 && avgMass == 0)
            {
                char aa = unmodifiedSequence[i];
                if ((staticMod.LabelAtoms & LabelAtoms.LabelsAA) != LabelAtoms.None && AminoAcid.IsAA(aa))
                {
                    string heavyFormula = SequenceMassCalc.GetHeavyFormula(aa, staticMod.LabelAtoms);
                    monoMass = SequenceMassCalc.FormulaMass(BioMassCalc.MONOISOTOPIC, heavyFormula,
                                                            SequenceMassCalc.MassPrecision);
                    avgMass = SequenceMassCalc.FormulaMass(BioMassCalc.AVERAGE, heavyFormula,
                                                           SequenceMassCalc.MassPrecision);
                }
            }
            return(new Modification(explicitMod, monoMass, avgMass));
        }
Esempio n. 14
0
 public void TestTokenizeFormula()
 {
     CollectionAssert.AreEqual(new[] { "C'", "6", "Cl", "2", "C", "H", "4", "-", "H", "24", "O" },
                               SequenceMassCalc.TokenizeFormula("C'6Cl2CH4-H24O").ToArray());
     // Test garbage characters before an element name.
     CollectionAssert.AreEqual(new[] { "x", "y", "z", "Element" },
                               SequenceMassCalc.TokenizeFormula("xyzElement").ToArray());
 }
Esempio n. 15
0
        private static string GetMzLabel(TransitionGroup tranGroup, double precursorMz)
        {
            int?   massShift = tranGroup.DecoyMassShift;
            double shift     = SequenceMassCalc.GetPeptideInterval(massShift);

            return(string.Format(@"{0:F04}{1}", precursorMz - shift,
                                 Transition.GetDecoyText(massShift)));
        }
Esempio n. 16
0
        private static string GetMzLabel(TransitionDocNode nodeTran)
        {
            int?   massShift = nodeTran.Transition.DecoyMassShift;
            double shift     = SequenceMassCalc.GetPeptideInterval(massShift);

            return(string.Format(@"{0:F04}{1}", nodeTran.Mz - shift,
                                 Transition.GetDecoyText(massShift)));
        }
Esempio n. 17
0
        public void TestParseModParts()
        {
            var bioMassCalc = new BioMassCalc(MassType.Monoisotopic);

            CollectionAssert.AreEqual(new[] { "C'2", "" }, SequenceMassCalc.ParseModParts(bioMassCalc, "C'2"));
            CollectionAssert.AreEqual(new[] { "", "C2" }, SequenceMassCalc.ParseModParts(bioMassCalc, "-C2"));
            CollectionAssert.AreEqual(new[] { "C'2", "C2" }, SequenceMassCalc.ParseModParts(bioMassCalc, "C'2-C2"));
        }
Esempio n. 18
0
 public virtual Target GetNormalizedModifiedSequence()
 {
     if (_normalizedModifiedSequence == null)
     {
         var seq = SequenceMassCalc.NormalizeModifiedSequence(_peptideModSeq.Sequence);
         _normalizedModifiedSequence = _peptideModSeq.ChangeSequence(seq);
     }
     return(_normalizedModifiedSequence);
 }
Esempio n. 19
0
        public static string GetMassIndexText(int massIndex)
        {
            if (massIndex == 0)
            {
                return(string.Empty);
            }

            return(@" " + SequenceMassCalc.GetMassIDescripion(massIndex));
        }
Esempio n. 20
0
        public static bool ValidateRow(object[] columns, IWin32Window parent, int lineNumber, bool postiveTime)
        {
            if (columns.Length != 2)
            {
                MessageDlg.Show(parent, string.Format(Resources.PeptideGridViewDriver_ValidateRow_The_pasted_text_must_have_two_columns_));
                return(false);
            }

            string seq     = columns[COLUMN_SEQUENCE] as string;
            string time    = columns[COLUMN_TIME] as string;
            string message = null;

            if (string.IsNullOrWhiteSpace(seq))
            {
                message = string.Format(Resources.PeptideGridViewDriver_ValidateRow_Missing_peptide_sequence_on_line__0_, lineNumber);
            }
            else if (!FastaSequence.IsExSequence(seq))
            {
                message = string.Format(Resources.PeptideGridViewDriver_ValidateRow_The_text__0__is_not_a_valid_peptide_sequence_on_line__1_, seq, lineNumber);
            }
            else
            {
                try
                {
                    columns[COLUMN_SEQUENCE] = SequenceMassCalc.NormalizeModifiedSequence(seq);
                }
                catch (Exception x)
                {
                    message = x.Message;
                }

                if (message == null)
                {
                    double dTime;
                    if (string.IsNullOrWhiteSpace(time))
                    {
                        message = string.Format(Resources.PeptideGridViewDriver_ValidateRow_Missing_value_on_line__0_, lineNumber);
                    }
                    else if (!double.TryParse(time, out dTime))
                    {
                        message = string.Format(Resources.PeptideGridViewDriver_ValidateRow_Invalid_decimal_number_format__0__on_line__1_, time, lineNumber);
                    }
                    else if (postiveTime && dTime <= 0)
                    {
                        message = string.Format(Resources.PeptideGridViewDriver_ValidateRow_The_time__0__must_be_greater_than_zero_on_line__1_, time, lineNumber);
                    }
                    else
                    {
                        return(true);
                    }
                }
            }

            MessageDlg.Show(parent, message);
            return(false);
        }
Esempio n. 21
0
 public static TransitionLibInfo GetLibInfo(Transition transition, double massH,
                                            IDictionary <double, LibraryRankedSpectrumInfo.RankedMI> ranks)
 {
     LibraryRankedSpectrumInfo.RankedMI rmi;
     if (ranks == null || !ranks.TryGetValue(SequenceMassCalc.GetMZ(massH, transition.Charge), out rmi))
     {
         return(null);
     }
     return(new TransitionLibInfo(rmi.Rank, rmi.Intensity));
 }
Esempio n. 22
0
                public SequenceAndCharge(string sequenceAndCharge)
                {
                    const int min = TransitionGroup.MIN_PRECURSOR_CHARGE;
                    const int max = TransitionGroup.MAX_PRECURSOR_CHARGE;

                    string seq = Transition.StripChargeIndicators(sequenceAndCharge, min, max);

                    ModifiedSequence = SequenceMassCalc.NormalizeModifiedSequence(new Target(seq));
                    Charge           = Transition.GetChargeFromIndicator(sequenceAndCharge, min, max, Adduct.SINGLY_PROTONATED);
                }
Esempio n. 23
0
        public static string LineSeparateMzs(params double[] mzValues)
        {
            var sb = new StringBuilder();

            foreach (var value in mzValues)
            {
                sb.AppendLine(SequenceMassCalc.PersistentMZ(value).ToString(CultureInfo.InvariantCulture));
            }
            return(sb.ToString());
        }
Esempio n. 24
0
 public static bool IsValidLibKey(string key)
 {
     try
     {
         SequenceMassCalc.FormulaMass(BioMassCalc.AVERAGE, key);
     }
     catch
     {
         return(false);
     }
     return(true);
 }
Esempio n. 25
0
        public double GetMassI(int massIndex, int?decoyMassShift = null)
        {
            // Return the original monoisotopic mass + H, if requested to maintain an exact match.
            if (massIndex == 0 && !decoyMassShift.HasValue)
            {
                return(_monoisotopicMass);
            }
            // Otherwize use the charge to convert from the peak center m/z values
            double shift = SequenceMassCalc.GetPeptideInterval(decoyMassShift);    // Correct for shift applied to the distribution

            return(_isMassH ? SequenceMassCalc.GetMH(ExpectedPeaks[MassIndexToPeakIndex(massIndex)].Mz - shift, _charge) : BioMassCalc.CalculateIonMassFromMz(ExpectedPeaks[MassIndexToPeakIndex(massIndex)].Mz - shift, _charge));
        }
Esempio n. 26
0
        public void TestSequenceMassCalcNormalizeModifiedSequence()
        {
            const string normalizedModifiedSequence = "ASDF[+6.0]GHIJ";

            Assert.AreEqual(normalizedModifiedSequence, SequenceMassCalc.NormalizeModifiedSequence("ASDF[6]GHIJ"));
            Assert.AreEqual(normalizedModifiedSequence, SequenceMassCalc.NormalizeModifiedSequence("ASDF[+6]GHIJ"));
            Assert.AreSame(normalizedModifiedSequence, SequenceMassCalc.NormalizeModifiedSequence(normalizedModifiedSequence));

            Assert.AreEqual("ASDF[-6.0]GHIJ", SequenceMassCalc.NormalizeModifiedSequence("ASDF[-6]GHIJ"));

            AssertEx.ThrowsException <ArgumentException>(() => SequenceMassCalc.NormalizeModifiedSequence("ASC[Carbomidomethyl C]FGHIJ"));
            AssertEx.ThrowsException <ArgumentException>(() => SequenceMassCalc.NormalizeModifiedSequence("ASC[6"));
        }
Esempio n. 27
0
        private MoleculeMasses GetCrosslinkMasses(SrmSettings settings)
        {
            var predictDocNode = MakeTransitionGroupWithAllPossibleChildren(settings, TargetInfoObj.TransitionGroupDocNode.LabelType);
            TransitionGroupDocNode matchDocNode;

            if (Equals(TargetInfoObj.TransitionGroupDocNode.LabelType, TargetInfoObj.SpectrumLabelType))
            {
                matchDocNode = predictDocNode;
            }
            else
            {
                matchDocNode = MakeTransitionGroupWithAllPossibleChildren(settings, TargetInfoObj.SpectrumLabelType);
            }

            var matchTransitions = matchDocNode.Transitions.ToDictionary(child => child.Key(matchDocNode));


            var predictFragments = new List <MatchedFragmentIon>();
            var matchFragments   = new List <MatchedFragmentIon>();

            foreach (var predictedTransition in predictDocNode.Transitions)
            {
                var key = predictedTransition.Key(null);
                TransitionDocNode matchTransition;
                if (!matchTransitions.TryGetValue(key, out matchTransition))
                {
                    continue;
                }

                var    complexFragmentIonName = predictedTransition.ComplexFragmentIon.GetName();
                var    ionType      = DecideIonType(complexFragmentIonName);
                string fragmentName = predictedTransition.ComplexFragmentIon.GetFragmentIonName();
                var    predictedIon = new MatchedFragmentIon(ionType, predictFragments.Count + 1,
                                                             predictedTransition.Transition.Adduct, fragmentName, predictedTransition.Losses,
                                                             predictedTransition.Mz)
                                      .ChangeComplexFragmentIonName(complexFragmentIonName);
                predictFragments.Add(predictedIon);
                matchFragments.Add(predictedIon.ChangePredictedMz(matchTransition.Mz));
            }

            var matchMasses = new IonMasses(
                SequenceMassCalc.GetMH(matchDocNode.PrecursorMz, matchDocNode.PrecursorAdduct,
                                       MassType.MonoisotopicMassH), IonTable <TypedMass> .EMPTY)
                              .ChangeKnownFragments(matchFragments);
            var predictMasses = new IonMasses(
                SequenceMassCalc.GetMH(predictDocNode.PrecursorMz, predictDocNode.PrecursorAdduct,
                                       MassType.MonoisotopicMassH), IonTable <TypedMass> .EMPTY)
                                .ChangeKnownFragments(predictFragments);

            return(new MoleculeMasses(predictDocNode.PrecursorMz, matchMasses).ChangePredictIonMasses(predictMasses));
        }
Esempio n. 28
0
 public void TestGetHeavyFormula()
 {
     Assert.AreEqual("C'O2", SequenceMassCalc.GetHeavyFormula("CO2", LabelAtoms.C13));
     Assert.AreEqual("C'O2", SequenceMassCalc.GetHeavyFormula("C'O2", LabelAtoms.C13));
     Assert.AreEqual("C'", SequenceMassCalc.GetHeavyFormula("C", LabelAtoms.C13));
     Assert.AreEqual("N'", SequenceMassCalc.GetHeavyFormula("N", LabelAtoms.N15));
     Assert.AreEqual("O'", SequenceMassCalc.GetHeavyFormula("O", LabelAtoms.O18));
     Assert.AreEqual("H'", SequenceMassCalc.GetHeavyFormula("H", LabelAtoms.H2));
     Assert.AreEqual("Cl'", SequenceMassCalc.GetHeavyFormula("Cl", LabelAtoms.Cl37));
     Assert.AreEqual("Br'", SequenceMassCalc.GetHeavyFormula("Br", LabelAtoms.Br81));
     Assert.AreEqual("P'", SequenceMassCalc.GetHeavyFormula("P", LabelAtoms.P32));
     Assert.AreEqual("S\"", SequenceMassCalc.GetHeavyFormula("S", LabelAtoms.S33));
     Assert.AreEqual("S'", SequenceMassCalc.GetHeavyFormula("S", LabelAtoms.S34));
 }
Esempio n. 29
0
        /// <summary>
        /// Calculates the matching charge within a tolerance for a mass, assuming (de)protonation.
        /// </summary>
        /// <param name="mass">The mass to calculate charge for (actually massH if !IsCustomIon)</param>
        /// <param name="mz">The desired m/z value the charge should produce</param>
        /// <param name="tolerance">How far off the actual m/z is allowed to be</param>
        /// <param name="isCustomIon">Is this a custom ion formula?</param>
        /// <param name="minCharge">Minimum charge to consider</param>
        /// <param name="maxCharge">Maximum charge to consider</param>
        /// <param name="massShifts">Possible mass shifts that may have been applied to decoys</param>
        /// <param name="massShiftType"></param>
        /// <param name="massShift">Mass shift required to to achieve this charge state or zero</param>
        /// <param name="nearestCharge">closest matching charge, useful when return value is null</param>
        /// <returns>A matching charge or null, in which case the closest non-matching charge can be found in the nearestCharge value.</returns>
        public static Adduct CalcCharge(TypedMass mass, double mz, double tolerance, bool isCustomIon, int minCharge, int maxCharge,
                                        ICollection <int> massShifts, MassShiftType massShiftType, out int massShift, out int nearestCharge)
        {
            Assume.IsTrue(minCharge <= maxCharge);

            massShift = 0;

            nearestCharge = 0;
            double nearestDelta = double.MaxValue;

            for (int i = minCharge; i <= maxCharge; i++)
            {
                if (i != 0) // Avoid z=0 if we're entertaining negative charge states
                {
                    double calculatedMz = isCustomIon
                        ? Adduct.FromChargeProtonated(i).MzFromNeutralMass(mass)
                        : SequenceMassCalc.GetMZ(mass, i);
                    double delta           = mz - calculatedMz;
                    double deltaAbs        = Math.Abs(delta);
                    int    potentialShift  = (int)Math.Round(deltaAbs);
                    double fractionalDelta = deltaAbs - potentialShift;
                    if (MatchMz(fractionalDelta, tolerance) && MatchMassShift(potentialShift, massShifts, massShiftType))
                    {
                        massShift = potentialShift;
                        if (delta < 0)
                        {
                            massShift = -massShift;
                        }
                        var result = i;
                        nearestCharge = i;
                        return(Adduct.FromCharge(result, isCustomIon ? Adduct.ADDUCT_TYPE.non_proteomic : Adduct.ADDUCT_TYPE.proteomic));
                    }
                    if (deltaAbs < nearestDelta)
                    {
                        nearestDelta  = deltaAbs;
                        nearestCharge = i;
                    }
                    // If the charge is positive and the calculated m/z is smaller than the desired m/z
                    // increasing the charge further cannot possibly produce a match
                    if (massShiftType == MassShiftType.none && minCharge > 0 && delta > 0)
                    {
                        break;
                    }
                }
            }

            Debug.Assert(nearestCharge != 0);   // Could only happen if min > max

            return(Adduct.EMPTY);
        }
Esempio n. 30
0
 public XmlPeptide(PepV01 peptide, XmlTransition[] transitions)
 {
     Begin           = peptide.Begin;
     End             = peptide.End;
     Sequence        = peptide.Sequence;
     PrevAA          = peptide.PrevAA;
     NextAA          = peptide.NextAA;
     NeutralMass     = SequenceMassCalc.PersistentNeutral(peptide.MassH);
     MissedCleavages = peptide.MissedCleavages;
     if (peptide.PredictedRetentionTime.HasValue)
     {
         PredictedRetentionTime = Math.Round(peptide.PredictedRetentionTime.Value, 2);
     }
     Transitions = transitions;
 }
Esempio n. 31
0
        /// <summary>
        /// Test only method for creating a <see cref="BiblioSpecLibrary"/> file
        /// from another loaded <see cref="Library"/>.  Should this move into test project?
        /// </summary>
        /// <param name="streamManager">Provides access to the file system</param>
        /// <param name="path">Path to write to</param>
        /// <param name="library">The loaded library to use as a data source</param>
        public static void Write(IStreamManager streamManager, string path, Library library)
        {
            using (FileSaver fs = new FileSaver(path, streamManager))
            using (Stream outStream = streamManager.CreateStream(fs.SafeName, FileMode.Create, true))
            {
                outStream.Write(BitConverter.GetBytes(library.SpectrumCount), 0, sizeof(int)); // num_spectra
                outStream.Write(BitConverter.GetBytes(0), 0, sizeof(int));             // filtered
                outStream.Write(BitConverter.GetBytes(1), 0, sizeof(int));             // version1
                outStream.Write(BitConverter.GetBytes(1), 0, sizeof(int));             // version2
                outStream.Write(BitConverter.GetBytes(0), 0, sizeof(int));             // next_id

                SequenceMassCalc calc = new SequenceMassCalc(MassType.Monoisotopic);

                byte[] seqBuffer = new byte[1024];

                int scanNum = 1;

                foreach (var key in library.Keys)
                {
                    SpectrumPeaksInfo peaksInfo;
                    if (!library.TryLoadSpectrum(key, out peaksInfo))
                        continue;

                    string sequence = key.Sequence;
                    // Only works for unmodified sequence
                    Debug.Assert(!key.IsModified);
                    double precursorMH = calc.GetPrecursorMass(sequence);
                    int charge = key.Charge;
                    float precursorMz = (float) SequenceMassCalc.GetMZ(precursorMH, charge);

                    outStream.Write(BitConverter.GetBytes(scanNum), 0, sizeof(int));      // scan_num
                    outStream.Write(BitConverter.GetBytes(2), 0, sizeof(int));              // scan_type
                    outStream.Write(BitConverter.GetBytes(precursorMz), 0, sizeof(float));  // pre_mz
                    outStream.Write(BitConverter.GetBytes(charge), 0, sizeof(int));         // scan_type
                    outStream.Write(BitConverter.GetBytes(0f), 0, sizeof(int));             // r_time
                    outStream.Write(BitConverter.GetBytes(peaksInfo.Peaks.Length), 0, sizeof(int)); // num_peaks
                    outStream.Write(BitConverter.GetBytes(0), 0, sizeof(int));               // 32-bit peak_ptr
                    outStream.Write(BitConverter.GetBytes(sequence.Length), 0, sizeof(int)); // seq_len
                    outStream.Write(BitConverter.GetBytes(0), 0, sizeof(int));               // annot
                    outStream.Write(BitConverter.GetBytes(scanNum), 0, sizeof(int));         // copies (bogus value for ranking)
                    outStream.Write(BitConverter.GetBytes(0), 0, sizeof(int));               // lib_id
                    scanNum++;

                    // Sequence
                    int len = sequence.Length;
                    seqBuffer[len] = 0;
                    Encoding.UTF8.GetBytes(sequence, 0, len, seqBuffer, 0);
                    outStream.Write(seqBuffer, 0, len + 1);
                    // Modifications
                    const string zeros = "000000000000000000000000000000000000000000000000000"; // Not L10N
                    Encoding.UTF8.GetBytes(zeros.Substring(0, len), 0, len, seqBuffer, 0);
                    outStream.Write(seqBuffer, 0, len + 1);
                    // Peaks
                    foreach (var mi in peaksInfo.Peaks)
                    {
                        outStream.Write(BitConverter.GetBytes((float)mi.Mz), 0, sizeof(float));
                        outStream.Write(BitConverter.GetBytes(mi.Intensity), 0, sizeof(float));
                    }
                }

                streamManager.Finish(outStream);
                fs.Commit();
            }
        }
Esempio n. 32
0
        private bool EquivalentFormulas(char aa, StaticMod obj)
        {
            SequenceMassCalc modCalc = new SequenceMassCalc(MassType.Monoisotopic);

            double unexplainedMassThis, unexplainedMassObj;

            string formulaThis = modCalc.GetModFormula(aa, this, out unexplainedMassThis);
            string formulaObj = modCalc.GetModFormula(aa, obj, out unexplainedMassObj);

            // If either is null, both must be null.
            if (formulaThis == null || formulaObj == null)
                return formulaThis == null && formulaObj == null;

            return unexplainedMassThis == unexplainedMassObj &&
                   ArrayUtil.EqualsDeep(GetFormulaModCounts(formulaThis).ToArray(),
                                        GetFormulaModCounts(formulaObj).ToArray());
        }
Esempio n. 33
0
 public IEnumerable<FragmentIon> GetFragmentIons(IEnumerable<IonType> ionTypes, SequenceMassCalc calc)
 {
     double[,] masses = calc.GetFragmentIonMasses(Sequence);
     int len = masses.GetLength(1);
     foreach (IonType ionType in ionTypes)
     {
         for (int i = 0; i < len; i++)
         {
             yield return new FragmentIon(this, ionType, i, masses[(int)ionType, i]);
         }
     }
 }
Esempio n. 34
0
 public void CalcMass(SequenceMassCalc massCalc)
 {
     MassH = massCalc.GetPrecursorMass(Sequence);
 }
Esempio n. 35
0
 private static double[] CalcModMasses(Peptide peptide, IEnumerable<ExplicitMod> mods,
     SequenceMassCalc massCalc)
 {
     double[] masses = new double[peptide.Length];
     string seq = peptide.Sequence;
     foreach (ExplicitMod mod in mods)
         masses[mod.IndexAA] += massCalc.GetModMass(seq[mod.IndexAA], mod.Modification);
     return masses;
 }
Esempio n. 36
0
 private static SequenceMassCalc CreateMassCalc(MassType type, IEnumerable<StaticMod> staticMods, IEnumerable<StaticMod> heavyMods)
 {
     SequenceMassCalc calc = new SequenceMassCalc(type);
     // Add implicit modifications to the mass calculator
     calc.AddStaticModifications(from mod in staticMods
                                 where !mod.IsExplicit
                                 select mod);
     if (heavyMods != null)
     {
         calc.AddHeavyModifications(from mod in heavyMods
                                    where !mod.IsExplicit
                                    select mod);
     }
     return calc;
 }