Example #1
0
        public static IList <ICollection <PeptideChromInfoData> > GetPeptideChromInfoDatas(MeasuredResults measuredResults, PeptideDocNode peptideDocNode)
        {
            var list           = new List <ICollection <PeptideChromInfoData> >();
            var peptideResults = peptideDocNode.Results;

            if (null == peptideResults)
            {
                return(list);
            }
            Assume.IsTrue(peptideResults.Count == measuredResults.Chromatograms.Count,
                          string.Format(@"Unexpected mismatch between precursor results {0} and chromatogram sets {1}", peptideResults.Count, measuredResults.Chromatograms.Count)); // CONSIDER: localize? Will users see this?
            for (int replicateIndex = 0; replicateIndex < peptideResults.Count; replicateIndex++)
            {
                var datas             = new List <PeptideChromInfoData>();
                var chromatograms     = measuredResults.Chromatograms[replicateIndex];
                var peptideChromInfos = peptideResults[replicateIndex];
                if (peptideChromInfos.IsEmpty)
                {
                    datas.Add(new PeptideChromInfoData(measuredResults, replicateIndex, null, null, peptideDocNode));
                }
                else
                {
                    foreach (var peptideChromInfo in peptideChromInfos)
                    {
                        var chromFileInfo = chromatograms.GetFileInfo(peptideChromInfo.FileId);
                        datas.Add(new PeptideChromInfoData(measuredResults, replicateIndex, chromFileInfo, peptideChromInfo, peptideDocNode));
                    }
                }
                list.Add(datas);
            }
            return(list);
        }
Example #2
0
        public static IList <ICollection <TransitionChromInfoData> > GetTransitionChromInfoDatas(MeasuredResults measuredResults, PeptideDocNode peptideDocNode, TransitionGroupDocNode transitionGroupDocNode, TransitionDocNode transitionDocNode)
        {
            var transitionResults = transitionDocNode.Results;
            var list = new List <ICollection <TransitionChromInfoData> >();

            if (null == transitionResults)
            {
                return(list);
            }
            Assume.IsTrue(transitionResults.Count == measuredResults.Chromatograms.Count,
                          string.Format(@"Unexpected mismatch between transition results {0} and chromatogram sets {1}", transitionResults.Count, measuredResults.Chromatograms.Count)); // CONSIDER: localize?
            for (int replicateIndex = 0; replicateIndex < transitionResults.Count; replicateIndex++)
            {
                var datas                = new List <TransitionChromInfoData>();
                var chromatograms        = measuredResults.Chromatograms[replicateIndex];
                var transitionChromInfos = transitionResults[replicateIndex];
                if (transitionChromInfos.IsEmpty)
                {
                    datas.Add(new TransitionChromInfoData(measuredResults, replicateIndex, null, null, peptideDocNode, transitionGroupDocNode, transitionDocNode));
                }
                else
                {
                    foreach (var transitionChromInfo in transitionChromInfos)
                    {
                        var chromFileInfo = chromatograms.GetFileInfo(transitionChromInfo.FileId);
                        datas.Add(new TransitionChromInfoData(measuredResults, replicateIndex, chromFileInfo, transitionChromInfo, peptideDocNode, transitionGroupDocNode, transitionDocNode));
                    }
                }
                list.Add(datas);
            }
            return(list);
        }
Example #3
0
        public static IList <ICollection <TransitionChromInfoData> > GetTransitionChromInfoDatas(MeasuredResults measuredResults, Results <TransitionChromInfo> transitionResults)
        {
            var list = new List <ICollection <TransitionChromInfoData> >();

            if (null == transitionResults)
            {
                return(list);
            }
            Assume.IsTrue(transitionResults.Count == measuredResults.Chromatograms.Count,
                          string.Format("Unexpected mismatch between transition results {0} and chromatogram sets {1}", transitionResults.Count, measuredResults.Chromatograms.Count)); // Not L10N?
            for (int replicateIndex = 0; replicateIndex < transitionResults.Count; replicateIndex++)
            {
                var datas                = new List <TransitionChromInfoData>();
                var chromatograms        = measuredResults.Chromatograms[replicateIndex];
                var transitionChromInfos = transitionResults[replicateIndex];
                if (transitionChromInfos == null)
                {
                    datas.Add(new TransitionChromInfoData(measuredResults, replicateIndex, null, null));
                }
                else
                {
                    foreach (var transitionChromInfo in transitionChromInfos)
                    {
                        var chromFileInfo = chromatograms.GetFileInfo(transitionChromInfo.FileId);
                        datas.Add(new TransitionChromInfoData(measuredResults, replicateIndex, chromFileInfo, transitionChromInfo));
                    }
                }
                list.Add(datas);
            }
            return(list);
        }
Example #4
0
        public SpectrumFilterPair(PrecursorTextId precursorTextId, Color peptideColor, int id, double?minTime, double?maxTime,
                                  bool highAccQ1, bool highAccQ3)
        {
            Id = id;
            ModifiedSequence = precursorTextId.Target;
            PeptideColor     = peptideColor;
            Q1        = precursorTextId.PrecursorMz;
            Extractor = precursorTextId.Extractor;

            if (minTime.HasValue && maxTime.HasValue)
            {
                _filterByTime = true;
                _minTime      = minTime.Value;
                _maxTime      = maxTime.Value;
            }
            else
            {
                // If not min and max, then it should be neither. Asymmetric limits not supported.
                Assume.IsTrue(!minTime.HasValue && !maxTime.HasValue);
            }
            IonMobilityInfo     = precursorTextId.IonMobility;
            MinIonMobilityValue = IonMobilityInfo.IsEmpty ? null : IonMobilityInfo.IonMobility.Mobility - (IonMobilityInfo.IonMobilityExtractionWindowWidth ?? 0) / 2;
            MaxIonMobilityValue = IonMobilityInfo.IsEmpty ? null : MinIonMobilityValue + (IonMobilityInfo.IonMobilityExtractionWindowWidth ?? 0);
            HighAccQ1           = highAccQ1;
            HighAccQ3           = highAccQ3;

            Ms1ProductFilters = SimProductFilters = Ms2ProductFilters = EMPTY_FILTERS;

            if (Q1 == 0)
            {
                Ms1ProductFilters = new[] { new SpectrumProductFilter(SignedMz.ZERO, 0, 0) };
                SimProductFilters = Ms1ProductFilters;  // We want TIC and BPC for all scans, even if they have narrow machine settings and look like SIM
            }
        }
