public AddRetentionTimePredictorDlg(string libName, string libPath)
        {
            InitializeComponent();

            txtName.Text = libName;
            Calculator = new RCalcIrt(libName, libPath);
        }
Пример #2
0
            public static IEnumerable <RegressionOption> All(SrmDocument document)
            {
                yield return(new RegressionOption(Resources.RegressionOption_All_Fixed_points));

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

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

                foreach (var standard in Settings.Default.IrtStandardList.Where(standard => !ReferenceEquals(standard, IrtStandard.EMPTY)))
                {
                    var pepMatches = new List <Tuple <DbIrtPeptide, PeptideDocNode> >();
                    foreach (var pep in standard.Peptides)
                    {
                        if (docPeptides.TryGetValue(pep.GetNormalizedModifiedSequence(), out var nodePep))
                        {
                            pepMatches.Add(Tuple.Create(pep, nodePep));
                        }
                    }
                    if (RCalcIrt.TryGetRegressionLine(
                            pepMatches.Select(pep => (double)pep.Item2.PercentileMeasuredRetentionTime.Value).ToList(),
                            pepMatches.Select(pep => pep.Item1.Irt).ToList(),
                            RCalcIrt.MinStandardCount(standard.Peptides.Count), out var regressionLine))
                    {
                        yield return(new RegressionOption(standard.Name, regressionLine, pepMatches, null, false, false));
                    }
                }
            }
        public AddRetentionTimePredictorDlg(string libName, string libPath)
        {
            InitializeComponent();

            txtName.Text = libName;
            Calculator   = new RCalcIrt(libName, libPath);
        }
Пример #4
0
        private static RegressionLine GetRegression(TargetMap <double> knownIrts, DbIrtPeptide[] matchingPeptides, int?minPoints, out RegressionGraphData graphData)
        {
            graphData = null;

            var matchingPeptideIrts = new TargetMap <List <double> >(matchingPeptides.Select(pep =>
                                                                                             new KeyValuePair <Target, List <double> >(pep.ModifiedTarget, new List <double>())));

            foreach (var pep in matchingPeptides)
            {
                var list = matchingPeptideIrts[pep.ModifiedTarget];
                list.Add(pep.Irt);
            }
            var listX   = new List <double>();
            var listY   = new List <double>();
            var targets = new Dictionary <int, Target>();

            foreach (var(i, kvp) in matchingPeptideIrts.Where(kvp => kvp.Value.Count > 0).Select((kvp, i) => Tuple.Create(i, kvp)))
            {
                targets[i] = kvp.Key;
                listX.Add(new Statistics(kvp.Value).Median());
                listY.Add(knownIrts[kvp.Key]);
            }

            var regressionMinPoints = minPoints ?? RCalcIrt.MinStandardCount(knownIrts.Count);
            var removed             = new List <Tuple <double, double> >();

            if (!IrtRegression.TryGet <RegressionLine>(listX, listY, regressionMinPoints, out var regression, removed))
            {
                return(null);
            }

            var outliers = new HashSet <int>();

            for (var i = 0; i < listX.Count; i++)
            {
                if (removed.Contains(Tuple.Create(listX[i], listY[i])))
                {
                    outliers.Add(i);
                }
            }

            graphData = new RegressionGraphData
            {
                Title          = Resources.ChooseIrtStandardPeptidesDlg_OkDialog_Linear_regression,
                LabelX         = Resources.ChooseIrtStandardPeptidesDlg_OkDialog_Library_iRTs,
                LabelY         = Resources.ChooseIrtStandardPeptidesDlg_OkDialog_Known_iRTs,
                XValues        = listX.ToArray(),
                YValues        = listY.ToArray(),
                Tooltips       = targets.ToDictionary(target => target.Key, target => target.Value.ToString()),
                OutlierIndices = outliers,
                RegressionLine = regression,
                MinCorrelation = RCalcIrt.MIN_IRT_TO_TIME_CORRELATION,
                MinPoints      = regressionMinPoints,
            };
            return(regression as RegressionLine);
        }
