示例#1
0
        public void OkDialog()
        {
            var reader           = new StringReader(PeptidesText);
            var invalidLines     = new List <string>();
            var notFoundLines    = new List <string>();
            var acceptedPeptides = new List <LibraryKey>();
            var peptideSequences = GetPeptideSequences();

            string line;

            while ((line = reader.ReadLine()) != null)
            {
                line = line.Trim();
                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }
                int foundAt;
                var charge = Transition.GetChargeFromIndicator(line,
                                                               TransitionGroup.MIN_PRECURSOR_CHARGE, TransitionGroup.MAX_PRECURSOR_CHARGE, out foundAt);
                if (!charge.IsEmpty)
                {
                    line = line.Substring(0, foundAt);
                }
                Target target;
                try
                {
                    // CONSIDER(bspratt) small molecule equivalent?
                    if (!FastaSequence.IsExSequence(line))
                    {
                        invalidLines.Add(line);
                        continue;
                    }
                    line   = SequenceMassCalc.NormalizeModifiedSequence(line);
                    target = new Target(line);
                }
                catch (Exception)
                {
                    invalidLines.Add(line);
                    continue;
                }

                if (!peptideSequences.ContainsKey(target))
                {
                    notFoundLines.Add(line);
                }
                else
                {
                    acceptedPeptides.Add(new LibKey(target, charge).LibraryKey);
                }
            }

            if (invalidLines.Count > 0)
            {
                if (invalidLines.Count == 1)
                {
                    MessageDlg.Show(this, string.Format(Resources.RefineListDlg_OkDialog_The_sequence__0__is_not_a_valid_peptide, invalidLines[0]));
                }
                else
                {
                    MessageDlg.Show(this, TextUtil.LineSeparate(Resources.RefineListDlg_OkDialog_The_following_sequences_are_not_valid_peptides, string.Empty, TextUtil.LineSeparate(invalidLines)));
                }
                return;
            }
            if (acceptedPeptides.Count == 0)
            {
                MessageDlg.Show(this, Resources.RefineListDlg_OkDialog_None_of_the_specified_peptides_are_in_the_document);
                return;
            }
            if (notFoundLines.Count > 0)
            {
                string message;
                if (notFoundLines.Count == 1)
                {
                    message = string.Format(Resources.RefineListDlg_OkDialog_The_peptide__0__is_not_in_the_document_Do_you_want_to_continue, notFoundLines[0]);
                }
                else if (notFoundLines.Count < 15)
                {
                    message = TextUtil.LineSeparate(Resources.RefineListDlg_OkDialog_The_following_peptides_are_not_in_the_document, string.Empty,
                                                    TextUtil.LineSeparate(notFoundLines), string.Empty,
                                                    Resources.RefineListDlg_OkDialog_Do_you_want_to_continue);
                }
                else
                {
                    message = string.Format(Resources.RefineListDlg_OkDialog_Of_the_specified__0__peptides__1__are_not_in_the_document_Do_you_want_to_continue,
                                            notFoundLines.Count + acceptedPeptides.Count, notFoundLines.Count);
                }
                if (MultiButtonMsgDlg.Show(this, message, MultiButtonMsgDlg.BUTTON_OK) != DialogResult.OK)
                {
                    return;
                }
            }

            AcceptedPeptides = acceptedPeptides.ToArray();
            DialogResult     = DialogResult.OK;
        }
示例#2
0
        public void OkDialog()
        {
            var helper = new MessageBoxHelper(this);

            string name;

            if (!helper.ValidateNameTextBox(textName, out name))
            {
                return;
            }

            if (_existing.Contains(en => !ReferenceEquals(_isolationScheme, en) && Equals(name, en.Name)))
            {
                helper.ShowTextBoxError(textName,
                                        Resources.EditIsolationSchemeDlg_OkDialog_The_isolation_scheme_named__0__already_exists, name);
                return;
            }

            if (rbUseResultsData.Checked)
            {
                double?precursorFilter = null;
                bool   filterMargin    = Equals(comboIsolationWidth.SelectedItem, IsolationWidthType.RESULTS_WITH_MARGIN);
                if (!Equals(comboIsolationWidth.SelectedItem, IsolationWidthType.RESULTS))
                {
                    double minFilt = filterMargin ? 0 : TransitionFullScan.MIN_PRECURSOR_MULTI_FILTER;
                    double maxFilt = filterMargin
                        ? TransitionFullScan.MAX_PRECURSOR_MULTI_FILTER_MARGIN
                        : TransitionFullScan.MAX_PRECURSOR_MULTI_FILTER;
                    double precFilt;
                    if (!helper.ValidateDecimalTextBox(textPrecursorFilterMz,
                                                       minFilt, maxFilt, out precFilt))
                    {
                        return;
                    }
                    precursorFilter = precFilt;
                }
                try
                {
                    _isolationScheme = new IsolationScheme(name, SpecialHandling, precursorFilter, null, filterMargin);
                }
                catch (InvalidDataException exception)
                {
                    MessageDlg.ShowException(this, exception);
                    return;
                }
            }
            else
            {
                // Validate prespecified windows.
                List <IsolationWindow> windowList;
                if ((windowList = GetIsolationWindows()) == null)
                {
                    return;
                }


                // Must be at least one window.
                if (windowList.Count == 0)
                {
                    _gridViewDriver.SelectCell(COLUMN_START, 0);
                    MessageDlg.Show(this,
                                    Resources
                                    .EditIsolationSchemeDlg_OkDialog_Specify_Start_and_End_values_for_at_least_one_isolation_window);
                    gridIsolationWindows.Focus();
                    _gridViewDriver.EditCell();
                    return;
                }

                int?windowsPerScan = null;
                if (Equals(SpecialHandling, IsolationScheme.SpecialHandlingType.MULTIPLEXED))
                {
                    int x;
                    if (!helper.ValidateNumberTextBox(textWindowsPerScan,
                                                      IsolationScheme.MIN_MULTIPLEXED_ISOLATION_WINDOWS,
                                                      IsolationScheme.MAX_MULTIPLEXED_ISOLATION_WINDOWS,
                                                      out x))
                    {
                        return;
                    }
                    windowsPerScan = x;
                }
                // Check for overlap and gaps
                var          sortedWindowList = windowList.OrderBy(o => o.Start).ToList();
                bool         gapsOk           = false;
                bool         overlapsOk       = false;
                bool         overlap          = Overlap;
                int          increment        = overlap ? 2 : 1;
                int          subtraction      = overlap ? 3 : 1;
                const double tolerance        = 0.0001;
                for (int i = 0; i < sortedWindowList.Count - subtraction; i += increment)
                {
                    for (int j = 0; j < increment; j++)
                    {
                        IsolationWindow current = sortedWindowList.ElementAt(i + j);
                        IsolationWindow next    = sortedWindowList.ElementAt(i + j + increment);
                        if (!gapsOk && next.Start - current.End > tolerance)
                        {
                            if (MultiButtonMsgDlg.Show(this,
                                                       Resources
                                                       .EditIsolationSchemeDlg_OkDialog_There_are_gaps_in_a_single_cycle_of_your_extraction_windows__Do_you_want_to_continue_,
                                                       MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false) !=
                                DialogResult.Yes)
                            {
                                return;
                            }
                            gapsOk = true;
                        }
                        else if (!overlapsOk && current.End - next.Start > tolerance)
                        {
                            if (MultiButtonMsgDlg.Show(this,
                                                       Resources.EditIsolationSchemeDlgOkDialogThereAreOverlapsContinue,
                                                       MultiButtonMsgDlg.BUTTON_YES,
                                                       MultiButtonMsgDlg.BUTTON_NO, false) != DialogResult.Yes)
                            {
                                return;
                            }
                            overlapsOk = true;
                        }
                    }
                }
                try
                {
                    _isolationScheme = new IsolationScheme(name, windowList, SpecialHandling, windowsPerScan);
                }
                catch (InvalidDataException exception)
                {
                    MessageDlg.ShowException(this, exception);
                    return;
                }
            }

            DialogResult = DialogResult.OK;
        }
示例#3
0
        public void OkDialog()
        {
            IrtType irtType = GetIrtType();

            if (textCalculatorName.Text.Length == 0)
            {
                MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_Calculator_name_cannot_be_empty);
                return;
            }
            if (_existing.Select(spec => spec.Name).Contains(textCalculatorName.Text))
            {
                var replaceResult = MultiButtonMsgDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_A_calculator_with_that_name_already_exists___Do_you_want_to_replace_it_,
                                                           MultiButtonMsgDlg.BUTTON_YES,
                                                           MultiButtonMsgDlg.BUTTON_NO,
                                                           false);
                if (replaceResult == DialogResult.No)
                {
                    return;
                }
            }
            if (irtType == IrtType.existing)
            {
                try
                {
                    if (!File.Exists(textOpenDatabase.Text))
                    {
                        MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_iRT_database_field_must_contain_a_path_to_a_valid_file_);
                        textOpenDatabase.Focus();
                        return;
                    }
                    var db = IrtDb.GetIrtDb(textOpenDatabase.Text, null);
                    if (db == null)
                    {
                        throw new DatabaseOpeningException(string.Format(Resources.CreateIrtCalculatorDlg_OkDialog_Cannot_read_the_database_file__0_, textOpenDatabase.Text));
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(this, string.Format(Resources.CreateIrtCalculatorDlg_OkDialog_Failed_to_open_the_database_file___0_, x.Message), x);
                    return;
                }
            }
            else if (irtType == IrtType.separate_list)
            {
                if (textNewDatabase.Text.Length == 0)
                {
                    MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_iRT_database_field_must_not_be_empty_);
                    textNewDatabase.Focus();
                    return;
                }
                if (!CreateIrtDatabase(textNewDatabase.Text))
                {
                    return;
                }
            }
            else
            {
                if (textNewDatabaseProteins.Text.Length == 0)
                {
                    MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_iRT_database_field_must_not_be_empty_);
                    textNewDatabaseProteins.Focus();
                    return;
                }
                if (comboBoxProteins.SelectedIndex == -1)
                {
                    MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_Please_select_a_protein_containing_the_list_of_standard_peptides_for_the_iRT_calculator_);
                    comboBoxProteins.Focus();
                    return;
                }
                if (!CreateIrtDatabase(textNewDatabaseProteins.Text))
                {
                    return;
                }
            }
            // Make a version of the document with the new calculator in it
            var databaseFileName = irtType == IrtType.existing ? textOpenDatabase.Text :
                                   irtType == IrtType.separate_list ? textNewDatabase.Text :
                                   textNewDatabaseProteins.Text;
            var calculator = new RCalcIrt(textCalculatorName.Text, databaseFileName);
            // CONSIDER: Probably can't use just a static default like 10 below
            var retentionTimeRegression = new RetentionTimeRegression(calculator.Name, calculator, null, null, RetentionTimeRegression.DEFAULT_WINDOW, new List <MeasuredRetentionTime>());
            var docNew = Document.ChangeSettings(Document.Settings.ChangePeptidePrediction(prediction =>
                                                                                           prediction.ChangeRetentionTime(retentionTimeRegression)));

            // Import transition list of standards, if applicable
            if (irtType == IrtType.separate_list)
            {
                try
                {
                    if (!File.Exists(textImportText.Text))
                    {
                        MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_Transition_list_field_must_contain_a_path_to_a_valid_file_);
                        return;
                    }
                    IdentityPath selectPath;
                    List <MeasuredRetentionTime>     irtPeptides;
                    List <TransitionImportErrorInfo> errorList;
                    var inputs = new MassListInputs(textImportText.Text);
                    docNew = docNew.ImportMassList(inputs, null, out selectPath, out irtPeptides, out _librarySpectra, out errorList);
                    if (errorList.Any())
                    {
                        throw new InvalidDataException(errorList[0].ErrorMessage);
                    }
                    _dbIrtPeptides = irtPeptides.Select(rt => new DbIrtPeptide(rt.PeptideSequence, rt.RetentionTime, true, TimeSource.scan)).ToList();
                    IrtFile        = textImportText.Text;
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(this, string.Format(Resources.CreateIrtCalculatorDlg_OkDialog_Error_reading_iRT_standards_transition_list___0_, x.Message), x);
                    return;
                }
            }
            else if (irtType == IrtType.protein)
            {
                PeptideGroupDocNode selectedGroup = comboBoxProteins.SelectedItem as PeptideGroupDocNode;
// ReSharper disable PossibleNullReferenceException
                _irtPeptideSequences = new HashSet <Target>(selectedGroup.Peptides.Select(pep => pep.ModifiedTarget));
// ReSharper restore PossibleNullReferenceException
            }
            Document     = docNew;
            DialogResult = DialogResult.OK;
        }