Example #5
0
        protected override void DoTest()
        {
            // Open the empty .sky file (has no peptides)
            const string documentFile = "ThermoFAIMSTest.sky";

            PrepareDocument(documentFile);

            // Prepare for full scan
            RunUI(() => SkylineWindow.ModifyDocument("Set Orbitrap full-scan settings", doc => doc.ChangeSettings(
                                                         doc.Settings.ChangeTransitionFullScan(fs => fs
                                                                                               .ChangeAcquisitionMethod(FullScanAcquisitionMethod.Targeted, null)
                                                                                               .ChangePrecursorResolution(FullScanMassAnalyzerType.orbitrap, 60000, 400)
                                                                                               .ChangeProductResolution(FullScanMassAnalyzerType.orbitrap, 60000, 400))
                                                         .ChangeTransitionSettings(ts => ts.ChangeFilter(ts.Filter
                                                                                                         .ChangePeptidePrecursorCharges(new[] { Adduct.DOUBLY_PROTONATED, Adduct.TRIPLY_PROTONATED })
                                                                                                         .ChangePeptideProductCharges(new[] { Adduct.SINGLY_PROTONATED, Adduct.DOUBLY_PROTONATED })
                                                                                                         .ChangePeptideIonTypes(new[] { IonType.y, IonType.precursor }))).
                                                         ChangePeptideSettings(ps => ps.ChangePrediction(ps.Prediction
                                                                                                         .ChangeLibraryDriftTimesWindowWidthCalculator(new IonMobilityWindowWidthCalculator(IonMobilityWindowWidthCalculator.IonMobilityPeakWidthType.resolving_power, 20, 0, 0))
                                                                                                         .ChangeUseLibraryIonMobilityValues(true))))));

            TestWizardBuildDocumentLibraryAndFinish(documentFile);

            TestPopulateDocumentFromLibrary();

            // Now import chromatograms, check that FAIMS filtering is working
            ImportResultsFile(GetTestPath(TestFilesPersistent[1]));

            // First precursor area will be less than 7613528 @ RT47.4 if we aren't treating CV data properly (397369 @ RT47.52 instead)
            Assume.IsTrue(SkylineWindow.Document.MoleculeTransitions.First().GetPeakArea(-1) >= 7600000);
        }
Example #6
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));
 }
Example #7
0
        // Unit test of annotations handler class
        private static void TestSpectrumPeakAnnotations()
        {
            var noNote      = SpectrumPeakAnnotation.Create(new CustomIon(null, Adduct.FromChargeNoMass(-2), 100, 101, "noNote"), null);
            var noName      = SpectrumPeakAnnotation.Create(new CustomIon(null, Adduct.FromChargeNoMass(-2), 100, 101, null), "noted");
            var fullIon     = new CustomIon("C12H5O3", Adduct.FromStringAssumeChargeOnly("M-H2O+"), null, null, "full");
            var full        = SpectrumPeakAnnotation.Create(fullIon, "noted");
            var fullToo     = SpectrumPeakAnnotation.Create(fullIon, "noted");
            var nameOnlyTab = SpectrumPeakAnnotation.Create(new CustomIon(null, Adduct.FromChargeNoMass(-2), 100, 101, "test\ttabs"), "noted"); // Check tab escape
            var fullIonTabs = new CustomIon("C12H5", Adduct.FromChargeNoMass(-2), null, null, "full\ttabs");
            var tabbedFull  = SpectrumPeakAnnotation.Create(fullIonTabs, "noted\ttabs");                                                        // Check tab escape

            Assume.AreEqual(full, fullToo);
            Assume.AreNotEqual(full, tabbedFull);
            var tests = new List <List <SpectrumPeakAnnotation> >
            {
                new List <SpectrumPeakAnnotation> {
                    noNote, noName, full
                },
                new List <SpectrumPeakAnnotation> {
                    fullToo, nameOnlyTab, tabbedFull
                }
            };
            var cached    = SpectrumPeakAnnotation.ToCacheFormat(tests);
            var roundtrip = SpectrumPeakAnnotation.FromCacheFormat(cached);
            int i         = 0;

            foreach (var annotsPerPeak in tests)
            {
                Assume.IsTrue(CollectionUtil.EqualsDeep(annotsPerPeak, roundtrip[i++]));
            }
        }
