Example #1
8
 private static double? GetPrecursorCollisionEnergy(Precursor precursor)
 {
     var param = precursor.activation.cvParam(CVID.MS_collision_energy);
     if (param.empty())
         return null;
     return (double)param.value;
 }
Example #2
0
        private void WritePrecursor(Precursor pc)
        {
            writer.WriteStartElement("precursor");

            if (pc.SpectrumReference != null)
            {
                WriteSpectrumRef(pc.SpectrumReference);
            }

            WriteList("selectedIonList", pc.SelectedIons, WriteSelectedIon);

            if (pc.IsolationWindow != null)
            {
                WriteIsolationWindow(pc.IsolationWindow);
            }

            if (pc.Activation != null)
            {
                writer.WriteStartElement("activation");
                WriteParamGroup(pc.Activation);
                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }
Example #3
0
        protected int getPrecursorCharge(Spectrum spectrum)
        {
            int result     = 0;
            var retryTimes = 3;

            while (result < 0 && retryTimes > 0)
            {
                try
                {
                    Precursor precursor = spectrum.precursors[0];
                    if (precursor.selectedIons == null || precursor.selectedIons[0].cvParamChild(CVID.MS_charge_state)
                        .cvid.Equals(CVID.CVID_Unknown))
                    {
                        return(0);
                    }

                    result = Int32.Parse(precursor.selectedIons[0].cvParamChild(CVID.MS_charge_state).value.ToString());
                }
                catch (FormatException e)
                {
                    jobInfo.log("Charge-重试次数-" + retryTimes + "-Result:" + result);
                    jobInfo.log(e.StackTrace);
                }
                retryTimes--;
            }

            if (result < 0)
            {
                throw new Exception("Parse Integer Error:" + result);
            }
            return(result);
        }
Example #4
0
        protected double getPrecursorIsolationWindowParams(Spectrum spectrum, CVID cvid)
        {
            double result     = -1;
            var    retryTimes = 3;

            while (result < 0 && retryTimes > 0)
            {
                try
                {
                    Precursor precursor = spectrum.precursors[0];
                    result = Double.Parse(precursor.isolationWindow.cvParamChild(cvid).value.ToString());
                }
                catch (FormatException e)
                {
                    jobInfo.log(cvid + "-重试次数-" + retryTimes + "-Result:" + result);
                    jobInfo.log(e.StackTrace);
                }
                retryTimes--;
            }

            if (result < 0)
            {
                throw new Exception("Parse Double Error:" + result);
            }
            return(result);
        }
Example #5
0
        /// <summary>
        /// Check and set attribute based on attributes dictionary
        /// </summary>
        /// <param name="attribute"></param>
        /// <param name="value"></param>
        private void SetAttribute(CVParam cvParam, Scan scan, Precursor precursor)
        {
            string member = "";
            object o      = null;

            if (scanAttrs.ContainsKey(cvParam.Name))
            {
                member = scanAttrs[cvParam.Name];
                o      = scan;
            }
            else if (precursorAttrs.ContainsKey(cvParam.Name))
            {
                member = precursorAttrs[cvParam.Name];
                o      = precursor;
            }

            if (member == "")
            {
                return;
            }

            var prop  = o.GetType().GetProperty(member);
            var value = Convert.ChangeType(cvParam.Value, prop.PropertyType);

            prop.SetValue(o, value);
        }
Example #6
0
        /// <summary>
        /// Open the given file and import scans into the reader.
        /// </summary>
        /// <returns></returns>
        public IEnumerator GetEnumerator() {
            // Reset to beginning of document.
            Reader = XmlReader.Create(FilePath);
            Scan scan = null;
            while(Reader.Read()) {
                switch (Reader.NodeType) {
                    case XmlNodeType.Element:

                        if (scan != null && (Reader.Name == "scan" || Reader.Name == "index")) {
                            // mzXML can have nested scans, so returning scans here.
                            yield return scan;
                        }

                        if (Reader.Name == "scan") {
                            scan = new Scan();
                            while (Reader.MoveToNextAttribute()) {
                                SetAttribute(scan, Reader.Name, Reader.Value);
                                if (Reader.Name == "filterLine") {
                                    int spacePos = scan.FilterLine.IndexOf(' ');
                                    if (spacePos > 0) {
                                        // Setting detector after setting filterLine in SetAttribute()
                                        scan.DetectorType = scan.FilterLine.Substring(0, spacePos).ToUpper();
                                    }
                                }
                            }
                        }
                        if (Reader.Name == "peaks" && scan != null) {
                            scan.Centroids = ReadPeaks(Reader.ReadElementContentAsString(), scan.PeakCount);
                        }
                        else if (Reader.Name == "precursorMz" && scan != null) {
                            var precursor = new Precursor();
                            while (Reader.MoveToNextAttribute()) {
                                if (Reader.Name == "precursorCharge") {
                                    precursor.Charge = int.Parse(Reader.Value);
                                }
                                else if(Reader.Name == "precursorIntensity") {
                                    precursor.Intensity = double.Parse(Reader.Value);
                                }
                                else if(Reader.Name == "isolationWidth") {
                                    precursor.IsolationWidth = double.Parse(Reader.Value);
                                }
                                else if(Reader.Name == "isolationMz") {
                                    precursor.IsolationMz = double.Parse(Reader.Value);
                                }
                                else {
                                    SetAttribute(scan, Reader.Name, Reader.Value);
                                }
                            }
                            Reader.MoveToContent();
                            precursor.Mz = double.Parse(Reader.ReadElementContentAsString());
                            precursor.OriginalMz = precursor.Mz;
                            precursor.OriginalCharge = precursor.Charge;
                            scan.Precursors.Add(precursor);
                        }
                        break;
                    default:
                    break;
                }
            }
        }
Example #7
0
 public Precursor(Precursor precursor)
 {
     Mz                   = precursor.Mz;
     Intensity            = precursor.Intensity;
     Charge               = precursor.Charge;
     OriginalMz           = precursor.OriginalMz;
     OriginalCharge       = precursor.OriginalCharge;
     IsolationMz          = precursor.IsolationMz;
     IsolationWidth       = precursor.IsolationWidth;
     IsolationSpecificity = precursor.IsolationSpecificity;
 }
Example #8
0
        private List <Protein> GetProteinsFromSkyline()
        {
            var     result = new List <Protein>();
            IReport reportTrackINTargets = _toolClient.GetReport("BLR TrackIN Targets");
            var     ProteinsQ            = from reportRow in reportTrackINTargets.Cells
                                           where string.IsNullOrEmpty(reportRow[0]) != true
                                           group reportRow by reportRow[0] into ProteintGroup
                                           select new
            {
                Protein  = ProteintGroup.Key,
                Peptides = from reportRow in ProteintGroup
                           group reportRow by reportRow[1] into PeptideGroup
                           select new
                {
                    Peptide    = PeptideGroup.Key,
                    Precursors = from reportRow in PeptideGroup
                                 group reportRow by new { Isotope = reportRow[2], Precursor = reportRow[3] } into PrecursorGroup
                    select new
                    {
                        Isotope     = PrecursorGroup.Key.Isotope,
                        PrecursorMZ = PrecursorGroup.Key.Precursor,
                        ProductMZ   = from reportRow in PrecursorGroup
                                      select reportRow[4]
                    }
                }
            };

            foreach (var prot in ProteinsQ)
            {
                Protein protein = new Protein();
                protein.Name = prot.Protein;
                foreach (var pept in prot.Peptides)
                {
                    Peptide peptide = new Peptide();
                    peptide.Name = pept.Peptide;
                    foreach (var prec in pept.Precursors)
                    {
                        Precursor precursor = new Precursor();
                        precursor.IsotopeLabelType = prec.Isotope;
                        precursor.PrecursorMZ      = Convert.ToDouble(prec.PrecursorMZ);
                        foreach (var prod in prec.ProductMZ)
                        {
                            precursor.Products.Add(Convert.ToDouble(prod));
                        }
                        peptide.Precursors.Add(precursor);
                    }
                    protein.Peptides.Add(peptide);
                }
                result.Add(protein);
            }
            return(result);
        }
Example #9
0
        /// <summary>
        /// Overload to handle all available scans allowing for Ms1 inclusion of before + after
        /// </summary>
        /// <param name="AllScans"></param>
        /// <param name="DependentScan"></param>
        /// <param name="Number_Of_Scans_To_Average"></param>
        public static void Run(ref List <Scan> scans, MonocleOptions Options)
        {
            foreach (Scan scan in scans)
            {
                if (scan.MsOrder != Options.MS_Level)
                {
                    continue;
                }

                if (scan.PrecursorMasterScanNumber <= 0)
                {
                    Console.WriteLine(String.Format("Scan {0} does not have a precursor scan number assigned.", scan.ScanNumber));
                    continue;
                }

                Scan precursorScan = scans[scan.PrecursorMasterScanNumber - 1];
                var  nearbyScans   = GetNearbyScans(ref scans, precursorScan, Options);

                // For low-res scans, or if ForceCharges is true, generate precursors with
                // a range of charges given by the ChargeRangeUnknown option.
                bool lowResPrecursor = precursorScan.FilterLine.Contains("ITMS");
                if (lowResPrecursor || Options.ForceCharges)
                {
                    int range      = 1 + Options.ChargeRangeUnknown.High - Options.ChargeRangeUnknown.Low;
                    var precursors = new List <Precursor>(range);
                    foreach (var precursor in scan.Precursors)
                    {
                        for (int z = Options.ChargeRangeUnknown.Low; z <= Options.ChargeRangeUnknown.High; ++z)
                        {
                            var p = new Precursor(precursor);
                            p.Charge = z;
                            precursors.Add(p);
                        }
                    }
                    scan.Precursors = precursors;
                }

                if (!Options.SkipMono && !lowResPrecursor)
                {
                    foreach (var precursor in scan.Precursors)
                    {
                        if (!Options.Charge_Detection && precursor.Charge == 0)
                        {
                            Console.WriteLine(String.Format("Scan {0} does not have a charge state assigned.  Charge detection enabled.", scan.ScanNumber));
                        }
                        Run(nearbyScans, precursorScan, precursor, Options);
                    }
                }
            }
        }
Example #10
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = (Client != null ? Client.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (IntensityModel != null ? IntensityModel.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (RTModel != null ? RTModel.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Settings != null ? Settings.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Precursor != null ? Precursor.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Peptide != null ? Peptide.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ NCE;
         return(hashCode);
     }
 }
        public TransitionGroupDocNode UpdatePrecursor(IdentityPath parent, TransitionGroupDocNode precursorDocNode)
        {
            CheckCancelled();
            AnnotationUpdater updater;

            _annotationUpdaters.TryGetValue(AnnotationDef.AnnotationTarget.precursor, out updater);
            IdentityPath identityPath = new IdentityPath(parent, precursorDocNode.TransitionGroup);

            if (updater != null || _precursorResultUpdater != null)
            {
                var precursor = new Precursor(SkylineDataSchema, identityPath);
                if (updater != null)
                {
                    var annotations = updater.UpdateAnnotations(precursorDocNode.Annotations, precursor);
                    if (!Equals(annotations, precursorDocNode.Annotations))
                    {
                        precursorDocNode = (TransitionGroupDocNode)precursorDocNode.ChangeAnnotations(annotations);
                    }
                }

                if (_precursorResultUpdater != null)
                {
                    var newResults = _precursorResultUpdater.Update(precursorDocNode.Results, precursor.Results);
                    precursorDocNode = precursorDocNode.ChangeResults(newResults);
                }
            }

            if (!RecurseTransitions)
            {
                return(precursorDocNode);
            }

            var newChildren = precursorDocNode.Transitions
                              .Select(transition => UpdateTransition(identityPath, transition)).ToArray();

            if (!ArrayUtil.ReferencesEqual(precursorDocNode.Children, newChildren))
            {
                precursorDocNode = (TransitionGroupDocNode)precursorDocNode.ChangeChildren(newChildren);
            }

            return(precursorDocNode);
        }
Example #12
0
        /// <summary>
        /// Run a single Monocle scan.
        /// </summary>
        /// <param name="Ms1ScansCentroids"></param>
        /// <param name="ParentScan"></param>
        /// <param name="precursor"></param>
        public static void Run(List <Scan> Ms1ScansCentroids, Scan ParentScan, Precursor precursor, MonocleOptions Options)
        {
            double precursorMz = precursor.IsolationMz;

            if (precursorMz < 1)
            {
                precursorMz = precursor.Mz;
            }
            int precursorCharge = precursor.Charge;

            if (Options.UseMostIntense && precursor.IsolationWidth > 0)
            {
                // Re-assign the precursor m/z to that of the most intense peak in the isolation window.
                int peakIndex = PeakMatcher.MostIntenseIndex(ParentScan, precursor.IsolationMz, precursor.IsolationWidth / 2, PeakMatcher.DALTON);
                if (peakIndex >= 0)
                {
                    precursorMz = ParentScan.Centroids[peakIndex].Mz;
                }
            }

            // Search for ion in parent scan, use parent ion mz for future peaks
            int index = PeakMatcher.Match(ParentScan, precursorMz, 50, PeakMatcher.PPM);

            if (index >= 0)
            {
                precursorMz = ParentScan.Centroids[index].Mz;
            }

            // For charge detection
            int           bestCharge          = 0;
            double        bestScore           = -1;
            int           bestIndex           = 0;
            List <double> bestPeaks           = new List <double>();
            List <double> bestPeakIntensities = new List <double>();

            //Create new class to maintain ref class options
            ChargeRange chargeRange = new ChargeRange(precursorCharge, precursorCharge);

            if (Options.Charge_Detection || precursorCharge == 0)
            {
                chargeRange.Low  = Options.Charge_Range.Low;
                chargeRange.High = Options.Charge_Range.High;
            }

            for (int charge = chargeRange.Low; charge <= chargeRange.High; charge++)
            {
                // Restrict number of isotopes to consider based on precursor mass.
                double mass         = precursor.Mz * charge;
                var    isotopeRange = new IsotopeRange(mass);

                // Generate expected relative intensities.
                List <double> expected = PeptideEnvelopeCalculator.GetTheoreticalEnvelope(precursorMz, charge, isotopeRange.CompareSize);
                Vector.Scale(expected);

                PeptideEnvelope envelope = PeptideEnvelopeExtractor.Extract(Ms1ScansCentroids, precursorMz, charge, isotopeRange.Left, isotopeRange.Isotopes);

                // Get best match using dot product.
                // Limit the number of isotopeRange peaks to test
                for (int i = 0; i < (isotopeRange.Isotopes - (isotopeRange.CompareSize - 1)); ++i)
                {
                    List <double> observed = envelope.averageIntensity.GetRange(i, expected.Count);
                    Vector.Scale(observed);
                    PeptideEnvelopeExtractor.ScaleByPeakCount(observed, envelope, i);
                    double score = Vector.Dot(observed, expected);

                    // add 5% to give bias toward left peaks.
                    if (score > bestScore * 1.05)
                    {
                        bestScore = score;
                        if (score > 0.1)
                        {
                            // A peak to the left is included, so add
                            // offset to get monoisotopic index.
                            bestIndex           = i + 1;
                            bestCharge          = charge;
                            bestPeaks           = envelope.mzs[bestIndex];
                            bestPeakIntensities = envelope.intensities[bestIndex];
                        }
                    }
                }
            } // end charge for loop

            if (bestCharge > 0)
            {
                precursor.Charge = bestCharge;
            }

            // Calculate m/z
            if (bestPeaks.Count > 0)
            {
                precursor.Mz = Vector.WeightedAverage(bestPeaks, bestPeakIntensities);
            }
            else
            {
                precursor.Mz = precursorMz;
            }

            precursor.IsolationSpecificity = IsolationSpecificityCalculator.calculate(
                ParentScan.Centroids,
                precursor.IsolationMz,
                precursor.Mz,
                precursor.Charge,
                precursor.IsolationWidth
                );
        }
Example #13
0
 public Transitions(Precursor precursor) : base(precursor.DataSchema, precursor.IdentityPath)
 {
 }
Example #14
0
 private static double? GetIsolationWindowValue(Precursor precursor, CVID cvid)
 {
     var term = precursor.isolationWindow.cvParam(cvid);
     if (!term.empty())
         return term.value;
     return null;
 }
Example #15
0
 public PrecursorResultList(Precursor precursor) : base(precursor.DataSchema)
 {
     Precursor = precursor;
     OnDocumentChanged();
 }
Example #16
0
 public PrecursorResult(Precursor precursor, ResultFile file)
     : base(precursor, file)
 {
     _chromInfo = CachedValue.Create(DataSchema, ()=>GetResultFile().FindChromInfo(precursor.DocNode.Results));
 }
Example #17
0
        private MzLite.Model.MassSpectrum ReadMassSpectrum(int scanNo)
        {
            RaiseDisposed();

            try
            {
                string       spectrumID = GetSpectrumID(scanNo);
                MassSpectrum spectrum   = new MassSpectrum(spectrumID);

                // spectrum

                int msLevel = GetMSLevel(rawFile, scanNo);
                spectrum.SetMsLevel(msLevel);

                if (IsCentroidSpectrum(rawFile, scanNo))
                {
                    spectrum.SetCentroidSpectrum();
                }
                else
                {
                    spectrum.SetProfileSpectrum();
                }

                // scan

                Scan scan = new Scan();
                scan.SetFilterString(GetFilterString(rawFile, scanNo))
                .SetScanStartTime(GetRetentionTime(rawFile, scanNo));
                //.UO_Minute();

                spectrum.Scans.Add(scan);

                // precursor

                if (msLevel > 1)
                {
                    Precursor precursor = new Precursor();

                    double isoWidth    = GetIsolationWindowWidth(rawFile, scanNo, msLevel) * 0.5d;
                    double targetMz    = GetIsolationWindowTargetMz(rawFile, scanNo, msLevel);
                    double precursorMz = GetPrecursorMz(rawFile, scanNo, msLevel);
                    int    chargeState = GetChargeState(rawFile, scanNo);

                    precursor.IsolationWindow
                    .SetIsolationWindowTargetMz(targetMz)
                    .SetIsolationWindowUpperOffset(isoWidth)
                    .SetIsolationWindowLowerOffset(isoWidth);

                    SelectedIon selectedIon = new SelectedIon();

                    selectedIon
                    .SetSelectedIonMz(precursorMz)
                    .SetChargeState(chargeState);

                    precursor.SelectedIons.Add(selectedIon);

                    spectrum.Precursors.Add(precursor);
                }

                return(spectrum);
            }
            catch (Exception ex)
            {
                throw new MzLiteIOException(ex.Message, ex);
            }
        }
Example #18
0
        private MassSpectrum ReadMassSpectrum(UInt64 spectrumId)
        {
            BafSqlSpectrum bafSpec = linq2BafSql.GetBafSqlSpectrum(this.linq2BafSql.Core, spectrumId);

            if (bafSpec == null)
            {
                throw new MzLiteIOException("No spectrum found for id: " + spectrumId);
            }

            MassSpectrum ms = new MassSpectrum(spectrumId.ToString());

            // determine ms level
            BafSqlAcquisitionKey aqKey   = linq2BafSql.GetBafSqlAcquisitionKey(this.linq2BafSql.Core, bafSpec.AcquisitionKey);
            Nullable <int>       msLevel = null;

            if (aqKey != null && aqKey.MsLevel.HasValue)
            {
                // bruker starts ms level by 0, must be added by 1
                msLevel = aqKey.MsLevel.Value + 1;
                ms.SetMsLevel(msLevel.Value);
            }

            // determine type of spectrum and read peak data
            // if profile data available we prefer to get profile data otherwise centroided data (line spectra)
            if (bafSpec.ProfileMzId.HasValue && bafSpec.ProfileIntensityId.HasValue)
            {
                ms.SetProfileSpectrum();
            }
            else if (bafSpec.LineMzId.HasValue && bafSpec.LineIntensityId.HasValue)
            {
                ms.SetCentroidSpectrum();
            }

            if (msLevel == 1)
            {
                ms.SetMS1Spectrum();
            }
            else if (msLevel > 1)
            {
                ms.SetMSnSpectrum();
            }

            // scan
            if (bafSpec.Rt.HasValue)
            {
                Scan scan = new Scan();
                scan.SetScanStartTime(bafSpec.Rt.Value).UO_Second();
                ms.Scans.Add(scan);
            }

            // precursor
            if (msLevel > 1)
            {
                SpectrumVariableCollection spectrumVariables = SpectrumVariableCollection.ReadSpectrumVariables(linq2BafSql, bafSpec.Id);

                Precursor precursor = new Precursor();

                decimal value;

                if (spectrumVariables.TryGetValue("Collision_Energy_Act", supportedVariables, out value))
                {
                    precursor.Activation.SetCollisionEnergy(Decimal.ToDouble(value));
                }
                if (spectrumVariables.TryGetValue("MSMS_IsolationMass_Act", supportedVariables, out value))
                {
                    precursor.IsolationWindow.SetIsolationWindowTargetMz(Decimal.ToDouble(value));
                }
                if (spectrumVariables.TryGetValue("Quadrupole_IsolationResolution_Act", supportedVariables, out value))
                {
                    double width = Decimal.ToDouble(value) * 0.5d;
                    precursor.IsolationWindow.SetIsolationWindowUpperOffset(width);
                    precursor.IsolationWindow.SetIsolationWindowLowerOffset(width);
                }

                Nullable <int> charge = null;

                if (spectrumVariables.TryGetValue("MSMS_PreCursorChargeState", supportedVariables, out value))
                {
                    charge = Decimal.ToInt32(value);
                }

                IEnumerable <BafSqlStep> ions = linq2BafSql.GetBafSqlSteps(this.linq2BafSql.Core, bafSpec.Id);

                foreach (BafSqlStep ion in ions)
                {
                    if (ion.Mass.HasValue)
                    {
                        SelectedIon selectedIon = new SelectedIon();
                        precursor.SelectedIons.Add(selectedIon);
                        selectedIon.SetSelectedIonMz(ion.Mass.Value);

                        selectedIon.SetUserParam("Number", ion.Number.Value);
                        selectedIon.SetUserParam("IsolationType", ion.IsolationType.Value);
                        selectedIon.SetUserParam("ReactionType", ion.ReactionType.Value);
                        selectedIon.SetUserParam("MsLevel", ion.MsLevel.Value);

                        if (charge.HasValue)
                        {
                            selectedIon.SetChargeState(charge.Value);
                        }
                    }
                }

                // set parent spectrum as reference
                if (bafSpec.Parent.HasValue)
                {
                    precursor.SpectrumReference = new SpectrumReference(bafSpec.Parent.ToString());
                }

                ms.Precursors.Add(precursor);
            }

            return(ms);
        }
Example #19
0
        private static MzLite.Model.MassSpectrum GetSpectrum(
            Batch batch,
            MassSpectrometerSample sample,
            MSExperiment msExp,
            int sampleIndex,
            int experimentIndex,
            int scanIndex)
        {
            MassSpectrumInfo wiffSpectrum = msExp.GetMassSpectrumInfo(scanIndex);

            MzLite.Model.MassSpectrum mzLiteSpectrum = new Model.MassSpectrum(ToSpectrumID(sampleIndex, experimentIndex, scanIndex));

            // spectrum

            mzLiteSpectrum.SetMsLevel(wiffSpectrum.MSLevel);

            if (wiffSpectrum.CentroidMode)
            {
                mzLiteSpectrum.SetCentroidSpectrum();
            }
            else
            {
                mzLiteSpectrum.SetProfileSpectrum();
            }

            // scan

            Scan scan = new Scan();

            scan.SetScanStartTime(wiffSpectrum.StartRT)
            .UO_Minute();

            mzLiteSpectrum.Scans.Add(scan);

            // precursor

            if (wiffSpectrum.IsProductSpectrum)
            {
                Precursor precursor = new Precursor();

                double isoWidth;
                double targetMz;

                if (GetIsolationWindow(wiffSpectrum.Experiment, out isoWidth, out targetMz))
                {
                    precursor.IsolationWindow
                    .SetIsolationWindowTargetMz(targetMz)
                    .SetIsolationWindowUpperOffset(isoWidth)
                    .SetIsolationWindowLowerOffset(isoWidth);
                }

                SelectedIon selectedIon = new SelectedIon();

                selectedIon.SetSelectedIonMz(wiffSpectrum.ParentMZ)
                .SetChargeState(wiffSpectrum.ParentChargeState);

                precursor.SelectedIons.Add(selectedIon);

                precursor.Activation
                .SetCollisionEnergy(wiffSpectrum.CollisionEnergy);

                mzLiteSpectrum.Precursors.Add(precursor);
            }

            return(mzLiteSpectrum);
        }
Example #20
0
        /// <summary>
        /// Open the given file and import scans into the reader.
        /// </summary>
        /// <returns></returns>
        public IEnumerator GetEnumerator()
        {
            // Reset to beginning of document.
            Reader = XmlReader.Create(FilePath);
            Scan      scan       = null;
            Precursor precursor  = null;
            var       binaryData = new BinaryData();

            while (Reader.Read())
            {
                if (Reader.NodeType == XmlNodeType.Element)
                {
                    if (Reader.Name == "spectrum")
                    {
                        // Using spectrum as a start of scan.
                        // <spectrum index="11" defaultArrayLength="113" id="index=12">
                        // Using id attr for scan numbers
                        scan = new Scan();
                        ReadSpectrumAttrs(scan);
                    }
                    else if (Reader.Name == "precursor")
                    {
                        // Precursor contains the precursor scan number.
                        // <precursor spectrumRef="index=11">
                    }
                    else if (Reader.Name == "selectedIon")
                    {
                        precursor = new Precursor();
                    }
                    else if (Reader.Name == "cvParam")
                    {
                        var cvParam = ReadCVParam();
                        SetAttribute(cvParam, scan, precursor);
                    }
                    else if (Reader.Name == "binaryDataArray")
                    {
                        ReadBinaryData(binaryData, scan.PeakCount);
                    }
                }
                else if (Reader.NodeType == XmlNodeType.EndElement)
                {
                    // Reached a closing tag.
                    if (Reader.Name == "spectrum")
                    {
                        scan.Centroids.Clear();
                        for (int i = 0; i < scan.PeakCount; ++i)
                        {
                            scan.Centroids.Add(
                                new Centroid(
                                    binaryData.mzs[i],
                                    binaryData.intensities[i])
                                );
                        }
                        yield return(scan);
                    }

                    if (Reader.Name == "selectedIon")
                    {
                        scan.Precursors.Add(precursor);
                    }
                    else if (Reader.Name == "spectrumList")
                    {
                        break;
                    }
                }
            }
        }
Example #21
0
        public IEnumerator GetEnumerator()
        {
            var scanCommand      = new SQLiteCommand("SELECT * FROM scans AS s LEFT JOIN scan_peaks as p ON p.scan=s.scan", db);
            var precursorCommand = new SQLiteCommand("SELECT * FROM scan_precursors WHERE scan=$scan", db);

            using (var scanReader = scanCommand.ExecuteReader())
            {
                while (scanReader.Read())
                {
                    int foo  = (int)scanReader["scan"];
                    var scan = new Scan {
                        ScanNumber                = (int)scanReader["scan"],
                        ScanEvent                 = (int)scanReader["scan_event"],
                        MsOrder                   = (int)scanReader["ms_level"],
                        PeakCount                 = (int)scanReader["peak_count"],
                        MasterIndex               = (int)scanReader["master_index"],
                        IonInjectionTime          = (double)scanReader["ion_injection_time"],
                        ElapsedScanTime           = (double)scanReader["elapsed_scan_time"],
                        Polarity                  = ReadPolarity((string)scanReader["polarity"]),
                        ScanType                  = (string)scanReader["scan_type"],
                        DetectorType              = (string)scanReader["detector_type"],
                        FilterLine                = (string)scanReader["filter_line"],
                        RetentionTime             = (double)scanReader["time"],
                        StartMz                   = (double)scanReader["start_mz"],
                        EndMz                     = (double)scanReader["end_mz"],
                        LowestMz                  = (double)scanReader["low_mz"],
                        HighestMz                 = (double)scanReader["high_mz"],
                        BasePeakMz                = (double)scanReader["base_peak_mz"],
                        BasePeakIntensity         = (double)scanReader["base_peak_intensity"],
                        FaimsCV                   = (int)(double)scanReader["cv"],
                        TotalIonCurrent           = (double)scanReader["total_intensity"],
                        CollisionEnergy           = (double)scanReader["activation_energy"],
                        PrecursorMasterScanNumber = (int)scanReader["parent_scan"],
                        PrecursorActivationMethod = (string)scanReader["activation_type"]
                    };

                    int peakFlags = (int)scanReader["data_type"];
                    if (peakFlags > 0)
                    {
                        byte[] data = (byte[])scanReader["data"];
                        if (compression == "zlib")
                        {
                            data = DecompressData(data);
                        }
                        DecodePeaks(scan, peakFlags, data);
                    }

                    precursorCommand.Parameters.AddWithValue("$scan", scan.ScanNumber);
                    using (var precursorReader = precursorCommand.ExecuteReader()) {
                        while (precursorReader.Read())
                        {
                            Precursor precursor = new Precursor()
                            {
                                Mz                   = (double)precursorReader["precursor_mz"],
                                Intensity            = (double)precursorReader["precursor_intensity"],
                                Charge               = (int)precursorReader["precursor_charge"],
                                OriginalMz           = (double)precursorReader["original_mz"],
                                OriginalCharge       = (int)precursorReader["original_charge"],
                                IsolationMz          = (double)precursorReader["isolation_mz"],
                                IsolationWidth       = (double)precursorReader["isolation_width"],
                                IsolationSpecificity = (double)precursorReader["isolation_specificity"]
                            };
                            scan.Precursors.Add(precursor);
                        }
                    }

                    yield return(scan);
                }
            }
        }
Example #22
0
 public PrecursorResultList(Precursor precursor) : base(precursor.DataSchema)
 {
     Precursor = precursor;
 }
Example #23
0
 private static double? GetPrecursorMz(Precursor precursor)
 {
     // CONSIDER: Only the first selected ion m/z is considered for the precursor m/z
     var selectedIon = precursor.selectedIons.FirstOrDefault();
     if (selectedIon == null)
         return null;
     return selectedIon.cvParam(CVID.MS_selected_ion_m_z).value;
 }
Example #24
0
        private const string USERPARAM_DRIFT_TIME = "drift time"; // Not L10N

        private static double? GetPrecursorDriftTimeMsec(Precursor precursor)
        {
            UserParam param = precursor.userParam(USERPARAM_DRIFT_TIME);  //   CONSIDER: this will eventually be a proper CVParam
            if (param.empty())
                return null;
            return param.timeInSeconds() * 1000.0;
        }
Example #25
0
        /// <summary>
        /// Overload to handle all available scans allowing for Ms1 inclusion of before + after
        /// </summary>
        /// <param name="AllScans"></param>
        /// <param name="DependentScan"></param>
        /// <param name="Number_Of_Scans_To_Average"></param>
        public static void Run(ref List <Scan> scans, MonocleOptions Options)
        {
            if (Options.Ms2Ms3Precursor)
            {
                AssignMs3Precursors(scans);
            }

            CheckMs2Precursors(scans);

            foreach (Scan scan in scans)
            {
                if (scan.MsOrder != Options.MS_Level)
                {
                    continue;
                }

                if (scan.PrecursorMasterScanNumber <= 0)
                {
                    Console.WriteLine(String.Format("Scan {0} does not have a precursor scan number assigned.", scan.ScanNumber));
                    continue;
                }

                Scan precursorScan = scans[scan.PrecursorMasterScanNumber - 1];

                // For low-res scans, or if ForceCharges is true, or if there's no charge information
                // and monoisotopic peak detection is disabled, generate precursors with
                // a range of charges given by the ChargeRangeUnknown option.
                bool lowResPrecursor = precursorScan.FilterLine.Contains("ITMS");
                int  range           = 1 + Options.ChargeRangeUnknown.High - Options.ChargeRangeUnknown.Low;
                var  precursors      = new List <Precursor>(range);
                foreach (var precursor in scan.Precursors)
                {
                    if (lowResPrecursor || Options.ForceCharges || (precursor.Charge == 0 && Options.SkipMono))
                    {
                        for (int z = Options.ChargeRangeUnknown.Low; z <= Options.ChargeRangeUnknown.High; ++z)
                        {
                            var p = new Precursor(precursor);
                            p.Charge = z;
                            precursors.Add(p);
                        }
                    }
                }
                if (precursors.Count > 0)
                {
                    scan.Precursors = precursors;
                }

                if (!Options.SkipMono && !lowResPrecursor)
                {
                    var nearbyScans = GetNearbyScans(ref scans, precursorScan, Options);
                    precursors = new List <Precursor>();
                    foreach (var precursor in scan.Precursors)
                    {
                        if (!Options.Charge_Detection && precursor.Charge == 0)
                        {
                            // Charge detection will be enabled in the Run method.
                            Console.WriteLine(String.Format("Scan {0} does not have a charge state assigned.  Charge detection enabled.", scan.ScanNumber));
                        }

                        Run(nearbyScans, precursorScan, precursor, Options);

                        // If there is still no charge, use charge range.
                        if (precursor.Charge == 0)
                        {
                            Console.WriteLine(String.Format("No charge found for scan {0}. Using charge range.", scan.ScanNumber));
                            for (int z = Options.ChargeRangeUnknown.Low; z <= Options.ChargeRangeUnknown.High; ++z)
                            {
                                var p = new Precursor(precursor);
                                p.Charge = z;
                                precursors.Add(p);
                            }
                        }
                        else
                        {
                            precursors.Add(precursor);
                        }
                    }
                    scan.Precursors = precursors;
                }
            }
        }