Esempio n. 1
0
        private bool AddIrts(LibraryManager.BuildState buildState)
        {
            try
            {
                Library lib;
                ProcessedIrtAverages processed = null;
                var initialMessage             = Resources.LibraryBuildNotificationHandler_LibraryBuildCompleteCallback_Adding_iRTs_to_library;
                using (var longWait = new LongWaitDlg {
                    Text = Resources.LibraryBuildNotificationHandler_LibraryBuildCompleteCallback_Adding_iRTs_to_library
                })
                {
                    var status = longWait.PerformWork(TopMostApplicationForm, 800, monitor =>
                    {
                        var initStatus = new ProgressStatus(initialMessage).ChangeSegments(0, 2);
                        monitor.UpdateProgress(initStatus);
                        lib = NotificationContainer.LibraryManager.TryGetLibrary(buildState.LibrarySpec) ??
                              NotificationContainer.LibraryManager.LoadLibrary(buildState.LibrarySpec, () => new DefaultFileLoadMonitor(monitor));
                        foreach (var stream in lib.ReadStreams)
                        {
                            stream.CloseStream();
                        }
                        if (longWait.IsCanceled)
                        {
                            return;
                        }
                        var irtProviders = lib.RetentionTimeProvidersIrt.ToArray();
                        if (!irtProviders.Any())
                        {
                            irtProviders = lib.RetentionTimeProviders.ToArray();
                        }
                        processed = RCalcIrt.ProcessRetentionTimes(monitor, irtProviders, irtProviders.Length,
                                                                   buildState.IrtStandard.Peptides.ToArray(), new DbIrtPeptide[0]);
                    });
                    if (status.IsCanceled)
                    {
                        return(false);
                    }
                    if (status.IsError)
                    {
                        throw status.ErrorException;
                    }
                }

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

                var recalibrate = false;
                if (processed.CanRecalibrateStandards(buildState.IrtStandard.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(TopMostApplicationForm) == DialogResult.Yes)
                        {
                            recalibrate = true;
                        }
                    }
                }

                var processedDbIrtPeptides = processed.DbIrtPeptides.ToArray();
                if (!processedDbIrtPeptides.Any())
                {
                    return(false);
                }

                using (var longWait = new LongWaitDlg {
                    Text = Resources.LibraryBuildNotificationHandler_LibraryBuildCompleteCallback_Adding_iRTs_to_library
                })
                {
                    ImmutableList <DbIrtPeptide> newStandards = null;
                    var status = longWait.PerformWork(TopMostApplicationForm, 800, monitor =>
                    {
                        if (recalibrate)
                        {
                            monitor.UpdateProgress(new ProgressStatus().ChangeSegments(0, 2));
                            newStandards = ImmutableList.ValueOf(processed.RecalibrateStandards(buildState.IrtStandard.Peptides));
                            processed    = RCalcIrt.ProcessRetentionTimes(
                                monitor, processed.ProviderData.Select(data => data.Value.RetentionTimeProvider),
                                processed.ProviderData.Count, newStandards.ToArray(), new DbIrtPeptide[0]);
                        }
                        var irtDb = IrtDb.CreateIrtDb(buildState.LibrarySpec.FilePath);
                        irtDb.AddPeptides(monitor, (newStandards ?? buildState.IrtStandard.Peptides).Concat(processedDbIrtPeptides).ToList());
                    });
                    if (status.IsError)
                    {
                        throw status.ErrorException;
                    }
                }
            }
            catch (Exception x)
            {
                MessageDlg.ShowWithException(TopMostApplicationForm,
                                             TextUtil.LineSeparate(Resources.LibraryBuildNotificationHandler_LibraryBuildCompleteCallback_An_error_occurred_trying_to_add_iRTs_to_the_library_, x.Message), x);
                return(false);
            }
            return(true);
        }
        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));
                                        if (lib != null)
                                        {
                                            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(IrtRegressionType.DEFAULT, 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();
        }
Esempio n. 3
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_);
                    }
                    PeakTransitionGroupFeatureSet featureScores = null;
                    if (ArrayUtil.EqualsDeep(_cacheCalculators, scoringModel.PeakFeatureCalculators))
                    {
                        featureScores = _cachedFeatureScores;
                    }
                    var resultsHandler = new MProphetResultsHandler(Document, scoringModel, featureScores)
                    {
                        QValueCutoff   = qCutoff,
                        OverrideManual = checkBoxOverwrite.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_);
                        }
                        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;
        }
        private void RefreshStatus()
        {
            if (File.Exists(textPath.Text))
            {
                btnAddFastaFile.Enabled = true;
                ProteomeDb        proteomeDb   = null;
                int               proteinCount = 0;
                IList <Digestion> digestions   = null;
                try
                {
                    using (var longWaitDlg = new LongWaitDlg
                    {
                        Text = Resources.BuildBackgroundProteomeDlg_RefreshStatus_Loading_Proteome_File,
                        Message =
                            string.Format(
                                Resources.BuildBackgroundProteomeDlg_RefreshStatus_Loading_protein_information_from__0__,
                                textPath.Text)
                    })
                    {
                        longWaitDlg.PerformWork(this, 1000, () =>
                        {
                            proteomeDb = ProteomeDb.OpenProteomeDb(textPath.Text);
                            if (proteomeDb != null)
                            {
                                proteinCount = proteomeDb.GetProteinCount(); // This can be a lengthy operation on a large protdb, do it within the longwait
                                digestions   = proteomeDb.ListDigestions();
                            }
                        });
                    }
                    if (proteomeDb == null)
                    {
                        throw new Exception();
                    }

                    tbxStatus.Text =
                        string.Format(
                            Resources.BuildBackgroundProteomeDlg_RefreshStatus_The_proteome_file_contains__0__proteins,
                            proteinCount);
                    if (proteinCount != 0 && digestions.Count > 0)
                    {
                        tbxStatus.Text = TextUtil.LineSeparate(tbxStatus.Text,
                                                               Resources.BuildBackgroundProteomeDlg_RefreshStatus_The_proteome_has_already_been_digested);
                    }
                }
                catch (Exception)
                {
                    tbxStatus.Text          = Resources.BuildBackgroundProteomeDlg_OkDialog_The_proteome_file_is_not_valid;
                    btnAddFastaFile.Enabled = false;
                }
                finally
                {
                    if (null != proteomeDb)
                    {
                        proteomeDb.Dispose();
                    }
                }
            }
            else
            {
                btnAddFastaFile.Enabled = false;
                tbxStatus.Text          = Resources.BuildBackgroundProteomeDlg_RefreshStatus_Click_the_Open_button_to_choose_an_existing_proteome_file_or_click_the_Create_button_to_create_a_new_proteome_file;
            }
        }
