示例#1
0
        private SrmDocument ExportTestLib(string docName, string libName, bool convertFromPeptides, out IList <DbRefSpectra> refSpectra)
        {
            RunUI(() => SkylineWindow.OpenFile(TestFilesDir.GetTestPath(docName)));
            var docOrig = WaitForDocumentLoaded();
            var doc     = docOrig;

            _convertedFromPeptides = convertFromPeptides;
            if (_convertedFromPeptides)
            {
                var refine = new RefinementSettings();
                doc = refine.ConvertToSmallMolecules(docOrig, TestFilesDirs[0].FullPath, addAnnotations: false);
                SkylineWindow.SetDocument(doc, docOrig);
            }
            var exported        = TestFilesDir.GetTestPath(libName);
            var libraryExporter = new SpectralLibraryExporter(SkylineWindow.Document, SkylineWindow.DocumentFilePath);

            libraryExporter.ExportSpectralLibrary(exported, null);
            Assert.IsTrue(File.Exists(exported));
            refSpectra = null;
            using (var connection = new SQLiteConnection(string.Format("Data Source='{0}';Version=3", exported)))
            {
                connection.Open();
                refSpectra = GetRefSpectra(connection);
            }

            return(doc);
        }
示例#2
0
        public void ConvertDocumentToSmallMolecules(RefinementSettings.ConvertToSmallMoleculesMode mode = RefinementSettings.ConvertToSmallMoleculesMode.formulas,
                                                    RefinementSettings.ConvertToSmallMoleculesChargesMode invertCharges = RefinementSettings.ConvertToSmallMoleculesChargesMode.none,
                                                    bool ignoreDecoys = false)
        {
            var doc = WaitForDocumentLoaded();

            RunUI(() => SkylineWindow.ModifyDocument("Convert to small molecules", document =>
            {
                var refine      = new RefinementSettings();
                var path        = Path.GetDirectoryName(SkylineWindow.DocumentFilePath);
                var smallMolDoc = refine.ConvertToSmallMolecules(document, path, mode, invertCharges, ignoreDecoys);
                CheckConsistentLibraryInfo(smallMolDoc);
                return(smallMolDoc);
            }));
            WaitForDocumentChange(doc);

            var newDocFileName =
                SkylineWindow.DocumentFilePath.Contains(BiblioSpecLiteSpec.DotConvertedToSmallMolecules) ?
                SkylineWindow.DocumentFilePath :
                SkylineWindow.DocumentFilePath.Replace(".sky", BiblioSpecLiteSpec.DotConvertedToSmallMolecules + ".sky");

            RunUI(() => SkylineWindow.SaveDocument(newDocFileName));
            WaitForCondition(() => File.Exists(newDocFileName));
            RunUI(() => SkylineWindow.OpenFile(newDocFileName));
            WaitForDocumentLoaded();
            CheckConsistentLibraryInfo();

            Thread.Sleep(1000);
        }
示例#3
0
        private void DoTestImportSim(bool asSmallMolecules)
        {
            if (asSmallMolecules && !RunSmallMoleculeTestVersions)
            {
                System.Console.Write(MSG_SKIPPING_SMALLMOLECULE_TEST_VERSION);
                return;
            }

            var    testFilesDir = new TestFilesDir(TestContext, ZIP_FILE);
            string docPath      = testFilesDir.GetTestPath(DOCUMENT_NAME);
            string cachePath    = ChromatogramCache.FinalPathForName(docPath, null);

            FileEx.SafeDelete(cachePath);
            SrmDocument doc = ResultsUtil.DeserializeDocument(docPath);

            var pepdoc = doc;

            if (asSmallMolecules)
            {
                var refine = new RefinementSettings();
                doc = refine.ConvertToSmallMolecules(pepdoc, TestContext.ResultsDirectory);
            }

            using (var docContainer = new ResultsTestDocumentContainer(doc, docPath))
            {
                // Import the mzML file and verify Mz range
                Import(docContainer, testFilesDir.GetTestPath(RESULTS_NAME), 510, 512);
                Import(docContainer, testFilesDir.GetTestPath(RESULTS_NAME2), 555, 557);
            }
        }
示例#4
0
        public void DoAgilentMseChromatogramTest(RefinementSettings.ConvertToSmallMoleculesMode asSmallMolecules)
        {
            if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.none && !RunSmallMoleculeTestVersions)
            {
                System.Console.Write(MSG_SKIPPING_SMALLMOLECULE_TEST_VERSION);
                return;
            }

            var testFilesDir = new TestFilesDir(TestContext, ZIP_FILE);

            TestSmallMolecules = false; // We have an explicit test for that here

            string      docPath;
            SrmDocument document = InitAgilentMseDocument(testFilesDir, out docPath);

            if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.none)
            {
                var refine = new RefinementSettings();
                document = refine.ConvertToSmallMolecules(document, asSmallMolecules);
            }
            using (var docContainer = new ResultsTestDocumentContainer(document, docPath))
            {
                var doc = docContainer.Document;
                var listChromatograms = new List <ChromatogramSet>();
                var path = MsDataFileUri.Parse(@"AgilentMse\BSA-AI-0-10-25-41_first_100_scans.mzML");
                listChromatograms.Add(AssertResult.FindChromatogramSet(doc, path) ??
                                      new ChromatogramSet(path.GetFileName().Replace('.', '_'), new[] { path }));
                var docResults = doc.ChangeMeasuredResults(new MeasuredResults(listChromatograms));
                Assert.IsTrue(docContainer.SetDocument(docResults, doc, true));
                docContainer.AssertComplete();
                document = docContainer.Document;

                float tolerance = (float)document.Settings.TransitionSettings.Instrument.MzMatchTolerance;
                var   results   = document.Settings.MeasuredResults;
                foreach (var pair in document.MoleculePrecursorPairs)
                {
                    ChromatogramGroupInfo[] chromGroupInfo;
                    Assert.IsTrue(results.TryLoadChromatogram(0, pair.NodePep, pair.NodeGroup,
                                                              tolerance, true, out chromGroupInfo));
                    Assert.AreEqual(1, chromGroupInfo.Length);
                }

                // now drill down for specific values
                int nPeptides = 0;
                foreach (var nodePep in document.Molecules.Where(nodePep => nodePep.Results[0] != null))
                {
                    // expecting just one peptide result in this small data set
                    if (nodePep.Results[0].Sum(chromInfo => chromInfo.PeakCountRatio > 0 ? 1 : 0) > 0)
                    {
                        Assert.AreEqual(0.2462, (double)nodePep.GetMeasuredRetentionTime(0), .0001, "averaged retention time differs in node " + nodePep.RawTextId);
                        Assert.AreEqual(0.3333, (double)nodePep.GetPeakCountRatio(0), 0.0001);
                        nPeptides++;
                    }
                }
                Assert.AreEqual(1, nPeptides);
            }
            testFilesDir.Dispose();
        }
 public void ConvertDocumentToSmallMolecules(RefinementSettings.ConvertToSmallMoleculesMode mode = RefinementSettings.ConvertToSmallMoleculesMode.formulas,
                                             bool invertCharges = false, bool ignoreDecoys = false)
 {
     WaitForDocumentLoaded();
     RunUI(() => SkylineWindow.ModifyDocument("Convert to small molecules", document =>
     {
         var refine = new RefinementSettings();
         return(refine.ConvertToSmallMolecules(document, mode, invertCharges, ignoreDecoys));
     }));
 }
示例#6
0
        public void RefineConvertToSmallMoleculeMassesAndNamesTest()
        {
            TestFilesDir testFilesDir = new TestFilesDir(TestContext, @"TestA\Refine.zip");

            var document       = InitRefineDocument(testFilesDir);
            var refineSettings = new RefinementSettings();
            var converted      = refineSettings.ConvertToSmallMolecules(document, RefinementSettings.ConvertToSmallMoleculesMode.masses_and_names);

            AssertEx.ConvertedSmallMoleculeDocumentIsSimilar(document, converted);
        }
示例#7
0
        private void CheckRoundTrip()
        {
            // Verify that document roundtrips properly as small molecule
            var refine = new RefinementSettings();
            var doc    = refine.ConvertToSmallMolecules(SkylineWindow.Document, ignoreDecoys: true);

            AssertEx.RoundTrip(doc);
            // Verify that document roundtrips properly
            AssertEx.RoundTrip(SkylineWindow.Document);
        }
示例#8
0
        private void CheckRoundTrip(int pass)
        {
            // Verify that document roundtrips properly
            AssertEx.RoundTrip(SkylineWindow.Document);

            // Verify that document roundtrips properly as small molecule
            var    refine = new RefinementSettings();
            string pathForSmallMoleculeLibs =
                Path.Combine(TestFilesDirs[0].FullPath,
                             string.Format("AsSmallMolecules{0}", pass));
            var doc = refine.ConvertToSmallMolecules(SkylineWindow.Document, pathForSmallMoleculeLibs, ignoreDecoys: true);

            AssertEx.RoundTrip(doc);
        }
示例#9
0
        private static SrmDocument InitWatersImsMseDocument(TestFilesDir testFilesDir, string skyFile,
                                                            RefinementSettings.ConvertToSmallMoleculesMode asSmallMolecules,
                                                            out string docPath)
        {
            docPath = testFilesDir.GetTestPath(skyFile);
            var cmdline = new CommandLine();

            Assert.IsTrue(cmdline.OpenSkyFile(docPath)); // Handles any path shifts in database files, like our .imdb file
            SrmDocument doc    = cmdline.Document;
            var         refine = new RefinementSettings();

            doc = refine.ConvertToSmallMolecules(doc, asSmallMolecules);
            return(doc);
        }
示例#10
0
        public void RefineConvertToSmallMoleculesTest()
        {
            // Exercise the code that helps match heavy labeled ion formulas with unlabled
            Assert.AreEqual("C5H12NO2S", BioMassCalc.MONOISOTOPIC.StripLabelsFromFormula("C5H9H'3NO2S"));
            Assert.IsNull(BioMassCalc.MONOISOTOPIC.StripLabelsFromFormula(""));
            Assert.IsNull(BioMassCalc.MONOISOTOPIC.StripLabelsFromFormula(null));

            TestFilesDir testFilesDir = new TestFilesDir(TestContext, @"TestA\Refine.zip");

            var document       = InitRefineDocument(testFilesDir);
            var refineSettings = new RefinementSettings();
            var converted      = refineSettings.ConvertToSmallMolecules(document);

            AssertEx.ConvertedSmallMoleculeDocumentIsSimilar(document, converted);
        }