Example #8
0
        private string FormatCrosslinkMod(Func <IEnumerable <Modification>, string> modFormatter,
                                          int totalPeptideCount,
                                          Modification linkedModification,
                                          int peptideIndex1, int peptideIndex2)
        {
            Assume.IsTrue(peptideIndex1 <= peptideIndex2);
            var strMod = modFormatter(new[] { linkedModification });

            if (strMod.Length == 0)
            {
                strMod = @"[]";
            }


            var indexes = new List <string>(totalPeptideCount);

            indexes.AddRange(Enumerable.Repeat(@"*", peptideIndex1));
            if (peptideIndex1 == peptideIndex2)
            {
                indexes.Add((linkedModification.IndexAA + 1) + @"-" + (linkedModification.ExplicitMod.LinkedPeptide.IndexAa + 1));
            }
            else
            {
                indexes.Add((linkedModification.IndexAA + 1).ToString());
                indexes.AddRange(Enumerable.Repeat(@"*", peptideIndex2 - peptideIndex1 - 1));
                indexes.Add((linkedModification.ExplicitMod.LinkedPeptide.IndexAa + 1).ToString());
            }
            indexes.AddRange(Enumerable.Repeat(@"*", totalPeptideCount - peptideIndex2 - 1));
            return(strMod.Substring(0, strMod.Length - 1) + @"@" + string.Join(@",", indexes) +
                   strMod.Substring(strMod.Length - 1));
        }
Example #9
0
        public ShareType DecideShareType(FolderInformation folderInfo, SrmDocument document)
        {
            ShareType shareType = ShareType.DEFAULT;

            var settings = document.Settings;

            Assume.IsTrue(document.IsLoaded);
            var cacheVersion = settings.HasResults ? settings.MeasuredResults.CacheVersion : null;

            if (!cacheVersion.HasValue)
            {
                // The document may not have any chromatogram data.
                return(shareType);
            }

            CacheFormatVersion supportedVersion = GetSupportedSkydVersion(folderInfo);

            if (supportedVersion >= cacheVersion.Value)
            {
                return(shareType);
            }
            var skylineVersion = SkylineVersion.SupportedForSharing().FirstOrDefault(ver => ver.CacheFormatVersion <= supportedVersion);

            if (skylineVersion == null)
            {
                throw new PanoramaServerException(string.Format(
                                                      Resources.PublishDocumentDlg_ServerSupportsSkydVersion_, (int)cacheVersion.Value));
            }
            return(shareType.ChangeSkylineVersion(skylineVersion));
        }
Example #10
0
        private bool ProcessChromInfo(MsDataFileUri filePath, ChromatogramGroupInfo chromInfo, PeptidePrecursorPair pair,
                                      TransitionGroupDocNode nodeGroup, float tolerance, LibKey libKey)
        {
            Assume.IsTrue(chromInfo.BestPeakIndex != -1);
            var resultIndex = _document.Settings.MeasuredResults.Chromatograms.IndexOf(c => c.GetFileInfo(filePath) != null);

            if (resultIndex == -1)
            {
                return(true);
            }
            var chromFileInfo = _document.Settings.MeasuredResults.Chromatograms[resultIndex].GetFileInfo(filePath);

            Assume.IsTrue(Equals(chromFileInfo.FilePath.GetLockMassParameters(), filePath.GetLockMassParameters()));

            // Determine apex RT for DT measurement using most intense MS1 peak
            var apexRT = GetApexRT(nodeGroup, resultIndex, chromFileInfo, true) ??
                         GetApexRT(nodeGroup, resultIndex, chromFileInfo, false);

            Assume.IsTrue(chromInfo.PrecursorMz == pair.NodeGroup.PrecursorMz);
            // Only use the transitions currently enabled
            var transitionPointSets = chromInfo.TransitionPointSets.Where(
                tp => nodeGroup.Transitions.Any(
                    t => (t.Mz - (tp.ExtractionWidth ?? tolerance) / 2) <= tp.ProductMz &&
                    (t.Mz + (tp.ExtractionWidth ?? tolerance) / 2) >= tp.ProductMz))
                                      .ToArray();

            for (var msLevel = 1; msLevel <= 2; msLevel++)
            {
                if (!ProcessMSLevel(filePath, msLevel, transitionPointSets, chromInfo, apexRT, nodeGroup, libKey, tolerance))
                {
                    return(false); // User cancelled
                }
            }
            return(true);
        }
Example #11
0
 private static void CheckLibrary(Library lib, int minPeaks, LibKey[] keys = null, Dictionary <int, List <SpectrumPeakAnnotation> > fragmentAnnotations = null)
 {
     Assert.IsNotNull(lib);
     Assert.IsTrue(lib.IsLoaded);
     foreach (var key in keys ?? KEYS_LIB_YEAST_NIST)
     {
         SpectrumHeaderInfo info;
         Assert.IsTrue(lib.TryGetLibInfo(key, out info));
         SpectrumPeaksInfo peaksInfo;
         Assert.IsTrue(lib.TryLoadSpectrum(key, out peaksInfo));
         Assert.IsTrue(peaksInfo.Peaks.Length >= minPeaks);
         if (fragmentAnnotations != null)
         {
             for (var p = 0; p < peaksInfo.Peaks.Length; p++)
             {
                 List <SpectrumPeakAnnotation> annotations;
                 if (!fragmentAnnotations.TryGetValue(p, out annotations))
                 {
                     annotations = null;
                 }
                 Assume.IsTrue(CollectionUtil.EqualsDeep(annotations, peaksInfo.Peaks[p].Annotations), "did not find expected annotation in converted library");
             }
         }
     }
 }