示例#4
0
        private bool UpdateFullScanSettings()
        {
            var helper = new MessageBoxHelper(this);

            // Validate and store MS1 full-scan settings

            // If high resolution MS1 filtering is enabled, make sure precursor m/z type
            // is monoisotopic and isotope enrichments are set
            var precursorIsotopes     = FullScanSettingsControl.PrecursorIsotopesCurrent;
            var precursorAnalyzerType = FullScanSettingsControl.PrecursorMassAnalyzer;
            var precursorMassType     = TransitionSettings.Prediction.PrecursorMassType;

            if (precursorIsotopes == FullScanPrecursorIsotopes.None)
            {
                if (WorkflowType != Workflow.dia)
                {
                    MessageDlg.Show(this, Resources.ImportPeptideSearchDlg_UpdateFullScanSettings_Full_scan_MS1_filtering_must_be_enabled_in_order_to_import_a_peptide_search_);
                    return(false);
                }
                else if (FullScanSettingsControl.AcquisitionMethod == FullScanAcquisitionMethod.None)
                {
                    MessageDlg.Show(this, Resources.ImportPeptideSearchDlg_UpdateFullScanSettings_Full_scan_MS1_or_MS_MS_filtering_must_be_enabled_in_order_to_import_a_peptide_search_);
                    return(false);
                }
            }
            else if (precursorAnalyzerType != FullScanMassAnalyzerType.qit)
            {
                precursorMassType = MassType.Monoisotopic;
                if (FullScanSettingsControl.Enrichments == null)
                {
                    MessageDlg.Show(GetParentForm(this), Resources.TransitionSettingsUI_OkDialog_Isotope_enrichment_settings_are_required_for_MS1_filtering_on_high_resolution_mass_spectrometers);
                    return(false);
                }
            }

            if (FullScanSettingsControl.IsolationScheme == null && FullScanSettingsControl.AcquisitionMethod == FullScanAcquisitionMethod.DIA)
            {
                MessageDlg.Show(this, Resources.TransitionSettingsUI_OkDialog_An_isolation_scheme_is_required_to_match_multiple_precursors);
                return(false);
            }

            TransitionFilter filter = TransitionSettings.Filter;

            if (FullScanSettingsControl.PrecursorChargesTextBox.Visible)
            {
                Adduct[] precursorCharges;
                if (!TransitionSettingsControl.ValidateAdductListTextBox(helper, FullScanSettingsControl.PrecursorChargesTextBox, true, TransitionGroup.MIN_PRECURSOR_CHARGE, TransitionGroup.MAX_PRECURSOR_CHARGE, out precursorCharges))
                {
                    return(false);
                }
                precursorCharges = precursorCharges.Distinct().ToArray();
                filter           = TransitionSettings.Filter.ChangePeptidePrecursorCharges(precursorCharges);
            }
            if (WorkflowType == Workflow.dda && !filter.PeptideIonTypes.Contains(IonType.precursor))
            {
                filter = filter.ChangePeptideIonTypes(new[] { IonType.precursor });
            }
            if (!filter.AutoSelect)
            {
                filter = filter.ChangeAutoSelect(true);
            }
            Helpers.AssignIfEquals(ref filter, TransitionSettings.Filter);

            if (FullScanSettingsControl.IsDIA() && filter.ExclusionUseDIAWindow)
            {
                if (FullScanSettingsControl.IsolationScheme.IsAllIons)
                {
                    MessageDlg.Show(this, Resources.TransitionSettingsUI_OkDialog_Cannot_use_DIA_window_for_precusor_exclusion_when__All_Ions__is_selected_as_the_isolation_scheme___To_use_the_DIA_window_for_precusor_exclusion__change_the_isolation_scheme_in_the_Full_Scan_settings_);
                    return(false);
                }
                if (FullScanSettingsControl.IsolationScheme.FromResults)
                {
                    MessageDlg.Show(this, Resources.TransitionSettingsUI_OkDialog_Cannot_use_DIA_window_for_precursor_exclusion_when_isolation_scheme_does_not_contain_prespecified_windows___Please_select_an_isolation_scheme_with_prespecified_windows_);
                    return(false);
                }
            }

            TransitionFullScan fullScan;

            if (!FullScanSettingsControl.ValidateFullScanSettings(helper, out fullScan))
            {
                return(false);
            }

            Helpers.AssignIfEquals(ref fullScan, TransitionSettings.FullScan);

            var prediction = TransitionSettings.Prediction.ChangePrecursorMassType(precursorMassType);

            Helpers.AssignIfEquals(ref prediction, TransitionSettings.Prediction);

            TransitionSettings settings;

            try
            {
                settings = new TransitionSettings(prediction, filter,
                                                  TransitionSettings.Libraries, TransitionSettings.Integration, TransitionSettings.Instrument, fullScan);
            }
            catch (Exception x)
            {
                MessageDlg.Show(this, x.Message);
                return(false);
            }

            // Only update, if anything changed
            if (Equals(settings, TransitionSettings))
            {
                return(true);
            }

            if (SkylineWindow.ChangeSettings(SkylineWindow.DocumentUI.Settings.ChangeTransitionSettings(settings), true))
            {
                _fullScanSettingsChanged = true;
                return(true);
            }

            return(false);
        }
示例#5
0
        private bool AddIrtLibraryTable(string path, IrtStandard standard)
        {
            if (!ImportPeptideSearch.HasDocLib || !ImportPeptideSearch.DocLib.IsLoaded)
            {
                return(false);
            }

            var lib = ImportPeptideSearch.DocLib;

            ProcessedIrtAverages processed = null;

            using (var longWait = new LongWaitDlg
            {
                Text = Resources.BuildPeptideSearchLibraryControl_AddIrtLibraryTable_Processing_Retention_Times
            })
            {
                try
                {
                    var status = longWait.PerformWork(WizardForm, 800, monitor =>
                    {
                        var irtProviders = lib.RetentionTimeProvidersIrt.ToArray();
                        if (!irtProviders.Any())
                        {
                            irtProviders = lib.RetentionTimeProviders.ToArray();
                        }
                        processed = RCalcIrt.ProcessRetentionTimes(monitor, irtProviders, irtProviders.Length, standard.Peptides.ToArray(), new DbIrtPeptide[0]);
                    });
                    if (status.IsError)
                    {
                        throw status.ErrorException;
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(WizardForm,
                                                 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(this) != DialogResult.OK)
                {
                    return(false);
                }
            }

            var recalibrate = false;

            if (processed.CanRecalibrateStandards(standard.Peptides))
            {
                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))
                {
                    if (dlg.ShowDialog(WizardForm) == DialogResult.Yes)
                    {
                        recalibrate = true;
                    }
                }
            }

            using (var longWait = new LongWaitDlg
            {
                Text = Resources.BuildPeptideSearchLibraryControl_AddIrtLibraryTable_Adding_iRTs_to_Library
            })
            {
                try
                {
                    ImmutableList <DbIrtPeptide> newStandards = null;
                    var status = longWait.PerformWork(WizardForm, 800, monitor =>
                    {
                        if (recalibrate)
                        {
                            monitor.UpdateProgress(new ProgressStatus().ChangeSegments(0, 2));
                            newStandards = ImmutableList.ValueOf(processed.RecalibrateStandards(standard.Peptides));
                            processed    = RCalcIrt.ProcessRetentionTimes(
                                monitor, processed.ProviderData.Select(data => data.Value.RetentionTimeProvider),
                                processed.ProviderData.Count, newStandards.ToArray(), new DbIrtPeptide[0]);
                        }
                        var irtDb = IrtDb.CreateIrtDb(path);
                        irtDb.AddPeptides(monitor, (newStandards ?? standard.Peptides).Concat(processed.DbIrtPeptides).ToList());
                    });
                    if (status.IsError)
                    {
                        throw status.ErrorException;
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(WizardForm,
                                                 TextUtil.LineSeparate(Resources.BuildPeptideSearchLibraryControl_AddIrtLibraryTable_An_error_occurred_trying_to_add_iRTs_to_the_library_, x.Message), x);
                    return(false);
                }
            }
            return(true);
        }
示例#6
0
        private void updateCheck_Complete(object sender, RunWorkerCompletedEventArgs e)
        {
            var exTrust = e.Result as TrustNotGrantedException;

            if (exTrust != null)
            {
                if (ShowUpgradeForm(AppDeployment.GetVersionFromUpdateLocation(), false, true))
                {
                    AppDeployment.OpenInstallLink(ParentWindow);
                }
                return;
            }
            var ex = e.Result as Exception;

            if (ex != null)
            {
                // Show an error message box to allow a user to inspect the exception stack trace
                MessageDlg.ShowWithException(ParentWindow,
                                             Resources.UpgradeManager_updateCheck_Complete_Failed_attempting_to_check_for_an_upgrade_, ex);
                // Show no upgrade found message to allow a user to turn off or on this checking
                ShowUpgradeForm(null, false, false);
                return;
            }
            _updateInfo = e.Result as UpdateCheckDetails;
            if (_updateInfo != null && _updateInfo.UpdateAvailable)
            {
                if (!ShowUpgradeForm(_updateInfo.AvailableVersion, true, true))
                {
                    return;
                }

                using (var longWaitUpdate = new LongWaitDlg
                {
                    Text = string.Format(Resources.UpgradeManager_updateCheck_Complete_Upgrading__0_, Program.Name),
                    Message = GetProgressMessage(0, _updateInfo.UpdateSizeBytes ?? 0),
                    ProgressValue = 0
                })
                {
                    longWaitUpdate.PerformWork(ParentWindow, 500, broker =>
                    {
                        BeginUpdate(broker);
                        _endUpdateEvent.WaitOne();
                        _endUpdateEvent.Dispose();
                        broker.ProgressValue = 100;
                    });
                }
                if (_completeArgs == null || _completeArgs.Cancelled)
                {
                    return;
                }

                if (_completeArgs.Error != null)
                {
                    MessageDlg.ShowWithException(ParentWindow,
                                                 Resources.UpgradeManager_updateCheck_Complete_Failed_attempting_to_upgrade_, _completeArgs.Error);
                    if (ShowUpgradeForm(null, false, true))
                    {
                        AppDeployment.OpenInstallLink(ParentWindow);
                    }
                    return;
                }

                AppDeployment.Restart();
            }
            else if (!_startup)
            {
                ShowUpgradeForm(null, false, false);
            }
        }
示例#7
0
        public static bool AddIrts(Library lib, LibrarySpec libSpec, IrtStandard standard, Control parent, bool useTopMostForm = false)
        {
            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 cirtPeptides = new DbIrtPeptide[0];

            using (var longWait = new LongWaitDlg {
                Text = Resources.LibraryBuildNotificationHandler_AddIrts_Loading_retention_time_providers
            })
            {
                var status = longWait.PerformWork(GetParent(), 800, monitor =>
                {
                    monitor.UpdateProgress(new ProgressStatus().ChangePercentComplete(-1));
                    irtProviders = lib.RetentionTimeProvidersIrt.ToArray();
                    if (!irtProviders.Any())
                    {
                        irtProviders = lib.RetentionTimeProviders.ToArray();
                    }

                    if (ReferenceEquals(standard, IrtStandard.CIRT_SHORT))
                    {
                        var libPeptides = irtProviders.SelectMany(provider => provider.PeptideRetentionTimes).Select(rt => rt.PeptideSequence).ToHashSet();
                        cirtPeptides    = IrtStandard.CIRT.Peptides.Where(pep => libPeptides.Contains(pep.ModifiedTarget)).ToArray();
                    }
                });
                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;
                }
            }

            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 = !numCirt.HasValue
                            ? RCalcIrt.ProcessRetentionTimes(monitor, irtProviders, standardPeptides, new DbIrtPeptide[0])
                            : RCalcIrt.ProcessRetentionTimesCirt(monitor, irtProviders, cirtPeptides, numCirt.Value, out standardPeptides);
                    });
                    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;
                }
            }

            var processedDbIrtPeptides = processed.DbIrtPeptides.ToArray();

            if (!processedDbIrtPeptides.Any())
            {
                return(false);
            }

            using (var longWait = new LongWaitDlg {
                Text = Resources.LibraryBuildNotificationHandler_AddIrts_Adding_iRTs_to_library
            })
            {
                try
                {
                    DbIrtPeptide[] newStandards = null;
                    var            status       = longWait.PerformWork(GetParent(), 800, monitor =>
                    {
                        if (recalibrate)
                        {
                            monitor.UpdateProgress(new ProgressStatus().ChangeSegments(0, 2));
                            newStandards = processed.RecalibrateStandards(standardPeptides).ToArray();
                            processed    = RCalcIrt.ProcessRetentionTimes(monitor,
                                                                          processed.ProviderData.Select(data => data.RetentionTimeProvider).ToArray(),
                                                                          newStandards.ToArray(), new DbIrtPeptide[0]);
                        }
                        var irtDb = IrtDb.CreateIrtDb(libSpec.FilePath);
                        irtDb.AddPeptides(monitor, (newStandards ?? standardPeptides).Concat(processed.DbIrtPeptides).ToList());
                    });
                    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);
        }
