Example #1
0
        public bool Initialize(SrmDocument document)
        {
            if (!ImportPeptideSearch.HasDocLib)
            {
                return(false);
            }

            ImportPeptideSearch.InitializeModifications(document);
            FillLists(document);
            return(modificationsListBox.Items.Count > 1 || unmatchedListBox.Items.Count > 1);
        }
        public SrmSettings AddCheckedModifications(SrmDocument document)
        {
            var firstHeavyModificationType = document.Settings.PeptideSettings.Modifications
                                             .GetHeavyModificationTypes().FirstOrDefault();

            // in the non-DDA case, AddCheckedModifications is only additive, so no checked items is a no-op
            if (modificationsListBox.CheckedItems.Count == 0)
            {
                if (!ImportPeptideSearch.IsDDASearch)
                {
                    return(document.Settings);
                }
                else
                {
                    // in DDA-case, return empty mod lists
                    var emptyPeptideMods = document.Settings.PeptideSettings.Modifications
                                           .ChangeStaticModifications(new List <StaticMod>());
                    emptyPeptideMods = emptyPeptideMods.ChangeModifications(firstHeavyModificationType, new List <StaticMod>());
                    return(ImportPeptideSearch.AddModifications(document, emptyPeptideMods));
                }
            }
            // Find checked mods
            List <StaticMod> structuralMods;
            List <StaticMod> heavyMods;

            if (ImportPeptideSearch.IsDDASearch)
            {
                var selectedMods = modificationsListBox.CheckedItems.Cast <ListBoxModification>().Select(o => o.Mod).ToList();
                structuralMods = selectedMods.Where(o => o.LabelAtoms == LabelAtoms.None).ToList();
                heavyMods      = selectedMods.Where(o => o.LabelAtoms != LabelAtoms.None).ToList();
            }
            else
            {
                structuralMods = (from mod in ImportPeptideSearch.MatcherPepMods.StaticModifications
                                  from ListBoxModification checkedMod in modificationsListBox.CheckedItems
                                  where mod.Equivalent(checkedMod.Mod)
                                  select mod).ToList();

                // Find checked heavy mods
                heavyMods = (from mod in ImportPeptideSearch.MatcherHeavyMods
                             from ListBoxModification checkedMod in modificationsListBox.CheckedItems
                             where mod.Equivalent(checkedMod.Mod)
                             select mod).ToList();
            }

            // Update document modifications
            var newPeptideMods = document.Settings.PeptideSettings.Modifications.ChangeStaticModifications(structuralMods);

            newPeptideMods = newPeptideMods.ChangeModifications(firstHeavyModificationType, heavyMods);
            return(ImportPeptideSearch.AddModifications(document, newPeptideMods));
        }
        public BuildPeptideSearchLibraryControl(SkylineWindow skylineWindow, ImportPeptideSearch importPeptideSearch, LibraryManager libraryManager)
        {
            SkylineWindow       = skylineWindow;
            ImportPeptideSearch = importPeptideSearch;
            LibraryManager      = libraryManager;

            InitializeComponent();

            textCutoff.Text = ImportPeptideSearch.CutoffScore.ToString(LocalizationHelper.CurrentCulture);

            if (SkylineWindow.Document.PeptideCount == 0)
            {
                cbFilterForDocumentPeptides.Hide();
            }
        }
        private void FillLists(SrmDocument document)
        {
            IList <StaticMod> modsToAdd, modsToCheck;

            if (ImportPeptideSearch.IsDDASearch)
            {
                modsToAdd = Settings.Default.StaticModList.ToList();
                modsToAdd.AddRange(Settings.Default.HeavyModList.Distinct());
                modsToCheck = document.Settings.PeptideSettings.Modifications.StaticModifications.ToList();
                modsToCheck.AddRange(document.Settings.PeptideSettings.Modifications.AllHeavyModifications.Distinct());
                //modsToAdd = ImportPeptideSearch.UserDefinedTypedMods;
            }
            else
            {
                ImportPeptideSearch.UpdateModificationMatches(document);
                modsToAdd   = ImportPeptideSearch.GetMatchedMods().ToList();
                modsToCheck = new List <StaticMod>(); // don't check any mods
            }

            modificationsListBox.Items.Clear();
            unmatchedListBox.Items.Clear();

            foreach (var match in modsToAdd)
            {
                modificationsListBox.Items.Add(new ListBoxModification(match, ImportPeptideSearch.IsDDASearch), modsToCheck.Contains(match));
            }

            var unmatched = ImportPeptideSearch.GetUnmatchedSequences();

            if (unmatched != null && unmatched.Any())
            {
                splitContainer.Panel2Collapsed = false;
                foreach (var uninterpretedMod in unmatched)
                {
                    unmatchedListBox.Items.Add(uninterpretedMod);
                }
            }
            else
            {
                splitContainer.Panel2Collapsed = true;
            }
            if (modificationsListBox.Items.Count <= 3)
            {
                cbSelectAll.Visible          = false;
                modificationsListBox.Height += cbSelectAll.Bottom - modificationsListBox.Bottom;
            }
        }
        public BuildPeptideSearchLibraryControl(IModifyDocumentContainer documentContainer, ImportPeptideSearch importPeptideSearch, LibraryManager libraryManager)
        {
            DocumentContainer   = documentContainer;
            ImportPeptideSearch = importPeptideSearch;
            LibraryManager      = libraryManager;

            InitializeComponent();

            textCutoff.Text = ImportPeptideSearch.CutoffScore.ToString(LocalizationHelper.CurrentCulture);

            if (DocumentContainer.Document.PeptideCount == 0)
            {
                cbFilterForDocumentPeptides.Hide();
            }

            _driverStandards = new SettingsListComboDriver <IrtStandard>(comboStandards, Settings.Default.IrtStandardList);
            _driverStandards.LoadList(IrtStandard.EMPTY.GetKey());
        }
        public bool Initialize(SrmDocument document)
        {
            Document = document;

            if (!ImportPeptideSearch.HasDocLib && !ImportPeptideSearch.IsDDASearch)
            {
                return(false);
            }
            if (ImportPeptideSearch.IsDDASearch)
            {
                labelModifications.Text = Resources.MatchModificationsControl_ModificationLabelText_DDA_Search;
                btnAddModification.Text = Resources.MatchModificationsControl_Initialize__Edit_modifications;
                menuItemAddStructuralModification.Text = Resources.MatchModificationsControl_Initialize_Edit__structural_modifications___;
                menuItemAddHeavyModification.Text      = Resources.MatchModificationsControl_Initialize_Edit__heavy_modifications___;
            }

            ImportPeptideSearch.InitializeModifications(document);
            FillLists(document);
            return(modificationsListBox.Items.Count > 1 || unmatchedListBox.Items.Count > 1);
        }
        public BuildPeptideSearchLibraryControl(IModifyDocumentContainer documentContainer, ImportPeptideSearch importPeptideSearch, LibraryManager libraryManager)
        {
            DocumentContainer   = documentContainer;
            ImportPeptideSearch = importPeptideSearch;
            LibraryManager      = libraryManager;

            InitializeComponent();

            textCutoff.Text = ImportPeptideSearch.CutoffScore.ToString(LocalizationHelper.CurrentCulture);

            if (DocumentContainer.Document.PeptideCount == 0)
            {
                cbFilterForDocumentPeptides.Hide();
            }

            foreach (var standard in IrtStandard.ALL)
            {
                comboStandards.Items.Add(standard);
            }
        }
        public SrmSettings AddCheckedModifications(SrmDocument document)
        {
            if (modificationsListBox.CheckedItems.Count == 0)
            {
                return(document.Settings);
            }

            // Find checked static mods
            var newStructuralMods = (from mod in ImportPeptideSearch.MatcherPepMods.StaticModifications
                                     from ListBoxModification checkedMod in modificationsListBox.CheckedItems
                                     where mod.Equivalent(checkedMod.Mod)
                                     select mod).ToList();

            // Find checked heavy mods
            var newHeavyMods = (from mod in ImportPeptideSearch.MatcherHeavyMods
                                from ListBoxModification checkedMod in modificationsListBox.CheckedItems
                                where mod.Equivalent(checkedMod.Mod)
                                select mod).ToList();

            // Update document modifications
            return(ImportPeptideSearch.AddModifications(document,
                                                        new PeptideModifications(newStructuralMods, new[] { new TypedModifications(IsotopeLabelType.heavy, newHeavyMods) })));
        }
        public bool UpdateResultsFiles(IEnumerable <string> dirPaths, bool overwrite)
        {
            using (var longWaitDlg = new LongWaitDlg
            {
                Text = Resources.ImportResultsControl_FindResultsFiles_Searching_for_Results_Files
            })
            {
                try
                {
                    longWaitDlg.PerformWork(WizardForm, 1000, longWaitBroker =>
                                            ImportPeptideSearch.UpdateSpectrumSourceFilesFromDirs(dirPaths, overwrite, longWaitBroker));
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(WizardForm, TextUtil.LineSeparate(
                                                     Resources.ImportResultsControl_FindResultsFiles_An_error_occurred_attempting_to_find_results_files_,
                                                     x.Message), x);
                }
            }

            UpdateResultsFilesUI();

            return(!MissingResultsFiles.Any());
        }
