Exemple #1
0
        void CalculateAnalysisResults(PeptideAnalysis peptideAnalysis)
        {
            bool changed = false;

            foreach (var fileAnalysis in peptideAnalysis.FileAnalyses.ListPeptideFileAnalyses(false))
            {
                if (fileAnalysis.PeptideDistributions.ChildCount != 0)
                {
                    continue;
                }
                if (!fileAnalysis.EnsureCalculated())
                {
                    _workspace.EnsureChromatograms(fileAnalysis);
                    continue;
                }
                changed = true;
                Debug.Assert(fileAnalysis.HasChromatograms);
            }
            if (!changed)
            {
                peptideAnalysis.PeptideRates.EnsureChildrenLoaded();
            }
            if (changed || peptideAnalysis.PeptideRates.ChildCount == 0)
            {
                using (_workspace.OpenSession())
                {
                    peptideAnalysis.PeptideRates.Clear();
                    peptideAnalysis.PeptideRates.EnsureCalculated();
                }
            }
        }
Exemple #2
0
        public static PeptideAnalysisFrame ShowPeptideAnalysis(PeptideAnalysis peptideAnalysis)
        {
            if (peptideAnalysis == null)
            {
                return(null);
            }
            var form = Program.FindOpenEntityForm <PeptideAnalysisFrame>(peptideAnalysis);

            if (form != null)
            {
                form.Activate();
                return(form);
            }
            using (peptideAnalysis.IncChromatogramRefCount())
            {
                TopographForm.Instance.LoadPeptideAnalysis(peptideAnalysis.Id);
                if (!peptideAnalysis.ChromatogramsWereLoaded)
                {
                    return(null);
                }
                form = new PeptideAnalysisFrame(peptideAnalysis);
                form.Show(TopographForm.Instance.DocumentPanel, DockState.Document);
                return(form);
            }
        }
Exemple #3
0
        /// <summary>
        /// returns max B-fac and resolution values for all pdbs in AB database without duplicate entries
        /// </summary>
        /// <param name="_myModule"></param>
        /// <param name="_pathToInputXMLPDBfiles"></param>
        /// <returns>Hashtable: keyed by pdbname, value: ArrayList:
        /// [0]: (double) resolution
        /// [1]: (Hashtable) keys: loopType values: (double) maxBfac</returns>
        public Hashtable GetQualityStatisticsHash(ref PeptideAnalysis _myModule, string _pathToInputXMLPDBfiles)
        {
            Hashtable     qualityStatsHash    = new Hashtable();
            List <string> nonredundantPDBlist = new List <string>();

            nonredundantPDBlist = GetPDBidsWithoutDuplicates();
            Hashtable resolutionHash = new Hashtable();
            Hashtable bfactorHash    = new Hashtable();

            resolutionHash = GetResolutionHashtable(nonredundantPDBlist);
            //public Hashtable GetMaxBfactorHash(ref AntibodyXMLreader _xmlReader, string _pathToInputXMLPDBfiles, ArrayList _pdbList)
            bfactorHash = _myModule.GetMaxBfactorHash(this, _pathToInputXMLPDBfiles, nonredundantPDBlist);
            ICollection resKeys = resolutionHash.Keys;

            foreach (string pdbKey in resKeys)
            {
                if (bfactorHash.ContainsKey(pdbKey))
                {
                    ArrayList valuesForPDB = new ArrayList();
                    valuesForPDB.Add((double)resolutionHash[pdbKey]); // double
                    valuesForPDB.Add((Hashtable)bfactorHash[pdbKey]); // hash by loop type: values are doubles (bfac)
                    qualityStatsHash.Add((string)pdbKey, valuesForPDB);
                }
                else
                {
                    Console.WriteLine("bfactorHash does not contain key {0} in GetQualityStatisticsHash", pdbKey);
                    Console.ReadLine();
                }
            }

            return(qualityStatsHash);
        }
Exemple #4
0
 private void OnPeptideAnalysisChanged()
 {
     Text                       = TabText = PeptideAnalysis.GetLabel();
     tbxSequence.Text           = PeptideAnalysis.Peptide.FullSequence;
     tbxProteinDescription.Text = PeptideAnalysis.Peptide.ProteinDescription;
     tbxProteinName.Text        = PeptideAnalysis.Peptide.GetProteinKey();
 }
Exemple #5
0
        private void TestPeptide(Workspace workspace, PeakFinderPeptide peakFinderPeptide)
        {
            DbPeptideFileAnalysis dbPeptideFileAnalysis;

            using (var session = workspace.OpenSession())
            {
                dbPeptideFileAnalysis = (DbPeptideFileAnalysis)session.CreateQuery(
                    "FROM DbPeptideFileAnalysis T WHERE T.MsDataFile.Name = :dataFile AND T.PeptideAnalysis.Peptide.Sequence = :sequence")
                                        .SetParameter("dataFile", peakFinderPeptide.DataFile)
                                        .SetParameter("sequence",
                                                      peakFinderPeptide.PeptideSequence)
                                        .UniqueResult();
            }
            PeptideAnalysis peptideAnalysis = workspace.PeptideAnalyses.FindByKey(dbPeptideFileAnalysis.PeptideAnalysis.Id.GetValueOrDefault());

            using (peptideAnalysis.IncChromatogramRefCount())
            {
                workspace.DatabasePoller.LoadAndMergeChanges(new Dictionary <long, bool> {
                    { peptideAnalysis.Id, true }
                });
                PeptideFileAnalysis peptideFileAnalysis = peptideAnalysis.GetFileAnalysis(dbPeptideFileAnalysis.Id.GetValueOrDefault());
                var          peaks  = CalculatedPeaks.Calculate(peptideFileAnalysis, new CalculatedPeaks[0]);
                const string format = "0.000";
                Assert.AreEqual(
                    peakFinderPeptide.ExpectedPeakStart.ToString(format) + "-" + peakFinderPeptide.ExpectedPeakEnd.ToString(format),
                    (peaks.StartTime.GetValueOrDefault() / 60).ToString(format) + "-" + (peaks.EndTime.GetValueOrDefault() / 60).ToString(format), peakFinderPeptide.PeptideSequence);
            }
        }
        protected override bool MsGraphControlOnMouseUpEvent(ZedGraphControl sender, MouseEventArgs e)
        {
            if (_peakResize != null)
            {
                var    point = new PointF(e.X - _peakResize.MousePt.X + _peakResize.CoordPt.X, e.Y);
                double x, y;
                MsGraphControl.GraphPane.ReverseTransform(point, out x, out y);
                var    peaks = PeptideFileAnalysis.CalculatedPeaks;
                double newStart, newEnd;
                switch (_peakResize.LineSegment)
                {
                case LineSegment.Start:
                    newStart = x;
                    newEnd   = _peakResize.Peak.EndTime;
                    break;

                case LineSegment.End:
                    newStart = _peakResize.Peak.StartTime;
                    newEnd   = x;
                    break;

                default:
                    newStart = x;
                    newEnd   = x - _peakResize.Peak.StartTime + _peakResize.Peak.EndTime;
                    break;
                }
                var newPeaks = peaks.ChangeTime(_peakResize.TracerFormula, Math.Min(newStart, newEnd), Math.Max(newStart, newEnd));
                _peakResize = null;
                PeptideFileAnalysis.SetCalculatedPeaks(newPeaks);
                PeptideAnalysis.EnsurePeaksCalculated();
            }
            return(base.MsGraphControlOnMouseUpEvent(sender, e));
        }