Esempio n. 5
0
        public static int Main(string[] args = null)
        {
            if (String.IsNullOrEmpty(Settings.Default.InstallationId)) // Each instance to have GUID
            {
                Settings.Default.InstallationId = Guid.NewGuid().ToString();
            }

            // don't allow 64-bit Skyline to run in a 32-bit process
            if (Install.Is64Bit && !Environment.Is64BitProcess)
            {
                string installUrl   = Install.Url;
                string installLabel = (installUrl == string.Empty) ? string.Empty : string.Format(Resources.Program_Main_Install_32_bit__0__, Name);
                AlertLinkDlg.Show(null,
                                  string.Format(Resources.Program_Main_You_are_attempting_to_run_a_64_bit_version_of__0__on_a_32_bit_OS_Please_install_the_32_bit_version, Name),
                                  installLabel,
                                  installUrl);
                return(1);
            }

            SecurityProtocolInitializer.Initialize(); // Enable highest available security level for HTTPS connections, esp. Chorus

            CommonFormEx.TestMode      = FunctionalTest;
            CommonFormEx.Offscreen     = SkylineOffscreen;
            CommonFormEx.ShowFormNames = FormEx.ShowFormNames = ShowFormNames;

            // For testing and debugging Skyline command-line interface
            bool openDoc = args != null && args.Length > 0 && args[0] == OPEN_DOCUMENT_ARG;

            if (args != null && args.Length > 0 && !openDoc)
            {
                if (!CommandLineRunner.HasCommandPrefix(args[0]))
                {
                    TextWriter textWriter;
                    if (Debugger.IsAttached)
                    {
                        textWriter = new DebugWriter();
                    }
                    else
                    {
                        AttachConsole(-1);
                        textWriter = Console.Out;
                    }
                    var writer = new CommandStatusWriter(textWriter);
                    if (args[0].Equals(@"--ui", StringComparison.InvariantCultureIgnoreCase))
                    {
                        // ReSharper disable once ObjectCreationAsStatement
                        new CommandLineUI(args, writer);
                    }
                    else
                    {
                        return(CommandLineRunner.RunCommand(args, writer));
                    }
                }
                else
                {
                    // For testing SkylineRunner without installation
                    CommandLineRunner clr = new CommandLineRunner();
                    clr.Start(args[0]);
                }

                return(EXIT_CODE_SUCCESS);
            }
            // The way Skyline command-line interface is run for an installation
            else if (AppDomain.CurrentDomain.SetupInformation.ActivationArguments != null &&
                     AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData != null &&
                     AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData.Length > 0 &&
                     CommandLineRunner.HasCommandPrefix(AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0]))
            {
                CommandLineRunner clr = new CommandLineRunner();
                clr.Start(AppDomain.CurrentDomain.SetupInformation.ActivationArguments.ActivationData[0]);

                // HACK: until the "invalid string binding" error is resolved, this will prevent an error dialog at exit
                Process.GetCurrentProcess().Kill();
                return(EXIT_CODE_SUCCESS);
            }

            try
            {
                Init();
                if (!string.IsNullOrEmpty(Settings.Default.DisplayLanguage))
                {
                    try
                    {
                        LocalizationHelper.CurrentUICulture =
                            CultureInfo.GetCultureInfo(Settings.Default.DisplayLanguage);
                    }
                    catch (CultureNotFoundException)
                    {
                    }
                }
                LocalizationHelper.InitThread(Thread.CurrentThread);

                // Make sure the user has agreed to the current license version
                // or one more recent.
                int licenseVersion = Settings.Default.LicenseVersionAccepted;
                if (licenseVersion < LICENSE_VERSION_CURRENT && !NoSaveSettings)
                {
                    // If the user has never used the application before, then
                    // they must have agreed to the current license agreement during
                    // installation.  Otherwise, make sure they agree to the new
                    // license agreement.
                    if (Install.Type == Install.InstallType.release &&
                        (licenseVersion != 0 || !Settings.Default.MainWindowSize.IsEmpty))
                    {
                        using (var dlg = new UpgradeLicenseDlg(licenseVersion))
                        {
                            if (dlg.ShowParentlessDialog() == DialogResult.Cancel)
                            {
                                return(EXIT_CODE_FAILURE_TO_START);
                            }
                        }
                    }

                    try
                    {
                        // Make sure the user never sees this again for this license version
                        Settings.Default.LicenseVersionAccepted = LICENSE_VERSION_CURRENT;
                        Settings.Default.Save();
                    }
// ReSharper disable EmptyGeneralCatchClause
                    catch (Exception)
// ReSharper restore EmptyGeneralCatchClause
                    {
                        // Just try to update the license version next time.
                    }
                }

                try
                {
                    // If this is a new installation copy over installed external tools from previous installation location.
                    var toolsDirectory = ToolDescriptionHelpers.GetToolsDirectory();
                    if (!Directory.Exists(toolsDirectory))
                    {
                        using (var longWaitDlg = new LongWaitDlg
                        {
                            Text = Name,
                            Message = Resources.Program_Main_Copying_external_tools_from_a_previous_installation,
                            ProgressValue = 0
                        })
                        {
                            longWaitDlg.PerformWork(null, 1000 * 3, broker => CopyOldTools(toolsDirectory, broker));
                        }
                    }
                }
                // ReSharper disable once EmptyGeneralCatchClause
                catch
                {
                }

                // Force live reports (though tests may reset this)
                //Settings.Default.EnableLiveReports = true;

                if (ReportShutdownDlg.HadUnexpectedShutdown())
                {
                    using (var reportShutdownDlg = new ReportShutdownDlg())
                    {
                        reportShutdownDlg.ShowParentlessDialog();
                    }
                }
                SystemEvents.DisplaySettingsChanged += SystemEventsOnDisplaySettingsChanged;
                // Careful, a throw out of the SkylineWindow constructor without this
                // catch causes Skyline just to appear to silently never start.  Makes for
                // some difficult debugging.
                try
                {
                    var activationArgs = AppDomain.CurrentDomain.SetupInformation.ActivationArguments;
                    if ((activationArgs != null &&
                         activationArgs.ActivationData != null &&
                         activationArgs.ActivationData.Length != 0) ||
                        openDoc ||
                        !Settings.Default.ShowStartupForm)
                    {
                        MainWindow = new SkylineWindow(args);
                    }
                    else
                    {
                        StartWindow = new StartPage();
                        try
                        {
                            if (StartWindow.ShowParentlessDialog() != DialogResult.OK)
                            {
                                Application.Exit();
                                return(EXIT_CODE_SUCCESS);
                            }

                            MainWindow = StartWindow.MainWindow;
                        }
                        finally
                        {
                            StartWindow.Dispose();
                            StartWindow = null;
                        }
                    }
                }
                catch (Exception x)
                {
                    ReportExceptionUI(x, new StackTrace(1, true));
                }

//                ConcurrencyVisualizer.StartEvents(MainWindow);

                // Position window offscreen for stress testing.
                if (SkylineOffscreen)
                {
                    FormEx.SetOffscreen(MainWindow);
                }

                SendAnalyticsHitAsync();

                MainToolServiceName = Guid.NewGuid().ToString();
                Application.Run(MainWindow);
                StopToolService();
            }
            catch (Exception x)
            {
                // Send unhandled exceptions to the console.
                Console.WriteLine(x.Message);
                Console.Write(x.StackTrace);
            }

            MainWindow = null;
            return(EXIT_CODE_SUCCESS);
        }