示例#11
0
        public void DoAsymmetricIsolationTest(RefinementSettings.ConvertToSmallMoleculesMode asSmallMolecules)
        {
            if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.none && !RunSmallMoleculeTestVersions)
            {
                Console.Write(MSG_SKIPPING_SMALLMOLECULE_TEST_VERSION);
                return;
            }

            TestSmallMolecules = false;      // We test small molecules explicitly in this test

            LocalizationHelper.InitThread(); // TODO: All unit tests should be correctly initialized

            var    testFilesDir = new TestFilesDir(TestContext, ZIP_FILE);
            string docPath      = testFilesDir.GetTestPath("TROUBLED_File.sky");
            string cachePath    = ChromatogramCache.FinalPathForName(docPath, null);

            FileEx.SafeDelete(cachePath);
            SrmDocument doc    = ResultsUtil.DeserializeDocument(docPath);
            var         refine = new RefinementSettings();

            doc = refine.ConvertToSmallMolecules(doc, testFilesDir.FullPath, asSmallMolecules);
            const int expectedMoleculeCount = 1;   // At first small molecules did not support multiple label types

            AssertEx.IsDocumentState(doc, null, 1, expectedMoleculeCount, 2, 6);

            using (var docContainer = new ResultsTestDocumentContainer(doc, docPath))
            {
                // Import the first RAW file (or mzML for international)
                string rawPath         = testFilesDir.GetTestPath("Rush_p3_96_21May16_Smeagol.mzML");
                var    measuredResults = new MeasuredResults(new[] { new ChromatogramSet("Single", new[] { rawPath }) });

                {
                    // Import with symmetric isolation window
                    var docResults =
                        docContainer.ChangeMeasuredResults(measuredResults, expectedMoleculeCount, 1, 1, 3, 3);
                    var    nodeGroup = docResults.MoleculeTransitionGroups.First();
                    double ratio     = nodeGroup.Results[0][0].Ratio ?? 0;
                    // The expected ratio is 1.0, but the symmetric isolation window should produce poor results
                    if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.masses_only) // Can't use labels without a formula
                    {
                        Assert.AreEqual(0.008, ratio, 0.001);
                    }
                }
            }

            testFilesDir.Dispose();
        }
示例#12
0
        private static SrmDocument InitFullScanDocument(string docPath, int prot, ref int pep, ref int prec, ref int tran, RefinementSettings.ConvertToSmallMoleculesMode smallMoleculeTestMode)
        {
            SrmDocument doc = ResultsUtil.DeserializeDocument(docPath);
            int?        expectedRevisionNumber = 0;

            if (smallMoleculeTestMode != RefinementSettings.ConvertToSmallMoleculesMode.none)
            {
                var refine = new RefinementSettings();
                var oldDoc = doc;
                AssertEx.Serializable(oldDoc);
                doc = refine.ConvertToSmallMolecules(doc, smallMoleculeTestMode);
                AssertEx.ConvertedSmallMoleculeDocumentIsSimilar(oldDoc, doc);
                AssertEx.Serializable(doc);
                expectedRevisionNumber = null;
            }
            AssertEx.IsDocumentState(doc, expectedRevisionNumber, prot, pep, prec, tran);
            return(doc);
        }
示例#13
0
        public void DoTestDemux(bool asSmallMolecules)
        {
            var    testFilesDir = new TestFilesDir(TestContext, ZIP_FILE);
            string docPathMsx   = testFilesDir.GetTestPath("MsxTest.sky");
            string dataPathMsx  = testFilesDir.GetTestPath("MsxTest.mzML");
            string cachePathMsx = ChromatogramCache.FinalPathForName(docPathMsx, null);

            FileEx.SafeDelete(cachePathMsx);
            SrmDocument docMsx = ResultsUtil.DeserializeDocument(docPathMsx);

            if (asSmallMolecules)
            {
                var refine = new RefinementSettings();
                docMsx = refine.ConvertToSmallMolecules(docMsx);
            }
            var fullScanInitialMsx = docMsx.Settings.TransitionSettings.FullScan;

            Assert.IsTrue(fullScanInitialMsx.IsEnabledMsMs);

            TestMsx(docMsx, dataPathMsx);

            string docPathOverlap   = testFilesDir.GetTestPath("OverlapTest.sky");
            string dataPathOverlap  = testFilesDir.GetTestPath("OverlapTest.mzML");
            string cachePathOverlap = ChromatogramCache.FinalPathForName(docPathOverlap, null);

            FileEx.SafeDelete(cachePathOverlap);
            SrmDocument docOverlap = ResultsUtil.DeserializeDocument(docPathOverlap);

            if (asSmallMolecules)
            {
                var refine = new RefinementSettings();
                docOverlap = refine.ConvertToSmallMolecules(docOverlap);
            }
            var fullScanInitialOverlap = docMsx.Settings.TransitionSettings.FullScan;

            Assert.IsTrue(fullScanInitialOverlap.IsEnabledMsMs);
            TestOverlap(docOverlap, dataPathOverlap);
        }
示例#14
0
        private void DoTestImportSim(bool asSmallMolecules)
        {
            TestSmallMolecules = false; // Don't need that magic extra node
            var    testFilesDir = new TestFilesDir(TestContext, ZIP_FILE);
            string docPath      = testFilesDir.GetTestPath(DOCUMENT_NAME);
            string cachePath    = ChromatogramCache.FinalPathForName(docPath, null);

            FileEx.SafeDelete(cachePath);
            SrmDocument doc = ResultsUtil.DeserializeDocument(docPath);

            var pepdoc = doc;

            if (asSmallMolecules)
            {
                var refine = new RefinementSettings();
                doc = refine.ConvertToSmallMolecules(pepdoc);
            }

            var docContainer = new ResultsTestDocumentContainer(doc, docPath);

            // Import the mzML file and verify Mz range
            Import(docContainer, testFilesDir.GetTestPath(RESULTS_NAME), 510, 512);
            Import(docContainer, testFilesDir.GetTestPath(RESULTS_NAME2), 555, 557);
        }
示例#15
0
        private void ExportWithExplicitCollisionEnergyValues(string pathForSmallMoleculeLibs, string pathList)
        {
            var original      = SkylineWindow.Document;
            var refine        = new RefinementSettings();
            var document      = refine.ConvertToSmallMolecules(original, pathForSmallMoleculeLibs);
            int expectedTrans = document.MoleculeTransitionCount * 11 + 1;

            for (var loop = 0; loop < 2; loop++)
            {
                SkylineWindow.SetDocument(document, SkylineWindow.Document);
                var exportMethodDlg = ShowDialog <ExportMethodDlg>(() => SkylineWindow.ShowExportMethodDialog(ExportFileType.List));
                RunUI(() =>
                {
                    exportMethodDlg.InstrumentType = ExportInstrumentType.THERMO_QUANTIVA;
                    exportMethodDlg.OptimizeType   = ExportOptimize.CE;
                    exportMethodDlg.MethodType     = ExportMethodType.Standard;
                });
                RunUI(() => exportMethodDlg.OkDialog(pathList));
                WaitForClosedForm(exportMethodDlg);
                var actual = File.ReadAllLines(pathList);
                if (loop == 1)
                {
                    // Explicit CE values
                    Assert.AreEqual(expectedTrans, actual.Length); // Should still contain steps based on the explicit values
                    break;
                }
                else
                {
                    Assert.AreEqual(expectedTrans, actual.Length); // Multiple steps, and a header
                }
                // Change the current document to use explicit CE values, verify that this changes the output
                var ce = 1; // Starting at 1 means some transitions will not have all CE steps
                expectedTrans = 1;
                for (bool changing = true; changing;)
                {
                    changing = false;
                    foreach (var peptideGroupDocNode in document.MoleculeGroups)
                    {
                        var pepGroupPath = new IdentityPath(IdentityPath.ROOT, peptideGroupDocNode.Id);
                        foreach (var nodePep in peptideGroupDocNode.Molecules)
                        {
                            var pepPath = new IdentityPath(pepGroupPath, nodePep.Id);
                            foreach (var nodeTransitionGroup in nodePep.TransitionGroups)
                            {
                                if (!nodeTransitionGroup.ExplicitValues.CollisionEnergy.HasValue)
                                {
                                    var tgPath = new IdentityPath(pepPath, nodeTransitionGroup.Id);
                                    // Add to expected transition count, limiting to account for CE <= 0
                                    expectedTrans += nodeTransitionGroup.TransitionCount * (Math.Min(ce - 1, 5) + 6);
                                    document       = (SrmDocument)document.ReplaceChild(tgPath.Parent,
                                                                                        nodeTransitionGroup.ChangeExplicitValues(nodeTransitionGroup.ExplicitValues.ChangeCollisionEnergy(ce++)));
                                    changing = true;
                                    break;
                                }
                            }
                        }
                        if (changing)
                        {
                            break;
                        }
                    }
                }
            }
            SkylineWindow.SetDocument(original, SkylineWindow.Document);
        }