Example #10
0
        public bool BuildPeptideSearchLibrary(CancelEventArgs e)
        {
            // Nothing to build, if now search files were specified
            if (!SearchFilenames.Any())
            {
                var libraries = SkylineWindow.Document.Settings.PeptideSettings.Libraries;
                if (!libraries.HasLibraries)
                {
                    return(false);
                }
                var libSpec = libraries.LibrarySpecs.FirstOrDefault(s => s.IsDocumentLibrary);
                return(libSpec != null && LoadPeptideSearchLibrary(libSpec));
            }

            double           cutOffScore;
            MessageBoxHelper helper = new MessageBoxHelper(WizardForm);

            if (!helper.ValidateDecimalTextBox(textCutoff, 0, 1.0, out cutOffScore))
            {
                e.Cancel = true;
                return(false);
            }
            ImportPeptideSearch.CutoffScore = cutOffScore;

            BiblioSpecLiteBuilder builder;

            try
            {
                builder = ImportPeptideSearch.GetLibBuilder(SkylineWindow.Document, SkylineWindow.DocumentFilePath, cbIncludeAmbiguousMatches.Checked);
            }
            catch (FileEx.DeleteException de)
            {
                MessageDlg.ShowException(this, de);
                return(false);
            }

            using (var longWaitDlg = new LongWaitDlg
            {
                Text = Resources.BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Building_Peptide_Search_Library,
                Message = Resources.BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Building_document_library_for_peptide_search_,
            })
            {
                // Disable the wizard, because the LongWaitDlg does not
                try
                {
                    ImportPeptideSearch.ClosePeptideSearchLibraryStreams(SkylineWindow.DocumentUI);
                    var status = longWaitDlg.PerformWork(WizardForm, 800,
                                                         monitor => LibraryManager.BuildLibraryBackground(SkylineWindow, builder, monitor, new LibraryManager.BuildState(null, null)));
                    if (status.IsError)
                    {
                        MessageDlg.ShowException(WizardForm, status.ErrorException);
                        return(false);
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(WizardForm, TextUtil.LineSeparate(string.Format(Resources.BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Failed_to_build_the_library__0__,
                                                                                                 Path.GetFileName(BiblioSpecLiteSpec.GetLibraryFileName(SkylineWindow.DocumentFilePath))), x.Message), x);
                    return(false);
                }
            }

            var docLibSpec = builder.LibrarySpec.ChangeDocumentLibrary(true);

            Settings.Default.SpectralLibraryList.Insert(0, docLibSpec);

            // Go ahead and load the library - we'll need it for
            // the modifications and chromatograms page.
            if (!LoadPeptideSearchLibrary(docLibSpec))
            {
                return(false);
            }

            var selectedIrtStandard = comboStandards.SelectedItem as IrtStandard;
            var addedIrts           = false;

            if (selectedIrtStandard != null && selectedIrtStandard != IrtStandard.NULL)
            {
                addedIrts = AddIrtLibraryTable(docLibSpec.FilePath, selectedIrtStandard);
            }

            var docNew = ImportPeptideSearch.AddDocumentSpectralLibrary(SkylineWindow.Document, docLibSpec);

            if (docNew == null)
            {
                return(false);
            }

            if (addedIrts)
            {
                docNew = ImportPeptideSearch.AddRetentionTimePredictor(docNew, docLibSpec);
            }

            SkylineWindow.ModifyDocument(Resources.BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Add_document_spectral_library, doc => docNew);

            if (!string.IsNullOrEmpty(builder.AmbiguousMatchesMessage))
            {
                MessageDlg.Show(WizardForm, builder.AmbiguousMatchesMessage);
            }
            return(true);
        }
Example #11
0
        public bool ImportFasta()
        {
            var settings        = SkylineWindow.Document.Settings;
            var peptideSettings = settings.PeptideSettings;
            int missedCleavages = MaxMissedCleavages;
            var enzyme          = Enzyme;

            if (!Equals(missedCleavages, peptideSettings.DigestSettings.MaxMissedCleavages) || !Equals(enzyme, peptideSettings.Enzyme))
            {
                var digest = new DigestSettings(missedCleavages, peptideSettings.DigestSettings.ExcludeRaggedEnds);
                peptideSettings = peptideSettings.ChangeDigestSettings(digest).ChangeEnzyme(enzyme);
                SkylineWindow.ModifyDocument(string.Format(Resources.ImportFastaControl_ImportFasta_Change_digestion_settings), doc =>
                                             doc.ChangeSettings(settings.ChangePeptideSettings(peptideSettings)));
            }

            if (!ContainsFastaContent) // The user didn't specify any FASTA content
            {
                var docCurrent = SkylineWindow.DocumentUI;
                // If the document has precursor transitions already, then just trust the user
                // knows what they are doing, and this document is already set up for MS1 filtering
                if (HasPrecursorTransitions(docCurrent))
                {
                    return(true);
                }

                if (docCurrent.PeptideCount == 0)
                {
                    MessageDlg.Show(WizardForm, TextUtil.LineSeparate(Resources.ImportFastaControl_ImportFasta_The_document_does_not_contain_any_peptides_,
                                                                      Resources.ImportFastaControl_ImportFasta_Please_import_FASTA_to_add_peptides_to_the_document_));
                    return(false);
                }

                if (MessageBox.Show(WizardForm, TextUtil.LineSeparate(Resources.ImportFastaControl_ImportFasta_The_document_does_not_contain_any_precursor_transitions_,
                                                                      Resources.ImportFastaControl_ImportFasta_Would_you_like_to_change_the_document_settings_to_automatically_pick_the_precursor_transitions_specified_in_the_full_scan_settings_),
                                    Program.Name, MessageBoxButtons.OKCancel) != DialogResult.OK)
                {
                    return(false);
                }

                SkylineWindow.ModifyDocument(Resources.ImportFastaControl_ImportFasta_Change_settings_to_add_precursors, doc => ImportPeptideSearch.ChangeAutoManageChildren(doc, PickLevel.transitions, true));
            }
            else // The user specified some FASTA content
            {
                // If the user is about to add any new transitions by importing
                // FASTA, set FragmentType='p' and AutoSelect=true
                var docCurrent = SkylineWindow.Document;
                var docNew     = ImportPeptideSearch.PrepareImportFasta(docCurrent);

                var          nodeInsert         = SkylineWindow.SequenceTree.SelectedNode as SrmTreeNode;
                IdentityPath selectedPath       = nodeInsert != null ? nodeInsert.Path : null;
                int          emptyPeptideGroups = 0;

                if (!_fastaFile)
                {
                    // Import FASTA as content
                    docNew = ImportFastaHelper.AddFasta(docNew, ref selectedPath, out emptyPeptideGroups);
                    // Document will be null if there was an error
                    if (docNew == null)
                    {
                        return(false);
                    }
                }
                else
                {
                    // Import FASTA as file
                    var fastaPath = tbxFasta.Text;
                    try
                    {
                        using (var longWaitDlg = new LongWaitDlg(SkylineWindow)
                        {
                            Text = Resources.ImportFastaControl_ImportFasta_Insert_FASTA
                        })
                        {
                            IdentityPath to             = selectedPath;
                            var          docImportFasta = docNew;
                            longWaitDlg.PerformWork(WizardForm, 1000, longWaitBroker =>
                            {
                                IdentityPath nextAdd;
                                docImportFasta = ImportPeptideSearch.ImportFasta(docImportFasta, fastaPath,
                                                                                 longWaitBroker, to, out selectedPath, out nextAdd, out emptyPeptideGroups);
                            });
                            docNew = docImportFasta;
                        }
                    }
                    catch (Exception x)
                    {
                        MessageDlg.ShowWithException(this, string.Format(Resources.SkylineWindow_ImportFastaFile_Failed_reading_the_file__0__1__,
                                                                         fastaPath, x.Message), x);
                        return(false);
                    }
                }

                // Check for empty proteins
                docNew = ImportFastaHelper.HandleEmptyPeptideGroups(WizardForm, emptyPeptideGroups, docNew);
                // Document will be null if user was given option to keep or remove empty proteins and pressed cancel
                if (docNew == null)
                {
                    return(false);
                }

                SkylineWindow.ModifyDocument(Resources.ImportFastaControl_ImportFasta_Insert_FASTA, doc =>
                {
                    if (!ReferenceEquals(doc, docCurrent))
                    {
                        throw new InvalidDataException(Resources.SkylineWindow_ImportFasta_Unexpected_document_change_during_operation);
                    }
                    return(docNew);
                });

                if (!VerifyAtLeastOnePrecursorTransition(SkylineWindow.Document))
                {
                    return(false);
                }
            }

            return(true);
        }
Example #12
0
 public void CloseWizard(DialogResult result)
 {
     // Close file handles to the peptide search library
     ImportPeptideSearch.ClosePeptideSearchLibraryStreams(Document);
     DialogResult = result;
 }
Example #13
0
        public ImportPeptideSearchDlg(SkylineWindow skylineWindow, LibraryManager libraryManager)
        {
            SkylineWindow = skylineWindow;
            _documents    = new Stack <SrmDocument>();
            SetDocument(skylineWindow.Document, null);

            ImportPeptideSearch = new ImportPeptideSearch();

            InitializeComponent();

            Icon = Resources.Skyline;

            btnEarlyFinish.Location = btnBack.Location;

            CurrentPage     = Pages.spectra_page;
            btnNext.Text    = Resources.ImportPeptideSearchDlg_ImportPeptideSearchDlg_Next;
            AcceptButton    = btnNext;
            btnNext.Enabled = HasUnmatchedLibraryRuns(Document);

            // Create and add wizard pages
            BuildPepSearchLibControl = new BuildPeptideSearchLibraryControl(this, ImportPeptideSearch, libraryManager)
            {
                Anchor   = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right,
                Location = new Point(2, 50)
            };
            BuildPepSearchLibControl.InputFilesChanged += BuildPepSearchLibForm_OnInputFilesChanged;
            buildSearchSpecLibPage.Controls.Add(BuildPepSearchLibControl);

            ImportFastaControl = new ImportFastaControl(this, SkylineWindow.SequenceTree)
            {
                Anchor   = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right,
                Location = new Point(2, 60)
            };
            importFastaPage.Controls.Add(ImportFastaControl);

            MatchModificationsControl = new MatchModificationsControl(this, ImportPeptideSearch)
            {
                Anchor   = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right,
                Location = new Point(2, 60)
            };
            matchModificationsPage.Controls.Add(MatchModificationsControl);

            TransitionSettingsControl = new TransitionSettingsControl(this)
            {
                Anchor   = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right,
                Location = new Point(18, 60)
            };
            transitionSettingsUiPage.Controls.Add(TransitionSettingsControl);

            FullScanSettingsControl = new FullScanSettingsControl(this)
            {
                Anchor   = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right,
                Location = new Point(18, 50)
            };
            ms1FullScanSettingsPage.Controls.Add(FullScanSettingsControl);

            ImportResultsControl = new ImportResultsControl(ImportPeptideSearch, DocumentFilePath)
            {
                Anchor   = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right,
                Location = new Point(2, 60)
            };
            getChromatogramsPage.Controls.Add((Control)ImportResultsControl);

            _pagesToSkip = new HashSet <Pages>();
        }
Example #14
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();
        }
 public void InitializeChromatogramsPage(SrmDocument document)
 {
     ImportPeptideSearch.InitializeSpectrumSourceFiles(document);
     UpdateResultsFiles(ImportPeptideSearch.GetDirsToSearch(DocumentDirectory), false);
 }
