Exemple #1
0
        /// <summary>
        /// Creates an Xic for a feature based on individual charge states.
        /// </summary>
        /// <param name="rawPath">Path to the raw file.</param>
        /// <param name="peaksPath">Path to the peaks file.</param>
        /// <param name="feature">Feature to target</param>
        public Dictionary <int, Chromatogram> CreateXicForChargeStates(UMCLight feature, bool shouldSmooth)
        {
            Dictionary <int, Chromatogram>    chromatograms = new Dictionary <int, Chromatogram>();
            Dictionary <int, List <XYZData> > charges       = feature.CreateChargeSIC();

            XicFinder finder = new XicFinder();

            feature.ChargeStateChromatograms.Clear();

            //
            foreach (int charge in charges.Keys)
            {
                // This is the current XIC - but it's not that great
                List <XYZData> xicMz = charges[charge];

                // Finds the maximum point in the XIC, we'll use this as our target, it most likely contains
                // the exact point that we'll want to use to help identify the feature.
                var maxPoint = xicMz.Where(u => u.Y == xicMz.Max(x => x.Y)).Select(u => new { u.X, u.Y, u.Z }).FirstOrDefault();

                int    targetScan = Convert.ToInt32(maxPoint.X);
                double targetMz   = maxPoint.Z;

                // Find the Xic based on the target point, this may include other peaks
                List <XYData> totalXic = null;

                try
                {
                    totalXic = FindXic(targetMz, targetScan, shouldSmooth);

                    if (totalXic.Count > 1)
                    {
                        // Then find a specific Xic based on the target scan.
                        List <XYData> specificXic = finder.FindTarget(totalXic, targetScan);

                        // Add the targeted Xic to the charge state map so that we can create Xic's for each charge state.
                        Chromatogram gram = new Chromatogram(specificXic, maxPoint.Z, charge);
                        chromatograms.Add(charge, gram);
                    }
                }
                catch (PreconditionException)
                {
                    // This would mean that the charge state didnt have enough features in it.
                }
            }
            return(chromatograms);
        }
Exemple #2
0
        private void SqlInsert(string runID, Chromatogram chromatogram, Peak2DArray peaks)
        {
            SQLiteCommand cmd;

            if (!currentScope.TryGetCommand("INSERT_CHROMATOGRAM_CMD", out cmd))
            {
                cmd = currentScope.PrepareCommand("INSERT_CHROMATOGRAM_CMD", "INSERT INTO Chromatogram VALUES(@runID, @chromatogramID, @description, @peakArray, @peakData);");
            }

            cmd.Parameters.Clear();
            cmd.Parameters.AddWithValue("@runID", runID);
            cmd.Parameters.AddWithValue("@chromatogramID", chromatogram.ID);
            cmd.Parameters.AddWithValue("@description", MzLiteJson.ToJson(chromatogram));
            cmd.Parameters.AddWithValue("@peakArray", MzLiteJson.ToJson(peaks));
            cmd.Parameters.AddWithValue("@peakData", encoder.Encode(peaks));

            cmd.ExecuteNonQuery();
        }
Exemple #3
0
        /// <summary>
        /// Creates an Xic for a feature based on individual charge states.
        /// </summary>
        /// <param name="rawPath">Path to the raw file.</param>
        /// <param name="peaksPath">Path to the peaks file.</param>
        /// <param name="feature">Feature to target</param>
        public Dictionary <int, List <Chromatogram> > CreateXicForIsotopes(UMCLight feature, bool shouldSmooth)
        {
            Dictionary <int, List <Chromatogram> > chromatograms = new Dictionary <int, List <Chromatogram> >();
            Dictionary <int, List <XYZData> >      charges       = feature.CreateChargeSIC();
            XicFinder finder = new XicFinder();

            feature.IsotopeChromatograms.Clear();

            foreach (int charge in charges.Keys)
            {
                /// Creates a list of Xic's for a given chromatogram.
                List <Chromatogram> grams = new List <Chromatogram>();
                chromatograms.Add(charge, grams);

                // This is the current XIC - but it's not that great
                List <XYZData> xicMz = charges[charge];

                // Finds the maximum point in the XIC, we'll use this as our target, it most likely contains
                // the exact point that we'll want to use to help identify the feature.
                var    maxPoint   = xicMz.Where(u => u.Y == xicMz.Max(x => x.Y)).Select(u => new { u.X, u.Y, u.Z }).FirstOrDefault();
                int    targetScan = Convert.ToInt32(maxPoint.X);
                double targetMz   = maxPoint.Z;

                List <XYData> isotopicProfile = CreateIsotopicProfile(targetMz, targetScan, charge);

                foreach (XYData isotope in isotopicProfile)
                {
                    // Find the Xic based on the target point, this may include other peaks
                    List <XYData> totalXic = FindXic(targetMz, targetScan, shouldSmooth);

                    // Then find a specific Xic based on the target scan.
                    List <XYData> targetIsotopeXic = finder.FindTarget(totalXic, targetScan);

                    // Add the targeted Xic to the charge state map so that we can create Xic's for each charge state.
                    Chromatogram gram = new Chromatogram(targetIsotopeXic, maxPoint.Z, charge);
                    grams.Add(gram);
                }

                chromatograms[charge] = grams;
            }

            feature.IsotopeChromatograms = chromatograms;
            return(chromatograms);
        }
        public void AnotherChromatogramTest()
        {
            double[,] timeintensities = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 } };
            Chromatogram a = new Chromatogram(timeintensities);

            Assert.AreEqual(1, a.FirstTime);
            Assert.AreEqual(4, a.LastTime);
            Assert.AreEqual(3, a.GetTime(2));
            Assert.AreEqual(8, a.GetIntensity(3));
            Assert.AreEqual(6, a.GetApex(1.5, 2.5).Intensity);
            Assert.AreEqual(6, a.GetApex(1.5, 2.5).Intensity);
            Assert.AreEqual(4, a.GetApex(4, 5).X);

            Assert.AreEqual(6, a.CreateSmoothChromatogram(SmoothingType.None, -10).GetApex(1.5, 2.5).Intensity);

            Assert.AreEqual(8, a.FindNearestApex(10, 1).Y);

            Assert.AreEqual(4, a.GetApex(5, 6).X);
        }
