Пример #1
0
        public MsSpectraViewModel(MSSpectra spectrum)
        {
            Peptides = new ObservableCollection<PeptideViewModel>();
            spectrum.Peptides.ForEach(x => Peptides.Add(new PeptideViewModel(x)));

            var info = SingletonDataProviders.GetDatasetInformation(spectrum.GroupId);
            if (info != null)
            {
                Dataset = new DatasetInformationViewModel(info);
            }

            Spectrum = spectrum;
            SelectedSpectrumPlotModel = new MsMsSpectraViewModel(spectrum, "");

            if (spectrum.ParentFeature != null)
            {
                var msFeature = spectrum.ParentFeature;
                var umc = msFeature.ParentFeature;
                if (umc != null)
                {
                    var newList = new List<UMCLight> {umc};

                    var xic = new XicViewModel(newList, "xic")
                    {
                        Model =
                        {
                            IsLegendVisible = false,
                            TitleFontSize = 0
                        }
                    };

                    SelectedSpectrumXic = xic;
                }
            }
        }
Пример #2
0
        public void PlotSpectra(MSSpectra spectrum)
        {
            Model.Series.Clear();

            var colorIterator = new ColorTypeIterator();
            var charge        = 0;

            if (spectrum.ParentFeature != null)
            {
                charge = spectrum.ParentFeature.ChargeState;
            }
            var series = new StemSeries
            {
                Title = string.Format("{0} m/z charge {1}",
                                      spectrum.PrecursorMz,
                                      charge),
                Color = colorIterator.GetColor(charge)
            };

            foreach (var peak in spectrum.Peaks)
            {
                series.Points.Add(new DataPoint(peak.X, peak.Y));
            }
            Model.Series.Add(series);
        }
Пример #3
0
        /// <summary>
        /// Computes the dot product of two spectra.
        /// </summary>
        /// <param name="spectraX">Spectrum X</param>
        /// <param name="spectraY">Spectrum Y</param>
        /// <returns>Normalized Dot Product</returns>
        public double CompareSpectra(MSSpectra xSpectrum, MSSpectra ySpectrum)
        {
            var a = xSpectrum.Peaks;
            var b = ySpectrum.Peaks;

            // Then compute the magnitudes of the spectra
            double sum = 0;
            var    xc  = 0;
            var    yc  = 0;


            for (var i = 0; i < xSpectrum.Peaks.Count; i++)
            {
                var x = a[i].Y;
                var y = b[i].Y;

                if (x > 0)
                {
                    xc++;
                }

                if (y > 0)
                {
                    yc++;
                }

                if (x > 0 && y > 0)
                {
                    sum++;
                }
            }
            return(Convert.ToDouble(sum) / Convert.ToDouble(xc + yc));
        }
Пример #4
0
        private void DisplayComparisonPlot(MSSpectra spectrumX, MSSpectra spectrumY, double mzTolerance,
                                           string path = "comparison.png", string newTitle = "MS/MS Spectra")
        {
            var model = CreatePlot(spectrumX.Peaks, spectrumY.Peaks, mzTolerance);

            model.Title = newTitle;

            var plot = new PlotView();

            plot.Model = model;
            var form = new Form();

            form.Size = Screen.PrimaryScreen.WorkingArea.Size;
            plot.Dock = DockStyle.Fill;
            form.Controls.Add(plot);
            form.Show();

            IO.Utilities.SleepNow(3);

            using (var bitmap = new Bitmap(form.Width, form.Height))
            {
                form.DrawToBitmap(bitmap, form.DisplayRectangle);
                bitmap.Save(path);
            }
        }
Пример #5
0
        public MsMsSpectraViewModel(MSSpectra spectrum, string name) :
            base(name)
        {
            var mzAxis = new LinearAxis
            {
                Position        = AxisPosition.Bottom,
                IsZoomEnabled   = true,
                Minimum         = 0,
                MaximumPadding  = .01,
                AbsoluteMinimum = 0
            };

            var intensityAxis = new LinearAxis
            {
                IsPanEnabled              = false,
                Position                  = AxisPosition.Left,
                IsZoomEnabled             = true,
                Minimum                   = 0,
                AbsoluteMinimum           = 0,
                MaximumPadding            = .01,
                UseSuperExponentialFormat = true
            };

            Model.Axes.Add(mzAxis);
            Model.Axes.Add(intensityAxis);

            m_mzAxis        = mzAxis;
            m_intensityAxis = intensityAxis;

            m_spectrum = spectrum;
            PlotSpectra(spectrum);
        }
Пример #6
0
        public int CompareSpectra(Peptide p, MSSpectra s)
        {
            var matchingPeaks = 0;

            foreach (var point in p.Spectrum.Peaks)
            {
                var px = point.X;
                for (var i = 0; i < s.Peaks.Count - 1; i++)
                {
                    var iPoint = s.Peaks[i];
                    var jPoint = s.Peaks[i + 1];

                    if (px < jPoint.X && px >= iPoint.X)
                    {
                        if (iPoint.Y > 0)
                        {
                            matchingPeaks++;
                            break;
                        }
                    }
                }
            }

            return(matchingPeaks);
        }
Пример #7
0
        public double CompareSpectra(MSSpectra spectraX, MSSpectra spectraY)
        {
            var xIntensities = this.ExpandVector(spectraY.Peaks, spectraX.Peaks).Select(xpeak => xpeak.X).ToArray();
            var yIntensities = this.ExpandVector(spectraX.Peaks, spectraY.Peaks).Select(ypeak => ypeak.Y).ToArray();

            return(FitScoreCalculator.GetPearsonCorrelation(xIntensities, yIntensities, yIntensities.Length));
        }