Пример #5
0
        public static ProcessedIrtAverages ProcessRetentionTimes(int?numCirt, IRetentionTimeProvider[] irtProviders,
                                                                 DbIrtPeptide[] standardPeptides, DbIrtPeptide[] cirtPeptides, IrtRegressionType regressionType, IProgressMonitor monitor, out DbIrtPeptide[] newStandardPeptides)
        {
            newStandardPeptides = null;
            var processed = !numCirt.HasValue
                ? RCalcIrt.ProcessRetentionTimes(monitor, irtProviders, standardPeptides, new DbIrtPeptide[0], regressionType)
                : RCalcIrt.ProcessRetentionTimesCirt(monitor, irtProviders, cirtPeptides, numCirt.Value, regressionType, out newStandardPeptides);

            return(processed);
        }
Пример #6
0
        public AddRetentionTimePredictorDlg(string libName, string libPath, bool allowCancel)
        {
            InitializeComponent();

            txtName.Text   = libName;
            Calculator     = new RCalcIrt(Helpers.GetUniqueName(libName, Settings.Default.RTScoreCalculatorList.Select(calc => calc.Name).ToArray()), libPath);
            txtWindow.Text = ImportPeptideSearch.DEFAULT_RT_WINDOW.ToString(LocalizationHelper.CurrentCulture);

            if (!allowCancel)
            {
                btnCancel.Hide();
            }
        }
Пример #7
0
        public static void CreateIrtDb(string path, ProcessedIrtAverages processed, DbIrtPeptide[] standardPeptides, bool recalibrate, IrtRegressionType regressionType, IProgressMonitor monitor)
        {
            DbIrtPeptide[] newStandards = null;
            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], regressionType);
            }
            var irtDb = IrtDb.CreateIrtDb(path);

            irtDb.AddPeptides(monitor, (newStandards ?? standardPeptides).Concat(processed.DbIrtPeptides).ToList());
        }
Пример #8
0
        public static SrmDocument AddRetentionTimePredictor(SrmDocument doc, LibrarySpec libSpec)
        {
            var calc = new RCalcIrt(
                Helpers.GetUniqueName(libSpec.Name, Settings.Default.RTScoreCalculatorList.Select(lib => lib.Name).ToArray()),
                libSpec.FilePath);
            var predictor = new RetentionTimeRegression(
                Helpers.GetUniqueName(libSpec.Name, Settings.Default.RetentionTimeList.Select(rt => rt.Name).ToArray()),
                calc, null, null, DEFAULT_RT_WINDOW, new List <MeasuredRetentionTime>());

            Settings.Default.RTScoreCalculatorList.Add(calc);
            Settings.Default.RetentionTimeList.Add(predictor);
            return(doc.ChangeSettings(
                       doc.Settings.ChangePeptideSettings(
                           doc.Settings.PeptideSettings.ChangePrediction(
                               doc.Settings.PeptideSettings.Prediction.ChangeRetentionTime(predictor)))));
        }
Пример #9
0
        public static List <DbIrtPeptide> GetUnscoredIrtPeptides(List <DbIrtPeptide> dbIrtPeptides, RCalcIrt calcIrt)
        {
            var dbIrtPeptidesFilter = new List <DbIrtPeptide>();

            // Filter out peptides that have the same sequence and iRT as those in the database
            foreach (var dbIrtPeptide in dbIrtPeptides)
            {
                double?oldScore = calcIrt != null?calcIrt.ScoreSequence(dbIrtPeptide.PeptideModSeq) : null;

                if (oldScore == null || Math.Abs(oldScore.Value - dbIrtPeptide.Irt) > DbIrtPeptide.IRT_MIN_DIFF)
                {
                    dbIrtPeptidesFilter.Add(dbIrtPeptide);
                }
            }
            return(dbIrtPeptidesFilter);
        }
Пример #10
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);
        }