Exemple #5
0
        IChromatogram GenerateChromatogram(string sampleName)
        {
            IChromatogram chromatogram = new Chromatogram();

            chromatogram.Name  = sampleName;
            chromatogram.Title = sampleName;
            List <DataPoint> points = new List <DataPoint>();

            for (int i = 0; i < 10; i++)
            {
                DataPoint point = new DataPoint();
                point.X = random.NextDouble();
                point.Y = random.NextDouble();

                points.Add(point);
            }

            chromatogram.Data = points;

            return(chromatogram);
        }
Exemple #6
0
        public ScaledRetentionTime FindPeakRetentionTime(double time)
        {
            // Search for a time that corresponds with a label
            int    closestLabelIndex     = -1;
            double closestLabelDeltaTime = Double.MaxValue;

            for (int i = 0; i < _arrayLabelIndexes.Length; i++)
            {
                int iLabel = _arrayLabelIndexes[i];
                if (iLabel == -1)
                {
                    continue;
                }
                double deltaTime = Math.Abs(time - _displayTimes[iLabel]);
                if (deltaTime < 0.15 && deltaTime < closestLabelDeltaTime)
                {
                    closestLabelIndex     = i;
                    closestLabelDeltaTime = deltaTime;
                }
            }
            if (closestLabelIndex == -1)
            {
                return(ScaledRetentionTime.ZERO);
            }

            var   peak  = Chromatogram.GetPeak(closestLabelIndex);
            float rt    = peak.RetentionTime;
            int   iTime = Array.BinarySearch(_measuredTimes, rt);

            if (iTime < 0)
            {
                iTime = ~iTime;
                if (iTime > _measuredTimes.Length - 1 ||
                    (iTime > 0 && Math.Abs(rt - _measuredTimes[iTime]) > Math.Abs(rt - _measuredTimes[iTime - 1])))
                {
                    iTime--;
                }
            }
            return(new ScaledRetentionTime(rt, _displayTimes[iTime]));
        }
Exemple #7
0
        /// <summary>
        /// Scores two chromatograms using their basis functions.
        /// </summary>
        /// <param name="profileA">chromatogram A</param>
        /// <param name="profileB">chromatogram B</param>
        /// <param name="basisFunction">Function used to interpolate</param>
        /// <param name="intensityProfile"></param>
        /// <returns>R-squared value for a given linear regression between intensity matrix</returns>
        public double ScoreChromatogramIntensity(Chromatogram profileA,
                                                 Chromatogram profileB,
                                                 BasisFunctionBase basisFunction,
                                                 ref List <XYData> intensityProfile)
        {
            if (intensityProfile == null)
            {
                throw new ArgumentNullException("intensityProfile");
            }

            var minScan = profileA.FitPoints.Min(x => x.X);
            var maxScan = profileA.FitPoints.Max(x => x.X);

            minScan = Math.Min(minScan, profileB.FitPoints.Min(x => x.X));
            maxScan = Math.Max(maxScan, profileB.FitPoints.Max(x => x.X));

            var deltaScan = Math.Abs(maxScan - minScan) / 100;
            var scan      = minScan;

            var pairs = new List <XYData>();

            while (scan <= maxScan)
            {
                var x = basisFunction.Evaluate(profileA.FitCoefficients, scan);
                var y = basisFunction.Evaluate(profileB.FitCoefficients, scan);

                pairs.Add(new XYData(x, y));
                scan += deltaScan;
            }

            var linearRegression = BasisFunctionFactory.BasisFunctionSelector(BasisFunctionsEnum.Linear);
            var solver           = new LevenburgMarquadtSolver {
                BasisFunction = linearRegression.FunctionDelegate
            };

            var coeffs = linearRegression.Coefficients;
            var report = solver.Solve(pairs, ref coeffs);

            return(report.RSquared);
        }