示例#8
0
        private void SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold(int threshold, UniquenessType uniqueBy)
        {
            dataGridView1.EndEdit();
            var dubious = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            for (int rowIndex = 0; rowIndex < dataGridView1.Rows.Count; rowIndex++)
            {
                var row        = dataGridView1.Rows[rowIndex];
                var rowTag     = (Tuple <IdentityPath, PeptideDocNode>)row.Tag;
                int matchCount = _peptidesInBackgroundProteome.Contains(rowTag.Item1) ? 1 : 0;
                for (int col = 0; col < dataGridView1.ColumnCount; col++)
                {
                    if (col == PeptideIncludedColumn.Index || col == PeptideColumn.Index)
                    {
                        continue;
                    }

                    if (row.Cells[col].Value is bool && ((bool)row.Cells[col].Value))
                    {
                        if (uniqueBy == UniquenessType.protein)
                        {
                            matchCount++;
                        }
                        else
                        {
                            var    peptide = rowTag.Item2;
                            var    parent  = PeptideGroupDocNodes.First(p => p.Children.Contains(peptide));
                            string testValA;
                            string testValB;
                            // ATP5B and atp5b are the same thing, as are "mus musculus" and "MUS MUSCULUS"
                            if (uniqueBy == UniquenessType.gene)
                            {
                                // ReSharper disable once PossibleNullReferenceException
                                testValA = parent.ProteinMetadata.Gene;
                                testValB = ((ProteinColumn)dataGridView1.Columns[col].Tag).Protein.Gene;
                            }
                            else
                            {
                                // ReSharper disable once PossibleNullReferenceException
                                testValA = parent.ProteinMetadata.Species;
                                testValB = ((ProteinColumn)dataGridView1.Columns[col].Tag).Protein.Species;
                            }
                            // Can't filter on something that isn't there - require nonempty values
                            if (!string.IsNullOrEmpty(testValA) && !string.IsNullOrEmpty(testValB) &&
                                string.Compare(testValA, testValB, StringComparison.OrdinalIgnoreCase) != 0)
                            {
                                matchCount++;
                            }
                            if (string.IsNullOrEmpty(testValA))
                            {
                                dubious.Add(parent.Name);
                            }
                            if (string.IsNullOrEmpty(testValB))
                            {
                                dubious.Add(((ProteinColumn)dataGridView1.Columns[col].Tag).Protein.Name);
                            }
                        }
                    }
                    if (matchCount > threshold)
                    {
                        break;
                    }
                }
                row.Cells[PeptideIncludedColumn.Name].Value = (matchCount <= threshold);
            }
            SetCheckBoxPeptideIncludedHeaderState();
            if (dubious.Any())
            {
                var dubiousValues = TextUtil.LineSeparate(uniqueBy == UniquenessType.gene ?
                                                          Resources.UniquePeptidesDlg_SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold_Some_background_proteome_proteins_did_not_have_gene_information__this_selection_may_be_suspect_ :
                                                          Resources.UniquePeptidesDlg_SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold_Some_background_proteome_proteins_did_not_have_species_information__this_selection_may_be_suspect_,
                                                          Resources.UniquePeptidesDlg_SelectPeptidesWithNumberOfMatchesAtOrBelowThreshold_These_proteins_include_,
                                                          TextUtil.LineSeparate(dubious)); // Not L10N
                MessageDlg.Show(this, dubiousValues);
            }
        }
示例#9
0
        public void OkDialog()
        {
            var helper = new MessageBoxHelper(this);

            string name;

            if (!helper.ValidateNameTextBox(_editing ? (Control)textName : comboMod, out name))
            {
                return;
            }

            // Allow updating the original modification
            if (!_editing || !Equals(name, Modification.Name))
            {
                if (!ModNameAvailable(name))
                {
                    helper.ShowTextBoxError(_editing ? (Control)textName : comboMod,
                                            Resources.EditStaticModDlg_OkDialog_The_modification__0__already_exists, name);
                    return;
                }
            }

            string aas = comboAA.Text;

            if (string.IsNullOrEmpty(aas))
            {
                aas = null;
            }
            else
            {
                // Use the cleanest possible format.
                var sb = new StringBuilder();
                foreach (string aaPart in aas.Split(SEPARATOR_AA))
                {
                    string aa = aaPart.Trim();
                    if (aa.Length == 0)
                    {
                        continue;
                    }
                    if (sb.Length > 0)
                    {
                        sb.Append(@", ");
                    }
                    sb.Append(aa);
                }
            }

            string      termString = comboTerm.SelectedItem.ToString();
            ModTerminus?term       = null;

            if (!string.IsNullOrEmpty(termString))
            {
                term = (ModTerminus)Enum.Parse(typeof(ModTerminus), termString);
            }

            if (cbVariableMod.Checked && aas == null && term == null)
            {
                MessageDlg.Show(this, Resources.EditStaticModDlg_OkDialog_Variable_modifications_must_specify_amino_acid_or_terminus);
                comboAA.Focus();
                return;
            }

            string     formula    = null;
            double?    monoMass   = null;
            double?    avgMass    = null;
            LabelAtoms labelAtoms = LabelAtoms.None;

            if (cbChemicalFormula.Checked)
            {
                formula = Formula;
            }
            else
            {
                labelAtoms = LabelAtoms;
            }

            // Get the losses to know whether any exist below
            IList <FragmentLoss> losses = null;

            if (listNeutralLosses.Items.Count > 0)
            {
                losses = Losses.ToArray();
            }

            if (!string.IsNullOrEmpty(formula))
            {
                try
                {
                    SequenceMassCalc.FormulaMass(BioMassCalc.MONOISOTOPIC, formula, SequenceMassCalc.MassPrecision);
                }
                catch (ArgumentException x)
                {
                    _formulaBox.ShowTextBoxErrorFormula(helper, x.Message);
                    return;
                }
            }
            else if (labelAtoms == LabelAtoms.None)
            {
                formula = null;

                // Allow formula and both masses to be empty, if losses are present
                if (NotZero(_formulaBox.MonoMass) || NotZero(_formulaBox.AverageMass) || losses == null)
                {
                    // TODO: Maximum and minimum masses should be formalized and applied everywhere
                    double mass;
                    if (!_formulaBox.ValidateMonoText(helper, -1500, 5000, out mass))
                    {
                        return;
                    }
                    monoMass = mass;
                    if (!_formulaBox.ValidateAverageText(helper, -1500, 5000, out mass))
                    {
                        return;
                    }
                    avgMass = mass;
                }
                // Loss-only modifications may not be variable
                else if (cbVariableMod.Checked)
                {
                    MessageDlg.Show(this, Resources.EditStaticModDlg_OkDialog_The_variable_checkbox_only_applies_to_precursor_modification_Product_ion_losses_are_inherently_variable);
                    cbVariableMod.Focus();
                    return;
                }
            }
            else if (aas == null && term.HasValue)
            {
                MessageDlg.Show(this, Resources.EditStaticModDlg_OkDialog_Labeled_atoms_on_terminal_modification_are_not_valid);
                return;
            }

            RelativeRT relativeRT = RelativeRT.Matching;

            if (comboRelativeRT.Visible && comboRelativeRT.SelectedItem != null)
            {
                relativeRT = RelativeRTExtension.GetEnum(comboRelativeRT.SelectedItem.ToString());
            }

            // Store state of the chemical formula checkbox for next use.
            if (cbChemicalFormula.Visible)
            {
                Settings.Default.ShowHeavyFormula = _formulaBox.FormulaVisible;
            }

            var newMod = new StaticMod(name,
                                       aas,
                                       term,
                                       cbVariableMod.Checked,
                                       formula,
                                       labelAtoms,
                                       relativeRT,
                                       monoMass,
                                       avgMass,
                                       losses);

            foreach (StaticMod mod in _existing)
            {
                if (newMod.Equivalent(mod) && !(_editing && mod.Equals(_originalModification)))
                {
                    if (DialogResult.OK == MultiButtonMsgDlg.Show(
                            this,
                            TextUtil.LineSeparate(Resources.EditStaticModDlg_OkDialog_There_is_an_existing_modification_with_the_same_settings,
                                                  string.Format(@"'{0}'.", mod.Name),
                                                  string.Empty,
                                                  Resources.EditStaticModDlg_OkDialog_Continue),
                            MultiButtonMsgDlg.BUTTON_OK))
                    {
                        Modification = newMod;
                        DialogResult = DialogResult.OK;
                    }
                    return;
                }
            }

            var uniMod = UniMod.GetModification(name, IsStructural);

            // If the modification name is not found in Unimod, check if there exists a modification in Unimod that matches
            // the dialog modification, and prompt the user to to use the Unimod modification instead.
            if (uniMod == null)
            {
                var matchingMod = UniMod.FindMatchingStaticMod(newMod, IsStructural);
                if (matchingMod != null &&
                    (ModNameAvailable(matchingMod.Name) ||
                     (_editing && Equals(matchingMod.Name, Modification.Name))))
                {
                    var result = MultiButtonMsgDlg.Show(
                        this,
                        TextUtil.LineSeparate(Resources.EditStaticModDlg_OkDialog_There_is_a_Unimod_modification_with_the_same_settings,
                                              string.Empty,
                                              string.Format(Resources.EditStaticModDlg_OkDialog_Click__Unimod__to_use_the_name___0___, matchingMod.Name),
                                              string.Format(Resources.EditStaticModDlg_OkDialog_Click__Custom__to_use_the_name___0___, name)),
                        Resources.EditStaticModDlg_OkDialog_Unimod,
                        Resources.EditStaticModDlg_OkDialog_Custom,
                        true);
                    if (result == DialogResult.Yes)
                    {
                        newMod = matchingMod.MatchVariableAndLossInclusion(newMod);   // Unimod
                    }
                    if (result == DialogResult.Cancel)
                    {
                        return;
                    }
                }
            }
            else
            {
                // If the dialog modification matches the modification of the same name in Unimod,
                // use the UnimodId.
                if (newMod.Equivalent(uniMod))
                {
                    newMod = uniMod.MatchVariableAndLossInclusion(newMod);
                }
                else
                {
                    // Finally, if the modification name is found in Unimod, but the modification in Unimod does not
                    // match the dialog modification, prompt the user to use the Unimod modification definition instead.
                    if (DialogResult.OK != MultiButtonMsgDlg.Show(
                            this,
                            TextUtil.LineSeparate(string.Format(Resources.EditStaticModDlg_OkDialog_This_modification_does_not_match_the_Unimod_specifications_for___0___, name),
                                                  string.Empty,
                                                  Resources.EditStaticModDlg_OkDialog_Use_non_standard_settings_for_this_name),
                            MultiButtonMsgDlg.BUTTON_OK))
                    {
                        return;
                    }
                }
            }

            _modification = newMod;

            DialogResult = DialogResult.OK;
        }
示例#10
0
        public void OkDialog()
        {
            if (string.IsNullOrEmpty(textName.Text))
            {
                MessageDlg.Show(this, Resources.EditOptimizationLibraryDlg_OkDialog_Please_enter_a_name_for_the_optimization_library_);
                textName.Focus();
                return;
            }

            if (_existing != null)
            {
                foreach (var existing in _existing)
                {
                    if (Equals(existing.Name, textName.Text) && !Equals(existing.Name, _editingName))
                    {
                        if (MessageBox.Show(this, string.Format(Resources.EditOptimizationLibraryDlg_OkDialog_A_library_with_the_name__0__already_exists__Do_you_want_to_overwrite_it_,
                                                                textName.Text),
                                            Program.Name, MessageBoxButtons.YesNo) != DialogResult.Yes)
                        {
                            textName.Focus();
                            return;
                        }
                    }
                }
            }

            string message;

            if (string.IsNullOrEmpty(textDatabase.Text))
            {
                message = TextUtil.LineSeparate(Resources.EditOptimizationLibraryDlg_OkDialog_Please_choose_a_library_file_for_the_optimization_library_,
                                                Resources.EditOptimizationLibraryDlg_OkDialog_Click_the_Create_button_to_create_a_new_library_or_the_Open_button_to_open_an_existing_library_file_);
                MessageDlg.Show(this, message);
                textDatabase.Focus();
                return;
            }
            string path = Path.GetFullPath(textDatabase.Text);

            if (!Equals(path, textDatabase.Text))
            {
                message = TextUtil.LineSeparate(Resources.EditOptimizationLibraryDlg_OkDialog_Please_use_a_full_path_to_a_library_file_for_the_optimization_library_,
                                                Resources.EditOptimizationLibraryDlg_OkDialog_Click_the_Create_button_to_create_a_new_library_or_the_Open_button_to_open_an_existing_library_file_);
                MessageDlg.Show(this, message);
                textDatabase.Focus();
                return;
            }
            if (!string.Equals(Path.GetExtension(path), OptimizationDb.EXT))
            {
                path += OptimizationDb.EXT;
            }

            if (!ValidateOptimizationList(LibraryOptimizations, Resources.EditOptimizationLibraryDlg_OkDialog_library))
            {
                gridViewLibrary.Focus();
                return;
            }

            try
            {
                var library = new OptimizationLibrary(textName.Text, path);

                OptimizationDb db = File.Exists(path)
                               ? OptimizationDb.GetOptimizationDb(path, null, _document)
                               : OptimizationDb.CreateOptimizationDb(path);

                db = db.UpdateOptimizations(LibraryOptimizations.ToArray(), _original ?? new DbOptimization[0]);

                Library = library.ChangeDatabase(db);
            }
            catch (OptimizationsOpeningException x)
            {
                MessageDlg.ShowException(this, x);
                textDatabase.Focus();
                return;
            }
            catch (StaleStateException)
            {
                // CONSIDER: Not sure if this is the right thing to do.  It would
                //           be nice to solve whatever is causing this, but this is
                //           better than showing an unexpected error form with stack trace.
                MessageDlg.Show(this, Resources.EditOptimizationLibraryDlg_OkDialog_Failure_updating_optimizations_in_the_optimization_library__The_database_may_be_out_of_synch_);
                return;
            }

            DialogResult = DialogResult.OK;
        }