Пример #11
0
        public void OkDialog()
        {
            IrtType irtType = GetIrtType();

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

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

            // Remove repeated/duplicate peptides
            var newDoc = removeRepeated || removeDuplicate
                ? new RefinementSettings {
                RemoveRepeatedPeptides = removeRepeated, RemoveDuplicatePeptides = removeDuplicate
            }.Refine(doc)
                : doc;

            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            // Remove proteins without enough peptides
            newDoc = ImportPeptideSearch.RemoveProteinsByPeptideCount(newDoc, minPeptides);

            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            // Move iRT proteins to top
            var irtPeptides = new HashSet <Target>(RCalcIrt.IrtPeptides(newDoc));
            var proteins    = new List <PeptideGroupDocNode>(newDoc.PeptideGroups);
            var proteinsIrt = new List <PeptideGroupDocNode>();

            for (var i = 0; i < proteins.Count; i++)
            {
                var nodePepGroup = proteins[i];
                if (nodePepGroup.Peptides.All(nodePep => irtPeptides.Contains(new Target(nodePep.ModifiedSequence))))
                {
                    proteinsIrt.Add(nodePepGroup);
                    proteins.RemoveAt(i--);
                }
            }
            if (proteinsIrt.Any())
            {
                newDoc = (SrmDocument)newDoc.ChangeChildrenChecked(proteinsIrt.Concat(proteins).Cast <DocNode>().ToArray());
            }

            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            // Add decoys
            newDoc = AddDecoys(newDoc);

            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            // Count empty proteins
            emptyProteins = newDoc.PeptideGroups.Count(pepGroup => pepGroup.PeptideCount == 0);

            if (cancellationToken.IsCancellationRequested)
            {
                return(null);
            }

            return(newDoc);
        }
Пример #13
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);
        }
Пример #14
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);
        }
Пример #15
0
        private RCalcIrt FindIrtDatabase(IWin32Window parent, string documentPath, RCalcIrt irtCalc)
        {
            RetentionScoreCalculatorSpec result;
            if (Settings.Default.RTScoreCalculatorList.TryGetValue(irtCalc.Name, out result))
            {
                var calc = result as RCalcIrt;
                if (calc != null && File.Exists(calc.DatabasePath))
                    return calc;
            }
            if (documentPath == null)
                return null;

            // First look for the file name in the document directory
            string fileName = Path.GetFileName(irtCalc.DatabasePath);
            string filePath = Path.Combine(Path.GetDirectoryName(documentPath) ?? string.Empty, fileName ?? string.Empty);

            if (File.Exists(filePath))
            {
                try
                {
                    return irtCalc.ChangeDatabasePath(filePath);
                }
                catch (CalculatorException)
                {
                    //Todo: should this fail silenty or raise another dialog box?
                }
            }

            do
            {
                using (var dlg = new MissingFileDlg
                         {
                             ItemName = irtCalc.Name,
                             ItemType = Resources.SkylineWindow_FindIrtDatabase_iRT_Calculator,
                             Filter = TextUtil.FileDialogFilterAll(Resources.SkylineWindow_FindIrtDatabase_iRT_Database_Files, IrtDb.EXT),
                             FileHint = Path.GetFileName(irtCalc.DatabasePath),
                             FileDlgInitialPath = Path.GetDirectoryName(documentPath),
                             Title = Resources.SkylineWindow_FindIrtDatabase_Find_iRT_Calculator
                         })
                {
                    if (dlg.ShowDialog(parent) == DialogResult.OK)
                    {
                        if (dlg.FilePath == null)
                            return RCalcIrt.NONE;

                        try
                        {
                            return irtCalc.ChangeDatabasePath(dlg.FilePath);
                        }
                        catch (DatabaseOpeningException e)
                        {
                            var message = TextUtil.SpaceSeparate(
                                Resources.SkylineWindow_FindIrtDatabase_The_database_file_specified_could_not_be_opened,
                                e.Message); // Not L10N
                            MessageBox.Show(message);
                        }
                    }
                    else
                    {
                        return null;
                    }
                }
            }
            while (true);
        }