Exemple #8
0
        public void WriteXics(string path,
                              List <UMCLight> features)
        {
            using (TextWriter writer = File.CreateText(path))
            {
                foreach (UMCLight feature in features)
                {
                    foreach (int charge in feature.ChargeStateChromatograms.Keys)
                    {
                        writer.WriteLine("id\t{0}\tcharge\t{1}", feature.ID, charge);
                        writer.WriteLine("mz\ttime\tintensity");

                        Chromatogram gram = feature.ChargeStateChromatograms[charge];

                        foreach (XYData point in gram.Points)
                        {
                            writer.WriteLine("{0}\t{1}\t{2}", gram.Mz, point.X, point.Y);
                        }
                    }
                }
            }
        }
        public void ChromatogramTest()
        {
            Chromatogram a = new Chromatogram(new double[] { 1, 2, 3, 4, 5 }, new double[] { 1, 2, 6, 4, 2 }, false);
            var          b = a.CreateSmoothChromatogram(SmoothingType.BoxCar, 4);

            Assert.IsTrue(b.GetTimes().SequenceEqual(new double[] { 2, 3, 4 }));
            Assert.IsTrue(b.GetIntensities().SequenceEqual(new double[] { 3, 4, 4 }));

            Chromatogram d = new Chromatogram(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, new double[] { 10, 0, 2, 6, 2, 0, 1, 10, 1 }, false);

            // Finds the APEX! Not nearest peak!
            Assert.AreEqual(6, d.FindNearestApex(5.9, 1).Intensity);
            Assert.AreEqual(10, d.FindNearestApex(6.1, 1).Intensity);

            var elutionProfile = d.GetElutionProfile(new DoubleRange(3, 7));

            Assert.AreEqual(5, elutionProfile.Count);
            Assert.AreEqual(9.5, elutionProfile.TrapezoidalArea());

            Assert.AreEqual(2, elutionProfile.StartPeak.Intensity);
            Assert.AreEqual(3, elutionProfile.StartPeak.Time);
            Assert.AreEqual(7, elutionProfile.EndPeak.Time);

            var thePeak = new ChromatographicPeak(1, 10);

            Assert.AreEqual(1, thePeak.Time);
            Assert.AreEqual(10, thePeak.Intensity);
            Assert.AreEqual("(1, 10)", thePeak.ToString());

            var elutionProfileEmpty = d.GetElutionProfile(new DoubleRange(6.5, 6.5));

            Assert.AreEqual(0, elutionProfileEmpty.TrapezoidalArea());
            Assert.AreEqual(0, elutionProfileEmpty.SummedArea);

            Assert.AreEqual("Count = 9 TIC = 32", d.ToString());
            Assert.AreEqual(10, d.GetApex().Intensity);
            Assert.AreEqual(1, d.GetApex().Time);
        }
Exemple #10
0
        public override PointAnnotation AnnotatePoint(PointPair point)
        {
            var showRT    = GraphChromatogram.ShowRT;
            int timeIndex = Array.BinarySearch(_displayTimes, point.X);

            if (showRT == ShowRTChrom.all ||
                (showRT == ShowRTChrom.threshold && Settings.Default.ShowRetentionTimesThreshold <= point.Y))
            {
                int indexPeak;
                if (_annotatedTimes.TryGetValue(timeIndex, out indexPeak))
                {
                    double dotProduct = _dotProducts != null ? _dotProducts[indexPeak] : 0;
                    float? massError  = null;
                    if (Settings.Default.ShowMassError)
                    {
                        massError = Chromatogram.GetPeak(indexPeak).MassError;
                    }
                    string label = FormatTimeLabel(point.X, massError, dotProduct);
                    return(new PointAnnotation(label, FontSpec));
                }
            }

            return(null);
        }
 public MassRangeChromatogram(Chromatogram chromatogram, DoubleRange range)
     : base(chromatogram)
 {
     Range = range;
 }
Exemple #12
0
        private void showChromatogram( Chromatogram chromatogram, bool isOverlay )
        {
            ZedGraph.GraphPane pane = zedGraphControl1.GraphPane;

            if( isOverlay && pane.CurveList.Count > overlayColors.Length )
                MessageBox.Show( "SeeMS only supports up to " + overlayColors.Length + " simultaneous overlays.", "Too many overlays", MessageBoxButtons.OK, MessageBoxIcon.Stop );

            // set form title
            if( !isOverlay )
                Text = String.Format( "{0} - {1}", currentDataSource.Name, chromatogram.Id );
            else
                Text += "," + chromatogram.Id;

            if( !isOverlay )
                pane.CurveList.Clear();

            if( currentGraphItem != null && !currentGraphItem.IsChromatogram )
            {
                zedGraphControl1.RestoreScale( pane );
                zedGraphControl1.ZoomOutAll( pane );
            }
            bool isScaleAuto = !pane.IsZoomed;

            //pane.GraphObjList.Clear();

            PointList pointList = chromatogram.PointList;
            if( pointList.FullCount > 0 )
            {
                int bins = (int) pane.CalcChartRect( zedGraphControl1.CreateGraphics() ).Width;

                if( isScaleAuto )
                    pointList.SetScale( bins, pointList[0].X, pointList[pointList.Count - 1].X );
                else
                    pointList.SetScale( bins, pane.XAxis.Scale.Min, pane.XAxis.Scale.Max );
                pane.YAxis.Title.Text = "Total Intensity";
                pane.XAxis.Title.Text = "Retention Time (in minutes)";
                pane.AddCurve( chromatogram.Id, pointList, Color.Gray, ZedGraph.SymbolType.None );
            }
            pane.AxisChange();

            if( isOverlay )
            {
                pane.Legend.IsVisible = true;
                pane.Legend.Position = ZedGraph.LegendPos.TopCenter;
                for( int i = 0; i < pane.CurveList.Count; ++i )
                {
                    pane.CurveList[i].Color = overlayColors[i];
                    ( pane.CurveList[i] as ZedGraph.LineItem ).Line.Width = 2;
                }
            } else
            {
                pane.Legend.IsVisible = false;
                currentGraphItem = chromatogram;
            }

            SetDataLabelsVisible( true );
            zedGraphControl1.Refresh();
        }
 internal ChromatogramListCellDoubleClickEventArgs( ChromatogramListForm sender, DataGridViewCellMouseEventArgs e )
     : base(e.Button, e.Clicks, e.X, e.Y, e.Delta)
 {
     if( e.RowIndex > -1 && e.RowIndex < sender.GridView.RowCount )
         chromatogram = sender.GridView.Rows[e.RowIndex].Tag as Chromatogram;
 }
 public void Add( Chromatogram chromatogram )
 {
     pwiz.CLI.msdata.Chromatogram c = chromatogram.Element;
     int rowIndex = gridView.Rows.Add(
         c.id, c.nativeID, c.index,
         c.cvParamChild( CVID.MS_chromatogram_type ).name
     );
     gridView.Rows[rowIndex].Tag = chromatogram;
     chromatogram.Tag = gridView.Rows[rowIndex];
 }
        public void updateRow( ChromatogramDataSet.ChromatogramTableRow row, Chromatogram chromatogram )
        {
            chromatogramList[chromatogram.Index] = chromatogram;

            pwiz.CLI.msdata.Chromatogram c = chromatogram.Element;
            DataProcessing dp = chromatogram.DataProcessing;
            if( dp == null )
                dp = c.dataProcessing;

            row.Type = c.cvParamChild( CVID.MS_chromatogram_type ).name;
            row.DataPoints = c.defaultArrayLength;
            row.DpId = ( dp == null || dp.id.Length == 0 ? "unknown" : dp.id );
        }
        public new MassRangeChromatogram Smooth(SmoothingType smoothing, int points)
        {
            Chromatogram chrom = base.Smooth(smoothing, points);

            return(new MassRangeChromatogram(chrom, Range));
        }