Exemple #7
0
 public void SetPeptideAnalysis(PeptideAnalysis peptideAnalysis)
 {
     PeptideSequence = peptideAnalysis.Peptide.Sequence;
     MinCharge       = peptideAnalysis.MinCharge;
     MaxCharge       = peptideAnalysis.MaxCharge;
     MassAccuracy    = peptideAnalysis.GetMassAccuracy();
 }
Exemple #8
0
 public PeptideAnalysisForm(PeptideAnalysis peptideAnalysis) : base(peptideAnalysis)
 {
     InitializeComponent();
     gridViewExcludedMzs.PeptideAnalysis = peptideAnalysis;
     tbxSequence.Text = peptideAnalysis.Peptide.Sequence;
     TabText          = PeptideAnalysis.GetLabel();
 }
 public PeptideAnalysisForm(PeptideAnalysis peptideAnalysis)
     : base(peptideAnalysis)
 {
     InitializeComponent();
     gridViewExcludedMzs.PeptideAnalysis = peptideAnalysis;
     tbxSequence.Text = peptideAnalysis.Peptide.Sequence;
     TabText = PeptideAnalysis.GetLabel();
 }
 private IList <KeyValuePair <PeptideFileAnalysis, double> > ListScores()
 {
     return(PeptideAnalysis.GetFileAnalyses(true)
            .Select(peptideFileAnalysis => new KeyValuePair <PeptideFileAnalysis, double?>(peptideFileAnalysis, peptideFileAnalysis.PeakData.DeconvolutionScore))
            .Where(kvp => kvp.Value.HasValue)
            .Select(kvp => new KeyValuePair <PeptideFileAnalysis, double>(kvp.Key, kvp.Value.GetValueOrDefault()))
            .ToArray());
 }
Exemple #11
0
 protected override void OnHandleCreated(EventArgs e)
 {
     base.OnHandleCreated(e);
     foreach (PeptideFileAnalysis peptideFileAnalysis in PeptideAnalysis.GetFileAnalyses())
     {
         UpdateRow(AddRow(peptideFileAnalysis));
     }
     OnPeptideAnalysisChanged();
 }
Exemple #12
0
 public PeptideAnalysisFrame(PeptideAnalysis peptideAnalysis) : base(peptideAnalysis)
 {
     InitializeComponent();
     _dockPanel = new DockPanel
     {
         Dock = DockStyle.Fill
     };
     panel1.Controls.Add(_dockPanel);
 }
Exemple #13
0
 protected override void OnHandleCreated(EventArgs e)
 {
     base.OnHandleCreated(e);
     foreach (PeptideFileAnalysis peptideFileAnalysis in PeptideAnalysis.GetFileAnalyses(false))
     {
         UpdateRow(AddRow(peptideFileAnalysis));
     }
     OnPeptideAnalysisChanged();
     InitializeOriginalMinMaxCharge();
 }
 public PeptideAnalysisFrame(PeptideAnalysis peptideAnalysis)
     : base(peptideAnalysis)
 {
     InitializeComponent();
     _dockPanel = new DockPanel
                      {
                          Dock = DockStyle.Fill
                      };
     panel1.Controls.Add(_dockPanel);
 }
Exemple #15
0
        public void UpdateGrid()
        {
            double monoisotopicMass =
                Workspace.GetAminoAcidFormulas().GetMonoisotopicMass(PeptideAnalysis.Peptide.Sequence);
            var masses = PeptideAnalysis.GetTurnoverCalculator().GetMzs(0);

            if (MassColumn == null)
            {
                MassColumn = new DataGridViewTextBoxColumn
                {
                    HeaderText = "Mass",
                    Name       = "colMass",
                    Width      = 60,
                    ReadOnly   = true,
                };
                Columns.Add(MassColumn);
            }
            if (ExcludedColumn == null)
            {
                ExcludedColumn = new DataGridViewCheckBoxColumn
                {
                    HeaderText = "Excluded",
                    Name       = "colExcluded",
                    Width      = 50,
                    SortMode   = DataGridViewColumnSortMode.NotSortable,
                };
                Columns.Add(ExcludedColumn);
            }
            if (Rows.Count != PeptideAnalysis.GetMassCount())
            {
                Rows.Clear();
                Rows.Add(PeptideAnalysis.GetMassCount());
                for (int iRow = 0; iRow < Rows.Count; iRow++)
                {
                    Rows[iRow].Tag = iRow;
                }
            }
            for (int iRow = 0; iRow < Rows.Count; iRow++)
            {
                var    row            = Rows[iRow];
                var    iMass          = (int)row.Tag;
                double massDifference = masses[iMass].Center - monoisotopicMass;

                var label = massDifference.ToString("0.#");
                if (label[0] != '-')
                {
                    label = "+" + label;
                }
                label = "M" + label;
                row.Cells[MassColumn.Index].Value           = label;
                row.Cells[MassColumn.Index].ToolTipText     = "Mass:" + masses[iMass];
                row.Cells[MassColumn.Index].Style.BackColor = TracerChromatogramForm.GetColor(iRow, Rows.Count);
                row.Cells[ExcludedColumn.Index].Value       = ExcludedMasses.IsMassExcluded(iMass);
            }
        }