Пример #16
0
 public void OkDialog()
 {
     IrtType irtType = GetIrtType();
     if (textCalculatorName.Text.Length == 0)
     {
         MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_Calculator_name_cannot_be_empty);
         return;
     }
     if (_existing.Select(spec => spec.Name).Contains(textCalculatorName.Text))
     {
         var replaceResult = MultiButtonMsgDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_A_calculator_with_that_name_already_exists___Do_you_want_to_replace_it_,
                                MultiButtonMsgDlg.BUTTON_YES,
                                MultiButtonMsgDlg.BUTTON_NO,
                                false);
         if (replaceResult == DialogResult.No)
             return;
     }
     if (irtType == IrtType.existing)
     {
         try
         {
             if (!File.Exists(textOpenDatabase.Text))
             {
                 MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_iRT_database_field_must_contain_a_path_to_a_valid_file_);
                 textOpenDatabase.Focus();
                 return;
             }
             var db = IrtDb.GetIrtDb(textOpenDatabase.Text, null);
             if (db == null)
             {
                 throw new DatabaseOpeningException(string.Format(Resources.CreateIrtCalculatorDlg_OkDialog_Cannot_read_the_database_file__0_, textOpenDatabase.Text));
             }
         }
         catch (Exception x)
         {
             MessageDlg.ShowWithException(this, string.Format(Resources.CreateIrtCalculatorDlg_OkDialog_Failed_to_open_the_database_file___0_, x.Message), x);
             return;
         }
     }
     else if (irtType == IrtType.separate_list)
     {
         if (textNewDatabase.Text.Length == 0)
         {
             MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_iRT_database_field_must_not_be_empty_);
             textNewDatabase.Focus();
             return;
         }
         if (!CreateIrtDatabase(textNewDatabase.Text))
             return;
     }
     else
     {
         if (textNewDatabaseProteins.Text.Length == 0)
         {
             MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_iRT_database_field_must_not_be_empty_);
             textNewDatabaseProteins.Focus();
             return;
         }
         if (comboBoxProteins.SelectedIndex == -1)
         {
             MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_Please_select_a_protein_containing_the_list_of_standard_peptides_for_the_iRT_calculator_);
             comboBoxProteins.Focus();
             return;
         }
         if (!CreateIrtDatabase(textNewDatabaseProteins.Text))
             return;
     }
     // Make a version of the document with the new calculator in it
     var databaseFileName = irtType == IrtType.existing ? textOpenDatabase.Text :
                            irtType == IrtType.separate_list ? textNewDatabase.Text :
                             textNewDatabaseProteins.Text;
     var calculator = new RCalcIrt(textCalculatorName.Text, databaseFileName);
     // CONSIDER: Probably can't use just a static default like 10 below
     var retentionTimeRegression = new RetentionTimeRegression(calculator.Name, calculator, null, null, 10, new List<MeasuredRetentionTime>());
     var docNew = Document.ChangeSettings(Document.Settings.ChangePeptidePrediction(prediction =>
         prediction.ChangeRetentionTime(retentionTimeRegression)));
     // Import transition list of standards, if applicable
     if (irtType == IrtType.separate_list)
     {
         try
         {
             if (!File.Exists(textImportText.Text))
             {
                 MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_Transition_list_field_must_contain_a_path_to_a_valid_file_);
                 return;
             }
             IdentityPath selectPath;
             List<MeasuredRetentionTime> irtPeptides;
             List<TransitionImportErrorInfo> errorList;
             var inputs = new MassListInputs(textImportText.Text);
             docNew = docNew.ImportMassList(inputs, null, out selectPath, out irtPeptides, out _librarySpectra, out errorList);
             if (errorList.Any())
             {
                 throw new InvalidDataException(errorList[0].ErrorMessage);
             }
             _dbIrtPeptides = irtPeptides.Select(rt => new DbIrtPeptide(rt.PeptideSequence, rt.RetentionTime, true, TimeSource.scan)).ToList();
             IrtFile = textImportText.Text;
         }
         catch (Exception x)
         {
             MessageDlg.ShowWithException(this, string.Format(Resources.CreateIrtCalculatorDlg_OkDialog_Error_reading_iRT_standards_transition_list___0_, x.Message), x);
             return;
         }
     }
     else if (irtType == IrtType.protein)
     {
         PeptideGroupDocNode selectedGroup = comboBoxProteins.SelectedItem as PeptideGroupDocNode;
     // ReSharper disable PossibleNullReferenceException
         _irtPeptideSequences = new HashSet<string>(selectedGroup.Peptides.Select(pep => pep.ModifiedSequence));
     // ReSharper restore PossibleNullReferenceException
     }
     Document = docNew;
     DialogResult = DialogResult.OK;
 }