Esempio n. 6
0
        public 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);
            }
            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(DocumentContainer.Document);
                    var status = longWaitDlg.PerformWork(WizardForm, 800,
                                                         monitor => LibraryManager.BuildLibraryBackground(DocumentContainer, 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(DocumentContainer.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(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);
        }
Esempio n. 7
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 (!File.Exists(path))
            {
                MessageBox.Show(this, string.Format(Resources.EditLibraryDlg_OkDialog_The_file__0__does_not_exist, path), Program.Name);
                textPath.Focus();
                return;
            }
            if (FileEx.IsDirectory(path))
            {
                MessageBox.Show(this, string.Format(Resources.EditLibraryDlg_OkDialog_The_path__0__is_a_directory, path), Program.Name);
                textPath.Focus();
                return;
            }

            // Display an error message if the user is trying to add a BiblioSpec library,
            // and the library has the text "redundant" in the file name.
            if (path.EndsWith(BiblioSpecLiteSpec.EXT_REDUNDANT))
            {
                var message = TextUtil.LineSeparate(string.Format(Resources.EditLibraryDlg_OkDialog_The_file__0__appears_to_be_a_redundant_library, path),
                                                    Resources.EditLibraryDlg_OkDialog_Please_choose_a_non_redundant_library);
                MessageDlg.Show(this, string.Format(message, 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;
            }
            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))
                            {
                                switch (addPredictorDlg.ShowDialog(this))
                                {
                                case DialogResult.OK:
                                    Settings.Default.RTScoreCalculatorList.Add(addPredictorDlg.Calculator);
                                    Settings.Default.RetentionTimeList.Add(addPredictorDlg.Regression);
                                    Settings.Default.Save();
                                    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();
        }
Esempio n. 8
0
        public string ImportFromSpectralLibrary(LibrarySpec librarySpec, IDictionary <int, RegressionLine> chargeRegressionLines)
        {
            var     libraryManager = ((ILibraryBuildNotificationContainer)Program.MainWindow).LibraryManager;
            Library library        = null;
            IEnumerable <ValidatingIonMobilityPeptide> peptideCollisionalCrossSections = null;

            try
            {
                library = libraryManager.TryGetLibrary(librarySpec);
                using (var longWait = new LongWaitDlg
                {
                    Text = Resources.CollisionalCrossSectionGridViewDriver_AddSpectralLibrary_Adding_Spectral_Library,
                    Message = string.Format(Resources.CollisionalCrossSectionGridViewDriver_AddSpectralLibrary_Adding_ion_mobility_data_from__0_, librarySpec.FilePath),
                    FormBorderStyle = FormBorderStyle.Sizable
                })
                {
                    try
                    {
                        var status = longWait.PerformWork(MessageParent, 800, monitor =>
                        {
                            if (library == null)
                            {
                                library = librarySpec.LoadLibrary(new DefaultFileLoadMonitor(monitor));
                            }

                            int fileCount = library.FileCount ?? 0;
                            if (fileCount == 0)
                            {
                                string message = string.Format(Resources.CollisionalCrossSectionGridViewDriver_AddSpectralLibrary_The_library__0__does_not_contain_ion_mobility_information_,
                                                               librarySpec.FilePath);
                                monitor.UpdateProgress(new ProgressStatus(string.Empty).ChangeErrorException(new IOException(message)));
                                return;
                            }

                            peptideCollisionalCrossSections = ConvertDriftTimesToCollisionalCrossSections(monitor, GetIonMobilityProviders(library), fileCount, chargeRegressionLines);
                        });
                        if (status.IsError)
                        {
                            return(status.ErrorException.Message);
                        }
                    }
                    catch (Exception x)
                    {
                        var message = TextUtil.LineSeparate(string.Format(Resources.CollisionalCrossSectionGridViewDriver_AddSpectralLibrary_An_error_occurred_attempting_to_load_the_library_file__0__,
                                                                          librarySpec.FilePath),
                                                            x.Message);
                        return(message);
                    }
                }
            }
            finally
            {
                if (library != null)
                {
                    foreach (var pooledStream in library.ReadStreams)
                    {
                        pooledStream.CloseStream();
                    }
                }
            }

            if (peptideCollisionalCrossSections == null)
            {
                return(null);
            }

            SetTablePeptides(peptideCollisionalCrossSections);
            return(null);
        }
        public void MinimizeToFile(string targetFile)
        {
            var targetSkydFile = ChromatogramCache.FinalPathForName(targetFile, null);

            using (var skydSaver = new FileSaver(targetSkydFile))
                using (var scansSaver = new FileSaver(targetSkydFile + ChromatogramCache.SCANS_EXT, true))
                    using (var peaksSaver = new FileSaver(targetSkydFile + ChromatogramCache.PEAKS_EXT, true))
                        using (var scoreSaver = new FileSaver(targetSkydFile + ChromatogramCache.SCORES_EXT, true))
                        {
                            skydSaver.Stream = File.OpenWrite(skydSaver.SafeName);
                            using (var longWaitDlg = new LongWaitDlg(DocumentUIContainer))
                            {
                                longWaitDlg.PerformWork(this, 1000,
                                                        longWaitBroker =>
                                {
                                    longWaitBroker.Message = Resources.MinimizeResultsDlg_MinimizeToFile_Saving_new_cache_file;
                                    try
                                    {
                                        using (var backgroundWorker =
                                                   new BackgroundWorker(this, longWaitBroker))
                                        {
                                            backgroundWorker.RunBackground(skydSaver.Stream,
                                                                           scansSaver.FileStream, peaksSaver.FileStream, scoreSaver.FileStream);
                                        }
                                    }
                                    catch (ObjectDisposedException)
                                    {
                                        if (!longWaitBroker.IsCanceled)
                                        {
                                            throw;
                                        }
                                    }
                                });

                                if (longWaitDlg.IsCanceled)
                                {
                                    return;
                                }
                            }

                            var skylineWindow = (SkylineWindow)DocumentUIContainer;
                            if (!skylineWindow.SaveDocument(targetFile, false))
                            {
                                return;
                            }
                            try
                            {
                                var         measuredResults = DocumentUIContainer.Document.Settings.MeasuredResults.CommitCacheFile(skydSaver);
                                SrmDocument docOrig, docNew;
                                do
                                {
                                    docOrig = DocumentUIContainer.Document;
                                    docNew  = docOrig.ChangeMeasuredResults(measuredResults);
                                } while (!DocumentUIContainer.SetDocument(docNew, docOrig));
                            }
                            catch (Exception x)
                            {
                                var message = TextUtil.LineSeparate(
                                    string.Format(Resources.MinimizeResultsDlg_MinimizeToFile_An_unexpected_error_occurred_while_saving_the_data_cache_file__0__,
                                                  targetFile),
                                    x.Message);
                                MessageDlg.ShowWithException(this, message, x);
                                return;
                            }
                            skylineWindow.InvalidateChromatogramGraphs();
                        }
            DialogResult = DialogResult.OK;
        }
Esempio n. 10
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));
            }
        }
