Beispiel #1
0
        public static void GetLibIrtProviders(Library lib, IrtStandard standard, IProgressMonitor monitor,
                                              out IRetentionTimeProvider[] irtProviders, out List <IrtStandard> autoStandards, out DbIrtPeptide[] cirtPeptides)
        {
            monitor?.UpdateProgress(new ProgressStatus().ChangePercentComplete(-1));

            irtProviders = lib.RetentionTimeProvidersIrt.ToArray();
            if (!irtProviders.Any())
            {
                irtProviders = lib.RetentionTimeProviders.ToArray();
            }

            var isAuto = ReferenceEquals(standard, IrtStandard.AUTO);

            autoStandards = isAuto
                ? IrtStandard.BestMatch(irtProviders.SelectMany(provider => provider.PeptideRetentionTimes).Select(rt => rt.PeptideSequence))
                : null;

            if (ReferenceEquals(standard, IrtStandard.CIRT_SHORT) || isAuto && autoStandards.Count == 0)
            {
                var libPeptides = new TargetMap <bool>(irtProviders
                                                       .SelectMany(provider => provider.PeptideRetentionTimes)
                                                       .Select(rt => new KeyValuePair <Target, bool>(rt.PeptideSequence, true)));
                cirtPeptides = IrtStandard.CIRT.Peptides.Where(pep => libPeptides.ContainsKey(pep.ModifiedTarget)).ToArray();
            }
            else
            {
                cirtPeptides = new DbIrtPeptide[0];
            }
        }
Beispiel #2
0
        public CalibrateIrtDlg(IrtStandard standard, IEnumerable <IrtStandard> existing, DbIrtPeptide[] updatePeptides)
        {
            InitializeComponent();

            Icon = Resources.Skyline;

            _standard = standard;
            _standardPeptidesSorted = standard != null?standard.Peptides.OrderBy(pep => pep.Irt).ToArray() : new DbIrtPeptide[0];

            _existing       = existing;
            _updatePeptides = updatePeptides;

            _gridViewDriver = new CalibrationGridViewDriver(this, gridViewCalibrate, bindingSourceStandard,
                                                            new SortableBindingList <StandardPeptide>());

            FireStandardsChanged = true;

            comboRegression.Items.AddRange(RegressionOption.All(Program.ActiveDocumentUI).ToArray());
            comboRegression.SelectedIndex = 0;

            if (IsRecalibration)
            {
                textName.Text   = standard?.Name;
                FormBorderStyle = FormBorderStyle.Fixed3D;
                panelPeptides.Hide();
                btnUseCurrent.Hide();
                Height -= panelPeptides.Height;
                var standardPeptides = _standardPeptidesSorted.Select(pep => pep.PeptideModSeq).ToArray();
                comboMinPeptide.Items.AddRange(standardPeptides);
                comboMaxPeptide.Items.AddRange(standardPeptides);
                if (standardPeptides.Length > 0)
                {
                    // Look for standard peptides with whole number values as the suggested fixed points
                    var iFixed1 = _standardPeptidesSorted.IndexOf(pep => Math.Round(pep.Irt, 8) == Math.Round(pep.Irt));
                    var iFixed2 = _standardPeptidesSorted.LastIndexOf(pep => Math.Round(pep.Irt, 8) == Math.Round(pep.Irt));
                    if (iFixed1 == -1 || iFixed2 == -1)
                    {
                        iFixed1 = 0;
                        iFixed2 = _standardPeptidesSorted.Length - 1;
                    }
                    else if (iFixed1 == iFixed2)
                    {
                        if (iFixed1 < _standardPeptidesSorted.Length / 2)
                        {
                            iFixed2 = _standardPeptidesSorted.Length - 1;
                        }
                        else
                        {
                            iFixed1 = 0;
                        }
                    }
                    comboMinPeptide.SelectedIndex = iFixed1;
                    comboMaxPeptide.SelectedIndex = iFixed2;
                    SetIrtRange(_standardPeptidesSorted[iFixed1].Irt, _standardPeptidesSorted[iFixed2].Irt);
                }
            }
        }
 public BuildPeptideSearchLibrarySettings(double cutoffScore, IList <string> searchFileNames, IrtStandard standard, bool includeAmbiguousMatches, bool filterForDocumentPeptides, ImportPeptideSearchDlg.Workflow workFlow)
 {
     CutoffScore     = cutoffScore;
     SearchFileNames = searchFileNames == null
         ? new List <AuditLogPath>()
         : searchFileNames.Select(AuditLogPath.Create).ToList();
     Standard = standard;
     IncludeAmbiguousMatches   = includeAmbiguousMatches;
     FilterForDocumentPeptides = filterForDocumentPeptides;
     WorkFlow = workFlow;
 }