Example #16
0
        public bool ImportFasta()
        {
            var settings        = SkylineWindow.Document.Settings;
            var peptideSettings = settings.PeptideSettings;
            int missedCleavages = MaxMissedCleavages;
            var enzyme          = Enzyme;

            if (!Equals(missedCleavages, peptideSettings.DigestSettings.MaxMissedCleavages) || !Equals(enzyme, peptideSettings.Enzyme))
            {
                var digest = new DigestSettings(missedCleavages, peptideSettings.DigestSettings.ExcludeRaggedEnds);
                peptideSettings = peptideSettings.ChangeDigestSettings(digest).ChangeEnzyme(enzyme);
                SkylineWindow.ModifyDocument(string.Format(Resources.ImportFastaControl_ImportFasta_Change_digestion_settings), doc =>
                                             doc.ChangeSettings(settings.ChangePeptideSettings(peptideSettings)));
            }

            if (!string.IsNullOrEmpty(DecoyGenerationMethod))
            {
                if (!NumDecoys.HasValue || NumDecoys < 0)
                {
                    MessageDlg.Show(WizardForm, Resources.ImportFastaControl_ImportFasta_Please_enter_a_valid_non_negative_number_of_decoys_per_target_);
                    txtNumDecoys.Focus();
                    return(false);
                }
                else if (Equals(DecoyGenerationMethod, DecoyGeneration.REVERSE_SEQUENCE) && NumDecoys > 1)
                {
                    MessageDlg.Show(WizardForm, Resources.ImportFastaControl_ImportFasta_A_maximum_of_one_decoy_per_target_may_be_generated_when_using_reversed_decoys_);
                    txtNumDecoys.Focus();
                    return(false);
                }
            }

            if (!ContainsFastaContent) // The user didn't specify any FASTA content
            {
                var docCurrent = SkylineWindow.DocumentUI;
                // If the document has precursor transitions already, then just trust the user
                // knows what they are doing, and this document is already set up for MS1 filtering
                if (HasPrecursorTransitions(docCurrent))
                {
                    return(true);
                }

                if (docCurrent.PeptideCount == 0)
                {
                    MessageDlg.Show(WizardForm, TextUtil.LineSeparate(Resources.ImportFastaControl_ImportFasta_The_document_does_not_contain_any_peptides_,
                                                                      Resources.ImportFastaControl_ImportFasta_Please_import_FASTA_to_add_peptides_to_the_document_));
                    return(false);
                }

                if (MessageBox.Show(WizardForm, TextUtil.LineSeparate(Resources.ImportFastaControl_ImportFasta_The_document_does_not_contain_any_precursor_transitions_,
                                                                      Resources.ImportFastaControl_ImportFasta_Would_you_like_to_change_the_document_settings_to_automatically_pick_the_precursor_transitions_specified_in_the_full_scan_settings_),
                                    Program.Name, MessageBoxButtons.OKCancel) != DialogResult.OK)
                {
                    return(false);
                }

                SkylineWindow.ModifyDocument(Resources.ImportFastaControl_ImportFasta_Change_settings_to_add_precursors, doc => ImportPeptideSearch.ChangeAutoManageChildren(doc, PickLevel.transitions, true));
            }
            else // The user specified some FASTA content
            {
                // If the user is about to add any new transitions by importing
                // FASTA, set FragmentType='p' and AutoSelect=true
                var docCurrent = SkylineWindow.Document;
                var docNew     = ImportPeptideSearch.PrepareImportFasta(docCurrent);

                var          nodeInsert       = SkylineWindow.SequenceTree.SelectedNode as SrmTreeNode;
                IdentityPath selectedPath     = nodeInsert != null ? nodeInsert.Path : null;
                var          newPeptideGroups = new List <PeptideGroupDocNode>();

                if (!_fastaFile)
                {
                    // Import FASTA as content
                    using (var longWaitDlg = new LongWaitDlg(SkylineWindow)
                    {
                        Text = Resources.ImportFastaControl_ImportFasta_Insert_FASTA
                    })
                    {
                        var docImportFasta = docNew;
                        longWaitDlg.PerformWork(WizardForm, 1000, longWaitBroker =>
                        {
                            docImportFasta = ImportFastaHelper.AddFasta(docImportFasta, longWaitBroker, ref selectedPath, out newPeptideGroups);
                        });
                        docNew = docImportFasta;
                    }
                    // Document will be null if there was an error
                    if (docNew == null)
                    {
                        return(false);
                    }
                }
                else
                {
                    // Import FASTA as file
                    var fastaPath = tbxFasta.Text;
                    try
                    {
                        using (var longWaitDlg = new LongWaitDlg(SkylineWindow)
                        {
                            Text = Resources.ImportFastaControl_ImportFasta_Insert_FASTA
                        })
                        {
                            IdentityPath to             = selectedPath;
                            var          docImportFasta = docNew;
                            longWaitDlg.PerformWork(WizardForm, 1000, longWaitBroker =>
                            {
                                IdentityPath nextAdd;
                                docImportFasta = ImportPeptideSearch.ImportFasta(docImportFasta, fastaPath, longWaitBroker, to, out selectedPath, out nextAdd, out newPeptideGroups);
                            });
                            docNew = docImportFasta;
                        }
                    }
                    catch (Exception x)
                    {
                        MessageDlg.ShowWithException(this, string.Format(Resources.SkylineWindow_ImportFastaFile_Failed_reading_the_file__0__1__,
                                                                         fastaPath, x.Message), x);
                        return(false);
                    }
                }

                if (!newPeptideGroups.Any())
                {
                    MessageDlg.Show(this, Resources.ImportFastaControl_ImportFasta_Importing_the_FASTA_did_not_create_any_target_proteins_);
                    return(false);
                }

                // Filter proteins based on number of peptides and add decoys
                using (var dlg = new PeptidesPerProteinDlg(docNew, newPeptideGroups, DecoyGenerationMethod, NumDecoys ?? 0))
                {
                    docNew = dlg.ShowDialog(WizardForm) == DialogResult.OK ? dlg.DocumentFinal : null;
                }

                // Document will be null if user was given option to keep or remove empty proteins and pressed cancel
                if (docNew == null)
                {
                    return(false);
                }

                if (AutoTrain)
                {
                    docNew = docNew.ChangeSettings(docNew.Settings.ChangePeptideIntegration(integration => integration.ChangeAutoTrain(true)));
                }

                SkylineWindow.ModifyDocument(Resources.ImportFastaControl_ImportFasta_Insert_FASTA, doc =>
                {
                    if (!ReferenceEquals(doc, docCurrent))
                    {
                        throw new InvalidDataException(Resources.SkylineWindow_ImportFasta_Unexpected_document_change_during_operation);
                    }
                    return(docNew);
                });

                if (RequirePrecursorTransition && !VerifyAtLeastOnePrecursorTransition(SkylineWindow.Document))
                {
                    return(false);
                }
            }

            return(true);
        }