Exemple #16
0
 protected override void OnHandleCreated(EventArgs e)
 {
     base.OnHandleCreated(e);
     PeptideAnalysis.IncChromatogramRefCount();
     OnPeptideAnalysisChanged();
     if (PeptideAnalysisSummary == null)
     {
         PeptideAnalysisSummary = new PeptideAnalysisSummary(PeptideAnalysis);
         PeptideAnalysisSummary.Show(_dockPanel, DockState.Document);
     }
 }
        protected virtual ICollection <int> GetSelectedMasses()
        {
            var result    = new List <int>();
            int massCount = PeptideAnalysis.GetMassCount();

            for (int i = 0; i < massCount; i++)
            {
                result.Add(i);
            }
            return(result);
        }
Exemple #18
0
 private void AddDirtyPeptideAnalysis(PeptideAnalysis peptideAnalysis)
 {
     lock (this)
     {
         if (_dirtyPeptideAnalysesSet.Contains(peptideAnalysis))
         {
             return;
         }
         _dirtyPeptideAnalysesSet.Add(peptideAnalysis);
         _dirtyPeptideAnalyses.AddLast(peptideAnalysis);
         _eventWaitHandle.Set();
     }
 }
 private void AddDirtyPeptideAnalysis(PeptideAnalysis peptideAnalysis)
 {
     lock(this)
     {
         if (_dirtyPeptideAnalysesSet.Contains(peptideAnalysis))
         {
             return;
         }
         _dirtyPeptideAnalysesSet.Add(peptideAnalysis);
         _dirtyPeptideAnalyses.AddLast(peptideAnalysis);
         _eventWaitHandle.Set();
     }
 }
Exemple #20
0
 public PeptideAnalysisSummary(PeptideAnalysis peptideAnalysis) : base(peptideAnalysis)
 {
     InitializeComponent();
     colPeakStart.DefaultCellStyle.Format           = "0.##";
     colPeakEnd.DefaultCellStyle.Format             = "0.##";
     colScore.DefaultCellStyle.Format               = "0.####";
     colTracerPercent.DefaultCellStyle.Format       = "0.##%";
     colTurnover.DefaultCellStyle.Format            = "0.##%";
     colPrecursorEnrichment.DefaultCellStyle.Format = "0.##%";
     gridViewExcludedMzs.PeptideAnalysis            = peptideAnalysis;
     tbxSequence.Text = peptideAnalysis.Peptide.Sequence;
     TabText          = "Summary";
 }
 public PeptideAnalysisSummary(PeptideAnalysis peptideAnalysis)
     : base(peptideAnalysis)
 {
     InitializeComponent();
     colPeakStart.DefaultCellStyle.Format = "0.##";
     colPeakEnd.DefaultCellStyle.Format = "0.##";
     colScore.DefaultCellStyle.Format = "0.####";
     colTracerPercent.DefaultCellStyle.Format = "0.##%";
     colTurnover.DefaultCellStyle.Format = "0.##%";
     colPrecursorEnrichment.DefaultCellStyle.Format = "0.##%";
     gridViewExcludedMzs.PeptideAnalysis = peptideAnalysis;
     tbxSequence.Text = peptideAnalysis.Peptide.Sequence;
     TabText = "Summary";
 }
Exemple #22
0
        void WorkerMethod()
        {
            _workspace.PeptideAnalyses.LoadPeptideRates();
            _workspace.PeptideAnalyses.LoadPeptideFileAnalyses();
            var fileAnalysesWithoutChromatograms = new List <PeptideFileAnalysis>();

            foreach (var peptideAnalysis in _workspace.PeptideAnalyses.ListChildren())
            {
                AddDirtyPeptideAnalysis(peptideAnalysis);
                foreach (var peptideFileAnalysis in peptideAnalysis.FileAnalyses.ListChildren())
                {
                    if (!peptideFileAnalysis.HasChromatograms)
                    {
                        fileAnalysesWithoutChromatograms.Add(peptideFileAnalysis);
                    }
                }
            }
            _workspace.GenerateChromatograms(fileAnalysesWithoutChromatograms);
            while (true)
            {
                PeptideAnalysis peptideAnalysis = null;
                lock (this)
                {
                    if (!_isRunning)
                    {
                        break;
                    }
                    if (_dirtyPeptideAnalyses.Count > 0)
                    {
                        peptideAnalysis = _dirtyPeptideAnalyses.First.Value;
                        _dirtyPeptideAnalyses.RemoveFirst();
                        _dirtyPeptideAnalysesSet.Remove(peptideAnalysis);
                    }
                    if (peptideAnalysis == null)
                    {
                        _eventWaitHandle.Reset();
                    }
                }
                if (peptideAnalysis == null)
                {
                    _eventWaitHandle.WaitOne();
                    continue;
                }
                CalculateAnalysisResults(peptideAnalysis);
            }
        }
 protected void SetAutoFindPeak(bool autoFindPeak)
 {
     if (autoFindPeak == PeptideFileAnalysis.AutoFindPeak)
     {
         return;
     }
     if (autoFindPeak)
     {
         PeptideFileAnalysis.SetAutoFindPeak();
     }
     else
     {
         PeptideAnalysis.EnsurePeaksCalculated();
         var newPeaks = PeptideFileAnalysis.CalculatedPeaks.ChangeBasePeak(PeptideFileAnalysis.CalculatedPeaks.BasePeakKey);
         Debug.Assert(!newPeaks.AutoFindPeak);
         PeptideFileAnalysis.SetCalculatedPeaks(newPeaks);
     }
 }