Exemple #17
0
        private void initializeManagedDataSource( ManagedDataSource managedDataSource )
        {
            try
            {
                DataSource source = managedDataSource.Source;
                MSDataFile msDataFile = source.MSDataFile;
                ChromatogramListForm chromatogramListForm = managedDataSource.ChromatogramListForm;
                SpectrumListForm spectrumListForm = managedDataSource.SpectrumListForm;

                chromatogramListForm.Text = source.Name + " chromatograms";
                chromatogramListForm.TabText = source.Name + " chromatograms";
                chromatogramListForm.ShowIcon = false;
                chromatogramListForm.CellDoubleClick += new ChromatogramListCellDoubleClickHandler( chromatogramListForm_CellDoubleClick );

                spectrumListForm.Text = source.Name + " spectra";
                spectrumListForm.TabText = source.Name + " spectra";
                spectrumListForm.ShowIcon = false;
                spectrumListForm.CellDoubleClick += new SpectrumListCellDoubleClickHandler( spectrumListForm_CellDoubleClick );

                bool firstChromatogramLoaded = false;
                bool firstSpectrumLoaded = false;
                GraphForm firstGraph = null;

                ChromatogramList cl = msDataFile.run.chromatogramList;
                SpectrumList sl = msDataFile.run.spectrumList;

                if( sl == null )
                    throw new Exception( "Error loading metadata: no spectrum list" );

                int ticIndex = 0;
                if( cl != null )
                {
                    ticIndex = cl.findNative( "TIC" );
                    if( ticIndex < cl.size() )
                    {
                        pwiz.CLI.msdata.Chromatogram tic = cl.chromatogram( ticIndex );
                        Chromatogram ticChromatogram = new Chromatogram( source, tic );
                        chromatogramListForm.Add( ticChromatogram );
                        source.Chromatograms.Add( ticChromatogram );
                        firstGraph = OpenGraph( true );
                        showData( firstGraph, managedDataSource, ticChromatogram );
                        firstChromatogramLoaded = true;
                        chromatogramListForm.Show( mainForm.DockPanel, DockState.DockBottomAutoHide );
                        Application.DoEvents();
                    }
                }

                CVParam spectrumType = msDataFile.fileDescription.fileContent.cvParamChild( CVID.MS_spectrum_type );
                if( spectrumType.cvid == CVID.CVID_Unknown && !sl.empty() )
                    spectrumType = sl.spectrum( 0 ).cvParamChild( CVID.MS_spectrum_type );

                if( spectrumType.cvid == CVID.MS_SRM_spectrum )
                {
                    if( cl != null && cl.empty() )
                        throw new Exception( "Error loading metadata: SRM file contains no chromatograms" );

                } else //if( spectrumType.cvid == CVID.MS_MS1_spectrum ||
                       //    spectrumType.cvid == CVID.MS_MSn_spectrum )
                {
                    if( sl.empty() )
                        throw new Exception( "Error loading metadata: MSn file contains no spectra" );
                }// else
                //	throw new Exception( "Error loading metadata: unable to open files with spectrum type \"" + spectrumType.name + "\"" );

                if( cl != null )
                {
                    // load the rest of the chromatograms
                    for( int i = 0; i < cl.size(); ++i )
                    {
                        if( i == ticIndex )
                            continue;
                        pwiz.CLI.msdata.Chromatogram c = cl.chromatogram( i );

                        mainForm.SetStatusLabel( String.Format( "Loading chromatograms from source file ({0} of {1})...",
                                        ( i + 1 ), cl.size() ) );
                        mainForm.SetProgressPercentage( ( i + 1 ) * 100 / cl.size() );

                        Chromatogram chromatogram = new Chromatogram( source, c );
                        chromatogramListForm.Add( chromatogram );
                        source.Chromatograms.Add( chromatogram );
                        if( !firstChromatogramLoaded )
                        {
                            firstChromatogramLoaded = true;
                            chromatogramListForm.Show( mainForm.DockPanel, DockState.DockBottomAutoHide );
                            firstGraph = OpenGraph( true );
                            showData( firstGraph, managedDataSource, chromatogram );
                        }
                        Application.DoEvents();
                    }
                }

                // get all scans by sequential access
                for( int i = 0; i < sl.size(); ++i )
                {
                    pwiz.CLI.msdata.Spectrum s = sl.spectrum( i );

                    if( ( ( i + 1 ) % 100 ) == 0 || ( i + 1 ) == sl.size() )
                    {
                        mainForm.SetStatusLabel( String.Format( "Loading spectra from source file ({0} of {1})...",
                                        ( i + 1 ), sl.size() ) );
                        mainForm.SetProgressPercentage( ( i + 1 ) * 100 / sl.size() );
                    }

                    MassSpectrum spectrum = new MassSpectrum( source, s );
                    spectrumListForm.Add( spectrum );
                    source.Spectra.Add( spectrum );
                    if( !firstSpectrumLoaded )
                    {
                        firstSpectrumLoaded = true;
                        spectrumListForm.Show( mainForm.DockPanel, DockState.DockBottomAutoHide );
                        if( firstChromatogramLoaded )
                        {
                            GraphForm spectrumGraph = CreateGraph();
                            spectrumGraph.Show( firstGraph.Pane, DockPaneAlignment.Bottom, 0.5 );
                            showData( spectrumGraph, managedDataSource, spectrum );
                        } else
                        {
                            firstGraph = OpenGraph( true );
                            showData( firstGraph, managedDataSource, spectrum );
                        }
                    }
                    Application.DoEvents();
                }

                mainForm.SetStatusLabel( "Finished loading source metadata." );
                mainForm.SetProgressPercentage( 100 );

            } catch( Exception ex )
            {
                string message = "SeeMS encountered an error reading metadata from \"" + managedDataSource.Source.CurrentFilepath + "\" (" + ex.Message + ")";
                if( ex.InnerException != null )
                    message += "\n\nAdditional information: " + ex.InnerException.Message;
                MessageBox.Show( message,
                                "Error reading source metadata",
                                MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1,
                                0, false );
                mainForm.SetStatusLabel( "Failed to read source metadata." );
            }
        }