Пример #8
0
        /// <summary>
        /// Creates a MGF file based on the spectra provided.
        /// </summary>
        /// <param name="path"></param>
        public List <MSSpectra> Read(string path)
        {
            var lines = File.ReadAllLines(path);
            var mode  = 0;

            var       spectra         = new List <MSSpectra>();
            MSSpectra currentSpectrum = null;
            var       delimiter       = new[] { " " };

            for (var i = 0; i < lines.Length; i++)
            {
                var line = lines[i].ToUpper();
                if (line.Contains("BEGIN IONS"))
                {
                    mode = 0;
                }
                else if (line.Contains("CHARGE="))
                {
                    mode            = 1;
                    i               = i + 1;
                    currentSpectrum = new MSSpectra();
                }
                else if (line.Contains("END IONS"))
                {
                    mode = 0;
                    if (currentSpectrum != null)
                    {
                        spectra.Add(currentSpectrum);
                    }
                }


                if (mode == 1)
                {
                    var data = line.Split(delimiter,
                                          StringSplitOptions.RemoveEmptyEntries);

                    if (data.Length < 2)
                    {
                        continue;
                    }

                    try
                    {
                        var x     = Convert.ToDouble(data[0]);
                        var y     = Convert.ToDouble(data[1]);
                        var datum = new XYData(x, y);
                        currentSpectrum.Peaks.Add(datum);
                    }
                    catch
                    {
                    }
                }
            }

            return(spectra);
        }
Пример #9
0
 /// <summary>
 ///     Loads the MS/MS spectrum from file.
 /// </summary>
 /// <param name="spectrum"></param>
 public static List<XYData> LoadSpectrum(MSSpectra spectrum)
 {
     var peaks = new List<XYData>();
     var info = SingletonDataProviders.GetDatasetInformation(spectrum.GroupId);
     if (info != null && info.Raw != null && info.RawPath != null)
     {
         peaks = ParentSpectraFinder.GetDaughterSpectrum(info.RawPath, spectrum.Scan);
     }
     return peaks;
 }
Пример #10
0
        private MSSpectra GetSpectrum(ISpectraProvider reader, int scan, int group, double mzTolerance = .5)
        {
            var summary  = new ScanSummary();
            var peaks    = reader.GetRawSpectra(scan, 2, out summary);
            var spectrum = new MSSpectra();

            spectrum.Peaks = peaks;

            return(spectrum);
        }
Пример #11
0
        private List <MSSpectra> GetSpectra(string path)
        {
            var spectrum = new MSSpectra();

            spectrum.Peptides = new List <Peptide>();
            IMsMsSpectraReader reader = new MgfFileReader();
            var spectra = reader.Read(path);

            return(spectra);
        }
Пример #12
0
        /// <summary>
        ///     Loads the MS/MS spectrum from file.
        /// </summary>
        /// <param name="spectrum"></param>
        public static List <XYData> LoadSpectrum(MSSpectra spectrum)
        {
            var peaks = new List <XYData>();
            var info  = SingletonDataProviders.GetDatasetInformation(spectrum.GroupId);

            if (info != null && info.RawFile != null && info.RawFile.Path != null)
            {
                peaks = ParentSpectraFinder.GetDaughterSpectrum(info.RawFile.Path, spectrum.Scan);
            }
            return(peaks);
        }
Пример #13
0
        /// <summary>
        /// Converts a spectra into a binary one.
        /// </summary>
        /// <param name="spectrum"></param>
        /// <returns></returns>
        public MSSpectra Normalize(MSSpectra spectrum)
        {
            var filteredSpectrum = new MSSpectra();

            foreach (var peak in spectrum.Peaks)
            {
                var data = new XYData(peak.X, 1);
                filteredSpectrum.Peaks.Add(data);
            }

            return(filteredSpectrum);
        }
Пример #14
0
        public static UMCLight GetParentUmc(this MSSpectra spectrum)
        {
            if (spectrum == null)
            {
                return(null);
            }

            if (spectrum.ParentFeature != null)
            {
                return(spectrum.ParentFeature.GetParentUmc());
            }
            return(null);
        }
Пример #15
0
        public MsMsTreeViewModel(MSSpectra feature, TreeItemViewModel parent)
        {
            m_feature = feature;
            m_parent  = parent;


            var information = SingletonDataProviders.GetDatasetInformation(m_feature.GroupId);


            AddStatistic("Id", m_feature.Id);
            AddStatistic("Dataset Id", m_feature.GroupId);
            AddStatistic("Precursor m/z", m_feature.PrecursorMz);
            if (feature.ParentFeature != null)
            {
                AddStatistic("Charge", m_feature.ParentFeature.ChargeState);
            }
            else
            {
                AddStatistic("Charge", m_feature.PrecursorChargeState);
            }
            AddStatistic("Scan", m_feature.Scan);


            Peptides = new ObservableCollection <Peptide>();

            Peptide maxPeptide = null;

            foreach (var p in m_feature.Peptides)
            {
                Peptides.Add(p);
                if (maxPeptide == null)
                {
                    maxPeptide = p;
                }
                else if (p.Score < maxPeptide.Score)
                {
                    maxPeptide = p;
                }
            }

            if (maxPeptide != null)
            {
                Name = maxPeptide.Sequence;
                AddStatistic("Score", maxPeptide.Score);
                AddStatistic("Scan", maxPeptide.Scan);
            }
            else
            {
                Name = string.Format("Unknown - Scan: {0} m/z: {1:.00} ", m_feature.Scan, m_feature.PrecursorMz);
            }
        }