示例#11
0
        public void OkDialog()
        {
            bool isModel = radioButtonModel.Checked;

            if (isModel)
            {
                var model = _driverPeakScoringModel.SelectedItem;
                if (model == null)
                {
                    MessageDlg.Show(this, Resources.PeakBoundaryCompareTest_DoTest_Must_select_a_model_for_comparison_);
                    return;
                }
                if (!model.IsTrained)
                {
                    MessageDlg.Show(this, Resources.AddPeakCompareDlg_OkDialog_Model_must_be_trained_before_it_can_be_used_for_peak_boundary_comparison_);
                    return;
                }
                BoundaryComparer = new ComparePeakBoundaries(model);
            }
            else
            {
                string displayName = textName.Text;
                if (displayName.Length == 0)
                {
                    MessageDlg.Show(this, Resources.AddPeakCompareDlg_OkDialog_Comparison_name_cannot_be_empty_);
                    return;
                }
                string filePath = textFilePath.Text;
                if (filePath.Length == 0)
                {
                    MessageDlg.Show(this, Resources.AddPeakCompareDlg_OkDialog_File_path_cannot_be_empty_);
                    return;
                }
                if (!File.Exists(filePath))
                {
                    MessageDlg.Show(this, Resources.AddPeakCompareDlg_OkDialog_File_path_field_must_contain_a_path_to_a_valid_file_);
                    return;
                }
                BoundaryComparer = new ComparePeakBoundaries(displayName, filePath);
            }
            var compNames = _existing.Select(comp => comp.Name);

            if (compNames.Contains(BoundaryComparer.Name) && (_current == null || _current.Name != BoundaryComparer.Name))
            {
                var message = isModel
                    ? Resources.AddPeakCompareDlg_OkDialog_The_selected_model_is_already_included_in_the_list_of_comparisons__Please_choose_another_model_
                    : Resources.AddPeakCompareDlg_OkDialog_There_is_already_an_imported_file_with_the_current_name___Please_choose_another_name;
                MessageDlg.Show(this, message);
                return;
            }
            using (var longWaitDlg = new LongWaitDlg
            {
                Text = isModel ? Resources.AddPeakCompareDlg_OkDialog_Comparing_Models : Resources.AddPeakCompareDlg_OkDialog_Comparing_Imported_Files
            })
            {
                try
                {
                    longWaitDlg.PerformWork(this, 1000, pm => BoundaryComparer.GenerateComparison(Document, pm));
                    if (longWaitDlg.IsCanceled)
                    {
                        return;
                    }

                    if (BoundaryComparer.Matches.Count == 0)
                    {
                        throw new IOException(Resources.AddPeakCompareDlg_OkDialog_Document_has_no_eligible_chromatograms_for_analysis___Valid_chromatograms_must_not_be_decoys_or_iRT_standards_);
                    }
                    if (BoundaryComparer.Matches.All(match => match.IsMissingPickedPeak))
                    {
                        throw new IOException(Resources.AddPeakCompareDlg_OkDialog_The_selected_file_or_model_does_not_assign_peak_boundaries_to_any_chromatograms_in_the_document___Please_select_a_different_model_or_file_);
                    }
                    if (BoundaryComparer.HasNoQValues && BoundaryComparer.HasNoScores)
                    {
                        throw new IOException(Resources.AddPeakCompareDlg_OkDialog_The_current_file_or_model_has_no_q_values_or_scores_to_analyze___Either_q_values_or_scores_are_necessary_to_compare_peak_picking_tools_);
                    }
                    if (BoundaryComparer.CountMissing > 0)
                    {
                        var missingMessage = string.Format(Resources.AddPeakCompareDlg_OkDialog_The_imported_file_does_not_contain_any_peak_boundaries_for__0__transition_group___file_pairs___These_chromatograms_will_be_treated_as_if_no_boundary_was_selected_,
                                                           BoundaryComparer.CountMissing);
                        var dlgMissing = MultiButtonMsgDlg.Show(this, missingMessage, MultiButtonMsgDlg.BUTTON_OK);
                        if (dlgMissing == DialogResult.Cancel)
                        {
                            return;
                        }
                    }
                    // Show a warning message and give a chance to cancel, if there are unrecognized peptides
                    if (BoundaryComparer.Importer != null && !BoundaryComparer.Importer.UnrecognizedPeptidesCancel(this))
                    {
                        return;
                    }
                }
                catch (Exception x)
                {
                    string initMessage = isModel
                        ? Resources.AddPeakCompareDlg_OkDialog_Error_comparing_model_peak_boundaries___0_
                        : Resources.AddPeakCompareDlg_OkDialog_Error_applying_imported_peak_boundaries___0_;
                    MessageDlg.ShowWithException(this, string.Format(initMessage, x.Message), x);
                    return;
                }
            }
            DialogResult = DialogResult.OK;
        }
示例#12
0
        public void OkDialog()
        {
            var helper = new MessageBoxHelper(this);

            // Validate and store prediction settings
            string   massType          = comboPrecursorMass.SelectedItem.ToString();
            MassType precursorMassType = MassTypeExtension.GetEnum(massType);

            massType = comboIonMass.SelectedItem.ToString();
            MassType fragmentMassType = MassTypeExtension.GetEnum(massType);
            string   nameCE           = comboCollisionEnergy.SelectedItem.ToString();
            CollisionEnergyRegression collisionEnergy =
                Settings.Default.GetCollisionEnergyByName(nameCE);
            string nameDP = comboDeclusterPotential.SelectedItem.ToString();
            DeclusteringPotentialRegression declusteringPotential =
                Settings.Default.GetDeclusterPotentialByName(nameDP);
            string nameCoV = comboCompensationVoltage.SelectedItem.ToString();
            CompensationVoltageParameters compensationVoltage =
                Settings.Default.GetCompensationVoltageByName(nameCoV);
            string nameOptLib = comboOptimizationLibrary.SelectedItem.ToString();
            OptimizationLibrary optimizationLibrary =
                Settings.Default.GetOptimizationLibraryByName(nameOptLib);
            OptimizedMethodType optimizedMethodType = OptimizedMethodType.None;

            if (cbUseOptimized.Checked)
            {
                optimizedMethodType = OptimizedMethodTypeExtension.GetEnum(comboOptimizeType.SelectedItem.ToString());
            }
            TransitionPrediction prediction = new TransitionPrediction(precursorMassType,
                                                                       fragmentMassType, collisionEnergy,
                                                                       declusteringPotential,
                                                                       compensationVoltage,
                                                                       optimizationLibrary,
                                                                       optimizedMethodType);

            Helpers.AssignIfEquals(ref prediction, Prediction);

            // Validate and store filter settings
            int[] precursorCharges;
            int   min = TransitionGroup.MIN_PRECURSOR_CHARGE;
            int   max = TransitionGroup.MAX_PRECURSOR_CHARGE;

            if (!helper.ValidateNumberListTextBox(tabControl1, (int)TABS.Filter, textPrecursorCharges,
                                                  min, max, out precursorCharges))
            {
                return;
            }
            precursorCharges = precursorCharges.Distinct().ToArray();

            int[] productCharges;
            min = Transition.MIN_PRODUCT_CHARGE;
            max = Transition.MAX_PRODUCT_CHARGE;
            if (!helper.ValidateNumberListTextBox(tabControl1, (int)TABS.Filter, textIonCharges,
                                                  min, max, out productCharges))
            {
                return;
            }
            productCharges = productCharges.Distinct().ToArray();

            IonType[] types = TransitionFilter.ParseTypes(textIonTypes.Text, new IonType[0]);
            if (types.Length == 0)
            {
                helper.ShowTextBoxError(tabControl1, (int)TABS.Filter, textIonTypes,
                                        Resources.TransitionSettingsUI_OkDialog_Ion_types_must_contain_a_comma_separated_list_of_ion_types_a_b_c_x_y_z_and_p_for_precursor);
                return;
            }
            types = types.Distinct().ToArray();

            double exclusionWindow = 0;

            if (!string.IsNullOrEmpty(textExclusionWindow.Text) &&
                !Equals(textExclusionWindow.Text, exclusionWindow.ToString(LocalizationHelper.CurrentCulture)))
            {
                if (!helper.ValidateDecimalTextBox(tabControl1, (int)TABS.Filter, textExclusionWindow,
                                                   TransitionFilter.MIN_EXCLUSION_WINDOW, TransitionFilter.MAX_EXCLUSION_WINDOW, out exclusionWindow))
                {
                    return;
                }
            }

            string fragmentRangeFirst = TransitionFilter.GetStartFragmentNameFromLabel(comboRangeFrom.SelectedItem.ToString());
            string fragmentRangeLast  = TransitionFilter.GetEndFragmentNameFromLabel(comboRangeTo.SelectedItem.ToString());

            var  measuredIons          = _driverIons.Chosen;
            bool autoSelect            = cbAutoSelect.Checked;
            bool exclusionUseDIAWindow = FullScanSettingsControl.IsDIA() && cbExclusionUseDIAWindow.Checked;
            var  filter = new TransitionFilter(precursorCharges, productCharges, types,
                                               fragmentRangeFirst, fragmentRangeLast, measuredIons,
                                               exclusionWindow, exclusionUseDIAWindow, autoSelect);

            Helpers.AssignIfEquals(ref filter, Filter);

            // Validate and store library settings
            TransitionLibraryPick pick = TransitionLibraryPick.none;

            if (cbLibraryPick.Checked)
            {
                if (radioAll.Checked)
                {
                    pick = TransitionLibraryPick.all;
                }
                else if (radioAllAndFiltered.Checked)
                {
                    pick = TransitionLibraryPick.all_plus;
                }
                else
                {
                    pick = TransitionLibraryPick.filter;
                }
            }

            double ionMatchTolerance;

            double minTol = TransitionLibraries.MIN_MATCH_TOLERANCE;
            double maxTol = TransitionLibraries.MAX_MATCH_TOLERANCE;

            if (!helper.ValidateDecimalTextBox(tabControl1, (int)TABS.Library, textTolerance,
                                               minTol, maxTol, out ionMatchTolerance))
            {
                return;
            }

            int ionCount = Libraries.IonCount;

            if (pick != TransitionLibraryPick.none)
            {
                min = TransitionLibraries.MIN_ION_COUNT;
                max = TransitionLibraries.MAX_ION_COUNT;
                if (!helper.ValidateNumberTextBox(tabControl1, (int)TABS.Library, textIonCount,
                                                  min, max, out ionCount))
                {
                    return;
                }
            }

            TransitionLibraries libraries = new TransitionLibraries(ionMatchTolerance, ionCount, pick);

            Helpers.AssignIfEquals(ref libraries, Libraries);

            // This dialog does not yet change integration settings
            TransitionIntegration integration = _transitionSettings.Integration;

            // Validate and store instrument settings
            int minMz;

            min = TransitionInstrument.MIN_MEASUREABLE_MZ;
            max = TransitionInstrument.MAX_MEASURABLE_MZ - TransitionInstrument.MIN_MZ_RANGE;
            if (!helper.ValidateNumberTextBox(tabControl1, (int)TABS.Instrument, textMinMz, min, max, out minMz))
            {
                return;
            }
            int maxMz;

            min = minMz + TransitionInstrument.MIN_MZ_RANGE;
            max = TransitionInstrument.MAX_MEASURABLE_MZ;
            if (!helper.ValidateNumberTextBox(tabControl1, (int)TABS.Instrument, textMaxMz, min, max, out maxMz))
            {
                return;
            }
            bool   isDynamicMin = cbDynamicMinimum.Checked;
            double mzMatchTolerance;

            minTol = TransitionInstrument.MIN_MZ_MATCH_TOLERANCE;
            maxTol = TransitionInstrument.MAX_MZ_MATCH_TOLERANCE;
            if (!helper.ValidateDecimalTextBox(tabControl1, (int)TABS.Instrument, textMzMatchTolerance,
                                               minTol, maxTol, out mzMatchTolerance))
            {
                return;
            }
            int?maxTrans = null;

            if (!string.IsNullOrEmpty(textMaxTrans.Text))
            {
                int maxTransTemp;
                min = TransitionInstrument.MIN_TRANSITION_MAX;
                max = TransitionInstrument.MAX_TRANSITION_MAX;
                if (!helper.ValidateNumberTextBox(tabControl1, (int)TABS.Instrument, textMaxTrans,
                                                  min, max, out maxTransTemp))
                {
                    return;
                }
                maxTrans = maxTransTemp;
            }
            int?maxInclusions = null;

            if (!string.IsNullOrEmpty(textMaxInclusions.Text))
            {
                int maxInclusionsTemp;
                min = TransitionInstrument.MIN_INCLUSION_MAX;
                max = TransitionInstrument.MAX_INCLUSION_MAX;
                if (!helper.ValidateNumberTextBox(tabControl1, (int)TABS.Instrument, textMaxInclusions,
                                                  min, max, out maxInclusionsTemp))
                {
                    return;
                }
                maxInclusions = maxInclusionsTemp;
            }
            int?minTime = null, maxTime = null;

            min = TransitionInstrument.MIN_TIME;
            max = TransitionInstrument.MAX_TIME;
            if (!string.IsNullOrEmpty(textMinTime.Text))
            {
                int minTimeTemp;
                if (!helper.ValidateNumberTextBox(tabControl1, (int)TABS.Instrument, textMinTime,
                                                  min, max, out minTimeTemp))
                {
                    return;
                }
                minTime = minTimeTemp;
            }
            if (!string.IsNullOrEmpty(textMaxTime.Text))
            {
                int maxTimeTemp;
                if (!helper.ValidateNumberTextBox(tabControl1, (int)TABS.Instrument, textMaxTime,
                                                  min, max, out maxTimeTemp))
                {
                    return;
                }
                maxTime = maxTimeTemp;
            }
            if (minTime.HasValue && maxTime.HasValue && maxTime.Value - minTime.Value < TransitionInstrument.MIN_TIME_RANGE)
            {
                helper.ShowTextBoxError(tabControl1, (int)TABS.Instrument, textMaxTime,
                                        string.Format(Resources.TransitionSettingsUI_OkDialog_The_allowable_retention_time_range__0__to__1__must_be_at_least__2__minutes_apart,
                                                      minTime, maxTime, TransitionInstrument.MIN_TIME_RANGE));
                return;
            }

            TransitionInstrument instrument = new TransitionInstrument(minMz,
                                                                       maxMz, isDynamicMin, mzMatchTolerance, maxTrans, maxInclusions, minTime, maxTime);

            Helpers.AssignIfEquals(ref instrument, Instrument);

            // Validate and store full-scan settings

            // If high resolution MS1 filtering is enabled, make sure precursor m/z type
            // is monoisotopic and isotope enrichments are set
            FullScanPrecursorIsotopes precursorIsotopes = PrecursorIsotopesCurrent;
            FullScanMassAnalyzerType  precursorAnalyzerType = PrecursorMassAnalyzer;

            if (precursorIsotopes != FullScanPrecursorIsotopes.None &&
                precursorAnalyzerType != FullScanMassAnalyzerType.qit)
            {
                if (precursorMassType != MassType.Monoisotopic)
                {
                    MessageDlg.Show(this, Resources.TransitionSettingsUI_OkDialog_High_resolution_MS1_filtering_requires_use_of_monoisotopic_precursor_masses);
                    tabControl1.SelectedIndex = (int)TABS.Prediction;
                    comboPrecursorMass.Focus();
                    return;
                }

                if (FullScanSettingsControl.Enrichments == null)
                {
                    tabControl1.SelectedIndex = (int)TABS.FullScan;
                    MessageDlg.Show(GetParentForm(this), Resources.TransitionSettingsUI_OkDialog_Isotope_enrichment_settings_are_required_for_MS1_filtering_on_high_resolution_mass_spectrometers);
                    FullScanSettingsControl.ComboEnrichmentsSetFocus();
                    return;
                }
            }

            IsolationScheme           isolationScheme = FullScanSettingsControl.IsolationScheme;
            FullScanAcquisitionMethod acquisitionMethod = AcquisitionMethod;

            if (isolationScheme == null && acquisitionMethod == FullScanAcquisitionMethod.DIA)
            {
                tabControl1.SelectedIndex = (int)TABS.FullScan;
                MessageDlg.Show(this, Resources.TransitionSettingsUI_OkDialog_An_isolation_scheme_is_required_to_match_multiple_precursors);
                FullScanSettingsControl.ComboIsolationSchemeSetFocus();
                return;
            }

            if (isolationScheme != null && isolationScheme.WindowsPerScan.HasValue && !maxInclusions.HasValue)
            {
                MessageDlg.Show(this, Resources.TransitionSettingsUI_OkDialog_Before_performing_a_multiplexed_DIA_scan_the_instrument_s_firmware_inclusion_limit_must_be_specified);
                tabControl1.SelectedIndex = (int)TABS.Instrument;
                textMaxInclusions.Focus();
                return;
            }

            if (FullScanSettingsControl.IsDIA() && cbExclusionUseDIAWindow.Checked)
            {
                if (FullScanSettingsControl.IsolationScheme.IsAllIons)
                {
                    MessageDlg.Show(this, Resources.TransitionSettingsUI_OkDialog_Cannot_use_DIA_window_for_precusor_exclusion_when__All_Ions__is_selected_as_the_isolation_scheme___To_use_the_DIA_window_for_precusor_exclusion__change_the_isolation_scheme_in_the_Full_Scan_settings_);
                    tabControl1.SelectedIndex = (int)TABS.Filter;
                    cbExclusionUseDIAWindow.Focus();
                    return;
                }
                if (FullScanSettingsControl.IsolationScheme.FromResults)
                {
                    MessageDlg.Show(this, Resources.TransitionSettingsUI_OkDialog_Cannot_use_DIA_window_for_precursor_exclusion_when_isolation_scheme_does_not_contain_prespecified_windows___Please_select_an_isolation_scheme_with_prespecified_windows_);
                    tabControl1.SelectedIndex = (int)TABS.Filter;
                    cbExclusionUseDIAWindow.Focus();
                    return;
                }
            }

            TransitionFullScan fullScan;

            if (!FullScanSettingsControl.ValidateFullScanSettings(helper, out fullScan, tabControl1, (int)TABS.FullScan))
            {
                return;
            }

            Helpers.AssignIfEquals(ref fullScan, FullScan);

            TransitionSettings settings = new TransitionSettings(prediction,
                                                                 filter, libraries, integration, instrument, fullScan);

            // Only update, if anything changed
            if (!Equals(settings, _transitionSettings))
            {
                if (!_parent.ChangeSettingsMonitored(this, Resources.TransitionSettingsUI_OkDialog_Changing_transition_settings,
                                                     s => s.ChangeTransitionSettings(settings)))
                {
                    return;
                }
                _transitionSettings = settings;
            }

            DialogResult = DialogResult.OK;
        }
