public void AddModification(StaticMod mod, ModType type)
        {
            if (mod == null)
            {
                return;
            }

            ImportPeptideSearch.UserDefinedTypedMods.Add(mod);

            PeptideModifications peptideModifications = DocumentContainer.Document.Settings.PeptideSettings.Modifications;

            if (type == ModType.structural)
            {
                peptideModifications = peptideModifications.ChangeStaticModifications(
                    peptideModifications.StaticModifications.Concat(new[] { mod }).ToArray());
            }
            else
            {
                peptideModifications = peptideModifications.AddHeavyModifications(new[] { mod });
            }

            DocumentContainer.ModifyDocumentNoUndo(doc => doc.ChangeSettings(DocumentContainer.Document.Settings.ChangePeptideSettings(
                                                                                 DocumentContainer.Document.Settings.PeptideSettings.ChangeModifications(peptideModifications))));

            DocumentContainer.Document.Settings.UpdateDefaultModifications(false);

            FillLists(DocumentContainer.Document);
        }
        private bool AddExistingLibrary(CancelEventArgs e)
        {
            string libraryPath = ValidateLibraryPath();

            if (libraryPath == null)
            {
                e.Cancel = true;
                return(false);
            }

            var peptideLibraries = DocumentContainer.Document.Settings.PeptideSettings.Libraries;
            var docLibSpec       = peptideLibraries.LibrarySpecs.FirstOrDefault(spec => spec.FilePath == libraryPath);

            if (docLibSpec == null)
            {
                docLibSpec =
                    Settings.Default.SpectralLibraryList.FirstOrDefault(spec => spec.FilePath == libraryPath);
                if (docLibSpec == null)
                {
                    var existingNames = new HashSet <string>();
                    existingNames.UnionWith(Settings.Default.SpectralLibraryList.Select(spec => spec.Name));
                    existingNames.UnionWith(peptideLibraries.LibrarySpecs.Select(spec => spec.Name));
                    string libraryName =
                        Helpers.GetUniqueName(Path.GetFileNameWithoutExtension(libraryPath), existingNames);
                    docLibSpec = LibrarySpec.CreateFromPath(libraryName, libraryPath);
                    Settings.Default.SpectralLibraryList.SetValue(docLibSpec);
                }
            }
            if (!LoadPeptideSearchLibrary(docLibSpec))
            {
                return(false);
            }
            DocumentContainer.ModifyDocumentNoUndo(doc => ImportPeptideSearch.AddDocumentSpectralLibrary(doc, docLibSpec));
            return(true);
        }
        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);
        }
Example #4
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);
        }