Пример #16
0
        public MsMsTreeViewModel(MSSpectra feature, TreeItemViewModel parent)
        {
            m_feature = feature;
            m_parent = parent;

            var information = SingletonDataProviders.GetDatasetInformation(m_feature.GroupId);

            AddStatistic("Id", m_feature.Id);
            AddStatistic("Dataset Id", m_feature.GroupId);
            AddStatistic("Precursor m/z", m_feature.PrecursorMz);
            if (feature.ParentFeature != null)
            {
                AddStatistic("Charge", m_feature.ParentFeature.ChargeState);
            }
            else
            {
                AddStatistic("Charge", m_feature.PrecursorChargeState);
            }
            AddStatistic("Scan", m_feature.Scan);

            Peptides = new ObservableCollection<Peptide>();

            Peptide maxPeptide = null;
            foreach (var p in m_feature.Peptides)
            {
                Peptides.Add(p);
                if (maxPeptide == null)
                {
                    maxPeptide = p;
                }
                else if (p.Score < maxPeptide.Score)
                {
                    maxPeptide = p;
                }
            }

            if (maxPeptide != null)
            {
                Name = maxPeptide.Sequence;
                AddStatistic("Score", maxPeptide.Score);
                AddStatistic("Scan", maxPeptide.Scan);
            }
            else
            {
                Name = string.Format("Unknown - Scan: {0} m/z: {1:.00} ", m_feature.Scan, m_feature.PrecursorMz);
            }
        }
Пример #17
0
        private MSSpectra ReadSpectrum(string path)
        {
            var spectrum = new MSSpectra();
            var lines    = File.ReadAllLines(path);

            spectrum.Peaks = new List <XYData>();
            foreach (var line in lines)
            {
                var data = line.Split('\t');
                if (data.Length > 1)
                {
                    spectrum.Peaks.Add(new XYData(Convert.ToDouble(data[0]),
                                                  Convert.ToDouble(data[1])));
                }
            }
            spectrum.Peaks = XYData.Bin(spectrum.Peaks, 0, 2000, .15);
            return(spectrum);
        }
Пример #18
0
        private void DisplayComparisonPlot(MSSpectra spectrumX, MSSpectra spectrumY, double mzTolerance,
                                           string newTitle = "MS/MS Spectra")
        {
            var model = CreatePlot(spectrumX.Peaks, spectrumY.Peaks, mzTolerance);

            model.Title = newTitle;

            var plot = new PlotView {
                Model = model, Dock = DockStyle.Fill
            };
            var form = new Form {
                Size = Screen.PrimaryScreen.WorkingArea.Size
            };

            form.Controls.Add(plot);
            form.Show();

            MultiAlignTestSuite.IO.Utilities.SleepNow(3);
        }
Пример #19
0
        /// <summary>
        /// Reads a list of MSMS Spectra header data from the Raw file
        /// </summary>
        /// <param name="groupId">File group ID</param>
        /// <param name="excludeMap">Dictionary indicating which scans and related feature ID's to ignore.</param>
        /// <param name="loadPeaks">True to also load the mass/intensity pairs for each spectrum</param>
        /// <returns>List of MSMS spectra data</returns>
        public List <MSSpectra> GetMSMSSpectra(Dictionary <int, int> excludeMap, bool loadPeaks)
        {
            var spectra = new List <MSSpectra>();

            var numberOfScans = this._lcmsRun.NumSpectra;

            for (var i = 1; i <= numberOfScans; i++)
            {
                var isInExcludeMap = excludeMap.ContainsKey(i);
                if (isInExcludeMap)
                {
                    // This scan is not to be used.
                    continue;
                }

                var summary = this.GetScanSummary(i);

                if (summary.MsLevel > 1)
                {
                    var spectrum = new MSSpectra
                    {
                        MsLevel         = summary.MsLevel,
                        RetentionTime   = summary.Time,
                        Scan            = summary.Scan,
                        PrecursorMz     = summary.PrecursorMz,
                        TotalIonCurrent = summary.TotalIonCurrent,
                        CollisionType   = summary.CollisionType
                    };

                    // Need to make this a standard type of collision based off of the data.
                    if (loadPeaks)
                    {
                        spectrum.Peaks = this.LoadSpectra(i);
                    }
                    spectra.Add(spectrum);
                }
            }

            return(spectra);
        }
Пример #20
0
        public MSSpectra GetSpectrum(int scan, int scanLevel, out ScanSummary summary, bool loadPeaks)
        {
            summary = this.GetScanSummary(scan);

            var spectrum = new MSSpectra
            {
                MsLevel         = summary.MsLevel,
                RetentionTime   = summary.Time,
                Scan            = scan,
                PrecursorMz     = summary.PrecursorMz,
                TotalIonCurrent = summary.TotalIonCurrent,
                CollisionType   = summary.CollisionType
            };

            // Need to make this a standard type of collision based off of the data.
            if (loadPeaks)
            {
                spectrum.Peaks = this.LoadSpectra(scan);
            }

            return(spectrum);
        }
Пример #21
0
        public MsSpectraViewModel(MSSpectra spectrum)
        {
            Peptides = new ObservableCollection <PeptideViewModel>();
            spectrum.Peptides.ForEach(x => Peptides.Add(new PeptideViewModel(x)));

            var info = SingletonDataProviders.GetDatasetInformation(spectrum.GroupId);

            if (info != null)
            {
                Dataset = new DatasetInformationViewModel(info);
            }

            Spectrum = spectrum;
            SelectedSpectrumPlotModel = new MsMsSpectraViewModel(spectrum, "");

            if (spectrum.ParentFeature != null)
            {
                var msFeature = spectrum.ParentFeature;
                var umc       = msFeature.GetParentFeature();
                if (umc != null)
                {
                    var newList = new List <UMCLight> {
                        umc
                    };

                    var xic = new XicViewModel(newList, "xic")
                    {
                        Model =
                        {
                            IsLegendVisible = false,
                            TitleFontSize   = 0
                        }
                    };

                    SelectedSpectrumXic = xic;
                }
            }
        }