示例#13
0
        public void OkDialog()
        {
            var helper = new MessageBoxHelper(this);

            string name;

            if (!helper.ValidateNameTextBox(textName, out name))
            {
                return;
            }

            // Allow updating the original modification
            if (LibrarySpec == null || !Equals(name, LibrarySpec.Name))
            {
                // But not any other existing modification
                foreach (LibrarySpec mod in _existing)
                {
                    if (Equals(name, mod.Name))
                    {
                        helper.ShowTextBoxError(textName, Resources.EditLibraryDlg_OkDialog_The_library__0__already_exists, name);
                        return;
                    }
                }
            }

            String path = textPath.Text;

            if (!ValidateLibraryPath(this, path))
            {
                textPath.Focus();
                return;
            }

            var librarySpec = LibrarySpec.CreateFromPath(name, path);

            if (librarySpec == null)
            {
                MessageDlg.Show(this, string.Format(Resources.EditLibraryDlg_OkDialog_The_file__0__is_not_a_supported_spectral_library_file_format, path));
                textPath.Focus();
                return;
            }
            librarySpec = librarySpec.ChangeUseExplicitPeakBounds(cbxUseExplicitPeakBounds.Checked);
            if (librarySpec is ChromatogramLibrarySpec)
            {
                using (var longWait = new LongWaitDlg {
                    Text = Resources.EditLibraryDlg_OkDialog_Loading_chromatogram_library
                })
                {
                    Library lib = null;
                    try
                    {
                        try
                        {
                            longWait.PerformWork(this, 800,
                                                 monitor => lib = librarySpec.LoadLibrary(new DefaultFileLoadMonitor(monitor)));
                        }
// ReSharper disable once EmptyGeneralCatchClause
                        catch
                        {
                            // Library failed to load
                        }
                        LibraryRetentionTimes libRts;
                        if (lib != null && lib.TryGetIrts(out libRts) &&
                            Settings.Default.RTScoreCalculatorList.All(calc => calc.PersistencePath != path))
                        {
                            using (var addPredictorDlg = new AddRetentionTimePredictorDlg(name, path, true))
                            {
                                switch (addPredictorDlg.ShowDialog(this))
                                {
                                case DialogResult.OK:
                                    Settings.Default.RTScoreCalculatorList.Add(addPredictorDlg.Calculator);
                                    Settings.Default.RetentionTimeList.Add(addPredictorDlg.Regression);
                                    break;

                                case DialogResult.No:
                                    break;

                                default:
                                    return;
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (null != lib)
                        {
                            foreach (var pooledStream in lib.ReadStreams)
                            {
                                pooledStream.CloseStream();
                            }
                        }
                    }
                }
            }

            _librarySpec = librarySpec;
            DialogResult = DialogResult.OK;
            Close();
        }
示例#14
0
        public void OkDialog()
        {
            var helper = new MessageBoxHelper(this);

            // Validate start and end.
            double start;
            double end;

            if (!helper.ValidateDecimalTextBox(textStart, TransitionFullScan.MIN_RES_MZ, TransitionFullScan.MAX_RES_MZ, out start) ||
                !helper.ValidateDecimalTextBox(textEnd, TransitionFullScan.MIN_RES_MZ, TransitionFullScan.MAX_RES_MZ, out end))
            {
                return;
            }

            if (start >= end)
            {
                MessageDlg.Show(this, Resources.CalculateIsolationSchemeDlg_OkDialog_Start_value_must_be_less_than_End_value);
                return;
            }

            // Validate window width.
            double windowWidth;

            if (!helper.ValidateDecimalTextBox(textWidth, 0.1, TransitionFullScan.MAX_RES_MZ - TransitionFullScan.MIN_RES_MZ, out windowWidth))
            {
                return;
            }

            if (windowWidth > end - start)
            {
                MessageDlg.Show(this, Resources.CalculateIsolationSchemeDlg_OkDialog_Window_width_must_be_less_than_or_equal_to_the_isolation_range);
                return;
            }

            // if given windowWidth is not an integer value
            if (windowWidth % 1 != 0 && OptimizeWindowPlacement)
            {
                MessageDlg.Show(this, Resources.CalculateIsolationSchemeDlg_OkDialog_Window_width_must_be_an_integer);
                return;
            }

            // if given windowWidth is odd
            if (windowWidth % 2 != 0 && OptimizeWindowPlacement && (string)comboDeconv.SelectedItem != EditIsolationSchemeDlg.DeconvolutionMethod.NONE && (string)comboDeconv.SelectedItem != EditIsolationSchemeDlg.DeconvolutionMethod.MSX)
            {
                MessageDlg.Show(this, Resources.CalculateIsolationSchemeDlg_OkDialog_Window_width_not_even);
                return;
            }

            // Validate margins.
            double?margin = null;

            if (!helper.IsZeroOrEmpty(textMargin))
            {
                double marginValue;
                if (!helper.ValidateDecimalTextBox(textMargin, TransitionInstrument.MIN_MZ_MATCH_TOLERANCE,
                                                   TransitionFullScan.MAX_RES_MZ - TransitionFullScan.MIN_RES_MZ, out marginValue))
                {
                    return;
                }
                margin = marginValue;
            }

            // Validate CE range.
            double?ceRange = null;

            if (!helper.IsZeroOrEmpty(textCERange))
            {
                double ceRangeValue;
                if (!helper.ValidateDecimalTextBox(textCERange, 0.0, double.MaxValue, out ceRangeValue))
                {
                    return;
                }
                ceRange = ceRangeValue;
            }


            // Validate multiplexing.
            if (Multiplexed)
            {
                int windowsPerScan;
                if (!helper.ValidateNumberTextBox(textWindowsPerScan, 2, 20, out windowsPerScan))
                {
                    return;
                }

                // Make sure multiplexed window count is a multiple of windows per scan.
                if (Multiplexed && IsolationWindows.Count % windowsPerScan != 0)
                {
                    MessageDlg.Show(this, Resources.CalculateIsolationSchemeDlg_OkDialog_The_number_of_generated_windows_could_not_be_adjusted_to_be_a_multiple_of_the_windows_per_scan_Try_changing_the_windows_per_scan_or_the_End_value);
                    return;
                }
            }

            try
            {
// ReSharper disable ObjectCreationAsStatement
                new IsolationWindow(start, end, null, margin, margin, ceRange);
// ReSharper restore ObjectCreationAsStatement
            }
            catch (InvalidDataException x)
            {
                MessageDlg.ShowException(this, x);
                return;
            }

            DialogResult = DialogResult.OK;
        }
 /// <summary>
 /// Provides a user defined method.
 /// </summary>
 protected virtual async void DoTest(Session session)
 {
     MessageDlg dialog = new MessageDlg("A handy place to put test code.");
     await dialog.ShowAsync();
 }
示例#16
0
        public void OkDialog()
        {
            var helper = new MessageBoxHelper(this);

            string name;

            if (!helper.ValidateNameTextBox(textName, out name))
            {
                return;
            }

            if (_existing.Contains(r => !ReferenceEquals(_regression, r) && Equals(name, r.Name)))
            {
                helper.ShowTextBoxError(textName, Resources.EditCEDlg_OkDialog_The_collision_energy_regression__0__already_exists, name);
                return;
            }

            List <ChargeRegressionLine> conversions =
                new List <ChargeRegressionLine>();

            foreach (DataGridViewRow row in gridRegression.Rows)
            {
                if (row.IsNewRow)
                {
                    continue;
                }

                int charge;
                if (!ValidateCharge(row.Cells[0], out charge))
                {
                    return;
                }

                double slope;
                if (!ValidateSlope(row.Cells[1], out slope))
                {
                    return;
                }

                double intercept;
                if (!ValidateIntercept(row.Cells[2], out intercept))
                {
                    return;
                }

                conversions.Add(new ChargeRegressionLine(charge, slope, intercept));
            }

            if (conversions.Count == 0)
            {
                MessageDlg.Show(this, Resources.EditCEDlg_OkDialog_Collision_energy_regressions_require_at_least_one_regression_function);
                return;
            }

            double stepSize;

            if (!helper.ValidateDecimalTextBox(textStepSize,
                                               CollisionEnergyRegression.MIN_STEP_SIZE,
                                               CollisionEnergyRegression.MAX_STEP_SIZE,
                                               out stepSize))
            {
                return;
            }

            int stepCount;

            if (!helper.ValidateNumberTextBox(textStepCount,
                                              OptimizableRegression.MIN_OPT_STEP_COUNT,
                                              OptimizableRegression.MAX_OPT_STEP_COUNT,
                                              out stepCount))
            {
                return;
            }

            _regression = new CollisionEnergyRegression(name, conversions, stepSize, stepCount);

            DialogResult = DialogResult.OK;
            Close();
        }
        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);
        }
示例#18
0
 private void HandleLoadScanExceptionUI(Exception ex)
 {
     GraphPane.Title.Text = Resources.GraphFullScan_LoadScan_Spectrum_unavailable;
     MessageDlg.ShowException(this, ex);
 }
示例#19
0
        public void LibraryBuildCompleteCallback(LibraryManager.BuildState buildState, bool success)
        {
            // Completion needs to happen on a separate thread because of the access to UI elements
            // In order to make sure the thread handle is released, it needs to call Application.ThreadExit()
            var threadComplete = BackgroundEventThreads.CreateThreadForAction(() =>
            {
                if (success && NotificationContainerForm.IsHandleCreated)
                {
                    // Only one form showing at a time
                    lock (this)
                    {
                        RemoveLibraryBuildNotification();

                        var frm                   = new BuildLibraryNotification(buildState.LibrarySpec.Name);
                        frm.Activated            += notification_Activated;
                        frm.Shown                += notification_Shown;
                        frm.ExploreLibrary       += notification_ExploreLibrary;
                        frm.NotificationComplete += notification_NotificationComplete;
                        Point anchor              = NotificationAnchor;
                        frm.Left                  = anchor.X;
                        frm.Top                   = anchor.Y - frm.Height;
                        NotificationContainerForm.BeginInvoke(new Action(() =>
                        {
                            if (!string.IsNullOrEmpty(buildState.ExtraMessage))
                            {
                                MessageDlg.Show(TopMostApplicationForm, buildState.ExtraMessage);
                            }
                            if (buildState.IrtStandard != null && !buildState.IrtStandard.Name.Equals(IrtStandard.EMPTY.Name))
                            {
                                // Load library
                                Library lib = null;
                                using (var longWait = new LongWaitDlg {
                                    Text = Resources.LibraryBuildNotificationHandler_AddIrts_Loading_library
                                })
                                {
                                    var status = longWait.PerformWork(TopMostApplicationForm, 800, monitor =>
                                    {
                                        lib = NotificationContainer.LibraryManager.TryGetLibrary(buildState.LibrarySpec) ??
                                              NotificationContainer.LibraryManager.LoadLibrary(buildState.LibrarySpec, () => new DefaultFileLoadMonitor(monitor));
                                        foreach (var stream in lib.ReadStreams)
                                        {
                                            stream.CloseStream();
                                        }
                                    });
                                    if (status.IsCanceled)
                                    {
                                        lib = null;
                                    }
                                    if (status.IsError)
                                    {
                                        throw status.ErrorException;
                                    }
                                }
                                // Add iRTs to library
                                if (AddIrts(lib, buildState.LibrarySpec, buildState.IrtStandard, NotificationContainerForm, true))
                                {
                                    AddRetentionTimePredictor(buildState);
                                }
                            }
                        }));
                        frm.Start();
                        Assume.IsNull(Interlocked.Exchange(ref _notification, frm));
                    }
                }
            });

            threadComplete.Name = @"Library Build Completion";
            threadComplete.Start();
        }
示例#20
0
        // return:
        //      0   普通返回
        //      1   要全部中断
        NormalResult DoImport(string strTargetDbName)
        {
            string   strError = "";
            Encoding encoding = null;

            if (string.IsNullOrEmpty(this.InputEncodingName) == true)
            {
                return(new NormalResult(-1, "尚未选定 ISO2709 文件的编码方式"));
            }

            if (StringUtil.IsNumber(this.InputEncodingName) == true)
            {
                encoding = Encoding.GetEncoding(Convert.ToInt32(this.InputEncodingName));
            }
            else
            {
                encoding = Encoding.GetEncoding(this.InputEncodingName);
            }

            ClearErrorInfoForm();

            string strInputFileName = "";

            strInputFileName = this.InputFileName;

            string strBiblioSyntax = Program.MainForm.GetBiblioSyntax(strTargetDbName);

            if (strBiblioSyntax == null)
            {
                strBiblioSyntax = Program.MainForm.GetAuthoritySyntax(strTargetDbName);
                if (strBiblioSyntax == null)
                {
                    strError = "没有找到书目或规范库 '" + strTargetDbName + "' 的 MARC 格式信息";
                    goto ERROR1;
                }
            }

            // 和第一个属性页的 MARC 格式进行对比,如果不符合,要报错
            if (strBiblioSyntax != this.InputMarcSyntax)
            {
                strError = "您在 数据来源 属性页为文件 '" + strInputFileName + "' 选定的 MARC 格式 '" + this.InputMarcSyntax + "' 与数据库 '" + strTargetDbName + "' 的预定义 MARC 格式 '" + strBiblioSyntax + "' 不符合。导入被终止";
                goto ERROR1;
            }

            string strRange = (string)this.Invoke(new Func <string>(() =>
            {
                return(this.textBox_importRange.Text);
            }));
            RangeList range = null;

            if (string.IsNullOrEmpty(strRange) == false)
            {
                range = new RangeList(strRange);
                range.Sort();
            }

            Stream file = null;

            try
            {
                file = File.Open(strInputFileName,
                                 FileMode.Open,
                                 FileAccess.Read);
            }
            catch (Exception ex)
            {
                return(new NormalResult(-1, "打开文件 " + strInputFileName + " 失败: " + ex.Message));
            }

            this.Invoke((Action)(() =>
            {
                this.progressBar_records.Minimum = 0;
                this.progressBar_records.Maximum = (int)file.Length;
                this.progressBar_records.Value = 0;
            }));

            stop.OnStop += new StopEventHandler(this.DoStop);
            stop.Initial("正在获取ISO2709记录 ...");
            stop.BeginLoop();

            bool dont_display_dialog = false;

            LibraryChannel channel = this.GetChannel();

            EnableControls(false);

            try
            {
                int nCount = 0;

                DialogResult retry_result = DialogResult.Yes;

                for (int i = 0; ; i++)
                {
                    Application.DoEvents(); // 出让界面控制权

                    if (stop != null && stop.State != 0)
                    {
                        DialogResult result = MessageBox.Show(this,
                                                              "准备中断。\r\n\r\n确实要中断全部操作? (Yes 全部中断;No 中断循环,但是继续收尾处理;Cancel 放弃中断,继续操作)",
                                                              "ImportMarcForm",
                                                              MessageBoxButtons.YesNoCancel,
                                                              MessageBoxIcon.Question,
                                                              MessageBoxDefaultButton.Button3);

                        if (result == DialogResult.Yes)
                        {
                            strError = "用户中断";
                            goto ERROR1;
                        }
                        if (result == DialogResult.No)
                        {
                            return(new NormalResult()); // 假装loop正常结束
                        }
                        stop.Continue();                // 继续循环
                    }


                    // 从ISO2709文件中读入一条MARC记录
                    // return:
                    //	-2	MARC格式错
                    //	-1	出错
                    //	0	正确
                    //	1	结束(当前返回的记录有效)
                    //	2	结束(当前返回的记录无效)
                    int nRet = MarcUtil.ReadMarcRecord(file,
                                                       encoding,
                                                       true, // bRemoveEndCrLf,
                                                       true, // bForce,
                                                       out string strMARC,
                                                       out strError);
                    if (nRet == -2 || nRet == -1)
                    {
                        DialogResult result = MessageBox.Show(this,
                                                              "读入MARC记录(" + nCount.ToString() + ")出错: " + strError + "\r\n\r\n确实要中断当前批处理操作?",
                                                              "ImportMarcForm",
                                                              MessageBoxButtons.YesNo,
                                                              MessageBoxIcon.Question,
                                                              MessageBoxDefaultButton.Button2);
                        if (result == DialogResult.Yes)
                        {
                            break;
                        }
                        else
                        {
                            strError = "读入MARC记录(" + nCount.ToString() + ")出错: " + strError;
                            GetErrorInfoForm().WriteHtml(strError + "\r\n");
                            continue;
                        }
                    }

                    if (nRet != 0 && nRet != 1)
                    {
                        return(new NormalResult());   // 结束
                    }
                    this.Invoke((Action)(() =>
                    {
                        this.progressBar_records.Value = (int)file.Position;
                    }));

                    if (range != null && range.IsInRange(i, true) == false)
                    {
                        stop.SetMessage("跳过第 " + (i + 1).ToString() + " 个 ISO2709 记录");
                        continue;
                    }
                    else
                    {
                        stop.SetMessage("正在获取第 " + (i + 1).ToString() + " 个 ISO2709 记录");
                    }

                    // 跳过太短的记录
                    if (string.IsNullOrEmpty(strMARC) == true ||
                        strMARC.Length <= 24)
                    {
                        continue;
                    }

                    if (this._openMarcFileDialog.Mode880 == true &&
                        (this._openMarcFileDialog.MarcSyntax == "usmarc" || this._openMarcFileDialog.MarcSyntax == "<自动>"))
                    {
                        MarcRecord temp = new MarcRecord(strMARC);
                        MarcQuery.ToParallel(temp);
                        strMARC = temp.Text;
                    }

                    // 处理
                    string strBiblioRecPath = strTargetDbName + "/?";

                    nRet = MarcUtil.Marc2Xml(strMARC,
                                             strBiblioSyntax,
                                             out XmlDocument domMarc,
                                             out strError);
                    if (nRet == -1)
                    {
                        goto ERROR1;
                    }
REDO:
                    long lRet = channel.SetBiblioInfo(
                        stop,
                        "new",
                        strBiblioRecPath,
                        "xml",
                        domMarc.DocumentElement.OuterXml,
                        null, // timestamp
                        "",
                        out string strOutputBiblioRecPath,
                        out byte[] baNewTimestamp,
                        out strError);
                    if (lRet == -1)
                    {
#if NO
                        strError = "创建书目记录 '" + strBiblioRecPath + "' 时出错: " + strError + "\r\n";
                        goto ERROR1;
#endif

                        // string strText = strError;
                        if (dont_display_dialog == false)
                        {
                            retry_result = (DialogResult)this.Invoke((Func <DialogResult>)(() =>
                            {
                                // return AutoCloseMessageBox.Show(this, strText + "\r\n\r\n(点右上角关闭按钮可以中断批处理)", 5000);
                                return(MessageDlg.Show(this,
                                                       strError + ", 是否重试?\r\n---\r\n\r\n[重试]重试; [跳过]跳过本条继续后面批处理; [中断]中断批处理",
                                                       "ImportMarcForm",
                                                       MessageBoxButtons.YesNoCancel,
                                                       MessageBoxDefaultButton.Button1,
                                                       ref dont_display_dialog,
                                                       new string[] { "重试", "跳过", "中断" },
                                                       "后面不再出现此对话框,按本次选择自动处理"));
                            }));
                        }

                        if (retry_result == System.Windows.Forms.DialogResult.Cancel)
                        {
                            goto ERROR1;
                        }
                        if (retry_result == DialogResult.Yes)
                        {
                            goto REDO;
                        }

                        // 在操作历史中显示出错信息
                    }

                    nCount++;
                }

                return(new NormalResult());
            }
            finally
            {
                EnableControls(true);

                this.ReturnChannel(channel);

                stop.EndLoop();
                stop.OnStop -= new StopEventHandler(this.DoStop);
                stop.Initial("");

                if (file != null)
                {
                    file.Close();
                }
            }
ERROR1:
            return(new NormalResult(-1, strError));
        }
        public void OkDialog()
        {
            if (string.IsNullOrEmpty(textLibraryName.Text))
            {
                MessageDlg.Show(this, Resources.EditIonMobilityLibraryDlg_OkDialog_Please_enter_a_name_for_the_ion_mobility_library_);
                textLibraryName.Focus();
                return;
            }

            if (_existingLibs != null)
            {
                foreach (var existingLib in _existingLibs)
                {
                    if (Equals(existingLib.Name, textLibraryName.Text) && !Equals(existingLib.Name, _editingName))
                    {
                        if (MessageBox.Show(this, string.Format(Resources.EditIonMobilityLibraryDlg_OkDialog_An_ion_mobility_library_with_the_name__0__already_exists__Do_you_want_to_overwrite_it_,
                                                                textLibraryName.Text),
                                            Program.Name, MessageBoxButtons.YesNo) != DialogResult.Yes)
                        {
                            textLibraryName.Focus();
                            return;
                        }
                    }
                }
            }

            string message;

            if (string.IsNullOrEmpty(textDatabase.Text))
            {
                message = TextUtil.LineSeparate(Resources.EditIonMobilityLibraryDlg_OkDialog_Please_choose_a_file_for_the_ion_mobility_library,
                                                Resources.EditIonMobilityLibraryDlg_OkDialog_Click_the_Create_button_to_create_a_new_library_or_the_Open_button_to_open_an_existing_library_file_);
                MessageDlg.Show(this, message);
                textDatabase.Focus();
                return;
            }
            string path = Path.GetFullPath(textDatabase.Text);

            if (!Equals(path, textDatabase.Text))
            {
                message = TextUtil.LineSeparate(Resources.EditIonMobilityLibraryDlg_OkDialog_Please_use_a_full_path_to_a_file_for_the_ion_mobility_library_,
                                                Resources.EditIonMobilityLibraryDlg_OkDialog_Click_the_Create_button_to_create_a_new_library_or_the_Open_button_to_open_an_existing_library_file_);
                MessageDlg.Show(this, message);
                textDatabase.Focus();
                return;
            }
            if (!string.Equals(Path.GetExtension(path), IonMobilityDb.EXT))
            {
                path += IonMobilityDb.EXT;
            }

            // This function MessageBox.Show's error messages
            if (!ValidatePeptideList(LibraryPeptideList, textLibraryName.Text ?? string.Empty))
            {
                gridViewMeasuredPeptides.Focus();
                return;
            }

            try
            {
                var calculator = new IonMobilityLibrary(textLibraryName.Text, path);

                IonMobilityDb db = File.Exists(path)
                               ? IonMobilityDb.GetIonMobilityDb(path, null)
                               : IonMobilityDb.CreateIonMobilityDb(path);

                db = db.UpdatePeptides(LibraryPeptides.ToArray(), _originalPeptides ?? new ValidatingIonMobilityPeptide[0]);

                IonMobilityLibrary = calculator.ChangeDatabase(db);
            }
            catch (DatabaseOpeningException x)
            {
                MessageDlg.Show(this, x.Message);
                textDatabase.Focus();
                return;
            }
            catch (StaleStateException staleStateException)
            {
                // CONSIDER: (copied from iRT code) Not sure if this is the right thing to do.  It would
                //           be nice to solve whatever is causing this, but this is
                //           better than showing an unexpected error form with stack trace.
                MessageDlg.ShowWithException(this, Resources.EditIonMobilityLibraryDlg_OkDialog_Failure_updating_peptides_in_the_ion_mobility_library__The_library_may_be_out_of_synch_, staleStateException);
                return;
            }

            DialogResult = DialogResult.OK;
        }
示例#22
0
        public void UploadSharedZipFile(Control parent, Server server, string zipFilePath, string folderPath)
        {
            Uri result = null;

            if (server == null)
            {
                return;
            }
            try
            {
                var isCanceled = false;
                using (var waitDlg = new LongWaitDlg {
                    Text = Resources.PublishDocumentDlg_UploadSharedZipFile_Uploading_File
                })
                {
                    waitDlg.PerformWork(parent, 1000, longWaitBroker =>
                    {
                        result = SendZipFile(server, folderPath,
                                             zipFilePath, longWaitBroker);
                        if (longWaitBroker.IsCanceled)
                        {
                            isCanceled = true;
                        }
                    });
                }
                if (!isCanceled) // if user not canceled
                {
                    String message = Resources.WebPanoramaPublishClient_UploadSharedZipFile_Publish_succeeded__would_you_like_to_view_the_file_in_Panorama_;
                    if (MultiButtonMsgDlg.Show(parent, message, MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false)
                        == DialogResult.Yes)
                    {
                        Process.Start(result.ToString());
                    }
                }
            }
            catch (Exception x)
            {
                var panoramaEx = x.InnerException as PanoramaImportErrorException;
                if (panoramaEx != null)
                {
                    var message = Resources.WebPanoramaPublishClient_UploadSharedZipFile_An_error_occured_while_publishing_to_Panorama__would_you_like_to_go_to_Panorama_;
                    if (MultiButtonMsgDlg.Show(parent, message, MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false)
                        == DialogResult.Yes)
                    {
                        Process.Start(panoramaEx.JobUrl.ToString());
                    }
                }
                else
                {
                    MessageDlg.ShowException(parent, x);
                }
            }

            // Change PanoramaUrl setting to the successful url used
            var uriString = server.GetKey() + folderPath;

            uriString = Uri.EscapeUriString(uriString);
            var window = parent as SkylineWindow;

            if (window != null && Uri.IsWellFormedUriString(uriString, UriKind.Absolute)) // cant do Uri.isWellFormed because of port and ip
            {
                window.ChangeDocPanoramaUri(new Uri(uriString));
            }
        }
示例#23
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);
        }