Example #17
0
        public bool ImportFasta(IrtStandard irtStandard)
        {
            var settings        = DocumentContainer.Document.Settings;
            var peptideSettings = settings.PeptideSettings;
            int missedCleavages = MaxMissedCleavages;
            var enzyme          = Enzyme;

            if (!Equals(missedCleavages, peptideSettings.DigestSettings.MaxMissedCleavages) || !Equals(enzyme, peptideSettings.Enzyme))
            {
                var digest = new DigestSettings(missedCleavages, peptideSettings.DigestSettings.ExcludeRaggedEnds);
                peptideSettings = peptideSettings.ChangeDigestSettings(digest).ChangeEnzyme(enzyme);
                DocumentContainer.ModifyDocumentNoUndo(doc =>
                                                       doc.ChangeSettings(settings.ChangePeptideSettings(peptideSettings)));
            }

            if (!string.IsNullOrEmpty(DecoyGenerationMethod))
            {
                if (!NumDecoys.HasValue || NumDecoys <= 0)
                {
                    MessageDlg.Show(WizardForm, Resources.ImportFastaControl_ImportFasta_Please_enter_a_valid_number_of_decoys_per_target_greater_than_0_);
                    txtNumDecoys.Focus();
                    return(false);
                }
                else if (Equals(DecoyGenerationMethod, DecoyGeneration.REVERSE_SEQUENCE) && NumDecoys > 1)
                {
                    MessageDlg.Show(WizardForm, Resources.ImportFastaControl_ImportFasta_A_maximum_of_one_decoy_per_target_may_be_generated_when_using_reversed_decoys_);
                    txtNumDecoys.Focus();
                    return(false);
                }
            }

            if (!ContainsFastaContent) // The user didn't specify any FASTA content
            {
                var docCurrent = DocumentContainer.Document;
                // If the document has precursor transitions already, then just trust the user
                // knows what they are doing, and this document is already set up for MS1 filtering
                if (HasPrecursorTransitions(docCurrent))
                {
                    return(true);
                }

                if (docCurrent.PeptideCount == 0)
                {
                    MessageDlg.Show(WizardForm, TextUtil.LineSeparate(Resources.ImportFastaControl_ImportFasta_The_document_does_not_contain_any_peptides_,
                                                                      Resources.ImportFastaControl_ImportFasta_Please_import_FASTA_to_add_peptides_to_the_document_));
                    return(false);
                }

                if (MessageBox.Show(WizardForm, TextUtil.LineSeparate(Resources.ImportFastaControl_ImportFasta_The_document_does_not_contain_any_precursor_transitions_,
                                                                      Resources.ImportFastaControl_ImportFasta_Would_you_like_to_change_the_document_settings_to_automatically_pick_the_precursor_transitions_specified_in_the_full_scan_settings_),
                                    Program.Name, MessageBoxButtons.OKCancel) != DialogResult.OK)
                {
                    return(false);
                }

                DocumentContainer.ModifyDocumentNoUndo(doc => ImportPeptideSearch.ChangeAutoManageChildren(doc, PickLevel.transitions, true));
            }
            else // The user specified some FASTA content
            {
                // If the user is about to add any new transitions by importing
                // FASTA, set FragmentType='p' and AutoSelect=true
                var docCurrent = DocumentContainer.Document;
                var docNew     = ImportPeptideSearch.PrepareImportFasta(docCurrent);

                var          nodeInsert       = _sequenceTree.SelectedNode as SrmTreeNode;
                IdentityPath selectedPath     = nodeInsert != null ? nodeInsert.Path : null;
                var          newPeptideGroups = new List <PeptideGroupDocNode>();

                if (!_fastaFile)
                {
                    FastaText = tbxFasta.Text;
                    PasteError error = null;
                    // Import FASTA as content
                    using (var longWaitDlg = new LongWaitDlg(DocumentContainer)
                    {
                        Text = Resources.ImportFastaControl_ImportFasta_Insert_FASTA
                    })
                    {
                        var docImportFasta = docNew;
                        longWaitDlg.PerformWork(WizardForm, 1000, longWaitBroker =>
                        {
                            docImportFasta = ImportFastaHelper.AddFasta(docImportFasta, longWaitBroker, ref selectedPath, out newPeptideGroups, out error);
                        });
                        docNew = docImportFasta;
                    }
                    // Document will be null if there was an error
                    if (docNew == null)
                    {
                        ImportFastaHelper.ShowFastaError(error);
                        return(false);
                    }
                }
                else
                {
                    // Import FASTA as file
                    var fastaPath = tbxFasta.Text;
                    try
                    {
                        using (var longWaitDlg = new LongWaitDlg(DocumentContainer)
                        {
                            Text = Resources.ImportFastaControl_ImportFasta_Insert_FASTA
                        })
                        {
                            IdentityPath to             = selectedPath;
                            var          docImportFasta = docNew;
                            longWaitDlg.PerformWork(WizardForm, 1000, longWaitBroker =>
                            {
                                IdentityPath nextAdd;
                                docImportFasta = ImportPeptideSearch.ImportFasta(docImportFasta, fastaPath, longWaitBroker, to, out selectedPath, out nextAdd, out newPeptideGroups);
                            });
                            docNew = docImportFasta;
                        }
                    }
                    catch (Exception x)
                    {
                        MessageDlg.ShowWithException(this, string.Format(Resources.SkylineWindow_ImportFastaFile_Failed_reading_the_file__0__1__,
                                                                         fastaPath, x.Message), x);
                        return(false);
                    }
                }

                if (!newPeptideGroups.Any())
                {
                    MessageDlg.Show(this, Resources.ImportFastaControl_ImportFasta_Importing_the_FASTA_did_not_create_any_target_proteins_);
                    return(false);
                }

                // Filter proteins based on number of peptides and add decoys
                using (var dlg = new PeptidesPerProteinDlg(docNew, newPeptideGroups, DecoyGenerationMethod, NumDecoys ?? 0))
                {
                    docNew = dlg.ShowDialog(WizardForm) == DialogResult.OK ? dlg.DocumentFinal : null;
                }

                // Document will be null if user was given option to keep or remove empty proteins and pressed cancel
                if (docNew == null)
                {
                    return(false);
                }

                // Add iRT standards if not present
                if (irtStandard != null && !irtStandard.Name.Equals(IrtStandard.EMPTY.Name))
                {
                    using (var reader = irtStandard.GetDocumentReader())
                    {
                        if (reader != null)
                        {
                            var standardMap  = new TargetMap <bool>(irtStandard.Peptides.Select(pep => new KeyValuePair <Target, bool>(pep.ModifiedTarget, true)));
                            var docStandards = new TargetMap <bool>(docNew.Peptides
                                                                    .Where(nodePep => standardMap.ContainsKey(nodePep.ModifiedTarget)).Select(nodePep =>
                                                                                                                                              new KeyValuePair <Target, bool>(nodePep.ModifiedTarget, true)));
                            if (irtStandard.Peptides.Any(pep => !docStandards.ContainsKey(pep.ModifiedTarget)))
                            {
                                docNew = docNew.ImportDocumentXml(reader,
                                                                  string.Empty,
                                                                  Model.Results.MeasuredResults.MergeAction.remove,
                                                                  false,
                                                                  null,
                                                                  Settings.Default.StaticModList,
                                                                  Settings.Default.HeavyModList,
                                                                  new IdentityPath(docNew.Children.First().Id),
                                                                  out _,
                                                                  out _,
                                                                  false);
                            }
                        }
                    }
                }

                if (AutoTrain)
                {
                    if (!docNew.Peptides.Any(pep => pep.IsDecoy))
                    {
                        MessageDlg.Show(this, Resources.ImportFastaControl_ImportFasta_Cannot_automatically_train_mProphet_model_without_decoys__but_decoy_options_resulted_in_no_decoys_being_generated__Please_increase_number_of_decoys_per_target__or_disable_automatic_training_of_mProphet_model_);
                        return(false);
                    }
                    docNew = docNew.ChangeSettings(docNew.Settings.ChangePeptideIntegration(integration => integration.ChangeAutoTrain(true)));
                }

                DocumentContainer.ModifyDocumentNoUndo(doc =>
                {
                    if (!ReferenceEquals(doc, docCurrent))
                    {
                        throw new InvalidDataException(Resources.SkylineWindow_ImportFasta_Unexpected_document_change_during_operation);
                    }
                    return(docNew);
                });

                if (RequirePrecursorTransition && !VerifyAtLeastOnePrecursorTransition(DocumentContainer.Document))
                {
                    return(false);
                }
            }

            return(true);
        }
