Exemplo n.º 1
0
        public override MsDataScan GetOneBasedScan(int oneBasedScanNumber)
        {
            if (Scans[oneBasedScanNumber - 1] == null)
            {
                var representativeScanNumber = oneBasedScanNumber + (numScansToAverage - 1) / 2;
                var representative           = raw.GetOneBasedScan(representativeScanNumber);
                if (representative.MsnOrder != 1)
                {
                    throw new MzLibException("Scan " + representativeScanNumber + " is not MS1 scan");
                }
                int      msnOrder = 1;
                Polarity polarity = representative.Polarity;
                if (!representative.IsCentroid)
                {
                    throw new MzLibException("Scan " + representativeScanNumber + " is not centroid scan");
                }
                bool           isCentroid    = true;
                double         retentionTime = representative.RetentionTime;
                MZAnalyzerType mzAnalyzer    = representative.MzAnalyzer;

                MzSpectrum peaks = CombinePeaks(raw.GetAllScansList().Where(b => b.OneBasedScanNumber >= oneBasedScanNumber && b.OneBasedScanNumber <= oneBasedScanNumber + numScansToAverage - 1).Select(b => b.MassSpectrum).ToList(), ppmToleranceForPeakCombination);

                MzRange scanWindowRange = representative.ScanWindowRange;

                double totalIonCurrent = peaks.SumOfAllY;
                double injectionTime   = double.NaN;
                double[,] noiseData = null;

                Scans[oneBasedScanNumber - 1] = new MsDataScan(peaks, oneBasedScanNumber, msnOrder, isCentroid, polarity, retentionTime, scanWindowRange, null, mzAnalyzer, totalIonCurrent, injectionTime, noiseData, "scan=" + oneBasedScanNumber);
            }
            return(Scans[oneBasedScanNumber - 1]);
        }
Exemplo n.º 2
0
        public void SpectrumMassRange()
        {
            MzRange range = new MzRange(328.73795, 723.35345);

            Assert.AreEqual(0, _mzSpectrumA.Range.Minimum - range.Minimum, 1e-9);
            Assert.AreEqual(0, _mzSpectrumA.Range.Maximum - range.Maximum, 1e-9);
        }
        public IEnumerable <DeconvolutedEnvelope> Deconvolute(MzSpectrum spectrum, MzRange mzRange)
        {
            // if no peaks in the scan, stop
            if (spectrum.Size == 0)
            {
                yield break;
            }

            // get list of envelope candidates for this scan
            var indicies           = GetPeaksThatPassSignalToNoiseFilter(spectrum).ToList();
            var candidateEnvelopes = GetEnvelopeCandidates(spectrum, mzRange, indicies);

            CalculateSignalToNoise(spectrum, candidateEnvelopes);
            var parsimoniousEnvelopes = RunEnvelopeParsimony(candidateEnvelopes, spectrum);

            // return deconvoluted envelopes
            foreach (DeconvolutedEnvelope envelope in parsimoniousEnvelopes.Where(p =>
                                                                                  p.SignalToNoise >= SignalToNoiseRequired &&
                                                                                  p.MonoisotopicMass >= MinMass &&
                                                                                  p.Charge >= MinCharge &&
                                                                                  p.Peaks.Count >= MinPeaks))
            {
                yield return(envelope);
            }
        }
Exemplo n.º 4
0
 public MsDataScan(MzSpectrum massSpectrum, int oneBasedScanNumber, int msnOrder, bool isCentroid, Polarity polarity, double retentionTime, MzRange scanWindowRange, string scanFilter, MZAnalyzerType mzAnalyzer,
                   double totalIonCurrent, double?injectionTime, double[,] noiseData, string nativeId, double?selectedIonMz = null, int?selectedIonChargeStateGuess = null, double?selectedIonIntensity = null, double?isolationMZ = null,
                   double?isolationWidth = null, DissociationType?dissociationType = null, int?oneBasedPrecursorScanNumber = null, double?selectedIonMonoisotopicGuessMz = null, string hcdEnergy = null)
 {
     OneBasedScanNumber             = oneBasedScanNumber;
     MsnOrder                       = msnOrder;
     IsCentroid                     = isCentroid;
     Polarity                       = polarity;
     RetentionTime                  = retentionTime;
     ScanWindowRange                = scanWindowRange;
     ScanFilter                     = scanFilter;
     MzAnalyzer                     = mzAnalyzer;
     TotalIonCurrent                = totalIonCurrent;
     InjectionTime                  = injectionTime;
     NoiseData                      = noiseData;
     MassSpectrum                   = massSpectrum;
     NativeId                       = nativeId;
     OneBasedPrecursorScanNumber    = oneBasedPrecursorScanNumber;
     IsolationMz                    = isolationMZ;
     IsolationWidth                 = isolationWidth;
     DissociationType               = dissociationType;
     SelectedIonMZ                  = selectedIonMz;
     SelectedIonIntensity           = selectedIonIntensity;
     SelectedIonChargeStateGuess    = selectedIonChargeStateGuess;
     SelectedIonMonoisotopicGuessMz = selectedIonMonoisotopicGuessMz;
     HcdEnergy                      = hcdEnergy;
 }
Exemplo n.º 5
0
        private void button2_Click(object sender, EventArgs e)
        {
            double  lowMZ  = (double)numericUpDown5.Value;
            double  highMZ = (double)numericUpDown6.Value;
            MzRange range  = new MzRange(lowMZ, highMZ);

            listBox1.Items.Add(range);
        }
Exemplo n.º 6
0
        public static void ReplaceBadStdevTwo()
        {
            //here we are adding a really hydrophobic psm at the same time as a regular peptide so that there is a big difference in their computed hydrophobicities. The stdev of these hydrophobicities is out of whach the the collective and so it needs to get replaced by the global average

            var              variableModifications = new List <Modification>();
            var              fixedModifications    = new List <Modification>();
            var              origDataFile          = Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestData\TaGe_SA_HeLa_04_subset_longestSeq.mzML");
            MyFileManager    myFileManager         = new MyFileManager(true);
            CommonParameters CommonParameters      = new CommonParameters(digestionParams: new DigestionParams());
            var              myMsDataFile          = myFileManager.LoadFile(origDataFile, CommonParameters);
            var              searchModes           = new SinglePpmAroundZeroSearchMode(5);
            List <Protein>   proteinList           = ProteinDbLoader.LoadProteinFasta(Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestData\hela_snip_for_unitTest.fasta"), true, DecoyType.Reverse, false, ProteinDbLoader.UniprotAccessionRegex, ProteinDbLoader.UniprotFullNameRegex, ProteinDbLoader.UniprotFullNameRegex, ProteinDbLoader.UniprotGeneNameRegex,
                                                                                      ProteinDbLoader.UniprotOrganismRegex, out var dbErrors, -1);
            var listOfSortedms2Scans = MetaMorpheusTask.GetMs2Scans(myMsDataFile, @"TestData\TaGe_SA_HeLa_04_subset_longestSeq.mzML", CommonParameters).OrderBy(b => b.PrecursorMass).ToArray();

            //adding a new scan that creates a psm at an isolated retention time. This will ultimately cause PEP to replace its retention time standard deviation "Z-score" with the global average.
            Ms2ScanWithSpecificMass topMs2Scan = listOfSortedms2Scans[395];
            int        newOneBasedScanNumber   = 1000;
            MzRange    range             = new MzRange(topMs2Scan.TheScan.MassSpectrum.XArray.Min(), topMs2Scan.TheScan.MassSpectrum.XArray.Max());
            MzSpectrum mzs               = new MzSpectrum(topMs2Scan.TheScan.MassSpectrum.XArray, topMs2Scan.TheScan.MassSpectrum.YArray, true);
            double     newRetentionTime  = topMs2Scan.TheScan.RetentionTime - 25;
            MsDataScan msd               = new MsDataScan(mzs, newOneBasedScanNumber, 2, topMs2Scan.TheScan.IsCentroid, Polarity.Positive, newRetentionTime, range, "", MZAnalyzerType.Orbitrap, topMs2Scan.TheScan.TotalIonCurrent, topMs2Scan.TheScan.InjectionTime, topMs2Scan.TheScan.NoiseData, "", topMs2Scan.TheScan.SelectedIonMZ, topMs2Scan.TheScan.SelectedIonChargeStateGuess, topMs2Scan.TheScan.SelectedIonIntensity, topMs2Scan.TheScan.IsolationMz, topMs2Scan.TheScan.IsolationWidth, DissociationType.HCD, topMs2Scan.TheScan.OneBasedPrecursorScanNumber, topMs2Scan.TheScan.SelectedIonMonoisotopicGuessMz);
            Ms2ScanWithSpecificMass mwsm = new Ms2ScanWithSpecificMass(msd, topMs2Scan.PrecursorMonoisotopicPeakMz, topMs2Scan.PrecursorCharge, topMs2Scan.FullFilePath, new CommonParameters(), topMs2Scan.ExperimentalFragments);

            Ms2ScanWithSpecificMass[] extendedArray = new Ms2ScanWithSpecificMass[listOfSortedms2Scans.Length + 1];
            for (int i = 0; i < listOfSortedms2Scans.Length; i++)
            {
                extendedArray[i] = listOfSortedms2Scans[i];
            }
            extendedArray[listOfSortedms2Scans.Length] = mwsm;

            extendedArray = extendedArray.OrderBy(b => b.PrecursorMass).ToArray();

            PeptideSpectralMatch[] allPsmsArray = new PeptideSpectralMatch[extendedArray.Length];
            new ClassicSearchEngine(allPsmsArray, extendedArray, variableModifications, fixedModifications, null, null, null, proteinList, searchModes, CommonParameters, new List <string>()).Run();

            List <PeptideSpectralMatch> nonNullPsms = allPsmsArray.Where(p => p != null).ToList();

            nonNullPsms = nonNullPsms.OrderByDescending(p => p.Score).ToList();
            List <PeptideSpectralMatch> psmBloated = new List <PeptideSpectralMatch>();

            psmBloated.AddRange(nonNullPsms);
            int arrayMax = nonNullPsms.Count;

            psmBloated.AddRange(nonNullPsms.GetRange(2, arrayMax - 2));
            psmBloated.AddRange(nonNullPsms.GetRange(2, arrayMax - 2));


            PeptideSpectralMatch pp = psmBloated.Where(p => p.ScanRetentionTime < (newRetentionTime + 1)).First();

            PeptideWithSetModifications newPwsmTwo = new PeptideWithSetModifications(new Protein("WAGVLPWFPWAAVVWGFWF", "ACCESSION", "ORGANISM"), new DigestionParams(), 1, 2, CleavageSpecificity.Full, "", 0, new Dictionary <int, Modification>(), 0);
            PeptideSpectralMatch        newPsmTwo  = new PeptideSpectralMatch(newPwsmTwo, pp.BestMatchingPeptides.First().Notch, pp.Score, pp.ScanIndex, mwsm, new DigestionParams(), pp.MatchedFragmentIons);

            psmBloated.Add(newPsmTwo);

            FdrAnalysisResults fdrResultsClassicDelta = (FdrAnalysisResults)(new FdrAnalysisEngine(psmBloated.Where(p => p != null).ToList(), 1, CommonParameters, new List <string>()).Run());
        }
 public MzFeature(Peptide precursor, int charge)
 {
     this.feature         = precursor;
     this.charge          = charge;
     this.mzRange         = new MzRange(this.feature.ToMz(this.charge), massTolerance);
     this.intensities     = new List <double>();
     this.spectrumNumbers = new List <int>();
     this.spectrumTICs    = new List <double>();
 }
 public MzFeature(Fragment fragment, int charge)
 {
     this.feature         = fragment;
     this.charge          = charge;
     this.mzRange         = new MzRange(this.feature.ToMz(this.charge), massTolerance);
     this.intensities     = new List <double>();
     this.spectrumNumbers = new List <int>();
     this.spectrumTICs    = new List <double>();
 }