示例#16
0
        public void DoThermoRatioTest(RefinementSettings.ConvertToSmallMoleculesMode smallMoleculesTestMode)
        {
            TestSmallMolecules = false;  // We do this explicitly

            var         testFilesDir = new TestFilesDir(TestContext, ZIP_FILE);
            string      docPath;
            SrmDocument doc      = InitThermoDocument(testFilesDir, out docPath);
            SrmSettings settings = doc.Settings.ChangePeptideModifications(mods =>
                                                                           mods.ChangeInternalStandardTypes(new[] { IsotopeLabelType.light }));

            doc = doc.ChangeSettings(settings);
            if (smallMoleculesTestMode != RefinementSettings.ConvertToSmallMoleculesMode.none)
            {
                var docOrig = doc;
                var refine  = new RefinementSettings();
                doc = refine.ConvertToSmallMolecules(doc, smallMoleculesTestMode);
                // This is our first example of a converted label doc - check roundtripping
                AssertEx.ConvertedSmallMoleculeDocumentIsSimilar(docOrig, doc);
                AssertEx.Serializable(doc);
            }
            var    docContainer      = new ResultsTestDocumentContainer(doc, docPath);
            string extRaw            = ExtensionTestContext.ExtThermoRaw;
            var    listChromatograms = new List <ChromatogramSet>
            {
                new ChromatogramSet("rep03", new[]
                {
                    MsDataFileUri.Parse(testFilesDir.GetTestPath(
                                            "Site20_STUDY9P_PHASEII_QC_03" + extRaw))
                }),
                new ChromatogramSet("rep05", new[]
                {
                    MsDataFileUri.Parse(testFilesDir.GetTestPath(
                                            "Site20_STUDY9P_PHASEII_QC_05" + extRaw))
                })
            };
            var docResults = doc.ChangeMeasuredResults(new MeasuredResults(listChromatograms));

            Assert.IsTrue(docContainer.SetDocument(docResults, doc, true));
            docContainer.AssertComplete();
            docResults = docContainer.Document;
            // Make sure all groups have at least 5 transitions (of 6) with ratios
            int ratioGroupMissingCount = 0;

            foreach (var nodeGroup in docResults.MoleculeTransitionGroups)
            {
                if (nodeGroup.TransitionGroup.LabelType.IsLight)
                {
                    foreach (var result in nodeGroup.Results)
                    {
                        Assert.IsFalse(result[0].Ratio.HasValue, "Light group found with a ratio");
                    }
                    foreach (TransitionDocNode nodeTran in nodeGroup.Children)
                    {
                        foreach (var resultTran in nodeTran.Results)
                        {
                            Assert.IsFalse(resultTran[0].Ratio.HasValue, "Light transition found with a ratio");
                        }
                    }
                }
                else
                {
                    bool missingRatio = false;
                    foreach (ChromInfoList <TransitionGroupChromInfo> chromInfoList in nodeGroup.Results)
                    {
                        var ratioHeavy = chromInfoList[0].Ratio;
                        if (!ratioHeavy.HasValue)
                        {
                            missingRatio = true;
                        }
                    }
                    int ratioCount1 = 0;
                    int ratioCount2 = 0;
                    foreach (TransitionDocNode nodeTranHeavy in nodeGroup.Children)
                    {
                        float?ratioHeavy = nodeTranHeavy.Results[0][0].Ratio;
                        if (ratioHeavy.HasValue)
                        {
                            Assert.IsFalse(float.IsNaN(ratioHeavy.Value) || float.IsInfinity(ratioHeavy.Value));
                            ratioCount1++;
                        }
                        ratioHeavy = nodeTranHeavy.Results[1][0].Ratio;
                        if (ratioHeavy.HasValue)
                        {
                            Assert.IsFalse(float.IsNaN(ratioHeavy.Value) || float.IsInfinity(ratioHeavy.Value));
                            ratioCount2++;
                        }
                    }
                    Assert.AreEqual(3, ratioCount1);
                    if (ratioCount2 < 2)
                    {
                        ratioGroupMissingCount++;
                    }
                    else
                    {
                        Assert.IsFalse(missingRatio, "Precursor missing ratio when transitions have ratios");
                    }
                }
            }
            // 3 groups with less than 2 transition ratios
            Assert.AreEqual(3, ratioGroupMissingCount);

            // Remove the first light transition, checking that this removes the ratio
            // from the corresponding heavy transition, but not the entire group, until
            // after all light transitions have been removed.
            IdentityPath pathFirstPep = docResults.GetPathTo((int)SrmDocument.Level.Molecules, 0);
            var          nodePep      = (PeptideDocNode)docResults.FindNode(pathFirstPep);

            Assert.AreEqual(2, nodePep.Children.Count);
            var          nodeGroupLight = (TransitionGroupDocNode)nodePep.Children[0];
            IdentityPath pathGroupLight = new IdentityPath(pathFirstPep, nodeGroupLight.TransitionGroup);

            Assert.IsNull(nodeGroupLight.Results[0][0].Ratio, "Light group has ratio");
            var          nodeGroupHeavy = (TransitionGroupDocNode)nodePep.Children[1];
            IdentityPath pathGroupHeavy = new IdentityPath(pathFirstPep, nodeGroupHeavy.TransitionGroup);
            float?       ratioStart     = nodeGroupHeavy.Results[0][0].Ratio;

            Assert.IsTrue(ratioStart.HasValue, "No starting heavy group ratio");
            var expectedValues = new[] { 1.403414, 1.38697791, 1.34598482 };

            for (int i = 0; i < 3; i++)
            {
                var pathLight = docResults.GetPathTo((int)SrmDocument.Level.Transitions, 0);
                var pathHeavy = docResults.GetPathTo((int)SrmDocument.Level.Transitions, 3);
                TransitionDocNode nodeTran  = (TransitionDocNode)docResults.FindNode(pathHeavy);
                float?            ratioTran = nodeTran.Results[0][0].Ratio;
                Assert.IsTrue(ratioTran.HasValue, "Expected transition ratio not found");
                Assert.AreEqual(ratioTran.Value, expectedValues[i], 1.0e-5);
                docResults = (SrmDocument)docResults.RemoveChild(pathLight.Parent, docResults.FindNode(pathLight));
                nodeTran   = (TransitionDocNode)docResults.FindNode(pathHeavy);
                Assert.IsFalse(nodeTran.Results[0][0].Ratio.HasValue, "Unexpected transiton ratio found");
                Assert.AreEqual(pathGroupHeavy, pathHeavy.Parent, "Transition found outside expected group");
//                nodePep = (PeptideDocNode) docResults.FindNode(pathFirstPep);
                nodeGroupHeavy = (TransitionGroupDocNode)docResults.FindNode(pathGroupHeavy);
//                Assert.AreEqual(nodePep.Results[0][0].RatioToStandard, nodeGroupHeavy.Results[0][0].Ratio,
//                                "Peptide and group ratios not equal");
                if (i < 2)
                {
                    float?ratioGroup = nodeGroupHeavy.Results[0][0].Ratio;
                    Assert.IsTrue(ratioGroup.HasValue, "Group ratio removed with transition ratios");
                    Assert.AreEqual(ratioStart.Value, ratioGroup.Value, 0.1,
                                    "Unexpected group ratio change by more than 0.1");
                }
                else
                {
                    Assert.IsFalse(nodeGroupHeavy.Results[0][0].Ratio.HasValue,
                                   "Group ratio still present with no transition ratios");
                }
            }
            bool asSmallMolecules = (smallMoleculesTestMode != RefinementSettings.ConvertToSmallMoleculesMode.none);

            if (!asSmallMolecules) // GetTransitions() doesn't work the same way for small molecules - it only lists existing ones
            {
                bool      firstAdd           = true;
                var       nodeGroupLightOrig = (TransitionGroupDocNode)doc.FindNode(pathGroupLight);
                DocNode[] lightChildrenOrig  = nodeGroupLightOrig.Children.ToArray();
                foreach (var nodeTran in nodeGroupLightOrig.GetTransitions(docResults.Settings,
                                                                           null, nodeGroupLightOrig.PrecursorMz, null, null, null, false))
                {
                    var transition = nodeTran.Transition;
                    if (!firstAdd && lightChildrenOrig.IndexOf(node => Equals(node.Id, transition)) == -1)
                    {
                        continue;
                    }
                    // Add the first transition, and then the original transitions
                    docResults     = (SrmDocument)docResults.Add(pathGroupLight, nodeTran);
                    nodeGroupHeavy = (TransitionGroupDocNode)docResults.FindNode(pathGroupHeavy);
                    if (firstAdd)
                    {
                        Assert.IsNull(nodeGroupHeavy.Results[0][0].Ratio, "Unexpected heavy ratio found");
                    }
                    else
                    {
                        Assert.IsNotNull(nodeGroupHeavy.Results[0][0].Ratio,
                                         "Heavy ratio null after adding light children");
                    }
                    firstAdd = false;
                }
                Assert.AreEqual(ratioStart, nodeGroupHeavy.Results[0][0].Ratio);
            }
            // Release file handles
            docContainer.Release();
            testFilesDir.Dispose();
        }
        protected override void DoTest()
        {
            // Export and check spectral library
            RunUI(() => SkylineWindow.OpenFile(TestFilesDir.GetTestPath("msstatstest.sky")));
            var docOrig = WaitForDocumentLoaded();
            var refine  = new RefinementSettings();
            var doc     = refine.ConvertToSmallMolecules(docOrig, TestFilesDirs[0].FullPath);

            SkylineWindow.SetDocument(doc, docOrig);
            var exported = TestFilesDir.GetTestPath("exportSM.blib");

            Skyline.SkylineWindow.ExportSpectralLibrary(SkylineWindow.DocumentFilePath, SkylineWindow.Document, exported, null);
            Assert.IsTrue(File.Exists(exported));

            var refSpectra = new List <DbRefSpectra>();

            using (var connection = new SQLiteConnection(string.Format("Data Source='{0}';Version=3", exported)))
            {
                connection.Open();
                using (var select = new SQLiteCommand(connection)
                {
                    CommandText = "SELECT * FROM RefSpectra"
                })
                    using (var reader = select.ExecuteReader())
                    {
                        var iAdduct = reader.GetOrdinal("precursorAdduct");
                        while (reader.Read())
                        {
                            refSpectra.Add(new DbRefSpectra
                            {
                                PeptideSeq      = reader["peptideSeq"].ToString(),
                                PeptideModSeq   = reader["peptideModSeq"].ToString(),
                                PrecursorCharge = int.Parse(reader["precursorCharge"].ToString()),
                                PrecursorAdduct = reader[iAdduct].ToString(),
                                MoleculeName    = reader["moleculeName"].ToString(),
                                ChemicalFormula = reader["chemicalFormula"].ToString(),
                                PrecursorMZ     = double.Parse(reader["precursorMZ"].ToString()),
                                NumPeaks        = ushort.Parse(reader["numPeaks"].ToString())
                            });
                        }
                    }
            }
            CheckRefSpectra(refSpectra, "APVPTGEVYFADSFDR", "C81H115N19O26", "[M+2H]", 885.9203087025, 4);
            CheckRefSpectra(refSpectra, "APVPTGEVYFADSFDR", "C81H115N19O26", "[M6C134N15+2H]", 890.9244430127, 4);
            CheckRefSpectra(refSpectra, "AVTELNEPLSNEDR", "C65H107N19O27", "[M+2H]", 793.8864658775, 4);
            CheckRefSpectra(refSpectra, "AVTELNEPLSNEDR", "C65H107N19O27", "[M6C134N15+2H]", 798.8906001877, 4);
            CheckRefSpectra(refSpectra, "DQGGELLSLR", "C45H78N14O17", "[M+2H]", 544.29074472, 4);
            CheckRefSpectra(refSpectra, "DQGGELLSLR", "C45H78N14O17", "[M6C134N15+2H]", 549.2948790302, 4);
            CheckRefSpectra(refSpectra, "ELLTTMGDR", "C42H74N12O16S", "[M+2H]", 518.260598685, 4);
            CheckRefSpectra(refSpectra, "ELLTTMGDR", "C42H74N12O16S", "[M6C134N15+2H]", 523.2647329952, 4);
            CheckRefSpectra(refSpectra, "FEELNADLFR", "C57H84N14O18", "[M+2H]", 627.31167714, 3);
            CheckRefSpectra(refSpectra, "FEELNADLFR", "C57H84N14O18", "[M6C134N15+2H]", 632.3158114502, 4);
            CheckRefSpectra(refSpectra, "FHQLDIDDLQSIR", "C70H110N20O23", "[M+2H]", 800.40991117, 3);
            CheckRefSpectra(refSpectra, "FHQLDIDDLQSIR", "C70H110N20O23", "[M6C134N15+2H]", 805.4140454802, 4);
            CheckRefSpectra(refSpectra, "FLIPNASQAESK", "C58H93N15O19", "[M+2H]", 652.8458841125, 4);
            CheckRefSpectra(refSpectra, "FLIPNASQAESK", "C58H93N15O19", "[M6C132N15+2H]", 656.8529835243, 4);
            CheckRefSpectra(refSpectra, "FTPGTFTNQIQAAFR", "C78H115N21O22", "[M+2H]", 849.9335534425, 4);
            CheckRefSpectra(refSpectra, "FTPGTFTNQIQAAFR", "C78H115N21O22", "[M6C134N15+2H]", 854.9376877527, 4);
            CheckRefSpectra(refSpectra, "ILTFDQLALDSPK", "C67H109N15O21", "[M+2H]", 730.9033990225, 4);
            CheckRefSpectra(refSpectra, "ILTFDQLALDSPK", "C67H109N15O21", "[M6C132N15+2H]", 734.9104984343, 4);
            CheckRefSpectra(refSpectra, "LSSEMNTSTVNSAR", "C58H101N19O25S", "[M+2H]", 748.8541114925, 4);
            CheckRefSpectra(refSpectra, "LSSEMNTSTVNSAR", "C58H101N19O25S", "[M6C134N15+2H]", 753.8582458027, 4);
            CheckRefSpectra(refSpectra, "NIVEAAAVR", "C40H71N13O13", "[M+2H]", 471.7719908375, 4);
            CheckRefSpectra(refSpectra, "NIVEAAAVR", "C40H71N13O13", "[M6C134N15+2H]", 476.7761251477, 4);
            CheckRefSpectra(refSpectra, "NLQYYDISAK", "C55H83N13O18", "[M+2H]", 607.8062276225, 4);
            CheckRefSpectra(refSpectra, "NLQYYDISAK", "C55H83N13O18", "[M6C132N15+2H]", 611.8133270343, 4);
            CheckRefSpectra(refSpectra, "TSAALSTVGSAISR", "C54H97N17O21", "[M+2H]", 660.8595228125, 4);
            CheckRefSpectra(refSpectra, "TSAALSTVGSAISR", "C54H97N17O21", "[M6C134N15+2H]", 665.8636571227, 4);
            CheckRefSpectra(refSpectra, "VHIEIGPDGR", "C47H77N15O15", "[M+2H]", 546.7934545725, 4);
            CheckRefSpectra(refSpectra, "VHIEIGPDGR", "C47H77N15O15", "[M6C134N15+2H]", 551.7975888827, 4);
            CheckRefSpectra(refSpectra, "VLTPELYAELR", "C60H98N14O18", "[M+2H]", 652.366452385, 4);
            CheckRefSpectra(refSpectra, "VLTPELYAELR", "C60H98N14O18", "[M6C134N15+2H]", 657.3705866952, 4);
            CheckRefSpectra(refSpectra, "VNLAELFK", "C44H72N10O12", "[M+2H]", 467.27383504, 4);
            CheckRefSpectra(refSpectra, "VNLAELFK", "C44H72N10O12", "[M6C132N15+2H]", 471.2809344518, 4);
            CheckRefSpectra(refSpectra, "VPDFSEYR", "C46H65N11O15", "[M+2H]", 506.7403563625, 4);
            CheckRefSpectra(refSpectra, "VPDFSEYR", "C46H65N11O15", "[M6C134N15+2H]", 511.7444906727, 4);
            CheckRefSpectra(refSpectra, "VPDGMVGFIIGR", "C57H93N15O15S", "[M+2H]", 630.8420902025, 4);
            CheckRefSpectra(refSpectra, "VPDGMVGFIIGR", "C57H93N15O15S", "[M6C134N15+2H]", 635.8462245127, 4);
            CheckRefSpectra(refSpectra, "ADVTPADFSEWSK", "C65H93N15O23", "[M+2H]", 726.8357133725, 3);
            CheckRefSpectra(refSpectra, "DGLDAASYYAPVR", "C62H92N16O21", "[M+2H]", 699.338423225, 3);
            CheckRefSpectra(refSpectra, "GAGSSEPVTGLDAK", "C53H89N15O22", "[M+2H]", 644.8226059875, 3);
            CheckRefSpectra(refSpectra, "GTFIIDPAAVIR", "C59H97N15O16", "[M+2H]", 636.8691622375, 3);
            CheckRefSpectra(refSpectra, "GTFIIDPGGVIR", "C57H93N15O16", "[M+2H]", 622.8535121675, 3);
            CheckRefSpectra(refSpectra, "LFLQFGAQGSPFLK", "C76H113N17O18", "[M+2H]", 776.9297511475, 3);
            CheckRefSpectra(refSpectra, "LGGNEQVTR", "C39H68N14O15", "[M+2H]", 487.256704915, 3);
            CheckRefSpectra(refSpectra, "TPVISGGPYEYR", "C61H91N15O19", "[M+2H]", 669.8380590775, 3);
            CheckRefSpectra(refSpectra, "TPVITGAPYEYR", "C63H95N15O19", "[M+2H]", 683.8537091475, 3);
            CheckRefSpectra(refSpectra, "VEATFGVDESNAK", "C58H91N15O23", "[M+2H]", 683.8278883375, 3);
            CheckRefSpectra(refSpectra, "YILAGVENSK", "C49H80N12O16", "[M+2H]", 547.29803844, 3);
            Assert.IsTrue(!refSpectra.Any());

            // Try to export spectral library with no results
            var manageResultsDlg = ShowDialog <ManageResultsDlg>(SkylineWindow.ManageResults);

            RunUI(() => manageResultsDlg.RemoveAllReplicates());
            OkDialog(manageResultsDlg, manageResultsDlg.OkDialog);
            WaitForDocumentChangeLoaded(doc);
            var errDlg1 = ShowDialog <MessageDlg>(SkylineWindow.ShowExportSpectralLibraryDialog);

            Assert.AreEqual(Resources.SkylineWindow_ShowExportSpectralLibraryDialog_The_document_must_contain_results_to_export_a_spectral_library_, errDlg1.Message);
            OkDialog(errDlg1, errDlg1.OkDialog);
            RunUI(() => SkylineWindow.Undo());

            // Try to export spectral library with no precursors
            RunUI(() => SkylineWindow.NewDocument());
            var errDlg2 = ShowDialog <MessageDlg>(SkylineWindow.ShowExportSpectralLibraryDialog);

            Assert.AreEqual(Resources.SkylineWindow_ShowExportSpectralLibraryDialog_The_document_must_contain_at_least_one_peptide_precursor_to_export_a_spectral_library_, errDlg2.Message);
            OkDialog(errDlg2, errDlg2.OkDialog);
        }