Esempio n. 11
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);
             }
             if (longWaitDlg.IsCanceled)
             {
                 return(false);
             }
         }
     }
     MessageDlg.Show(this, Resources.EditChorusAccountDlg_TestSettings_Settings_are_correct);
     return(true);
 }
Esempio n. 12
0
            private List <MeasuredPeptide> PickPeptides(SrmDocument doc, int count, ICollection <Target> exclude, RegressionOption currentRegression, out RegressionOption cirt)
            {
                cirt = null;

                if (!_picker.HasScoredPeptides)
                {
                    using (var longWaitDlg = new LongWaitDlg {
                        Text = Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_Calculating_scores
                    })
                    {
                        longWaitDlg.PerformWork(_parent, 1000, pm => _picker.ScorePeptides(doc, pm));
                        if (longWaitDlg.IsCanceled)
                        {
                            return(null);
                        }
                    }
                }

                RegressionLine cirtRegression    = null;
                var            useCirt           = false;
                var            cirtUsePredefined = false;

                if (_picker.TryGetCirtRegression(count, out var tryCirtRegression, out var matchedPeptides))
                {
                    var currentIsCirt = currentRegression != null && currentRegression.IsCirtDiscovered;
                    switch (MultiButtonMsgDlg.Show(_parent, string.Format(
                                                       Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_This_document_contains__0__CiRT_peptides__Would_you_like_to_use__1__of_them_as_your_iRT_standards_,
                                                       _picker.CirtPeptideCount, count), MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, true))
                    {
                    case DialogResult.Yes:
                        cirtRegression = tryCirtRegression;
                        useCirt        = true;
                        if (currentRegression?.RegressionLine == null || currentIsCirt)
                        {
                            switch (MultiButtonMsgDlg.Show(_parent,
                                                           Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_Would_you_like_to_use_the_predefined_iRT_values_,
                                                           Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_Predefined_values,
                                                           Resources.CalibrationGridViewDriver_FindEvenlySpacedPeptides_Calculate_from_regression,
                                                           true))
                            {
                            case DialogResult.Yes:
                                cirtUsePredefined = true;
                                break;

                            case DialogResult.No:
                                break;

                            case DialogResult.Cancel:
                                return(null);
                            }
                        }
                        break;

                    case DialogResult.No:
                        if (currentIsCirt)
                        {
                            cirtRegression = tryCirtRegression;
                        }
                        break;

                    case DialogResult.Cancel:
                        return(null);
                    }
                }

                var bestPeptides = _picker.Pick(count, exclude, useCirt);

                if (cirtRegression != null)
                {
                    var standardPeptides = bestPeptides.Select(pep => new StandardPeptide
                    {
                        Irt           = cirtUsePredefined ? _picker.CirtIrt(pep.Target).Value : double.NaN,
                        RetentionTime = pep.RetentionTime,
                        Target        = pep.Target
                    }).ToList();
                    cirt = new RegressionOption(Resources.CalibrationGridViewDriver_CiRT_option_name, cirtRegression,
                                                matchedPeptides.ToList(), standardPeptides, false, false);
                }
                return(bestPeptides);
            }