Exemple #24
0
        private PeptideDataForm(PeptideAnalysis peptideAnalysis) : base(peptideAnalysis)
        {
            InitializeComponent();
            Workspace = peptideAnalysis.Workspace;
            dockPanel = new DockPanel
            {
                Dock = DockStyle.Fill
            };
            panel1.Controls.Add(dockPanel);
            tbxDataFile.Text = peptideAnalysis.MsDataFileName;
            tbxSequence.Text = peptideAnalysis.ChargedPeptide.ToString();
            String label = PeptideAnalysis.Sequence + "+" + PeptideAnalysis.Charge;

            if (label.Length > 15)
            {
                label = label.Substring(0, 5) + "..." + label.Substring(label.Length - 7, 7);
            }
            Name = TabText = label;
        }
        void DisplaySpectrum(int scanIndex)
        {
            if (!TopographForm.Instance.EnsureMsDataFile(PeptideFileAnalysis.MsDataFile, true))
            {
                return;
            }
            SpectrumForm spectrumForm;

            spectrumForm = new SpectrumForm(PeptideFileAnalysis.MsDataFile)
            {
                ScanIndex = scanIndex,
            };
            spectrumForm.SetPeptideAnalysis(PeptideAnalysis);
            spectrumForm.Show(TopLevelControl);
            double minMz           = 2000;
            double maxMz           = 0;
            var    selectedCharges = GetSelectedCharges();
            var    selectedMasses  = GetSelectedMasses();

            for (int charge = PeptideAnalysis.MinCharge; charge <= PeptideAnalysis.MaxCharge; charge++)
            {
                if (selectedCharges.Count > 0 && !selectedCharges.Contains(charge))
                {
                    continue;
                }
                for (int iMass = 0; iMass < PeptideAnalysis.GetMassCount(); iMass++)
                {
                    if (selectedMasses.Count > 0 && !selectedMasses.Contains(iMass))
                    {
                        continue;
                    }
                    var mzRange = PeptideAnalysis.GetMzs()[charge][iMass];
                    minMz = Math.Min(minMz, mzRange.Min);
                    maxMz = Math.Max(maxMz, mzRange.Max);
                }
            }
            if (minMz <= maxMz)
            {
                spectrumForm.Zoom(minMz - 1, maxMz + 1);
            }
        }
Exemple #26
0
        public static PeptideDataForm ActivatePeptideDataForm(Form sibling, PeptideAnalysis peptideAnalysis)
        {
            PeptideDataForm peptideDataForm;

            foreach (var form in Application.OpenForms)
            {
                if (!(form is PeptideDataForm))
                {
                    continue;
                }

                if (((PeptideDataForm)form).PeptideAnalysis != peptideAnalysis)
                {
                    continue;
                }
                peptideDataForm = (PeptideDataForm)form;
                peptideDataForm.Activate();
                return(peptideDataForm);
            }
            peptideDataForm = new PeptideDataForm(peptideAnalysis);
            if (sibling is DockableForm)
            {
                DockableForm dockableSibling = (DockableForm)sibling;
                if (dockableSibling.DockPanel != null)
                {
                    peptideDataForm.Show(dockableSibling.DockPanel, dockableSibling.DockState);
                    return(peptideDataForm);
                }
            }
            if (sibling != null)
            {
                peptideDataForm.Show(sibling.Parent);
            }
            else
            {
                peptideDataForm.Show(null);
            }
            peptideDataForm.ShowForm <PeptideInfoForm>();
            return(peptideDataForm);
        }
Exemple #27
0
        protected void OnPeptideAnalysisChanged()
        {
            PeptideAnalysis.EnsurePeaksCalculated();
            var res = Workspace.GetAminoAcidFormulas();

            tbxFormula.Text      = res.GetFormula(Peptide.Sequence).ToString();
            tbxMonoMass.Text     = Peptide.GetChargedPeptide(1).GetMonoisotopicMass(res).ToString("0.####");
            tbxAvgMass.Text      = Peptide.GetChargedPeptide(1).GetMassDistribution(res).AverageMass.ToString("0.####");
            tbxMinCharge.Text    = PeptideAnalysis.MinCharge.ToString(CultureInfo.CurrentCulture);
            tbxMaxCharge.Text    = PeptideAnalysis.MaxCharge.ToString(CultureInfo.CurrentCulture);
            tbxProtein.Text      = Peptide.ProteinName + " " + Peptide.ProteinDescription;
            tbxMassAccuracy.Text = PeptideAnalysis.GetMassAccuracy().ToString(CultureInfo.CurrentCulture);
            if (PeptideAnalysis.MassAccuracy == null)
            {
                tbxMassAccuracy.Font = Font;
            }
            else
            {
                tbxMassAccuracy.Font = new Font(Font, FontStyle.Bold);
            }
            if (_originalMinCharge.HasValue && _originalMinCharge != PeptideAnalysis.MinCharge)
            {
                tbxMinCharge.Font = new Font(Font, FontStyle.Bold);
            }
            else
            {
                tbxMinCharge.Font = Font;
            }
            if (_originalMaxCharge.HasValue && _originalMaxCharge != PeptideAnalysis.MaxCharge)
            {
                tbxMaxCharge.Font = new Font(Font, FontStyle.Bold);
            }
            else
            {
                tbxMaxCharge.Font = Font;
            }

            UpdateMassGrid();
            UpdateRows(PeptideAnalysis.FileAnalyses);
        }
 public static PeptideAnalysisFrame ShowPeptideAnalysis(PeptideAnalysis peptideAnalysis)
 {
     if (peptideAnalysis == null)
     {
         return null;
     }
     var form = Program.FindOpenEntityForm<PeptideAnalysisFrame>(peptideAnalysis);
     if (form != null)
     {
         form.Activate();
         return form;
     }
     using (peptideAnalysis.IncChromatogramRefCount())
     {
         TopographForm.Instance.LoadPeptideAnalysis(peptideAnalysis.Id);
         if (!peptideAnalysis.ChromatogramsWereLoaded)
         {
             return null;
         }
         form = new PeptideAnalysisFrame(peptideAnalysis);
         form.Show(TopographForm.Instance.DocumentPanel, DockState.Document);
         return form;
     }
 }