Beispiel #4
0
 public void OkDialogStandard(IrtStandard standard)
 {
     for (var i = 0; i < comboExisting.Items.Count; i++)
     {
         if (ReferenceEquals((IrtStandard)comboExisting.Items[i], standard))
         {
             radioExisting.Checked       = true;
             comboExisting.SelectedIndex = i;
             OkDialog();
             return;
         }
     }
 }
Beispiel #5
0
 public PrositLibraryBuilder(SrmDocument doc, string name, string outPath, Func <bool> replaceLibrary,
                             IrtStandard irtStandard, IList <PeptideDocNode> peptides, IList <TransitionGroupDocNode> precursors, int nce)
 {
     _prositClient   = PrositPredictionClient.Current;
     _intensityModel = PrositIntensityModel.Instance;
     _rtModel        = PrositRetentionTimeModel.Instance;
     _peptides       = peptides;
     _precursors     = precursors;
     _document       = doc;
     LibrarySpec     = new BiblioSpecLiteSpec(name, outPath); // Needs to be created before building
     _replaceLibrary = replaceLibrary;
     IrtStandard     = irtStandard;
     _nce            = nce;
 }
Beispiel #6
0
        public CalibrateIrtDlg(IrtStandard standard, IEnumerable <IrtStandard> existing, DbIrtPeptide[] updatePeptides)
        {
            InitializeComponent();

            Icon = Resources.Skyline;

            var docPeptides = new Dictionary <Target, PeptideDocNode>();

            foreach (var nodePep in Program.ActiveDocumentUI.Peptides.Where(nodePep => nodePep.PercentileMeasuredRetentionTime.HasValue && !nodePep.IsDecoy))
            {
                if (!docPeptides.ContainsKey(nodePep.ModifiedTarget))
                {
                    docPeptides[nodePep.ModifiedTarget] = nodePep;
                }
            }

            _standard = standard;
            _recalibrationPeptides = standard?.Peptides.OrderBy(pep => pep.Irt).Select(pep => new StandardPeptide
            {
                Irt           = pep.Irt,
                RetentionTime = docPeptides.TryGetValue(pep.Target, out var nodePep) ? nodePep.PercentileMeasuredRetentionTime.Value : double.NaN,
                Target        = pep.Target
            }).ToList();
Beispiel #7
0
        public void OkDialog()
        {
            var helper = new MessageBoxHelper(this);

            if (!helper.ValidateNameTextBox(textName, out var name))
            {
                return;
            }
            else if (_existing.Contains(r => !ReferenceEquals(_standard, r) && Equals(name, r.Name)))
            {
                helper.ShowTextBoxError(textName, Resources.CalibrateIrtDlg_OkDialog_The_iRT_standard__0__already_exists_, name);
                return;
            }

            if (!TryGetLine(true, out var linearEquation))
            {
                return;
            }

            if (!IsRecalibration)
            {
                IrtStandard = new IrtStandard(name, null,
                                              StandardPeptideList.Select(pep => new DbIrtPeptide(pep.Target, pep.Irt, true, TimeSource.peak)));
            }
            else
            {
                foreach (var pep in _updatePeptides)
                {
                    pep.Irt = linearEquation.GetY(pep.Irt);
                }
                IrtStandard = new IrtStandard(name, null,
                                              _standard.Peptides.Select(pep =>
                                                                        new DbIrtPeptide(pep.Target, linearEquation.GetY(pep.Irt), true, TimeSource.peak)));
            }
            DialogResult = DialogResult.OK;
        }
Beispiel #8
0
        private static void removePeptidesAndImport(IrtStandard standard, int numPeptides)
        {
            Target[]      standardPeptides = null;
            List <Target> removedPeptides  = null;

            RunUI(() =>
            {
                standardPeptides = standard.Peptides.Select(pep => pep.Target).ToArray();
                removedPeptides  = standardPeptides.Except(SkylineWindow.DocumentUI.Peptides.Select(nodePep => nodePep.ModifiedTarget)).ToList();
            });
            var toRemove = standardPeptides.Except(removedPeptides).ToArray();

            if (numPeptides > toRemove.Length)
            {
                Assert.Fail("Not enough peptides to remove");
            }

            for (var i = 0; i < numPeptides; i++)
            {
                RemovePeptide(toRemove[i]);
                removedPeptides.Add(toRemove[i]);
            }

            if (!removedPeptides.Any())
            {
                var importResultsDlg = ShowDialog <ImportResultsDlg>(SkylineWindow.ImportResults);
                OkDialog(importResultsDlg, importResultsDlg.CancelDialog);
                return;
            }

            var docCount = standardPeptides.Length - removedPeptides.Count;

            if (docCount >= RCalcIrt.MinStandardCount(standardPeptides.Length))
            {
                var allowedMissing = docCount - RCalcIrt.MinStandardCount(standardPeptides.Length);
                var warningDlg     = ShowDialog <MultiButtonMsgDlg>(SkylineWindow.ImportResults);
                RunUI(() =>
                {
                    foreach (var pep in removedPeptides)
                    {
                        Assert.IsTrue(warningDlg.Message.Contains(pep.ToString()));
                    }
                    Assert.IsTrue(warningDlg.Message.Contains(
                                      string.Format(Resources.SkylineWindow_ImportResults_The_document_contains__0__of_these_iRT_standard_peptides_, docCount)));
                    Assert.IsTrue(warningDlg.Message.Contains(
                                      allowedMissing > 0
                            ? string.Format(Resources.SkylineWindow_ImportResults_A_maximum_of__0__may_be_missing_and_or_outliers_for_a_successful_import_, allowedMissing)
                            : Resources.SkylineWindow_ImportResults_None_may_be_missing_or_outliers_for_a_successful_import_));
                });
                OkDialog(warningDlg, warningDlg.BtnCancelClick);
            }
            else
            {
                var errorDlg = ShowDialog <MessageDlg>(SkylineWindow.ImportResults);
                RunUI(() =>
                {
                    foreach (var pep in removedPeptides)
                    {
                        Assert.IsTrue(errorDlg.Message.Contains(pep.ToString()));
                    }
                    Assert.IsTrue(errorDlg.Message.Contains(
                                      docCount > 0
                            ? string.Format(Resources.SkylineWindow_ImportResults_The_document_only_contains__0__of_these_iRT_standard_peptides_, docCount)
                            : Resources.SkylineWindow_ImportResults_The_document_does_not_contain_any_of_these_iRT_standard_peptides_));
                    Assert.IsTrue(errorDlg.Message.Contains(Resources.SkylineWindow_ImportResults_Add_missing_iRT_standard_peptides_to_your_document_or_change_the_retention_time_predictor_));
                });
                OkDialog(errorDlg, errorDlg.OkDialog);
            }
        }
Beispiel #9
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);
        }