示例#24
0
        private bool GetPackages()
        {
            ICollection <string> downloadablePackages = new Collection <string>();
            ICollection <string> localPackages        = new Collection <string>();

            AssignPackagesToInstall(ref downloadablePackages, ref localPackages);

            IEnumerable <string> packagePaths = null;

            try
            {
                // download packages
                using (var waitDlg = new LongWaitDlg {
                    ProgressValue = 0
                })
                {
                    waitDlg.PerformWork(this, 500, longWaitBroker => packagePaths = DownloadPackages(longWaitBroker, downloadablePackages));
                }

                // separate packages
                ICollection <string> exePaths    = new Collection <string>();
                ICollection <string> sourcePaths = new Collection <string>();
                foreach (var package in (packagePaths == null) ? localPackages : packagePaths.Concat(localPackages))
                {
                    if (package.EndsWith(@".exe"))
                    {
                        exePaths.Add(package);
                    }
                    else
                    {
                        sourcePaths.Add(package);
                    }
                }

                // first install executable packages, if any
                if (exePaths.Count != 0)
                {
                    using (var waitDlg = new LongWaitDlg(null, false)
                    {
                        Message = Resources.PythonInstaller_GetPackages_Installing_Packages
                    })
                    {
                        waitDlg.PerformWork(this, 500, () => InstallExecutablePackages(exePaths));
                    }
                }

                // then install source paths, if any
                if (sourcePaths.Count != 0)
                {
                    // try and find the path to the pip package manager .exe
                    string pipPath = PythonUtil.GetPipPath(_version);

                    // if it can't be found, install it
                    if (pipPath == null || TestingPip)
                    {
                        DialogResult result = MultiButtonMsgDlg.Show(
                            this,
                            Resources.PythonInstaller_InstallPackages_Skyline_uses_the_Python_tool_setuptools_and_the_Python_package_manager_Pip_to_install_packages_from_source__Click_install_to_begin_the_installation_process_,
                            Resources.PythonInstaller_InstallPackages_Install);
                        if (result == DialogResult.OK && GetPip())
                        {
                            pipPath = PythonUtil.GetPipPath(_version);
                            MessageDlg.Show(this, Resources.PythonInstaller_InstallPackages_Pip_installation_complete_);
                        }
                        else
                        {
                            MessageDlg.Show(this, Resources.PythonInstaller_InstallPackages_Python_package_installation_cannot_continue__Canceling_tool_installation_);
                            return(false);
                        }
                    }

                    using (var waitDlg = new LongWaitDlg(null, false)
                    {
                        Message = Resources.PythonInstaller_GetPackages_Installing_Packages
                    })
                    {
                        waitDlg.PerformWork(this, 500, () => InstallSourcePackages(sourcePaths, pipPath));
                    }
                }
                MessageDlg.Show(this, Resources.PythonInstaller_GetPackages_Package_installation_completed_);
                return(true);
            }
            catch (TargetInvocationException ex)
            {
                if (ex.InnerException is ToolExecutionException)
                {
                    MessageDlg.ShowException(this, ex);
                    return(false);
                }
                throw;
            }
        }