示例#18
0
        private void PerformTestMeasuredDriftValues(bool asSmallMolecules)
        {
            if (asSmallMolecules)
            {
                if (!RunSmallMoleculeTestVersions)
                {
                    Console.Write(MSG_SKIPPING_SMALLMOLECULE_TEST_VERSION);
                    return;
                }
                TestSmallMolecules = false;                                                          // No need to add the magic small molecule test node
            }
            var testFilesDir = new TestFilesDir(TestContext, @"Test\Results\BlibDriftTimeTest.zip"); // Re-used from BlibDriftTimeTest
            // Open document with some peptides but no results
            var docPath = testFilesDir.GetTestPath("BlibDriftTimeTest.sky");
            // This was a malformed document, which caused problems after a fix to not recalculate
            // document library settings on open. To avoid rewriting this test for the document
            // which now contains 2 precursors, the first precursor is removed immediately.
            SrmDocument docOriginal      = ResultsUtil.DeserializeDocument(docPath);
            var         pathFirstPeptide = docOriginal.GetPathTo((int)SrmDocument.Level.Molecules, 0);
            var         nodeFirstPeptide = (DocNodeParent)docOriginal.FindNode(pathFirstPeptide);

            docOriginal = (SrmDocument)docOriginal.RemoveChild(pathFirstPeptide, nodeFirstPeptide.Children[0]);
            if (asSmallMolecules)
            {
                var refine = new RefinementSettings();
                docOriginal = refine.ConvertToSmallMolecules(docOriginal, testFilesDir.FullPath);
            }
            using (var docContainer = new ResultsTestDocumentContainer(docOriginal, docPath))
            {
                var doc = docContainer.Document;

                // Import an mz5 file that contains drift info
                const string replicateName = "ID12692_01_UCA168_3727_040714";
                var          chromSets     = new[]
                {
                    new ChromatogramSet(replicateName, new[]
                                        { new MsDataFilePath(testFilesDir.GetTestPath("ID12692_01_UCA168_3727_040714" + ExtensionTestContext.ExtMz5)), }),
                };
                var docResults = doc.ChangeMeasuredResults(new MeasuredResults(chromSets));
                Assert.IsTrue(docContainer.SetDocument(docResults, docOriginal, true));
                docContainer.AssertComplete();
                var document = docContainer.Document;
                document = document.ChangeSettings(document.Settings.ChangePeptidePrediction(prediction => new PeptidePrediction(null, IonMobilityPredictor.EMPTY)));

                // Verify ability to extract predictions from raw data
                var newPred = document.Settings.PeptideSettings.Prediction.IonMobilityPredictor.ChangeMeasuredIonMobilityValuesFromResults(
                    document, docContainer.DocumentFilePath);
                var result = newPred.MeasuredMobilityIons;
                Assert.AreEqual(TestSmallMolecules ? 2 : 1, result.Count);
                const double expectedDT     = 4.0019;
                var          expectedOffset = .4829;
                Assert.AreEqual(expectedDT, result.Values.First().IonMobility.Mobility.Value, .001);
                Assert.AreEqual(expectedOffset, result.Values.First().HighEnergyIonMobilityValueOffset, .001);

                // Check ability to update, and to preserve unchanged
                var revised = new Dictionary <LibKey, IonMobilityAndCCS>();
                var libKey  = result.Keys.First();
                revised.Add(libKey, IonMobilityAndCCS.GetIonMobilityAndCCS(IonMobilityValue.GetIonMobilityValue(4, eIonMobilityUnits.drift_time_msec), null, 0.234));  // N.B. CCS handling would require actual raw data in this test, it's covered in a perf test
                var libKey2 = new LibKey("DEADEELS", asSmallMolecules ? Adduct.NonProteomicProtonatedFromCharge(2) : Adduct.DOUBLY_PROTONATED);
                revised.Add(libKey2, IonMobilityAndCCS.GetIonMobilityAndCCS(IonMobilityValue.GetIonMobilityValue(5, eIonMobilityUnits.drift_time_msec), null, 0.123));
                document =
                    document.ChangeSettings(
                        document.Settings.ChangePeptidePrediction(prediction => new PeptidePrediction(null, new IonMobilityPredictor("test", revised, null, null, IonMobilityWindowWidthCalculator.IonMobilityPeakWidthType.resolving_power, 40, 0, 0))));
                newPred = document.Settings.PeptideSettings.Prediction.ChangeDriftTimePredictor(
                    document.Settings.PeptideSettings.Prediction.IonMobilityPredictor.ChangeMeasuredIonMobilityValuesFromResults(
                        document, docContainer.DocumentFilePath)).IonMobilityPredictor;
                result = newPred.MeasuredMobilityIons;
                Assert.AreEqual(TestSmallMolecules ? 3 : 2, result.Count);
                Assert.AreEqual(expectedDT, result[libKey].IonMobility.Mobility.Value, .001);
                Assert.AreEqual(expectedOffset, result[libKey].HighEnergyIonMobilityValueOffset, .001);
                Assert.AreEqual(5, result[libKey2].IonMobility.Mobility.Value, .001);
                Assert.AreEqual(0.123, result[libKey2].HighEnergyIonMobilityValueOffset, .001);
            }
        }
        protected override void DoTest()
        {
            // Lest we get "To export a scheduled method, you must first choose a retention time predictor in Peptide Settings / Prediction, or import results for all peptides in the document."
            TestSmallMolecules = false;

            // Skyline Collision Energy Optimization
            RunUI(() => SkylineWindow.OpenFile(GetTestPath("CE_Vantage_15mTorr.sky"))); // Not L10N

            if (AsSmallMolecules)
            {
                var doc    = WaitForDocumentLoaded();
                var refine = new RefinementSettings();
                SkylineWindow.SetDocument(refine.ConvertToSmallMolecules(doc), doc);
            }

            // Deriving a New Linear Equation, p. 2
            var transitionSettingsUI = ShowDialog <TransitionSettingsUI>(SkylineWindow.ShowTransitionSettingsUI);
            var editList             =
                ShowDialog <EditListDlg <SettingsListBase <CollisionEnergyRegression>, CollisionEnergyRegression> >
                    (transitionSettingsUI.EditCEList);

            RunUI(() => editList.SelectItem("Thermo")); // Not L10N
            EditCEDlg editItem = ShowDialog <EditCEDlg>(editList.EditItem);

            PauseForScreenShot <EditCEDlg>("Edit Collision Energy Equation form", 3);

            ChargeRegressionLine regressionLine2 = new ChargeRegressionLine(2, 0.034, 3.314);
            ChargeRegressionLine regressionLine3 = new ChargeRegressionLine(3, 0.044, 3.314);

            CheckRegressionLines(new[] { regressionLine2, regressionLine3 }, editItem.Regression.Conversions);

            RunUI(() =>
            {
                editItem.DialogResult             = DialogResult.OK;
                editList.DialogResult             = DialogResult.Cancel;
                transitionSettingsUI.DialogResult = DialogResult.Cancel;
            });
            WaitForClosedForm(transitionSettingsUI);

            // Measuring Retention Times for Method Scheduling, p. 3
            {
                var exportMethodDlg = ShowDialog <ExportMethodDlg>(() => SkylineWindow.ShowExportMethodDialog(ExportFileType.List));
                RunUI(() =>
                {
                    exportMethodDlg.InstrumentType = ExportInstrumentType.THERMO;
                    exportMethodDlg.ExportStrategy = ExportStrategy.Single;
                    exportMethodDlg.OptimizeType   = ExportOptimize.NONE;
                    exportMethodDlg.MethodType     = ExportMethodType.Standard;
                });

                PauseForScreenShot <ExportMethodDlg.TransitionListView>("Export Transition List form", 4);

                RunUI(() => exportMethodDlg.OkDialog(GetTestPath("CE_Vantage_15mTorr_unscheduled.csv"))); // Not L10N
                WaitForClosedForm(exportMethodDlg);
            }

            string filePathTemplate = GetTestPath("CE_Vantage_15mTorr_unscheduled.csv"); // Not L10N

            CheckTransitionList(filePathTemplate, 1, 6);

            const string unscheduledName = "Unscheduled"; // Not L10N

            RunDlg <ImportResultsDlg>(SkylineWindow.ImportResults, importResultsDlg =>
            {
                importResultsDlg.RadioAddNewChecked = true;
                var path =
                    new[] { new KeyValuePair <string, MsDataFileUri[]>(unscheduledName,
                                                                                                                                                                       // This is not actually a valid file path (missing OptimizeCE)
                                                                                                                                                                       // but Skyline should correctly find the file in the same folder
                                                                                                                                                                       // as the document.
                                                                       new[] { MsDataFileUri.Parse(GetTestPath("CE_Vantage_15mTorr_unscheduled" + ExtThermoRaw)) }) }; // Not L10N
                importResultsDlg.NamedPathSets = path;
                importResultsDlg.OkDialog();
            });
            WaitForCondition(5 * 60 * 1000, () => SkylineWindow.Document.Settings.MeasuredResults.IsLoaded);    // 5 minutes
            AssertEx.IsDocumentState(SkylineWindow.Document, null, 7, 27, 30, 120);
            var docUnsched = SkylineWindow.Document;

            AssertResult.IsDocumentResultsState(SkylineWindow.Document,
                                                unscheduledName,
                                                docUnsched.MoleculeCount,
                                                docUnsched.MoleculeTransitionGroupCount, 0,
                                                docUnsched.MoleculeTransitionCount - 1, 0);

            RunUI(() =>
            {
                SkylineWindow.ExpandProteins();
                SkylineWindow.ExpandPeptides();
            });

            PauseForScreenShot("Main Skyline window", 5);

            // Creating Optimization Methods, p. 5
            {
                var exportMethodDlg = ShowDialog <ExportMethodDlg>(() => SkylineWindow.ShowExportMethodDialog(ExportFileType.List));
                RunUI(() =>
                {
                    exportMethodDlg.InstrumentType = ExportInstrumentType.THERMO;
                    exportMethodDlg.ExportStrategy = ExportStrategy.Buckets;
                    exportMethodDlg.MaxTransitions = 110;
                    exportMethodDlg.IgnoreProteins = true;
                    exportMethodDlg.OptimizeType   = ExportOptimize.CE;
                    exportMethodDlg.MethodType     = ExportMethodType.Scheduled;
                });

                PauseForScreenShot <ExportMethodDlg.TransitionListView>("Export Transition List form", 6);

                RunUI(() => exportMethodDlg.OkDialog(GetTestPath("CE_Vantage_15mTorr.csv"))); // Not L10N
                WaitForClosedForm(exportMethodDlg);
            }

            string filePathTemplate1 = GetTestPath("CE_Vantage_15mTorr_000{0}.csv"); // Not L10N

            CheckTransitionList(filePathTemplate1, 5, 9);

            var filePath = GetTestPath("CE_Vantage_15mTorr_0001.csv"); // Not L10N

            CheckCEValues(filePath, 11);

            // Analyze Optimization Data, p. 7
            RunDlg <ImportResultsDlg>(SkylineWindow.ImportResults, importResultsDlg =>
            {
                importResultsDlg.RadioAddNewChecked = true;
                importResultsDlg.OptimizationName   = ExportOptimize.CE;
                importResultsDlg.NamedPathSets      = DataSourceUtil.GetDataSourcesInSubdirs(TestFilesDirs[0].FullPath).ToArray();
                importResultsDlg.NamedPathSets[0]   =
                    new KeyValuePair <string, MsDataFileUri[]>("Optimize CE", importResultsDlg.NamedPathSets[0].Value.Take(5).ToArray()); // Not L10N
                importResultsDlg.OkDialog();
            });
            RunUI(() =>
            {
                SkylineWindow.ShowSingleTransition();
                SkylineWindow.AutoZoomBestPeak();
                SkylineWindow.ShowPeakAreaReplicateComparison();
            });

            WaitForDocumentLoaded(15 * 60 * 1000); // 10 minutes

            if (AsSmallMolecules)
            {
                return;  // Too peptide-centric from here to end of test
            }

            FindNode("IHGFDLAAINLQR");
            RestoreViewOnScreen(8);

            PauseForScreenShot("Main Skyline window", 8);

            // p. 8
            // Not L10N
            RemovePeptide("EGIHAQQK");

            FindNode("IDALNENK");

            RunUI(() => SkylineWindow.NormalizeAreaGraphTo(AreaNormalizeToView.area_percent_view));

            PauseForScreenShot("Main Skyline window", 9);

            RunUI(SkylineWindow.EditDelete);

            RemovePeptide("LICDNTHITK");

            // Creating a New Equation for CE, p. 9
            var transitionSettingsUI1 = ShowDialog <TransitionSettingsUI>(SkylineWindow.ShowTransitionSettingsUI);
            var editCEDlg1            = ShowDialog <EditListDlg <SettingsListBase <CollisionEnergyRegression>, CollisionEnergyRegression> >(transitionSettingsUI1.EditCEList);
            var addItem = ShowDialog <EditCEDlg>(editCEDlg1.AddItem);

            RunUI(() =>
            {
                addItem.RegressionName = "Thermo Vantage Tutorial"; // Not L10N
                addItem.UseCurrentData();
            });

            var graphRegression = ShowDialog <GraphRegression>(addItem.ShowGraph);

            PauseForScreenShot <GraphRegression>("Collision Energy Regression graphs", 10);

            var graphDatas = graphRegression.RegressionGraphDatas.ToArray();

            Assert.AreEqual(2, graphDatas.Length);

            ChargeRegressionLine regressionLine21 = new ChargeRegressionLine(2, 0.0305, 2.5061);
            ChargeRegressionLine regressionLine31 = new ChargeRegressionLine(3, 0.0397, 1.4217);
            var expectedRegressions = new[] { regressionLine21, regressionLine31 };

            CheckRegressionLines(expectedRegressions, new[]
            {
                new ChargeRegressionLine(2,
                                         Math.Round(graphDatas[0].RegressionLine.Slope, 4),
                                         Math.Round(graphDatas[0].RegressionLine.Intercept, 4)),
                new ChargeRegressionLine(3,
                                         Math.Round(graphDatas[1].RegressionLine.Slope, 4),
                                         Math.Round(graphDatas[1].RegressionLine.Intercept, 4)),
            });

            RunUI(graphRegression.CloseDialog);
            WaitForClosedForm(graphRegression);
            RunUI(addItem.OkDialog);
            WaitForClosedForm(addItem);
            RunUI(editCEDlg1.OkDialog);
            WaitForClosedForm(editCEDlg1);
            RunUI(transitionSettingsUI1.OkDialog);
            WaitForClosedForm(transitionSettingsUI1);

            // Optimizing Each Transition, p. 10
            RunDlg <TransitionSettingsUI>(SkylineWindow.ShowTransitionSettingsUI, transitionSettingsUI2 =>
            {
                transitionSettingsUI2.UseOptimized = true;
                transitionSettingsUI2.OptimizeType = OptimizedMethodType.Transition.GetLocalizedString();
                transitionSettingsUI2.OkDialog();
            });
            RunDlg <ExportMethodDlg>(() => SkylineWindow.ShowExportMethodDialog(ExportFileType.List), exportMethodDlg =>
            {
                exportMethodDlg.ExportStrategy = ExportStrategy.Single;
                exportMethodDlg.OkDialog(GetTestPath("CE_Vantage_15mTorr_optimized.csv")); // Not L10N
            });

            var filePathTemplate2 = GetTestPath("CE_Vantage_15mTorr_optimized.csv"); // Not L10N

            CheckTransitionList(filePathTemplate2, 1, 9);

            RunUI(() => SkylineWindow.SaveDocument());
            WaitForConditionUI(() => !SkylineWindow.Dirty);
        }