Example #12
0
        /// <summary>
        /// Replace all of the crosslinked peptide with the mass of the crosslinker plus the mass of the linked peptide.
        /// </summary>
        public ModifiedSequence ReplaceCrosslinksWithMasses(SrmSettings settings, IsotopeLabelType labelType)
        {
            if (ExplicitMods.All(mod => null == mod.LinkedPeptideSequence))
            {
                return(this);
            }

            var newModifications = new List <Modification>(ExplicitMods.Count);

            foreach (var modification in ExplicitMods)
            {
                if (null == modification.LinkedPeptideSequence)
                {
                    newModifications.Add(modification);
                    continue;
                }
                var formula = modification.StaticMod.Formula;
                MoleculeMassOffset moleculeMassOffset;
                if (string.IsNullOrEmpty(formula))
                {
                    moleculeMassOffset = new MoleculeMassOffset(Molecule.Empty, modification.StaticMod.MonoisotopicMass ?? 0, modification.StaticMod.AverageMass ?? 0);
                }
                else
                {
                    moleculeMassOffset = new MoleculeMassOffset(Molecule.ParseExpression(formula), 0, 0);
                }
                moleculeMassOffset = moleculeMassOffset.Plus(modification.ExplicitMod.LinkedPeptide.GetNeutralFormula(settings, labelType));
                var fragmentedMoleculeSettings = FragmentedMolecule.Settings.FromSrmSettings(settings);
                moleculeMassOffset = fragmentedMoleculeSettings.ReplaceMoleculeWithMassOffset(moleculeMassOffset);
                Assume.IsTrue(0 == moleculeMassOffset.Molecule.Count);
                newModifications.Add(new Modification(modification.ExplicitMod, moleculeMassOffset.MonoMassOffset, moleculeMassOffset.AverageMassOffset));
            }
            return(new ModifiedSequence(_unmodifiedSequence, newModifications, _defaultMassType));
        }
Example #13
0
        protected override void DoTest()
        {
            var skyfile = TestFilesDir.GetTestPath("test.sky"); // Has Full Scan settings good to go

            OpenDocument(skyfile);

            SetCsvFileClipboardText(TestFilesDir.GetTestPath("Testing_list_for_skyline.csv"));
            RunUI(SkylineWindow.Paste); // Paste into targets window

            // Enable fragments only
            RunUI(() => SkylineWindow.ModifyDocument("fragments only", doc => doc.ChangeSettings(doc.Settings.ChangeTransitionFilter(f =>
                                                                                                                                     f.ChangeSmallMoleculeIonTypes(new[] { IonType.custom })))));
            AssertEx.IsDocumentState(SkylineWindow.Document, null, 2, 9, 9, 30);

            // Enable precursors too
            RunUI(() => SkylineWindow.ModifyDocument("fragments and precursors", doc => doc.ChangeSettings(doc.Settings.ChangeTransitionFilter(f =>
                                                                                                                                               f.ChangeSmallMoleculeIonTypes(new[] { IonType.custom, IonType.precursor })))));
            AssertEx.IsDocumentState(SkylineWindow.Document, null, 2, 9, 9, 39);

            ImportResults(TestFilesDir.GetTestPath("GC_00343_500ng_62std2nd.raw"));
            // If data has not been properly understood as high energy all-ions (despite being MS1), some peaks won't be found
            foreach (var peak in from tg in SkylineWindow.Document.MoleculeTransitions
                     from r in tg.Results
                     from p in r
                     select p)
            {
                Assume.IsTrue((peak.PointsAcrossPeak ?? 0) > 20); // Without proper logic, points across peak is about half this since we skip every other spectrum as being low energy
                Assume.IsTrue(peak.Rank > 0);
                Assume.IsTrue(peak.Area > 0);
            }
        }
Example #14
0
        /// <summary>
        /// Saves the database to a new directory with only the charged peptides used
        /// in a given document.
        /// </summary>
        /// <param name="pathDestDir">The directory to save to</param>
        /// <param name="document">The document for which charged peptides are to be kept</param>
        /// <param name="smallMoleculeConversionMap">Used for changing charge,modifedSeq to adduct,molecule in small molecule conversion</param>
        /// <returns>The full path to the file saved</returns>
        public override string PersistMinimized(string pathDestDir,
                                                SrmDocument document, IDictionary <LibKey, LibKey> smallMoleculeConversionMap)
        {
            RequireUsable();

            var fname = Path.GetFileName(PersistencePath);

            if (smallMoleculeConversionMap != null && fname != null &&
                !fname.Contains(BiblioSpecLiteSpec.DotConvertedToSmallMolecules))
            {
                fname = fname.Replace(IonMobilityDb.EXT, BiblioSpecLiteSpec.DotConvertedToSmallMolecules + IonMobilityDb.EXT);
            }
            string persistPath = Path.Combine(pathDestDir, fname ?? String.Empty);

            using (var fs = new FileSaver(persistPath))
            {
                var ionMobilityDbMinimal = IonMobilityDb.CreateIonMobilityDb(fs.SafeName);

                // Calculate the minimal set of peptides needed for this document
                var dbPeptides      = _database.GetPeptides().ToList();
                var persistPeptides = new List <ValidatingIonMobilityPeptide>();

                var dictPeptides = dbPeptides.ToDictionary(pep => pep.GetLibKey());
                foreach (var pair in document.MoleculePrecursorPairs)
                {
                    var test =
                        new ValidatingIonMobilityPeptide(pair.NodePep.ModifiedTarget, pair.NodeGroup.PrecursorAdduct, 0, 0);
                    var key = test.GetLibKey();
                    DbIonMobilityPeptide dbPeptide;
                    if (dictPeptides.TryGetValue(key, out dbPeptide))
                    {
                        if (smallMoleculeConversionMap != null)
                        {
                            // We are in the midst of converting a document to small molecules for test purposes
                            LibKey smallMolInfo;
                            if (smallMoleculeConversionMap.TryGetValue(new LibKey(pair.NodePep.ModifiedSequence, pair.NodeGroup.PrecursorCharge), out smallMolInfo))
                            {
                                var precursorAdduct         = smallMolInfo.Adduct;
                                var smallMoleculeAttributes = smallMolInfo.SmallMoleculeLibraryAttributes;
                                dbPeptide = new DbIonMobilityPeptide(smallMoleculeAttributes, precursorAdduct, dbPeptide.CollisionalCrossSection, dbPeptide.HighEnergyDriftTimeOffsetMsec);
                            }
                            else
                            {
                                // Not being converted
                                Assume.IsTrue(pair.NodeGroup.Peptide.IsDecoy);
                                continue;
                            }
                        }
                        persistPeptides.Add(new ValidatingIonMobilityPeptide(dbPeptide));
                        // Only add once
                        dictPeptides.Remove(key);
                    }
                }

                ionMobilityDbMinimal.UpdatePeptides(persistPeptides, new ValidatingIonMobilityPeptide[0]);
                fs.Commit();
            }

            return(persistPath);
        }