Пример #22
0
        public double CompareSpectra(MSSpectra spectraX, MSSpectra spectraY)
        {
            var a = spectraX.Peaks;
            var b = spectraY.Peaks;


            // Then compute the magnitudes of the spectra
            double sum    = 0;
            double sumOne = 0;
            double sumTwo = 0;

            for (var i = 0; i < spectraX.Peaks.Count; i++)
            {
                var x = a[i].Y;
                var y = b[i].Y;

                sum    += x * y;
                sumOne += (x * x);
                sumTwo += (y * y);
            }


            return(sum / (sumOne * sumTwo));
        }
Пример #23
0
        public IEnumerable <UMCLight> CreateXic(IList <UMCLight> features,
                                                double massError,
                                                ISpectraProvider provider)
        {
            // this algorithm works as follows
            //
            //  PART A - Build the XIC target list
            //  For each UMC Light , find the XIC representation
            //      for each charge in a feature
            //          from start scan to end scan
            //              1. Compute a lower / upper m/z bound
            //              2. build an XIC chomatogram object
            //              3. reference the original UMC Feature -- this allows us to easily add
            //                  chromatograms to the corresponding feature
            //              4. store the chomatogram (with unique ID across all features)
            //
            //  PART B - Read Data From File
            //  Sort the list of XIC's by scan
            //  for each scan s = start scan to end scan
            //      1. find all xic's that start before and end after s -
            //          a. cache these xics in a dictionary based on unique id
            //          b. NOTE: this is why we sort so we can do an O(N) search for
            //             all XIC's that need data from this scan s
            //      2.  Then for each XIC that needs data
            //          a. Pull intensity data from lower / upper m/z bound
            //          b. create an MS Feature
            //          c. store in original UMC Feature
            //          d. Test to see if the XIC is done building (Intensity < 1 or s > scan end)
            //      3. Remove features that are done building from cache
            //
            //  CONCLUSIONS
            //  Building UMC's then takes linear time  (well O(N Lg N) time if you consider sort)
            //      and theoretically is only bounded by the time it takes to read an entire raw file
            //
            if (features.Count <= 0)
            {
                throw new Exception("No features were available to create XIC's from");
            }

            var minScan = Math.Max(1, features.Min(x => x.Scan - ScanWindowSize));
            var maxScan = features.Max(x => x.Scan + ScanWindowSize);

            OnProgress("Sorting features for optimized scan partitioning");
            // PART A
            // Map the feature ID to the xic based features
            var xicFeatures = new SortedSet <XicFeature>();
            var allFeatures = CreateXicTargets(features, massError);

            // PART B
            // sort the features...
            var featureCount = allFeatures.Count;

            allFeatures = allFeatures.OrderBy(x => x.StartScan).ToList();

            // This map tracks all possible features to keep

            var msFeatureId = 0;

            // This list stores a temporary amount of parent MS features
            // so that we can link MS/MS spectra to MS Features
            var parentMsList = new List <MSFeatureLight>();

            // Creates a comparison function for building a BST from a spectrum.
            var msmsFeatureId = 0;

            var totalScans = provider.GetTotalScans(0);

            OnProgress(string.Format("Analyzing {0} scans", totalScans));


            // Iterate over all the scans...
            for (var currentScan = minScan; currentScan < maxScan && currentScan <= totalScans; currentScan++)
            {
                // Find any features that need data from this scan
                var featureIndex = 0;
                while (featureIndex < featureCount)
                {
                    var xicFeature = allFeatures[featureIndex];
                    // This means that no new features were eluting with this scan....
                    if (xicFeature.StartScan > currentScan)
                    {
                        break;
                    }

                    // This means that there is a new feature...
                    if (currentScan <= xicFeature.EndScan)
                    {
                        if (!xicFeatures.Contains(xicFeature))
                        {
                            xicFeatures.Add(xicFeature);
                        }
                    }
                    featureIndex++;
                }

                // Skip pulling the data from the file if there is nothing to pull from.
                if (xicFeatures.Count < 1)
                {
                    continue;
                }

                // Here We link the MSMS Spectra to the UMC Features
                ScanSummary summary;
                var         spectrum = provider.GetRawSpectra(currentScan, 0, 1, out summary);


                if (summary.MsLevel > 1)
                {
                    // If it is an MS 2 spectra... then let's link it to the parent MS
                    // Feature
                    var matching = parentMsList.Where(
                        x => Math.Abs(x.Mz - summary.PrecursorMz) <= FragmentationSizeWindow
                        );

                    foreach (var match in matching)
                    {
                        // We create multiple spectra because this guy is matched to multiple ms
                        // features
                        var spectraData = new MSSpectra
                        {
                            Id              = msmsFeatureId,
                            ScanMetaData    = summary,
                            CollisionType   = summary.CollisionType,
                            Scan            = currentScan,
                            MsLevel         = summary.MsLevel,
                            PrecursorMz     = summary.PrecursorMz,
                            TotalIonCurrent = summary.TotalIonCurrent
                        };

                        match.MSnSpectra.Add(spectraData);
                        spectraData.ParentFeature = match;
                    }

                    if (spectrum != null)
                    {
                        spectrum.Clear();
                    }
                    msmsFeatureId++;

                    continue;
                }


                var mzList        = new double[spectrum.Count];
                var intensityList = new double[spectrum.Count];
                XYData.XYDataListToArrays(spectrum, mzList, intensityList);
                Array.Sort(mzList, intensityList);

                // Tracks which spectra need to be removed from the cache
                var toRemove = new List <XicFeature>();

                // Tracks which features we need to link to MSMS spectra with
                parentMsList.Clear();

                // now we iterate through all features that need data from this scan

                foreach (var xic in xicFeatures)
                {
                    var lower  = xic.LowMz;
                    var higher = xic.HighMz;

                    var startIndex = Array.BinarySearch(mzList, lower);
                    // A bitwise complement of the index, so use the bitwise complement
                    if (startIndex < 0)
                    {
                        startIndex = ~startIndex;
                    }

                    double summedIntensity = 0;

                    if (startIndex < mzList.Count() && mzList[startIndex] < lower)
                    {
                        // All data in the list is lighter than lower; nothing to sum
                    }
                    else
                    {
                        while (startIndex < mzList.Count() && mzList[startIndex] <= higher)
                        {
                            summedIntensity += intensityList[startIndex];
                            startIndex++;
                        }
                    }

                    // See if we need to remove this feature
                    // We only do so if the intensity has dropped off and we are past the end of the feature.
                    if (summedIntensity < 1 && currentScan > xic.EndScan)
                    {
                        toRemove.Add(xic);
                        continue;
                    }

                    var umc = xic.Feature;

                    // otherwise create a new feature here...
                    var msFeature = new MSFeatureLight
                    {
                        ChargeState      = xic.ChargeState,
                        Mz               = xic.Mz,
                        MassMonoisotopic = umc.MassMonoisotopic,
                        Scan             = currentScan,
                        Abundance        = Convert.ToInt64(summedIntensity),
                        Id               = msFeatureId++,
                        DriftTime        = umc.DriftTime,
                        Net              = currentScan,
                        GroupId          = umc.GroupId
                    };
                    parentMsList.Add(msFeature);
                    xic.Feature.AddChildFeature(msFeature);
                }

                // Remove features that end their elution prior to the current scan
                toRemove.ForEach(x => xicFeatures.Remove(x));
            }

            OnProgress("Filtering bad features with no data.");
            features = features.Where(x => x.MsFeatures.Count > 0).ToList();

            OnProgress("Refining XIC features.");
            return(RefineFeatureXics(features));
        }