Esempio n. 13
0
        public void CommitBatchModifyDocument(string description, DataGridViewPasteHandler.BatchModifyInfo batchModifyInfo)
        {
            if (null == _batchChangesOriginalDocument)
            {
                throw new InvalidOperationException();
            }
            string message = Resources.DataGridViewPasteHandler_EndDeferSettingsChangesOnDocument_Updating_settings;

            SkylineWindow.ModifyDocument(description, document =>
            {
                VerifyDocumentCurrent(_batchChangesOriginalDocument, document);
                using (var longWaitDlg = new LongWaitDlg
                {
                    Message = message
                })
                {
                    SrmDocument newDocument = null;
                    longWaitDlg.PerformWork(SkylineWindow, 1000, progressMonitor =>
                    {
                        var srmSettingsChangeMonitor = new SrmSettingsChangeMonitor(progressMonitor,
                                                                                    message);
                        newDocument = _document.EndDeferSettingsChanges(_batchChangesOriginalDocument.Settings, srmSettingsChangeMonitor);
                    });
                    return(newDocument);
                }
            }, docPair =>
            {
                MessageType singular, plural;
                var detailType = MessageType.set_to_in_document_grid;
                Func <EditDescription, object[]> getArgsFunc = descr => new object[]
                {
                    descr.ColumnCaption.GetCaption(DataSchemaLocalizer), descr.ElementRefName,
                    CellValueToString(descr.Value)
                };

                switch (batchModifyInfo.BatchModifyAction)
                {
                case DataGridViewPasteHandler.BatchModifyAction.Paste:
                    singular = MessageType.pasted_document_grid_single;
                    plural   = MessageType.pasted_document_grid;
                    break;

                case DataGridViewPasteHandler.BatchModifyAction.Clear:
                    singular    = MessageType.cleared_document_grid_single;
                    plural      = MessageType.cleared_document_grid;
                    detailType  = MessageType.cleared_cell_in_document_grid;
                    getArgsFunc = descr => new[] { (object)descr.ColumnCaption.GetCaption(DataSchemaLocalizer), descr.ElementRefName };
                    break;

                case DataGridViewPasteHandler.BatchModifyAction.FillDown:
                    singular = MessageType.fill_down_document_grid_single;
                    plural   = MessageType.fill_down_document_grid;
                    break;

                default:
                    return(null);
                }

                var entry = AuditLogEntry.CreateCountChangeEntry(docPair.OldDoc, singular, plural,
                                                                 _batchEditDescriptions,
                                                                 descr => MessageArgs.Create(descr.ColumnCaption.GetCaption(DataSchemaLocalizer)),
                                                                 null).ChangeExtraInfo(batchModifyInfo.ExtraInfo + Environment.NewLine);

                entry = entry.Merge(batchModifyInfo.EntryCreator.Create(docPair));

                return(entry.AppendAllInfo(_batchEditDescriptions.Select(descr => new MessageInfo(detailType,
                                                                                                  getArgsFunc(descr))).ToList()));
            });
            _batchChangesOriginalDocument = null;
            _batchEditDescriptions        = null;
            DocumentChangedEventHandler(_documentContainer, new DocumentChangedEventArgs(_document));
        }
Esempio n. 14
0
        public static bool AddIrts(IrtRegressionType regressionType, Library lib, LibrarySpec libSpec, IrtStandard standard, Control parent, bool useTopMostForm)
        {
            if (lib == null || !lib.IsLoaded || standard == null || standard.Name.Equals(IrtStandard.EMPTY.Name))
            {
                return(false);
            }

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

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

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

            int?numCirt = null;

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

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

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

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

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

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

            var recalibrate = false;

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

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

            using (var longWait = new LongWaitDlg {
                Text = Resources.LibraryBuildNotificationHandler_AddIrts_Adding_iRTs_to_library
            })
            {
                try
                {
                    var status = longWait.PerformWork(GetParent(), 800, monitor =>
                    {
                        ImportPeptideSearch.CreateIrtDb(libSpec.FilePath, processed, standardPeptides, recalibrate, regressionType, monitor);
                    });
                    if (status.IsError)
                    {
                        throw status.ErrorException;
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(GetParent(),
                                                 TextUtil.LineSeparate(
                                                     Resources.LibraryBuildNotificationHandler_AddIrts_An_error_occurred_trying_to_add_iRTs_to_the_library_,
                                                     x.Message), x);
                    return(false);
                }
            }
            return(true);
        }
        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;
                builder.DebugMode             = DebugMode;
            }
            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 buildState = new LibraryManager.BuildState(null, null);
                        var status     = longWaitDlg.PerformWork(WizardForm, 800,
                                                                 monitor => LibraryManager.BuildLibraryBackground(DocumentContainer, builder, monitor, buildState));
                        LastBuildCommandArgs = buildState.BuildCommandArgs;
                        LastBuildOutput      = buildState.BuildOutput;
                        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 = _driverStandards.SelectedItem;
            var addedIrts           = false;

            if (selectedIrtStandard != null && !selectedIrtStandard.Name.Equals(IrtStandard.EMPTY.Name))
            {
                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);
        }
Esempio n. 16
0
        private void LaunchPeptideProteinsQuery()
        {
            HashSet <Protein> proteinSet = new HashSet <Protein>();

            using (var longWaitDlg = new LongWaitDlg
            {
                Text = Resources.UniquePeptidesDlg_LaunchPeptideProteinsQuery_Querying_Background_Proteome_Database,
                Message = Resources.UniquePeptidesDlg_LaunchPeptideProteinsQuery_Looking_for_proteins_with_matching_peptide_sequences
            })
            {
                try
                {
                    longWaitDlg.PerformWork(this, 1000, QueryPeptideProteins);
                }
                catch (Exception x)
                {
                    var message = TextUtil.LineSeparate(string.Format(Resources.UniquePeptidesDlg_LaunchPeptideProteinsQuery_Failed_querying_background_proteome__0__,
                                                                      BackgroundProteome.Name), x.Message);
                    MessageDlg.ShowWithException(this, message, x);
                }
            }
            if (_peptideProteins == null)
            {
                Close();
                return;
            }
            foreach (var proteins in _peptideProteins)
            {
                proteinSet.UnionWith(proteins);
            }
            List <Protein> proteinList = new List <Protein>();

            proteinList.AddRange(proteinSet);
            proteinList.Sort();
            foreach (var protein in proteinList)
            {
                ProteinColumn proteinColumn = new ProteinColumn(_proteinColumns.Count, protein);
                _proteinColumns.Add(proteinColumn);
                DataGridViewCheckBoxColumn column = new DataGridViewCheckBoxColumn
                {
                    Name        = proteinColumn.Name,
                    HeaderText  = ((protein.Gene != null) ? String.Format(Resources.UniquePeptidesDlg_LaunchPeptideProteinsQuery_, protein.Name, protein.Gene) : protein.Name), // Not L10N
                    ReadOnly    = true,
                    ToolTipText = protein.ProteinMetadata.DisplayTextWithoutName(),
                    SortMode    = DataGridViewColumnSortMode.Automatic,
                    Tag         = proteinColumn,
                };
                dataGridView1.Columns.Add(column);
            }

            for (int i = 0; i < _peptideDocNodes.Count; i++)
            {
                var peptide  = _peptideDocNodes[i];
                var proteins = _peptideProteins[i];
                var row      = dataGridView1.Rows[dataGridView1.Rows.Add()];
                row.Tag = peptide;
                row.Cells[PeptideIncludedColumn.Name].Value = true;
                row.Cells[PeptideColumn.Name].Value         = peptide.Peptide.Sequence;
                foreach (var proteinColumn in _proteinColumns)
                {
                    row.Cells[proteinColumn.Name].Value = proteins.Contains(proteinColumn.Protein);
                }
            }
            dataGridView1.EndEdit();
            if (dataGridView1.RowCount > 0)
            {
                // Select the first peptide to populate the other controls in the dialog.
                dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[1];
            }

            DrawCheckBoxOnPeptideIncludedColumnHeader();
        }