Пример #17
0
 public DatabaseNotConnectedException(RCalcIrt calc)
     : base(string.Format(DBERROR, calc.Name, calc.DatabasePath))
 {
     _calculator = calc;
 }
Пример #18
0
 public bool Equals(RCalcIrt other)
 {
     if (ReferenceEquals(null, other)) return false;
     if (ReferenceEquals(this, other)) return true;
     return base.Equals(other) && Equals(other._database, _database) && Equals(other.DatabasePath, DatabasePath);
 }
Пример #19
0
 private RCalcIrt LoadCalculator(IDocumentContainer container, RCalcIrt calc)
 {
     // TODO: Something better than locking for the entire load
     lock (_loadedCalculators)
     {
         RCalcIrt calcResult;
         if (!_loadedCalculators.TryGetValue(calc.Name, out calcResult))
         {
             calcResult = (RCalcIrt) calc.Initialize(new LoadMonitor(this, container, calc));
             if (calcResult != null)
                 _loadedCalculators.Add(calcResult.Name, calcResult);
         }
         return calcResult;
     }
 }
Пример #20
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);
            }
        }
Пример #21
0
        private RCalcIrt FindIrtDatabase(string documentPath, RCalcIrt irtCalc)
        {
            RetentionScoreCalculatorSpec result;
            if (Settings.Default.RTScoreCalculatorList.TryGetValue(irtCalc.Name, out result))
            {
                var irtCalcSettings = result as RCalcIrt;
                if (irtCalcSettings != null && (irtCalcSettings.IsUsable || File.Exists(irtCalcSettings.DatabasePath)))
                {
                    return irtCalcSettings;
                }
            }

            // First look for the file name in the document directory
            string fileName = Path.GetFileName(irtCalc.DatabasePath);
            string filePath = Path.Combine(Path.GetDirectoryName(documentPath) ?? string.Empty, fileName ?? string.Empty);

            if (File.Exists(filePath))
            {
                try
                {
                    return irtCalc.ChangeDatabasePath(filePath);
                }
                catch (CalculatorException)
                {
                    //Todo: should this fail silenty or report an error
                }
            }

            _out.WriteLine(Resources.CommandLine_FindIrtDatabase_Error__Could_not_find_the_iRT_database__0__, Path.GetFileName(irtCalc.DatabasePath));
            return null;
        }