Пример #24
0
        /// <summary>
        /// Compares two spectra finding similar peaks in two masses.
        /// </summary>
        /// <param name="spectraX"></param>
        /// <param name="spectraY"></param>
        /// <returns></returns>
        public double CompareSpectra(MSSpectra xSpectrum, MSSpectra ySpectrum)
        {
            var x = xSpectrum.Peaks;
            var y = ySpectrum.Peaks;

            var i   = 0;
            var j   = 0;
            var eps = .0000001;
            var Nx  = x.Count;
            var Ny  = y.Count;

            var distanceMap = new Dictionary <int, int>();

            while (i < Nx)
            {
                var    massX   = x[i].X;
                double massMax = 0;
                double massMin = 0;

                if (i + 1 >= Nx)
                {
                    massMax = MassTolerance;
                }
                else
                {
                    massMax = x[i + 1].X - massX - eps;
                }

                if (i == 0)
                {
                    massMin = MassTolerance;
                }
                else
                {
                    massMin = massX - x[i - 1].X - eps;
                }

                var mzTol     = Math.Min(Math.Min(MassTolerance, massMax), massMin);
                var bestDelta = mzTol;
                var bestMatch = -1;

                while (j < Ny)
                {
                    var massY     = y[j].X;
                    var deltaMass = massX - massY;
                    var absDelta  = Math.Abs(deltaMass);

                    if (absDelta >= bestDelta && deltaMass < 0)
                    {
                        break;
                    }
                    bestMatch = j;
                    j         = j + 1;
                }

                if (bestMatch >= 0)
                {
                    distanceMap.Add(i, j);
                }
                i = i + 1;
            }

            // Score
            var nx      = x.Count;
            var ny      = y.Count;
            var matches = distanceMap.Keys.Count;

            return(Convert.ToDouble(matches) / Convert.ToDouble(Math.Max(nx, ny)));
        }
Пример #25
0
        private void DisplayComparisonPlot(MSSpectra spectrumX, MSSpectra spectrumY, double mzTolerance,
            string newTitle = "MS/MS Spectra")
        {
            var model = CreatePlot(spectrumX.Peaks, spectrumY.Peaks, mzTolerance);
            model.Title = newTitle;

            var plot = new PlotView {Model = model, Dock = DockStyle.Fill};
            var form = new Form {Size = Screen.PrimaryScreen.WorkingArea.Size};
            form.Controls.Add(plot);
            form.Show();

            MultiAlignTestSuite.IO.Utilities.SleepNow(3);
        }