Esempio n. 17
0
        public bool ImportFasta(IrtStandard irtStandard)
        {
            var settings        = DocumentContainer.Document.Settings;
            var peptideSettings = settings.PeptideSettings;
            int missedCleavages = MaxMissedCleavages;
            var enzyme          = Enzyme;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return(true);
        }
Esempio n. 18
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")) // Not L10N
                    {
                        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;
            }
        }
Esempio n. 19
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);
        }
Esempio n. 20
0
        private bool ExportReport(string fileName, char separator)
        {
            try
            {
                using (var saver = new FileSaver(fileName))
                {
                    if (!saver.CanSave(this))
                    {
                        return(false);
                    }

                    using (var writer = new StreamWriter(saver.SafeName))
                    {
                        Report report  = GetReport();
                        bool   success = false;

                        using (var longWait = new LongWaitDlg {
                            Text = Resources.ExportReportDlg_ExportReport_Generating_Report
                        })
                        {
                            longWait.PerformWork(this, 1500, broker =>
                            {
                                var status = new ProgressStatus(Resources.ExportReportDlg_GetDatabase_Analyzing_document);
                                broker.UpdateProgress(status);
                                Database database = EnsureDatabase(broker, 80, ref status);
                                if (broker.IsCanceled)
                                {
                                    return;
                                }
                                broker.UpdateProgress(status = status.ChangeMessage(Resources.ExportReportDlg_ExportReport_Building_report));
                                ResultSet resultSet          = report.Execute(database);
                                if (broker.IsCanceled)
                                {
                                    return;
                                }
                                broker.UpdateProgress(status = status.ChangePercentComplete(95)
                                                               .ChangeMessage(Resources.ExportReportDlg_ExportReport_Writing_report));

                                ResultSet.WriteReportHelper(resultSet, separator, writer, CultureInfo);

                                writer.Flush();
                                writer.Close();

                                if (broker.IsCanceled)
                                {
                                    return;
                                }
                                broker.UpdateProgress(status.Complete());

                                saver.Commit();
                                success = true;
                            });
                        }

                        return(success);
                    }
                }
            }
            catch (Exception x)
            {
                MessageDlg.ShowWithException(this, string.Format(Resources.ExportReportDlg_ExportReport_Failed_exporting_to, fileName, GetExceptionDisplayMessage(x)), x);
                return(false);
            }
        }
Esempio n. 21
0
        public override void UpdateGraph(bool selectionChanged)
        {
            SrmDocument document         = !_exportMethodDlg ? GraphSummary.DocumentUIContainer.DocumentUI : Program.MainWindow.DocumentUI;
            var         windows          = ScheduleWindows;
            var         brukerTemplate   = BrukerTemplateFile;
            var         brukerMetricType = BrukerMetricType;

            // No need to re-graph for a selection change
            if (ReferenceEquals(document, _documentShowing) && ArrayUtil.EqualsDeep(windows, _windowsShowing) &&
                Equals(BrukerTemplateFile, _brukerTemplate) && Equals(BrukerMetricType, _brukerMetricType))
            {
                return;
            }

            _documentShowing  = document;
            _windowsShowing   = windows;
            _brukerTemplate   = brukerTemplate;
            _brukerMetricType = brukerMetricType;

            // TODO: Make it possible to see transition scheduling when full-scan enabled.
            if (string.IsNullOrEmpty(brukerTemplate))
            {
                XAxis.Title.Text = Resources.RTScheduleGraphPane_RTScheduleGraphPane_Scheduled_Time;
                YAxis.Title.Text = document.Settings.TransitionSettings.FullScan.IsEnabledMsMs
                    ? Resources.RTScheduleGraphPane_UpdateGraph_Concurrent_Precursors
                    : Resources.RTScheduleGraphPane_UpdateGraph_Concurrent_Transitions;
            }
            else if (BrukerMetrics == null)
            {
                XAxis.Title.Text = Resources.RTScheduleGraphPane_RTScheduleGraphPane_Scheduled_Time;
                YAxis.Title.Text = Resources.RTScheduleGraphPane_UpdateGraph_Concurrent_Accumulations;
            }
            else
            {
                switch (brukerMetricType)
                {
                case SchedulingMetrics.CONCURRENT_FRAMES:
                    XAxis.Title.Text = Resources.RTScheduleGraphPane_RTScheduleGraphPane_Scheduled_Time;
                    YAxis.Title.Text = Resources.RTScheduleGraphPane_UpdateGraph_Concurrent_frames;
                    break;

                case SchedulingMetrics.MAX_SAMPLING_TIMES:
                    XAxis.Title.Text = Resources.RTScheduleGraphPane_UpdateGraph_Target;
                    YAxis.Title.Text = Resources.RTScheduleGraphPane_UpdateGraph_Max_sampling_times;
                    break;

                case SchedulingMetrics.MEAN_SAMPLING_TIMES:
                    XAxis.Title.Text = Resources.RTScheduleGraphPane_UpdateGraph_Target;
                    YAxis.Title.Text = Resources.RTScheduleGraphPane_UpdateGraph_Mean_sampling_times;
                    break;

                case SchedulingMetrics.REDUNDANCY_OF_TARGETS:
                    XAxis.Title.Text = Resources.RTScheduleGraphPane_RTScheduleGraphPane_Scheduled_Time;
                    YAxis.Title.Text = Resources.RTScheduleGraphPane_UpdateGraph_Redundancy_of_targets;
                    break;

                case SchedulingMetrics.TARGETS_PER_FRAME:
                    XAxis.Title.Text = Resources.RTScheduleGraphPane_RTScheduleGraphPane_Scheduled_Time;
                    YAxis.Title.Text = Resources.RTScheduleGraphPane_UpdateGraph_Targets_per_frame;
                    break;
                }
            }

            CurveList.Clear();

            using (var longWait = new LongWaitDlg())
            {
                longWait.PerformWork(null, 800, progressMonitor =>
                {
                    AddCurve(document, Color.Blue, progressMonitor);
                    for (int i = 0; i < windows.Length; i++)
                    {
                        double window = windows[i];
                        // Do not show the window used by the current document twice.
                        if (window == GetSchedulingWindow(document))
                        {
                            continue;
                        }

                        var settings = document.Settings.ChangePeptidePrediction(p => p.ChangeMeasuredRTWindow(window));
                        if (settings.PeptideSettings.Prediction.RetentionTime != null)
                        {
                            settings = settings.ChangePeptidePrediction(p =>
                                                                        p.ChangeRetentionTime(p.RetentionTime.ChangeTimeWindow(window)));
                        }
                        var docWindow = document.ChangeSettings(settings);

                        AddCurve(docWindow, COLORS_WINDOW[(i + 1) % COLORS_WINDOW.Count], progressMonitor);
                    }
                });
            }

            AxisChange();
        }