Exemple #29
0
        public void ClusterByAffinityWithMultiThreading(ref int _numberOfClusters, ref List <PeptideAnalysis.myLoopDataObject> _loopObjsByPDB, int _maxIterationCount, ref ArrayList _centerOfEachCluster, ref ArrayList _centerForEachPoint, ref ArrayList _LinesToWrite, double _selfSimFactor, string _progFileName, ref PeptideAnalysis _myModule)
        {
            bool reportOnEachIteration = new bool();

            reportOnEachIteration = true;
            bool useSimulatedAnnealing = new bool();

            useSimulatedAnnealing = false;
            Console.WriteLine("Started clustering at {0}", DateTime.Now);
            int[] bestClusterData       = new int[_loopObjsByPDB.Count];
            int   totalNumberOfClusters = new int();

            totalNumberOfClusters = 0;
            int    previousTotalNumberOfClusters = new int();
            string doNotWriteFlag = "donotwrite";
            bool   writeProgFiles = new bool();

            writeProgFiles = true;
            int lastExecutedIteration = new int();

            lastExecutedIteration = 0;
            if (_progFileName == doNotWriteFlag)
            {
                writeProgFiles = false;
            }
            ArrayList linesToWrite = new ArrayList();
            //bool needToBreak = new bool();
            //needToBreak = false;
            bool reportOnIteration = new bool();

            //bool firstReportOfConstCenters = new bool();
            //firstReportOfConstCenters = false;
            //bool firstReportOfConstClusters = new bool();
            //firstReportOfConstClusters = false;

            // setup: calculate matrix of distances
            // need: *list of pdbs, dihedrals
            // to create distance matrix, need to pass ArrayList of ArrayLists (one per dihedral-position)[loop0][loop1]
            //double[,] distanceMatrix = new double[_dihedralsByPDB.Count, _dihedralsByPDB.Count];
            //double[,] similarityMatrix = new double[_dihedralsByPDB.Count, _dihedralsByPDB.Count];

            //testing with number line here!!

            double[,] distanceMatrix = new double[_loopObjsByPDB.Count, _loopObjsByPDB.Count];

            distanceMatrix = _myModule.GenerateDistanceMatrix(ref _loopObjsByPDB);

            //generateMultiThreadInfoHere
            int numberOfRowsPerThread = _loopObjsByPDB.Count / totalNumberOfThreads; // forces answer to be rounded-off int

            //end multithreadInfo


            // ************** opening up a temporary write file (pdbs,centers)
            ArrayList progFileLinesToWrite = new ArrayList();

            //*************** end of write file block


            //distanceMatrix = GenerateDistanceMatrix(_dihedralsByPDB);

            // now, calculate the similarities
            // self-similarity can be an adjustable parameter
            double selfSimilarityConstant = new double();
            int    countForAverage        = new int();

            countForAverage        = 0;
            selfSimilarityConstant = 0;
            for (int simIndex = 0; simIndex < _loopObjsByPDB.Count; simIndex++)
            {
                for (int simIndex2 = 0; simIndex2 < _loopObjsByPDB.Count; simIndex2++)
                {
                    localSimilarities[simIndex, simIndex2] = -1 * distanceMatrix[simIndex, simIndex2];
                    if (simIndex != simIndex2)
                    {
                        selfSimilarityConstant += localSimilarities[simIndex, simIndex2];
                        countForAverage++;
                    }
                }
            }
            selfSimilarityConstant = _selfSimFactor * selfSimilarityConstant / countForAverage;
            for (int simIndex = 0; simIndex < _loopObjsByPDB.Count; simIndex++)
            {
                localSimilarities[simIndex, simIndex] = selfSimilarityConstant;
            }

            // more setup: initialize availabilities, set update parameter lambda, declare responsibility matrix

            double updateLambda = new double();

            updateLambda = 0.5;
            for (int avIndex = 0; avIndex < _loopObjsByPDB.Count; avIndex++)
            {
                for (int avIndex2 = 0; avIndex2 < _loopObjsByPDB.Count; avIndex2++)
                {
                    localAvailabilities[avIndex, avIndex2]   = 0;
                    localResponsibilities[avIndex, avIndex2] = 0;
                }
            }

            updateLambda = 0.5;

            //double withinClusterScatter = new double();
            bool haveSeenIdenticalCenterAssignments = new bool();

            haveSeenIdenticalCenterAssignments = false;
            bool reportNextClusters = new bool();

            reportNextClusters = false;
            int numberOfIterationsWithConstantClusterAssignments = new int();

            numberOfIterationsWithConstantClusterAssignments = 0;
            int[] previousClusterAssignments = new int[_loopObjsByPDB.Count];
            for (int loopIndex = 0; loopIndex < _loopObjsByPDB.Count; loopIndex++)
            {
                previousClusterAssignments[loopIndex] = 0;
            }

            for (int iterationCounter = 0; iterationCounter < _maxIterationCount; iterationCounter++)
            {
                previousTotalNumberOfClusters = totalNumberOfClusters;
                if (iterationCounter % 20 == 0)
                {
                    reportOnIteration = true;
                }
                else
                {
                    reportOnIteration = false;
                }
                if (reportOnEachIteration)
                {
                    reportOnIteration = true;
                }

                // relaxing parameter
                // doesn't do anything with clustering of AB conformations, because they cluster before 250 anyways
                // (and there the max iteration count is 500)
                if ((useSimulatedAnnealing) && ((iterationCounter > _maxIterationCount / 2) || haveSeenIdenticalCenterAssignments))
                {
                    updateLambda = updateLambda * (double)0.95;
                }


                if (reportOnIteration)
                {
                    Console.WriteLine("Started algorithm loop {0} at {1}", iterationCounter, DateTime.Now);
                }

                //step 1: update responsibilities
                // find the value of k' (!=k) that maxs the quantity (a(i,k') + s(i,k')) for fixed i
                List <Thread> threadsForResp = new List <Thread>();
                for (int thrCtr = 0; thrCtr < totalNumberOfThreads; thrCtr++)
                {
                    Thread aTaskThread = new Thread(this.CalculateResponsibilitiesMT);
                    threadsForResp.Add(aTaskThread);
                }
                for (int thrCtr = 0; thrCtr < totalNumberOfThreads; thrCtr++)
                {
                    ArrayList paramsListForPass = new ArrayList();
                    paramsListForPass.Add((numberOfRowsPerThread * thrCtr));
                    if (thrCtr < totalNumberOfThreads - 1)
                    {
                        paramsListForPass.Add((numberOfRowsPerThread * (thrCtr + 1)) - 1);
                    }
                    else
                    {
                        paramsListForPass.Add(_loopObjsByPDB.Count - 1);
                    }
                    paramsListForPass.Add(updateLambda);
                    threadsForResp[thrCtr].Start((object)paramsListForPass);
                }

                // now, wait until the threads are done

                thrCountdown.Wait();
                thrCountdown.AddCount(totalNumberOfThreads);

                // step 2: update availabilities
                if (reportOnIteration)
                {
                    Console.WriteLine("Finished responsibilities, starting availabilities at {0}", DateTime.Now);
                }

                List <Thread> threadsForAv = new List <Thread>();
                for (int thrCtr = 0; thrCtr < totalNumberOfThreads; thrCtr++)
                {
                    Thread aTaskThread = new Thread(this.CalculateAvailabilitiesMT);
                    threadsForAv.Add(aTaskThread);
                }
                for (int thrCtr = 0; thrCtr < totalNumberOfThreads; thrCtr++)
                {
                    ArrayList paramsListForPass = new ArrayList();
                    paramsListForPass.Add((numberOfRowsPerThread * thrCtr));
                    if (thrCtr < totalNumberOfThreads - 1)
                    {
                        paramsListForPass.Add((numberOfRowsPerThread * (thrCtr + 1)) - 1);
                    }
                    else
                    {
                        paramsListForPass.Add(_loopObjsByPDB.Count - 1);
                    }
                    paramsListForPass.Add(updateLambda);
                    threadsForAv[thrCtr].Start((object)paramsListForPass);
                }
                // then, wait until the threads finish

                thrCountdown.Wait();
                thrCountdown.AddCount(totalNumberOfThreads);

                // Step 3: compute centers
                // debugging variables here
                // define clustering after this step?

                if (reportOnIteration)
                {
                    Console.WriteLine("Finished availabilities, computing centers at {0}", DateTime.Now);
                }

                List <Thread> threadsForCtr = new List <Thread>();
                for (int thrCtr = 0; thrCtr < totalNumberOfThreads; thrCtr++)
                {
                    Thread aTaskThread = new Thread(this.ComputeCentersMT);
                    threadsForCtr.Add(aTaskThread);
                }
                for (int thrCtr = 0; thrCtr < totalNumberOfThreads; thrCtr++)
                {
                    ArrayList paramsListForPass = new ArrayList();
                    paramsListForPass.Add((numberOfRowsPerThread * thrCtr));
                    if (thrCtr < totalNumberOfThreads - 1)
                    {
                        paramsListForPass.Add((numberOfRowsPerThread * (thrCtr + 1)) - 1);
                    }
                    else
                    {
                        paramsListForPass.Add(_loopObjsByPDB.Count - 1);
                    }
                    threadsForCtr[thrCtr].Start((object)paramsListForPass);
                }

                thrCountdown.Wait();
                thrCountdown.AddCount(totalNumberOfThreads);

                // see if the center/exemplar assignments are the same as the previous iteration
                //bool writeToProgressFile = new bool();


                if (reportOnIteration)
                {
                    Console.WriteLine("Finished computing centers, calculating clusters at {0}", DateTime.Now);
                }

                //code block: convergence by constant cluster ID
                int[] thisIterClusterData      = new int[_loopObjsByPDB.Count];
                bool  thisIterClusteringFailed = new bool();
                // don't need to multithread this-- not O(N-squared)?

                int[] thisIterCenters = _myModule.ClusterWithSorting(ref localCenterAssignments, ref thisIterClusterData, ref thisIterClusteringFailed);

                // end of Clustering MT block
                if (thisIterClusteringFailed && writeProgFiles)
                {
                    string oopsstring = "attempt at clustering in loop failed in affinity clustering for progfile " + _progFileName + " at iteration " + iterationCounter.ToString();
                    linesToWrite.Add(oopsstring);
                    progFileLinesToWrite.Add(oopsstring);
                }
                if (thisIterClusteringFailed)
                {
                    Console.WriteLine("clustering failed in affinity clustering. error!");
                }
                if ((iterationCounter < 200) || (iterationCounter % 1000 == 0) || (reportNextClusters))
                {
                    int debugNumberClusters = new int();
                    debugNumberClusters = thisIterCenters.Length;
                    string debugLine = iterationCounter.ToString() + "\t" + debugNumberClusters.ToString();
                    progFileLinesToWrite.Add(debugLine);
                    if (iterationCounter > 200)
                    {
                        if ((iterationCounter - 10) % 1000 == 0)
                        {
                            reportNextClusters = false;
                        }
                        else
                        {
                            reportNextClusters = true;
                        }
                    }
                }
                bool testedAsEqual = new bool();
                testedAsEqual = true;
                for (int dIndex = 0; dIndex < thisIterClusterData.Length; dIndex++)
                {
                    if (thisIterClusterData[dIndex] != previousClusterAssignments[dIndex])
                    {
                        testedAsEqual = false; break;
                    }
                }

                if (testedAsEqual)
                {
                    numberOfIterationsWithConstantClusterAssignments++;
                    if (numberOfIterationsWithConstantClusterAssignments > 3)
                    {
                        if (iterationCounter > 10)
                        {
                            lastExecutedIteration = iterationCounter; break;
                        }
                    }
                }
                else
                {
                    numberOfIterationsWithConstantClusterAssignments = 0; previousClusterAssignments = thisIterClusterData;
                }

                // output for FS

                if (reportOnIteration)
                {
                    Console.WriteLine("Finished iteration {0} at {1}", iterationCounter.ToString(), DateTime.Now);
                }

                if ((iterationCounter == _maxIterationCount - 1) && writeProgFiles)
                {
                    string progLine = "Hit max iterations at it " + iterationCounter.ToString() +
                                      ", did not converge according to test, exiting.";
                    progFileLinesToWrite.Add(progLine);
                    lastExecutedIteration = iterationCounter;
                }
            }

            // get _centerForEachPoint ready to return

            foreach (int intCenter in localCenterAssignments)
            {
                _centerForEachPoint.Add(intCenter);
            }
            // construct clusters from exemplar data
            Console.WriteLine("Starting cluster construction at {0}", DateTime.Now);

            bool finalClusteringFailed = new bool();

            int[] centersForEachCluster = _myModule.ClusterWithSorting(ref localCenterAssignments, ref bestClusterData, ref finalClusteringFailed);
            if (finalClusteringFailed)
            {
                string oopsstring = "attempt at clustering in wrapup failed in affinity clustering for progfile " + _progFileName;
                linesToWrite.Add(oopsstring);
                if (writeProgFiles)
                {
                    progFileLinesToWrite.Add(oopsstring);
                }
            }
            if (writeProgFiles)
            {
                string       concatFilename = @"F:\andreasAB\abClusteringNR\progFiles\concatProg.log";
                StreamWriter progFileW      = new StreamWriter(concatFilename, true);
                progFileW.WriteLine("for run {0}", _progFileName);
                foreach (object lineObj in progFileLinesToWrite)
                {
                    progFileW.WriteLine((string)lineObj);
                }
                progFileW.WriteLine("Finished at iteration {0}", lastExecutedIteration);
                progFileW.Close();
                Console.WriteLine("{0} written.", _progFileName);
            }

            foreach (int clCenter in centersForEachCluster)
            {
                _centerOfEachCluster.Add(clCenter);
            }

            _numberOfClusters = centersForEachCluster.Length;

            // get the algorithm ready for output

            // compute scatter
            //_centerOfEachCluster

            _LinesToWrite = linesToWrite;
            Console.WriteLine("about to return at {0}", DateTime.Now);

            // sort clusters by length: fix bestClusterData (int[]) and _centerOfEachCluster (ArrayList)

            //return bestClusterData;
            for (int pdbIndex = 0; pdbIndex < _loopObjsByPDB.Count; pdbIndex++)
            {
                _loopObjsByPDB[pdbIndex].myClusterID = bestClusterData[pdbIndex];
            }
            return;
        }