示例#25
0
        public void OkDialog()
        {
            var helper = new MessageBoxHelper(this);

            double qCutoff = double.MaxValue;

            if (reintegrateQCutoff.Checked)
            {
                if (!helper.ValidateDecimalTextBox(textBoxCutoff, 0.0, 1.0, out qCutoff))
                {
                    return;
                }
            }

            using (var longWaitDlg = new LongWaitDlg
            {
                Text = Resources.ReintegrateDlg_OkDialog_Reintegrating,
            })
            {
                try
                {
                    var scoringModel = _driverPeakScoringModel.SelectedItem;
                    if (Equals(scoringModel, LegacyScoringModel.DEFAULT_UNTRAINED_MODEL))
                    {
                        scoringModel = LegacyScoringModel.DEFAULT_MODEL;
                    }
                    if (scoringModel == null || !scoringModel.IsTrained)
                    {
                        throw new InvalidDataException(Resources.ReintegrateDlg_OkDialog_You_must_train_and_select_a_model_in_order_to_reintegrate_peaks_);
                    }
                    var resultsHandler = new MProphetResultsHandler(Document, scoringModel)
                    {
                        QValueCutoff   = qCutoff,
                        OverrideManual = checkBoxOverwrite.Checked,
                        AddAnnotation  = checkBoxAnnotation.Checked,
                        AddMAnnotation = checkBoxAnnotation.Checked
                    };
                    longWaitDlg.PerformWork(this, 1000, pm =>
                    {
                        resultsHandler.ScoreFeatures(pm);
                        if (resultsHandler.IsMissingScores())
                        {
                            throw new InvalidDataException(Resources.ReintegrateDlg_OkDialog_The_current_peak_scoring_model_is_incompatible_with_one_or_more_peptides_in_the_document___Please_train_a_new_model_);
                        }
                        // TODO: Add a checkbox for including decoys.  Probably most of the time real users won't want to bother with reintegrating decoys
                        Document = resultsHandler.ChangePeaks(pm);
                    });
                    if (longWaitDlg.IsCanceled)
                    {
                        return;
                    }
                }
                catch (Exception x)
                {
                    var message = TextUtil.LineSeparate(string.Format(Resources.ReintegrateDlg_OkDialog_Failed_attempting_to_reintegrate_peaks_),
                                                        x.Message);
                    MessageDlg.ShowWithException(this, message, x);
                    return;
                }
            }

            var newPeakScoringModel = _driverPeakScoringModel.SelectedItem;

            if (!Equals(newPeakScoringModel, Document.Settings.PeptideSettings.Integration.PeakScoringModel))
            {
                Document = Document.ChangeSettings(Document.Settings.ChangePeptideIntegration(
                                                       i => i.ChangePeakScoringModel(newPeakScoringModel)));
            }

            DialogResult = DialogResult.OK;
        }
        public override void Delete()
        {
            if (null == BoundDataGridView)
            {
                return;
            }
            var selectedRows = GetSelectedRows <FoldChangeBindingSource.FoldChangeRow>(BoundDataGridView);

            if (!selectedRows.Any())
            {
                MessageDlg.Show(BoundDataGridView, GroupComparisonStrings.GroupComparisonViewContext_Delete_No_rows_are_selected);
                return;
            }
            var docNodes = new Dictionary <IdentityPath, SkylineDocNode>();

            foreach (var row in selectedRows)
            {
                if (row.Peptide != null)
                {
                    docNodes[row.Peptide.IdentityPath] = row.Peptide;
                }
                else
                {
                    docNodes[row.Protein.IdentityPath] = row.Protein;
                }
            }
            string message;

            if (docNodes.Count == 1)
            {
                var peptide = docNodes.Values.First() as Peptide;
                if (null != peptide)
                {
                    message = string.Format(GroupComparisonStrings.GroupComparisonViewContext_Delete_Are_you_sure_you_want_to_delete_the_peptide__0_, peptide);
                }
                else
                {
                    var protein = docNodes.Values.First() as Protein;
                    message = string.Format(GroupComparisonStrings.GroupComparisonViewContext_Delete_Are_you_sure_you_want_to_delete_the_protein__0_, protein);
                }
            }
            else
            {
                if (docNodes.Values.First() is Peptide)
                {
                    message = string.Format(GroupComparisonStrings.GroupComparisonViewContext_Delete_Are_you_sure_you_want_to_delete_these__0__peptides, docNodes.Count);
                }
                else
                {
                    message = string.Format(GroupComparisonStrings.GroupComparisonViewContext_Delete_Are_you_sure_you_want_to_delete_these__0__proteins, docNodes.Count);
                }
            }
            if (MultiButtonMsgDlg.Show(BoundDataGridView, message, Resources.OK) != DialogResult.OK)
            {
                return;
            }
            var identityPathsToDelete = new HashSet <IdentityPath>(docNodes.Keys);
            var skylineWindow         = ((SkylineDataSchema)DataSchema).SkylineWindow;

            if (null != skylineWindow)
            {
                skylineWindow.ModifyDocument(GroupComparisonStrings.GroupComparisonViewContext_Delete_Delete_items, doc => DeleteProteins(doc, identityPathsToDelete));
            }
        }