Exemplo n.º 9
0
        public double[,] GetChro(string scanFilter, MzRange range, double startTime, double endTime, Smoothing smoothing = Smoothing.None, int smoothingPoints = 3)
        {
            object chro    = null;
            object flags   = null;
            int    size    = 0;
            string mzrange = range.Minimum.ToString("F4") + "-" + range.Maximum.ToString("F4");

            _rawConnection.GetChroData(0, 0, 0, scanFilter, mzrange, string.Empty, 0.0, startTime, endTime, (int)smoothing, smoothingPoints, ref chro, ref flags, ref size);
            return((double[, ])chro);
        }
Exemplo n.º 10
0
        public IEnumerable <Tuple <List <IMzPeak>, int> > Deconvolute(MzRange theRange, int maxAssumedChargeState, Tolerance massTolerance, double intensityRatio)
        {
            var isolatedMassesAndCharges = new List <Tuple <List <IMzPeak>, int> >();

            foreach (var peak in Extract(theRange))
            {
                // Always assume the current peak is a monoisotopic peak!

                List <IMzPeak> bestListOfPeaks = new List <IMzPeak>();
                int            bestChargeState = 1;
                for (int chargeState = 1; chargeState <= maxAssumedChargeState; chargeState++)
                {
                    var listOfPeaksForThisChargeState = new List <IMzPeak> {
                        peak
                    };
                    var mMass = peak.Mz.ToMass(chargeState);
                    for (int mm = 1; mm <= mms.Length; mm++)
                    {
                        double diffToNextMmPeak = mms[mm - 1];
                        double theorMass        = mMass + diffToNextMmPeak;
                        var    closestpeak      = GetClosestPeak(theorMass.ToMz(chargeState));
                        if (massTolerance.Within(closestpeak.Mz.ToMass(chargeState), theorMass) && SatisfiesRatios(mMass, mm, peak, closestpeak, intensityRatio))
                        {
                            // Found a match to an isotope peak for this charge state!
                            listOfPeaksForThisChargeState.Add(closestpeak);
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (listOfPeaksForThisChargeState.Count >= bestListOfPeaks.Count)
                    {
                        bestListOfPeaks = listOfPeaksForThisChargeState;
                        bestChargeState = chargeState;
                    }
                }
                if (bestListOfPeaks.Count >= 2)
                {
                    isolatedMassesAndCharges.Add(new Tuple <List <IMzPeak>, int>(bestListOfPeaks, bestChargeState));
                }
            }

            List <double> seen = new List <double>();

            while (isolatedMassesAndCharges.Any())
            {
                // Pick longest
                var longest = isolatedMassesAndCharges.OrderByDescending(b => b.Item1.Count).First();
                yield return(longest);

                isolatedMassesAndCharges.Remove(longest);
                isolatedMassesAndCharges.RemoveAll(b => b.Item1.Intersect(longest.Item1).Any());
            }
        }
Exemplo n.º 11
0
        public void TransformMzs(Func <IMzPeak, double> convertorForSpectrum, Func <IMzPeak, double> convertorForPrecursor)
        {
            MassSpectrum.ReplaceXbyApplyingFunction(convertorForSpectrum);
            this.SelectedIonMZ = convertorForPrecursor(new MzPeak(SelectedIonMZ, SelectedIonIntensity.Value));
            if (SelectedIonMonoisotopicGuessMz.HasValue)
            {
                this.SelectedIonMonoisotopicGuessMz = convertorForPrecursor(new MzPeak(SelectedIonMonoisotopicGuessMz.Value, SelectedIonMonoisotopicGuessIntensity.Value));
            }
            this.IsolationMz = convertorForPrecursor(new MzPeak(IsolationMz, SelectedIonIntensity.Value));

            // Will need to recompute this...
            isolationRange = null;
        }
Exemplo n.º 12
0
        public double GetIntensity(MzRange mzRange, double massAccuracy)
        {
            double result = 0;

            foreach (var entry in Values)
            {
                if (mzRange.ContainsWithMassAccuracy(entry.Key, massAccuracy))
                {
                    result += entry.Value;
                }
            }
            return(result);
        }
Exemplo n.º 13
0
 protected MsDataScan(int oneBasedScanNumber, int msnOrder, bool isCentroid, Polarity polarity, double retentionTime, MzRange scanWindowRange, string scanFilter, MZAnalyzerType mzAnalyzer, double totalIonCurrent, double?injectionTime, double[,] noiseData)
 {
     OneBasedScanNumber = oneBasedScanNumber;
     MsnOrder           = msnOrder;
     IsCentroid         = isCentroid;
     Polarity           = polarity;
     RetentionTime      = retentionTime;
     ScanWindowRange    = scanWindowRange;
     ScanFilter         = scanFilter;
     MzAnalyzer         = mzAnalyzer;
     TotalIonCurrent    = totalIonCurrent;
     InjectionTime      = injectionTime;
     NoiseData          = noiseData;
 }
Exemplo n.º 14
0
 public MsDataScan(TSpectrum massSpectrum, int oneBasedScanNumber, int msnOrder, bool isCentroid, Polarity polarity, double retentionTime, MzRange scanWindowRange, string scanFilter, MZAnalyzerType mzAnalyzer, double totalIonCurrent, double?injectionTime, double[,] noiseData, string nativeId)
 {
     OneBasedScanNumber = oneBasedScanNumber;
     MsnOrder           = msnOrder;
     IsCentroid         = isCentroid;
     Polarity           = polarity;
     RetentionTime      = retentionTime;
     ScanWindowRange    = scanWindowRange;
     ScanFilter         = scanFilter;
     MzAnalyzer         = mzAnalyzer;
     TotalIonCurrent    = totalIonCurrent;
     InjectionTime      = injectionTime;
     NoiseData          = noiseData;
     MassSpectrum       = massSpectrum;
     NativeId           = nativeId;
 }
Exemplo n.º 15
0
        /// <summary>
        /// Returns the ChromatogramPoint which has the intensities of the points
        /// closest to the specified MzRange.  The intensities are assumed to be
        /// from a centroided spectrum, and the mzRange is much smaller than the
        /// machine resolution.
        /// </summary>
        public static ChromatogramPoint GetPoint(MzRange mzRange, double[] mzs, double[] intensities)
        {
            if (mzs.Length == 0)
            {
                return(new ChromatogramPoint());
            }
            int imin   = ClosestIndex(mzRange.Min - .1, mzs);
            int imax   = ClosestIndex(mzRange.Max + .1, mzs);
            var values = new List <KeyValuePair <float, float> >();

            for (int i = imin; i <= imax; i++)
            {
                values.Add(new KeyValuePair <float, float>((float)mzs[i], (float)intensities[i]));
            }
            return(new ChromatogramPoint(values.ToArray()));
        }
Exemplo n.º 16
0
        protected override MsDataScan <ThermoSpectrum> GetMsDataScanFromFile(int spectrumNumber)
        {
            var precursorID = GetPrecursorID(spectrumNumber);

            int    numberOfPackets   = -1;
            double startTime         = double.NaN;
            double lowMass           = double.NaN;
            double highMass          = double.NaN;
            double totalIonCurrent   = double.NaN;
            double basePeakMass      = double.NaN;
            double basePeakIntensity = double.NaN;
            int    numberOfChannels  = -1;
            int    uniformTime       = -1;
            double frequency         = double.NaN;

            _rawConnection.GetScanHeaderInfoForScanNum(spectrumNumber, ref numberOfPackets, ref startTime, ref lowMass,
                                                       ref highMass, ref totalIonCurrent, ref basePeakMass, ref basePeakIntensity,
                                                       ref numberOfChannels, ref uniformTime, ref frequency);


            MzRange ScanWindowRange = new MzRange(lowMass, highMass);



            double retentionTime = 0;

            _rawConnection.RTFromScanNum(spectrumNumber, ref retentionTime);
            int msnOrder = 0;

            _rawConnection.GetMSOrderForScanNum(spectrumNumber, ref msnOrder);


            if (precursorID.Equals(GetSpectrumID(spectrumNumber)))
            {
                return(new MsDataScan <ThermoSpectrum>(spectrumNumber, GetSpectrumFromRawFile(spectrumNumber), GetSpectrumID(spectrumNumber), msnOrder, GetIsCentroid(spectrumNumber), GetPolarity(spectrumNumber), retentionTime, ScanWindowRange, GetScanFilter(spectrumNumber), GetMzAnalyzer(spectrumNumber), GetInjectionTime(spectrumNumber), totalIonCurrent));
            }
            else
            {
                return(new MsDataScan <ThermoSpectrum>(spectrumNumber, GetSpectrumFromRawFile(spectrumNumber), GetSpectrumID(spectrumNumber), msnOrder, GetIsCentroid(spectrumNumber), GetPolarity(spectrumNumber), retentionTime, ScanWindowRange, GetScanFilter(spectrumNumber), GetMzAnalyzer(spectrumNumber), GetInjectionTime(spectrumNumber), totalIonCurrent, precursorID, GetSelectedIonMZ(spectrumNumber), GetPrecusorCharge(spectrumNumber), GetSelectedIonIntensity(spectrumNumber), GetIsolationMZ(spectrumNumber), GetIsolationWidth(spectrumNumber), GetDissociationType(spectrumNumber), GetParentSpectrumNumber(spectrumNumber), GetPrecursorMonoisotopicIntensity(spectrumNumber), GetPrecursorMonoisotopicMZ(spectrumNumber)));
            }
        }
Exemplo n.º 17
0
        public void SpectrumMassRange()
        {
            MzRange range = new MzRange(328.73795, 723.35345);

            Assert.AreEqual(range, _mzSpectrumA.GetMzRange());
        }
Exemplo n.º 18
0
        public static List <IsoEnvelop> MsDeconv_Deconvolute(MzSpectrumXY mzSpectrumXY, MzRange theRange, DeconvolutionParameter deconvolutionParameter)
        {
            var isolatedMassesAndCharges = new List <IsoEnvelop>();

            if (mzSpectrumXY.Size == 0)
            {
                return(isolatedMassesAndCharges);
            }

            ////Deconvolution by MZ increasing order
            //double intensityThread = mzSpectrumXY.TotalIntensity / mzSpectrumXY.Size;
            for (int candidateForMostIntensePeak = 0; candidateForMostIntensePeak < mzSpectrumXY.XArray.Length - 1; candidateForMostIntensePeak++)
            {
                //if (mzSpectrumXY.YArray[candidateForMostIntensePeak] <= intensityThread)
                //{
                //    continue;
                //}

                double noiseLevel = CalNoiseLevel();

                //TO THINK: Only get one isoEnvelop per best peak. It is possible this is a overlap best peak with different charge state.
                IsoEnvelop bestIsotopeEnvelopeForThisPeak = MsDeconvExperimentPeak(mzSpectrumXY, candidateForMostIntensePeak, deconvolutionParameter, noiseLevel);

                if (bestIsotopeEnvelopeForThisPeak != null)
                {
                    bestIsotopeEnvelopeForThisPeak.MsDeconvSignificance = CalIsoEnvelopNoise(mzSpectrumXY, bestIsotopeEnvelopeForThisPeak);
                    bestIsotopeEnvelopeForThisPeak.IntensityRatio       = bestIsotopeEnvelopeForThisPeak.TotalIntensity / mzSpectrumXY.TotalIntensity;

                    isolatedMassesAndCharges.Add(bestIsotopeEnvelopeForThisPeak);
                }
            }

            HashSet <double> seen = new HashSet <double>(); //Do we still need this

            List <IsoEnvelop> isoEnvelops = new List <IsoEnvelop>();

            //TO DO: consider peak overlap
            foreach (var ok in isolatedMassesAndCharges.OrderByDescending(b => b.MsDeconvScore))
            {
                //if (seen.Overlaps(ok.ExperimentIsoEnvelop.Select(b => b.Mz)))
                //{
                //    continue;
                //}

                int noOverlap = 0;
                foreach (var ah in ok.ExistedExperimentPeak.Select(b => b.Mz))
                {
                    if (!seen.Contains(ah))
                    {
                        noOverlap++;
                    }
                }
                if (noOverlap < 2)
                {
                    continue;
                }
                foreach (var ah in ok.ExperimentIsoEnvelop.Select(b => b.Mz))
                {
                    seen.Add(ah);
                }

                isoEnvelops.Add(ok);
            }


            var orderedIsoEnvelops = isoEnvelops.OrderBy(p => p.ExperimentIsoEnvelop.First().Mz).ToList();

            return(orderedIsoEnvelops);
        }
Exemplo n.º 19
0
        public void SpectrumMassRange()
        {
            MzRange range = new MzRange(328.73795, 723.35345);

            Assert.AreEqual(range, _mzSpectrumA.GetMzRange());
        }
Exemplo n.º 20
0
        protected MsDataScanWithPrecursor(TSpectrum massSpectrum, int ScanNumber, int MsnOrder, bool isCentroid, Polarity Polarity, double RetentionTime, MzRange MzRange, string ScanFilter, MZAnalyzerType MzAnalyzer, double TotalIonCurrent, double selectedIonMZ, int?selectedIonChargeStateGuess, double?selectedIonIntensity, double?isolationMZ, double?isolationWidth, DissociationType dissociationType, int?oneBasedPrecursorScanNumber, double?selectedIonMonoisotopicGuessMz, double?injectionTime, double[,] noiseData, string nativeId)
            : base(massSpectrum, ScanNumber, MsnOrder, isCentroid, Polarity, RetentionTime, MzRange, ScanFilter, MzAnalyzer, TotalIonCurrent, injectionTime, noiseData, nativeId)
        {
            this.OneBasedPrecursorScanNumber = oneBasedPrecursorScanNumber;

            this.IsolationMz    = isolationMZ;
            this.IsolationWidth = isolationWidth;

            this.DissociationType = dissociationType;

            this.SelectedIonMZ                  = selectedIonMZ;
            this.SelectedIonIntensity           = selectedIonIntensity;
            this.SelectedIonChargeStateGuess    = selectedIonChargeStateGuess;
            this.SelectedIonMonoisotopicGuessMz = selectedIonMonoisotopicGuessMz;
        }
Exemplo n.º 21
0
        public MzmlScan(int oneBasedScanNumber, MzmlMzSpectrum massSpectrum, int msnOrder, bool isCentroid, Polarity polarity, double retentionTime, MzRange scanWindowRange, string scanFilter, MZAnalyzerType mzAnalyzer, double totalIonCurrent, double?injectionTime)
            : base(oneBasedScanNumber, msnOrder, isCentroid, polarity, retentionTime, scanWindowRange, scanFilter, mzAnalyzer, totalIonCurrent, injectionTime, null)

        {
            this.MassSpectrum = massSpectrum;
        }
Exemplo n.º 22
0
        /// <summary>
        /// Gets the scan with the specified one-based scan number.
        /// </summary>
        public override MsDataScan GetOneBasedScanFromDynamicConnection(int oneBasedScanNumber, IFilteringParams filterParams = null)
        {
            MsDataScan scan = null;

            if (ScanNumberToByteOffset.TryGetValue(oneBasedScanNumber, out long byteOffset))
            {
                // seek to the byte of the scan
                reader.BaseStream.Position = byteOffset;
                reader.DiscardBufferedData();

                // DO NOT USE THIS METHOD! it does not seek reliably
                //stream.BaseStream.Seek(byteOffset, SeekOrigin.Begin);

                // read the scan
                using (XmlReader xmlReader = XmlReader.Create(reader))
                {
                    string nativeId = null;
                    while (xmlReader.Read())
                    {
                        // this skips whitespace
                        string upperName = xmlReader.Name.ToUpper();
                        if (upperName == "SPECTRUM" && xmlReader.IsStartElement())
                        {
                            nativeId = xmlReader["id"];
                            break;
                        }
                    }

                    // deserializing the scan's data doesn't work well. the spectrum type is deserialized
                    // but sub-elements aren't. this is probably because we're trying to deserialize only
                    // a part of the XML file... deserialization would probably be cleaner code than
                    // using the current implementation but I couldn't get it to work
                    //var deserializedSpectrum = (IO.MzML.Generated.SpectrumType)serializer.Deserialize(xmlReader.ReadSubtree());

                    MzSpectrum     spectrum       = null;
                    int?           msOrder        = 0;
                    bool?          isCentroid     = false;
                    Polarity       polarity       = Polarity.Unknown;
                    double         retentionTime  = double.NaN;
                    MzRange        range          = null;
                    string         scanFilter     = null;
                    MZAnalyzerType mzAnalyzerType = MZAnalyzerType.Unknown;
                    double         tic            = 0;
                    double?        injTime        = null;
                    double[,] noiseData = null; // TODO: read this
                    double?          selectedIonMz                  = null;
                    int?             selectedCharge                 = null;
                    double?          selectedIonIntensity           = null;
                    double?          isolationMz                    = null; // TODO: should this be refined? or taken from the scan header?
                    double?          isolationWidth                 = null;
                    DissociationType?dissociationType               = null;
                    int?             oneBasedPrecursorScanNumber    = null;
                    double?          selectedIonMonoisotopicGuessMz = null;

                    double scanLowerLimit             = double.NaN;
                    double scanUpperLimit             = double.NaN;
                    double isolationWindowLowerOffset = double.NaN;
                    double isolationWindowUpperOffset = double.NaN;

                    bool     compressed         = false;
                    bool     readingMzs         = false;
                    bool     readingIntensities = false;
                    bool     is32bit            = true;
                    double[] mzs         = null;
                    double[] intensities = null;

                    while (xmlReader.Read())
                    {
                        switch (xmlReader.Name.ToUpper())
                        {
                        // controlled vocabulary parameter
                        case "CVPARAM":
                            string cvParamAccession = xmlReader["accession"];

                            if (Mzml.DissociationDictionary.ContainsKey(cvParamAccession))
                            {
                                dissociationType = Mzml.DissociationDictionary[cvParamAccession];
                                break;
                            }

                            if (Mzml.PolarityDictionary.ContainsKey(cvParamAccession))
                            {
                                polarity = Mzml.PolarityDictionary[cvParamAccession];
                                break;
                            }

                            switch (cvParamAccession)
                            {
                            // MS order
                            case "MS:1000511":
                                msOrder = int.Parse(xmlReader["value"]);
                                break;

                            // centroid mode
                            case "MS:1000127":
                                isCentroid = true;
                                break;

                            // profile mode
                            case "MS:1000128":
                                isCentroid = false;
                                throw new MzLibException("Reading profile mode mzmls not supported");
                                break;

                            // total ion current
                            case "MS:1000285":
                                tic = double.Parse(xmlReader["value"]);
                                break;

                            // retention time
                            case "MS:1000016":
                                retentionTime = double.Parse(xmlReader["value"]);
                                break;

                            // filter string
                            case "MS:1000512":
                                scanFilter = xmlReader["value"];
                                break;

                            // ion injection time
                            case "MS:1000927":
                                injTime = double.Parse(xmlReader["value"]);
                                break;

                            // scan lower limit
                            case "MS:1000501":
                                scanLowerLimit = double.Parse(xmlReader["value"]);
                                break;

                            // scan upper limit
                            case "MS:1000500":
                                scanUpperLimit = double.Parse(xmlReader["value"]);
                                break;

                            // isolation window lower offset
                            case "MS:1000828":
                                isolationWindowLowerOffset = double.Parse(xmlReader["value"]);
                                break;

                            // isolation window upper offset
                            case "MS:1000829":
                                isolationWindowUpperOffset = double.Parse(xmlReader["value"]);
                                break;

                            // isolated m/z
                            case "MS:1000827":
                                isolationMz = double.Parse(xmlReader["value"]);
                                break;

                            // selected ion m/z
                            case "MS:1000744":
                                selectedIonMz = double.Parse(xmlReader["value"]);
                                break;

                            // selected charge state
                            case "MS:1000041":
                                selectedCharge = int.Parse(xmlReader["value"]);
                                break;

                            // selected intensity
                            case "MS:1000042":
                                selectedIonIntensity = double.Parse(xmlReader["value"]);
                                break;

                            // mass analyzer types
                            case "MS:1000081":
                                mzAnalyzerType = MZAnalyzerType.Quadrupole;
                                break;

                            case "MS:1000291":
                                mzAnalyzerType = MZAnalyzerType.IonTrap2D;
                                break;

                            case "MS:1000082":
                                mzAnalyzerType = MZAnalyzerType.IonTrap3D;
                                break;

                            case "MS:1000484":
                                mzAnalyzerType = MZAnalyzerType.Orbitrap;
                                break;

                            case "MS:1000084":
                                mzAnalyzerType = MZAnalyzerType.TOF;
                                break;

                            case "MS:1000079":
                                mzAnalyzerType = MZAnalyzerType.FTICR;
                                break;

                            case "MS:1000080":
                                mzAnalyzerType = MZAnalyzerType.Sector;
                                break;

                            case "MS:1000523":
                                is32bit = false;
                                break;

                            case "MS:1000574":
                                compressed = true;
                                break;

                            case "MS:1000514":
                                readingMzs = true;
                                break;

                            case "MS:1000515":
                                readingIntensities = true;
                                break;
                            }
                            break;

                        // binary data array (e.g., m/z or intensity array)
                        case "BINARY":
                            if (!readingMzs && !readingIntensities)
                            {
                                break;
                            }

                            while (string.IsNullOrWhiteSpace(xmlReader.Value))
                            {
                                xmlReader.Read();
                            }

                            string binaryString = xmlReader.Value;

                            byte[] binaryData = null;

                            if (!is32bit)
                            {
                                binaryData = Convert.FromBase64String(binaryString);
                            }
                            else
                            {
                                // todo: check. not sure if this is right
                                binaryData = Encoding.UTF8.GetBytes(binaryString);
                            }

                            double[] data = Mzml.ConvertBase64ToDoubles(binaryData, compressed, is32bit);

                            if (readingMzs)
                            {
                                mzs        = data;
                                readingMzs = false;
                            }
                            else if (readingIntensities)
                            {
                                intensities        = data;
                                readingIntensities = false;
                            }

                            break;

                        case "PRECURSOR":
                            if (xmlReader.IsStartElement())
                            {
                                string precursorScanInfo = xmlReader["spectrumRef"];

                                if (precursorScanInfo != null)
                                {
                                    oneBasedPrecursorScanNumber = NativeIdToScanNumber[precursorScanInfo];
                                }
                            }
                            break;

                        case "USERPARAM":
                            if (xmlReader.IsStartElement() && xmlReader["name"] != null && xmlReader["name"] == "[mzLib]Monoisotopic M/Z:")
                            {
                                selectedIonMonoisotopicGuessMz = double.Parse(xmlReader["value"]);
                            }
                            break;

                        // done reading spectrum
                        case "SPECTRUM":
                            if (!xmlReader.IsStartElement())
                            {
                                if (msOrder > 1)
                                {
                                    isolationWidth = isolationWindowUpperOffset + isolationWindowLowerOffset;

                                    if (dissociationType == null)
                                    {
                                        dissociationType = DissociationType.Unknown;
                                    }
                                }

                                if (!msOrder.HasValue || !isCentroid.HasValue)
                                {
                                    throw new MzLibException("Could not determine the MS order or centroid/profile status");
                                }

                                // peak filtering
                                if (filterParams != null && intensities.Length > 0 &&
                                    ((filterParams.ApplyTrimmingToMs1 && msOrder.Value == 1) || (filterParams.ApplyTrimmingToMsMs && msOrder.Value > 1)))
                                {
                                    MsDataFile.WindowModeHelper(ref intensities, ref mzs, filterParams, scanLowerLimit, scanUpperLimit);
                                }

                                Array.Sort(mzs, intensities);

                                range    = new MzRange(scanLowerLimit, scanUpperLimit);
                                spectrum = new MzSpectrum(mzs, intensities, false);

                                scan = new MsDataScan(spectrum, oneBasedScanNumber, msOrder.Value, isCentroid.Value, polarity,
                                                      retentionTime, range, scanFilter, mzAnalyzerType, tic, injTime, noiseData,
                                                      nativeId, selectedIonMz, selectedCharge, selectedIonIntensity, isolationMz, isolationWidth,
                                                      dissociationType, oneBasedPrecursorScanNumber, selectedIonMonoisotopicGuessMz);

                                return(scan);
                            }
                            else
                            {
                                throw new MzLibException("Spectrum data is malformed");
                            }
                        }
                    }
                }
            }

            return(scan);
        }
Exemplo n.º 23
0
        // Mass tolerance must account for different isotope spacing!
        public IEnumerable <IsotopicEnvelope> Deconvolute(MzRange theRange, int minAssumedChargeState, int maxAssumedChargeState, double deconvolutionTolerancePpm, double intensityRatioLimit)
        {
            if (Size == 0)
            {
                yield break;
            }

            var isolatedMassesAndCharges = new List <IsotopicEnvelope>();

            foreach (var candidateForMostIntensePeak in ExtractIndices(theRange.Minimum, theRange.Maximum))
            {
                IsotopicEnvelope bestIsotopeEnvelopeForThisPeak = null;

                var candidateForMostIntensePeakMz = XArray[candidateForMostIntensePeak];
                //Console.WriteLine("candidateForMostIntensePeakMz: " + candidateForMostIntensePeakMz);
                var candidateForMostIntensePeakIntensity = YArray[candidateForMostIntensePeak];

                for (int chargeState = minAssumedChargeState; chargeState <= maxAssumedChargeState; chargeState++)
                {
                    //Console.WriteLine(" chargeState: " + chargeState);
                    var testMostIntenseMass = candidateForMostIntensePeakMz.ToMass(chargeState);

                    var massIndex = Array.BinarySearch(mostIntenseMasses, testMostIntenseMass);
                    if (massIndex < 0)
                    {
                        massIndex = ~massIndex;
                    }
                    if (massIndex == mostIntenseMasses.Length)
                    {
                        //Console.WriteLine("Breaking  because mass is too high: " + testMostIntenseMass);
                        break;
                    }
                    //Console.WriteLine("  massIndex: " + massIndex);

                    var listOfPeaks = new List <(double, double)> {
                        (candidateForMostIntensePeakMz, candidateForMostIntensePeakIntensity)
                    };
                    var listOfRatios = new List <double> {
                        allIntensities[massIndex][0] / candidateForMostIntensePeakIntensity
                    };
                    // Assuming the test peak is most intense...
                    // Try to find the rest of the isotopes!

                    double differenceBetweenTheorAndActual = testMostIntenseMass - mostIntenseMasses[massIndex];
                    double totalIntensity = candidateForMostIntensePeakIntensity;
                    for (int indexToLookAt = 1; indexToLookAt < allIntensities[massIndex].Length; indexToLookAt++)
                    {
                        //Console.WriteLine("   indexToLookAt: " + indexToLookAt);
                        double theorMassThatTryingToFind = allMasses[massIndex][indexToLookAt] + differenceBetweenTheorAndActual;
                        //Console.WriteLine("   theorMassThatTryingToFind: " + theorMassThatTryingToFind);
                        //Console.WriteLine("   theorMassThatTryingToFind.ToMz(chargeState): " + theorMassThatTryingToFind.ToMz(chargeState));
                        var closestPeakToTheorMass = GetClosestPeakIndex(theorMassThatTryingToFind.ToMz(chargeState));
                        var closestPeakmz          = XArray[closestPeakToTheorMass.Value];
                        //Console.WriteLine("   closestPeakmz: " + closestPeakmz);
                        var closestPeakIntensity = YArray[closestPeakToTheorMass.Value];
                        if (Math.Abs(closestPeakmz.ToMass(chargeState) - theorMassThatTryingToFind) / theorMassThatTryingToFind * 1e6 <= deconvolutionTolerancePpm &&
                            Peak2satisfiesRatio(allIntensities[massIndex][0], allIntensities[massIndex][indexToLookAt], candidateForMostIntensePeakIntensity, closestPeakIntensity, intensityRatioLimit) &&
                            !listOfPeaks.Contains((closestPeakmz, closestPeakIntensity)))
                        {
                            //Found a match to an isotope peak for this charge state!
                            //Console.WriteLine(" *   Found a match to an isotope peak for this charge state!");
                            //Console.WriteLine(" *   chargeState: " + chargeState);
                            //Console.WriteLine(" *   closestPeakmz: " + closestPeakmz);
                            listOfPeaks.Add((closestPeakmz, closestPeakIntensity));
                            totalIntensity += closestPeakIntensity;
                            listOfRatios.Add(allIntensities[massIndex][indexToLookAt] / closestPeakIntensity);
                        }
Exemplo n.º 24
0
        private IEnumerable <QuantFile> LoadFiles(IEnumerable <string> filePaths, bool ms3Quant = false)
        {
            MSDataFile.CacheScans = false;
            //int largestQuantPeak = 0;
            int i = 0;

            foreach (TagInformation tag in UsedTags.Values)
            {
                tag.UniqueTagNumber       = i++;
                tag.TotalSignal           = 0;
                tag.NormalizedTotalSignal = 0;
            }
            int largestQuantPeak = i - 1;

            //int largestQuantPeak = UsedTags.Values.Select(tag => tag.UniqueTagNumber).Concat(new[] {0}).Max();

            foreach (string filePath in filePaths)
            {
                Log("Processing file:\t" + filePath);
                OnUpdateLog("Processing File " + filePath + "...");
                QuantFile    quantFile        = new QuantFile(filePath);
                StreamReader basestreamReader = new StreamReader(filePath);
                int          oldProgress      = -1;
                using (CsvReader reader = new CsvReader(basestreamReader, true))
                {
                    while (reader.ReadNextRecord()) // go through csv and raw file to extract the info we want
                    {
                        int           scanNumber  = int.Parse(reader["Spectrum number"]);
                        string        filenameID  = reader["Filename/id"];
                        string        rawFileName = filenameID.Split('.')[0];
                        bool          isDecoy     = reader["DEFLINE"].StartsWith("DECOY_");
                        ThermoRawFile rawFile;
                        if (!RawFiles.TryGetValue(rawFileName, out rawFile))
                        {
                            throw new ArgumentException("Cannot find this raw file: " + rawFileName + ".raw");
                        }
                        if (!rawFile.IsOpen)
                        {
                            rawFile.Open();
                        }

                        int progress = (int)(100 * (double)basestreamReader.BaseStream.Position / basestreamReader.BaseStream.Length);
                        if (progress != oldProgress)
                        {
                            OnProgressUpdate(progress);
                            oldProgress = progress;
                        }

                        //// Set default fragmentation to CAD / HCD
                        //FragmentationMethod ScanFragMethod = filenameID.Contains(".ETD.")
                        //    ? FragmentationMethod.ETD
                        //    : FragmentationMethod.CAD;

                        //if (ScanFragMethod == FragmentationMethod.ETD)
                        //{
                        //    ScanFragMethod = FragmentationMethod.CAD;
                        //    scanNumber += ETDQuantPosition;
                        //}

                        // Get the scan object for the sequence ms2 scan
                        MsnDataScan quantitationMsnScan = rawFile[scanNumber] as MsnDataScan;

                        double purity = 1;
                        if (CalculatePurity)
                        {
                            double      mz             = quantitationMsnScan.PrecursorMz;
                            int         charge         = quantitationMsnScan.PrecursorCharge;
                            DoubleRange isolationRange = MzRange.FromDa(mz, PurityWindowInTh);

                            MSDataScan parentScan = rawFile[quantitationMsnScan.ParentScanNumber];
                            purity = DeterminePurity(parentScan, mz, charge, isolationRange);
                        }

                        if (quantitationMsnScan == null)
                        {
                            OnUpdateLog("Spectrum Number " + scanNumber + " is not a valid MS2 scan from: " + rawFile.FilePath + ". Skipping PSM...");
                            continue;
                        }

                        if (MS3Quant)
                        {
                            quantitationMsnScan = null;
                            // Look forward to find associated MS3 quant scan (based on parent scan number)
                            int ms3ScanNumber = scanNumber + 1;
                            while (ms3ScanNumber < rawFile.LastSpectrumNumber)
                            {
                                if (rawFile.GetParentSpectrumNumber(ms3ScanNumber) == scanNumber)
                                {
                                    quantitationMsnScan = rawFile[ms3ScanNumber] as MsnDataScan;
                                    break;
                                }
                                ms3ScanNumber++;
                            }

                            if (quantitationMsnScan == null)
                            {
                                OnUpdateLog("Cannot find a MS3 spectrum associated with spectrum number " + scanNumber + ". Skipping PSM...");
                                continue;
                            }
                        }

                        Tolerance Tolerance = quantitationMsnScan.MzAnalyzer == MZAnalyzerType.IonTrap2D ? ItMassTolerance : FtMassTolerance;
                        bool      isETD     = quantitationMsnScan.DissociationType == DissociationType.ETD;

                        double injectionTime = quantitationMsnScan.InjectionTime;
                        //var massSpectrum = quantitationMsnScan.MassSpectrum;
                        var thermoSpectrum = rawFile.GetLabeledSpectrum(quantitationMsnScan.SpectrumNumber);

                        double noise = 0;
                        if (NoisebandCap)
                        {
                            // Noise is pretty constant over a small region, find the noise of the center of all isobaric tags
                            MassRange range = new MassRange(UsedTags.Keys[0], UsedTags.Keys[UsedTags.Count - 1]);

                            if (thermoSpectrum != null)
                            {
                                var peak = thermoSpectrum.GetClosestPeak(range.Mean, 500);
                                if (peak != null)
                                {
                                    noise = peak.Noise;
                                }
                                else
                                {
                                    OnUpdateLog("Spectrum (#" + quantitationMsnScan.SpectrumNumber + ") has no m/z peaks. Skipping PSM...");
                                    continue;
                                }
                            }
                            else
                            {
                                OnUpdateLog("Spectrum (#" + quantitationMsnScan.SpectrumNumber + ") is low-resolution data without noise information. Skipping PSM...");
                                continue;
                            }
                        }

                        //Dictionary<TagInformation, QuantPeak> peaks = new Dictionary<TagInformation, QuantPeak>();
                        QuantPeak[] peaks = new QuantPeak[largestQuantPeak + 1];
                        // Read in the peak data
                        foreach (TagInformation tag in UsedTags.Values)
                        {
                            double tagMz = isETD
                                ? tag.MassEtd
                                : tag.MassCAD;

                            var peak = thermoSpectrum.GetClosestPeak(Tolerance.GetRange(tagMz));

                            QuantPeak qPeak = new QuantPeak(tag, peak, injectionTime, quantitationMsnScan, noise, peak == null && NoisebandCap);

                            peaks[tag.UniqueTagNumber] = qPeak;
                        }

                        PurityCorrect(peaks, isDecoy);

                        PSM psm = new PSM(filenameID, scanNumber, peaks, purity);
                        quantFile.AddPSM(psm);
                    }
                }

                // Dispose of all raw files
                foreach (ThermoRawFile rawFile in RawFiles.Values)
                {
                    rawFile.Dispose();
                }
                OnUpdateLog("PSMs loaded " + quantFile.Psms.Count);
                Log("PSMs Loaded:\t" + quantFile.Psms.Count);
                yield return(quantFile);
            }
        }
Exemplo n.º 25
0
 public MzmlScanWithPrecursor(int ScanNumber, MzmlMzSpectrum massSpectrum, int MsnOrder, bool isCentroid, Polarity Polarity, double RetentionTime, MzRange MzRange, string ScanFilter, MZAnalyzerType MzAnalyzer, double TotalIonCurrent, double selectedIonMz, int?selectedIonChargeStateGuess, double?selectedIonIntensity, double isolationMZ, double?isolationWidth, DissociationType dissociationType, int oneBasedPrecursorScanNumber, double?selectedIonGuessMonoisotopicMZ, double?injectionTime)
     : base(ScanNumber, MsnOrder, isCentroid, Polarity, RetentionTime, MzRange, ScanFilter, MzAnalyzer, TotalIonCurrent, selectedIonMz, selectedIonChargeStateGuess, selectedIonIntensity, isolationMZ, isolationWidth, dissociationType, oneBasedPrecursorScanNumber, selectedIonGuessMonoisotopicMZ, injectionTime, null)
 {
     this.MassSpectrum = massSpectrum;
 }
Exemplo n.º 26
0
        public static MsDataScan GetNextMsDataOneBasedScanFromConnection(StreamReader sr, HashSet <int> scanNumbersAlreadyObserved,
                                                                         IFilteringParams filterParams = null, int?alreadyKnownScanNumber = null)
        {
            List <double> mzs         = new List <double>();
            List <double> intensities = new List <double>();
            int           charge      = 2;          //default when unknown
            double        precursorMz = 0;
            double        rtInMinutes = double.NaN; //default when unknown

            int oldScanNumber = scanNumbersAlreadyObserved.Count > 0 ? scanNumbersAlreadyObserved.Max() : 0;
            int scanNumber    = alreadyKnownScanNumber.HasValue ? alreadyKnownScanNumber.Value : 0;

            // read the scan data
            while (sr.Peek() > 0)
            {
                string   line   = sr.ReadLine();
                string[] sArray = line.Split('=');

                if (String.IsNullOrWhiteSpace(line))
                {
                    continue;
                }

                if (char.IsDigit(line[0]) && sArray.Length == 1)
                {
                    ParsePeakLine(line, mzs, intensities);
                }
                else if (line.StartsWith("PEPMASS"))
                {
                    sArray      = sArray[1].Split(' ');
                    precursorMz = Convert.ToDouble(sArray[0], CultureInfo.InvariantCulture);
                }
                else if (line.StartsWith("CHARGE"))
                {
                    string entry = sArray[1];
                    charge = Convert.ToInt32(entry.Substring(0, entry.Length - 1));
                    if (entry[entry.Length - 1].Equals("-"))
                    {
                        charge *= -1;
                    }
                }
                else if (line.StartsWith("SCANS"))
                {
                    scanNumber = Convert.ToInt32(sArray[1]);
                }
                else if (line.StartsWith("RTINSECONDS"))
                {
                    rtInMinutes = Convert.ToDouble(sArray[sArray.Length - 1], CultureInfo.InvariantCulture) / 60.0;
                }
                else if (line.StartsWith("END IONS"))
                {
                    break;
                }
            }

            double[] mzArray        = mzs.ToArray();
            double[] intensityArray = intensities.ToArray();

            Array.Sort(mzArray, intensityArray);

            //Remove Zero Intensity Peaks
            double zeroEquivalentIntensity = 0.01;
            int    zeroIntensityCount      = intensityArray.Count(i => i < zeroEquivalentIntensity);
            int    intensityValueCount     = intensityArray.Count();

            if (zeroIntensityCount > 0 && zeroIntensityCount < intensityValueCount)
            {
                Array.Sort(intensityArray, mzArray);
                double[] nonZeroIntensities = new double[intensityValueCount - zeroIntensityCount];
                double[] nonZeroMzs         = new double[intensityValueCount - zeroIntensityCount];
                intensityArray = intensityArray.SubArray(zeroIntensityCount, intensityValueCount - zeroIntensityCount);
                mzArray        = mzArray.SubArray(zeroIntensityCount, intensityValueCount - zeroIntensityCount);
                Array.Sort(mzArray, intensityArray);
            }


            MzRange scanRange = new MzRange(mzArray[0], mzArray[mzArray.Length - 1]);

            // peak filtering
            if (filterParams != null && intensityArray.Length > 0 && filterParams.ApplyTrimmingToMsMs)
            {
                MsDataFile.WindowModeHelper(ref intensityArray, ref mzArray, filterParams, scanRange.Minimum, scanRange.Maximum);
            }

            MzSpectrum spectrum = new MzSpectrum(mzArray, intensityArray, false);

            if (scanNumber == 0)
            {
                scanNumber = oldScanNumber + 1;
            }

            scanNumbersAlreadyObserved.Add(scanNumber);

            return(new MsDataScan(spectrum, scanNumber, 2, true, charge > 0 ? Polarity.Positive : Polarity.Negative,
                                  rtInMinutes, scanRange, null, MZAnalyzerType.Unknown,
                                  intensities.Sum(), 0, null, null, precursorMz, charge, null, precursorMz, null,
                                  DissociationType.Unknown, null, precursorMz));
        }
Exemplo n.º 27
0
        public static void CreateAndWriteMyMzmlWithCalibratedSpectra(IMsDataFile <IMsDataScan <IMzSpectrum <IMzPeak> > > myMsDataFile, string outputFile, bool writeIndexed)
        {
            var mzML = new Generated.mzMLType()
            {
                version = "1",
                cvList  = new Generated.CVListType()
            };

            mzML.cvList.count = "1";
            mzML.cvList.cv    = new Generated.CVType[1];
            mzML.cvList.cv[0] = new Generated.CVType()
            {
                URI      = @"https://raw.githubusercontent.com/HUPO-PSI/psi-ms-CV/master/psi-ms.obo",
                fullName = "Proteomics Standards Initiative Mass Spectrometry Ontology",
                id       = "MS"
            };
            mzML.fileDescription = new Generated.FileDescriptionType()
            {
                fileContent = new Generated.ParamGroupType()
            };
            mzML.fileDescription.fileContent.cvParam    = new Generated.CVParamType[2];
            mzML.fileDescription.fileContent.cvParam[0] = new Generated.CVParamType()
            {
                accession = "MS:1000579" // MS1 Data
            };
            mzML.fileDescription.fileContent.cvParam[1] = new Generated.CVParamType()
            {
                accession = "MS:1000580" // MSn Data
            };
            mzML.softwareList = new Generated.SoftwareListType()
            {
                count    = "1",
                software = new Generated.SoftwareType[1]
            };

            // TODO: add the raw file fields
            mzML.softwareList.software[0] = new Generated.SoftwareType()
            {
                id      = "mzLib",
                version = "1",
                cvParam = new Generated.CVParamType[1]
            };
            mzML.softwareList.software[0].cvParam[0] = new Generated.CVParamType()
            {
                accession = "MS:1000799",
                value     = "mzLib"
            };

            // Leaving empty. Can't figure out the configurations.
            // ToDo: read instrumentConfigurationList from mzML file
            mzML.instrumentConfigurationList = new Generated.InstrumentConfigurationListType();

            mzML.dataProcessingList = new Generated.DataProcessingListType()
            {
                count          = "1",
                dataProcessing = new Generated.DataProcessingType[1]
            };
            // Only writing mine! Might have had some other data processing (but not if it is a raw file)
            // ToDo: read dataProcessingList from mzML file
            mzML.dataProcessingList.dataProcessing[0] = new Generated.DataProcessingType()
            {
                id = "mzLibProcessing"
            };
            mzML.run = new Generated.RunType()
            {
                chromatogramList = new Generated.ChromatogramListType()
                {
                    count        = "1",
                    chromatogram = new Generated.ChromatogramType[1]
                }
            };
            // ToDo: Finish the chromatogram writing!
            mzML.run.chromatogramList.chromatogram[0] = new Generated.ChromatogramType();

            mzML.run.spectrumList = new Generated.SpectrumListType()
            {
                count = (myMsDataFile.NumSpectra).ToString(CultureInfo.InvariantCulture),
                defaultDataProcessingRef = "mzLibProcessing",
                spectrum = new Generated.SpectrumType[myMsDataFile.NumSpectra]
            };

            // Loop over all spectra
            for (int i = 1; i <= myMsDataFile.NumSpectra; i++)
            {
                mzML.run.spectrumList.spectrum[i - 1] = new Generated.SpectrumType()
                {
                    defaultArrayLength = myMsDataFile.GetOneBasedScan(i).MassSpectrum.Size,

                    index = i.ToString(CultureInfo.InvariantCulture),
                    id    = myMsDataFile.GetOneBasedScan(i).OneBasedScanNumber.ToString(),

                    cvParam = new Generated.CVParamType[8]
                };
                mzML.run.spectrumList.spectrum[i - 1].cvParam[0] = new Generated.CVParamType();

                if (myMsDataFile.GetOneBasedScan(i).MsnOrder == 1)
                {
                    mzML.run.spectrumList.spectrum[i - 1].cvParam[0].accession = "MS:1000579";
                }
                else if (myMsDataFile.GetOneBasedScan(i) is IMsDataScanWithPrecursor <IMzSpectrum <IMzPeak> > )
                {
                    var scanWithPrecursor = myMsDataFile.GetOneBasedScan(i) as IMsDataScanWithPrecursor <IMzSpectrum <IMzPeak> >;
                    mzML.run.spectrumList.spectrum[i - 1].cvParam[0].accession = "MS:1000580";

                    // So needs a precursor!
                    mzML.run.spectrumList.spectrum[i - 1].precursorList = new Generated.PrecursorListType()
                    {
                        count     = 1.ToString(),
                        precursor = new Generated.PrecursorType[1]
                    };
                    mzML.run.spectrumList.spectrum[i - 1].precursorList.precursor[0] = new Generated.PrecursorType();
                    string precursorID = scanWithPrecursor.OneBasedPrecursorScanNumber.ToString();
                    mzML.run.spectrumList.spectrum[i - 1].precursorList.precursor[0].spectrumRef     = precursorID;
                    mzML.run.spectrumList.spectrum[i - 1].precursorList.precursor[0].selectedIonList = new Generated.SelectedIonListType()
                    {
                        count       = 1.ToString(),
                        selectedIon = new Generated.ParamGroupType[1]
                    };
                    mzML.run.spectrumList.spectrum[i - 1].precursorList.precursor[0].selectedIonList.selectedIon[0] = new Generated.ParamGroupType()
                    {
                        cvParam = new Generated.CVParamType[3]
                    };
                    // Selected ion MZ
                    mzML.run.spectrumList.spectrum[i - 1].precursorList.precursor[0].selectedIonList.selectedIon[0].cvParam[0] = new Generated.CVParamType()
                    {
                        name      = "selected ion m/z",
                        value     = scanWithPrecursor.SelectedIonMZ.ToString(CultureInfo.InvariantCulture),
                        accession = "MS:1000744"
                    };

                    // Charge State
                    if (scanWithPrecursor.SelectedIonChargeStateGuess.HasValue)
                    {
                        mzML.run.spectrumList.spectrum[i - 1].precursorList.precursor[0].selectedIonList.selectedIon[0].cvParam[1] = new Generated.CVParamType()
                        {
                            name      = "charge state",
                            value     = scanWithPrecursor.SelectedIonChargeStateGuess.Value.ToString(CultureInfo.InvariantCulture),
                            accession = "MS:1000041"
                        };
                    }

                    // Selected ion intensity
                    if (scanWithPrecursor.SelectedIonIntensity.HasValue)
                    {
                        mzML.run.spectrumList.spectrum[i - 1].precursorList.precursor[0].selectedIonList.selectedIon[0].cvParam[2] = new Generated.CVParamType()
                        {
                            name      = "peak intensity",
                            value     = scanWithPrecursor.SelectedIonIntensity.Value.ToString(CultureInfo.InvariantCulture),
                            accession = "MS:1000042"
                        };
                    }

                    MzRange isolationRange = scanWithPrecursor.IsolationRange;
                    mzML.run.spectrumList.spectrum[i - 1].precursorList.precursor[0].isolationWindow = new Generated.ParamGroupType()
                    {
                        cvParam = new Generated.CVParamType[3]
                    };
                    mzML.run.spectrumList.spectrum[i - 1].precursorList.precursor[0].isolationWindow.cvParam[0] = new Generated.CVParamType()
                    {
                        accession = "MS:1000827",
                        name      = "isolation window target m/z",
                        value     = isolationRange.Mean.ToString(CultureInfo.InvariantCulture)
                    };
                    mzML.run.spectrumList.spectrum[i - 1].precursorList.precursor[0].isolationWindow.cvParam[1] = new Generated.CVParamType()
                    {
                        accession = "MS:1000828",
                        name      = "isolation window lower offset",
                        value     = (isolationRange.Width / 2).ToString(CultureInfo.InvariantCulture)
                    };
                    mzML.run.spectrumList.spectrum[i - 1].precursorList.precursor[0].isolationWindow.cvParam[2] = new Generated.CVParamType()
                    {
                        accession = "MS:1000829",
                        name      = "isolation window upper offset",
                        value     = (isolationRange.Width / 2).ToString(CultureInfo.InvariantCulture)
                    };
                    mzML.run.spectrumList.spectrum[i - 1].precursorList.precursor[0].activation = new Generated.ParamGroupType()
                    {
                        cvParam = new Generated.CVParamType[1]
                    };
                    mzML.run.spectrumList.spectrum[i - 1].precursorList.precursor[0].activation.cvParam[0] = new Generated.CVParamType();

                    DissociationType dissociationType = scanWithPrecursor.DissociationType;

                    mzML.run.spectrumList.spectrum[i - 1].precursorList.precursor[0].activation.cvParam[0].accession = DissociationTypeAccessions[dissociationType];
                    mzML.run.spectrumList.spectrum[i - 1].precursorList.precursor[0].activation.cvParam[0].name      = DissociationTypeNames[dissociationType];
                }

                mzML.run.spectrumList.spectrum[i - 1].cvParam[1] = new Generated.CVParamType()
                {
                    name      = "ms level",
                    accession = "MS:1000511",
                    value     = myMsDataFile.GetOneBasedScan(i).MsnOrder.ToString(CultureInfo.InvariantCulture)
                };
                mzML.run.spectrumList.spectrum[i - 1].cvParam[2] = new Generated.CVParamType()
                {
                    name      = CentroidNames[myMsDataFile.GetOneBasedScan(i).IsCentroid],
                    accession = CentroidAccessions[myMsDataFile.GetOneBasedScan(i).IsCentroid]
                };
                if (PolarityNames.TryGetValue(myMsDataFile.GetOneBasedScan(i).Polarity, out string polarityName) && PolarityAccessions.TryGetValue(myMsDataFile.GetOneBasedScan(i).Polarity, out string polarityAccession))
                {
                    mzML.run.spectrumList.spectrum[i - 1].cvParam[3] = new Generated.CVParamType()
                    {
                        name      = polarityName,
                        accession = polarityAccession
                    };
                }
                // Spectrum title
                mzML.run.spectrumList.spectrum[i - 1].cvParam[4] = new Generated.CVParamType()
                {
                    name      = "spectrum title",
                    accession = "MS:1000796",
                    value     = myMsDataFile.GetOneBasedScan(i).OneBasedScanNumber.ToString()
                };
                if ((myMsDataFile.GetOneBasedScan(i).MassSpectrum.Size) > 0)
                {
                    // Lowest observed mz
                    mzML.run.spectrumList.spectrum[i - 1].cvParam[5] = new Generated.CVParamType()
                    {
                        name      = "lowest observed m/z",
                        accession = "MS:1000528",
                        value     = myMsDataFile.GetOneBasedScan(i).MassSpectrum.FirstX.ToString(CultureInfo.InvariantCulture)
                    };

                    // Highest observed mz
                    mzML.run.spectrumList.spectrum[i - 1].cvParam[6] = new Generated.CVParamType()
                    {
                        name      = "highest observed m/z",
                        accession = "MS:1000527",
                        value     = myMsDataFile.GetOneBasedScan(i).MassSpectrum.LastX.ToString(CultureInfo.InvariantCulture)
                    };
                }

                // Total ion current
                mzML.run.spectrumList.spectrum[i - 1].cvParam[7] = new Generated.CVParamType()
                {
                    name      = "total ion current",
                    accession = "MS:1000285",
                    value     = myMsDataFile.GetOneBasedScan(i).TotalIonCurrent.ToString(CultureInfo.InvariantCulture)
                };

                // Retention time
                mzML.run.spectrumList.spectrum[i - 1].scanList = new Generated.ScanListType()
                {
                    count = "1",
                    scan  = new Generated.ScanType[1]
                };
                mzML.run.spectrumList.spectrum[i - 1].scanList.scan[0] = new Generated.ScanType()
                {
                    cvParam = new Generated.CVParamType[3]
                };
                mzML.run.spectrumList.spectrum[i - 1].scanList.scan[0].cvParam[0] = new Generated.CVParamType()
                {
                    name          = "scan start time",
                    accession     = "MS:1000016",
                    value         = myMsDataFile.GetOneBasedScan(i).RetentionTime.ToString(CultureInfo.InvariantCulture),
                    unitCvRef     = "UO",
                    unitAccession = "UO:0000031",
                    unitName      = "minute"
                };
                mzML.run.spectrumList.spectrum[i - 1].scanList.scan[0].cvParam[1] = new Generated.CVParamType()
                {
                    name      = "filter string",
                    accession = "MS:1000512",
                    value     = myMsDataFile.GetOneBasedScan(i).ScanFilter
                };
                if (myMsDataFile.GetOneBasedScan(i).InjectionTime.HasValue)
                {
                    mzML.run.spectrumList.spectrum[i - 1].scanList.scan[0].cvParam[2] = new Generated.CVParamType()
                    {
                        name      = "ion injection time",
                        accession = "MS:1000927",
                        value     = myMsDataFile.GetOneBasedScan(i).InjectionTime.Value.ToString(CultureInfo.InvariantCulture)
                    };
                }
                if (myMsDataFile.GetOneBasedScan(i) is IMsDataScanWithPrecursor <IMzSpectrum <IMzPeak> > )
                {
                    var scanWithPrecursor = myMsDataFile.GetOneBasedScan(i) as IMsDataScanWithPrecursor <IMzSpectrum <IMzPeak> >;
                    if (scanWithPrecursor.SelectedIonMonoisotopicGuessMz.HasValue)
                    {
                        mzML.run.spectrumList.spectrum[i - 1].scanList.scan[0].userParam    = new Generated.UserParamType[1];
                        mzML.run.spectrumList.spectrum[i - 1].scanList.scan[0].userParam[0] = new Generated.UserParamType()
                        {
                            name  = "[mzLib]Monoisotopic M/Z:",
                            value = scanWithPrecursor.SelectedIonMonoisotopicGuessMz.Value.ToString(CultureInfo.InvariantCulture)
                        };
                    }
                }

                mzML.run.spectrumList.spectrum[i - 1].scanList.scan[0].scanWindowList = new Generated.ScanWindowListType()
                {
                    count      = 1,
                    scanWindow = new Generated.ParamGroupType[1]
                };
                mzML.run.spectrumList.spectrum[i - 1].scanList.scan[0].scanWindowList.scanWindow[0] = new Generated.ParamGroupType()
                {
                    cvParam = new Generated.CVParamType[2]
                };
                mzML.run.spectrumList.spectrum[i - 1].scanList.scan[0].scanWindowList.scanWindow[0].cvParam[0] = new Generated.CVParamType()
                {
                    name      = "scan window lower limit",
                    accession = "MS:1000501",
                    value     = myMsDataFile.GetOneBasedScan(i).ScanWindowRange.Minimum.ToString(CultureInfo.InvariantCulture)
                };
                mzML.run.spectrumList.spectrum[i - 1].scanList.scan[0].scanWindowList.scanWindow[0].cvParam[1] = new Generated.CVParamType()
                {
                    name      = "scan window upper limit",
                    accession = "MS:1000500",
                    value     = myMsDataFile.GetOneBasedScan(i).ScanWindowRange.Maximum.ToString(CultureInfo.InvariantCulture)
                };
                mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList = new Generated.BinaryDataArrayListType()
                {
                    // ONLY WRITING M/Z AND INTENSITY DATA, NOT THE CHARGE! (but can add charge info later)
                    // CHARGE (and other stuff) CAN BE IMPORTANT IN ML APPLICATIONS!!!!!
                    count           = 2.ToString(),
                    binaryDataArray = new Generated.BinaryDataArrayType[5]
                };

                // M/Z Data
                mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[0] = new Generated.BinaryDataArrayType()
                {
                    binary = myMsDataFile.GetOneBasedScan(i).MassSpectrum.Get64BitXarray()
                };
                mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[0].encodedLength = (4 * Math.Ceiling(((double)mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[0].binary.Length / 3))).ToString(CultureInfo.InvariantCulture);
                mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[0].cvParam       = new Generated.CVParamType[3];
                mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[0].cvParam[0]    = new Generated.CVParamType()
                {
                    accession = "MS:1000514",
                    name      = "m/z array"
                };
                mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[0].cvParam[1] = new Generated.CVParamType()
                {
                    accession = "MS:1000523",
                    name      = "64-bit float"
                };
                mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[0].cvParam[2] = new Generated.CVParamType()
                {
                    accession = "MS:1000576",
                    name      = "no compression"
                };

                // Intensity Data
                mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[1] = new Generated.BinaryDataArrayType()
                {
                    binary = myMsDataFile.GetOneBasedScan(i).MassSpectrum.Get64BitYarray()
                };
                mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[1].encodedLength = (4 * Math.Ceiling(((double)mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[1].binary.Length / 3))).ToString(CultureInfo.InvariantCulture);
                mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[1].cvParam       = new Generated.CVParamType[3];
                mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[1].cvParam[0]    = new Generated.CVParamType()
                {
                    accession = "MS:1000515",
                    name      = "intensity array"
                };
                mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[1].cvParam[1] = new Generated.CVParamType()
                {
                    accession = "MS:1000523",
                    name      = "64-bit float"
                };
                mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[1].cvParam[2] = new Generated.CVParamType()
                {
                    accession = "MS:1000576",
                    name      = "no compression"
                };
                if (myMsDataFile.GetOneBasedScan(i).NoiseData != null)
                {
                    // mass
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[2] = new Generated.BinaryDataArrayType()
                    {
                        binary = myMsDataFile.GetOneBasedScan(i).Get64BitNoiseDataMass()
                    };
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[2].encodedLength = (4 * Math.Ceiling(((double)mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[2].binary.Length / 3))).ToString(CultureInfo.InvariantCulture);
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[2].cvParam       = new Generated.CVParamType[3];
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[2].cvParam[0]    = new Generated.CVParamType()
                    {
                        accession = "MS:1000786",
                        name      = "non-standard data array"
                    };
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[2].cvParam[1] = new Generated.CVParamType()
                    {
                        accession = "MS:1000523",
                        name      = "64-bit float"
                    };
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[2].cvParam[2] = new Generated.CVParamType()
                    {
                        accession = "MS:1000576",
                        name      = "no compression"
                    };
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[2].userParam    = new Generated.UserParamType[1];
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[2].userParam[0] = new Generated.UserParamType()
                    {
                        name  = "kelleherCustomType",
                        value = "noise m/z"
                    };

                    // noise
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[3] = new Generated.BinaryDataArrayType()
                    {
                        binary = myMsDataFile.GetOneBasedScan(i).Get64BitNoiseDataNoise()
                    };
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[3].encodedLength = (4 * Math.Ceiling(((double)mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[3].binary.Length / 3))).ToString(CultureInfo.InvariantCulture);
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[3].cvParam       = new Generated.CVParamType[3];
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[3].cvParam[0]    = new Generated.CVParamType()
                    {
                        accession = "MS:1000786",
                        name      = "non-standard data array"
                    };
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[3].cvParam[1] = new Generated.CVParamType()
                    {
                        accession = "MS:1000523",
                        name      = "64-bit float"
                    };
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[3].cvParam[2] = new Generated.CVParamType()
                    {
                        accession = "MS:1000576",
                        name      = "no compression"
                    };
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[3].userParam    = new Generated.UserParamType[1];
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[3].userParam[0] = new Generated.UserParamType()
                    {
                        name  = "kelleherCustomType",
                        value = "noise baseline"
                    };

                    // baseline
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[4] = new Generated.BinaryDataArrayType()
                    {
                        binary = myMsDataFile.GetOneBasedScan(i).Get64BitNoiseDataBaseline()
                    };
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[4].encodedLength = (4 * Math.Ceiling(((double)mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[4].binary.Length / 3))).ToString(CultureInfo.InvariantCulture);
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[4].cvParam       = new Generated.CVParamType[3];
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[4].cvParam[0]    = new Generated.CVParamType()
                    {
                        accession = "MS:1000786",
                        name      = "non-standard data array"
                    };
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[4].cvParam[1] = new Generated.CVParamType()
                    {
                        accession = "MS:1000523",
                        name      = "64-bit float"
                    };
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[4].cvParam[2] = new Generated.CVParamType()
                    {
                        accession = "MS:1000576",
                        name      = "no compression"
                    };
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[4].userParam    = new Generated.UserParamType[1];
                    mzML.run.spectrumList.spectrum[i - 1].binaryDataArrayList.binaryDataArray[4].userParam[0] = new Generated.UserParamType()
                    {
                        name  = "kelleherCustomType",
                        value = "noise intensity"
                    };
                }
            }

            if (writeIndexed)
            {
                throw new NotImplementedException("Writing indexed mzMLs not yet supported");
            }
            else
            {
                using (TextWriter writer = new StreamWriter(outputFile))
                {
                    mzmlSerializer.Serialize(writer, mzML);
                }
            }
        }
Exemplo n.º 28
0
 public Chromatogram(MzKey mzKey, MzRange mzRange)
 {
     MzKey   = mzKey;
     MzRange = mzRange;
     Points  = new List <ChromatogramPoint>();
 }
Exemplo n.º 29
0
        private void CleanSpectrum(Spectrum spectrum)
        {
            List<MzRange> ranges = new List<MzRange>();
            double precursor_mz = spectrum.PrecursorMZ.Value;

            if (cleanPrecursor
                || (enableEtdPreProcessing && (spectrum.ScanType == ScanType.ETD || spectrum.ScanType == ScanType.ECD)))
            {
                double half_width = spectrum.Parent.GetIsolationWidth(spectrum.ScanNumber) / 2.0;
                MzRange range = new MzRange(precursor_mz - half_width, precursor_mz + half_width);
                ranges.Add(range);
            }
            if (enableEtdPreProcessing && (spectrum.ScanType == ScanType.ETD || spectrum.ScanType == ScanType.ECD))
            {
                if (spectrum.Charge.HasValue)
                {
                    int charge = spectrum.Charge.Value;
                    if (charge < 0)
                    {
                        // NETD TODO
                    }
                    else
                    {
                        // ETD
                        for (int reduced_precursor_charge = 1; reduced_precursor_charge < charge; reduced_precursor_charge++)
                        {
                            double cr_mz = MZFromMass(precursor_mz, reduced_precursor_charge);
                            double min = cr_mz - 2; // TODO make variable
                            double max = cr_mz + 2;
                            ranges.Add(new MzRange(min, max));
                        }
                    }
                }
            }
            spectrum.CleanSpectrum(ranges);
        }
Exemplo n.º 30
0
 public double[,] GetChro(string scanFilter, MzRange range, double startTime, double endTime, Smoothing smoothing = Smoothing.None, int smoothingPoints = 3)
 {
     object chro = null;
     object flags =null;
     int size = 0;
     string mzrange = range.Minimum.ToString("F4") + "-" + range.Maximum.ToString("F4");
     _rawConnection.GetChroData(0, 0, 0, scanFilter, mzrange, string.Empty, 0.0, startTime, endTime, (int)smoothing, smoothingPoints, ref chro, ref flags, ref size);
     return (double[,])chro;
 }
        public List <DeconvolutedEnvelope> GetEnvelopeCandidates(MzSpectrum spectrum, MzRange mzRange, List <int> optionalIndicies = null)
        {
            List <DeconvolutedEnvelope> envelopeCandidates = new List <DeconvolutedEnvelope>();
            List <DeconvolutedPeak>     peaksBuffer        = new List <DeconvolutedPeak>();
            HashSet <double>            mzsClaimed         = new HashSet <double>(); // this is empty, no m/z peaks have been claimed yet
            HashSet <int> potentialChargeStates            = new HashSet <int>();

            // get list of envelope candidates for this scan
            for (int p = 0; p < spectrum.XArray.Length; p++)
            {
                double mz = spectrum.XArray[p];

                if (optionalIndicies != null && !optionalIndicies.Contains(p))
                {
                    continue;
                }

                // check to see if this peak is in the m/z deconvolution range
                if (mz < mzRange.Minimum)
                {
                    continue;
                }
                else if (mz > mzRange.Maximum)
                {
                    break;
                }

                // get rough list of charge states to check for based on m/z peaks around this peak
                potentialChargeStates = GetPotentialChargeStates(potentialChargeStates, spectrum, p);

                // examine different charge state possibilities and get corresponding envelope candidates
                foreach (int z in potentialChargeStates)
                {
                    DeconvolutedEnvelope candidateEnvelope = GetIsotopicEnvelope(spectrum, p, z, peaksBuffer, mzsClaimed);

                    if (candidateEnvelope != null)
                    {
                        envelopeCandidates.Add(candidateEnvelope);
                    }
                }
            }

            return(envelopeCandidates);
        }
Exemplo n.º 32
0
        public static MsDataScan GetOneBasedScan(IRawDataPlus rawFile, IFilteringParams filteringParams, int scanNumber)
        {
            var filter = rawFile.GetFilterForScanNumber(scanNumber);

            string scanFilterString = filter.ToString();
            int    msOrder          = (int)filter.MSOrder;

            if (msOrder < 1 || msOrder > 10)
            {
                throw new MzLibException("Unknown MS Order (" + msOrder + ") for scan number " + scanNumber);
            }

            string     nativeId = "controllerType=0 controllerNumber=1 scan=" + scanNumber;
            MzSpectrum spectrum = GetSpectrum(rawFile, filteringParams, scanNumber, scanFilterString, msOrder);

            var     scanStats       = rawFile.GetScanStatsForScanNumber(scanNumber);
            double  scanRangeHigh   = scanStats.HighMass;
            double  scanRangeLow    = scanStats.LowMass;
            MzRange scanWindowRange = new MzRange(scanRangeLow, scanRangeHigh);

            double?          ionInjectionTime = null;
            double?          precursorSelectedMonoisotopicIonMz = null;
            int?             selectedIonChargeState             = null;
            double?          ms2IsolationWidth   = null;
            int?             precursorScanNumber = null;
            double?          isolationMz         = null;
            string           HcdEnergy           = null;
            ActivationType   activationType      = ActivationType.Any;       // thermo enum
            DissociationType dissociationType    = DissociationType.Unknown; // mzLib enum

            var trailer = rawFile.GetTrailerExtraInformation(scanNumber);

            string[] labels = trailer.Labels;
            string[] values = trailer.Values;

            for (int i = 0; i < trailer.Labels.Length; i++)
            {
                if (labels[i].StartsWith("Ion Injection Time (ms)", StringComparison.Ordinal))
                {
                    ionInjectionTime = double.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                       (double?)null :
                                       double.Parse(values[i], CultureInfo.InvariantCulture);
                }

                if (msOrder < 2)
                {
                    continue;
                }

                if (labels[i].StartsWith("MS" + msOrder + " Isolation Width", StringComparison.Ordinal))
                {
                    ms2IsolationWidth = double.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                        (double?)null :
                                        double.Parse(values[i], CultureInfo.InvariantCulture);
                }
                if (labels[i].StartsWith("Monoisotopic M/Z", StringComparison.Ordinal))
                {
                    precursorSelectedMonoisotopicIonMz = double.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                                         (double?)null :
                                                         double.Parse(values[i], CultureInfo.InvariantCulture);
                }
                if (labels[i].StartsWith("Charge State", StringComparison.Ordinal))
                {
                    selectedIonChargeState = int.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                             (int?)null :
                                             int.Parse(values[i], CultureInfo.InvariantCulture);
                }
                if (labels[i].StartsWith("Master Scan Number", StringComparison.Ordinal) ||
                    labels[i].StartsWith("Master Index", StringComparison.Ordinal))
                {
                    precursorScanNumber = int.Parse(values[i], CultureInfo.InvariantCulture) <= 1 ?
                                          (int?)null :
                                          int.Parse(values[i], CultureInfo.InvariantCulture);
                }
                if (labels[i].StartsWith("HCD Energy:", StringComparison.Ordinal))
                {
                    HcdEnergy = values[i];
                }
            }

            if (msOrder > 1)
            {
                var scanEvent = rawFile.GetScanEventForScanNumber(scanNumber);
                var reaction  = scanEvent.GetReaction(0);
                isolationMz    = reaction.PrecursorMass;
                activationType = reaction.ActivationType;

                dissociationType = GetDissociationType(activationType);

                // thermo does not have an enum value for ETHcD, so this needs to be detected from the scan filter
                if (scanFilterString.Contains("@etd", StringComparison.OrdinalIgnoreCase) &&
                    scanFilterString.Contains("@hcd", StringComparison.OrdinalIgnoreCase))
                {
                    dissociationType = DissociationType.EThcD;
                }

                if (ms2IsolationWidth == null)
                {
                    ms2IsolationWidth = reaction.IsolationWidth;
                }

                if (precursorScanNumber == null)
                {
                    // we weren't able to get the precursor scan number, so we'll have to guess;
                    // loop back to find precursor scan
                    // (assumed to be the first scan before this scan with an MS order of this scan's MS order - 1)
                    // e.g., if this is an MS2 scan, find the first MS1 scan before this and assume that's the precursor scan
                    for (int i = scanNumber; i >= 1; i--)
                    {
                        var possiblePrecursorScanFilter = rawFile.GetFilterForScanNumber(i);
                        int order = (int)possiblePrecursorScanFilter.MSOrder;
                        if (order == msOrder - 1)
                        {
                            precursorScanNumber = i;
                            break;
                        }
                    }

                    if (precursorScanNumber == null)
                    {
                        throw new MzLibException("Could not get precursor for scan #" + scanNumber);
                    }
                }
            }

            // at this point, we have the m/z value of the species that got fragmented, from the scan header
            // this section of the code finds that peak in the spectrum (it's actual intensity and centroided m/z values)
            // the intention is to remove any rounding issues caused by what is in the scan header and what is observable in the spectrum
            double?selectedIonIntensity = null;

            if (isolationMz.HasValue)
            {
                if (spectrum.Size != 0)
                {
                    int closest = spectrum.GetClosestPeakIndex(isolationMz.Value);

                    double mz        = spectrum.XArray[closest];
                    double intensity = spectrum.YArray[closest];

                    if (Math.Abs(mz - isolationMz.Value) < 0.1)
                    {
                        selectedIonIntensity = intensity;
                        isolationMz          = mz;
                    }
                }
            }

            return(new MsDataScan(
                       massSpectrum: spectrum,
                       oneBasedScanNumber: scanNumber,
                       msnOrder: msOrder,
                       isCentroid: true,
                       polarity: GetPolarity(filter.Polarity),
                       retentionTime: rawFile.RetentionTimeFromScanNumber(scanNumber),
                       scanWindowRange: scanWindowRange,
                       scanFilter: scanFilterString,
                       mzAnalyzer: GetMassAnalyzerType(filter.MassAnalyzer),
                       totalIonCurrent: spectrum.SumOfAllY,
                       injectionTime: ionInjectionTime,
                       noiseData: null, //TODO: implement reading noise data. it's unused right now, so it's just left as null
                       nativeId: nativeId,
                       selectedIonMz: isolationMz,
                       selectedIonChargeStateGuess: selectedIonChargeState,
                       selectedIonIntensity: selectedIonIntensity,
                       isolationMZ: isolationMz,
                       isolationWidth: ms2IsolationWidth,
                       dissociationType: dissociationType,
                       oneBasedPrecursorScanNumber: precursorScanNumber,
                       selectedIonMonoisotopicGuessMz: precursorSelectedMonoisotopicIonMz,
                       hcdEnergy: HcdEnergy));
        }
Exemplo n.º 33
0
        public ThermoScan(int oneBasedScanNumber, ThermoSpectrum massSpectrum, int msnOrder, Polarity polarity, double retentionTime, MzRange scanWindowRange, string scanFilter, MZAnalyzerType mzAnalyzer, double totalIonCurrent, double?injectionTime, double[,] noiseData, string nativeId)
            : base(massSpectrum, oneBasedScanNumber, msnOrder, true, polarity, retentionTime, scanWindowRange, scanFilter, mzAnalyzer, totalIonCurrent, injectionTime, noiseData, nativeId)

        {
        }