Example #1
0
        /// <summary>
        /// A quick unit test for the name->path name uniqueness enforcement code.
        /// </summary>
        private void TestUniqueness()
        {
            const string PREFIX = "prefix1";
            var          names  = new[] { PREFIX + "a", PREFIX + "b", PREFIX };

            Assert.AreEqual(PREFIX, ImportResultsDlg.GetCommonPrefix(names)); // Check common prefix code while we're at it
            var list = new List <ImportPeptideSearch.FoundResultsFile>
            {
                new ImportPeptideSearch.FoundResultsFile(PREFIX + "a", "path1"),
                new ImportPeptideSearch.FoundResultsFile(PREFIX + "b", "path2"),
                new ImportPeptideSearch.FoundResultsFile(PREFIX + "a", "path3")
            };
            var result = ImportResultsControl.EnsureUniqueNames(list);

            Assert.AreEqual(list[0].Name, result[0].Name);
            Assert.AreEqual(list[1].Name, result[1].Name);
            Assert.AreEqual(list[2].Name + "2", result[2].Name);
        }
Example #2
0
        private void NextPage()
        {
            switch (CurrentPage)
            {
            case Pages.spectra_page:
            {
                HasPeakBoundaries = BuildPepSearchLibControl.SearchFilenames.All(f => f.EndsWith(BiblioSpecLiteBuilder.EXT_TSV));
                if (BuildPepSearchLibControl.SearchFilenames.Any(f => f.EndsWith(BiblioSpecLiteBuilder.EXT_TSV)) && !HasPeakBoundaries)
                {
                    MessageDlg.Show(this, Resources.ImportPeptideSearchDlg_NextPage_Cannot_build_library_from_OpenSWATH_results_mixed_with_results_from_other_tools_);
                    return;
                }

                var eCancel = new CancelEventArgs();
                if (!BuildPeptideSearchLibrary(eCancel))
                {
                    // Page shows error
                    if (eCancel.Cancel)
                    {
                        return;
                    }
                    CloseWizard(DialogResult.Cancel);
                }

                // The user had the option to finish right after
                // building the peptide search library, but they
                // did not, so hide the "early finish" button for
                // the rest of the wizard pages.
                ShowEarlyFinish(false);

                if (FastaOptional)
                {
                    lblFasta.Text = Resources.ImportPeptideSearchDlg_NextPage_Import_FASTA__optional_;
                }

                // The next page is going to be the chromatograms page.
                var oldImportResultsControl = (ImportResultsControl)ImportResultsControl;

                if (WorkflowType != Workflow.dia || HasPeakBoundaries)
                {
                    oldImportResultsControl.InitializeChromatogramsPage(Document);

                    if (WorkflowType == Workflow.dda)
                    {
                        _pagesToSkip.Add(Pages.transition_settings_page);
                    }
                }
                else
                {
                    // DIA workflow, replace old ImportResultsControl
                    ImportResultsControl = new ImportResultsDIAControl(this)
                    {
                        Anchor   = oldImportResultsControl.Anchor,
                        Location = oldImportResultsControl.Location
                    };
                    getChromatogramsPage.Controls.Remove(oldImportResultsControl);
                    getChromatogramsPage.Controls.Add((Control)ImportResultsControl);
                }
                ImportResultsControl.ResultsFilesChanged += ImportResultsControl_OnResultsFilesChanged;

                // Set up full scan settings page
                TransitionSettingsControl.Initialize(WorkflowType);
                FullScanSettingsControl.ModifyOptionsForImportPeptideSearchWizard(WorkflowType);

                if (!MatchModificationsControl.Initialize(Document))
                {
                    _pagesToSkip.Add(Pages.match_modifications_page);
                }
                if (BuildPepSearchLibControl.FilterForDocumentPeptides)
                {
                    _pagesToSkip.Add(Pages.import_fasta_page);
                }

                // Decoy options enabled only for DIA
                ImportFastaControl.RequirePrecursorTransition = WorkflowType != Workflow.dia;
                ImportFastaControl.DecoyGenerationEnabled     = WorkflowType == Workflow.dia && !HasPeakBoundaries;
            }
            break;

            case Pages.chromatograms_page:
            {
                if (!ImportPeptideSearch.VerifyRetentionTimes(ImportResultsControl.FoundResultsFiles.Select(f => f.Path)))
                {
                    MessageDlg.Show(this, TextUtil.LineSeparate(Resources.ImportPeptideSearchDlg_NextPage_The_document_specific_spectral_library_does_not_have_valid_retention_times_,
                                                                Resources.ImportPeptideSearchDlg_NextPage_Please_check_your_peptide_search_pipeline_or_contact_Skyline_support_to_ensure_retention_times_appear_in_your_spectral_libraries_));
                    CloseWizard(DialogResult.Cancel);
                }

                if (ImportResultsControl.ResultsFilesMissing)
                {
                    if (MessageBox.Show(this, Resources.ImportPeptideSearchDlg_NextPage_Some_results_files_are_still_missing__Are_you_sure_you_want_to_continue_,
                                        Program.Name, MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                    {
                        return;
                    }
                }

                var foundResults = ImportResultsControl.FoundResultsFiles;
                if (foundResults.Count > 1)
                {
                    // Older Resharper code inspection implementations insist on warning here
                    // Resharper disable PossibleMultipleEnumeration
                    string[] resultNames = foundResults.Select(f => f.Name).ToArray();
                    string   prefix      = ImportResultsDlg.GetCommonPrefix(resultNames);
                    string   suffix      = ImportResultsDlg.GetCommonSuffix(resultNames);
                    // Resharper restore PossibleMultipleEnumeration
                    if (!string.IsNullOrEmpty(prefix) || !string.IsNullOrEmpty(suffix))
                    {
                        using (var dlgName = new ImportResultsNameDlg(prefix, suffix, resultNames))
                        {
                            var result = dlgName.ShowDialog(this);
                            if (result == DialogResult.Cancel)
                            {
                                return;
                            }
                            else if (dlgName.IsRemove)
                            {
                                ImportResultsControl.FoundResultsFiles = ImportResultsControl.FoundResultsFiles.Select(f =>
                                                                                                                       new ImportPeptideSearch.FoundResultsFile(dlgName.ApplyNameChange(f.Name), f.Path)).ToList();

                                ImportResultsControl.Prefix =
                                    string.IsNullOrEmpty(prefix) ? null : prefix;
                                ImportResultsControl.Suffix =
                                    string.IsNullOrEmpty(suffix) ? null : suffix;
                            }
                        }
                    }
                }
            }
            break;

            case Pages.match_modifications_page:
                if (!UpdateModificationSettings())
                {
                    return;
                }
                break;

            case Pages.transition_settings_page:
                // Try to accept changes to transition settings
                if (!UpdateTransitionSettings())
                {
                    return;
                }
                break;

            case Pages.full_scan_settings_page:
                // Try to accept changes to MS1 full-scan settings
                if (!UpdateFullScanSettings())
                {
                    // We can't allow the user to progress any further until
                    // we can verify that the MS1 full scan settings are valid.
                    return;
                }
                break;

            case Pages.import_fasta_page:     // This is the last page
                if (FastaOptional && !ImportFastaControl.ContainsFastaContent || ImportFastaControl.ImportFasta())
                {
                    WizardFinish();
                }
                return;
            }

            var newPage = CurrentPage + 1;

            while (_pagesToSkip.Contains(newPage))
            {
                ++newPage;
            }

            // Skip import FASTA if user filters for document peptides
            if (newPage > Pages.import_fasta_page)
            {
                WizardFinish();
                return;
            }

            CurrentPage = newPage;
            UpdateButtons();
        }
        private void NextPage()
        {
            switch (CurrentPage)
            {
            case Pages.spectra_page:
            {
                var eCancel = new CancelEventArgs();
                if (!BuildPepSearchLibControl.BuildPeptideSearchLibrary(eCancel))
                {
                    // Page shows error
                    if (eCancel.Cancel)
                    {
                        return;
                    }
                    CloseWizard(DialogResult.Cancel);
                }

                // The user had the option to finish right after
                // building the peptide search library, but they
                // did not, so hide the "early finish" button for
                // the rest of the wizard pages.
                ShowEarlyFinish(false);

                if (FastaOptional)
                {
                    lblFasta.Text = Resources.ImportPeptideSearchDlg_NextPage_Import_FASTA__optional_;
                }

                // The next page is going to be the chromatograms page.
                var oldImportResultsControl = (ImportResultsControl)ImportResultsControl;

                if (WorkflowType != Workflow.dia)
                {
                    oldImportResultsControl.InitializeChromatogramsPage(SkylineWindow.DocumentUI);

                    if (WorkflowType == Workflow.dda)
                    {
                        _pagesToSkip.Add(Pages.transition_settings_page);
                    }
                }
                else
                {
                    // DIA workflow, replace old ImportResultsControl
                    ImportResultsControl = new ImportResultsDIAControl(SkylineWindow)
                    {
                        Anchor   = oldImportResultsControl.Anchor,
                        Location = oldImportResultsControl.Location
                    };
                    getChromatogramsPage.Controls.Remove(oldImportResultsControl);
                    getChromatogramsPage.Controls.Add((Control)ImportResultsControl);
                }
                ImportResultsControl.ResultsFilesChanged += ImportResultsControl_OnResultsFilesChanged;

                // Set up full scan settings page
                TransitionSettingsControl.Initialize(WorkflowType);
                FullScanSettingsControl.ModifyOptionsForImportPeptideSearchWizard(WorkflowType);

                if (!MatchModificationsControl.Initialize(SkylineWindow.Document))
                {
                    _pagesToSkip.Add(Pages.match_modifications_page);
                }
                if (BuildPepSearchLibControl.FilterForDocumentPeptides)
                {
                    _pagesToSkip.Add(Pages.import_fasta_page);
                }
            }
            break;

            case Pages.chromatograms_page:
            {
                if (!ImportPeptideSearch.VerifyRetentionTimes(ImportResultsControl.FoundResultsFiles.Select(f => f.Path)))
                {
                    MessageDlg.Show(this, TextUtil.LineSeparate(Resources.ImportPeptideSearchDlg_NextPage_The_document_specific_spectral_library_does_not_have_valid_retention_times_,
                                                                Resources.ImportPeptideSearchDlg_NextPage_Please_check_your_peptide_search_pipeline_or_contact_Skyline_support_to_ensure_retention_times_appear_in_your_spectral_libraries_));
                    CloseWizard(DialogResult.Cancel);
                }

                if (ImportResultsControl.ResultsFilesMissing)
                {
                    if (MessageBox.Show(this, Resources.ImportPeptideSearchDlg_NextPage_Some_results_files_are_still_missing__Are_you_sure_you_want_to_continue_,
                                        Program.Name, MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                    {
                        return;
                    }
                }

                if (ImportResultsControl.FoundResultsFiles.Count > 1)
                {
                    string prefix = ImportResultsDlg.GetCommonPrefix(ImportResultsControl.FoundResultsFiles.Select(f => f.Name));
                    if (prefix.Length >= ImportResultsDlg.MIN_COMMON_PREFIX_LENGTH)
                    {
                        using (var dlgName = new ImportResultsNameDlg(prefix))
                        {
                            var result = dlgName.ShowDialog(this);
                            if (result == DialogResult.Cancel)
                            {
                                return;
                            }
                            else if (result == DialogResult.Yes)
                            {
                                // Rename all the replicates to remove the specified prefix.
                                ImportResultsControl.FoundResultsFiles = ImportResultsControl.FoundResultsFiles.Select(f =>
                                                                                                                       new ImportPeptideSearch.FoundResultsFile(f.Name.Substring(dlgName.Prefix.Length), f.Path)).ToList();
                            }
                        }
                    }
                }
            }
            break;

            case Pages.match_modifications_page:
            {
                var newSettings = MatchModificationsControl.AddCheckedModifications(SkylineWindow.Document);
                if (!ReferenceEquals(SkylineWindow.Document.Settings, newSettings))
                {
                    SkylineWindow.ChangeSettings(newSettings, true, Resources.MatchModificationsControl_AddCheckedModifications_Add_checked_modifications);
                    SkylineWindow.Document.Settings.UpdateDefaultModifications(false);
                }

                // The next page is going to be the MS1 Full-Scan Settings
                // page, so initialize it.
                // FullScanSettingsControl.InitializeMs1FullScanSettingsPage();
            }
            break;

            case Pages.transition_settings_page:
                // Try to accept changes to transition settings
                if (!UpdateTransitionSettings())
                {
                    return;
                }
                break;

            case Pages.full_scan_settings_page:
                // Try to accept changes to MS1 full-scan settings
                if (!UpdateFullScanSettings())
                {
                    // We can't allow the user to progress any further until
                    // we can verify that the MS1 full scan settings are valid.
                    return;
                }
                break;

            case Pages.import_fasta_page:     // This is the last page
                if ((FastaOptional && !ImportFastaControl.ContainsFastaContent) ||
                    ImportFastaControl.ImportFasta())
                {
                    WizardFinish();
                }
                return;
            }

            Pages newPage = CurrentPage + 1;

            while (_pagesToSkip.Contains(newPage))
            {
                ++newPage;
            }

            // Skip import FASTA if user filters for document peptides
            if (newPage > Pages.import_fasta_page)
            {
                WizardFinish();
                return;
            }

            CurrentPage = newPage;
            if (CurrentPage == LastPage)
            {
                btnNext.Text = Resources.ImportPeptideSearchDlg_NextPage_Finish;
            }
        }
Example #4
0
        protected override void DoTest()
        {
            // Clean-up before running the test
            RunUI(() => SkylineWindow.ModifyDocument("Set default settings",
                                                     d => d.ChangeSettings(SrmSettingsList.GetDefault())));

            SrmDocument doc = SkylineWindow.Document;

            const string documentBaseName = "Ms1FilterTutorial";
            string       documentFile     = GetTestPath(documentBaseName + SrmDocument.EXT);

            RunUI(() => SkylineWindow.SaveDocument(documentFile));

            // show the empty Transition Setting dialog
            var transitionSettingsDlg = ShowDialog <TransitionSettingsUI>(SkylineWindow.ShowTransitionSettingsUI);

            RunUI(() => transitionSettingsDlg.SelectedTab = TransitionSettingsUI.TABS.FullScan);
            PauseForScreenShot <TransitionSettingsUI.FullScanTab>("Transition Settings - Full-Scan tab nothing set", 2);
            OkDialog(transitionSettingsDlg, transitionSettingsDlg.OkDialog);

            // Launch the wizard
            var importPeptideSearchDlg = ShowDialog <ImportPeptideSearchDlg>(SkylineWindow.ShowImportPeptideSearchDlg);

            // We're on the "Build Spectral Library" page of the wizard.
            // Add the test xml file to the search files list and try to
            // build the document library.
            string[] searchFiles =
            {
                GetTestPath("100803_0001_MCF7_TiB_L.group.xml"),      // Not L10N
                GetTestPath("100803_0005b_MCF7_TiTip3.group.xml")     // Not L10N
            };
            foreach (var searchFile in searchFiles)
            {
                Assert.IsTrue(File.Exists(searchFile), string.Format("File {0} does not exist.", searchFile));
            }

            PauseForScreenShot <ImportPeptideSearchDlg.SpectraPage>("Import Peptide Search - Build Spectral Library empty page", 3);

            RunUI(() =>
            {
                Assert.IsTrue(importPeptideSearchDlg.CurrentPage == ImportPeptideSearchDlg.Pages.spectra_page);
                importPeptideSearchDlg.BuildPepSearchLibControl.AddSearchFiles(searchFiles);

                // Sanity check here, because of failure getting both files for results import below
                var searchNames = importPeptideSearchDlg.BuildPepSearchLibControl.SearchFilenames;
                Assert.AreEqual(searchFiles.Length, searchNames.Length,
                                PathsMessage("Unexpected search files found.", searchNames));
                var builder = importPeptideSearchDlg.BuildPepSearchLibControl.ImportPeptideSearch.GetLibBuilder(
                    SkylineWindow.DocumentUI, SkylineWindow.DocumentFilePath, false);
                Assert.IsTrue(ArrayUtil.EqualsDeep(searchFiles, builder.InputFiles),
                              PathsMessage("Unexpected BlibBuild input files.", builder.InputFiles));
                importPeptideSearchDlg.BuildPepSearchLibControl.DebugMode = true;
            });
            PauseForScreenShot <ImportPeptideSearchDlg.SpectraPage>("Import Peptide Search - Build Spectral Library populated page", 4);

            WaitForConditionUI(() => importPeptideSearchDlg.IsNextButtonEnabled);
            var ambiguousDlg = ShowDialog <MessageDlg>(() => importPeptideSearchDlg.ClickNextButton());

            RunUI(() => AssertEx.Contains(ambiguousDlg.Message,
                                          Resources.BiblioSpecLiteBuilder_AmbiguousMatches_The_library_built_successfully__Spectra_matching_the_following_peptides_had_multiple_ambiguous_peptide_matches_and_were_excluded_));
            OkDialog(ambiguousDlg, ambiguousDlg.OkDialog);

            // Verify document library was built
            string docLibPath          = BiblioSpecLiteSpec.GetLibraryFileName(documentFile);
            string redundantDocLibPath = BiblioSpecLiteSpec.GetRedundantName(docLibPath);

            Assert.IsTrue(File.Exists(docLibPath) && File.Exists(redundantDocLibPath));
            var librarySettings = SkylineWindow.Document.Settings.PeptideSettings.Libraries;

            Assert.IsTrue(librarySettings.HasDocumentLibrary);
            // Verify input paths sent to BlibBuild
            string buildArgs   = importPeptideSearchDlg.BuildPepSearchLibControl.LastBuildCommandArgs;
            string buildOutput = importPeptideSearchDlg.BuildPepSearchLibControl.LastBuildOutput;
            var    argLines    = buildArgs.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            var    dirCommon   = PathEx.GetCommonRoot(searchFiles);
            var    searchLines = searchFiles.Select(f => PathEx.RemovePrefix(f, dirCommon)).ToArray();

            Assert.IsTrue(ArrayUtil.EqualsDeep(searchLines, argLines.Skip(1).ToArray()), buildArgs);

            // Verify resulting .blib file contains the expected files
            var docLib                   = librarySettings.Libraries[0];
            int expectedFileCount        = searchFiles.Length;
            int expectedRedundantSpectra = 813; // 446 with TiTip only
            int expectedSpectra          = 552; // 428 with TiTip3 only

            if (expectedFileCount != docLib.FileCount)
            {
                var searchFileNames = searchFiles.Select(Path.GetFileName).ToArray();
                using (var blibDbRedundant = BlibDb.OpenBlibDb(redundantDocLibPath))
                {
                    VerifyLib(searchFileNames, expectedRedundantSpectra, blibDbRedundant.GetIdFilePaths(), blibDbRedundant.GetSpectraCount(),
                              "redunant library", buildArgs, buildOutput);
                }
                using (var blibDb = BlibDb.OpenBlibDb(docLibPath))
                {
                    VerifyLib(searchFileNames, expectedSpectra, blibDb.GetIdFilePaths(), blibDb.GetSpectraCount(),
                              "SQLite library", buildArgs, buildOutput);
                }
                VerifyLib(searchFileNames, expectedSpectra, docLib.LibraryDetails.DataFiles.Select(d => d.IdFilePath).ToArray(), docLib.SpectrumCount,
                          "in memory", buildArgs, buildOutput);
            }

            // We're on the "Extract Chromatograms" page of the wizard.
            // All the test results files are in the same directory as the
            // document file, so all the files should be found, and we should
            // just be able to move to the next page.
            WaitForConditionUI(() => importPeptideSearchDlg.CurrentPage == ImportPeptideSearchDlg.Pages.chromatograms_page &&
                               importPeptideSearchDlg.ImportResultsControl.FoundResultsFiles.Count > 0 &&
                               importPeptideSearchDlg.IsNextButtonEnabled);

            // Wait for extra for both source files in the list
            TryWaitForConditionUI(10 * 1000, () => importPeptideSearchDlg.ImportResultsControl.FoundResultsFiles.Count == searchFiles.Length);

            RunUI(() =>
            {
                // Check for missing files
                var missingFiles = importPeptideSearchDlg.ImportResultsControl.MissingResultsFiles.ToArray();
                Assert.AreEqual(0, missingFiles.Length,
                                PathsMessage("Unexpected missing file found.", missingFiles));
                // Check for expected results files
                var resultsNames = importPeptideSearchDlg.ImportResultsControl.FoundResultsFiles.Select(f => f.Name).ToArray();
                Assert.AreEqual(searchFiles.Length, importPeptideSearchDlg.ImportResultsControl.FoundResultsFiles.Count,
                                PathsMessage("Unexpected results files found.", resultsNames));
                // Check for expected common prefix
                var commonPrefix = ImportResultsDlg.GetCommonPrefix(resultsNames);
                Assert.IsFalse(string.IsNullOrEmpty(commonPrefix),
                               PathsMessage("File names do not have a common prefix.", resultsNames));
                Assert.AreEqual("100803_000", commonPrefix);
            });
            PauseForScreenShot <ImportPeptideSearchDlg.ChromatogramsPage>("Import Peptide Search - Extract Chromatograms page", 5);

            var importResultsNameDlg = ShowDialog <ImportResultsNameDlg>(() => importPeptideSearchDlg.ClickNextButton());

            PauseForScreenShot <ImportResultsNameDlg>("Import Results - Common prefix form", 6);

            OkDialog(importResultsNameDlg, importResultsNameDlg.YesDialog);

            // Wait for the "Add Modifications" page of the wizard.
            WaitForConditionUI(() => importPeptideSearchDlg.CurrentPage == ImportPeptideSearchDlg.Pages.match_modifications_page);

            List <string> modsToCheck = new List <string> {
                "Phospho (ST)", "Phospho (Y)", "Oxidation (M)"
            };                                                                                              // Not L10N

            RunUI(() =>
            {
                importPeptideSearchDlg.MatchModificationsControl.CheckedModifications = modsToCheck;
            });
            PauseForScreenShot <ImportPeptideSearchDlg.MatchModsPage>("Import Peptide Search - Add Modifications page", 7);
            RunUI(() => Assert.IsTrue(importPeptideSearchDlg.ClickNextButton()));

            // We're on the "Configure MS1 Full-Scan Settings" page of the wizard.
            RunUI(() =>
            {
                Assert.IsTrue(importPeptideSearchDlg.CurrentPage == ImportPeptideSearchDlg.Pages.full_scan_settings_page);
                importPeptideSearchDlg.FullScanSettingsControl.PrecursorCharges      = new[] { 2, 3, 4 };
                importPeptideSearchDlg.FullScanSettingsControl.PrecursorMassAnalyzer = FullScanMassAnalyzerType.tof;
                importPeptideSearchDlg.FullScanSettingsControl.PrecursorRes          = 10 * 1000;

                Assert.AreEqual(importPeptideSearchDlg.FullScanSettingsControl.PrecursorIsotopesCurrent, FullScanPrecursorIsotopes.Count);
                Assert.AreEqual(FullScanMassAnalyzerType.tof, importPeptideSearchDlg.FullScanSettingsControl.PrecursorMassAnalyzer);
                Assert.AreEqual(10 * 1000, importPeptideSearchDlg.FullScanSettingsControl.PrecursorRes);
                Assert.AreEqual(3, importPeptideSearchDlg.FullScanSettingsControl.Peaks);
                Assert.AreEqual(RetentionTimeFilterType.ms2_ids, importPeptideSearchDlg.FullScanSettingsControl.RetentionTimeFilterType);
                Assert.AreEqual(5, importPeptideSearchDlg.FullScanSettingsControl.TimeAroundMs2Ids);
            });
            PauseForScreenShot <ImportPeptideSearchDlg.Ms1FullScanPage>("Import Peptide Search - Configure MS1 Full-Scan Settings page", 8);

            RunUI(() => Assert.IsTrue(importPeptideSearchDlg.ClickNextButton()));

            // Last page of wizard - Import Fasta.
            string fastaPath = GetTestPath("12_proteins.062011.fasta");

            RunUI(() =>
            {
                Assert.IsTrue(importPeptideSearchDlg.CurrentPage == ImportPeptideSearchDlg.Pages.import_fasta_page);
                Assert.AreEqual("Trypsin [KR | P]", importPeptideSearchDlg.ImportFastaControl.Enzyme.GetKey());
                importPeptideSearchDlg.ImportFastaControl.MaxMissedCleavages = 2;
                importPeptideSearchDlg.ImportFastaControl.SetFastaContent(fastaPath);
                Assert.IsFalse(importPeptideSearchDlg.ImportFastaControl.DecoyGenerationEnabled);
            });
            PauseForScreenShot <ImportPeptideSearchDlg.FastaPage>("Import Peptide Search - Import FASTA page", 10);

            var peptidesPerProteinDlg = ShowDialog <PeptidesPerProteinDlg>(() => importPeptideSearchDlg.ClickNextButton());

            WaitForCondition(() => peptidesPerProteinDlg.DocumentFinalCalculated);
            RunUI(() =>
            {
                int proteinCount, peptideCount, precursorCount, transitionCount;
                peptidesPerProteinDlg.NewTargetsAll(out proteinCount, out peptideCount, out precursorCount, out transitionCount);
                Assert.AreEqual(11, proteinCount);
                Assert.AreEqual(51, peptideCount);
                Assert.AreEqual(52, precursorCount);
                Assert.AreEqual(156, transitionCount);
                peptidesPerProteinDlg.NewTargetsFinal(out proteinCount, out peptideCount, out precursorCount, out transitionCount);
                Assert.AreEqual(11, proteinCount);
                Assert.AreEqual(51, peptideCount);
                Assert.AreEqual(52, precursorCount);
                Assert.AreEqual(156, transitionCount);
            });
            OkDialog(peptidesPerProteinDlg, peptidesPerProteinDlg.OkDialog);
            PauseForScreenShot <AllChromatogramsGraph>("Loading chromatograms window", 11);
            WaitForDocumentChangeLoaded(doc, 8 * 60 * 1000); // 10 minutes

            var libraryExplorer   = ShowDialog <ViewLibraryDlg>(() => SkylineWindow.OpenLibraryExplorer(documentBaseName));
            var matchedPepModsDlg = WaitForOpenForm <AddModificationsDlg>();

            PauseForScreenShot <MultiButtonMsgDlg>("Add mods alert", 12);
            RunUI(() =>
            {
                Assert.AreEqual(13, matchedPepModsDlg.NumMatched);
                Assert.AreEqual(0, matchedPepModsDlg.NumUnmatched);
                matchedPepModsDlg.CancelDialog();
            });
            RunUI(() =>
            {
                libraryExplorer.GraphSettings.ShowBIons        = true;
                libraryExplorer.GraphSettings.ShowYIons        = true;
                libraryExplorer.GraphSettings.ShowCharge1      = true;
                libraryExplorer.GraphSettings.ShowCharge2      = true;
                libraryExplorer.GraphSettings.ShowPrecursorIon = true;
            });

            PauseForScreenShot <ViewLibraryDlg>("Spectral Library Explorer", 13);
            RunUI(() =>
            {
                const string sourceFirst = "100803_0005b_MCF7_TiTip3.wiff";
                const double timeFirst   = 35.2128;
                Assert.AreEqual(sourceFirst, libraryExplorer.SourceFile);
                Assert.AreEqual(timeFirst, libraryExplorer.RetentionTime, 0.0001);
                libraryExplorer.SelectedIndex++;
                Assert.AreNotEqual(sourceFirst, libraryExplorer.SourceFile);
                Assert.AreNotEqual(timeFirst, libraryExplorer.RetentionTime, 0.0001);
            });
            OkDialog(libraryExplorer, libraryExplorer.CancelDialog);

            const int TIB_L = 0; // index for Tib_L
            const int TIP3  = 1; // index for Tip3

            AssertEx.IsDocumentState(SkylineWindow.Document, null, 11, 51, 52, 156);
            AssertResult.IsDocumentResultsState(SkylineWindow.Document, GetFileNameWithoutExtension(searchFiles[TIB_L]), 51, 52, 0, 156, 0);
            AssertResult.IsDocumentResultsState(SkylineWindow.Document, GetFileNameWithoutExtension(searchFiles[TIP3]), 51, 52, 0, 156, 0);
            string Tib_LFilename = searchFiles[TIB_L].Replace(".group.xml", PreferedExtAbWiff);
            string Tip3Filename  = searchFiles[TIP3].Replace(".group.xml", PreferedExtAbWiff);

            // Select the first transition group.
            RunUI(() =>
            {
                SkylineWindow.SequenceTree.SelectedPath =
                    SkylineWindow.Document.GetPathTo((int)SrmDocument.Level.Molecules, 0);
                SkylineWindow.GraphSpectrumSettings.ShowAIons        = true;
                SkylineWindow.GraphSpectrumSettings.ShowBIons        = true;
                SkylineWindow.GraphSpectrumSettings.ShowYIons        = true;
                SkylineWindow.GraphSpectrumSettings.ShowPrecursorIon = true;
                SkylineWindow.ExpandPrecursors();
                SkylineWindow.ChangeTextSize(TreeViewMS.LRG_TEXT_FACTOR);
            });
            RunDlg <SpectrumChartPropertyDlg>(SkylineWindow.ShowSpectrumProperties, dlg =>
            {
                dlg.FontSize = GraphFontSize.NORMAL;
                dlg.OkDialog();
            });
            RunDlg <ChromChartPropertyDlg>(SkylineWindow.ShowChromatogramProperties, dlg =>
            {
                dlg.FontSize = GraphFontSize.NORMAL;
                dlg.OkDialog();
            });
            RunUI(() =>
            {
                // Make window screenshot size
                if (IsPauseForScreenShots && SkylineWindow.WindowState != FormWindowState.Maximized)
                {
                    SkylineWindow.Width  = 1160;
                    SkylineWindow.Height = 792;
                }
            });
            RestoreViewOnScreen(13);
            PauseForScreenShot("Main window with imported data", 14);

//            RunUIWithDocumentWait(() =>
//            {
//                SkylineWindow.ToggleIntegrateAll(); // TODO: No longer necessary.  Change in tutorial
//            });
            RunUI(() =>
            {
                SkylineWindow.ShowGraphPeakArea(true);
                SkylineWindow.ShowPeakAreaReplicateComparison();
                SkylineWindow.NormalizeAreaGraphTo(AreaNormalizeToView.none);
                Settings.Default.ShowDotProductPeakArea = true;
                Settings.Default.ShowLibraryPeakArea    = true;
            });
            PauseForScreenShot <GraphSummary.AreaGraphView>("Peak Areas view (show context menu)", 16);

            RestoreViewOnScreen(15);
            RunUI(() =>
            {
                SkylineWindow.AutoZoomBestPeak();
                SkylineWindow.ArrangeGraphsTiled();
                SkylineWindow.ShowChromatogramLegends(false);
            });
            PauseForScreenShot("Main window layout", 17);

            int atest = 0;

            CheckAnnotations(TIB_L, 0, atest++);
            int pepIndex = 3;

            RunUI(() => SkylineWindow.CollapsePeptides());
            RunUI(() => SkylineWindow.ShowAlignedPeptideIDTimes(true));
            ChangePeakBounds(TIB_L, pepIndex, 38.79, 39.385);
            PauseForScreenShot("Chromatogram graphs clipped from main window", 19);
            CheckAnnotations(TIB_L, pepIndex, atest++);

            var alignmentForm = ShowDialog <AlignmentForm>(() => SkylineWindow.ShowRetentionTimeAlignmentForm());

            RunUI(() =>
            {
                alignmentForm.Width  = 711;
                alignmentForm.Height = 561;
                alignmentForm.ComboAlignAgainst.SelectedIndex = 0;     // to match what's in the tutorial doc
            });
            PauseForScreenShot <AlignmentForm>("Retention time alignment form", 20);

            OkDialog(alignmentForm, alignmentForm.Close);
            PauseForScreenShot("Status bar clipped from main window - 4/51 pep 4/52 prec 10/156 tran", 21);

            pepIndex = JumpToPeptide("SSKASLGSLEGEAEAEASSPK");
            RunUI(() => SkylineWindow.ShowChromatogramLegends(true));
            Assert.IsTrue(8 == pepIndex);
            PauseForScreenShot("Chromatogram graph metafiles for 9th peptide", 21);
            CheckAnnotations(TIB_L, pepIndex, atest++);

            ZoomSingle(TIP3, 32.6, 41.4); // simulate the wheel scroll described in tutorial
            PauseForScreenShot("Chromatogram graph metafile showing all peaks for 1_MCF_TiB_L", 22);
            CheckAnnotations(TIB_L, pepIndex, atest++);

            // current TIB_L peak should have idotp .87 and ppm -6.9
            Assert.AreEqual(0.87, GetTransitionGroupChromInfo(TIB_L, pepIndex).IsotopeDotProduct ?? -1, .005);
            Assert.AreEqual(-10.8, GetTransitionChromInfo(TIB_L, pepIndex, 0).MassError ?? -1, .05);

            ChangePeakBounds(TIB_L, pepIndex, 36.5, 38.0);

            // now current TIB_L peak should have idotp .9 and ppm -6.5
            Assert.AreEqual(0.9, GetTransitionGroupChromInfo(TIB_L, pepIndex).IsotopeDotProduct ?? -1, .005);
            Assert.AreEqual(-9.4, GetTransitionChromInfo(TIB_L, pepIndex, 0).MassError ?? -1, .05);
            CheckAnnotations(TIB_L, pepIndex, atest++);

            var undoIndex = SkylineWindow.Document.RevisionIndex; // preserve for simulating ctrl-z

            PickPeakBoth(pepIndex, 40.471035, 40.8134);           // select peak for both chromatograms at these respective retention times
            PauseForScreenShot <GraphSummary.AreaGraphView>("Peak Areas graph metafile", 23);

            int[] m1Thru4 = { 1, 2, 3, 4, 5 };
            PickTransitions(pepIndex, m1Thru4, "Transition pick list filtered", 24, "Transition pick list unfiltered", 24); // turn on chromatograms
            PickPeakBoth(pepIndex, 36.992836, 37.3896027);                                                                  // select peak for both chromatograms at these respective retention times
            ZoomSingle(TIP3, 32.4, 39.6);                                                                                   // set the view for screenshot
            PauseForScreenShot("Chromatogram graph metafile comparing 33 and 37 minute peaks", 25);
            CheckAnnotations(TIB_L, pepIndex, atest++);
            CheckAnnotations(TIP3, pepIndex, atest++);

            RevertDoc(undoIndex);                             // undo changes
            pepIndex = JumpToPeptide("ASLGSLEGEAEAEASSPKGK"); // Not L10N
            Assert.IsTrue(10 == pepIndex);
            PauseForScreenShot("Chhromatogram graph meta files for peptide ASLGSLEGEAEAEASSPKGK", 26);
            CheckAnnotations(TIB_L, pepIndex, atest++);
            CheckAnnotations(TIP3, pepIndex, atest++);

            PickTransitions(pepIndex, m1Thru4); // turn on M+3 and M+4
            ChangePeakBounds(TIP3, pepIndex, 37.35, 38.08);
            ZoomSingle(TIP3, 36.65, 39.11);     // simulate the wheel scroll described in tutorial
            PauseForScreenShot("upper - Chromatogram graph metafile for peptide ASLGSLEGEAEAEASSPKGK with adjusted integration", 27);
            CheckAnnotations(TIP3, pepIndex, atest++);

            RevertDoc(undoIndex);                              // undo changes
            pepIndex = JumpToPeptide("AEGEWEDQEALDYFSDKESGK"); // Not L10N
            PauseForScreenShot("lower - Chromatogram graph metafiles for peptide AEGEWEDQEALDYFSDKESGK", 27);
            CheckAnnotations(TIB_L, pepIndex, atest++);
            CheckAnnotations(TIP3, pepIndex, atest++);

            int[] m1Thru5 = { 1, 2, 3, 4, 5, 6 };
            PickTransitions(pepIndex, m1Thru5); // turn on M+3 M+4 and M+5
            PauseForScreenShot("Chromatogram graph metafiles with M+3, M+4 and M+5 added", 28);
            CheckAnnotations(TIB_L, pepIndex, atest++);
            CheckAnnotations(TIP3, pepIndex, atest++);

            JumpToPeptide("ALVEFESNPEETREPGSPPSVQR"); // Not L10N
            PauseForScreenShot("Chromatogram graph metafiles for peptide ALVEFESNPEETREPGSPPSVQR", 29);

            pepIndex = JumpToPeptide("YGPADVEDTTGSGATDSKDDDDIDLFGSDDEEESEEAKR"); // Not L10N
            PauseForScreenShot("upper - Peak Areas graph metafile for peptide YGPADVEDTTGSGATDSKDDDDIDLFGSDDEEESEEAKR", 30);

            int[] m1Thru7 = { 1, 2, 3, 4, 5, 6, 7, 8 };
            PickTransitions(pepIndex, m1Thru7); // enable [M+3] [M+4] [M+5] [M+6] [M+7]
            PauseForScreenShot("lower - Peak Areas graph metafile with M+3 through M+7 added", 30);
            CheckAnnotations(TIB_L, pepIndex, atest++);
            CheckAnnotations(TIP3, pepIndex, atest++);

            // page 32 zooming setup
            RunUI(() =>
            {
                SkylineWindow.SynchronizeZooming(true);
                SkylineWindow.LockYChrom(false);
                SkylineWindow.AlignToFile = GetGraphChromatogram(TIP3).GetChromFileInfoId(); // align to Tip3
            });
            ZoomBoth(36.5, 39.5, 1600);                                                      // simulate the wheel scroll described in tutorial
            RunUI(() => SkylineWindow.ShowChromatogramLegends(false));
            PauseForScreenShot("Chromatogram graphs clipped from main window with synchronized zooming", 32);

            RestoreViewOnScreen(33);                                                                                                      // float the  Library Match window TODO this causes a crash at next call to ChangePeakBounds, in pwiz.Skyline.Controls.Graphs.GraphChromatogram.ChromGroupInfos.get() Line 492 , why?
            RunUI(() => SkylineWindow.GraphSpectrum.SelectSpectrum(new SpectrumIdentifier(MsDataFileUri.Parse(Tip3Filename), 37.6076f))); // set the Library Match view
            PauseForScreenShot <GraphSpectrum>("Library Match graph metafile - 5b_MCF7_TiTip3 (37.61 Min)", 33);

            RunUI(() => SkylineWindow.GraphSpectrum.SelectSpectrum(new SpectrumIdentifier(MsDataFileUri.Parse(Tib_LFilename), 37.0335f))); // set the Library Match view
            PauseForScreenShot <GraphSpectrum>("Library Match graph metafile - 1_MCF_TiB_L (37.03 min)", 33);

            RestoreViewOnScreen(34);                    // back to normal view

            pepIndex = JumpToPeptide("GVVDSEDLPLNISR"); // Not L10N
            RunUI(() => SkylineWindow.ShowChromatogramLegends(true));
            PauseForScreenShot("upper - Chromatogram graph metafiles for peptide GVVDSEDLPLNISR", 34);

            ZoomBoth(35.05, 36.9, 480);
            PauseForScreenShot("lower - Chromatogram graph metafile - effect of zoom ", 34);
            ChangePeakBounds(TIP3, pepIndex, 35.7, 36.5);  // adjust integration per tutorial
            CheckAnnotations(TIP3, pepIndex, atest++);     // check the new idotp values

            /* pepIndex = */ JumpToPeptide("DQVANSAFVER"); // Not L10N
            PauseForScreenShot("Chromatogram graph metafiles for peptide DQVANSAFVER", 35);

//            int[] m1 = {2};
//            PickTransitions(pepIndex, m1); // enable [M+1] only
//            // Measured times in TIB_L are different from displayed times, because of alignment
//            ChangePeakBounds(TIB_L, pepIndex, 23.99, 25.29);
//            ChangePeakBounds(TIP3, pepIndex, 23.81, 25.21);
//            // First transition selected for screenshot
//            RunUI(() =>
//            {
//                var pathPep = SkylineWindow.SelectedPath;
//                var nodePep = ((PeptideTreeNode)SkylineWindow.SelectedNode).DocNode;
//                var nodeGroup = nodePep.TransitionGroups.First();
//                var nodeTran = nodeGroup.Transitions.First();
//                SkylineWindow.SelectedPath = new IdentityPath(
//                    new IdentityPath(pathPep, nodeGroup.TransitionGroup), nodeTran.Transition);
//            });
//            PauseForScreenShot("page 36 - M+1 only, with adjusted integration");
//            CheckAnnotations(TIB_L, pepIndex, atest++);
//            CheckAnnotations(TIP3, pepIndex, EXPECTED_ANNOTATIONS[atest]);

            var docAfter = WaitForProteinMetadataBackgroundLoaderCompletedUI();

            // Minimizing a chromatogram cache file.
            RunUI(SkylineWindow.CollapsePeptides);
            for (int i = 0; i < 5; i++) // just do the first 5
            {
                int iPeptide = i;
                var path     = docAfter.GetPathTo((int)SrmDocument.Level.Molecules, iPeptide);
                RunUI(() =>
                {
                    SkylineWindow.SelectedPath = path;
                });
                WaitForGraphs();
            }

            // Eliminate extraneous chromatogram data.
            doc = WaitForProteinMetadataBackgroundLoaderCompletedUI();
            var minimizedFile = GetTestPath("Ms1FilteringTutorial-2min.sky"); // Not L10N
            var cacheFile     = Path.ChangeExtension(minimizedFile, ChromatogramCache.EXT);

            {
                // TODO: Figure out why the minimize fails to unlock the .skyd file, if not minimized to current file
                RunUI(() => SkylineWindow.SaveDocument(minimizedFile));

                var manageResultsDlg   = ShowDialog <ManageResultsDlg>(SkylineWindow.ManageResults);
                var minimizeResultsDlg = ShowDialog <MinimizeResultsDlg>(manageResultsDlg.MinimizeResults);
                RunUI(() =>
                {
                    minimizeResultsDlg.LimitNoiseTime = true;
                    minimizeResultsDlg.NoiseTimeRange = 2;                                                        // Not L10N
                });
                PauseForScreenShot <MinimizeResultsDlg>("Minimize Results form (percentages vary slightly)", 36); // old p. 23

                OkDialog(minimizeResultsDlg, () => minimizeResultsDlg.MinimizeToFile(minimizedFile));
                WaitForCondition(() => File.Exists(cacheFile));
                WaitForClosedForm(manageResultsDlg);
            }
            WaitForDocumentChange(doc);

            // Inclusion list method export for MS1 filtering
            doc = SkylineWindow.Document;
            RunDlg <PeptideSettingsUI>(() => SkylineWindow.ShowPeptideSettingsUI(PeptideSettingsUI.TABS.Prediction), dlg =>
            {
                dlg.IsUseMeasuredRT = true;
                dlg.TimeWindow      = 10;
                dlg.OkDialog();
            });
            doc = WaitForDocumentChangeLoaded(doc);

            // Now deviating from the tutorial script for a moment to make sure we can choose a Scheduled export method.
            // CONSIDER: This refinement seems to be a no-op. Not sure why it is here.
            RunDlg <RefineDlg>(SkylineWindow.ShowRefineDlg, dlg =>
            {
                dlg.MinPeptides = 1;                                // This would get rid of proteins with no peptides (none exist)
                const double minPeakFoundRatio = 0.1;
                dlg.MinPeakFoundRatio          = minPeakFoundRatio; // This would get rid of undetected transitions (none exist)
                dlg.OkDialog();                                     // Will not change the document or add an Undo entry
            });
            // Nothing should have changed on the UI thread
            RunUI(() => Assert.AreSame(doc, SkylineWindow.DocumentUI));

            // Ready to export, although we will just cancel out of the dialog.
            var exportMethodDlg = ShowDialog <ExportMethodDlg>(() => SkylineWindow.ShowExportMethodDialog(ExportFileType.Method));

            RunUI(() =>
            {
                exportMethodDlg.InstrumentType = ExportInstrumentType.ABI_TOF; // Not L10N
                exportMethodDlg.MethodType     = ExportMethodType.Scheduled;
                exportMethodDlg.CancelButton.PerformClick();
            });
            WaitForClosedForm(exportMethodDlg);

            // Because this was showing up in the nightly test failures
            WaitForConditionUI(() => exportMethodDlg.IsDisposed);

            RunUI(() => SkylineWindow.SaveDocument());
            RunUI(SkylineWindow.NewDocument);
        }