Esempio n. 22
0
        public bool ImportFasta()
        {
            var settings        = SkylineWindow.Document.Settings;
            var peptideSettings = settings.PeptideSettings;
            int missedCleavages = MaxMissedCleavages;
            var enzyme          = Enzyme;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return(true);
        }
Esempio n. 23
0
        public void OkDialog()
        {
            using (var dlg = new SaveFileDialog
            {
                Title = Resources.MProphetFeaturesDlg_OkDialog_Export_mProphet_Features,
                OverwritePrompt = true,
                DefaultExt = EXT,
                Filter = TextUtil.FileDialogFilterAll(Resources.MProphetFeaturesDlg_OkDialog_mProphet_Feature_Files, EXT),
            })
            {
                if (!string.IsNullOrEmpty(DocumentFilePath))
                {
                    dlg.InitialDirectory = Path.GetDirectoryName(DocumentFilePath);
                    dlg.FileName         = Path.GetFileNameWithoutExtension(DocumentFilePath) + EXT;
                }
                if (dlg.ShowDialog(this) == DialogResult.Cancel)
                {
                    return;
                }

                string mainVarName  = comboMainVar.SelectedItem.ToString();
                var    displayCalcs = new List <IPeakFeatureCalculator> {
                    GetCalcFromName(mainVarName)
                };
                displayCalcs.AddRange(from object calcName in checkedListVars.CheckedItems select GetCalcFromName(calcName.ToString()));

                IPeakScoringModel currentPeakScoringModel = Document.Settings.PeptideSettings.Integration.PeakScoringModel;
                var mProphetScoringModel = currentPeakScoringModel as MProphetPeakScoringModel;
//                if (mProphetScoringModel == null)
//                {
//                    MessageDlg.Show(this, Resources.MProphetFeaturesDlg_OkDialog_To_export_MProphet_features_first_train_an_MProphet_model_);
//                    return;
//                }
                var resultsHandler = new MProphetResultsHandler(Document, mProphetScoringModel);

                using (var longWaitDlg = new LongWaitDlg
                {
                    Text = Resources.SkylineWindow_OpenSharedFile_Extracting_Files,
                })
                {
                    try
                    {
                        longWaitDlg.PerformWork(this, 1000, b =>
                                                WriteFeatures(dlg.FileName,
                                                              resultsHandler,
                                                              displayCalcs,
                                                              LocalizationHelper.CurrentCulture,
                                                              checkBoxBestOnly.Checked,
                                                              !checkBoxTargetsOnly.Checked,
                                                              b));
                        if (longWaitDlg.IsCanceled)
                        {
                            return;
                        }
                    }
                    catch (Exception x)
                    {
                        var message = TextUtil.LineSeparate(string.Format(Resources.MProphetFeaturesDlg_OkDialog_Failed_attempting_to_save_mProphet_features_to__0__, dlg.FileName),
                                                            x.Message);
                        MessageDlg.ShowWithException(this, message, x);
                    }
                }
            }

            DialogResult = DialogResult.OK;
        }