Пример #22
0
        private bool ImportTransitionList(CommandArgs commandArgs)
        {
            _out.WriteLine(Resources.CommandLine_ImportTransitionList_Importing_transiton_list__0____, Path.GetFileName(commandArgs.TransitionListPath));

            IdentityPath selectPath;
            List<MeasuredRetentionTime> irtPeptides;
            List<SpectrumMzInfo> librarySpectra;
            List<TransitionImportErrorInfo> errorList;
            List<PeptideGroupDocNode> peptideGroups;
            var retentionTimeRegression = _doc.Settings.PeptideSettings.Prediction.RetentionTime;
            RCalcIrt calcIrt = retentionTimeRegression != null ? (retentionTimeRegression.Calculator as RCalcIrt) : null;

            var progressMonitor = new CommandProgressMonitor(_out, new ProgressStatus(string.Empty));
            var inputs = new MassListInputs(commandArgs.TransitionListPath);
            var docNew = _doc.ImportMassList(inputs, progressMonitor, null,
                out selectPath, out irtPeptides, out librarySpectra, out errorList, out peptideGroups);

            // If nothing was imported (e.g. operation was canceled or zero error-free transitions) and also no errors, just return
            if (ReferenceEquals(docNew, _doc) && !errorList.Any())
                return true;
            // Show the errors or as warnings, if error transitions are ignore
            if (errorList.Any())
            {
                string messageFormat = !commandArgs.IsIgnoreTransitionErrors
                    ? Resources.CommandLine_ImportTransitionList_Error___line__0___column__1____2_
                    : Resources.CommandLine_ImportTransitionList_Warning___line__0___column__1____2_;
                foreach (var errorMessage in errorList)
                {
                    _out.WriteLine(messageFormat, errorMessage.Row, errorMessage.Column, errorMessage.ErrorMessage);
                }
                if (!commandArgs.IsIgnoreTransitionErrors)
                    return false;
            }
            if (!commandArgs.IsTransitionListAssayLibrary)
            {
                _doc = docNew;
                return true;
            }
            if (irtPeptides.Count == 0 || librarySpectra.Count == 0)
            {
                if (irtPeptides.Any())
                    _out.WriteLine(Resources.CommandLine_ImportTransitionList_Error__Imported_assay_library__0__lacks_ion_abundance_values_);
                else if (librarySpectra.Any())
                    _out.WriteLine(Resources.CommandLine_ImportTransitionList_Error__Imported_assay_library__0__lacks_iRT_values_);
                else
                    _out.WriteLine(Resources.CommandLine_ImportTransitionList_Error__Imported_assay_library__0__lacks_iRT_and_ion_abundance_values_);
                return false;
            }

            string destinationPath = commandArgs.SaveFile ?? commandArgs.SkylineFile;
            string documentLibrary = BiblioSpecLiteSpec.GetLibraryFileName(destinationPath);
            // ReSharper disable once AssignNullToNotNullAttribute
            string outputLibraryPath = Path.Combine(Path.GetDirectoryName(documentLibrary),
                Path.GetFileNameWithoutExtension(documentLibrary) + BiblioSpecLiteSpec.ASSAY_NAME +
                BiblioSpecLiteSpec.EXT);
            bool libraryExists = File.Exists(outputLibraryPath);
            string libraryName = Path.GetFileNameWithoutExtension(destinationPath) + BiblioSpecLiteSpec.ASSAY_NAME;
            int indexOldLibrary = docNew.Settings.PeptideSettings.Libraries.LibrarySpecs.IndexOf(
                    spec => spec != null && spec.FilePath == outputLibraryPath);
            bool libraryLinkedToDoc = indexOldLibrary != -1;
            if (libraryExists && !libraryLinkedToDoc)
            {
                _out.WriteLine(Resources.CommandLine_ImportTransitionList_Error__There_is_an_existing_library_with_the_same_name__0__as_the_document_library_to_be_created_,
                        libraryName);
                return false;
            }

            var dbIrtPeptides = irtPeptides.Select(rt => new DbIrtPeptide(rt.PeptideSequence, rt.RetentionTime, false, TimeSource.scan)).ToList();
            var dbIrtPeptidesFilter = ImportAssayLibraryHelper.GetUnscoredIrtPeptides(dbIrtPeptides, calcIrt);
            // If there are no iRT peptides with different values than the database, don't import any iRT's
            bool checkPeptides = false;
            if (dbIrtPeptidesFilter.Any())
            {
                if (calcIrt == null)
                {
                    string irtDatabasePath = commandArgs.IrtDatabasePath;
                    if (string.IsNullOrEmpty(irtDatabasePath))
                        irtDatabasePath = Path.ChangeExtension(destinationPath, IrtDb.EXT);
                    if (!string.IsNullOrEmpty(commandArgs.IrtStandardsPath))
                    {
                        _out.WriteLine(Resources.CommandLine_ImportTransitionList_Importing_iRT_transition_list__0_, commandArgs.IrtStandardsPath);
                        var irtInputs = new MassListInputs(commandArgs.IrtStandardsPath);
                        try
                        {
                            List<SpectrumMzInfo> irtLibrarySpectra;
                            docNew = docNew.ImportMassList(irtInputs, null, out selectPath, out irtPeptides, out irtLibrarySpectra, out errorList);
                            if (errorList.Any())
                            {
                                throw new InvalidDataException(errorList[0].ErrorMessage);
                            }
                            librarySpectra.AddRange(irtLibrarySpectra);
                            dbIrtPeptidesFilter.AddRange(irtPeptides.Select(rt => new DbIrtPeptide(rt.PeptideSequence, rt.RetentionTime, true, TimeSource.scan)));
                        }
                        catch (Exception x)
                        {
                            _out.WriteLine(Resources.CommandLine_Run_Error__Failed_importing_the_file__0____1_, commandArgs.IrtStandardsPath, x.Message);
                            return false;
                        }
                        if (!CreateIrtDatabase(irtDatabasePath, commandArgs))
                            return false;
                    }
                    else if (!string.IsNullOrEmpty(commandArgs.IrtGroupName))
                    {
                        var nodeGroupIrt = docNew.PeptideGroups.FirstOrDefault(nodeGroup => nodeGroup.Name == commandArgs.IrtGroupName);
                        if (nodeGroupIrt == null)
                        {
                            _out.WriteLine(Resources.CommandLine_ImportTransitionList_Error__The_name__0__specified_with__1__was_not_found_in_the_imported_assay_library_,
                                commandArgs.IrtGroupName, CommandArgs.ArgText(CommandArgs.ARG_IRT_STANDARDS_GROUP_NAME));
                            return false;
                        }
                        var irtPeptideSequences = new HashSet<string>(nodeGroupIrt.Peptides.Select(pep => pep.ModifiedSequence));
                        dbIrtPeptidesFilter.ForEach(pep => pep.Standard = irtPeptideSequences.Contains(pep.PeptideModSeq));
                        if (!CreateIrtDatabase(irtDatabasePath, commandArgs))
                            return false;
                    }
                    else if (!File.Exists(irtDatabasePath))
                    {
                        _out.Write(Resources.CommandLine_ImportTransitionList_Error__To_create_the_iRT_database___0___for_this_assay_library__you_must_specify_the_iRT_standards_using_either_of_the_arguments__1__or__2_,
                            irtDatabasePath, CommandArgs.ArgText(CommandArgs.ARG_IRT_STANDARDS_GROUP_NAME), CommandArgs.ArgText(CommandArgs.ARG_IRT_STANDARDS_FILE));
                        return false;
                    }
                    else
                    {
                        checkPeptides = true;
                    }
                    string irtCalcName = commandArgs.IrtCalcName ?? Path.GetFileNameWithoutExtension(destinationPath);
                    calcIrt = new RCalcIrt(irtCalcName, irtDatabasePath);

                    retentionTimeRegression = new RetentionTimeRegression(calcIrt.Name, calcIrt, null, null, 10, new List<MeasuredRetentionTime>());
                    docNew = docNew.ChangeSettings(docNew.Settings.ChangePeptidePrediction(prediction =>
                        prediction.ChangeRetentionTime(retentionTimeRegression)));
                }
                string dbPath = calcIrt.DatabasePath;
                IrtDb db = IrtDb.GetIrtDb(dbPath, null);
                if (checkPeptides)
                {
                    var standards = docNew.Molecules.Where(m => db.IsStandard(m.RawTextId)).ToArray();
                    if (standards.Length != db.StandardPeptideCount)
                    {
                        _out.WriteLine(Resources.CommandLine_ImportTransitionList_Warning__The_document_is_missing_iRT_standards);
                        foreach (var rawTextId in db.StandardPeptides.Where(s => !standards.Contains(nodePep => s == nodePep.RawTextId)))
                        {
                            _out.WriteLine("    " + rawTextId); // Not L10N
                        }
                    }
                }
                var oldPeptides = db.GetPeptides().ToList();
                IList<DbIrtPeptide.Conflict> conflicts;
                dbIrtPeptidesFilter = DbIrtPeptide.MakeUnique(dbIrtPeptidesFilter);
                DbIrtPeptide.FindNonConflicts(oldPeptides, dbIrtPeptidesFilter, null, out conflicts);
                // Warn about peptides that are present in the import and already in the database
                foreach (var conflict in conflicts)
                {
                    _out.WriteLine(Resources.CommandLine_ImportTransitionList_Warning__The_iRT_calculator_already_contains__0__with_the_value__1___Ignoring__2_,
                        conflict.ExistingPeptide.PeptideModSeq, conflict.ExistingPeptide.Irt, conflict.NewPeptide.Irt);
                }

                _out.WriteLine(Resources.CommandLine_ImportTransitionList_Importing__0__iRT_values_into_the_iRT_calculator__1_, dbIrtPeptidesFilter.Count, calcIrt.Name);
                docNew = docNew.AddIrtPeptides(dbIrtPeptidesFilter, false, progressMonitor);
                if (docNew == null)
                    return false;
            }

            librarySpectra = SpectrumMzInfo.RemoveDuplicateSpectra(librarySpectra);

            if (libraryLinkedToDoc)
            {
                string oldName = docNew.Settings.PeptideSettings.Libraries.LibrarySpecs[indexOldLibrary].Name;
                var libraryOld = docNew.Settings.PeptideSettings.Libraries.GetLibrary(oldName);
                var additionalSpectra = SpectrumMzInfo.GetInfoFromLibrary(libraryOld);
                additionalSpectra = SpectrumMzInfo.RemoveDuplicateSpectra(additionalSpectra);

                librarySpectra = SpectrumMzInfo.MergeWithOverwrite(librarySpectra, additionalSpectra);

                foreach (var stream in libraryOld.ReadStreams)
                    stream.CloseStream();
            }

            if (librarySpectra.Any())
            {
                // Delete the existing library; either it's not tied to the document or we've already extracted the spectra
                _out.WriteLine(Resources.CommandLine_ImportTransitionList_Adding__0__spectra_to_the_library__1_, librarySpectra.Count, libraryName);
                if (libraryExists)
                {
                    FileEx.SafeDelete(outputLibraryPath);
                    FileEx.SafeDelete(Path.ChangeExtension(outputLibraryPath, BiblioSpecLiteSpec.EXT_REDUNDANT));
                }
                using (var blibDb = BlibDb.CreateBlibDb(outputLibraryPath))
                {
                    var docLibrarySpec = new BiblioSpecLiteSpec(libraryName, outputLibraryPath);
                    var docLibrary = blibDb.CreateLibraryFromSpectra(docLibrarySpec, librarySpectra, libraryName,
                        progressMonitor);
                    if (docLibrary == null)
                        return false;
                    var newSettings = docNew.Settings.ChangePeptideLibraries(
                        libs => libs.ChangeLibrary(docLibrary, docLibrarySpec, indexOldLibrary));
                    docNew = docNew.ChangeSettings(newSettings, new SrmSettingsChangeMonitor(progressMonitor,
                        Resources.SkylineWindow_ImportMassList_Finishing_up_import));
                }
            }
            _doc = docNew;
            return true;
        }
Пример #23
0
 public IncompleteStandardException(RCalcIrt calc)
     : base(String.Format(ERROR, calc.Name))
 {
     Calculator = calc;
 }