示例#20
0
        public void DoFullScanSettingsTest(RefinementSettings.ConvertToSmallMoleculesMode asSmallMolecules,
                                           out List <SrmDocument> docCheckPoints)
        {
            docCheckPoints = new List <SrmDocument>();

            var doc0   = ResultsUtil.DeserializeDocument("MultiLabel.sky", GetType());
            var refine = new RefinementSettings();
            var docSM  = refine.ConvertToSmallMolecules(doc0, ".", asSmallMolecules);

            docCheckPoints.Add(docSM);
            Assert.IsFalse(docSM.MoleculeTransitionGroups.Any(nodeGroup => nodeGroup.IsotopeDist != null));
            AssertEx.Serializable(docSM, AssertEx.Cloned);

            double c13Delta = BioMassCalc.MONOISOTOPIC.GetMass(BioMassCalc.C13) -
                              BioMassCalc.MONOISOTOPIC.GetMass(BioMassCalc.C);
            double n15Delta = BioMassCalc.MONOISOTOPIC.GetMass(BioMassCalc.N15) -
                              BioMassCalc.MONOISOTOPIC.GetMass(BioMassCalc.N);

            // Verify isotope distributions calculated when MS1 filtering enabled
            var enrichments = IsotopeEnrichmentsList.DEFAULT;
            var docIsotopes = docSM.ChangeSettings(docSM.Settings.ChangeTransitionFullScan(fs =>
                                                                                           fs.ChangePrecursorIsotopes(FullScanPrecursorIsotopes.Count, 3, enrichments)));

            docCheckPoints.Add(docIsotopes);
            Assert.AreEqual(FullScanMassAnalyzerType.tof,
                            docIsotopes.Settings.TransitionSettings.FullScan.PrecursorMassAnalyzer);
            Assert.IsFalse(docIsotopes.MoleculeTransitionGroups.Any(nodeGroup => nodeGroup.IsotopeDist == null));
            foreach (var nodeGroup in docIsotopes.MoleculeTransitionGroups)
            {
                Assert.AreEqual(3, nodeGroup.Children.Count);
                var isotopePeaks = nodeGroup.IsotopeDist;
                Assert.IsNotNull(isotopePeaks);
                Assert.IsTrue(nodeGroup.HasIsotopeDist);
                // The peaks should always includ at least M-1
                Assume.IsTrue(isotopePeaks.MassIndexToPeakIndex(0) > 0);
                // Within 2.5% of 100% of the entire isotope distribution
                Assert.AreEqual(1.0, isotopePeaks.ExpectedProportions.Sum(), 0.025);

                // Precursor mass and m/z values are expected to match exactly (well, within XML roundtrip accuracy anyway)

                Assert.AreEqual(nodeGroup.PrecursorMz, nodeGroup.IsotopeDist.GetMZI(0), SequenceMassCalc.MassTolerance);
                Assert.AreEqual(nodeGroup.PrecursorMz, nodeGroup.TransitionGroup.IsCustomIon ?
                                BioMassCalc.CalculateIonMz(nodeGroup.IsotopeDist.GetMassI(0),
                                                           nodeGroup.TransitionGroup.PrecursorAdduct.Unlabeled) :
                                SequenceMassCalc.GetMZ(nodeGroup.IsotopeDist.GetMassI(0),
                                                       nodeGroup.TransitionGroup.PrecursorAdduct), SequenceMassCalc.MassTolerance);

                // Check isotope distribution masses
                for (int i = 1; i < isotopePeaks.CountPeaks; i++)
                {
                    int massIndex = isotopePeaks.PeakIndexToMassIndex(i);
                    Assert.IsTrue(isotopePeaks.GetMZI(massIndex - 1) < isotopePeaks.GetMZI(massIndex));
                    double massDelta = GetMassDelta(isotopePeaks, massIndex);
                    if (nodeGroup.TransitionGroup.LabelType.IsLight)
                    {
                        // All positive should be close to 13C - C, and 0 should be the same as the next delta
                        double expectedDelta = (massIndex > 0 ? c13Delta : GetMassDelta(isotopePeaks, massIndex + 1));
                        Assert.AreEqual(expectedDelta, massDelta, 0.001);
                    }
                    else if (nodeGroup.TransitionGroup.LabelType.Name.Contains("15N"))
                    {
                        // All positive should be close to 13C, and all negative 15N
                        double expectedDelta = (massIndex > 0 ? c13Delta : n15Delta);
                        Assert.AreEqual(expectedDelta, massDelta, 0.0015);
                    }
                    else if (massIndex == 0)
                    {
                        double expectedDelta = (isotopePeaks.GetProportionI(massIndex - 1) == 0
                                                    ? GetMassDelta(isotopePeaks, massIndex + 1)
                                                    : 1.0017);
                        Assert.AreEqual(expectedDelta, massDelta, 0.001);
                    }
                    else
                    {
                        Assert.AreEqual(c13Delta, massDelta, 0.001);
                    }
                }
            }
            AssertEx.Serializable(docIsotopes, AssertEx.Cloned);

            // Narrow the resolution, and verify that predicted proportion of the isotope
            // distribution captured is reduced for all precursors
            var docIsotopesFt = docIsotopes.ChangeSettings(docIsotopes.Settings.ChangeTransitionFullScan(fs =>
                                                                                                         fs.ChangePrecursorResolution(FullScanMassAnalyzerType.ft_icr, 500 * 1000, 400)));

            docCheckPoints.Add(docIsotopesFt);
            var tranGroupsOld = docIsotopes.MoleculeTransitionGroups.ToArray();
            var tranGroupsNew = docIsotopesFt.MoleculeTransitionGroups.ToArray();

            Assume.AreEqual(tranGroupsOld.Length, tranGroupsNew.Length);
            for (int i = 0; i < tranGroupsOld.Length; i++)
            {
                Assert.AreNotSame(tranGroupsOld[i], tranGroupsNew[i]);
                Assert.AreNotSame(tranGroupsOld[i].IsotopeDist, tranGroupsNew[i].IsotopeDist);
                Assert.IsTrue(tranGroupsOld[i].IsotopeDist.ExpectedProportions.Sum() >
                              tranGroupsNew[i].IsotopeDist.ExpectedProportions.Sum());
            }

            // Use Min % of base peak and verify variation in transitions used
            const float minPercent1   = 10;
            var         docIsotopesP1 = docIsotopes.ChangeSettings(docIsotopes.Settings.ChangeTransitionFullScan(fs =>
                                                                                                                 fs.ChangePrecursorIsotopes(FullScanPrecursorIsotopes.Percent, minPercent1, enrichments)));

            docCheckPoints.Add(docIsotopesP1);
            tranGroupsNew = docIsotopesP1.MoleculeTransitionGroups.ToArray();
            int maxTran = 0;

            for (int i = 0; i < tranGroupsOld.Length; i++)
            {
                // Isotope distributions should not have changed
                var isotopePeaks = tranGroupsNew[i].IsotopeDist;
                Assert.AreSame(tranGroupsOld[i].IsotopeDist, isotopePeaks);
                // Expected transitions should be present
                maxTran = Math.Max(maxTran, tranGroupsNew[i].Children.Count);
                foreach (TransitionDocNode nodeTran in tranGroupsNew[i].Children)
                {
                    int massIndex = nodeTran.Transition.MassIndex;
                    Assume.IsTrue(minPercent1 <= isotopePeaks.GetProportionI(massIndex) * 100.0 / isotopePeaks.BaseMassPercent);
                }
            }
            Assume.AreEqual(5, maxTran);
            AssertEx.Serializable(docIsotopesP1, AssertEx.Cloned);  // Express any failure in terms of XML diffs

            // Use 10%, and check that 15N modifications all have M-1
            const float minPercent2   = 5;
            var         docIsotopesP2 = docIsotopesP1.ChangeSettings(docIsotopesP1.Settings.ChangeTransitionFullScan(fs =>
                                                                                                                     fs.ChangePrecursorIsotopes(FullScanPrecursorIsotopes.Percent, minPercent2, enrichments)));

            docCheckPoints.Add(docIsotopesP2);

            foreach (var nodeGroup in docIsotopesP2.MoleculeTransitionGroups)
            {
                var firstChild = (TransitionDocNode)nodeGroup.Children[0];
                if (nodeGroup.TransitionGroup.LabelType.Name.EndsWith("15N"))
                {
                    Assume.AreEqual(-1, firstChild.Transition.MassIndex);
                }
                else
                {
                    Assume.AreNotEqual(-1, firstChild.Transition.MassIndex);
                }
            }
            AssertEx.Serializable(docIsotopesP2, AssertEx.Cloned);

            // Use lower enrichment of 13C, and verify that this add M-1 for 13C labeled precursors
            var enrichmentsLow13C = enrichments.ChangeEnrichment(new IsotopeEnrichmentItem(BioMassCalc.C13, 0.9));
            var docIsotopesLow13C = docIsotopesP1.ChangeSettings(docIsotopesP1.Settings.ChangeTransitionFullScan(fs =>
                                                                                                                 fs.ChangePrecursorIsotopes(FullScanPrecursorIsotopes.Percent, minPercent2, enrichmentsLow13C)));

            tranGroupsNew = docIsotopesLow13C.MoleculeTransitionGroups.ToArray();
            for (int i = 0; i < tranGroupsOld.Length; i++)
            {
                var nodeGroup = tranGroupsNew[i];
                if (!Equals(nodeGroup.TransitionGroup.LabelType.Name, "heavy"))
                {
                    Assert.AreSame(tranGroupsOld[i].IsotopeDist, nodeGroup.IsotopeDist);
                }
                else
                {
                    var firstChild = (TransitionDocNode)nodeGroup.Children[0];
                    Assert.IsTrue(firstChild.Transition.MassIndex < 0);
                }
            }
            AssertEx.Serializable(docIsotopesLow13C, AssertEx.Cloned); // Express any failure as XML diffs

            // Use 0%, and check that everything has M-1 and lower
            var enrichmentsLow   = enrichmentsLow13C.ChangeEnrichment(new IsotopeEnrichmentItem(BioMassCalc.N15, 0.97));
            var docIsotopesLowP0 = docIsotopesP1.ChangeSettings(docIsotopesP1.Settings.ChangeTransitionFullScan(fs =>
                                                                                                                fs.ChangePrecursorIsotopes(FullScanPrecursorIsotopes.Percent, 0, enrichmentsLow)));

            docCheckPoints.Add(docIsotopesLowP0);
            foreach (var nodeGroup in docIsotopesLowP0.MoleculeTransitionGroups)
            {
                Assume.AreEqual(nodeGroup.IsotopeDist.CountPeaks, nodeGroup.Children.Count);
                var firstChild = (TransitionDocNode)nodeGroup.Children[0];
                if (nodeGroup.TransitionGroup.LabelType.IsLight)
                {
                    Assert.AreEqual(-1, firstChild.Transition.MassIndex);
                }
                else
                {
                    Assert.IsTrue(-1 > firstChild.Transition.MassIndex);
                }
            }
            AssertEx.Serializable(docIsotopesLowP0, AssertEx.Cloned);

            // Test a document with variable and heavy modifications, which caused problems for
            // the original implementation
            var docVariable = ResultsUtil.DeserializeDocument("HeavyVariable.sky", GetType());

            Assert.IsFalse(docVariable.MoleculeTransitionGroups.Any(nodeGroup => nodeGroup.IsotopeDist == null));

            foreach (var nodeGroup in docVariable.MoleculeTransitionGroups)
            {
                var isotopePeaks = nodeGroup.IsotopeDist;
                Assert.IsNotNull(isotopePeaks);
                // The peaks should always includ at least M-1
                Assert.IsTrue(isotopePeaks.MassIndexToPeakIndex(0) > 0);
                // Precursor mass and m/z values are expected to match exactly (well, within XML roundtrip tolerance anyway)
                var mzI = nodeGroup.IsotopeDist.GetMZI(0);
                Assert.AreEqual(nodeGroup.PrecursorMz, mzI, SequenceMassCalc.MassTolerance);

                // Check isotope distribution masses
                for (int i = 1; i < isotopePeaks.CountPeaks; i++)
                {
                    int massIndex = isotopePeaks.PeakIndexToMassIndex(i);
                    Assert.IsTrue(isotopePeaks.GetMZI(massIndex - 1) < isotopePeaks.GetMZI(massIndex));
                    double massDelta      = GetMassDelta(isotopePeaks, massIndex);
                    bool   containsSulfur = nodeGroup.TransitionGroup.Peptide.IsCustomMolecule
                        ? (nodeGroup.CustomMolecule.Formula.IndexOfAny("S".ToCharArray()) != -1)
                        : (nodeGroup.TransitionGroup.Peptide.Sequence.IndexOfAny("CM".ToCharArray()) != -1);
                    if (massIndex == 0)
                    {
                        double expectedDelta = (isotopePeaks.GetProportionI(massIndex - 1) == 0
                                                    ? GetMassDelta(isotopePeaks, massIndex + 1)
                                                    : 1.0017);
                        Assert.AreEqual(expectedDelta, massDelta, 0.001);
                    }
                    else if (!containsSulfur || massIndex == 1)
                    {
                        Assert.AreEqual(c13Delta, massDelta, 0.001);
                    }
                    else
                    {
                        Assert.AreEqual(1.00075, massDelta, 0.001);
                    }
                }
            }
            docCheckPoints.Add(docVariable);
        }