Example #15
0
        private void RunTestAbundancesWithNoNormalization(bool asSmallMolecules)
        {
            SrmDocument testDocument = OpenTestDocument(asSmallMolecules);

            if (testDocument == null)
            {
                Assume.IsTrue(asSmallMolecules);
                return;
            }
            var expected = ReadDataProcessedRows(new StreamReader(OpenTestFile("BrudererSubsetNoNormalization_dataProcessedData.csv")));

            VerifyAbundances(testDocument, asSmallMolecules, expected,
                             transitionChromInfo =>
            {
                if (transitionChromInfo.IsEmpty || transitionChromInfo.IsTruncated.GetValueOrDefault())
                {
                    return(null);
                }
                if (transitionChromInfo.Area < 1)
                {
                    return(0);
                }
                return(Math.Log(transitionChromInfo.Area, 2.0));
            });
        }
        public Pre372CustomIonTransitionGroupHandler(XmlReader readerIn, double settingsMzMatchToler)
        {
            ReadAhead = new XmlReadAhead(readerIn); // Read the current element and its children

            // Put the contents of the readahead buffer into parseable XML form, return a reader for that
            var reader = ReadAhead.CreateXmlReader();

            // Advance the reader to the start of the precursors list, if any
            Assume.IsTrue(reader.IsStartElement(DocumentSerializer.EL.molecule));
            while (!reader.IsStartElement(DocumentSerializer.EL.precursor) && !reader.EOF)
            {
                reader.Read();
            }

            // Gather info on all declared precursors
            _precursorRawDetails = new List <PrecursorRawDetails>();
            while (reader.IsStartElement(DocumentSerializer.EL.precursor))
            {
                var details = new PrecursorRawDetails
                {
                    _formulaUnlabeled = string.Empty,
                    _labels           = null,
                    _nominalAdduct    = Adduct.EMPTY,
                    _proposedAdduct   = Adduct.EMPTY,
                    _declaredCharge   = reader.GetIntAttribute(DocumentSerializer.ATTR.charge),
                    _declaredMz       = reader.GetDoubleAttribute(DocumentSerializer.ATTR.precursor_mz),
                    _declaredHeavy    = !IsotopeLabelType.LIGHT_NAME.Equals(reader.GetAttribute(DocumentSerializer.ATTR.isotope_label) ?? IsotopeLabelType.LIGHT_NAME)
                };
                var formula = reader.GetAttribute(DocumentSerializer.ATTR.ion_formula);
                if (formula != null)
                {
                    details._formulaUnlabeled = formula.Trim(); // We've seen tailing spaces in the wild
                    string   precursorFormula;
                    Adduct   precursorAdduct;
                    Molecule precursorMol;
                    if (IonInfo.IsFormulaWithAdduct(formula, out precursorMol, out precursorAdduct, out precursorFormula))
                    {
                        details._formulaUnlabeled = precursorFormula;
                        details._nominalAdduct    = precursorAdduct;
                    }
                    else
                    {
                        details._labels           = BioMassCalc.MONOISOTOPIC.FindIsotopeLabelsInFormula(details._formulaUnlabeled);
                        details._formulaUnlabeled = BioMassCalc.MONOISOTOPIC.StripLabelsFromFormula(details._formulaUnlabeled);
                    }
                }
                _precursorRawDetails.Add(details);
                reader.ReadToNextSibling(DocumentSerializer.EL.precursor);
            }

            // We want to use the recorded mz values as nearly as possible
            // Inspect the XML to find the expected precision, compare that with current settings
            MzToler = ReadAhead.ElementPrecision(DocumentSerializer.EL.precursor_mz);
            if (MzToler < 1.0)
            {
                MzToler *= 5;
            }
            MzToler = Math.Min(MzToler, settingsMzMatchToler);
        }
Example #17
0
        public InterpolatedTimeIntensities(IEnumerable <TimeIntensities> transitionTimeIntensities,
                                           IEnumerable <ChromSource> transitionChromSources) : base(transitionTimeIntensities)
        {
            TransitionChromSources = ImmutableList <ChromSource> .ValueOf(transitionChromSources);

            Assume.IsTrue(TransitionTimeIntensities.Count > 0);
            Assume.IsTrue(TransitionChromSources.Count == TransitionTimeIntensities.Count);
        }
Example #18
0
        public void SetFragmentIons(string fragmentIons)
        {
            int i = cbFragmentIons.Items.IndexOf(fragmentIons);

            Assume.IsTrue(i >= 0, $@"fragmentIons value ""{fragmentIons}"" not found in ComboBox items");
            cbFragmentIons.SelectedIndex = i;
            ImportPeptideSearch.SearchEngine.SetFragmentIons(fragmentIons);
        }