Exemple #18
0
        public override void AddPreCurveAnnotations(MSGraphPane graphPane, Graphics g,
                                                    MSPointList pointList, GraphObjList annotations)
        {
            if (Chromatogram == null)
            {
                return;
            }

            // Give priority to showing the best peak text object above all other annotations
            if (DragInfo != null || (!HideBest && TransitionChromInfo != null) || CurveAnnotation != null)
            {
                // Show text and arrow for the best peak
                double intensityBest = 0;
                if (_bestPeakTimeIndex != -1)
                {
                    ScaledRetentionTime timeBest = new ScaledRetentionTime(_measuredTimes[_bestPeakTimeIndex], _displayTimes[_bestPeakTimeIndex]);
                    float xBest = graphPane.XAxis.Scale.Transform(timeBest.DisplayTime);
                    intensityBest = _intensities[_bestPeakTimeIndex];
                    float yBest = graphPane.YAxis.Scale.Transform(intensityBest);

                    if (GraphChromatogram.ShowRT != ShowRTChrom.none || DragInfo != null)
                    {
                        // Best peak gets its own label to avoid curve overlap detection
                        double intensityLabel = graphPane.YAxis.Scale.ReverseTransform(yBest - 5);
                        float? massError      = Settings.Default.ShowMassError && TransitionChromInfo != null
                                               ? TransitionChromInfo.MassError
                                               : null;
                        double dotProduct = _dotProducts != null ? _bestProduct : 0;

                        TextObj text;
                        if (CurveAnnotation != null)
                        {
                            // Darken peptide name a little so light colors stand out against the white background.
                            var color = FontSpec.FontColor;
                            if (!GraphInfo.IsSelected)
                            {
                                color = Color.FromArgb(color.R * 7 / 10, color.G * 7 / 10, color.B * 7 / 10);
                            }
                            var fontSpec = new FontSpec(FontSpec)
                            {
                                FontColor = color, Angle = 90
                            };
                            if (GraphInfo.IsSelected)
                            {
                                fontSpec = new FontSpec(fontSpec)
                                {
                                    IsBold = true, Size = fontSpec.Size + 2, IsAntiAlias = true
                                }
                            }
                            ;

                            // Display peptide name label using vertical text.
                            text = new TextObj(CurveAnnotation, timeBest.DisplayTime, intensityLabel,
                                               CoordType.AxisXYScale, AlignH.Left, AlignV.Center)
                            {
                                ZOrder = ZOrder.A_InFront,
                                IsClippedToChartRect = true,
                                FontSpec             = fontSpec,
                                Tag = new GraphObjTag(this, GraphObjType.best_peak, timeBest),
                            };
                        }
                        else
                        {
                            string label = FormatTimeLabel(timeBest.DisplayTime, massError, dotProduct);

                            text = new TextObj(label, timeBest.DisplayTime, intensityLabel,
                                               CoordType.AxisXYScale, AlignH.Center, AlignV.Bottom)
                            {
                                ZOrder = ZOrder.A_InFront,
                                IsClippedToChartRect = true,
                                FontSpec             = FontSpec,
                                Tag = new GraphObjTag(this, GraphObjType.best_peak, timeBest),
                            };
                        }

                        annotations.Add(text);
                    }

                    // If showing multiple peptides, skip the best peak arrow indicator.
                    if (CurveAnnotation == null)
                    {
                        // Show the best peak arrow indicator
                        double timeArrow      = graphPane.XAxis.Scale.ReverseTransform(xBest - 4);
                        double intensityArrow = graphPane.YAxis.Scale.ReverseTransform(yBest - 2);

                        ArrowObj arrow = new ArrowObj(COLOR_BEST_PEAK, 12f,
                                                      timeArrow, intensityArrow, timeArrow, intensityArrow)
                        {
                            Location             = { CoordinateFrame = CoordType.AxisXYScale },
                            IsArrowHead          = true,
                            IsClippedToChartRect = true,
                            ZOrder = ZOrder.A_InFront
                        };
                        annotations.Add(arrow);
                    }
                }

                // Show the best peak boundary lines
                if (CurveAnnotation == null)
                {
                    double startTime = 0, endTime = 0;
                    if (DragInfo != null)
                    {
                        startTime = DragInfo.StartTime.MeasuredTime;
                        endTime   = DragInfo.EndTime.MeasuredTime;
                    }
                    else if (TransitionChromInfo != null)
                    {
                        var tranPeakInfo = TransitionChromInfo;
                        startTime = tranPeakInfo.StartRetentionTime;
                        endTime   = tranPeakInfo.EndRetentionTime;
                    }
                    AddPeakBoundaries(graphPane, annotations, true,
                                      ScaleRetentionTime(startTime), ScaleRetentionTime(endTime), intensityBest);
                }
                if (Chromatogram.BestPeakIndex >= 0)
                {
                    // Only shade peak when user modified. Otherwise, shading can be added when an entire
                    // precursor was force integrated because of another precursor (e.g. heavy) since that
                    // leads to an empty peak, which will not match the best peak.
                    if (Settings.Default.ShowOriginalPeak && TransitionChromInfo != null && TransitionChromInfo.IsUserModified)
                    {
                        var bestPeak = Chromatogram.GetPeak(Chromatogram.BestPeakIndex);
                        if (bestPeak.StartTime != TransitionChromInfo.StartRetentionTime ||
                            bestPeak.EndTime != TransitionChromInfo.EndRetentionTime)
                        {
                            AddOriginalPeakAnnotation(bestPeak, annotations, graphPane);
                        }
                    }
                }
            }
            if (_displayRawTimes.HasValue)
            {
                AddPeakRawTimes(graphPane, annotations,
                                ScaleRetentionTime(_displayRawTimes.Value.StartBound),
                                ScaleRetentionTime(_displayRawTimes.Value.EndBound),
                                Chromatogram);
            }
        }