Пример #26
0
        public IEnumerable <UMCLight> CreateXicNew(List <UMCLight> features,
                                                   double massError,
                                                   InformedProteomicsReader provider,
                                                   bool refine = true,
                                                   IProgress <ProgressData> progress = null)
        {
            var progressData = new ProgressData(progress);
            int id = 0, count = 0;
            int msmsFeatureId  = 0;
            var resultFeatures = new List <UMCLight> {
                Capacity = features.Count
            };
            var ipr = provider.LcMsRun;

            ipr.HigherPrecursorChromatogramCacheSize = 2000;

            features.Sort((x, y) => x.Mz.CompareTo(y.Mz));

            // Iterate over XIC targets.
            foreach (var xicTarget in CreateXicTargetsYield(features, massError))
            {
                count++;
                // Read XIC
                var target = xicTarget.StartScan + ((xicTarget.EndScan - xicTarget.StartScan) / 2);
                var xic    = ipr.GetPrecursorExtractedIonChromatogram(xicTarget.LowMz, xicTarget.HighMz, target);

                if (refine)
                {
                    var xicRefiner = this.XicRefiner ?? new XicRefiner();
                    xic = xicRefiner.RefineXic(xic);
                }

                if (xic.Count < 3)
                {
                    continue;
                }

                var minEt  = ipr.GetElutionTime(ipr.MinLcScan);
                var maxEt  = ipr.GetElutionTime(ipr.MaxLcScan);
                var diffEt = maxEt - minEt;

                // Add xic points as MSFeatures.
                xicTarget.Feature.MsFeatures.Clear();
                foreach (var point in xic)
                {
                    xicTarget.Feature.AddChildFeature(new MSFeatureLight
                    {
                        ChargeState      = xicTarget.ChargeState,
                        Mz               = xicTarget.Mz,
                        MassMonoisotopic = xicTarget.Feature.MassMonoisotopic,
                        Scan             = point.ScanNum,
                        Abundance        = Convert.ToInt64(point.Intensity),
                        Id               = id++,
                        DriftTime        = xicTarget.Feature.DriftTime,
                        Net              = (ipr.GetElutionTime(point.ScanNum) - minEt) / diffEt,
                        GroupId          = xicTarget.Feature.GroupId
                    });
                }

                // Associate MS/MS information.
                var ms2Scans = ipr.GetFragmentationSpectraScanNums(xicTarget.Feature.Mz).ToArray();
                int j        = 0;
                for (int i = 0; i < xicTarget.Feature.MsFeatures.Count; i++)
                {
                    for (; j < ms2Scans.Length; j++)
                    {
                        // Scan below UMC feature scan range.
                        if (ms2Scans[j] < xicTarget.Feature.MsFeatures[i].Scan)
                        {
                            break;
                        }

                        // Haven't reached the last ms2 scan and ms2 scan is larger than next feature, could be associated with next feature
                        if (i < xicTarget.Feature.MsFeatures.Count - 1 && ms2Scans[j] > xicTarget.Feature.MsFeatures[i + 1].Scan)
                        {
                            break;
                        }

                        // We're on the last MSFeature - is the MS/MS scan actually for this feature?
                        if (i == xicTarget.Feature.MsFeatures.Count - 1 &&
                            ipr.GetPrevScanNum(ms2Scans[j], 1) != xicTarget.Feature.MsFeatures[i].Scan)
                        {
                            continue;
                        }

                        // Otherwise this is a MS/MS we want to add!
                        var spectraData = new MSSpectra
                        {
                            Id           = msmsFeatureId++,
                            ScanMetaData = new ScanSummary
                            {
                                MsLevel     = 2,
                                Scan        = ms2Scans[j],
                                PrecursorMz = xicTarget.Feature.MsFeatures[i].Mz,
                            },
                            CollisionType = CollisionType.None,
                            Scan          = ms2Scans[j],
                            PrecursorMz   = xicTarget.Feature.MsFeatures[i].Mz
                        };
                        xicTarget.Feature.MsFeatures[i].MSnSpectra.Add(spectraData);
                    }
                }

                resultFeatures.Add(xicTarget.Feature);
                if (count % 100 == 0 || count == features.Count - 1)
                {
                    progressData.Report(count, features.Count);
                }
            }

            return(resultFeatures);
        }
 private void cluster_SpectrumSelected(object sender, IdentificationFeatureSelectedEventArgs e)
 {
     SelectedSpectrum = e.Spectrum;
 }
Пример #28
0
        private MSSpectra GetSpectrum(ISpectraProvider reader, int scan, int group, double mzTolerance = .5)
        {
            var summary = new ScanSummary();
            var peaks = reader.GetRawSpectra(scan, group, 2, out summary);
            var spectrum = new MSSpectra();
            spectrum.Peaks = peaks;

            return spectrum;
        }
Пример #29
0
        private MSSpectra ReadSpectrum(string path)
        {
            var spectrum = new MSSpectra();
            var lines = File.ReadAllLines(path);

            spectrum.Peaks = new List<XYData>();
            foreach (var line in lines)
            {
                var data = line.Split('\t');
                if (data.Length > 1)
                {
                    spectrum.Peaks.Add(new XYData(Convert.ToDouble(data[0]),
                        Convert.ToDouble(data[1])));
                }
            }
            spectrum.Peaks = XYData.Bin(spectrum.Peaks, 0, 2000, .15);
            return spectrum;
        }
Пример #30
0
        /// <summary>
        /// Reads a list of MSMS Spectra header data from the Raw file
        /// </summary>
        /// <param name="groupId">File group ID</param>
        /// <param name="excludeMap">Dictionary indicating which scans and related feature ID's to ignore.</param>
        /// <param name="loadPeaks">True to also load the mass/intensity pairs for each spectrum</param>
        /// <returns>List of MSMS spectra data</returns>
        public List<MSSpectra> GetMSMSSpectra(int groupId, Dictionary<int, int> excludeMap, bool loadPeaks)
        {
            // Get the RawFileReader for this group
            var rawReader = GetReaderForGroup(groupId);

            var spectra = new List<MSSpectra>();

            var numberOfScans = rawReader.GetNumScans();
            for (var i = 0; i < numberOfScans; i++)
            {
                var isInExcludeMap = excludeMap.ContainsKey(i);
                if (isInExcludeMap)
                {
                    // This scan is not to be used.
                    continue;
                }

                FinniganFileReaderBaseClass.udtScanHeaderInfoType header;
                var summary = GetScanSummary(i, rawReader, out header);

                if (header.MSLevel > 1)
                {
                    var spectrum = new MSSpectra
                    {
                        MsLevel = header.MSLevel,
                        RetentionTime = header.RetentionTime,
                        Scan = i,
                        PrecursorMz = header.ParentIonMZ,
                        TotalIonCurrent = header.TotalIonCurrent,
                        CollisionType = summary.CollisionType
                    };

                    // Need to make this a standard type of collision based off of the data.
                    if (loadPeaks)
                    {
                        spectrum.Peaks = LoadRawSpectra(rawReader, i);
                    }
                    spectra.Add(spectrum);
                }
            }

            return spectra;
        }
