/// <summary>
        /// Parse the mass list text, then show a status dialog if:
        ///     errors are found, or
        ///     errors are not found and "silentSuccess" arg is false
        /// Shows a special error message and forces the user to alter their entry if the list is missing Precursor m/z, Product m/z or Peptide Sequence.
        /// Return false if no errors found.
        /// </summary>
        /// <param name="silentSuccess">If true, don't show the confirmation dialog when there are no errors</param>
        /// <returns>True if list contains any errors and user does not elect to ignore them</returns>
        private bool CheckForErrors(bool silentSuccess)
        {
            IdentityPath testSelectPath = null;
            List <MeasuredRetentionTime>     testIrtPeptides    = null;
            List <SpectrumMzInfo>            testLibrarySpectra = null;
            List <TransitionImportErrorInfo> testErrorList      = null;
            List <PeptideGroupDocNode>       testPeptideGroups  = null;
            var columns = Importer.RowReader.Indices;

            MissingEssentialColumns = new List <string>();
            CheckEssentialColumn(new Tuple <int, string>(columns.PeptideColumn, Resources.ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Peptide_Modified_Sequence));
            CheckEssentialColumn(new Tuple <int, string>(columns.PrecursorColumn, Resources.ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Precursor_m_z));
            CheckEssentialColumn(new Tuple <int, string>(columns.ProductColumn, Resources.ImportTransitionListColumnSelectDlg_PopulateComboBoxes_Product_m_z));
            var docNew = _docCurrent.ImportMassList(_inputs, Importer, null,
                                                    _insertPath, out testSelectPath, out testIrtPeptides, out testLibrarySpectra,
                                                    out testErrorList, out testPeptideGroups);

            if (testErrorList.Any())
            {
                // There are errors, show them to user
                var          isErrorAll = ReferenceEquals(docNew, _docCurrent);
                DialogResult response;
                if (MissingEssentialColumns.Count != 0)
                {
                    // If the transition list is missing essential columns, tell the user in a
                    // readable way
                    string errorMessage = Resources.ImportTransitionListErrorDlg_ImportTransitionListErrorDlg_This_transition_list_cannot_be_imported_as_it_does_not_provide_values_for_;
                    for (var i = 0; i < MissingEssentialColumns.Count; i++)
                    {
                        errorMessage = errorMessage + @" " + MissingEssentialColumns[i];
                    }
                    MessageDlg.Show(this, errorMessage);
                    return(true);
                }
                else
                {
                    using (var dlg = new ImportTransitionListErrorDlg(testErrorList, isErrorAll, silentSuccess))
                    {
                        response = dlg.ShowDialog(this);
                    }

                    return(response == DialogResult.Cancel); // There are errors, and user does not want to ignore them
                }
            }
            else if (!silentSuccess)
            {
                // No errors, confirm this to user
                MessageDlg.Show(this, Resources.PasteDlg_ShowNoErrors_No_errors);
            }

            return(false); // No errors
        }