Example #19
0
        public ChromGroups(
            IList <IList <int> > chromatogramRequestOrder,
            IList <ChromKey> chromKeys,
            float maxRetentionTime,
            int cycleCount,
            string cachePath)
        {
            RequestOrder      = chromatogramRequestOrder;
            _chromKeys        = chromKeys;
            _maxRetentionTime = maxRetentionTime;
            _cycleCount       = cycleCount;
            _cachePath        = cachePath;
            if (RequestOrder == null)
            {
                return;
            }

            // Sanity check.
            foreach (var group in RequestOrder)
            {
                foreach (var chromIndex in group)
                {
                    Assume.IsTrue(chromIndex >= 0 && chromIndex < _chromKeys.Count);
                }
            }

            // Create array to map a provider id back to the peptide group that contains it.
            _idToGroupId = new int[_chromKeys.Count];
            for (int groupId = 0; groupId < chromatogramRequestOrder.Count; groupId++)
            {
                foreach (var id in chromatogramRequestOrder[groupId])
                {
                    _idToGroupId[id] = groupId;
                }
            }

            // Decide how groups will be allocated to spill files.
            long      maxSpillFileSize      = 0;
            long      estimateSpillFileSize = 0;
            SpillFile spillFile             = new SpillFile();

            _spillFiles = new SpillFile[chromatogramRequestOrder.Count];
            for (int groupId = 0; groupId < _spillFiles.Length; groupId++)
            {
                long maxGroupSize      = GetMaxSize(groupId);
                long estimateGroupSize = EstimateGroupSize(groupId);
                maxSpillFileSize      += maxGroupSize;
                estimateSpillFileSize += estimateGroupSize;
                if (maxSpillFileSize > MAX_SPILL_FILE_SIZE || estimateSpillFileSize > TARGET_SPILL_FILE_SIZE)
                {
                    spillFile             = new SpillFile();
                    maxSpillFileSize      = maxGroupSize;
                    estimateSpillFileSize = estimateGroupSize;
                }
                _spillFiles[groupId] = spillFile;
                spillFile.MaxTime    = Math.Max(spillFile.MaxTime, GetMaxTime(groupId));
            }
        }
        private XmlReader ConsiderMassShiftAdducts(ref Peptide peptide)
        {
            var commonFormula = ProposedMolecule.Formula;
            var molMass       = ProposedMolecule.MonoisotopicMass;

            foreach (var d in _precursorRawDetails.Where(d => Adduct.IsNullOrEmpty(d._proposedAdduct)))
            {
                if (!Adduct.IsNullOrEmpty(d._nominalAdduct) && Math.Abs(d._declaredMz - d._nominalAdduct.MzFromNeutralMass(molMass)) <= MzToler)
                {
                    d._proposedAdduct = d._nominalAdduct;
                }
            }

            // Final attempt at assigning adducts in the event that no adjustment to neutral molecule has worked out
            foreach (var d in _precursorRawDetails.Where(d => Adduct.IsNullOrEmpty(d._proposedAdduct)))
            {
                // So far we haven't hit on a common molecules + adducts scenario that explains the given mz
                // We're forced to add weird mass shifts to adducts
                for (var retry = 0; retry < 4; retry++)
                {
                    Adduct adduct;
                    switch (retry)
                    {
                    case 0:     // Try [M+H] style
                        adduct = Adduct.ProtonatedFromFormulaDiff(d._formulaUnlabeled, commonFormula, d._declaredCharge)
                                 .ChangeIsotopeLabels(d._labels);
                        break;

                    case 1:     // Try [M+] style
                        adduct = Adduct.FromFormulaDiff(d._formulaUnlabeled, commonFormula, d._declaredCharge)
                                 .ChangeIsotopeLabels(d._labels);
                        break;

                    default:
                        adduct = retry == 2
                                ? Adduct.ProtonatedFromFormulaDiff(d._formulaUnlabeled, commonFormula,
                                                                   d._declaredCharge)                            // Try [M1.2345+H] style
                                : Adduct.FromFormulaDiff(d._formulaUnlabeled, commonFormula, d._declaredCharge); // Try [M1.2345+] style
                        var ionMass         = adduct.MassFromMz(d._declaredMz, MassType.Monoisotopic);
                        var unexplainedMass = ionMass - molMass;
                        adduct = adduct.ChangeIsotopeLabels(unexplainedMass, _mzDecimalPlaces);
                        break;
                    }
                    if (Math.Abs(d._declaredMz - adduct.MzFromNeutralMass(molMass)) <= MzToler)
                    {
                        d._proposedAdduct = adduct;
                        break;
                    }
                }
            }
            Assume.IsTrue(_precursorRawDetails.TrueForAll(d => !Adduct.IsNullOrEmpty(d._proposedAdduct)),
                          "Unable to to deduce adducts and common molecule for " + peptide); // Not L10N

            // We found a satisfactory set of adducts and neutral molecule, update the "peptide" and
            // modify the readahead buffer with the new adduct info
            return(UpdatePeptideAndInsertAdductsInXML(ref peptide, _precursorRawDetails.Select(d => d._proposedAdduct)));
        }