Example #18
0
 public DDASearchControl(ImportPeptideSearch importPeptideSearch)
 {
     InitializeComponent();
     ImportPeptideSearch = importPeptideSearch;
     UpdateUI            = UpdateSearchEngineProgress;
 }
        private bool BuildPeptideSearchLibrary(CancelEventArgs e)
        {
            // Nothing to build, if now search files were specified
            if (!SearchFilenames.Any())
            {
                var libraries = DocumentContainer.Document.Settings.PeptideSettings.Libraries;
                if (!libraries.HasLibraries)
                {
                    return(false);
                }
                var libSpec = libraries.LibrarySpecs.FirstOrDefault(s => s.IsDocumentLibrary);
                return(libSpec != null && LoadPeptideSearchLibrary(libSpec));
            }

            double           cutOffScore;
            MessageBoxHelper helper = new MessageBoxHelper(WizardForm);

            if (!helper.ValidateDecimalTextBox(textCutoff, 0, 1.0, out cutOffScore))
            {
                e.Cancel = true;
                return(false);
            }
            ImportPeptideSearch.CutoffScore = cutOffScore;

            BiblioSpecLiteBuilder builder;

            try
            {
                builder = ImportPeptideSearch.GetLibBuilder(DocumentContainer.Document, DocumentContainer.DocumentFilePath, cbIncludeAmbiguousMatches.Checked);
                builder.PreferEmbeddedSpectra = PreferEmbeddedSpectra;
            }
            catch (FileEx.DeleteException de)
            {
                MessageDlg.ShowException(this, de);
                return(false);
            }

            bool retry = false;

            do
            {
                using (var longWaitDlg = new LongWaitDlg
                {
                    Text = Resources.BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Building_Peptide_Search_Library,
                    Message = Resources.BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Building_document_library_for_peptide_search_,
                })
                {
                    // Disable the wizard, because the LongWaitDlg does not
                    try
                    {
                        ImportPeptideSearch.ClosePeptideSearchLibraryStreams(DocumentContainer.Document);
                        var status = longWaitDlg.PerformWork(WizardForm, 800,
                                                             monitor => LibraryManager.BuildLibraryBackground(DocumentContainer, builder, monitor, new LibraryManager.BuildState(null, null)));
                        if (status.IsError)
                        {
                            // E.g. could not find external raw data for MaxQuant msms.txt; ask user if they want to retry with "prefer embedded spectra" option
                            if (BiblioSpecLiteBuilder.IsLibraryMissingExternalSpectraError(status.ErrorException))
                            {
                                var response = ShowLibraryMissingExternalSpectraError(WizardForm, status.ErrorException);
                                if (response == UpdateProgressResponse.cancel)
                                {
                                    return(false);
                                }
                                else if (response == UpdateProgressResponse.normal)
                                {
                                    builder.PreferEmbeddedSpectra = true;
                                }

                                retry = true;
                            }
                            else
                            {
                                MessageDlg.ShowException(WizardForm, status.ErrorException);
                                return(false);
                            }
                        }
                    }
                    catch (Exception x)
                    {
                        MessageDlg.ShowWithException(WizardForm, TextUtil.LineSeparate(string.Format(Resources.BuildPeptideSearchLibraryControl_BuildPeptideSearchLibrary_Failed_to_build_the_library__0__,
                                                                                                     Path.GetFileName(BiblioSpecLiteSpec.GetLibraryFileName(DocumentContainer.DocumentFilePath))), x.Message), x);
                        return(false);
                    }
                }
            } while (retry);

            var docLibSpec = builder.LibrarySpec.ChangeDocumentLibrary(true);

            Settings.Default.SpectralLibraryList.Insert(0, docLibSpec);

            // Go ahead and load the library - we'll need it for
            // the modifications and chromatograms page.
            if (!LoadPeptideSearchLibrary(docLibSpec))
            {
                return(false);
            }

            var selectedIrtStandard = comboStandards.SelectedItem as IrtStandard;
            var addedIrts           = false;

            if (selectedIrtStandard != null && selectedIrtStandard != IrtStandard.EMPTY)
            {
                addedIrts = AddIrtLibraryTable(docLibSpec.FilePath, selectedIrtStandard);
            }

            var docNew = ImportPeptideSearch.AddDocumentSpectralLibrary(DocumentContainer.Document, docLibSpec);

            if (docNew == null)
            {
                return(false);
            }

            if (addedIrts)
            {
                docNew = ImportPeptideSearch.AddRetentionTimePredictor(docNew, docLibSpec);
            }

            DocumentContainer.ModifyDocumentNoUndo(doc => docNew);

            if (!string.IsNullOrEmpty(builder.AmbiguousMatchesMessage))
            {
                MessageDlg.Show(WizardForm, builder.AmbiguousMatchesMessage);
            }
            return(true);
        }
        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 #21