Пример #31
0
        /// <summary>
        ///     Reads a list of MSMS Spectra header data from the mzXML file.
        /// </summary>
        /// <param name="file">file to read.</param>
        /// <returns>List of MSMS spectra data</returns>
        public List<MSSpectra> ReadMSMSSpectra(string file)
        {
            var spectra = new List<MSSpectra>();
            var reader = new clsMzXMLFileReader {SkipBinaryData = true};
            var opened = reader.OpenFile(file);

            if (!opened)
            {
                throw new IOException("Could not open the mzXML file " + file);
            }

            var totalScans = reader.ScanCount;

            for (var i = 0; i < totalScans; i++)
            {
                var info = new clsSpectrumInfo();
                reader.GetSpectrumByScanNumber(i, ref info);
                if (info.MSLevel > 1)
                {
                    var spectrum = new MSSpectra
                    {
                        MsLevel         = info.MSLevel,
                        RetentionTime   = info.RetentionTimeMin,
                        Scan            = i,
                        PrecursorMz     = info.ParentIonMZ,
                        TotalIonCurrent = info.TotalIonCurrent,
                        CollisionType   = CollisionType.Other
                    };

                    // Need to make this a standard type of collision based off of the data.
                    spectra.Add(spectrum);
                }
            }
            reader.CloseFile();
            return spectra;
        }
Пример #32
0
 public MsMsTreeViewModel(MSSpectra feature)
     : this(feature, null)
 {
 }
Пример #33
0
        private void DisplayComparisonPlot(MSSpectra spectrumX, MSSpectra spectrumY, double mzTolerance,
            string path = "comparison.png", string newTitle = "MS/MS Spectra")
        {
            var model = CreatePlot(spectrumX.Peaks, spectrumY.Peaks, mzTolerance);
            model.Title = newTitle;

            var plot = new PlotView();
            plot.Model = model;
            var form = new Form();
            form.Size = Screen.PrimaryScreen.WorkingArea.Size;
            plot.Dock = DockStyle.Fill;
            form.Controls.Add(plot);
            form.Show();

            IO.Utilities.SleepNow(3);

            using (var bitmap = new Bitmap(form.Width, form.Height))
            {
                form.DrawToBitmap(bitmap, form.DisplayRectangle);
                bitmap.Save(path);
            }
        }
Пример #34
0
 public IdentificationFeatureSelectedEventArgs(MSSpectra spectrum, Peptide id, UMCLight feature)
 {
     Feature  = feature;
     Spectrum = spectrum;
     Peptide  = id;
 }
Пример #35
0
        /// <summary>
        /// Computes the dot product of two spectra.
        /// </summary>
        /// <param name="spectraX">Spectrum X</param>
        /// <param name="spectraY">Spectrum Y</param>
        /// <returns>Normalized Dot Product</returns>
        public double CompareSpectra(MSSpectra xSpectrum, MSSpectra ySpectrum)
        {
            var x = xSpectrum.Peaks;
            var y = ySpectrum.Peaks;
            var N = x.Count;

            // Compute magnitudes of x y spectra
            var xIons         = new List <double>(N);
            var yIons         = new List <double>(N);
            var xTotalNonZero = 0;
            var yTotalNonZero = 0;

            for (var i = 0; i < x.Count; i++)
            {
                if (x[i].Y > 0)
                {
                    xTotalNonZero++;
                }
                if (y[i].Y > 0)
                {
                    yTotalNonZero++;
                }

                xIons.Add(x[i].Y);
                yIons.Add(y[i].Y);
            }
            // Find the top ions to keep.
            var xTopIons = new List <double>(N);
            var yTopIons = new List <double>(N);

            xTopIons.AddRange(xIons);
            yTopIons.AddRange(yIons);

            xTopIons.Sort();
            yTopIons.Sort();

            var xTop = Math.Max(0, xTopIons.Count - System.Convert.ToInt32(System.Convert.ToDouble(xTotalNonZero) * TopPercent));
            var yTop = Math.Max(0, yTopIons.Count - System.Convert.ToInt32(System.Convert.ToDouble(yTotalNonZero) * TopPercent));

            xTop = Math.Min(xTopIons.Count - 1, xTop);
            yTop = Math.Min(yTopIons.Count - 1, yTop);

            var xThreshold = xTopIons[xTop];
            var yThreshold = yTopIons[yTop];

            // Normalize each component and calculate the dot product.
            double sum = 0;

            for (var i = 0; i < x.Count; i++)
            {
                var xIon = xIons[i];
                var yIon = yIons[i];

                if (xIon < xThreshold)
                {
                    xIon = 0;
                }

                if (yIon <= yThreshold)
                {
                    yIon = 0;
                }

                sum += (xIon * yIon);
            }

            return(sum);
        }
Пример #36
0
 public IdentificationFeatureSelectedEventArgs(MSSpectra spectrum, Peptide id, UMCLight feature)
 {
     Feature = feature;
     Spectrum = spectrum;
     Peptide = id;
 }
Пример #37
0
        public int CompareSpectra(Peptide p, MSSpectra s)
        {
            var matchingPeaks = 0;

            foreach (var point in p.Spectrum.Peaks)
            {
                var px = point.X;
                for (var i = 0; i < s.Peaks.Count - 1; i++)
                {
                    var iPoint = s.Peaks[i];
                    var jPoint = s.Peaks[i + 1];

                    if (px < jPoint.X && px >= iPoint.X)
                    {
                        if (iPoint.Y > 0)
                        {
                            matchingPeaks++;
                            break;
                        }
                    }
                }
            }

            return matchingPeaks;
        }