Example #21
0
        public bool GetChromatogram(ChromKey chromKey, out float[] times, out int[] scanIds, out float[] intensities, out float[] massErrors)
        {
            int keyIndex = -1;

            if (_chromKeyIndiceses != null)
            {
                var tolerance = (float)ChromTaskList.SrmDocument.Settings.TransitionSettings.Instrument.MzMatchTolerance;
                Assume.IsNull(chromKey.OptionalMinTime);
                Assume.IsNull(chromKey.OptionalMaxTime);
                Assume.IsTrue(0 == chromKey.IonMobilityValue);
                Assume.IsTrue(0 == chromKey.IonMobilityExtractionWidth);
                keyIndex = _chromKeyIndiceses.IndexOf(entry => entry.Key.CompareTolerant(chromKey, tolerance) == 0);
            }
            if (keyIndex == -1 || _chromKeyIndiceses == null)   // Keep ReSharper from complaining
            {
                times       = null;
                scanIds     = null;
                intensities = null;
                massErrors  = null;
                return(false);
            }
            ChromKeyIndices chromKeyIndices = _chromKeyIndiceses[keyIndex];
            var             chromGroupInfo  = _chromatogramCache.LoadChromatogramInfo(chromKeyIndices.GroupIndex);

            chromGroupInfo.ReadChromatogram(_chromatogramCache);
            var tranInfo = chromGroupInfo.GetTransitionInfo(chromKeyIndices.TranIndex);

            times = tranInfo.Times;
            if (times.Length == 0)
            {
                // Chorus returns zero length chromatogram to indicate that no spectra matched
                // the precursor filter.
                times       = null;
                scanIds     = null;
                intensities = null;
                massErrors  = null;
                return(false);
            }
            if (null != tranInfo.ScanIndexes)
            {
                scanIds = tranInfo.ScanIndexes[(short)chromKeyIndices.Key.Source];
            }
            else
            {
                scanIds = null;
            }
            intensities = tranInfo.Intensities;
            massErrors  = null;
            if (tranInfo.MassError10Xs != null)
            {
                massErrors = tranInfo.MassError10Xs.Select(m => m / 10.0f).ToArray();
            }
            CoalesceIntensities(ref times, ref scanIds, ref intensities, ref massErrors);
            return(true);
        }
Example #22
0
        /// <summary>
        /// Release a chromatogram if its collector is complete (indicated by retention time).
        /// </summary>
        /// <returns>-1 if chromatogram is not finished yet.</returns>
        public int ReleaseChromatogram(
            int chromatogramIndex, float retentionTime, ChromCollector collector,
            out TimeIntensities timeIntensities)
        {
            int groupIndex = GetGroupIndex(chromatogramIndex);
            var spillFile  = _spillFiles[groupIndex];

            // Not done reading yet.
            if (retentionTime < spillFile.MaxTime || (collector != null && !collector.IsSetTimes))
            {
                timeIntensities = null;
                return(-1);
            }

            // No chromatogram information collected.
            if (collector == null)
            {
                timeIntensities = TimeIntensities.EMPTY;
                return(0);
            }

            if (ReferenceEquals(_cachedSpillFile, spillFile))
            {
                if (spillFile.Stream != null)
                {
                    if (_bytesFromSpillFile == null || spillFile.Stream.Length != _bytesFromSpillFile.Length)
                    {
                        // Need to reread spill file if more bytes were written since the time it was cached.
                        _cachedSpillFile = null;
                    }
                }
            }

            if (!ReferenceEquals(_cachedSpillFile, spillFile))
            {
                _cachedSpillFile    = spillFile;
                _bytesFromSpillFile = null;
                var fileStream = spillFile.Stream;
                if (fileStream != null)
                {
                    fileStream.Seek(0, SeekOrigin.Begin);
                    _bytesFromSpillFile = new byte[fileStream.Length];
                    int bytesRead = fileStream.Read(_bytesFromSpillFile, 0, _bytesFromSpillFile.Length);
                    Assume.IsTrue(bytesRead == _bytesFromSpillFile.Length);
                    // TODO: Would be nice to have something that releases spill files progressively, as they are
                    //       no longer needed.
                    // spillFile.CloseStream();
                }
            }
            collector.ReleaseChromatogram(_bytesFromSpillFile, out timeIntensities);

            return(collector.StatusId);
        }
        public void OkDialog()
        {
            var helper = new MessageBoxHelper(this);
            var isotopeModification = _driverIsotopeModification.SelectedItem;

            if (isotopeModification == null)
            {
                helper.ShowTextBoxError(comboIsotopeModification, Resources.MessageBoxHelper_ValidateNameTextBox__0__cannot_be_empty);
                return;
            }
            lock (SkylineWindow.GetDocumentChangeLock())
            {
                var originalDocument       = SkylineWindow.Document;
                var deferSettingsChangeDoc = originalDocument.BeginDeferSettingsChanges();
                var globalStaticMods       = Settings.Default.StaticModList.ToList();
                var globalIsotopeMods      = Settings.Default.HeavyModList.ToList();
                var newDocument            = deferSettingsChangeDoc;
                var simplePermutation      = SimplePermutation;
                using (var longWaitDlg = new LongWaitDlg()
                {
                    Text = Resources.PermuteIsotopeModificationsDlg_OkDialog_Permuting_Isotope_Modifications
                })
                {
                    longWaitDlg.PerformWork(this, 1000, progressMonitor =>
                    {
                        var isotopePermuter = new IsotopeModificationPermuter(isotopeModification,
                                                                              simplePermutation, IsotopeLabelType.heavy, globalStaticMods, globalIsotopeMods);
                        newDocument = isotopePermuter.PermuteIsotopeModifications(progressMonitor, newDocument);
                        if (!ReferenceEquals(newDocument, deferSettingsChangeDoc))
                        {
                            var settingsChangeMonitor = new SrmSettingsChangeMonitor(progressMonitor, Resources.PermuteIsotopeModificationsDlg_OkDialog_Updating_settings);
                            newDocument = newDocument.EndDeferSettingsChanges(originalDocument, settingsChangeMonitor);
                        }
                    });
                    if (longWaitDlg.IsCanceled)
                    {
                        return;
                    }
                }
                if (!ReferenceEquals(newDocument, deferSettingsChangeDoc))
                {
                    SkylineWindow.ModifyDocument(Resources.PermuteIsotopeModificationsDlg_OkDialog_Permute_isotope_modifications, doc =>
                    {
                        // This will be true because we have acquired the lock on SkylineWindow.DocumentChangeLock()
                        Assume.IsTrue(ReferenceEquals(doc, originalDocument));
                        return(newDocument);
                    }, docPair => GetAuditLogEntry(docPair, isotopeModification, simplePermutation));
                }
                DialogResult = DialogResult.OK;
            }
        }
            public object Validate(object value)
            {
                // incoming value must either be a string or value type must stay the same
                Assume.IsTrue(value is string || value?.GetType() == _value?.GetType());

                if (value == null)
                {
                    return(null);
                }

                // CONSIDER: worth an extra case to handle incoming values that are already int/double?
                switch (MinValue)
                {
                case string s:
                    return(value);

                case int minValue:
                    if (!int.TryParse(value.ToString(), out int tmpi32))
                    {
                        throw new ArgumentException(string.Format(
                                                        Resources.ValueInvalidIntException_ValueInvalidIntException_The_value___0___is_not_valid_for_the_argument__1__which_requires_an_integer_,
                                                        value, Name));
                    }
                    if (tmpi32 < minValue || tmpi32 > (int)MaxValue)
                    {
                        throw new ArgumentOutOfRangeException(string.Format(
                                                                  Resources.ValueOutOfRangeDoubleException_ValueOutOfRangeException_The_value___0___for_the_argument__1__must_be_between__2__and__3__,
                                                                  value, Name, minValue, MaxValue));
                    }
                    return(tmpi32);

                case double minValue:
                    if (!double.TryParse(value.ToString(), out double tmpd))
                    {
                        throw new ArgumentException(string.Format(
                                                        Resources.ValueInvalidDoubleException_ValueInvalidDoubleException_The_value___0___is_not_valid_for_the_argument__1__which_requires_a_decimal_number_,
                                                        value, Name));
                    }
                    if (tmpd < minValue || tmpd > (double)MaxValue)
                    {
                        throw new ArgumentOutOfRangeException(string.Format(
                                                                  Resources.ValueOutOfRangeDoubleException_ValueOutOfRangeException_The_value___0___for_the_argument__1__must_be_between__2__and__3__,
                                                                  value, Name, minValue, MaxValue));
                    }
                    return(tmpd);

                default:
                    throw new InvalidOperationException(@"unsupported setting type");
                }
            }