Esempio n. 24
0
        public void ShowGraph()
        {
            var calc = _driverCalculators.SelectedItem;

            if (calc == null)
            {
                return;
            }

            if (!calc.IsUsable)
            {
                using (var longWait = new LongWaitDlg
                {
                    Text = Resources.EditRTDlg_ShowGraph_Initializing,
                    Message = string.Format(Resources.EditRTDlg_ShowGraph_Initializing__0__calculator, calc.Name)
                })
                {
                    try
                    {
                        var status = longWait.PerformWork(this, 800, monitor =>
                        {
                            calc = Settings.Default.RTScoreCalculatorList.Initialize(monitor, calc);
                        });
                        if (status.IsError)
                        {
                            MessageBox.Show(this, status.ErrorException.Message, Program.Name);
                            return;
                        }
                    }
                    catch (Exception x)
                    {
                        var message = TextUtil.LineSeparate(string.Format(Resources.EditRTDlg_ShowGraph_An_error_occurred_attempting_to_initialize_the_calculator__0__,
                                                                          calc.Name),
                                                            x.Message);
                        MessageDlg.ShowWithException(this, message, x);
                        return;
                    }
                }
            }

            var helper = new MessageBoxHelper(this);

            double slope;

            if (!helper.ValidateDecimalTextBox(textSlope, out slope))
            {
                return;
            }

            double intercept;

            if (!helper.ValidateDecimalTextBox(textIntercept, out intercept))
            {
                return;
            }

            var scores = new List <double>();
            var times  = new List <double>();

            foreach (var measuredPeptide in Peptides)
            {
                times.Add(measuredPeptide.RetentionTime);
                double?score = calc.ScoreSequence(measuredPeptide.Target);
                scores.Add(score ?? calc.UnknownScore);
            }

            var    statScores       = new Statistics(scores);
            var    statTimes        = new Statistics(times);
            double slopeRegress     = statTimes.Slope(statScores);
            double interceptRegress = statTimes.Intercept(statScores);

            var regressionGraphData = new RegressionGraphData
            {
                Title                 = Resources.EditRTDlg_ShowGraph_Retention_Times_by_Score,
                LabelX                = calc.Name,
                LabelY                = Resources.EditRTDlg_ShowGraph_Measured_Time,
                XValues               = scores.ToArray(),
                YValues               = times.ToArray(),
                RegressionLine        = new RegressionLine(slopeRegress, interceptRegress),
                RegressionLineCurrent = new RegressionLine(slope, intercept)
            };

            using (var dlg = new GraphRegression(new[] { regressionGraphData }))
            {
                dlg.ShowDialog(this);
            }
        }
Esempio n. 25
0
 public void LongWaitDlgAction(SkylineWindow skylineWindow)
 {
     skylineWindow.ResetDefaultSettings();
     try
     {
         using (var longWaitDlg = new LongWaitDlg
         {
             Text = Resources.ActionTutorial_LongWaitDlgAction_Downloading_Tutorial_Zip_File,
             Message =
                 String.Format(
                     Resources
                         .ActionTutorial_LongWaitDlgAction_Downloading_to___0__1_Tutorial_will_open_in_browser_when_download_is_complete_,
                     getTempPath(), Environment.NewLine),
             ProgressValue = 0
         })
         {
             longWaitDlg.PerformWork(skylineWindow, 1000, DownloadTutorials);
             if (longWaitDlg.IsCanceled)
             {
                 return;
             }
         }
         using (var longWaitDlg = new LongWaitDlg
         {
             Text =
                 Resources.ActionTutorial_LongWaitDlgAction_Extracting_Tutorial_Zip_File_in_the_same_directory_,
             ProgressValue = 0
         })
         {
             longWaitDlg.PerformWork(skylineWindow, 1000, ExtractTutorial);
         }
     }
     catch (Exception exception)
     {
         MessageDlg.ShowWithException(Program.MainWindow, string.Format(Resources.ActionTutorial_DownloadTutorials_Error__0_, exception.Message), exception);
     }
 }
Esempio n. 26
0
        private void LaunchPeptideProteinsQuery()
        {
            HashSet <Protein> proteinSet = new HashSet <Protein>();

            using (var longWaitDlg = new LongWaitDlg
            {
                Text = Resources.UniquePeptidesDlg_LaunchPeptideProteinsQuery_Querying_Background_Proteome_Database,
                Message = Resources.UniquePeptidesDlg_LaunchPeptideProteinsQuery_Looking_for_proteins_with_matching_peptide_sequences
            })
            {
                try
                {
                    longWaitDlg.PerformWork(this, 1000, QueryPeptideProteins);
                }
                catch (Exception x)
                {
                    var message = TextUtil.LineSeparate(string.Format(Resources.UniquePeptidesDlg_LaunchPeptideProteinsQuery_Failed_querying_background_proteome__0__,
                                                                      BackgroundProteome.Name), x.Message);
                    MessageDlg.ShowWithException(this, message, x);
                }
            }
            if (_peptideProteins == null)
            {
                Close();
                return;
            }
            foreach (var proteins in _peptideProteins)
            {
                proteinSet.UnionWith(proteins);
            }
            List <Protein> proteinList = new List <Protein>();

            proteinList.AddRange(proteinSet);
            proteinList.Sort();
            foreach (var protein in proteinList)
            {
                ProteinColumn proteinColumn = new ProteinColumn(_proteinColumns.Count, protein);
                _proteinColumns.Add(proteinColumn);
                var accession   = string.IsNullOrEmpty(protein.Accession) ? string.Empty : protein.Accession + "\n"; // Not L10N
                var proteinName = protein.Name;
                // Isoforms may all get the same preferredname, which is confusing to look at
                if (!string.IsNullOrEmpty(protein.PreferredName) &&
                    !proteinList.Any(p => (!ReferenceEquals(p, protein) &&
                                           (string.Compare(p.PreferredName, protein.PreferredName, StringComparison.OrdinalIgnoreCase) == 0))))
                {
                    proteinName = protein.PreferredName;
                }
                var gene = string.IsNullOrEmpty(protein.Gene) ? string.Empty : "\n" + protein.Gene; // Not L10N
                DataGridViewCheckBoxColumn column = new DataGridViewCheckBoxColumn
                {
                    Name        = proteinColumn.Name,
                    HeaderText  = accession + proteinName + gene,
                    ReadOnly    = true,
                    ToolTipText = protein.ProteinMetadata.DisplayTextWithoutName(),
                    SortMode    = DataGridViewColumnSortMode.Automatic,
                    Tag         = proteinColumn,
                };
                dataGridView1.Columns.Add(column);
            }

            for (int i = 0; i < _peptideDocNodes.Count; i++)
            {
                var peptide  = _peptideDocNodes[i];
                var proteins = _peptideProteins[i];
                var row      = dataGridView1.Rows[dataGridView1.Rows.Add()];
                row.Tag = peptide;
                row.Cells[PeptideIncludedColumn.Name].Value = true;
                row.Cells[PeptideColumn.Name].Value         = peptide.Peptide.Sequence;
                foreach (var proteinColumn in _proteinColumns)
                {
                    row.Cells[proteinColumn.Name].Value = proteins.Contains(proteinColumn.Protein);
                }
            }
            dataGridView1.EndEdit();
            if (dataGridView1.RowCount > 0)
            {
                // Select the first peptide to populate the other controls in the dialog.
                dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[1];
            }

            DrawCheckBoxOnPeptideIncludedColumnHeader();
        }