Exemple #19
0
        /// <summary>
        /// Creates an Xic for a feature based on individual charge states.
        /// </summary>
        /// <param name="rawPath">Path to the raw file.</param>
        /// <param name="peaksPath">Path to the peaks file.</param>        
        /// <param name="feature">Feature to target</param>
        public Dictionary<int, Chromatogram> CreateXicForChargeStates(UMCLight feature, bool shouldSmooth)
        {
            Dictionary<int, Chromatogram> chromatograms = new Dictionary<int, Chromatogram>();
            Dictionary<int, List<XYZData>> charges      =  feature.CreateChargeSIC();

            XicFinder finder   = new XicFinder();
            feature.ChargeStateChromatograms.Clear();

            //
            foreach (int charge in charges.Keys)
            {
                // This is the current XIC - but it's not that great
                List<XYZData> xicMz             = charges[charge];

                // Finds the maximum point in the XIC, we'll use this as our target, it most likely contains
                // the exact point that we'll want to use to help identify the feature.
                var maxPoint                    = xicMz.Where( u => u.Y == xicMz.Max(x=>x.Y)).Select(u=> new { u.X, u.Y, u.Z}).FirstOrDefault();

                int     targetScan  = Convert.ToInt32(maxPoint.X);
                double  targetMz    = maxPoint.Z;

                // Find the Xic based on the target point, this may include other peaks
                List<PNNLOmics.Data.XYData> totalXic = null;

                try
                {
                    totalXic = FindXic(targetMz, targetScan, shouldSmooth);

                    if (totalXic.Count > 1)
                    {
                        // Then find a specific Xic based on the target scan.
                        List<PNNLOmics.Data.XYData> specificXic = finder.FindTarget(totalXic, targetScan);

                        // Add the targeted Xic to the charge state map so that we can create Xic's for each charge state.
                        Chromatogram gram = new Chromatogram(specificXic, maxPoint.Z, charge);
                        chromatograms.Add(charge, gram);
                    }
                }
                catch (PreconditionException)
                {
                    // This would mean that the charge state didnt have enough features in it.
                }
            }
            return chromatograms;
        }
Exemple #20
0
        /// <summary>
        /// Creates an Xic for a feature based on individual charge states.
        /// </summary>
        /// <param name="rawPath">Path to the raw file.</param>
        /// <param name="peaksPath">Path to the peaks file.</param>        
        /// <param name="feature">Feature to target</param>
        public Dictionary<int, List<Chromatogram>> CreateXicForIsotopes(UMCLight feature, bool shouldSmooth)
        {
            Dictionary<int, List<Chromatogram>> chromatograms = new Dictionary<int, List<Chromatogram>>();
            Dictionary<int, List<XYZData>> charges      = feature.CreateChargeSIC();
            XicFinder finder                            = new XicFinder();
            feature.IsotopeChromatograms.Clear();

            foreach (int charge in charges.Keys)
            {
                /// Creates a list of Xic's for a given chromatogram.
                List<Chromatogram> grams    = new List<Chromatogram>();
                chromatograms.Add(charge, grams);

                // This is the current XIC - but it's not that great
                List<XYZData> xicMz         = charges[charge];

                // Finds the maximum point in the XIC, we'll use this as our target, it most likely contains
                // the exact point that we'll want to use to help identify the feature.
                var maxPoint    = xicMz.Where(u => u.Y == xicMz.Max(x => x.Y)).Select(u => new { u.X, u.Y, u.Z }).FirstOrDefault();
                int targetScan  = Convert.ToInt32(maxPoint.X);
                double targetMz = maxPoint.Z;

                List<PNNLOmics.Data.XYData>  isotopicProfile = CreateIsotopicProfile(targetMz, targetScan, charge);

                foreach (PNNLOmics.Data.XYData isotope in isotopicProfile)
                {
                    // Find the Xic based on the target point, this may include other peaks
                    List<PNNLOmics.Data.XYData> totalXic = FindXic(targetMz, targetScan, shouldSmooth);

                    // Then find a specific Xic based on the target scan.
                    List<PNNLOmics.Data.XYData> targetIsotopeXic = finder.FindTarget(totalXic, targetScan);

                    // Add the targeted Xic to the charge state map so that we can create Xic's for each charge state.
                    Chromatogram gram = new Chromatogram(targetIsotopeXic, maxPoint.Z, charge);
                    grams.Add(gram);
                }

                chromatograms[charge] = grams;
            }

            feature.IsotopeChromatograms = chromatograms;
            return chromatograms;
        }