示例#21
0
        public SrmDocument ConvertToSmallMolecules(SrmDocument doc, ref string docPath, IEnumerable <string> dataPaths,
                                                   RefinementSettings.ConvertToSmallMoleculesMode mode)
        {
            if (doc == null)
            {
                using (var cmd = new CommandLine())
                {
                    Assert.IsTrue(cmd.OpenSkyFile(docPath)); // Handles any path shifts in database files, like our .imsdb file
                    var docLoad = cmd.Document;
                    using (var docContainer = new ResultsTestDocumentContainer(null, docPath))
                    {
                        docContainer.SetDocument(docLoad, null, true);
                        docContainer.AssertComplete();
                        doc = docContainer.Document;
                    }
                }
            }
            if (mode == RefinementSettings.ConvertToSmallMoleculesMode.none)
            {
                return(doc);
            }

            var docOriginal = doc;
            var refine      = new RefinementSettings();

            docPath = docPath.Replace(".sky", "_converted_to_small_molecules.sky");
            var docSmallMol =
                refine.ConvertToSmallMolecules(doc, Path.GetDirectoryName(docPath), mode);
            var listChromatograms = new List <ChromatogramSet>();

            if (dataPaths != null)
            {
                foreach (var dataPath in dataPaths)
                {
                    if (!string.IsNullOrEmpty(dataPath))
                    {
                        listChromatograms.Add(AssertResult.FindChromatogramSet(docSmallMol, new MsDataFilePath(dataPath)) ??
                                              new ChromatogramSet(Path.GetFileName(dataPath).Replace('.', '_'),
                                                                  new[] { dataPath }));
                    }
                }
            }
            var docResults = docSmallMol.ChangeMeasuredResults(listChromatograms.Any() ? new MeasuredResults(listChromatograms) : null);

            // Since refine isn't in a document container, have to close the streams manually to avoid file locking trouble (thanks, Nick!)
            foreach (var library in docResults.Settings.PeptideSettings.Libraries.Libraries)
            {
                foreach (var stream in library.ReadStreams)
                {
                    stream.CloseStream();
                }
            }

            // Save and restore to ensure library caches
            var cmdline = new CommandLine();

            cmdline.SaveDocument(docResults, docPath, TextWriter.Null);
            Assert.IsTrue(cmdline.OpenSkyFile(docPath)); // Handles any path shifts in database files, like our .imsdb file
            docResults = cmdline.Document;
            using (var docContainer = new ResultsTestDocumentContainer(null, docPath))
            {
                docContainer.SetDocument(docResults, null, true);
                docContainer.AssertComplete();
                doc = docContainer.Document;
            }
            AssertEx.ConvertedSmallMoleculeDocumentIsSimilar(docOriginal, doc, Path.GetDirectoryName(docPath), mode);
            return(doc);
        }