示例#27
0
 private bool TestUnifiAccount(UnifiAccount unifiAccount)
 {
     using (var unifiSession = new UnifiSession(unifiAccount))
     {
         try
         {
             var tokenResponse = unifiAccount.Authenticate();
             if (tokenResponse.IsError)
             {
                 string error = tokenResponse.ErrorDescription ?? tokenResponse.Error;
                 MessageDlg.Show(this, TextUtil.LineSeparate(Resources.EditRemoteAccountDlg_TestUnifiAccount_An_error_occurred_while_trying_to_authenticate_, error));
                 if (tokenResponse.Error == "invalid_scope") // Not L10N
                 {
                     tbxClientScope.Focus();
                 }
                 else if (tokenResponse.Error == "invalid_client") // Not L10N
                 {
                     tbxClientSecret.Focus();
                 }
                 else if (tokenResponse.HttpStatusCode == HttpStatusCode.NotFound)
                 {
                     tbxIdentityServer.Focus();
                 }
                 else
                 {
                     textPassword.Focus();
                 }
                 return(false);
             }
         }
         catch (Exception e)
         {
             MessageDlg.ShowWithException(this, Resources.EditRemoteAccountDlg_TestUnifiAccount_An_error_occurred_while_trying_to_authenticate_, e);
             tbxIdentityServer.Focus();
             return(false);
         }
         bool[] contentsAvailable = new bool[1];
         unifiSession.ContentsAvailable += () =>
         {
             lock (contentsAvailable)
             {
                 contentsAvailable[0] = true;
                 Monitor.Pulse(contentsAvailable);
             }
         };
         using (var longWaitDlg = new LongWaitDlg())
         {
             try
             {
                 longWaitDlg.PerformWork(this, 1000, (ILongWaitBroker broker) =>
                 {
                     while (!broker.IsCanceled)
                     {
                         RemoteServerException remoteServerException;
                         if (unifiSession.AsyncFetchContents(unifiAccount.GetRootUrl(),
                                                             out remoteServerException))
                         {
                             if (remoteServerException != null)
                             {
                                 throw remoteServerException;
                             }
                             break;
                         }
                         lock (contentsAvailable)
                         {
                             while (!contentsAvailable[0] && !broker.IsCanceled)
                             {
                                 Monitor.Wait(contentsAvailable, 10);
                             }
                         }
                     }
                 });
             }
             catch (OperationCanceledException)
             {
                 return(false);
             }
             catch (Exception e)
             {
                 MessageDlg.ShowWithException(this, Resources.EditRemoteAccountDlg_TestUnifiAccount_An_exception_occurred_while_trying_to_fetch_the_directory_listing_, e);
                 textServerURL.Focus();
                 return(false);
             }
         }
     }
     MessageDlg.Show(this, Resources.EditChorusAccountDlg_TestSettings_Settings_are_correct);
     return(true);
 }
示例#28
0
        /// <summary>
        /// Obtain new names from a FASTA file.
        /// </summary>
        public void UseFastaFile(string fastaFile)
        {
            try
            {
                var dictExistToNewName = new Dictionary <string, string>();
                using (var reader = new StreamReader(fastaFile))
                {
                    var dictSeqToNames = new Dictionary <string, List <string> >();
                    foreach (var nodePepGroup in _document.MoleculeGroups)
                    {
                        string sequence = nodePepGroup.PeptideGroup.Sequence;
                        if (string.IsNullOrEmpty(sequence))
                        {
                            continue;
                        }

                        List <string> names;
                        if (!dictSeqToNames.TryGetValue(sequence, out names))
                        {
                            names = new List <string>();
                            dictSeqToNames.Add(sequence, names);
                        }
                        if (!names.Contains(nodePepGroup.Name))
                        {
                            names.Add(nodePepGroup.Name);
                        }
                    }

                    foreach (var seq in FastaData.ParseFastaFile(reader))
                    {
                        List <string> names;
                        if (dictSeqToNames.TryGetValue(seq.Sequence, out names))
                        {
                            // Ignore multiple occurrances of the same sequence in the FASTA file
                            dictSeqToNames.Remove(seq.Sequence);

                            foreach (var name in names)
                            {
                                if (Equals(name, seq.Name))
                                {
                                    continue;
                                }
                                if (dictExistToNewName.ContainsKey(name))
                                {
                                    throw new IOException(string.Format(Resources.RenameProteinsDlg_UseFastaFile_The_document_contains_a_naming_conflict_The_name__0__is_currently_used_by_multiple_protein_sequences, name));
                                }
                                dictExistToNewName.Add(name, seq.Name);
                            }
                        }
                    }
                }

                _gridViewDriver.Populate(_document.MoleculeGroups
                                         .Where(nodePepGroup => dictExistToNewName.ContainsKey(nodePepGroup.Name))
                                         .Select(nodePepGroup => new RenameProteins
                {
                    CurrentName = nodePepGroup.Name,
                    NewName     = dictExistToNewName[nodePepGroup.Name]
                }));
                if (NameCount == 0)
                {
                    MessageDlg.Show(this, string.Format(Resources.RenameProteinsDlg_UseFastaFile_No_protein_sequence_matches_found_between_the_current_document_and_the_FASTA_file__0_,
                                                        fastaFile));
                }
            }
            catch (IOException x)
            {
                MessageDlg.Show(this, string.Format(Resources.RenameProteinsDlg_UseFastaFile_Failed_reading_the_file__0__1__,
                                                    fastaFile, x.Message));
            }
        }
示例#29
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();
        }
示例#30
0
        public void OkDialog()
        {
            var helper = new MessageBoxHelper(this);

            int?minPeptidesPerProtein = null;

            if (!string.IsNullOrEmpty(textMinPeptides.Text))
            {
                int minVal;
                if (!helper.ValidateNumberTextBox(tabControl1, 0, textMinPeptides, 0, 10, out minVal))
                {
                    return;
                }
                minPeptidesPerProtein = minVal;
            }
            int?minTransitionsPerPrecursor = null;

            if (!string.IsNullOrEmpty(textMinTransitions.Text))
            {
                int minVal;
                if (!helper.ValidateNumberTextBox(tabControl1, 0, textMinTransitions, 0, 100, out minVal))
                {
                    return;
                }
                minTransitionsPerPrecursor = minVal;
            }
            bool removeDuplicatePeptides = cbRemoveDuplicatePeptides.Checked;
            bool removeRepeatedPeptides  = cbRemoveRepeatedPeptides.Checked;
            bool removeMissingLibrary    = cbRemovePeptidesMissingLibrary.Checked;

            IsotopeLabelType refineLabelType = RefineLabelType;

            bool addLabelType = cbAdd.Checked;

            // If adding, make sure there is something to add
            if (addLabelType && refineLabelType != null && !CanAddLabelType(refineLabelType))
            {
                MessageDlg.Show(this, string.Format(Resources.RefineDlg_OkDialog_The_label_type__0__cannot_be_added_There_are_no_modifications_for_this_type,
                                                    refineLabelType.Name));
                tabControl1.SelectedIndex = 0;
                comboRefineLabelType.Focus();
                return;
            }

            double?minPeakFoundRatio = null, maxPeakFoundRatio = null;

            if (!string.IsNullOrEmpty(textMinPeakFoundRatio.Text))
            {
                double minVal;
                if (!helper.ValidateDecimalTextBox(tabControl1, 1, textMinPeakFoundRatio, 0, 1, out minVal))
                {
                    return;
                }
                minPeakFoundRatio = minVal;
            }
            if (!string.IsNullOrEmpty(textMaxPeakFoundRatio.Text))
            {
                double maxVal;
                if (!helper.ValidateDecimalTextBox(tabControl1, 1, textMaxPeakFoundRatio, 0, 1, out maxVal))
                {
                    return;
                }
                maxPeakFoundRatio = maxVal;
            }
            if (minPeakFoundRatio.HasValue && maxPeakFoundRatio.HasValue &&
                minPeakFoundRatio.Value > maxPeakFoundRatio.Value)
            {
                helper.ShowTextBoxError(textMaxPeakFoundRatio,
                                        Resources.RefineDlg_OkDialog__0__must_be_less_than_min_peak_found_ratio);
                return;
            }

            int?maxPepPeakRank = null;

            if (!string.IsNullOrEmpty(textMaxPepPeakRank.Text))
            {
                int maxVal;
                if (!helper.ValidateNumberTextBox(tabControl1, 1, textMaxPepPeakRank, 1, 10, out maxVal))
                {
                    return;
                }
                maxPepPeakRank = maxVal;
            }
            int?maxPeakRank = null;

            if (!string.IsNullOrEmpty(textMaxPeakRank.Text))
            {
                int maxVal;
                if (!helper.ValidateNumberTextBox(tabControl1, 1, textMaxPeakRank, 1, 10, out maxVal))
                {
                    return;
                }
                maxPeakRank = maxVal;
            }

            bool removeMissingResults = radioRemoveMissing.Checked;

            double?rtRegressionThreshold = null;

            if (!string.IsNullOrEmpty(textRTRegressionThreshold.Text))
            {
                double minVal;
                if (!helper.ValidateDecimalTextBox(tabControl1, 1, textRTRegressionThreshold, 0, 1, out minVal))
                {
                    return;
                }
                rtRegressionThreshold = minVal;
            }

            double?dotProductThreshold = null;

            if (!string.IsNullOrEmpty(textMinDotProduct.Text))
            {
                double minVal;
                if (!helper.ValidateDecimalTextBox(tabControl1, 1, textMinDotProduct, 0, 1, out minVal))
                {
                    return;
                }
                dotProductThreshold = minVal;
            }

            double?idotProductThreshold = null;

            if (!string.IsNullOrEmpty(textMinIdotProduct.Text))
            {
                double minVal;
                if (!helper.ValidateDecimalTextBox(tabControl1, 1, textMinIdotProduct, 0, 1, out minVal))
                {
                    return;
                }
                idotProductThreshold = minVal;
            }

            bool useBestResult = comboReplicateUse.SelectedIndex > 0;

            RefinementSettings = new RefinementSettings
            {
                MinPeptidesPerProtein      = minPeptidesPerProtein,
                RemoveRepeatedPeptides     = removeRepeatedPeptides,
                RemoveDuplicatePeptides    = removeDuplicatePeptides,
                RemoveMissingLibrary       = removeMissingLibrary,
                MinTransitionsPepPrecursor = minTransitionsPerPrecursor,
                RefineLabelType            = refineLabelType,
                AddLabelType          = addLabelType,
                MinPeakFoundRatio     = minPeakFoundRatio,
                MaxPeakFoundRatio     = maxPeakFoundRatio,
                MaxPepPeakRank        = maxPepPeakRank,
                MaxPeakRank           = maxPeakRank,
                PreferLargeIons       = cbPreferLarger.Checked,
                RemoveMissingResults  = removeMissingResults,
                RTRegressionThreshold = rtRegressionThreshold,
                DotProductThreshold   = dotProductThreshold,
                IdotProductThreshold  = idotProductThreshold,
                UseBestResult         = useBestResult,
                AutoPickChildrenAll   = (cbAutoPeptides.Checked ? PickLevel.peptides : 0) |
                                        (cbAutoPrecursors.Checked ? PickLevel.precursors : 0) |
                                        (cbAutoTransitions.Checked ? PickLevel.transitions : 0)
            };

            DialogResult = DialogResult.OK;
            Close();
        }