Exemple #21
0
        public void WriteXics(string path,
                              List <UMCLight> features)
        {
            using (TextWriter writer = File.CreateText(path))
            {
                foreach (UMCLight feature in features)
                {
                    Dictionary <int, List <XYZData> > chargeMap = feature.CreateChargeSIC();

                    foreach (int charge in feature.ChargeStateChromatograms.Keys)
                    {
                        Chromatogram  gram      = feature.ChargeStateChromatograms[charge];
                        List <XYData> oldPoints = chargeMap[charge].ToXYData();
                        List <XYData> newPoints = gram.Points;

                        writer.WriteLine("id\t{0}\tcharge\t{1}", feature.ID, charge);
                        writer.WriteLine("mz\tscan\tretention-time\tintensity\told-intensity");

                        // Find the minimum and maximum scans
                        int minScan = Convert.ToInt32(oldPoints.Min(x => x.X));
                        int maxScan = Convert.ToInt32(oldPoints.Max(x => x.X));
                        minScan = Math.Min(Convert.ToInt32(newPoints.Min(x => x.X)), minScan);
                        maxScan = Math.Max(Convert.ToInt32(newPoints.Max(x => x.X)), maxScan);

                        // Map out the points to their respective scan numbers
                        Dictionary <int, long> oldMap = new Dictionary <int, long>();
                        Dictionary <int, long> newMap = new Dictionary <int, long>();

                        foreach (XYData x in oldPoints)
                        {
                            int scan = Convert.ToInt32(x.X);
                            if (oldMap.ContainsKey(scan))
                            {
                                oldMap[scan] = Math.Max(Convert.ToInt64(x.Y), oldMap[scan]);
                                continue;
                            }

                            oldMap.Add(scan, Convert.ToInt64(x.Y));
                        }
                        foreach (XYData x in newPoints)
                        {
                            int scan = Convert.ToInt32(x.X);
                            if (newMap.ContainsKey(scan))
                            {
                                continue;
                            }

                            newMap.Add(scan, Convert.ToInt64(x.Y));
                        }

                        for (int i = minScan; i <= maxScan; i++)
                        {
                            string oldData = "";
                            string newData = "";

                            bool found = false;

                            if (oldMap.ContainsKey(i))
                            {
                                oldData = oldMap[i].ToString();
                                found   = true;
                            }

                            if (newMap.ContainsKey(i))
                            {
                                newData = newMap[i].ToString();
                                found   = true;
                            }

                            if (found)
                            {
                                writer.WriteLine("{0}\t{1}\t{2}\t{3}", gram.Mz, i, newData, oldData);
                            }
                        }
                    }
                }
            }
        }
Exemple #22
0
 public Task InsertAsync(string runID, Chromatogram chromatogram, Peak2DArray peaks)
 {
     return(Task.Run(() => { Insert(runID, chromatogram, peaks); }));
 }