Ejemplo n.º 2
0
        private void ImportMassList(MassListInputs inputs, string description)
        {
            SrmTreeNode nodePaste = SequenceTree.SelectedNode as SrmTreeNode;
            IdentityPath insertPath = nodePaste != null ? nodePaste.Path : null;
            IdentityPath selectPath = null;
            List<MeasuredRetentionTime> irtPeptides = null;
            List<SpectrumMzInfo> librarySpectra = null;
            List<TransitionImportErrorInfo> errorList = null;
            List<PeptideGroupDocNode> peptideGroups = null;
            RetentionTimeRegression retentionTimeRegressionStore = null;
            var docCurrent = DocumentUI;
            SrmDocument docNew = null;
            var retentionTimeRegression = docCurrent.Settings.PeptideSettings.Prediction.RetentionTime;
            RCalcIrt calcIrt = retentionTimeRegression != null ? (retentionTimeRegression.Calculator as RCalcIrt) : null;
            using (var longWaitDlg = new LongWaitDlg(this) {Text = description})
            {
                longWaitDlg.PerformWork(this, 1000, longWaitBroker =>
                {
                    docNew = docCurrent.ImportMassList(inputs, longWaitBroker,
                        insertPath, out selectPath, out irtPeptides, out librarySpectra, out errorList, out peptideGroups);
                });
            }
            bool isDocumentSame = ReferenceEquals(docNew, docCurrent);
            // If nothing was imported (e.g. operation was canceled or zero error-free transitions) and also no errors, just return
            if (isDocumentSame && !errorList.Any())
                return;
            // Show the errors, giving the option to accept the transitions without errors,
            // if there are any
            if (errorList.Any())
            {
                using (var errorDlg = new ImportTransitionListErrorDlg(errorList, isDocumentSame))
                {
                    if (errorDlg.ShowDialog(this) == DialogResult.Cancel || isDocumentSame)
                    {
                        return;
                    }
                }
            }

            var dbIrtPeptides = irtPeptides.Select(rt => new DbIrtPeptide(rt.PeptideSequence, rt.RetentionTime, false, TimeSource.scan)).ToList();
            var dbIrtPeptidesFilter = ImportAssayLibraryHelper.GetUnscoredIrtPeptides(dbIrtPeptides, calcIrt);
            bool overwriteExisting = false;
            MassListInputs irtInputs = null;
            // If there are no iRT peptides or none with different values than the database, don't import any iRT's
            if (dbIrtPeptidesFilter.Any())
            {
                // Ask whether or not to include iRT peptides in the paste
                string useIrtMessage = calcIrt == null
                    ? Resources.SkylineWindow_ImportMassList_The_transition_list_appears_to_contain_iRT_values__but_the_document_does_not_have_an_iRT_calculator___Create_a_new_calculator_and_add_these_iRT_values_
                    : Resources.SkylineWindow_ImportMassList_The_transition_list_appears_to_contain_iRT_library_values___Add_these_iRT_values_to_the_iRT_calculator_;
                string yesButton = calcIrt == null
                    ? Resources.SkylineWindow_ImportMassList__Create___
                    : Resources.SkylineWindow_ImportMassList_Add;
                var useIrtResult = MultiButtonMsgDlg.Show(this, useIrtMessage,
                    yesButton, Resources.SkylineWindow_ImportMassList__Skip, true);
                if (useIrtResult == DialogResult.Cancel)
                {
                    return;
                }
                if (useIrtResult == DialogResult.Yes)
                {
                    if (calcIrt == null)
                    {
                        // If there is no iRT calculator, ask the user to create one
                        using (var dlg = new CreateIrtCalculatorDlg(docNew, DocumentFilePath, Settings.Default.RTScoreCalculatorList, peptideGroups))
                        {
                            if (dlg.ShowDialog(this) != DialogResult.OK)
                            {
                                return;
                            }

                            docNew = dlg.Document;
                            calcIrt = (RCalcIrt)docNew.Settings.PeptideSettings.Prediction.RetentionTime.Calculator;
                            dlg.UpdateLists(librarySpectra, dbIrtPeptidesFilter);
                            if (!string.IsNullOrEmpty(dlg.IrtFile))
                                irtInputs = new MassListInputs(dlg.IrtFile);
                        }
                    }
                    string dbPath = calcIrt.DatabasePath;
                    IrtDb db = File.Exists(dbPath) ? IrtDb.GetIrtDb(dbPath, null) : IrtDb.CreateIrtDb(dbPath);
                    var oldPeptides = db.GetPeptides().ToList();
                    IList<DbIrtPeptide.Conflict> conflicts;
                    dbIrtPeptidesFilter = DbIrtPeptide.MakeUnique(dbIrtPeptidesFilter);
                    DbIrtPeptide.FindNonConflicts(oldPeptides, dbIrtPeptidesFilter, null, out conflicts);
                    // Ask whether to keep or overwrite peptides that are present in the import and already in the database
                    if (conflicts.Any())
                    {
                        string messageOverwrite = string.Format(Resources.SkylineWindow_ImportMassList_The_iRT_calculator_already_contains__0__of_the_imported_peptides_,
                                                                conflicts.Count);
                        var overwriteResult = MultiButtonMsgDlg.Show(this,
                            TextUtil.LineSeparate(messageOverwrite, conflicts.Count == 1
                                ? Resources.SkylineWindow_ImportMassList_Keep_the_existing_iRT_value_or_overwrite_with_the_imported_value_
                                : Resources.SkylineWindow_ImportMassList_Keep_the_existing_iRT_values_or_overwrite_with_imported_values_),
                            Resources.SkylineWindow_ImportMassList__Keep, Resources.SkylineWindow_ImportMassList__Overwrite, true);
                        if (overwriteResult == DialogResult.Cancel)
                        {
                            return;
                        }
                        overwriteExisting = overwriteResult == DialogResult.No;
                    }
                    using (var longWaitDlg = new LongWaitDlg(this) { Text = Resources.SkylineWindow_ImportMassList_Adding_iRT_values_})
                    {
                        longWaitDlg.PerformWork(this, 100, progressMonitor =>
                            docNew = docNew.AddIrtPeptides(dbIrtPeptidesFilter, overwriteExisting, progressMonitor));
                    }
                    if (docNew == null)
                        return;
                    retentionTimeRegressionStore = docNew.Settings.PeptideSettings.Prediction.RetentionTime;
                }
            }
            BiblioSpecLiteSpec docLibrarySpec = null;
            BiblioSpecLiteLibrary docLibrary = null;
            int indexOldLibrary = -1;
            if (librarySpectra.Any())
            {
                string addLibraryMessage = Resources.SkylineWindow_ImportMassList_The_transition_list_appears_to_contain_spectral_library_intensities___Create_a_document_library_from_these_intensities_;
                var addLibraryResult = MultiButtonMsgDlg.Show(this, addLibraryMessage,
                    Resources.SkylineWindow_ImportMassList__Create___, Resources.SkylineWindow_ImportMassList__Skip,
                    true);
                if (addLibraryResult == DialogResult.Cancel)
                {
                    return;
                }
                if (addLibraryResult == DialogResult.Yes)
                {
                    // Can't name a library after the document if the document is unsaved
                    // In this case, prompt to save
                    if (DocumentFilePath == null)
                    {
                        string saveDocumentMessage = Resources.SkylineWindow_ImportMassList_You_must_save_the_Skyline_document_in_order_to_create_a_spectral_library_from_a_transition_list_;
                        var saveDocumentResult = MultiButtonMsgDlg.Show(this, saveDocumentMessage, MultiButtonMsgDlg.BUTTON_OK);
                        if (saveDocumentResult == DialogResult.Cancel)
                        {
                            return;
                        }
                        else if (!SaveDocumentAs())
                        {
                            return;
                        }
                    }

                    librarySpectra = SpectrumMzInfo.RemoveDuplicateSpectra(librarySpectra);

                    string documentLibrary = BiblioSpecLiteSpec.GetLibraryFileName(DocumentFilePath);
            // ReSharper disable once AssignNullToNotNullAttribute
                    string outputPath = Path.Combine(Path.GetDirectoryName(documentLibrary),
                                                     Path.GetFileNameWithoutExtension(documentLibrary) + BiblioSpecLiteSpec.ASSAY_NAME + BiblioSpecLiteSpec.EXT);
                    bool libraryExists = File.Exists(outputPath);
                    string name = Path.GetFileNameWithoutExtension(DocumentFilePath) + BiblioSpecLiteSpec.ASSAY_NAME;
                    indexOldLibrary = docNew.Settings.PeptideSettings.Libraries.LibrarySpecs.IndexOf(spec => spec != null && spec.FilePath == outputPath);
                    bool libraryLinkedToDoc = indexOldLibrary != -1;
                    if (libraryLinkedToDoc)
                    {
                        string oldName = docNew.Settings.PeptideSettings.Libraries.LibrarySpecs[indexOldLibrary].Name;
                        var libraryOld = docNew.Settings.PeptideSettings.Libraries.GetLibrary(oldName);
                        var additionalSpectra = SpectrumMzInfo.GetInfoFromLibrary(libraryOld);
                        additionalSpectra = SpectrumMzInfo.RemoveDuplicateSpectra(additionalSpectra);
                        librarySpectra = SpectrumMzInfo.MergeWithOverwrite(librarySpectra, additionalSpectra);
                        foreach (var stream in libraryOld.ReadStreams)
                            stream.CloseStream();
                    }
                    if (libraryExists && !libraryLinkedToDoc)
                    {
                        string replaceLibraryMessage = string.Format(Resources.SkylineWindow_ImportMassList_There_is_an_existing_library_with_the_same_name__0__as_the_document_library_to_be_created___Overwrite_this_library_or_skip_import_of_library_intensities_,
                                          name);
                        // If the document does not have an assay library linked to it, then ask if user wants to delete the one that we have found
                        var replaceLibraryResult = MultiButtonMsgDlg.Show(this, replaceLibraryMessage,
                            Resources.SkylineWindow_ImportMassList__Overwrite, Resources.SkylineWindow_ImportMassList__Skip, true);
                        if (replaceLibraryResult == DialogResult.Cancel)
                            return;
                        if (replaceLibraryResult == DialogResult.No)
                            librarySpectra.Clear();
                    }
                    if (librarySpectra.Any())
                    {
                        // Delete the existing library; either it's not tied to the document or we've already extracted the spectra
                        if (libraryExists)
                        {
                            FileEx.SafeDelete(outputPath);
                            FileEx.SafeDelete(Path.ChangeExtension(outputPath, BiblioSpecLiteSpec.EXT_REDUNDANT));
                        }
                        using (var blibDb = BlibDb.CreateBlibDb(outputPath))
                        {
                            docLibrarySpec = new BiblioSpecLiteSpec(name, outputPath);
                            using (var longWaitDlg = new LongWaitDlg(this) { Text = Resources.SkylineWindow_ImportMassList_Creating_Spectral_Library })
                            {
                                longWaitDlg.PerformWork(this, 1000, progressMonitor =>
                                {
                                    docLibrary = blibDb.CreateLibraryFromSpectra(docLibrarySpec, librarySpectra, name, progressMonitor);
                                    if (docLibrary == null)
                                        return;
                                    var newSettings = docNew.Settings.ChangePeptideLibraries(libs => libs.ChangeLibrary(docLibrary, docLibrarySpec, indexOldLibrary));
                                    var status = new ProgressStatus(Resources.SkylineWindow_ImportMassList_Finishing_up_import);
                                    progressMonitor.UpdateProgress(status);
                                    progressMonitor.UpdateProgress(status.ChangePercentComplete(100));
                                    docNew = docNew.ChangeSettings(newSettings);
                                });
                                if (docLibrary == null)
                                    return;
                            }
                        }
                    }
                }
            }

            ModifyDocument(description, doc =>
            {
                if (ReferenceEquals(doc, docCurrent))
                    return docNew;
                try
                {
                    // If the document was changed during the operation, try all the changes again
                    // using the information given by the user.
                    docCurrent = DocumentUI;
                    doc = doc.ImportMassList(inputs, insertPath, out selectPath);
                    if (irtInputs != null)
                    {
                        doc = doc.ImportMassList(irtInputs, null, out selectPath);
                    }
                    var newSettings = doc.Settings;
                    if (retentionTimeRegressionStore != null)
                    {
                        newSettings = newSettings.ChangePeptidePrediction(prediction =>
                            prediction.ChangeRetentionTime(retentionTimeRegressionStore));
                    }
                    if (docLibrarySpec != null)
                    {
                        newSettings = newSettings.ChangePeptideLibraries(libs =>
                            libs.ChangeLibrary(docLibrary, docLibrarySpec, indexOldLibrary));
                    }
                    if (!ReferenceEquals(doc.Settings, newSettings))
                        doc = doc.ChangeSettings(newSettings);
                }
                catch (Exception x)
                {
                    throw new InvalidDataException(string.Format(Resources.SkylineWindow_ImportMassList_Unexpected_document_change_during_operation___0_, x.Message, x));
                }
                return doc;
            });

            if (selectPath != null)
                SequenceTree.SelectedPath = selectPath;
            if (retentionTimeRegressionStore != null)
            {
                Settings.Default.RetentionTimeList.Add(retentionTimeRegressionStore);
                Settings.Default.RTScoreCalculatorList.Add(retentionTimeRegressionStore.Calculator);
            }
            if (docLibrarySpec != null)
            {
                Settings.Default.SpectralLibraryList.Insert(0, docLibrarySpec);
            }
        }