示例#22
0
        private void PerformTestMeasuredDriftValues(bool asSmallMolecules)
        {
            if (asSmallMolecules)
            {
                if (!RunSmallMoleculeTestVersions)
                {
                    Console.Write(MSG_SKIPPING_SMALLMOLECULE_TEST_VERSION);
                    return;
                }
            }
            var testFilesDir = new TestFilesDir(TestContext, @"TestData\Results\BlibDriftTimeTest.zip"); // Re-used from BlibDriftTimeTest
            // Open document with some peptides but no results
            var docPath = testFilesDir.GetTestPath("BlibDriftTimeTest.sky");
            // This was a malformed document, which caused problems after a fix to not recalculate
            // document library settings on open. To avoid rewriting this test for the document
            // which now contains 2 precursors, the first precursor is removed immediately.
            SrmDocument docOriginal      = ResultsUtil.DeserializeDocument(docPath);
            var         pathFirstPeptide = docOriginal.GetPathTo((int)SrmDocument.Level.Molecules, 0);
            var         nodeFirstPeptide = (DocNodeParent)docOriginal.FindNode(pathFirstPeptide);

            docOriginal = (SrmDocument)docOriginal.RemoveChild(pathFirstPeptide, nodeFirstPeptide.Children[0]);
            if (asSmallMolecules)
            {
                var refine = new RefinementSettings();
                docOriginal = refine.ConvertToSmallMolecules(docOriginal, testFilesDir.FullPath);
            }
            using (var docContainer = new ResultsTestDocumentContainer(docOriginal, docPath))
            {
                var doc = docContainer.Document;

                // Import an mz5 file that contains drift info
                const string replicateName = "ID12692_01_UCA168_3727_040714";
                var          chromSets     = new[]
                {
                    new ChromatogramSet(replicateName, new[]
                                        { new MsDataFilePath(testFilesDir.GetTestPath("ID12692_01_UCA168_3727_040714" + ExtensionTestContext.ExtMz5)), }),
                };
                var docResults = doc.ChangeMeasuredResults(new MeasuredResults(chromSets));
                Assert.IsTrue(docContainer.SetDocument(docResults, docOriginal, true));
                docContainer.AssertComplete();
                var document = docContainer.Document;

                // Clear out any current settings
                document = document.ChangeSettings(document.Settings.ChangeTransitionIonMobilityFiltering(s => TransitionIonMobilityFiltering.EMPTY));

                // Verify ability to extract predictions from raw data
                var libraryName0   = "test0";
                var dbPath0        = testFilesDir.GetTestPath(libraryName0 + IonMobilityDb.EXT);
                var newIMFiltering = document.Settings.TransitionSettings.IonMobilityFiltering.ChangeLibrary(
                    IonMobilityLibrary.CreateFromResults(
                        document, docContainer.DocumentFilePath, true,
                        libraryName0, dbPath0));
                var result = newIMFiltering.IonMobilityLibrary.GetIonMobilityLibKeyMap().AsDictionary();
                Assert.AreEqual(1, result.Count);
                var expectedDT     = 4.0019;
                var expectedOffset = .4829;
                Assert.AreEqual(expectedDT, result.Values.First().First().IonMobility.Mobility.Value, .001);
                Assert.AreEqual(expectedOffset, result.Values.First().First().HighEnergyIonMobilityValueOffset ?? 0, .001);

                // Check ability to update, and to preserve unchanged
                var revised = new List <PrecursorIonMobilities>();
                var libKey  = result.Keys.First();
                revised.Add(new PrecursorIonMobilities(libKey, IonMobilityAndCCS.GetIonMobilityAndCCS(IonMobilityValue.GetIonMobilityValue(expectedDT = 4, eIonMobilityUnits.drift_time_msec), null, expectedOffset = 0.234)));  // N.B. CCS handling would require actual raw data in this test, it's covered in a perf test
                var pepSequence = "DEADEELS";
                var libKey2     = asSmallMolecules ?
                                  new LibKey(SmallMoleculeLibraryAttributes.Create(pepSequence, "C12H5", null, null, null, null), Adduct.M_PLUS_2H) :
                                  new LibKey(pepSequence, Adduct.DOUBLY_PROTONATED);
                revised.Add(new PrecursorIonMobilities(libKey2, IonMobilityAndCCS.GetIonMobilityAndCCS(IonMobilityValue.GetIonMobilityValue(5, eIonMobilityUnits.drift_time_msec), null, 0.123)));
                var libraryName = "test";
                var dbPath      = testFilesDir.GetTestPath(libraryName + IonMobilityDb.EXT);
                var imsdb       = IonMobilityDb.CreateIonMobilityDb(dbPath, libraryName, false, revised);
                var newLibIM    = new IonMobilityLibrary(libraryName, dbPath, imsdb);
                var ionMobilityWindowWidthCalculator = new IonMobilityWindowWidthCalculator(
                    IonMobilityWindowWidthCalculator.IonMobilityWindowWidthType.resolving_power, 40, 0, 0, 0);
                var calculator = ionMobilityWindowWidthCalculator;
                document = document.ChangeSettings(
                    document.Settings.ChangeTransitionIonMobilityFiltering(
                        imf => imf.ChangeFilterWindowWidthCalculator(calculator).
                        ChangeLibrary(newLibIM)));
                result = document.Settings.TransitionSettings.IonMobilityFiltering.IonMobilityLibrary.GetIonMobilityLibKeyMap().AsDictionary();
                Assert.AreEqual(2, result.Count);
                Assert.AreEqual(expectedDT, result[libKey].First().IonMobility.Mobility.Value, .001);
                Assert.AreEqual(expectedOffset, result[libKey].First().HighEnergyIonMobilityValueOffset ?? 0, .001);
                Assert.AreEqual(5, result[libKey2].First().IonMobility.Mobility.Value, .001);
                Assert.AreEqual(0.123, result[libKey2].First().HighEnergyIonMobilityValueOffset ?? 0, .001);

                ionMobilityWindowWidthCalculator = new IonMobilityWindowWidthCalculator(
                    IonMobilityWindowWidthCalculator.IonMobilityWindowWidthType.fixed_width, 40, 0, 0, 100);
                document = document.ChangeSettings(
                    document.Settings.ChangeTransitionIonMobilityFiltering(
                        imf => imf.ChangeFilterWindowWidthCalculator(ionMobilityWindowWidthCalculator).
                        ChangeLibrary(newLibIM)));
                result = document.Settings.TransitionSettings.IonMobilityFiltering.IonMobilityLibrary.GetIonMobilityLibKeyMap().AsDictionary();
                Assert.AreEqual(2, result.Count);
                Assert.AreEqual(expectedDT, result[libKey].First().IonMobility.Mobility.Value, .001);
                Assert.AreEqual(expectedOffset, result[libKey].First().HighEnergyIonMobilityValueOffset ?? 0, .001);
                Assert.AreEqual(5, result[libKey2].First().IonMobility.Mobility.Value, .001);
                Assert.AreEqual(0.123, result[libKey2].First().HighEnergyIonMobilityValueOffset ?? 0, .001);
            }
        }