Example #25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TextRange"/> class.
        /// </summary>
        internal TextRange(Int32 start, Int32 stop, TextDocument textDocument, TextRange previous = null,
                           TextRange next = null)
        {
            Assume.IsTrue(start >= 0, "start must be positive or zero!");
            Assume.IsTrue(start <= stop, "start must be lesser than stop!");
            Assume.NotNull(textDocument, "textDocument");

            Start        = start;
            Stop         = stop;
            TextDocument = textDocument;

            Previous = previous;
            Next     = next;
        }
Example #26
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);
        }
        /// <summary>
        /// Creates a new or gets an existing text range from text document
        /// </summary>
        /// <param name="start">The start position of text range</param>
        /// <param name="stop">The stop position of text range</param>
        public TextRange CreateOrGetTextRange(Int32 start, Int32 stop)
        {
            Assume.IsTrue(start >= 0, "start must be positive or zero!");
            Assume.IsTrue(start <= stop, "start must be lesser than stop!");

            var textRange = getExistingTextRange(start, stop);
            var isFoundExistingTextRange = (textRange != null);

            if (!isFoundExistingTextRange)
            {
                textRange = createTextRange(start, stop);
            }

            return(textRange);
        }
Example #28
0
 public static string KeyFromPropertyName(string propertyName)
 {
     Assume.IsTrue(IsRatioOrRdotpProperty(propertyName));
     if (propertyName.StartsWith(RATIO_GS_PREFIX))
     {
         return(propertyName.Substring(RATIO_GS_PREFIX.Length));
     }
     else if (propertyName.StartsWith(RATIO_PREFIX))
     {
         return(propertyName.Substring(RATIO_PREFIX.Length));
     }
     else
     {
         return(propertyName.Substring(RDOTP_PREFIX.Length));
     }
 }
Example #29
0
        private string MakeModifiedSequence(string unmodifiedSequence, IEnumerable <KeyValuePair <int, string> > modifications)
        {
            StringBuilder modifiedSequence = new StringBuilder();
            int           ichUnmodified    = 0;

            foreach (var modification in modifications)
            {
                Assume.IsTrue(modification.Key >= ichUnmodified);
                modifiedSequence.Append(unmodifiedSequence.Substring(ichUnmodified,
                                                                     modification.Key - ichUnmodified + 1));
                ichUnmodified = modification.Key + 1;
                modifiedSequence.Append(ModifiedSequence.Bracket(modification.Value));
            }
            modifiedSequence.Append(unmodifiedSequence.Substring(ichUnmodified));
            return(modifiedSequence.ToString());
        }
Example #30
0
        public void Validate()
        {
            if (AuditLogEntries.Count == 0)
            {
                return;
            }

            var logIndex = AuditLogEntries[0].LogIndex;
            var time     = AuditLogEntries[0].TimeStamp;

            foreach (var entry in AuditLogEntries.Skip(1))
            {
                Assume.IsTrue(entry.TimeStamp >= time && entry.LogIndex > logIndex,
                              AuditLogStrings.AuditLogList_Validate_Audit_log_is_corrupted__Audit_log_entry_time_stamps_and_indices_should_be_increasing);
            }
        }