Пример #1
0
        private void ExecuteAttestButton_Click(object sender, EventArgs e)
        {
            btnAttestPTMs.Enabled       = false;
            btnCancelAttestaion.Enabled = true;

            _bgWorkerAttestation = new BackgroundWorker();
            //_bgWorkerClustering.WorkerReportsProgress = true;
            _bgWorkerAttestation.WorkerSupportsCancellation = true;

            _bgWorkerCancelled = false;

            var config = new PhosphoRSConfig();

            config.setSpectrumType(dissociationTypeComboBox.SelectedItem.ToString());
            config.fragmentMassTolerance = Double.Parse(FragmentMZToleranceTextBox.Text);

            _bgWorkerAttestation.DoWork             += _bgWorkerClustering_DoWork;
            _bgWorkerAttestation.RunWorkerCompleted += _bgWorkerClustering_RunWorkerCompleted;
            _bgWorkerAttestation.RunWorkerAsync(config);
        }
Пример #2
0
        private void ExecuteAttestButton_Click(object sender, EventArgs e)
        {
            btnAttestPTMs.Enabled = false;
            btnCancelAttestaion.Enabled = true;
            
            _bgWorkerAttestation = new BackgroundWorker();
            //_bgWorkerClustering.WorkerReportsProgress = true;
            _bgWorkerAttestation.WorkerSupportsCancellation = true;

            _bgWorkerCancelled = false;

            var config = new PhosphoRSConfig();
            config.setSpectrumType(dissociationTypeComboBox.SelectedItem.ToString());
            config.fragmentMassTolerance = Double.Parse(FragmentMZToleranceTextBox.Text);

            _bgWorkerAttestation.DoWork += _bgWorkerClustering_DoWork;
            _bgWorkerAttestation.RunWorkerCompleted += _bgWorkerClustering_RunWorkerCompleted;
            _bgWorkerAttestation.RunWorkerAsync(config);
        }