Exemple #30
0
 public void SetPeptideAnalysis(PeptideAnalysis peptideAnalysis)
 {
     PeptideSequence = peptideAnalysis.Peptide.Sequence;
     MinCharge = peptideAnalysis.MinCharge;
     MaxCharge = peptideAnalysis.MaxCharge;
     MassAccuracy = peptideAnalysis.GetMassAccuracy();
 }
Exemple #31
0
        protected void ShowChromatograms()
        {
            if (MsGraphControl.GraphPane == null)
            {
                // TODO: How can this happen?
                return;
            }
            MsGraphControl.GraphPane.GraphObjList.Clear();
            MsGraphControl.GraphPane.CurveList.Clear();
            var selectedCharges  = gridIntensities.GetSelectedCharges();
            var selectedMasses   = gridIntensities.GetSelectedMasses();
            var chromatograms    = PeptideFileAnalysis.ChromatogramSet;
            var mzRanges         = PeptideFileAnalysis.TurnoverCalculator.GetMzs(0);
            var monoisotopicMass = Workspace.GetAminoAcidFormulas().GetMonoisotopicMass(PeptideAnalysis.Peptide.Sequence);

            for (int charge = PeptideAnalysis.MinCharge; charge <= PeptideAnalysis.MaxCharge; charge++)
            {
                if (selectedCharges.Count > 0 && !selectedCharges.Contains(charge))
                {
                    continue;
                }
                for (int iMass = 0; iMass < PeptideAnalysis.GetMassCount(); iMass++)
                {
                    var    mzKey          = new MzKey(charge, iMass);
                    double massDifference = mzRanges[iMass].Center - monoisotopicMass;

                    var label = massDifference.ToString("0.#");
                    if (label[0] != '-')
                    {
                        label = "+" + label;
                    }
                    label  = "M" + label;
                    label += new string('+', charge);

                    if (selectedMasses.Count > 0)
                    {
                        if (!selectedMasses.Contains(iMass))
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (ExcludedMasses.IsExcluded(mzKey.MassIndex))
                        {
                            continue;
                        }
                    }
                    ChromatogramSetData.Chromatogram chromatogram;
                    if (!chromatograms.Chromatograms.TryGetValue(mzKey, out chromatogram))
                    {
                        continue;
                    }
                    var graphItem = new ChromatogramGraphItem
                    {
                        Title = label,
                    };
                    graphItem.Color = TracerChromatogramForm.GetColor(iMass, PeptideAnalysis.GetMassCount());
                    var mzRange      = PeptideFileAnalysis.TurnoverCalculator.GetMzs(mzKey.Charge)[mzKey.MassIndex];
                    var massAccuracy = PeptideAnalysis.GetMassAccuracy();
                    var intensities  = chromatogram.ChromatogramPoints.Select(point => point.GetIntensity(mzRange, massAccuracy)).ToArray();
                    if (Smooth)
                    {
                        intensities = TracerChromatograms.SavitzkyGolaySmooth(intensities);
                    }
                    PointPairList points = new PointPairList(chromatograms.Times, intensities);
                    graphItem.Points = points;
                    var lineItem = (LineItem)MsGraphControl.AddGraphItem(MsGraphControl.GraphPane, graphItem);
                    lineItem.Line.Style      = TracerChromatogramForm.GetDashStyle(charge - PeptideAnalysis.MinCharge);
                    lineItem.Line.Width      = Settings.Default.ChromatogramLineWidth;
                    lineItem.Label.IsVisible = false;
                }
            }
        }
 public Task(PeptideAnalysis peptideAnalysis, ICollection<MsDataFile> msDataFiles)
 {
     PeptideAnalysis = peptideAnalysis;
     MsDataFiles = msDataFiles;
 }
 public CreateFileAnalysesForm(PeptideAnalysis peptideAnalysis)
     : base(peptideAnalysis)
 {
     InitializeComponent();
     UpdateListbox();
 }
 public PeptideAnalysisRow(PeptideAnalysis peptideAnalysis)
 {
     PeptideAnalysis = peptideAnalysis;
 }
 void CalculateAnalysisResults(PeptideAnalysis peptideAnalysis)
 {
     bool changed = false;
     foreach (var fileAnalysis in peptideAnalysis.FileAnalyses.ListPeptideFileAnalyses(false))
     {
         if (fileAnalysis.PeptideDistributions.ChildCount != 0)
         {
             continue;
         }
         if (!fileAnalysis.EnsureCalculated())
         {
             _workspace.EnsureChromatograms(fileAnalysis);
             continue;
         }
         changed = true;
         Debug.Assert(fileAnalysis.HasChromatograms);
     }
     if (!changed)
     {
         peptideAnalysis.PeptideRates.EnsureChildrenLoaded();
     }
     if (changed || peptideAnalysis.PeptideRates.ChildCount == 0)
     {
         using (_workspace.OpenSession())
         {
             peptideAnalysis.PeptideRates.Clear();
             peptideAnalysis.PeptideRates.EnsureCalculated();
         }
     }
 }
 public ResultCalculatorTask(PeptideAnalysis peptideAnalysis, DbLock dbLock)
     : base(peptideAnalysis.Workspace, dbLock)
 {
     PeptideAnalysis = peptideAnalysis;
 }