Пример #38
0
        /// <summary>
        /// Reads a list of MSMS Spectra header data from the Raw file
        /// </summary>
        /// <param name="groupId">File group ID</param>
        /// <param name="excludeMap">Dictionary indicating which scans and related feature ID's to ignore.</param>
        /// <param name="loadPeaks">True to also load the mass/intensity pairs for each spectrum</param>
        /// <returns>List of MSMS spectra data</returns>
        public List<MSSpectra> GetMSMSSpectra(int groupId, Dictionary<int, int> excludeMap, bool loadPeaks)
        {
            // Get the RawFileReader for this group
            var ipbReader = GetReaderForGroup(groupId);

            var spectra = new List<MSSpectra>();

            var numberOfScans = ipbReader.NumSpectra;
            for (var i = 1; i <= numberOfScans; i++)
            {
                var isInExcludeMap = excludeMap.ContainsKey(i);
                if (isInExcludeMap)
                {
                    // This scan is not to be used.
                    continue;
                }

                var summary = GetScanSummary(i, ipbReader);

                if (summary.MsLevel > 1)
                {
                    var spectrum = new MSSpectra
                    {
                        MsLevel = summary.MsLevel,
                        RetentionTime = summary.Time,
                        Scan = summary.Scan,
                        PrecursorMz = summary.PrecursorMz,
                        TotalIonCurrent = summary.TotalIonCurrent,
                        CollisionType = summary.CollisionType
                    };

                    // Need to make this a standard type of collision based off of the data.
                    if (loadPeaks)
                    {
                        spectrum.Peaks = LoadSpectra(ipbReader, i);
                    }
                    spectra.Add(spectrum);
                }
            }

            return spectra;
        }
Пример #39
0
        public List<MSSpectra> GetMSMSSpectra(int group, Dictionary<int, int> excludeMap, bool loadPeaks)
        {
            var spectra = new List<MSSpectra>();

            if (!m_dataFiles.ContainsKey(group))
            {
                throw new Exception("The group-dataset ID provided was not found.");
            }
            // If we dont have a reader, then create one for this group
            // next time, it will be available and we won't have to waste time
            // opening the file.
            if (!m_readers.ContainsKey(group))
            {
                var path = m_dataFiles[group];
                var reader = new clsMzXMLFileAccessor();
                m_readers.Add(group, reader);

                var opened = reader.OpenFile(path);
                if (!opened)
                {
                    throw new IOException("Could not open the mzXML file " + path);
                }
            }
            var rawReader = m_readers[group];

            var numberOfScans = rawReader.ScanCount;
            var info = new clsSpectrumInfo();

            for (var i = 0; i < numberOfScans; i++)
            {
                // This scan is not to be used.
                var isInExcludeMap = excludeMap.ContainsKey(i);
                if (isInExcludeMap)
                    continue;

                var header = new clsSpectrumInfo();

                rawReader.GetSpectrumHeaderInfoByIndex(i, ref header);
                if (header.MSLevel > 1)
                {
                    var spectrum = new MSSpectra();
                    spectrum.MsLevel = header.MSLevel;
                    spectrum.RetentionTime = header.RetentionTimeMin;
                    spectrum.Scan = i;
                    spectrum.PrecursorMz = header.ParentIonMZ;
                    spectrum.TotalIonCurrent = header.TotalIonCurrent;
                    spectrum.CollisionType = CollisionType.Other;
                    spectra.Add(spectrum);
                }
            }

            return spectra;
        }
Пример #40
0
        public MSSpectra GetSpectrum(int scan, int groupId, int scanLevel, out ScanSummary summary, bool loadPeaks)
        {
            // Get the RawFileReader for this group
            var ipbReader = GetReaderForGroup(groupId);

            scan = ValidateScanNumber(scan, ipbReader);

            summary = GetScanSummary(scan, ipbReader);

            var spectrum = new MSSpectra
            {
                MsLevel = summary.MsLevel,
                RetentionTime = summary.Time,
                Scan = scan,
                PrecursorMz = summary.PrecursorMz,
                TotalIonCurrent = summary.TotalIonCurrent,
                CollisionType = summary.CollisionType
            };

            // Need to make this a standard type of collision based off of the data.
            if (loadPeaks)
            {
                spectrum.Peaks = LoadSpectra(ipbReader, scan);
            }

            return spectrum;
        }
Пример #41
0
        public MSSpectra GetSpectrum(int scan, int groupId, int scanLevel, out ScanSummary summary, bool loadPeaks)
        {
            // Get the RawFileReader for this group
            var rawReader = GetReaderForGroup(groupId);

            ValidateScanNumber(scan, rawReader);

            FinniganFileReaderBaseClass.udtScanHeaderInfoType header;
            summary = GetScanSummary(scan, rawReader, out header);

            var spectrum = new MSSpectra
            {
                MsLevel = header.MSLevel,
                RetentionTime = header.RetentionTime,
                Scan = scan,
                PrecursorMz = header.ParentIonMZ,
                TotalIonCurrent = header.TotalIonCurrent,
                CollisionType = summary.CollisionType
            };

            // Need to make this a standard type of collision based off of the data.
            if (loadPeaks)
            {
                spectrum.Peaks = LoadRawSpectra(rawReader, scan);
            }

            return spectrum;
        }
Пример #42
0
 public MsMsTreeViewModel(MSSpectra feature)
     : this(feature, null)
 {
 }