Exemple #23
0
        public override void AddAnnotations(MSGraphPane graphPane, Graphics g,
                                            MSPointList pointList, GraphObjList annotations)
        {
            if (Chromatogram == null)
            {
                return;
            }


            // Calculate maximum y for potential retention time indicators
            PointF ptTop = new PointF(0, graphPane.Chart.Rect.Top);

            if (GraphChromatogram.ShowRT != ShowRTChrom.none)
            {
                if (RetentionMsMs != null)
                {
                    foreach (double retentionTime in RetentionMsMs)
                    {
                        Color color = COLOR_MSMSID_TIME;
                        if (SelectedRetentionMsMs.HasValue && Equals((float)retentionTime, (float)SelectedRetentionMsMs))
                        {
                            color = ColorSelected;
                        }
                        AddRetentionTimeAnnotation(graphPane, g, annotations, ptTop,
                                                   Resources.ChromGraphItem_AddAnnotations_ID, GraphObjType.ms_ms_id, color,
                                                   ScaleRetentionTime(retentionTime));
                    }
                }
                if (MidasRetentionMsMs != null)
                {
                    foreach (var retentionTime in MidasRetentionMsMs)
                    {
                        var color = SelectedRetentionMsMs.HasValue && Equals((float)retentionTime, (float)SelectedRetentionMsMs)
                            ? ColorSelected
                            : COLOR_MSMSID_TIME;
                        AddRetentionTimeAnnotation(graphPane, g, annotations, ptTop, string.Empty, GraphObjType.midas_spectrum, color, ScaleRetentionTime(retentionTime));
                    }
                }
                if (AlignedRetentionMsMs != null)
                {
                    foreach (var time in AlignedRetentionMsMs)
                    {
                        var scaledTime = ScaleRetentionTime(time);
                        var line       = new LineObj(COLOR_ALIGNED_MSMSID_TIME, scaledTime.DisplayTime, 0,
                                                     scaledTime.DisplayTime, 1)
                        {
                            ZOrder               = ZOrder.F_BehindGrid,
                            Location             = { CoordinateFrame = CoordType.XScaleYChartFraction },
                            IsClippedToChartRect = true,
                            Tag = new GraphObjTag(this, GraphObjType.aligned_ms_id, scaledTime),
                        };
                        annotations.Add(line);
                    }
                }
                if (UnalignedRetentionMsMs != null)
                {
                    foreach (var time in UnalignedRetentionMsMs)
                    {
                        var scaledTime = ScaleRetentionTime(time);
                        var line       = new LineObj(COLOR_UNALIGNED_MSMSID_TIME, scaledTime.DisplayTime, 0,
                                                     scaledTime.DisplayTime, 1)
                        {
                            ZOrder               = ZOrder.F_BehindGrid,
                            Location             = { CoordinateFrame = CoordType.XScaleYChartFraction },
                            IsClippedToChartRect = true,
                            Tag = new GraphObjTag(this, GraphObjType.unaligned_ms_id, scaledTime),
                        };
                        annotations.Add(line);
                    }
                }
            }

            // Draw retention time indicator, if set
            if (RetentionPrediction.HasValue)
            {
                double time = RetentionPrediction.Value;

                // Create temporary label to calculate positions
                if (GraphChromatogram.ShowRT != ShowRTChrom.none)
                {
                    AddRetentionTimeAnnotation(graphPane,
                                               g,
                                               annotations,
                                               ptTop,
                                               Resources.ChromGraphItem_AddAnnotations_Predicted,
                                               GraphObjType.predicted_rt_window,
                                               COLOR_RETENTION_TIME,
                                               ScaleRetentionTime(time));
                }

                // Draw background for retention time window
                if (RetentionWindow > 0)
                {
                    double x1  = ScaleRetentionTime(time - RetentionWindow / 2).DisplayTime;
                    double x2  = ScaleRetentionTime(time + RetentionWindow / 2).DisplayTime;
                    BoxObj box = new BoxObj(x1, 0, x2 - x1, 1,
                                            COLOR_RETENTION_WINDOW, COLOR_RETENTION_WINDOW)
                    {
                        Location             = { CoordinateFrame = CoordType.XScaleYChartFraction },
                        IsClippedToChartRect = true,
                        ZOrder = ZOrder.F_BehindGrid
                    };
                    annotations.Add(box);
                }
            }

            if (RetentionExplicit != null && GraphChromatogram.ShowRT != ShowRTChrom.none)
            {
                // Create temporary label to calculate positions
                AddRetentionTimeAnnotation(graphPane,
                                           g,
                                           annotations,
                                           ptTop,
                                           Resources.ChromGraphItem_AddAnnotations_Explicit,
                                           GraphObjType.predicted_rt_window,
                                           COLOR_RETENTION_TIME,
                                           ScaleRetentionTime(RetentionExplicit.RetentionTime));
            }

            for (int i = 0, len = Chromatogram.NumPeaks; i < len; i++)
            {
                if (_arrayLabelIndexes[i] == -1)
                {
                    continue;
                }

                double maxIntensity = _intensities[_arrayLabelIndexes[i]];

                // Show peak extent indicators, if they are far enough apart
                ChromPeak peak = Chromatogram.GetPeak(i);
                AddPeakBoundaries(graphPane, annotations, false,
                                  ScaleRetentionTime(peak.StartTime), ScaleRetentionTime(peak.EndTime), maxIntensity);
            }
        }
Exemple #24
0
 /// <summary>
 /// Finds the min scan for a profile.
 /// </summary>
 /// <param name="profile"></param>
 /// <returns></returns>
 public static int MinScan(this Chromatogram profile)
 {
     return(0);
 }
        public void Add( Chromatogram chromatogram )
        {
            ChromatogramDataSet.ChromatogramTableRow row = chromatogramDataSet.ChromatogramTable.NewChromatogramTableRow();
            row.Id = chromatogram.Id;

            /*if( nativeIdFormat != CVID.CVID_Unknown )
            {
                gridView.Columns["Id"].Visible = false;

                string[] nameValuePairs = chromatogram.Id.Split( " ".ToCharArray() );
                foreach( string nvp in nameValuePairs )
                {
                    string[] nameValuePair = nvp.Split( "=".ToCharArray() );
                    row[nameValuePair[0]] = nameValuePair[1];
                }
            }*/

            row.Index = chromatogram.Index;
            updateRow( row, chromatogram );
            chromatogramDataSet.ChromatogramTable.AddChromatogramTableRow( row );

            //int rowIndex = gridView.Rows.Add();
            //gridView.Rows[rowIndex].Tag = chromatogram;
            chromatogram.Tag = this;

            //UpdateRow( rowIndex );
        }
 public int IndexOf( Chromatogram chromatogram )
 {
     return chromatogramBindingSource.Find( "Index", chromatogram.Index );
 }
        public void TestGetApex()
        {
            Chromatogram d = new Chromatogram(new double[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, new double[] { 10, 0, 2, 6, 2, 0, 1, 10, 1 }, false);

            Assert.AreEqual(6, d.GetApex(new DoubleRange(2, 6)).Y);
        }
		internal ChromatogramListCellDoubleClickEventArgs( ChromatogramListForm sender, DataGridViewCellMouseEventArgs e )
			: base( e.ColumnIndex, e.RowIndex, e.X, e.Y, e )
		{
            if( e.RowIndex > -1 && e.RowIndex < sender.GridView.RowCount )
                chromatogram = sender.GetChromatogram( e.RowIndex );
		}
Exemple #29
0
 public Chromatogram GetChromatogram( Chromatogram metaChromatogram, ChromatogramList chromatogramList )
 {
     Chromatogram chromatogram = new Chromatogram( metaChromatogram, chromatogramList.chromatogram( metaChromatogram.Index, true ) );
     return chromatogram;
 }
 public MassRangeChromatogram(Chromatogram chromatogram, DoubleRange range)
     : base(chromatogram)
 {
     Range = range;
 }