Beispiel #10
0
        public static bool AddIrts(Library lib, LibrarySpec libSpec, IrtStandard standard, Control parent, bool useTopMostForm = false)
        {
            if (lib == null || !lib.IsLoaded || standard == null || standard.Name.Equals(IrtStandard.EMPTY.Name))
            {
                return(false);
            }

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

            IRetentionTimeProvider[] irtProviders = null;
            var cirtPeptides = new DbIrtPeptide[0];

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

                    if (ReferenceEquals(standard, IrtStandard.CIRT_SHORT))
                    {
                        var libPeptides = irtProviders.SelectMany(provider => provider.PeptideRetentionTimes).Select(rt => rt.PeptideSequence).ToHashSet();
                        cirtPeptides    = IrtStandard.CIRT.Peptides.Where(pep => libPeptides.Contains(pep.ModifiedTarget)).ToArray();
                    }
                });
                if (status.IsCanceled)
                {
                    return(false);
                }
                if (status.IsError)
                {
                    throw status.ErrorException;
                }
            }

            int?numCirt = null;

            if (cirtPeptides.Length >= RCalcIrt.MIN_PEPTIDES_COUNT)
            {
                using (var dlg = new AddIrtStandardsDlg(cirtPeptides.Length,
                                                        string.Format(
                                                            Resources.LibraryBuildNotificationHandler_AddIrts__0__distinct_CiRT_peptides_were_found__How_many_would_you_like_to_use_as_iRT_standards_,
                                                            cirtPeptides.Length)))
                {
                    if (dlg.ShowDialog(GetParent()) != DialogResult.OK)
                    {
                        return(false);
                    }
                    numCirt = dlg.StandardCount;
                }
            }

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

            using (var longWait = new LongWaitDlg {
                Text = Resources.LibraryBuildNotificationHandler_AddIrts_Processing_retention_times
            })
            {
                try
                {
                    var status = longWait.PerformWork(GetParent(), 800, monitor =>
                    {
                        processed = !numCirt.HasValue
                            ? RCalcIrt.ProcessRetentionTimes(monitor, irtProviders, standardPeptides, new DbIrtPeptide[0])
                            : RCalcIrt.ProcessRetentionTimesCirt(monitor, irtProviders, cirtPeptides, numCirt.Value, out standardPeptides);
                    });
                    if (status.IsCanceled)
                    {
                        return(false);
                    }
                    if (status.IsError)
                    {
                        throw status.ErrorException;
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(GetParent(),
                                                 TextUtil.LineSeparate(
                                                     Resources.BuildPeptideSearchLibraryControl_AddIrtLibraryTable_An_error_occurred_while_processing_retention_times_,
                                                     x.Message), x);
                    return(false);
                }
            }

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

            var recalibrate = false;

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

            var processedDbIrtPeptides = processed.DbIrtPeptides.ToArray();

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

            using (var longWait = new LongWaitDlg {
                Text = Resources.LibraryBuildNotificationHandler_AddIrts_Adding_iRTs_to_library
            })
            {
                try
                {
                    DbIrtPeptide[] newStandards = null;
                    var            status       = longWait.PerformWork(GetParent(), 800, monitor =>
                    {
                        if (recalibrate)
                        {
                            monitor.UpdateProgress(new ProgressStatus().ChangeSegments(0, 2));
                            newStandards = processed.RecalibrateStandards(standardPeptides).ToArray();
                            processed    = RCalcIrt.ProcessRetentionTimes(monitor,
                                                                          processed.ProviderData.Select(data => data.RetentionTimeProvider).ToArray(),
                                                                          newStandards.ToArray(), new DbIrtPeptide[0]);
                        }
                        var irtDb = IrtDb.CreateIrtDb(libSpec.FilePath);
                        irtDb.AddPeptides(monitor, (newStandards ?? standardPeptides).Concat(processed.DbIrtPeptides).ToList());
                    });
                    if (status.IsError)
                    {
                        throw status.ErrorException;
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(GetParent(),
                                                 TextUtil.LineSeparate(
                                                     Resources.LibraryBuildNotificationHandler_AddIrts_An_error_occurred_trying_to_add_iRTs_to_the_library_,
                                                     x.Message), x);
                    return(false);
                }
            }
            return(true);
        }
Beispiel #11
0
        private void BuildLibrary(string inputDir, IEnumerable <string> inputFiles, string libraryPath,
                                  bool keepRedundant, bool includeAmbiguous, bool filterPeptides, bool append, IrtStandard irtStandard)
        {
            EnsurePeptideSettings();

            var           buildLibraryDlg = ShowDialog <BuildLibraryDlg>(PeptideSettingsUI.ShowBuildLibraryDlg);
            List <string> inputPaths      = null;

            if (inputFiles != null)
            {
                inputPaths = new List <string>(inputFiles).ConvertAll(f => Path.Combine(inputDir, f));
            }
            string autoLibPath = null;

            RunUI(() =>
            {
                if (libraryPath != null)
                {
                    buildLibraryDlg.LibraryPath = libraryPath;
                }
                buildLibraryDlg.LibraryName = _libraryName;
                autoLibPath = buildLibraryDlg.LibraryPath;
                buildLibraryDlg.LibraryKeepRedundant    = keepRedundant;
                buildLibraryDlg.IncludeAmbiguousMatches = includeAmbiguous;
                buildLibraryDlg.LibraryFilterPeptides   = filterPeptides;
                buildLibraryDlg.LibraryBuildAction      = (append ?
                                                           LibraryBuildAction.Append : LibraryBuildAction.Create);
                if (irtStandard != null && !irtStandard.Equals(IrtStandard.EMPTY))
                {
                    buildLibraryDlg.IrtStandard = irtStandard;
                }
                buildLibraryDlg.OkWizardPage();
                if (inputPaths != null)
                {
                    buildLibraryDlg.AddInputFiles(inputPaths);
                }
                else
                {
                    buildLibraryDlg.AddDirectory(inputDir);
                }
            });
            OkDialog(buildLibraryDlg, buildLibraryDlg.OkWizardPage);

            if (inputPaths != null)
            {
                foreach (var inputFile in inputPaths)
                {
                    if (BiblioSpecLiteBuilder.HasEmbeddedSpectra(inputFile))
                    {
                        var embeddedSpectraDlg = WaitForOpenForm <MultiButtonMsgDlg>();
                        OkDialog(embeddedSpectraDlg, embeddedSpectraDlg.BtnYesClick);
                    }
                }
            }

            Assert.AreEqual(TestFilesDir.GetTestPath(_libraryName + BiblioSpecLiteSpec.EXT),
                            autoLibPath);
        }
Beispiel #12
0
        public void OkDialog()
        {
            var helper = new MessageBoxHelper(this);

            if (!helper.ValidateNameTextBox(textName, out var name))
            {
                return;
            }
            else if (_existing.Contains(r => !ReferenceEquals(_standard, r) && Equals(name, r.Name)))
            {
                helper.ShowTextBoxError(textName, Resources.CalibrateIrtDlg_OkDialog_The_iRT_standard__0__already_exists_, name);
                return;
            }

            if (!IsRecalibration)
            {
                var irts = IrtStandard.CIRT.Peptides.ToDictionary(p => p.GetNormalizedModifiedSequence(), p => p.Irt);
                var calibrationPeptides = new List <Tuple <DbIrtPeptide, double> >();
                foreach (var pep in StandardPeptideList)
                {
                    double irt;
                    if (!irts.TryGetValue(SequenceMassCalc.NormalizeModifiedSequence(pep.Target), out irt))
                    {
                        break;
                    }
                    calibrationPeptides.Add(new Tuple <DbIrtPeptide, double>(
                                                new DbIrtPeptide(pep.Target, irt, true, TimeSource.peak), pep.RetentionTime));
                }

                if (calibrationPeptides.Count == StandardPeptideList.Count)
                {
                    var statStandard = new Statistics(calibrationPeptides.Select(p => p.Item1.Irt));
                    var statMeasured = new Statistics(calibrationPeptides.Select(p => p.Item2));
                    if (statStandard.R(statMeasured) >= RCalcIrt.MIN_IRT_TO_TIME_CORRELATION)
                    {
                        var result = MultiButtonMsgDlg.Show(this,
                                                            Resources.CalibrateIrtDlg_OkDialog_All_of_these_peptides_are_known_CiRT_peptides__Would_you_like_to_use_the_predefined_iRT_values_,
                                                            MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, true);
                        if (result == DialogResult.Cancel)
                        {
                            return;
                        }

                        if (result == DialogResult.Yes)
                        {
                            IrtStandard  = new IrtStandard(name, null, calibrationPeptides.Select(x => x.Item1));
                            DialogResult = DialogResult.OK;
                            return;
                        }
                    }
                }
            }

            if (!TryGetLine(true, out var linearEquation))
            {
                return;
            }

            if (!IsRecalibration)
            {
                IrtStandard = new IrtStandard(name, null,
                                              StandardPeptideList.Select(pep =>
                                                                         new DbIrtPeptide(pep.Target, linearEquation.GetY(pep.RetentionTime), true, TimeSource.peak)));
            }
            else
            {
                foreach (var pep in _updatePeptides)
                {
                    pep.Irt = linearEquation.GetY(pep.Irt);
                }
                IrtStandard = new IrtStandard(name, null,
                                              _standard.Peptides.Select(pep =>
                                                                        new DbIrtPeptide(pep.Target, linearEquation.GetY(pep.Irt), true, TimeSource.peak)));
            }
            DialogResult = DialogResult.OK;
        }
Beispiel #13
0
        public static List <PrositIntensityModel.PeptidePrecursorNCE> ReadStandardPeptides(IrtStandard standard)
        {
            var peps  = standard.GetDocument().Peptides.ToList();
            var precs = peps.Select(p => p.TransitionGroups.First());

            /*for (var i = 0; i < peps.Count; i++)
             * {
             *  var modSeq = ModifiedSequence.GetModifiedSequence(docImport.Settings, peps[i], IsotopeLabelType.light);
             *  peps[i] = peps[i].ChangeExplicitMods(new ExplicitMods(peps[i].Peptide,
             *      modSeq.ExplicitMods.Select(m => m.ExplicitMod).ToArray(),
             *      new TypedExplicitModifications[0]));
             * }*/
            return(Enumerable.Zip(peps, precs,
                                  (pep, prec) => new PrositIntensityModel.PeptidePrecursorNCE(pep, prec)).ToList());
        }
Beispiel #14
0
        private void BuildLibrary(string inputDir, IEnumerable <string> inputFiles,
                                  string libraryPath, bool keepRedundant, bool filterPeptides, bool append, IrtStandard irtStandard)
        {
            EnsurePeptideSettings();

            var           buildLibraryDlg = ShowDialog <BuildLibraryDlg>(PeptideSettingsUI.ShowBuildLibraryDlg);
            List <string> inputPaths      = null;

            if (inputFiles != null)
            {
                inputPaths = new List <string>(inputFiles).ConvertAll(f => Path.Combine(inputDir, f));
            }
            string autoLibPath = null;

            RunUI(() =>
            {
                if (libraryPath != null)
                {
                    buildLibraryDlg.LibraryPath = libraryPath;
                }
                buildLibraryDlg.LibraryName = _libraryName;
                autoLibPath = buildLibraryDlg.LibraryPath;
                buildLibraryDlg.LibraryKeepRedundant  = keepRedundant;
                buildLibraryDlg.LibraryFilterPeptides = filterPeptides;
                buildLibraryDlg.LibraryBuildAction    = (append ?
                                                         LibraryBuildAction.Append : LibraryBuildAction.Create);
                if (irtStandard != null && !irtStandard.Equals(IrtStandard.NULL))
                {
                    buildLibraryDlg.IrtStandard = irtStandard;
                }
                buildLibraryDlg.OkWizardPage();
                if (inputPaths != null)
                {
                    buildLibraryDlg.AddInputFiles(inputPaths);
                }
                else
                {
                    buildLibraryDlg.AddDirectory(inputDir);
                }
            });
            OkDialog(buildLibraryDlg, buildLibraryDlg.OkWizardPage);
            Assert.AreEqual(TestFilesDir.GetTestPath(_libraryName + BiblioSpecLiteSpec.EXT),
                            autoLibPath);
        }
Beispiel #15
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);
        }
        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);
        }