Exemple #37
0
 public DbChangeLog(PeptideAnalysis peptideAnalysis)
 {
     Init(peptideAnalysis.Workspace);
     PeptideAnalysisId = peptideAnalysis.Id;
 }
Exemple #38
0
 protected override void OnHandleDestroyed(EventArgs e)
 {
     base.OnHandleDestroyed(e);
     PeptideAnalysis.DecChromatogramRefCount();
 }
Exemple #39
0
 public ResultCalculatorTask(PeptideAnalysis peptideAnalysis, DbLock dbLock) : base(peptideAnalysis.Workspace, dbLock)
 {
     PeptideAnalysis = peptideAnalysis;
 }
Exemple #40
0
        private void UpdateGraph()
        {
            zedGraphControl.GraphPane.CurveList.Clear();
            zedGraphControl.GraphPane.GraphObjList.Clear();
            zedGraphControl.GraphPane.Title.IsVisible = false;
            MsDataFile normalizeTo  = null;
            var        fileAnalyses = new List <PeptideFileAnalysis>();

            for (int iRow = 0; iRow < dataGridView.Rows.Count; iRow++)
            {
                fileAnalyses.Add((PeptideFileAnalysis)dataGridView.Rows[iRow].Tag);
            }
            if (fileAnalyses.Count == 0)
            {
                return;
            }
            if (_normalizeRetentionTimes)
            {
                normalizeTo = fileAnalyses[0].MsDataFile;
            }
            var tracerFormulas = PeptideAnalysis.GetTurnoverCalculator().ListTracerFormulas();
            var pointPairLists = tracerFormulas.Select(tf => new PointPairList()).ToArray();

            for (int iFileAnalysis = 0; iFileAnalysis < fileAnalyses.Count; iFileAnalysis++)
            {
                var fileAnalysis = fileAnalyses[iFileAnalysis];
                var peaks        = fileAnalysis.CalculatedPeaks;
                if (peaks == null)
                {
                    continue;
                }
                for (int iTracerFormula = 0; iTracerFormula < tracerFormulas.Count; iTracerFormula++)
                {
                    var pointPairList = pointPairLists[iTracerFormula];
                    var peak          = peaks.GetPeak(tracerFormulas[iTracerFormula]);
                    if (peak == null)
                    {
                        pointPairList.Add(new PointPair(iFileAnalysis + 1, PointPairBase.Missing, PointPairBase.Missing));
                    }
                    else
                    {
                        if (normalizeTo == null)
                        {
                            pointPairList.Add(new PointPair(iFileAnalysis + 1, peak.Value.EndTime, peak.Value.StartTime));
                        }
                        else
                        {
                            var alignment = fileAnalysis.MsDataFile.GetRetentionTimeAlignment(normalizeTo);
                            if (alignment.IsInvalid)
                            {
                                pointPairList.Add(new PointPair(iFileAnalysis + 1, PointPairBase.Missing, PointPairBase.Missing));
                            }
                            else
                            {
                                pointPairList.Add(new PointPair(iFileAnalysis + 1, alignment.GetTargetTime(peak.Value.EndTime), alignment.GetTargetTime(peak.Value.StartTime), fileAnalysis));
                            }
                        }
                    }
                }
            }
            zedGraphControl.GraphPane.XAxis.Type             = AxisType.Text;
            zedGraphControl.GraphPane.XAxis.Scale.TextLabels =
                fileAnalyses.Select(fileAnalysis => fileAnalysis.MsDataFile.ToString()).ToArray();
            zedGraphControl.GraphPane.XAxis.Title.Text = "Data File";
            zedGraphControl.GraphPane.YAxis.Title.Text = normalizeTo == null ? "Retention Time" : "Normalized Retention Time";

            for (int iTracerFormula = 0; iTracerFormula < tracerFormulas.Count; iTracerFormula++)
            {
                zedGraphControl.GraphPane.AddHiLowBar(tracerFormulas[iTracerFormula].ToDisplayString(),
                                                      pointPairLists[iTracerFormula],
                                                      TracerChromatogramForm.GetColor(iTracerFormula,
                                                                                      tracerFormulas.Count));
            }
            zedGraphControl.GraphPane.AxisChange();
            zedGraphControl.Invalidate();
        }