示例#23
0
        public void DoAgilentMseChromatogramTest(RefinementSettings.ConvertToSmallMoleculesMode asSmallMolecules, small_mol_mode smallMolMode = small_mol_mode.simple, string expectedError = null)
        {
            if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.none && !RunSmallMoleculeTestVersions && smallMolMode == small_mol_mode.simple)
            {
                System.Console.Write(MSG_SKIPPING_SMALLMOLECULE_TEST_VERSION);
                return;
            }

            var testFilesDir = new TestFilesDir(TestContext, ZIP_FILE);

            string      docPath;
            SrmDocument document = InitAgilentMseDocument(testFilesDir, out docPath);

            if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.none)
            {
                var refine = new RefinementSettings();
                document = refine.ConvertToSmallMolecules(document, testFilesDir.FullPath, asSmallMolecules, smallMolMode == small_mol_mode.simple ? RefinementSettings.ConvertToSmallMoleculesChargesMode.none : RefinementSettings.ConvertToSmallMoleculesChargesMode.invert);
            }
            using (var docContainer = new ResultsTestDocumentContainer(document, docPath))
            {
                var doc = docContainer.Document;
                var listChromatograms = new List <ChromatogramSet>();
                var path = MsDataFileUri.Parse(smallMolMode == small_mol_mode.invert_charges_and_data ? @"AgilentMse\BSA-AI-0-10-25-41_first_100_scans_neg.mzML" : @"AgilentMse\BSA-AI-0-10-25-41_first_100_scans.mzML");
                listChromatograms.Add(AssertResult.FindChromatogramSet(doc, path) ??
                                      new ChromatogramSet(path.GetFileName().Replace('.', '_'), new[] { path }));
                var docResults = doc.ChangeMeasuredResults(new MeasuredResults(listChromatograms));
                Assert.IsTrue(docContainer.SetDocument(docResults, doc, true));
                if (expectedError != null)
                {
                    docContainer.AssertError(expectedError);
                }
                else
                {
                    docContainer.AssertComplete();
                    document = docContainer.Document;

                    float tolerance = (float)document.Settings.TransitionSettings.Instrument.MzMatchTolerance;
                    var   results   = document.Settings.MeasuredResults;
                    foreach (var pair in document.MoleculePrecursorPairs)
                    {
                        ChromatogramGroupInfo[] chromGroupInfo;
                        Assert.IsTrue(results.TryLoadChromatogram(0, pair.NodePep, pair.NodeGroup,
                                                                  tolerance, true, out chromGroupInfo));
                        Assert.AreEqual(1, chromGroupInfo.Length);
                        VerifyMs1Truncated(chromGroupInfo.First());
                    }

                    // now drill down for specific values
                    int nPeptides = 0;
                    foreach (var nodePep in document.Molecules.Where(nodePep => !nodePep.Results[0].IsEmpty))
                    {
                        // expecting just one peptide result in this small data set
                        if (nodePep.Results[0].Any(chromInfo => chromInfo.PeakCountRatio > 0))
                        {
                            Assert.AreEqual(0.25205,
                                            (double)nodePep.GetMeasuredRetentionTime(0), .0001, "averaged retention time differs in node " + nodePep.ModifiedTarget);
                            Assert.AreEqual(0.3333, (double)nodePep.GetPeakCountRatio(0), 0.0001);
                            nPeptides++;
                        }
                    }
                    Assert.AreEqual(smallMolMode == small_mol_mode.invert_charges ? 0 : 1, nPeptides); // If we switched document polarity, we'd expect no chromatograms extracted
                }
            }
            testFilesDir.Dispose();
        }
示例#24
0
        public void DoAsymmetricIsolationTest(RefinementSettings.ConvertToSmallMoleculesMode asSmallMolecules)
        {
            if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.none && !RunSmallMoleculeTestVersions)
            {
                Console.Write(MSG_SKIPPING_SMALLMOLECULE_TEST_VERSION);
                return;
            }

            LocalizationHelper.InitThread();    // TODO: All unit tests should be correctly initialized

            var    testFilesDir = new TestFilesDir(TestContext, ZIP_FILE);
            string docPath      = testFilesDir.GetTestPath("Asym_DIA.sky");
            string cachePath    = ChromatogramCache.FinalPathForName(docPath, null);

            FileEx.SafeDelete(cachePath);
            SrmDocument doc    = ResultsUtil.DeserializeDocument(docPath);
            var         refine = new RefinementSettings();

            doc = refine.ConvertToSmallMolecules(doc, testFilesDir.FullPath, asSmallMolecules);
            const int expectedMoleculeCount = 1;   // At first small molecules did not support multiple charge states, and this was 2 for that test mode

            AssertEx.IsDocumentState(doc, null, 1, expectedMoleculeCount, 2, 4);
            var fullScanInitial = doc.Settings.TransitionSettings.FullScan;

            Assert.IsTrue(fullScanInitial.IsEnabledMsMs);
            Assert.AreEqual(FullScanAcquisitionMethod.DIA, fullScanInitial.AcquisitionMethod);
            Assert.AreEqual(25, fullScanInitial.PrecursorFilter);
            AssertEx.Serializable(doc);
            using (var docContainer = new ResultsTestDocumentContainer(doc, docPath))
            {
                // Import the first RAW file (or mzML for international)
                string rawPath         = testFilesDir.GetTestPath("Asym_DIA_data.mzML");
                var    measuredResults = new MeasuredResults(new[] { new ChromatogramSet("Single", new[] { rawPath }) });
                TransitionGroupDocNode nodeGroup;
                double ratio;

                const double poorRatio  = 0.25;
                const double fixedRatio = 1.05;
                {
                    // Import with symmetric isolation window
                    SrmDocument docResults = docContainer.ChangeMeasuredResults(measuredResults, expectedMoleculeCount, 1, 1, 2, 2);
                    nodeGroup = docResults.MoleculeTransitionGroups.First();
                    ratio     = nodeGroup.Results[0][0].Ratio ?? 0;
                    // The expected ratio is 1.0, but the symmetric isolation window should produce poor results
                    if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.masses_only)  // Can't use labels without a formula
                    {
                        Assert.AreEqual(poorRatio, ratio, 0.05);
                    }

                    // Revert to original document, and get rid of results cache
                    Assert.IsTrue(docContainer.SetDocument(doc, docResults, false));
                    FileEx.SafeDelete(testFilesDir.GetTestPath("Asym_DIA.skyd"));
                }

                {
                    // Import with asymmetric isolation window
                    SrmDocument docAsym = doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(fullScan =>
                                                                                                   fullScan.ChangeAcquisitionMethod(fullScan.AcquisitionMethod, new IsolationScheme("Test asym", 5, 20))));
                    AssertEx.Serializable(docAsym);
                    Assert.IsTrue(docContainer.SetDocument(docAsym, doc, false));

                    SrmDocument docResults = docContainer.ChangeMeasuredResults(measuredResults, expectedMoleculeCount, 1, 1, 2, 2);
                    nodeGroup = docResults.MoleculeTransitionGroups.First();
                    ratio     = nodeGroup.Results[0][0].Ratio ?? 0;
                    // Asymmetric should be a lot closer to 1.0
                    if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.masses_only)  // Can't use labels without a formula
                    {
                        Assert.AreEqual(fixedRatio, ratio, 0.05);
                    }

                    // Revert to original document, and get rid of results cache
                    Assert.IsTrue(docContainer.SetDocument(doc, docResults, false));
                    FileEx.SafeDelete(testFilesDir.GetTestPath("Asym_DIA.skyd"));
                }

                {
                    // Import with prespecified isolation windows
                    var windowList = new List <IsolationWindow>
                    {
                        new IsolationWindow(999.2702214, 1024.270221),
                        new IsolationWindow(1024.27267, 1049.27267)
                    };
                    SrmDocument docPrespecified = doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(fullScan =>
                                                                                                           fullScan.ChangeAcquisitionMethod(fullScan.AcquisitionMethod, new IsolationScheme("Test prespecified", windowList))));
                    AssertEx.Serializable(docPrespecified);
                    Assert.IsTrue(docContainer.SetDocument(docPrespecified, doc, false));

                    SrmDocument docResults = docContainer.ChangeMeasuredResults(measuredResults, expectedMoleculeCount, 1, 1, 2, 2);
                    nodeGroup = docResults.MoleculeTransitionGroups.First();
                    ratio     = nodeGroup.Results[0][0].Ratio ?? 0;
                    // Asymmetric should be a lot closer to 1.0
                    if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.masses_only)  // Can't use labels without a formula
                    {
                        Assert.AreEqual(fixedRatio, ratio, 0.05);
                    }

                    // Revert to original document, and get rid of results cache
                    Assert.IsTrue(docContainer.SetDocument(doc, docResults, false));
                    FileEx.SafeDelete(testFilesDir.GetTestPath("Asym_DIA.skyd"));
                }

                {
                    // Import with prespecified targets
                    var windowList = new List <IsolationWindow>
                    {
                        new IsolationWindow(999.2702214, 1024.270221, 1004.27),
                        new IsolationWindow(1024.27267, 1049.27267, 1029.27)
                    };
                    SrmDocument docPrespecified = doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(fullScan =>
                                                                                                           fullScan.ChangeAcquisitionMethod(fullScan.AcquisitionMethod, new IsolationScheme("Test target", windowList))));
                    AssertEx.Serializable(docPrespecified);
                    Assert.IsTrue(docContainer.SetDocument(docPrespecified, doc, false));

                    SrmDocument docResults = docContainer.ChangeMeasuredResults(measuredResults, expectedMoleculeCount, 1, 1, 2, 2);
                    nodeGroup = docResults.MoleculeTransitionGroups.First();
                    ratio     = nodeGroup.Results[0][0].Ratio ?? 0;
                    // Asymmetric should be a lot closer to 1.0
                    if (asSmallMolecules != RefinementSettings.ConvertToSmallMoleculesMode.masses_only)  // Can't use labels without a formula
                    {
                        Assert.AreEqual(fixedRatio, ratio, 0.05);
                    }

                    // Revert to original document, and get rid of results cache
                    Assert.IsTrue(docContainer.SetDocument(doc, docResults, false));
                    FileEx.SafeDelete(testFilesDir.GetTestPath("Asym_DIA.skyd"));
                }

                {
                    // Import with ambiguous prespecified targets
                    var windowList = new List <IsolationWindow>
                    {
                        new IsolationWindow(999.2702214, 1024.270221, 1004.27),
                        new IsolationWindow(1000.0, 1049.27267, 1004.28)
                    };
                    SrmDocument docAmbiguous = doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(fullScan =>
                                                                                                        fullScan.ChangeAcquisitionMethod(fullScan.AcquisitionMethod, new IsolationScheme("Test ambiguous", windowList))));
                    AssertEx.Serializable(docAmbiguous);
                    Assert.IsTrue(docContainer.SetDocument(docAmbiguous, doc, false));

                    try
                    {
                        docContainer.ChangeMeasuredResults(measuredResults, expectedMoleculeCount, 1, 1, 2, 2);
                        Assert.Fail("Expected ambiguous isolation targets.");
                    }
                    catch (Exception x)
                    {
                        AssertEx.AreComparableStrings(Resources.SpectrumFilter_FindFilterPairs_Two_isolation_windows_contain_targets_which_match_the_isolation_target__0__, x.Message, 1);
                    }

                    // Revert to original document, and get rid of results cache
                    Assert.IsTrue(docContainer.SetDocument(doc, docContainer.Document, false));
                    FileEx.SafeDelete(testFilesDir.GetTestPath("Asym_DIA.skyd"));
                }

                {
                    // Import with one isolation window, so one result is discarded.
                    var windowList = new List <IsolationWindow>
                    {
                        new IsolationWindow(999.2702214, 1024.270221),
                    };
                    SrmDocument docOneWindow = doc.ChangeSettings(doc.Settings.ChangeTransitionFullScan(fullScan =>
                                                                                                        fullScan.ChangeAcquisitionMethod(fullScan.AcquisitionMethod, new IsolationScheme("Test one window", windowList))));
                    AssertEx.Serializable(docOneWindow);
                    Assert.IsTrue(docContainer.SetDocument(docOneWindow, doc, false));

                    SrmDocument docResults = docContainer.ChangeMeasuredResults(measuredResults, 1, 1, 0, 2, 0);
                    nodeGroup = docResults.MoleculeTransitionGroups.First();
                    Assert.IsNull(nodeGroup.Results[0][0].Ratio);

                    // Revert to original document, and get rid of results cache
                    Assert.IsTrue(docContainer.SetDocument(doc, docResults, false));
                    FileEx.SafeDelete(testFilesDir.GetTestPath("Asym_DIA.skyd"));
                }
            }

            testFilesDir.Dispose();
        }