Пример #3
0
        private void ExecutePhosphoRS(PhosphoRSConfig config)
        {
            // Set up the cancel token.
            cancelAttestation = new CancellationTokenSource();

            // Initialize  time stamps and status reporting variables.
            DateTime startTime = DateTime.Now;

            Invoke(new MethodInvoker(() =>
            {
                progressBar.ProgressBar.Visible = true;
                progressBar.Maximum = 100;
                //tbStatus.Font = new Font(FontFamily.GenericMonospace, 10.0f);
            }));

            //session.CreateSQLQuery("CREATE TABLE IF NOT EXISTS PeptideModificationProbability (PeptideModification INTEGER PRIMARY KEY, Probability NUMERIC)").ExecuteUpdate();
            session.CreateSQLQuery("DELETE FROM PeptideModificationProbability").ExecuteUpdate();
            var insertSiteProbabilityCommand = session.Connection.CreateCommand();
            var PepModParameter = insertSiteProbabilityCommand.CreateParameter();
            var ProbParameter = insertSiteProbabilityCommand.CreateParameter();
            insertSiteProbabilityCommand.Parameters.Add(PepModParameter);
            insertSiteProbabilityCommand.Parameters.Add(ProbParameter);
            insertSiteProbabilityCommand.CommandText = "INSERT INTO PeptideModificationProbability VALUES (?,?)";

            // Init the variables used by phosphoRS. Clear its internal variables also.
            items = new List<System.Tuple<phosphoRS.PeptideSpectrumMatch, List<System.Tuple<int, List<int>>>>>();

            var distinctSources = session.Query<SpectrumSource>().ToList();

            var sourceFilepaths = new Dictionary<string, string>();
            distinctSources.ForEach(source => sourceFilepaths[source.Name] = IDPickerForm.LocateSpectrumSource(source.Name, session.Connection.GetDataSource()));

            if (distinctSources.Any(source => sourceFilepaths[source.Name].IsNullOrEmpty()))
                setStatus("Cancelled attestation: some sources are a missing source file");

            // group the spectra by source and run each source as a batch
            int totalSources = distinctSources.Count;
            int currentSource = 0;

            //This task listen to this collection and takes any message that is send... 
            Action progressListenerAction = () =>
            {
                try
                {
                    phosphoRS.ThreadManagement.progressMessage msg;
                    double lastProgress = -1;
                    while (!progressMessageQueue.IsCompleted)
                    {
                        msg = progressMessageQueue.Take();
                        if (msg.type == phosphoRS.ThreadManagement.progressMessage.typeOfMessage.stringMessage && !msg.message.IsNullOrEmpty())
                        {
                            //setStatus(String.Format("PhosphoRS message: {0}\r\n", msg.message));
                        }
                        else
                        {
                            if (msg.spectraProcessed == 1.0 || msg.spectraProcessed > lastProgress + 0.01)
                            {
                                lastProgress = msg.spectraProcessed;
                                double baseProgress = (double) currentSource / totalSources;
                                int currentProgress = Math.Min(100, (int) Math.Round((baseProgress + msg.spectraProcessed * 1.0 / totalSources) * 100));
                                setProgress(currentProgress, String.Format("Running PhosphoRS on source {0} of {1}...", currentSource, totalSources));
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            };

            foreach (var source in distinctSources)
            {
                Task progressListener = Task.Factory.StartNew(progressListenerAction);
                progressMessageQueue = new BlockingCollection<phosphoRS.ThreadManagement.progressMessage>(new ConcurrentQueue<phosphoRS.ThreadManagement.progressMessage>());

                // get phospho peptide-spectrum matches for the source
                setStatus(String.Format("Finding phosphopeptides in \"{0}\"... ", source.Name));
                setProgress(-1, String.Format("Finding phosphopeptides in \"{0}\"... ", source.Name));
                DateTime findTime = DateTime.Now;
                var phosphoPSMs = getPhosphoPSMs(source.Id.Value);
                setStatus(String.Format("found {0} phosphopeptides ({1} seconds elapsed).\r\n", phosphoPSMs.Count, (DateTime.Now - findTime).TotalSeconds));

                if (phosphoPSMs.Count == 0)
                    continue;

                phosphoRS.PTMResultClass result = RunOnSource(sourceFilepaths[source.Name], ++currentSource, totalSources, config, phosphoPSMs);

                if (cancelAttestation.IsCancellationRequested)
                    return;

                if (result == null)
                    throw new Exception("Error running PhosphoRS on source " + source.Name);

                IDictionary<int, double> propMap;
                IDictionary<int, double> peptideScoreMap;
                IDictionary<int, string> sitepropMap;
                // peptide ID to site probabilities map
                sitepropMap = result.PeptideIdPrsSiteProbabilitiesMap;
                // peptid ID to isoform confidence probability map
                propMap = result.PeptideIdPrsProbabilityMap;
                // peptide ID to binomial score map
                peptideScoreMap = result.PeptideIdPrsScoreMap;

                //setProgress(4, "(4/4) Injecting results into the database...");
                // A map of PSMId to localization representation in string format.
                //Dictionary<long, string> localizationStrings = new Dictionary<long, string>();
                var transaction = session.BeginTransaction();
                foreach (var isoform in result.IsoformGroupList)
                {
                    if (isoform.Count == 0)
                        continue;

                    PhosphoPeptideAttestationRow row;
                    if (isoform.Error)
                    {
                        long PSMId = (long) isoform.PeptideIDs[0];
                        row = phosphoPSMs[PSMId];
                        setStatus(String.Format("Error running on {0} ({1}): {2}\r\n", PSMId, phosphoPSMs[PSMId].Peptide.sequence, isoform.Message));
                        continue;
                    }
                    else
                    {
                        long PSMId = (long) isoform.Peptides.First().ID;
                        row = phosphoPSMs[PSMId];
                    }

                    long pmId = -1;
                    foreach(var site in isoform.SiteProbabilities)
                    {
                        bool gotSite = row.OriginalPhosphoSites.TryGetValue(site.SequencePosition - 1, out pmId);
                        if (!gotSite)
                            continue;

                        PepModParameter.Value = pmId;
                        ProbParameter.Value = site.Probability;
                        insertSiteProbabilityCommand.ExecuteNonQuery();
                    }

                    if (pmId == -1)
                        throw new InvalidDataException("no PhosphoRS site probability matches to an original phospho site");
                }
                transaction.Commit();
            }

            Invoke(new MethodInvoker(() =>
            {
                progressBar.ProgressBar.Visible = false;
                setProgress(-1, "Finished.");
            }));
        }
Пример #4
0
        private phosphoRS.PTMResultClass RunOnSource(string sourceFilepath, int currentSource, int totalSources, PhosphoRSConfig config, IDictionary<long, PhosphoPeptideAttestationRow> phosphoRows)
        {
            var msd = new pwiz.CLI.msdata.MSDataFile(sourceFilepath);
            var spectrumList = msd.run.spectrumList;

            int rowNumber = 0;
            int totalRows = phosphoRows.Count();
            items.Clear();

            var spectrumTypes = new Set<CVID>();

            foreach (var row in phosphoRows)
            {
                if (rowNumber == 0 || (rowNumber % 100) == 0)
                {
                    if (cancelAttestation.IsCancellationRequested)
                    {
                        this.progressBar.ProgressBar.Visible = false;
                        _bgWorkerCancelled = true;
                        setProgress(-1, "Cancelled.");
                        return null;
                    }
                    else
                    {
                        if (rowNumber == 0)
                            setStatus(String.Format("Reading peaks and creating PhosphoRS objects for source {0} of {1} ({2}): {3} spectra\r\n", currentSource, totalSources, Path.GetFileName(sourceFilepath), totalRows));
                        setProgress((rowNumber + 1) / totalRows * 100, String.Format("Reading peaks and creating PhosphoRS objects for source {0} of {1} ({2}): {3}/{4} spectra", currentSource, totalSources, Path.GetFileName(sourceFilepath), rowNumber + 1, totalRows));
                    }
                }

                var pwizSpectrum = spectrumList.spectrum(spectrumList.find(row.Value.SpectrumNativeID), true); //may create indexoutofrange error if no spectrum nativeID                   

                var OriginalMZs = pwizSpectrum.getMZArray().data; //getMZArray().data returns IList<double>
                var OriginalIntensities = pwizSpectrum.getIntensityArray().data;
                row.Value.Peaks = new phosphoRS.Peak[OriginalMZs.Count];
                for (int i = 0; i < OriginalMZs.Count; ++i)
                    row.Value.Peaks[i] = new phosphoRS.Peak(OriginalMZs[i], OriginalIntensities[i]);

                if (config.spectrumType == phosphoRS.SpectrumType.None)
                {
                    row.Value.SpectrumType = phosphoRS.SpectrumType.None;
                    foreach (var precursor in pwizSpectrum.precursors)
                        foreach (var method in precursor.activation.cvParamChildren(CVID.MS_dissociation_method))
                        {
                            // if dissociation method is set to "Auto" but could not be determined from the file, alert the user
                            if (!spectrumTypeByDissociationMethod.Contains(method.cvid))
                                throw new InvalidDataException("cannot handle unmapped dissociation method \"" + CV.cvTermInfo(method.cvid).shortName() + "\" for spectrum \"" + row.Value.SourceName + "/" + row.Value.SpectrumNativeID + "\"; please override the method manually");
                            else if (row.Value.SpectrumType != phosphoRS.SpectrumType.ECD_ETD) // don't override ETD (e.g. if there is also supplemental CID)
                            {
                                row.Value.SpectrumType = spectrumTypeByDissociationMethod[method.cvid];
                                spectrumTypes.Add(method.cvid);
                            }
                        }

                    if (row.Value.SpectrumType == phosphoRS.SpectrumType.None)
                        throw new InvalidDataException("cannot find a dissociation method for spectrum \"" + row.Value.SourceName + "/" + row.Value.SpectrumNativeID + "\"; please set the method manually");
                }
                else
                    row.Value.SpectrumType = config.spectrumType;

                var psm = getPhosphoRS_PSM(config, row.Value);

                // DEBUG
                //tbStatus.AppendText(PeptideToString(phosphoPeptide) + "," + AAS.ToOneLetterCodeString() + "," + ptmRepresentation.ToString() + "\n");
                // Init the mod map of original variant for this PSM.
                var id2ModMap = new List<System.Tuple<int, List<int>>> { new System.Tuple<int, List<int>>((int) row.Value.PSMId, row.Value.OriginalPhosphoSites.Keys.ToList<int>()) };

                items.Add(new System.Tuple<phosphoRS.PeptideSpectrumMatch, List<System.Tuple<int, List<int>>>>(psm, id2ModMap));

                ++rowNumber;
            }

            // report automatically found fragmentation method
            if (config.spectrumType == phosphoRS.SpectrumType.None)
                setStatus(String.Format("Found {0} fragmentation types: {1}\r\n", spectrumTypes.Count, String.Join(", ", spectrumTypes.Keys.Select(o => CV.cvTermInfo(o).shortName()))));

            setProgress(currentSource / totalSources * 100, String.Format("Running PhosphoRS on source {0} of {1} ({2})...", currentSource, totalSources, Path.GetFileName(sourceFilepath)));

            // Initialize the localization.
            currentNr = 0;
            var phosphoRS_Context = new phosphoRS.ThreadManagement(this, cancelAttestation, config.maxIsoformCount, config.maxPTMCount, config.scoreNLToo, config.fragmentMassTolerance, config.scoredAA, items.Count);

            // Start the site localization (takes advantage of multi-threading)
            try
            {
                phosphoRS_Context.StartPTMLocalisation();

                // Safety if the attestation module doesn't throw the exception.
                if (cancelAttestation.IsCancellationRequested)
                {
                    this.progressBar.ProgressBar.Visible = false;
                    _bgWorkerCancelled = true;
                    setProgress(-1, "Cancelled.");
                    return null;
                }

                return phosphoRS_Context.PTMResult;
            }
            catch (OperationCanceledException)
            {
                this.progressBar.ProgressBar.Visible = false;
                _bgWorkerCancelled = true;
                setProgress(-1, "Cancelled.");
                return null;
            }
            finally
            {
                msd.Dispose();
            }
        }
Пример #5
0
        private phosphoRS.PeptideSpectrumMatch getPhosphoRS_PSM(PhosphoRSConfig config, PhosphoPeptideAttestationRow variant)
        {
            // Get the phosphorylated peptide and add all modifications to the base sequence.
            proteome.Peptide phosphoPeptide = new proteome.Peptide(variant.UnphosphorylatedSequence, proteome.ModificationParsing.ModificationParsing_Auto, proteome.ModificationDelimiter.ModificationDelimiter_Brackets);
            proteome.ModificationMap variantPeptideMods = phosphoPeptide.modifications();
            variant.OriginalPhosphoSites.Keys.ToList().ForEach(location => { variantPeptideMods[location].Add(config.pwizMod); });

            // This modification ID is used to tell phosphoRS how to modify the sequence.
            int modificationID = config.phosphorylationSymbol + 1;

            // Build a string representation of all modificaitons in a peptide for phospoRS
            // "0.00011000000000.0" : 1 is the ID of the modification. All phosphos in a data
            // set need to have one ID. This ID is used by the PhosphoRS to figure out which
            // mods need to be scored.
            var ptmRepresentation = new StringBuilder();

            // Store all modifications in phosphoRS modification objects
            var modifications = new List<phosphoRS.AminoAcidModification>();

            // Get the n-terminal modifications.
            if (variantPeptideMods.ContainsKey(proteome.ModificationMap.NTerminus()))
            {
                phosphoRS.AminoAcidModification otherMod = new phosphoRS.AminoAcidModification('2', "unknown", "unk", "none", variantPeptideMods[proteome.ModificationMap.NTerminus()].monoisotopicDeltaMass(), 0.0, null);
                modifications.Add(otherMod);
                ptmRepresentation.Append(modificationID.ToString() + ".");
                //++modificationID;
            }
            else
            {
                ptmRepresentation.Append("0.");
            }

            // Process all other modifications.
            for (int aaIndex = 0; aaIndex < phosphoPeptide.sequence.Length; ++aaIndex)
            {
                // If phosphorylation, use the existing scoredAA variable.
                if (variantPeptideMods.ContainsKey(aaIndex))
                {
                    if (variant.OriginalPhosphoSites.Keys.Contains(aaIndex))
                    {
                        modifications.Add(config.scoredAA);
                        ptmRepresentation.Append(config.phosphorylationSymbol.ToString()[0]);
                    }
                    else
                    {
                        // Otherwise, make an "unknown" modification with a separate modification ID.
                        var otherMod = new phosphoRS.AminoAcidModification(modificationID.ToString()[0], "unknown", "unk", "none", variantPeptideMods[aaIndex].monoisotopicDeltaMass(), 0.0, phosphoRS.AminoAcidSequence.ParseAASequence("" + phosphoPeptide.sequence[aaIndex]));
                        modifications.Add(otherMod);
                        ptmRepresentation.Append(modificationID.ToString());
                        //++modificationID;
                    }
                }
                else
                {
                    ptmRepresentation.Append("0");
                }
            }
            // Process any c-terminal modifications.
            if (variantPeptideMods.ContainsKey(proteome.ModificationMap.CTerminus()))
            {
                var otherMod = new phosphoRS.AminoAcidModification(modificationID.ToString()[0], "unknown", "unk", "none", variantPeptideMods[proteome.ModificationMap.CTerminus()].monoisotopicDeltaMass(), 0.0, null);
                modifications.Add(otherMod);
                ptmRepresentation.Append("." + modificationID.ToString());
            }
            else
            {
                ptmRepresentation.Append(".0");
            }

            // Get the phosphoRS peptide sequence.
            // Assign spectrum ID, amino acid sequence, list of all modifications, a so-called 'modification position string' (here every digit represents an amino acid within the peptide sequence
            // '0' indicates not modified, values != '0' indicate the unique identifier of the amino acid's modification the first digit represents the n-terminus the last digit represents the c-terminus)
            var AAS = phosphoRS.AminoAcidSequence.Create((int)variant.SpectrumId, phosphoPeptide.sequence, modifications, ptmRepresentation.ToString());
            // Make a phosphoRS peptide-spectrum match.
            return new phosphoRS.PeptideSpectrumMatch((int)variant.PSMId, variant.SpectrumType, variant.Charge, variant.PrecursorMZ, variant.Peaks, AAS);
        }
Пример #6
0
        private string PeptideToString(proteome.Peptide peptide, IList<phosphoRS.PTMSiteProbability> localizationProbabilities, PhosphoRSConfig config)
        {
            var probabilityMap = localizationProbabilities.ToDictionary(o => o.SequencePosition, o => o.Probability);

            string format = String.Format("[{{0:f{0}}}]", 0);
            StringBuilder sb = new StringBuilder();
            if (peptide.modifications().ContainsKey(proteome.ModificationMap.NTerminus()))
                sb.AppendFormat(format, peptide.modifications()[proteome.ModificationMap.NTerminus()].monoisotopicDeltaMass());
            for (int i = 0; i < peptide.sequence.Length; ++i)
            {
                sb.Append(peptide.sequence[i]);
                if (probabilityMap.ContainsKey(i + 1))
                {
                    if (probabilityMap[i + 1] > 0)
                        sb.AppendFormat("[{0:f0}({1:f0}%)]", config.scoredAA.MassDelta, probabilityMap[i + 1] * 100);
                    //else
                    //    sb.AppendFormat("({0:f0})", config.scoredAA.MassDelta, probabilityMap[i + 1]);
                }
                else if (peptide.modifications().ContainsKey(i))
                {
                    double modMass = peptide.modifications()[i].monoisotopicDeltaMass();
                    sb.AppendFormat(format, modMass);
                }
            }
            if (peptide.modifications().ContainsKey(proteome.ModificationMap.CTerminus()))
                sb.AppendFormat(format, peptide.modifications()[proteome.ModificationMap.CTerminus()].monoisotopicDeltaMass());
            return sb.ToString();
        }
Пример #7
0
        private void ExecutePhosphoRS(PhosphoRSConfig config)
        {
            // Set up the cancel token.
            cancelAttestation = new CancellationTokenSource();

            // Initialize  time stamps and status reporting variables.
            DateTime startTime = DateTime.Now;

            Invoke(new MethodInvoker(() =>
            {
                progressBar.ProgressBar.Visible = true;
                progressBar.Maximum             = 100;
                //tbStatus.Font = new Font(FontFamily.GenericMonospace, 10.0f);
            }));

            //session.CreateSQLQuery("CREATE TABLE IF NOT EXISTS PeptideModificationProbability (PeptideModification INTEGER PRIMARY KEY, Probability NUMERIC)").ExecuteUpdate();
            session.CreateSQLQuery("DELETE FROM PeptideModificationProbability").ExecuteUpdate();
            var insertSiteProbabilityCommand = session.Connection.CreateCommand();
            var PepModParameter = insertSiteProbabilityCommand.CreateParameter();
            var ProbParameter   = insertSiteProbabilityCommand.CreateParameter();

            insertSiteProbabilityCommand.Parameters.Add(PepModParameter);
            insertSiteProbabilityCommand.Parameters.Add(ProbParameter);
            insertSiteProbabilityCommand.CommandText = "INSERT INTO PeptideModificationProbability VALUES (?,?)";

            // Init the variables used by phosphoRS. Clear its internal variables also.
            items = new List <System.Tuple <phosphoRS.PeptideSpectrumMatch, List <System.Tuple <int, List <int> > > > >();

            var distinctSources = session.Query <SpectrumSource>().ToList();

            var sourceFilepaths = new Dictionary <string, string>();

            distinctSources.ForEach(source => sourceFilepaths[source.Name] = IDPickerForm.LocateSpectrumSource(source.Name, session.Connection.GetDataSource()));

            if (distinctSources.Any(source => sourceFilepaths[source.Name].IsNullOrEmpty()))
            {
                setStatus("Cancelled attestation: some sources are a missing source file");
            }

            // group the spectra by source and run each source as a batch
            int totalSources  = distinctSources.Count;
            int currentSource = 0;

            //This task listen to this collection and takes any message that is send...
            Action progressListenerAction = () =>
            {
                try
                {
                    phosphoRS.ThreadManagement.progressMessage msg;
                    double lastProgress = -1;
                    while (!progressMessageQueue.IsCompleted)
                    {
                        msg = progressMessageQueue.Take();
                        if (msg.type == phosphoRS.ThreadManagement.progressMessage.typeOfMessage.stringMessage && !msg.message.IsNullOrEmpty())
                        {
                            //setStatus(String.Format("PhosphoRS message: {0}\r\n", msg.message));
                        }
                        else
                        {
                            if (msg.spectraProcessed == 1.0 || msg.spectraProcessed > lastProgress + 0.01)
                            {
                                lastProgress = msg.spectraProcessed;
                                double baseProgress    = (double)currentSource / totalSources;
                                int    currentProgress = Math.Min(100, (int)Math.Round((baseProgress + msg.spectraProcessed * 1.0 / totalSources) * 100));
                                setProgress(currentProgress, String.Format("Running PhosphoRS on source {0} of {1}...", currentSource, totalSources));
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            };

            foreach (var source in distinctSources)
            {
                Task progressListener = Task.Factory.StartNew(progressListenerAction);
                progressMessageQueue = new BlockingCollection <phosphoRS.ThreadManagement.progressMessage>(new ConcurrentQueue <phosphoRS.ThreadManagement.progressMessage>());

                // get phospho peptide-spectrum matches for the source
                setStatus(String.Format("Finding phosphopeptides in \"{0}\"... ", source.Name));
                setProgress(-1, String.Format("Finding phosphopeptides in \"{0}\"... ", source.Name));
                DateTime findTime    = DateTime.Now;
                var      phosphoPSMs = getPhosphoPSMs(source.Id.Value);
                setStatus(String.Format("found {0} phosphopeptides ({1} seconds elapsed).\r\n", phosphoPSMs.Count, (DateTime.Now - findTime).TotalSeconds));

                if (phosphoPSMs.Count == 0)
                {
                    continue;
                }

                phosphoRS.PTMResultClass result = RunOnSource(sourceFilepaths[source.Name], ++currentSource, totalSources, config, phosphoPSMs);

                if (cancelAttestation.IsCancellationRequested)
                {
                    return;
                }

                if (result == null)
                {
                    throw new Exception("Error running PhosphoRS on source " + source.Name);
                }

                IDictionary <int, double> propMap;
                IDictionary <int, double> peptideScoreMap;
                IDictionary <int, string> sitepropMap;
                // peptide ID to site probabilities map
                sitepropMap = result.PeptideIdPrsSiteProbabilitiesMap;
                // peptid ID to isoform confidence probability map
                propMap = result.PeptideIdPrsProbabilityMap;
                // peptide ID to binomial score map
                peptideScoreMap = result.PeptideIdPrsScoreMap;

                //setProgress(4, "(4/4) Injecting results into the database...");
                // A map of PSMId to localization representation in string format.
                //Dictionary<long, string> localizationStrings = new Dictionary<long, string>();
                var transaction = session.BeginTransaction();
                foreach (var isoform in result.IsoformGroupList)
                {
                    if (isoform.Count == 0)
                    {
                        continue;
                    }

                    PhosphoPeptideAttestationRow row;
                    if (isoform.Error)
                    {
                        long PSMId = (long)isoform.PeptideIDs[0];
                        row = phosphoPSMs[PSMId];
                        setStatus(String.Format("Error running on {0} ({1}): {2}\r\n", PSMId, phosphoPSMs[PSMId].Peptide.sequence, isoform.Message));
                        continue;
                    }
                    else
                    {
                        long PSMId = (long)isoform.Peptides.First().ID;
                        row = phosphoPSMs[PSMId];
                    }

                    long pmId = -1;
                    foreach (var site in isoform.SiteProbabilities)
                    {
                        bool gotSite = row.OriginalPhosphoSites.TryGetValue(site.SequencePosition - 1, out pmId);
                        if (!gotSite)
                        {
                            continue;
                        }

                        PepModParameter.Value = pmId;
                        ProbParameter.Value   = site.Probability;
                        insertSiteProbabilityCommand.ExecuteNonQuery();
                    }

                    if (pmId == -1)
                    {
                        throw new InvalidDataException("no PhosphoRS site probability matches to an original phospho site");
                    }
                }
                transaction.Commit();
            }

            Invoke(new MethodInvoker(() =>
            {
                progressBar.ProgressBar.Visible = false;
                setProgress(-1, "Finished.");
            }));
        }
Пример #8
0
        private phosphoRS.PTMResultClass RunOnSource(string sourceFilepath, int currentSource, int totalSources, PhosphoRSConfig config, IDictionary <long, PhosphoPeptideAttestationRow> phosphoRows)
        {
            var msd          = new pwiz.CLI.msdata.MSDataFile(sourceFilepath);
            var spectrumList = msd.run.spectrumList;

            int rowNumber = 0;
            int totalRows = phosphoRows.Count();

            items.Clear();

            var spectrumTypes = new Set <CVID>();

            foreach (var row in phosphoRows)
            {
                if (rowNumber == 0 || (rowNumber % 100) == 0)
                {
                    if (cancelAttestation.IsCancellationRequested)
                    {
                        this.progressBar.ProgressBar.Visible = false;
                        _bgWorkerCancelled = true;
                        setProgress(-1, "Cancelled.");
                        return(null);
                    }
                    else
                    {
                        if (rowNumber == 0)
                        {
                            setStatus(String.Format("Reading peaks and creating PhosphoRS objects for source {0} of {1} ({2}): {3} spectra\r\n", currentSource, totalSources, Path.GetFileName(sourceFilepath), totalRows));
                        }
                        setProgress((rowNumber + 1) / totalRows * 100, String.Format("Reading peaks and creating PhosphoRS objects for source {0} of {1} ({2}): {3}/{4} spectra", currentSource, totalSources, Path.GetFileName(sourceFilepath), rowNumber + 1, totalRows));
                    }
                }

                var pwizSpectrum = spectrumList.spectrum(spectrumList.find(row.Value.SpectrumNativeID), true); //may create indexoutofrange error if no spectrum nativeID

                var OriginalMZs         = pwizSpectrum.getMZArray().data;                                      //getMZArray().data returns IList<double>
                var OriginalIntensities = pwizSpectrum.getIntensityArray().data;
                row.Value.Peaks = new phosphoRS.Peak[OriginalMZs.Count];
                for (int i = 0; i < OriginalMZs.Count; ++i)
                {
                    row.Value.Peaks[i] = new phosphoRS.Peak(OriginalMZs[i], OriginalIntensities[i]);
                }

                if (config.spectrumType == phosphoRS.SpectrumType.None)
                {
                    row.Value.SpectrumType = phosphoRS.SpectrumType.None;
                    foreach (var precursor in pwizSpectrum.precursors)
                    {
                        foreach (var method in precursor.activation.cvParamChildren(CVID.MS_dissociation_method))
                        {
                            // if dissociation method is set to "Auto" but could not be determined from the file, alert the user
                            if (!spectrumTypeByDissociationMethod.Contains(method.cvid))
                            {
                                throw new InvalidDataException("cannot handle unmapped dissociation method \"" + CV.cvTermInfo(method.cvid).shortName() + "\" for spectrum \"" + row.Value.SourceName + "/" + row.Value.SpectrumNativeID + "\"; please override the method manually");
                            }
                            else if (row.Value.SpectrumType != phosphoRS.SpectrumType.ECD_ETD) // don't override ETD (e.g. if there is also supplemental CID)
                            {
                                row.Value.SpectrumType = spectrumTypeByDissociationMethod[method.cvid];
                                spectrumTypes.Add(method.cvid);
                            }
                        }
                    }

                    if (row.Value.SpectrumType == phosphoRS.SpectrumType.None)
                    {
                        throw new InvalidDataException("cannot find a dissociation method for spectrum \"" + row.Value.SourceName + "/" + row.Value.SpectrumNativeID + "\"; please set the method manually");
                    }
                }
                else
                {
                    row.Value.SpectrumType = config.spectrumType;
                }

                var psm = getPhosphoRS_PSM(config, row.Value);

                // DEBUG
                //tbStatus.AppendText(PeptideToString(phosphoPeptide) + "," + AAS.ToOneLetterCodeString() + "," + ptmRepresentation.ToString() + "\n");
                // Init the mod map of original variant for this PSM.
                var id2ModMap = new List <System.Tuple <int, List <int> > > {
                    new System.Tuple <int, List <int> >((int)row.Value.PSMId, row.Value.OriginalPhosphoSites.Keys.ToList <int>())
                };

                items.Add(new System.Tuple <phosphoRS.PeptideSpectrumMatch, List <System.Tuple <int, List <int> > > >(psm, id2ModMap));

                ++rowNumber;
            }

            // report automatically found fragmentation method
            if (config.spectrumType == phosphoRS.SpectrumType.None)
            {
                setStatus(String.Format("Found {0} fragmentation types: {1}\r\n", spectrumTypes.Count, String.Join(", ", spectrumTypes.Keys.Select(o => CV.cvTermInfo(o).shortName()))));
            }

            setProgress(currentSource / totalSources * 100, String.Format("Running PhosphoRS on source {0} of {1} ({2})...", currentSource, totalSources, Path.GetFileName(sourceFilepath)));

            // Initialize the localization.
            currentNr = 0;
            var phosphoRS_Context = new phosphoRS.ThreadManagement(this, cancelAttestation, config.maxIsoformCount, config.maxPTMCount, config.scoreNLToo, config.fragmentMassTolerance, config.scoredAA, items.Count);

            // Start the site localization (takes advantage of multi-threading)
            try
            {
                phosphoRS_Context.StartPTMLocalisation();

                // Safety if the attestation module doesn't throw the exception.
                if (cancelAttestation.IsCancellationRequested)
                {
                    this.progressBar.ProgressBar.Visible = false;
                    _bgWorkerCancelled = true;
                    setProgress(-1, "Cancelled.");
                    return(null);
                }

                return(phosphoRS_Context.PTMResult);
            }
            catch (OperationCanceledException)
            {
                this.progressBar.ProgressBar.Visible = false;
                _bgWorkerCancelled = true;
                setProgress(-1, "Cancelled.");
                return(null);
            }
            finally
            {
                msd.Dispose();
            }
        }
Пример #9
0
        private phosphoRS.PeptideSpectrumMatch getPhosphoRS_PSM(PhosphoRSConfig config, PhosphoPeptideAttestationRow variant)
        {
            // Get the phosphorylated peptide and add all modifications to the base sequence.
            proteome.Peptide         phosphoPeptide     = new proteome.Peptide(variant.UnphosphorylatedSequence, proteome.ModificationParsing.ModificationParsing_Auto, proteome.ModificationDelimiter.ModificationDelimiter_Brackets);
            proteome.ModificationMap variantPeptideMods = phosphoPeptide.modifications();
            variant.OriginalPhosphoSites.Keys.ToList().ForEach(location => { variantPeptideMods[location].Add(config.pwizMod); });

            // This modification ID is used to tell phosphoRS how to modify the sequence.
            int modificationID = config.phosphorylationSymbol + 1;

            // Build a string representation of all modificaitons in a peptide for phospoRS
            // "0.00011000000000.0" : 1 is the ID of the modification. All phosphos in a data
            // set need to have one ID. This ID is used by the PhosphoRS to figure out which
            // mods need to be scored.
            var ptmRepresentation = new StringBuilder();

            // Store all modifications in phosphoRS modification objects
            var modifications = new List <phosphoRS.AminoAcidModification>();

            // Get the n-terminal modifications.
            if (variantPeptideMods.ContainsKey(proteome.ModificationMap.NTerminus()))
            {
                phosphoRS.AminoAcidModification otherMod = new phosphoRS.AminoAcidModification('2', "unknown", "unk", "none", variantPeptideMods[proteome.ModificationMap.NTerminus()].monoisotopicDeltaMass(), 0.0, null);
                modifications.Add(otherMod);
                ptmRepresentation.Append(modificationID.ToString() + ".");
                //++modificationID;
            }
            else
            {
                ptmRepresentation.Append("0.");
            }

            // Process all other modifications.
            for (int aaIndex = 0; aaIndex < phosphoPeptide.sequence.Length; ++aaIndex)
            {
                // If phosphorylation, use the existing scoredAA variable.
                if (variantPeptideMods.ContainsKey(aaIndex))
                {
                    if (variant.OriginalPhosphoSites.Keys.Contains(aaIndex))
                    {
                        modifications.Add(config.scoredAA);
                        ptmRepresentation.Append(config.phosphorylationSymbol.ToString()[0]);
                    }
                    else
                    {
                        // Otherwise, make an "unknown" modification with a separate modification ID.
                        var otherMod = new phosphoRS.AminoAcidModification(modificationID.ToString()[0], "unknown", "unk", "none", variantPeptideMods[aaIndex].monoisotopicDeltaMass(), 0.0, phosphoRS.AminoAcidSequence.ParseAASequence("" + phosphoPeptide.sequence[aaIndex]));
                        modifications.Add(otherMod);
                        ptmRepresentation.Append(modificationID.ToString());
                        //++modificationID;
                    }
                }
                else
                {
                    ptmRepresentation.Append("0");
                }
            }
            // Process any c-terminal modifications.
            if (variantPeptideMods.ContainsKey(proteome.ModificationMap.CTerminus()))
            {
                var otherMod = new phosphoRS.AminoAcidModification(modificationID.ToString()[0], "unknown", "unk", "none", variantPeptideMods[proteome.ModificationMap.CTerminus()].monoisotopicDeltaMass(), 0.0, null);
                modifications.Add(otherMod);
                ptmRepresentation.Append("." + modificationID.ToString());
            }
            else
            {
                ptmRepresentation.Append(".0");
            }

            // Get the phosphoRS peptide sequence.
            // Assign spectrum ID, amino acid sequence, list of all modifications, a so-called 'modification position string' (here every digit represents an amino acid within the peptide sequence
            // '0' indicates not modified, values != '0' indicate the unique identifier of the amino acid's modification the first digit represents the n-terminus the last digit represents the c-terminus)
            var AAS = phosphoRS.AminoAcidSequence.Create((int)variant.SpectrumId, phosphoPeptide.sequence, modifications, ptmRepresentation.ToString());

            // Make a phosphoRS peptide-spectrum match.
            return(new phosphoRS.PeptideSpectrumMatch((int)variant.PSMId, variant.SpectrumType, variant.Charge, variant.PrecursorMZ, variant.Peaks, AAS));
        }
Пример #10
0
        private string PeptideToString(proteome.Peptide peptide, IList <phosphoRS.PTMSiteProbability> localizationProbabilities, PhosphoRSConfig config)
        {
            var probabilityMap = localizationProbabilities.ToDictionary(o => o.SequencePosition, o => o.Probability);

            string        format = String.Format("[{{0:f{0}}}]", 0);
            StringBuilder sb     = new StringBuilder();

            if (peptide.modifications().ContainsKey(proteome.ModificationMap.NTerminus()))
            {
                sb.AppendFormat(format, peptide.modifications()[proteome.ModificationMap.NTerminus()].monoisotopicDeltaMass());
            }
            for (int i = 0; i < peptide.sequence.Length; ++i)
            {
                sb.Append(peptide.sequence[i]);
                if (probabilityMap.ContainsKey(i + 1))
                {
                    if (probabilityMap[i + 1] > 0)
                    {
                        sb.AppendFormat("[{0:f0}({1:f0}%)]", config.scoredAA.MassDelta, probabilityMap[i + 1] * 100);
                    }
                    //else
                    //    sb.AppendFormat("({0:f0})", config.scoredAA.MassDelta, probabilityMap[i + 1]);
                }
                else if (peptide.modifications().ContainsKey(i))
                {
                    double modMass = peptide.modifications()[i].monoisotopicDeltaMass();
                    sb.AppendFormat(format, modMass);
                }
            }
            if (peptide.modifications().ContainsKey(proteome.ModificationMap.CTerminus()))
            {
                sb.AppendFormat(format, peptide.modifications()[proteome.ModificationMap.CTerminus()].monoisotopicDeltaMass());
            }
            return(sb.ToString());
        }