0
        private SrmDocument GetDocumentFinal(CancellationToken cancellationToken, SrmDocument doc, int minPeptides, bool removeRepeated, bool removeDuplicate, out int?emptyProteins)
        {
            emptyProteins = null;

            // Remove repeated/duplicate peptides
            var newDoc = removeRepeated || removeDuplicate
                ? new RefinementSettings {
                RemoveRepeatedPeptides = removeRepeated, RemoveDuplicatePeptides = removeDuplicate
            }.Refine(doc)
                : doc;

            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            // Remove proteins without enough peptides
            newDoc = ImportPeptideSearch.RemoveProteinsByPeptideCount(newDoc, minPeptides);

            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            // Move iRT proteins to top
            var irtPeptides = new HashSet <Target>(RCalcIrt.IrtPeptides(newDoc));
            var proteins    = new List <PeptideGroupDocNode>(newDoc.PeptideGroups);
            var proteinsIrt = new List <PeptideGroupDocNode>();

            for (var i = 0; i < proteins.Count; i++)
            {
                var nodePepGroup = proteins[i];
                if (nodePepGroup.Peptides.All(nodePep => irtPeptides.Contains(new Target(nodePep.ModifiedSequence))))
                {
                    proteinsIrt.Add(nodePepGroup);
                    proteins.RemoveAt(i--);
                }
            }
            if (proteinsIrt.Any())
            {
                newDoc = (SrmDocument)newDoc.ChangeChildrenChecked(proteinsIrt.Concat(proteins).Cast <DocNode>().ToArray());
            }

            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            // Add decoys
            newDoc = AddDecoys(newDoc);

            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            // Count empty proteins
            emptyProteins = newDoc.PeptideGroups.Count(pepGroup => pepGroup.PeptideCount == 0);

            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            return(newDoc);
        }
        public static bool AddIrts(IrtRegressionType regressionType, Library lib, LibrarySpec libSpec, IrtStandard standard, Control parent, bool useTopMostForm)
        {
            if (lib == null || !lib.IsLoaded || standard == null || standard.Name.Equals(IrtStandard.EMPTY.Name))
            {
                return(false);
            }

            Control GetParent()
            {
                return(useTopMostForm ? FormUtil.FindTopLevelOpenForm(f => f is BuildLibraryNotification) ?? parent : parent);
            }

            IRetentionTimeProvider[] irtProviders = null;
            var isAuto = ReferenceEquals(standard, IrtStandard.AUTO);
            List <IrtStandard> autoStandards = null;
            var cirtPeptides = new DbIrtPeptide[0];

            using (var longWait = new LongWaitDlg {
                Text = Resources.LibraryBuildNotificationHandler_AddIrts_Loading_retention_time_providers
            })
            {
                var standard1 = standard;
                var status    = longWait.PerformWork(GetParent(), 800, monitor =>
                {
                    ImportPeptideSearch.GetLibIrtProviders(lib, standard1, monitor, out irtProviders, out autoStandards, out cirtPeptides);
                });
                if (status.IsCanceled)
                {
                    return(false);
                }
                if (status.IsError)
                {
                    throw status.ErrorException;
                }
            }

            int?numCirt = null;

            if (cirtPeptides.Length >= RCalcIrt.MIN_PEPTIDES_COUNT)
            {
                using (var dlg = new AddIrtStandardsDlg(cirtPeptides.Length,
                                                        string.Format(
                                                            Resources.LibraryBuildNotificationHandler_AddIrts__0__distinct_CiRT_peptides_were_found__How_many_would_you_like_to_use_as_iRT_standards_,
                                                            cirtPeptides.Length)))
                {
                    if (dlg.ShowDialog(GetParent()) != DialogResult.OK)
                    {
                        return(false);
                    }
                    numCirt = dlg.StandardCount;
                }
            }
            else if (isAuto)
            {
                switch (autoStandards.Count)
                {
                case 0:
                    standard = new IrtStandard(XmlNamedElement.NAME_INTERNAL, null, null, IrtPeptidePicker.Pick(irtProviders, 10));
                    break;

                case 1:
                    standard = autoStandards[0];
                    break;

                default:
                    using (var selectIrtStandardDlg = new SelectIrtStandardDlg(autoStandards))
                    {
                        if (selectIrtStandardDlg.ShowDialog(GetParent()) != DialogResult.OK)
                        {
                            return(false);
                        }
                        standard = selectIrtStandardDlg.Selected;
                    }
                    break;
                }
            }

            var standardPeptides           = standard.Peptides.ToArray();
            ProcessedIrtAverages processed = null;

            using (var longWait = new LongWaitDlg {
                Text = Resources.LibraryBuildNotificationHandler_AddIrts_Processing_retention_times
            })
            {
                try
                {
                    var status = longWait.PerformWork(GetParent(), 800, monitor =>
                    {
                        processed = ImportPeptideSearch.ProcessRetentionTimes(numCirt, irtProviders, standardPeptides, cirtPeptides, regressionType, monitor, out var newStandardPeptides);
                        if (newStandardPeptides != null)
                        {
                            standardPeptides = newStandardPeptides;
                        }
                    });
                    if (status.IsCanceled)
                    {
                        return(false);
                    }
                    if (status.IsError)
                    {
                        throw status.ErrorException;
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(GetParent(),
                                                 TextUtil.LineSeparate(
                                                     Resources.BuildPeptideSearchLibraryControl_AddIrtLibraryTable_An_error_occurred_while_processing_retention_times_,
                                                     x.Message), x);
                    return(false);
                }
            }

            using (var resultsDlg = new AddIrtPeptidesDlg(AddIrtPeptidesLocation.spectral_library, processed))
            {
                if (resultsDlg.ShowDialog(GetParent()) != DialogResult.OK)
                {
                    return(false);
                }
            }

            var recalibrate = false;

            if (processed.CanRecalibrateStandards(standardPeptides))
            {
                using (var dlg = new MultiButtonMsgDlg(
                           TextUtil.LineSeparate(Resources.LibraryGridViewDriver_AddToLibrary_Do_you_want_to_recalibrate_the_iRT_standard_values_relative_to_the_peptides_being_added_,
                                                 Resources.LibraryGridViewDriver_AddToLibrary_This_can_improve_retention_time_alignment_under_stable_chromatographic_conditions_),
                           MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false))
                {
                    recalibrate = dlg.ShowDialog(GetParent()) == DialogResult.Yes;
                }
            }

            if (!processed.DbIrtPeptides.Any())
            {
                return(false);
            }

            using (var longWait = new LongWaitDlg {
                Text = Resources.LibraryBuildNotificationHandler_AddIrts_Adding_iRTs_to_library
            })
            {
                try
                {
                    var status = longWait.PerformWork(GetParent(), 800, monitor =>
                    {
                        ImportPeptideSearch.CreateIrtDb(libSpec.FilePath, processed, standardPeptides, recalibrate, regressionType, monitor);
                    });
                    if (status.IsError)
                    {
                        throw status.ErrorException;
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(GetParent(),
                                                 TextUtil.LineSeparate(
                                                     Resources.LibraryBuildNotificationHandler_AddIrts_An_error_occurred_trying_to_add_iRTs_to_the_library_,
                                                     x.Message), x);
                    return(false);
                }
            }
            return(true);
        }