Exemplo n.º 1
0
        public async Task <IPagedList <IVehicleModel> > FindModelAsync(IFilteringParams filter, ISortingParams sorter, IPagingParams pager)
        {
            var makers = await context.Models.Where(m => string.IsNullOrEmpty(filter.Search)?m != null : m.Name.ToLower().Contains(filter.Search.ToLower()))
                         .Where(m => filter.MakeId == Guid.Empty ? m.MakeId != Guid.Empty : m.MakeId == filter.MakeId).Include("Make")
                         .OrderByDescending(x => sorter.SortDirection == "dsc" ? x.Name : "")
                         .OrderBy(x => string.IsNullOrEmpty(sorter.SortDirection) || sorter.SortDirection == "asc" ? x.Name : "").ToListAsync();


            return(await mapper.Map <IEnumerable <IVehicleModel> >(makers).ToPagedListAsync(pager.CurrentPage, pager.PageSize));
        }
Exemplo n.º 2
0
        public static ThermoDynamicData InitiateDynamicConnection(string filePath, IFilteringParams filterParams = null)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException();
            }

            if (!ThermoStaticData.CheckForMsFileReader())
            {
                throw new MzLibException("MsFileReader Not Installed");
            }

            IXRawfile5 _rawConnection = (IXRawfile5) new MSFileReader_XRawfile();

            _rawConnection.Open(filePath);
            _rawConnection.SetCurrentController(0, 1);

            int lastspectrumNumber = -1;

            _rawConnection.GetLastSpectrumNumber(ref lastspectrumNumber);
            int firstspectrumNumber = -1;

            _rawConnection.GetFirstSpectrumNumber(ref firstspectrumNumber);

            var precursorInfoArray = new ManagedThermoHelperLayer.PrecursorInfo[lastspectrumNumber - firstspectrumNumber + 1];

            string sendCheckSum;

            using (FileStream stream = File.OpenRead(filePath))
            {
                using (SHA1Managed sha = new SHA1Managed())
                {
                    byte[] checksum = sha.ComputeHash(stream);
                    sendCheckSum = BitConverter.ToString(checksum)
                                   .Replace("-", string.Empty);
                }
            }
            SourceFile sourceFile = new SourceFile(
                @"Thermo nativeID format",
                @"Thermo RAW format",
                sendCheckSum,
                @"SHA-1",
                filePath,
                Path.GetFileNameWithoutExtension(filePath));

            var thermoGlobalParams = ThermoStaticData.GetAllGlobalStuff(_rawConnection, precursorInfoArray, filePath);

            // if the spectra file only contains 1 scan and its MS order is 0, this indicates an errored read result
            if (thermoGlobalParams.MsOrderByScan.Length == 1 && thermoGlobalParams.MsOrderByScan[0] == 0)
            {
                throw new MzLibException("Could not read data from file " + Path.GetFileName(filePath));
            }

            return(new ThermoDynamicData(_rawConnection, filterParams, lastspectrumNumber - firstspectrumNumber + 1, sourceFile, thermoGlobalParams));
        }
Exemplo n.º 3
0
        public async Task <IPagedList <IVehicleMake> > GetAllAsync(
            IFilteringParams filteringParams,
            IPagingParams pagingParams,
            ISortingParams sortingParams)
        {
            IQueryable <VehicleMake> makeList = await _repository.GetAllAsync <VehicleMake>();

            // Filtering
            if (!String.IsNullOrEmpty(filteringParams.SearchString))
            {
                makeList = makeList.Where(x => x.Name.ToLower().Contains(filteringParams.SearchString.ToLower()));
            }

            // Sorting
            switch (sortingParams.Sorting)
            {
            case "name_desc":
                makeList = makeList.OrderByDescending(x => x.Name);
                break;

            case "id":
                makeList = makeList.OrderBy(x => x.Id);
                break;

            case "id_desc":
                makeList = makeList.OrderByDescending(x => x.Id);
                break;

            case "abrv":
                makeList = makeList.OrderBy(x => x.Abrv);
                break;

            case "abrv_desc":
                makeList = makeList.OrderByDescending(x => x.Abrv);
                break;

            default:
                makeList = makeList.OrderBy(x => x.Name);
                break;
            }
            var pagedList = makeList.ToPagedList(pagingParams.PageNumber, pagingParams.PageSize);

            if (pagedList.PageCount < pagedList.PageNumber)
            {
                makeList.ToPagedList(1, pagingParams.PageSize);
            }
            return(pagedList);
        }
Exemplo n.º 4
0
        public static ThermoDynamicData InitiateDynamicConnection(string filePath, IFilteringParams filterParams = null)
        {
            if (CheckForMsFileReader() == false)
            {
                throw new MzLibException("MsFileReader Not Installed");
            }

            IXRawfile5 _rawConnection = (IXRawfile5) new MSFileReader_XRawfile();

            _rawConnection.Open(filePath);
            _rawConnection.SetCurrentController(0, 1);

            int lastspectrumNumber = -1;

            _rawConnection.GetLastSpectrumNumber(ref lastspectrumNumber);
            int firstspectrumNumber = -1;

            _rawConnection.GetFirstSpectrumNumber(ref firstspectrumNumber);

            var precursorInfoArray = new ManagedThermoHelperLayer.PrecursorInfo[lastspectrumNumber - firstspectrumNumber + 1];

            string sendCheckSum;

            using (FileStream stream = File.OpenRead(filePath))
            {
                using (SHA1Managed sha = new SHA1Managed())
                {
                    byte[] checksum = sha.ComputeHash(stream);
                    sendCheckSum = BitConverter.ToString(checksum)
                                   .Replace("-", string.Empty);
                }
            }
            SourceFile sourceFile = new SourceFile(
                @"Thermo nativeID format",
                @"Thermo RAW format",
                sendCheckSum,
                @"SHA-1",
                filePath,
                Path.GetFileNameWithoutExtension(filePath));

            var thermoGlobalParams = GetAllGlobalStuff(_rawConnection, precursorInfoArray, filePath);

            return(new ThermoDynamicData(_rawConnection, filterParams, lastspectrumNumber - firstspectrumNumber + 1, precursorInfoArray, sourceFile, thermoGlobalParams));
        }
Exemplo n.º 5
0
        public static int TopNpeakHelper(double[] intensities, double[] mArray, IFilteringParams filteringParams)
        {
            IComparer <double> c = new ReverseComparer();

            Array.Sort(intensities, mArray, c);

            int numPeaks = intensities.Length;

            if (filteringParams.MinimumAllowedIntensityRatioToBasePeakM.HasValue)
            {
                double minIntensity = filteringParams.MinimumAllowedIntensityRatioToBasePeakM.Value * intensities[0];
                numPeaks = Math.Min(intensities.Count(b => b >= minIntensity), numPeaks);
            }

            if (filteringParams.NumberOfPeaksToKeepPerWindow.HasValue)
            {
                numPeaks = Math.Min(filteringParams.NumberOfPeaksToKeepPerWindow.Value, numPeaks);
            }
            return(numPeaks);
        }
Exemplo n.º 6
0
 private ThermoDynamicData(IXRawfile5 _rawConnection, IFilteringParams filterParams, int numSpectra, ManagedThermoHelperLayer.PrecursorInfo[] couldBePrecursor, SourceFile sourceFile, ThermoGlobalParams thermoGlobalParams) : base(_rawConnection, numSpectra, couldBePrecursor, sourceFile, thermoGlobalParams)
 {
     this._rawConnection = _rawConnection;
     this.filterParams   = filterParams;
 }
Exemplo n.º 7
0
        public static ThermoStaticData LoadAllStaticData(string filePath, IFilteringParams filterParams = null)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException();
            }

            if (CheckForMsFileReader() == false)
            {
                throw new MzLibException("MsFileReader Not Installed");
            }

            var        ok            = new ManagedThermoHelperLayer.HelperClass();
            IXRawfile5 theConnection = (IXRawfile5) new MSFileReader_XRawfile();

            theConnection.Open(filePath);
            int pbSMData = 0;

            theConnection.IsThereMSData(ref pbSMData);
            if (pbSMData == 0)
            {
                throw new MzLibException("Could not read data from file " + Path.GetFileName(filePath));
            }

            theConnection.SetCurrentController(0, 1);

            var precursorInfosArray = ok.GetAllPrecursorInfos(filePath);

            for (int i = 0; i < precursorInfosArray.Length; i++)
            {
                if (precursorInfosArray[i].nScanNumber == 0)
                {
                    precursorInfosArray[i].nScanNumber = -1;
                }
            }

            int pnFirstSpectrum = 0;

            theConnection.GetFirstSpectrumNumber(ref pnFirstSpectrum);
            int pnLastSpectrum = 0;

            theConnection.GetLastSpectrumNumber(ref pnLastSpectrum);

            ThermoGlobalParams p = GetAllGlobalStuff(theConnection, precursorInfosArray, filePath);

            MsDataScan[] scans = new MsDataScan[pnLastSpectrum - pnFirstSpectrum + 1];
            for (int nScanNumber = pnFirstSpectrum; nScanNumber <= pnLastSpectrum; nScanNumber++)
            {
                scans[nScanNumber - pnFirstSpectrum] = GetMsDataOneBasedScanFromThermoFile(theConnection, nScanNumber, p, filterParams);
            }

            theConnection.Close();

            string sendCheckSum;

            using (FileStream stream = File.OpenRead(filePath))
            {
                using (SHA1Managed sha = new SHA1Managed())
                {
                    byte[] checksum = sha.ComputeHash(stream);
                    sendCheckSum = BitConverter.ToString(checksum)
                                   .Replace("-", string.Empty);
                }
            }
            SourceFile sourceFile = new SourceFile(
                @"Thermo nativeID format",
                @"Thermo RAW format",
                sendCheckSum,
                @"SHA-1",
                filePath,
                Path.GetFileNameWithoutExtension(filePath));

            return(new ThermoStaticData(scans, p, sourceFile));
        }
Exemplo n.º 8
0
        public static MsDataScan GetMsDataOneBasedScanFromThermoFile(IXRawfile5 theConnection, int nScanNumber, ThermoGlobalParams globalParams, IFilteringParams filterParams = null)
        {
            int    pnNumPackets        = 0;
            double pdLowMass           = 0;
            double pdHighMass          = 0;
            double pdTIC               = 0;
            double pdBasePeakMass      = 0;
            double pdBasePeakIntensity = 0;
            int    pnNumChannels       = 0;
            int    pbUniformTime       = 0;
            double pdFrequency         = 0;
            double pdStartTime         = 0;

            theConnection.GetScanHeaderInfoForScanNum(nScanNumber, ref pnNumPackets, ref pdStartTime, ref pdLowMass, ref pdHighMass, ref pdTIC, ref pdBasePeakMass, ref pdBasePeakIntensity, ref pnNumChannels, ref pbUniformTime, ref pdFrequency);

            double?ms2isolationWidthFromTrailerExtra        = null;
            double?injectionTimeFromTrailerExtra            = null;
            double?precursorMonoisotopicMZfromTrailierExtra = null;
            int?   chargeStatefromTrailierExtra             = null;
            int?   masterScanfromTrailierExtra = null;

            object pvarValues  = null;
            object pvarLables  = null;
            int    pnArraySize = 0;

            theConnection.GetTrailerExtraForScanNum(nScanNumber, ref pvarLables, ref pvarValues, ref pnArraySize);

            string[] labels = (string[])pvarLables;
            string[] values = (string[])pvarValues;
            for (int i = labels.GetLowerBound(0); i <= labels.GetUpperBound(0); i++)
            {
                if (labels[i].StartsWith("MS2 Isolation Width", StringComparison.Ordinal))
                {
                    ms2isolationWidthFromTrailerExtra = double.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                                        (double?)null :
                                                        double.Parse(values[i], CultureInfo.InvariantCulture);
                }
                if (labels[i].StartsWith("Ion Injection Time (ms)", StringComparison.Ordinal))
                {
                    injectionTimeFromTrailerExtra = double.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                                    (double?)null :
                                                    double.Parse(values[i], CultureInfo.InvariantCulture);
                }
                if (labels[i].StartsWith("Monoisotopic M/Z", StringComparison.Ordinal))
                {
                    precursorMonoisotopicMZfromTrailierExtra = double.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                                               (double?)null :
                                                               double.Parse(values[i], CultureInfo.InvariantCulture);
                }
                if (labels[i].StartsWith("Charge State", StringComparison.Ordinal))
                {
                    chargeStatefromTrailierExtra = int.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                                   (int?)null :
                                                   int.Parse(values[i], CultureInfo.InvariantCulture);
                }
                if (labels[i].StartsWith("Master Scan Number", StringComparison.Ordinal))
                {
                    masterScanfromTrailierExtra = int.Parse(values[i], CultureInfo.InvariantCulture) == 0 ?
                                                  (int?)null :
                                                  int.Parse(values[i], CultureInfo.InvariantCulture);
                }
            }

            string pbstrFilter = null;

            theConnection.GetFilterForScanNum(nScanNumber, ref pbstrFilter);

            int pnMSOrder = 0;

            theConnection.GetMSOrderForScanNum(nScanNumber, ref pnMSOrder);

            int pnMassAnalyzerType = 0;

            theConnection.GetMassAnalyzerTypeForScanNum(nScanNumber, ref pnMassAnalyzerType);

            object pvarNoisePacket = null;

            try //if there is no noise data
            {
                theConnection.GetNoiseData(ref pvarNoisePacket, nScanNumber);
            }
            catch
            {
                //pvarNoisePAcket is already null
            }
            double[,] noiseData = pvarNoisePacket as double[, ];

            double[,] data;
            try
            {
                object pvarFlags  = null;
                object pvarLabels = null;
                theConnection.GetLabelData(ref pvarLabels, ref pvarFlags, ref nScanNumber);
                data = pvarLabels as double[, ];
                if (data == null || data.Length == 0)
                {
                    throw new MzLibException("For spectrum number " + nScanNumber + " the data is null!");
                }
            }
            catch (MzLibException)
            {
                // Warning: the masses reported by GetMassListFromScanNum when centroiding are not properly calibrated and thus could be off by 0.3 m/z or more

                double pdCentroidPeakWidth = 0;
                object pvarnMassList       = null;
                object pvarPeakFlags       = null;
                theConnection.GetMassListFromScanNum(ref nScanNumber, null, 0, 0, 0, 1, ref pdCentroidPeakWidth, ref pvarnMassList, ref pvarPeakFlags, ref pnArraySize);
                data = (double[, ])pvarnMassList;
            }

            MzSpectrum thermoSpectrum;

            if (filterParams != null && data.GetLength(1) > 0 && (filterParams.MinimumAllowedIntensityRatioToBasePeakM.HasValue || filterParams.NumberOfPeaksToKeepPerWindow.HasValue) && ((filterParams.ApplyTrimmingToMs1 && pnMSOrder == 1) || (filterParams.ApplyTrimmingToMsMs && pnMSOrder > 1)))
            {
                var count = data.GetLength(1);

                var mzArray        = new double[count];
                var intensityArray = new double[count];
                Buffer.BlockCopy(data, 0, mzArray, 0, sizeof(double) * count);
                Buffer.BlockCopy(data, sizeof(double) * count, intensityArray, 0, sizeof(double) * count);
                if (filterParams.NumberOfWindows == null)
                {
                    int numPeaks = TopNpeakHelper(ref intensityArray, ref mzArray, filterParams);
                    //the following arrays are modified after TopN helper
                    Array.Resize(ref intensityArray, numPeaks);
                    Array.Resize(ref mzArray, numPeaks);
                }
                //Array reference passed by value, array calues will be modified after calling
                else
                {
                    WindowModeHelper(ref intensityArray, ref mzArray, filterParams);
                }
                Array.Sort(mzArray, intensityArray);
                thermoSpectrum = new MzSpectrum(mzArray, intensityArray, false);
            }
            else
            {
                thermoSpectrum = new MzSpectrum(data);
            }
            MZAnalyzerType mzAnalyzerType;

            if ((ThermoMzAnalyzer)pnMassAnalyzerType == ThermoMzAnalyzer.FTMS)
            {
                mzAnalyzerType = MZAnalyzerType.Orbitrap;
            }
            else
            {
                mzAnalyzerType = MZAnalyzerType.Unknown;
            }
            string nativeId = "controllerType=0 controllerNumber=1 scan=" + nScanNumber;

            if (pnMSOrder > 1)
            {
                int pnActivationType = 0;
                theConnection.GetActivationTypeForScanNum(nScanNumber, pnMSOrder, ref pnActivationType);

                // INITIALIZE globalParams.couldBePrecursor[nScanNumber - 1] (for dynamic connections that don't have it initialized yet)
                if (globalParams.CouldBePrecursor[nScanNumber - 1].Equals(default(ManagedThermoHelperLayer.PrecursorInfo)))
                {
                    var ok = new ManagedThermoHelperLayer.HelperClass();
                    globalParams.CouldBePrecursor[nScanNumber - 1] = ok.GetSingleScanPrecursorInfo(nScanNumber, globalParams.FilePath);
                }

                var precursorInfo = globalParams.CouldBePrecursor[nScanNumber - 1];

                // THIS METHOD IS BUGGY!!! DO NOT USE
                //theConnection.FindPrecursorMassInFullScan(nScanNumber, ref pnMasterScan, ref pdFoundMass, ref pdHeaderMass, ref pnChargeState);

                int oneBasedPrecursorScanNumber = -1;
                if (precursorInfo.nScanNumber > 0)
                {
                    oneBasedPrecursorScanNumber = precursorInfo.nScanNumber;
                }
                else if (masterScanfromTrailierExtra.HasValue && masterScanfromTrailierExtra > 0)
                {
                    oneBasedPrecursorScanNumber = masterScanfromTrailierExtra.Value;
                }
                else
                {
                    // 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
                    int scanOrder          = globalParams.MsOrderByScan[nScanNumber - 1];
                    int precursorScanOrder = scanOrder - 1;

                    for (int i = nScanNumber - 1; i >= 0; i--)
                    {
                        int msOrder = globalParams.MsOrderByScan[i];

                        if (msOrder == precursorScanOrder)
                        {
                            oneBasedPrecursorScanNumber = i + 1;
                            break;
                        }
                    }
                }
                if (oneBasedPrecursorScanNumber == -1)
                {
                    throw new MzLibException("Could not find precursor info for scan #" + nScanNumber);
                }

                int?selectedIonGuessChargeStateGuess = null;
                if (precursorInfo.nChargeState > 0)
                {
                    selectedIonGuessChargeStateGuess = precursorInfo.nChargeState;
                }
                else if (chargeStatefromTrailierExtra.HasValue)
                {
                    selectedIonGuessChargeStateGuess = chargeStatefromTrailierExtra;
                }

                double?selectedIonGuessMonoisotopicMz = null;
                if (precursorMonoisotopicMZfromTrailierExtra.HasValue && precursorMonoisotopicMZfromTrailierExtra.Value > 0)
                {
                    selectedIonGuessMonoisotopicMz = precursorMonoisotopicMZfromTrailierExtra;
                }
                if (precursorInfo.dMonoIsoMass > 0 && !selectedIonGuessMonoisotopicMz.HasValue)
                {
                    selectedIonGuessMonoisotopicMz = precursorInfo.dMonoIsoMass;
                }

                Regex matcher;
                if (pbstrFilter.ToLower().Contains("msx"))
                {
                    matcher = mFindParentIonOnlyMsx;
                }
                else
                {
                    matcher = mFindParentIonOnlyNonMsx;
                }
                double selectedIonGuessMZ = double.Parse(matcher.Match(pbstrFilter).Groups["ParentMZ"].Value);

                //   int? selectedIonChargeStateGuess, double? selectedIonIntensity, double? isolationMZ, double? isolationWidth, DissociationType dissociationType, int? oneBasedPrecursorScanNumber, double? selectedIonMonoisotopicGuessMz, double? injectionTime, double[,] noiseData, string nativeId)
                // double TotalIonCurrent, double selectedIonMZ, int? selectedIonChargeStateGuess, double? selectedIonIntensity, double? isolationMZ, double? isolationWidth, DissociationType dissociationType, int? oneBasedPrecursorScanNumber, double? selectedIonMonoisotopicGuessMz, double? injectionTime, double[,] noiseData, string nativeId)
                return(new MsDataScan(
                           thermoSpectrum,
                           nScanNumber,
                           pnMSOrder,
                           true,
                           PolarityRegex.IsMatch(pbstrFilter) ? Polarity.Positive : Polarity.Negative,
                           pdStartTime,
                           new MzRange(pdLowMass, pdHighMass),
                           pbstrFilter,
                           mzAnalyzerType,
                           pdTIC,
                           injectionTimeFromTrailerExtra,
                           noiseData,
                           nativeId,
                           selectedIonGuessMZ,
                           selectedIonGuessChargeStateGuess,
                           null,
                           selectedIonGuessMZ,
                           ms2isolationWidthFromTrailerExtra,
                           (DissociationType)pnActivationType,
                           oneBasedPrecursorScanNumber,
                           selectedIonGuessMonoisotopicMz
                           ));
            }
            else
            {
                return(new MsDataScan(
                           thermoSpectrum,
                           nScanNumber,
                           1,
                           true,
                           PolarityRegex.IsMatch(pbstrFilter) ? Polarity.Positive : Polarity.Negative,
                           pdStartTime,
                           new MzRange(pdLowMass, pdHighMass),
                           pbstrFilter,
                           mzAnalyzerType,
                           pdTIC,
                           injectionTimeFromTrailerExtra,
                           noiseData,
                           nativeId));
            }
        }
Exemplo n.º 9
0
 private ThermoDynamicData(IXRawfile5 _rawConnection, IFilteringParams filterParams, int numSpectra, SourceFile sourceFile, ThermoGlobalParams thermoGlobalParams) : base(numSpectra, sourceFile)
 {
     this._rawConnection = _rawConnection;
     this.filterParams   = filterParams;
     ThermoGlobalParams  = thermoGlobalParams;
 }
Exemplo n.º 10
0
        private static MzSpectrum GetSpectrum(IRawDataPlus rawFile, IFilteringParams filterParams, int scanNumber, string scanFilter, int scanOrder)
        {
            MzSpectrum spectrum;

            double[] xArray;
            double[] yArray;

            if (string.IsNullOrEmpty(scanFilter))
            {
                return(new MzSpectrum(new double[0], new double[0], false));
            }

            var centroidStream = rawFile.GetCentroidStream(scanNumber, false);

            // PreferredMasses should be used if centroidStream data is null; it's probably ITMS data
            if (centroidStream.Masses == null || centroidStream.Intensities == null)
            {
                var scan = Scan.FromFile(rawFile, scanNumber);
                var mzs  = scan.PreferredMasses;
                xArray = scan.PreferredMasses;
                yArray = scan.PreferredIntensities;

                if (xArray == null || yArray == null)
                {
                    throw new MzLibException("Could not centroid data from scan " + scanNumber);
                }
            }
            else
            {
                xArray = centroidStream.Masses;
                yArray = centroidStream.Intensities;
            }

            if (filterParams != null &&
                xArray.Length > 0 &&
                (filterParams.MinimumAllowedIntensityRatioToBasePeakM.HasValue || filterParams.NumberOfPeaksToKeepPerWindow.HasValue) &&
                ((filterParams.ApplyTrimmingToMs1 && scanOrder == 1) || (filterParams.ApplyTrimmingToMsMs && scanOrder > 1)))
            {
                var count = xArray.Length;

                var mzArray        = new double[count];
                var intensityArray = new double[count];
                Array.Copy(xArray, mzArray, count);
                Array.Copy(yArray, intensityArray, count);

                var    scanStats     = rawFile.GetScanStatsForScanNumber(scanNumber);
                double scanRangeHigh = scanStats.HighMass;
                double scanRangeLow  = scanStats.LowMass;

                WindowModeHelper(ref intensityArray, ref mzArray, filterParams, scanRangeLow, scanRangeHigh);

                Array.Sort(mzArray, intensityArray);
                spectrum = new MzSpectrum(mzArray, intensityArray, false);
            }
            else
            {
                spectrum = new MzSpectrum(xArray, yArray, false);
            }

            return(spectrum);
        }
Exemplo n.º 11
0
        /// <summary>
        /// This method is designed to break a scan up into windows and take the top N peaks (by intensity)
        /// from each window, then merge the results as the scan's new mass spectrum
        /// </summary>
        /// <param name="intensities"></param>
        /// <param name="mArray"></param>
        /// <param name="filteringParams"></param>
        public static void WindowModeHelper(ref double[] intensities, ref double[] mArray, IFilteringParams filteringParams, double scanRangeMinMz, double scanRangeMaxMz, bool keepZeroPeaks = false)
        {
            Array.Sort(intensities, mArray);
            double TIC = intensities.Sum();

            //filter low intensites based on a percent for the whole spectrum.
            if (filteringParams.MinimumAllowedIntensityRatioToBasePeakM.HasValue)
            {
                double maxIntensity = intensities.Max();
                double cutOff       = maxIntensity * filteringParams.MinimumAllowedIntensityRatioToBasePeakM.Value;
                for (int i = 0; i < intensities.Length; i++)
                {
                    if (intensities[i] <= cutOff && intensities[i] > 0)
                    {
                        intensities[i] = 0;
                    }
                }
            }

            const double shiftToMakeRangeInclusive = 0.000000001;

            Chemistry.ClassExtensions.TupleList <double, double> ranges = new Chemistry.ClassExtensions.TupleList <double, double>();

            if (filteringParams.WindowWidthThomsons != null && filteringParams.WindowWidthThomsons > 0)
            {
                double scanRangeToUse = Math.Min(scanRangeMaxMz - scanRangeMinMz, filteringParams.WindowWidthThomsons.Value);

                List <double> ends  = new List <double>();
                double        end   = 0;
                bool          first = true;
                while (end < scanRangeMaxMz)
                {
                    if ((end + scanRangeToUse) > scanRangeMinMz)
                    {
                        if (first)
                        {
                            ends.Add(scanRangeMinMz - shiftToMakeRangeInclusive);
                            first = false;
                        }
                        else
                        {
                            ends.Add(end);
                        }
                    }
                    end += scanRangeToUse;
                }

                for (int i = 0; i < ends.Count; i++)
                {
                    if (i == 0)
                    {
                        ranges.Add(ends[i], ends[i + 1]);
                    }
                    else if (i != (ends.Count - 1))
                    {
                        ranges.Add(ends[i] + shiftToMakeRangeInclusive, ends[i + 1]);
                    }
                    else
                    {
                        ranges.Add(ends[i] + shiftToMakeRangeInclusive, scanRangeMaxMz + shiftToMakeRangeInclusive);
                    }
                }
            }
            else if (filteringParams.NumberOfWindows != null && filteringParams.NumberOfWindows > 1)
            {
                double mzRangeInOneWindow = (scanRangeMaxMz - scanRangeMinMz) / filteringParams.NumberOfWindows.Value;

                ranges.Add(scanRangeMinMz - shiftToMakeRangeInclusive, (scanRangeMinMz + mzRangeInOneWindow));
                scanRangeMinMz += mzRangeInOneWindow;

                for (int i = 2; i < filteringParams.NumberOfWindows; i++)
                {
                    ranges.Add(scanRangeMinMz, (scanRangeMinMz + mzRangeInOneWindow));
                    scanRangeMinMz += mzRangeInOneWindow;
                }
                ranges.Add(scanRangeMinMz, (scanRangeMinMz + mzRangeInOneWindow) + shiftToMakeRangeInclusive);
                scanRangeMinMz += mzRangeInOneWindow;
            }
            else
            {
                ranges.Add(scanRangeMinMz - shiftToMakeRangeInclusive, scanRangeMaxMz + shiftToMakeRangeInclusive);
            }

            Dictionary <int, List <int> >    mzInRange          = new Dictionary <int, List <int> >();    //index of range and  list of index values in mArray
            Dictionary <int, List <double> > mzRangeIntensities = new Dictionary <int, List <double> >(); //index of range and  list of index values in mArray

            for (int i = 0; i < ranges.Count; i++)
            {
                mzInRange.Add(i, new List <int>());
                mzRangeIntensities.Add(i, new List <double>());
            }

            //we're going to keep track of the array indicies b/c that's easier than the m/zs b/c rounding issues
            //we're only keeping peaks with intensity greater than 1 (assuming those <= 1 has "zero" intensity)
            for (int j = mArray.Length - 1; j >= 0; j--)
            {
                foreach (int rangeIndex in Enumerable.Range(0, ranges.Count))
                {
                    if (mArray[j] > ranges[rangeIndex].Item1 && mArray[j] <= ranges[rangeIndex].Item2 && (intensities[j] > 0.000000001 || keepZeroPeaks))
                    {
                        mzInRange[rangeIndex].Add(j);
                        break;
                    }
                }
            }

            int countOfPeaksToKeepPerWindow = filteringParams.NumberOfPeaksToKeepPerWindow ?? int.MaxValue;

            foreach (int rangeIndex in mzInRange.Keys)
            {
                List <double> tempIntList = new List <double>();
                foreach (int arrayIndex in mzInRange[rangeIndex])
                {
                    tempIntList.Add(intensities[arrayIndex]);
                }
                mzRangeIntensities[rangeIndex] = tempIntList;
            }

            int countOfRangesWithIntensities = 0;

            foreach (int range in mzRangeIntensities.Keys)
            {
                if (mzRangeIntensities[range].Sum() > 0)
                {
                    countOfRangesWithIntensities++;
                }
            }

            List <double> reducedMzList        = new List <double>();
            List <double> reducedIntensityList = new List <double>();

            foreach (int rangeIndex in mzInRange.Keys)
            {
                List <double> tempMzList = new List <double>();
                foreach (int arrayIndex in mzInRange[rangeIndex])
                {
                    tempMzList.Add(mArray[arrayIndex]);
                }
                //There is no need to do any normalization unless there are multiple windows
                if (filteringParams.NormalizePeaksAcrossAllWindows)
                {
                    double max = mzRangeIntensities[rangeIndex].Max();
                    if (max == 0)
                    {
                        max = 1;
                    }
                    mzRangeIntensities[rangeIndex] = mzRangeIntensities[rangeIndex].Select(x => x / max * 50.0000).ToList();

                    //Saving b/c I might want to put it back.

                    //double sum = mzRangeIntensities[rangeIndex].Sum();
                    //if (sum > 0)
                    //{
                    //    double normalizationFactor = TIC / sum / countOfRangesWithIntensities;
                    //    mzRangeIntensities[rangeIndex] = mzRangeIntensities[rangeIndex].Select(x => x * normalizationFactor).ToList();
                    //}
                }

                if (tempMzList.Count > 0 && mzRangeIntensities[rangeIndex].Count > 0)
                {
                    reducedMzList.AddRange(tempMzList.GetRange(0, Math.Min(tempMzList.Count, countOfPeaksToKeepPerWindow)));
                    reducedIntensityList.AddRange(mzRangeIntensities[rangeIndex].GetRange(0, Math.Min(mzRangeIntensities[rangeIndex].Count, countOfPeaksToKeepPerWindow)));
                }
            }

            intensities = reducedIntensityList.ToArray();
            mArray      = reducedMzList.ToArray();
            Array.Sort(mArray, intensities);
        }
Exemplo n.º 12
0
 public async Task <IPagedList <IVehicleMake> > FindMakeAsync(IFilteringParams filter, ISortingParams sorter, IPagingParams pager)
 {
     return(await unitOfWork.Makers.FindMakeAsync(filter, sorter, pager));
 }
Exemplo n.º 13
0
 public abstract MsDataScan GetOneBasedScanFromDynamicConnection(int oneBasedScanNumber, IFilteringParams filterParams = null);
Exemplo n.º 14
0
 public FilteringFactory(IFilteringParams filteringParams)
 {
     _filteringParams = filteringParams ?? throw new ArgumentNullException(nameof(IFilteringParams));
 }
Exemplo n.º 15
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.º 16
0
        private static MsDataScan GetMsDataOneBasedScanFromConnection(Generated.mzMLType _mzMLConnection, int oneBasedIndex, IFilteringParams filterParams)
        {
            // Read in the instrument configuration types from connection (in mzml it's at the start)

            Generated.InstrumentConfigurationType[] configs = new Generated.InstrumentConfigurationType[_mzMLConnection.instrumentConfigurationList.instrumentConfiguration.Length];
            for (int i = 0; i < _mzMLConnection.instrumentConfigurationList.instrumentConfiguration.Length; i++)
            {
                configs[i] = _mzMLConnection.instrumentConfigurationList.instrumentConfiguration[i];
            }

            var defaultInstrumentConfig = _mzMLConnection.run.defaultInstrumentConfigurationRef;
            // May be null!
            var scanSpecificInsturmentConfig = _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].scanList.scan[0].instrumentConfigurationRef;

            MZAnalyzerType analyzer = default(MZAnalyzerType);

            // use default
            if (scanSpecificInsturmentConfig == null || scanSpecificInsturmentConfig == defaultInstrumentConfig)
            {
                if (configs[0].componentList == null)
                {
                    analyzer = default(MZAnalyzerType);
                }
                else if (AnalyzerDictionary.TryGetValue(configs[0].componentList.analyzer[0].cvParam[0].accession, out MZAnalyzerType returnVal))
                {
                    analyzer = returnVal;
                }
            }
            // use scan-specific
            else
            {
                for (int i = 0; i < _mzMLConnection.instrumentConfigurationList.instrumentConfiguration.Length; i++)
                {
                    if (configs[i].id.Equals(scanSpecificInsturmentConfig))
                    {
                        AnalyzerDictionary.TryGetValue(configs[i].componentList.analyzer[0].cvParam[0].accession, out MZAnalyzerType returnVal);
                        analyzer = returnVal;
                    }
                }
            }

            string nativeId = _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].id;

            int?     msOrder    = null;
            bool?    isCentroid = null;
            Polarity polarity   = Polarity.Unknown;
            double   tic        = double.NaN;

            foreach (Generated.CVParamType cv in _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].cvParam)
            {
                if (cv.accession.Equals(_msnOrderAccession))
                {
                    msOrder = int.Parse(cv.value);
                }
                if (cv.accession.Equals(_centroidSpectrum))
                {
                    isCentroid = true;
                }
                if (cv.accession.Equals(_profileSpectrum))
                {
                    throw new MzLibException("Reading profile mode mzmls not supported");
                }
                if (cv.accession.Equals(_totalIonCurrent))
                {
                    tic = double.Parse(cv.value, CultureInfo.InvariantCulture);
                }
                if (polarity.Equals(Polarity.Unknown))
                {
                    PolarityDictionary.TryGetValue(cv.accession, out polarity);
                }
            }

            double rtInMinutes        = double.NaN;
            string scanFilter         = null;
            double?injectionTime      = null;
            int    oneBasedScanNumber = oneBasedIndex;

            if (_mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].scanList.scan[0].cvParam != null)
            {
                foreach (Generated.CVParamType cv in _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].scanList.scan[0].cvParam)
                {
                    if (cv.accession.Equals(_retentionTime))
                    {
                        rtInMinutes = double.Parse(cv.value, CultureInfo.InvariantCulture);
                        if (cv.unitName == "second")
                        {
                            rtInMinutes /= 60;
                        }
                    }
                    if (cv.accession.Equals(_filterString))
                    {
                        scanFilter = cv.value;
                    }
                    if (cv.accession.Equals(_ionInjectionTime))
                    {
                        injectionTime = double.Parse(cv.value, CultureInfo.InvariantCulture);
                    }
                    if (cv.accession.Equals(_oneBasedScanNumber)) //get the real one based spectrum number (if available), the other assumes they are in order. This is present in .mgf->.mzml conversions from MSConvert
                    {
                        oneBasedScanNumber = int.Parse(cv.value);
                    }
                }
            }

            if (!msOrder.HasValue || !isCentroid.HasValue)
            {
                //one instance when this if statment is true (i.e. not false) is when there is no mz/intensity data
                //so, we return the MsDataScan object with a null spectrum
                //scans w/ null spectra are checked later and the scan numbers associated w those scans are returned to the reader.
                return(new MsDataScan(
                           null,
                           oneBasedScanNumber,
                           msOrder.Value,
                           false, //have to return a value here b/c it is not nullable
                           polarity,
                           rtInMinutes,
                           null,
                           scanFilter,
                           analyzer,
                           tic,
                           injectionTime,
                           null,
                           nativeId));
            }

            double[] masses      = new double[0];
            double[] intensities = new double[0];

            foreach (Generated.BinaryDataArrayType binaryData in _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].binaryDataArrayList.binaryDataArray)
            {
                bool compressed     = false;
                bool mzArray        = false;
                bool intensityArray = false;
                bool is32bit        = true;
                foreach (Generated.CVParamType cv in binaryData.cvParam)
                {
                    compressed     |= cv.accession.Equals(_zlibCompression);
                    is32bit        &= !cv.accession.Equals(_64bit);
                    is32bit        |= cv.accession.Equals(_32bit);
                    mzArray        |= cv.accession.Equals(_mzArray);
                    intensityArray |= cv.accession.Equals(_intensityArray);
                }

                //in the futurem we may see scass w/ no data and there will be a crash here. if that happens, you can retrun an MsDataScan with null as the mzSpectrum
                //the scans with no spectra will be reported to the reader and left out of the scan list.
                double[] data = ConvertBase64ToDoubles(binaryData.binary, compressed, is32bit);
                if (mzArray)
                {
                    masses = data;
                }

                if (intensityArray)
                {
                    intensities = data;
                }
            }

            double high = double.NaN;
            double low  = double.NaN;

            var aScanWindowList = _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].scanList.scan[0].scanWindowList;

            if (aScanWindowList != null)
            {
                foreach (Generated.CVParamType cv in _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].scanList.scan[0].scanWindowList.scanWindow[0].cvParam)
                {
                    if (cv.accession.Equals(_scanWindowLowerLimit))
                    {
                        low = double.Parse(cv.value, CultureInfo.InvariantCulture);
                    }
                    else if (cv.accession.Equals(_scanWindowUpperLimit))
                    {
                        high = double.Parse(cv.value, CultureInfo.InvariantCulture);
                    }
                }
            }

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

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

            if (filterParams != null && intensities.Length > 0 && ((filterParams.ApplyTrimmingToMs1 && msOrder.Value == 1) || (filterParams.ApplyTrimmingToMsMs && msOrder.Value > 1)))
            {
                WindowModeHelper(ref intensities, ref masses, filterParams, low, high);
            }

            Array.Sort(masses, intensities);
            var mzmlMzSpectrum = new MzSpectrum(masses, intensities, false);

            if (msOrder.Value == 1)
            {
                return(new MsDataScan(
                           mzmlMzSpectrum,
                           oneBasedScanNumber,
                           msOrder.Value,
                           isCentroid.Value,
                           polarity,
                           rtInMinutes,
                           new MzRange(low, high),
                           scanFilter,
                           analyzer,
                           tic,
                           injectionTime,
                           null,
                           nativeId));
            }

            double selectedIonMz        = double.NaN;
            int?   selectedIonCharge    = null;
            double?selectedIonIntensity = null;

            foreach (Generated.CVParamType cv in _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].precursorList.precursor[0].selectedIonList.selectedIon[0].cvParam)
            {
                if (cv.accession.Equals(_selectedIonMz))
                {
                    selectedIonMz = double.Parse(cv.value, CultureInfo.InvariantCulture);
                }
                if (cv.accession.Equals(_precursorCharge))
                {
                    selectedIonCharge = int.Parse(cv.value, CultureInfo.InvariantCulture);
                }
                if (cv.accession.Equals(_peakIntensity))
                {
                    selectedIonIntensity = double.Parse(cv.value, CultureInfo.InvariantCulture);
                }
            }

            double?isolationMz   = null;
            double lowIsolation  = double.NaN;
            double highIsolation = double.NaN;

            if (_mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].precursorList.precursor[0].isolationWindow != null)
            {
                foreach (Generated.CVParamType cv in _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].precursorList.precursor[0].isolationWindow.cvParam)
                {
                    if (cv.accession.Equals(_isolationWindowTargetMZ))
                    {
                        isolationMz = double.Parse(cv.value, CultureInfo.InvariantCulture);
                    }
                    if (cv.accession.Equals(_isolationWindowLowerOffset))
                    {
                        lowIsolation = double.Parse(cv.value, CultureInfo.InvariantCulture);
                    }
                    if (cv.accession.Equals(_isolationWindowUpperOffset))
                    {
                        highIsolation = double.Parse(cv.value, CultureInfo.InvariantCulture);
                    }
                }
            }

            DissociationType dissociationType = DissociationType.Unknown;

            if (_mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].precursorList.precursor[0].activation.cvParam != null)
            {
                // for EThcD scans, the dissociation type will not be listed as EThcD. it will be 2 different dissociation types
                // in the list, one as ETD and one with HCD. so we need to check for that case and interpret it as EThcD.
                List <DissociationType> scanDissociationTypes = new List <DissociationType>();

                foreach (Generated.CVParamType cv in _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].precursorList.precursor[0].activation.cvParam)
                {
                    if (DissociationDictionary.TryGetValue(cv.accession, out var scanDissociationType))
                    {
                        scanDissociationTypes.Add(scanDissociationType);
                    }
                }

                if (scanDissociationTypes.Contains(DissociationType.ETD) && scanDissociationTypes.Contains(DissociationType.HCD))
                {
                    dissociationType = DissociationType.EThcD;
                }
                else if (scanDissociationTypes.Any())
                {
                    dissociationType = scanDissociationTypes.First();
                }
                else
                {
                    dissociationType = DissociationType.Unknown;
                }
            }
            double?monoisotopicMz = null;

            if (_mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].scanList.scan[0].userParam != null)
            {
                foreach (var userParam in _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].scanList.scan[0].userParam)
                {
                    if (userParam.name.EndsWith("Monoisotopic M/Z:"))
                    {
                        monoisotopicMz = double.Parse(userParam.value, CultureInfo.InvariantCulture);
                    }
                }
            }

            int?precursorScanNumber;

            if (_mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].precursorList.precursor[0].spectrumRef == null)
            {
                precursorScanNumber = null;
            }
            else
            {
                precursorScanNumber = GetOneBasedPrecursorScanNumber(_mzMLConnection, oneBasedIndex);
            }

            return(new MsDataScan(
                       mzmlMzSpectrum,
                       oneBasedIndex,
                       msOrder.Value,
                       isCentroid.Value,
                       polarity,
                       rtInMinutes,
                       new MzRange(low, high),
                       scanFilter,
                       analyzer,
                       tic,
                       injectionTime,
                       null,
                       nativeId,
                       selectedIonMz,
                       selectedIonCharge,
                       selectedIonIntensity,
                       isolationMz,
                       lowIsolation + highIsolation,
                       dissociationType,
                       precursorScanNumber,
                       monoisotopicMz
                       ));
        }
Exemplo n.º 17
0
        private static MsDataScan GetMsDataOneBasedScanFromConnection(Generated.mzMLType _mzMLConnection, int oneBasedIndex, IFilteringParams filterParams)
        {
            // Read in the instrument configuration types from connection (in mzml it's at the start)

            Generated.InstrumentConfigurationType[] configs = new Generated.InstrumentConfigurationType[_mzMLConnection.instrumentConfigurationList.instrumentConfiguration.Length];
            for (int i = 0; i < _mzMLConnection.instrumentConfigurationList.instrumentConfiguration.Length; i++)
            {
                configs[i] = _mzMLConnection.instrumentConfigurationList.instrumentConfiguration[i];
            }

            var defaultInstrumentConfig = _mzMLConnection.run.defaultInstrumentConfigurationRef;
            // May be null!
            var scanSpecificInsturmentConfig = _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].scanList.scan[0].instrumentConfigurationRef;

            MZAnalyzerType analyzer = default(MZAnalyzerType);

            // use default
            if (scanSpecificInsturmentConfig == null || scanSpecificInsturmentConfig == defaultInstrumentConfig)
            {
                if (configs[0].componentList == null)
                {
                    analyzer = default(MZAnalyzerType);
                }
                else if (analyzerDictionary.TryGetValue(configs[0].componentList.analyzer[0].cvParam[0].accession, out MZAnalyzerType returnVal))
                {
                    analyzer = returnVal;
                }
            }
            // use scan-specific
            else
            {
                for (int i = 0; i < _mzMLConnection.instrumentConfigurationList.instrumentConfiguration.Length; i++)
                {
                    if (configs[i].id.Equals(scanSpecificInsturmentConfig))
                    {
                        analyzerDictionary.TryGetValue(configs[i].componentList.analyzer[0].cvParam[0].accession, out MZAnalyzerType returnVal);
                        analyzer = returnVal;
                    }
                }
            }

            string nativeId = _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].id;

            int?     msOrder    = null;
            bool?    isCentroid = null;
            Polarity polarity   = Polarity.Unknown;
            double   tic        = double.NaN;

            foreach (Generated.CVParamType cv in _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].cvParam)
            {
                if (cv.accession.Equals(_msnOrderAccession))
                {
                    msOrder = int.Parse(cv.value);
                }
                if (cv.accession.Equals(_centroidSpectrum))
                {
                    isCentroid = true;
                }
                if (cv.accession.Equals(_profileSpectrum))
                {
                    throw new MzLibException("Reading profile mode mzmls not supported");
                }
                if (cv.accession.Equals(_totalIonCurrent))
                {
                    tic = double.Parse(cv.value, CultureInfo.InvariantCulture);
                }
                if (polarity.Equals(Polarity.Unknown))
                {
                    polarityDictionary.TryGetValue(cv.accession, out polarity);
                }
            }

            if (!msOrder.HasValue || !isCentroid.HasValue)
            {
                throw new MzLibException("!msOrder.HasValue || !isCentroid.HasValue");
            }

            double[] masses      = new double[0];
            double[] intensities = new double[0];

            foreach (Generated.BinaryDataArrayType binaryData in _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].binaryDataArrayList.binaryDataArray)
            {
                bool compressed     = false;
                bool mzArray        = false;
                bool intensityArray = false;
                bool is32bit        = true;
                foreach (Generated.CVParamType cv in binaryData.cvParam)
                {
                    compressed     |= cv.accession.Equals(_zlibCompression);
                    is32bit        &= !cv.accession.Equals(_64bit);
                    is32bit        |= cv.accession.Equals(_32bit);
                    mzArray        |= cv.accession.Equals(_mzArray);
                    intensityArray |= cv.accession.Equals(_intensityArray);
                }

                double[] data = ConvertBase64ToDoubles(binaryData.binary, compressed, is32bit);
                if (mzArray)
                {
                    masses = data;
                }

                if (intensityArray)
                {
                    intensities = data;
                }
            }

            double high = double.NaN;
            double low  = double.NaN;

            var aScanWindowList = _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].scanList.scan[0].scanWindowList;

            if (aScanWindowList != null)
            {
                foreach (Generated.CVParamType cv in _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].scanList.scan[0].scanWindowList.scanWindow[0].cvParam)
                {
                    if (cv.accession.Equals(_scanWindowLowerLimit))
                    {
                        low = double.Parse(cv.value, CultureInfo.InvariantCulture);
                    }
                    else if (cv.accession.Equals(_scanWindowUpperLimit))
                    {
                        high = double.Parse(cv.value, CultureInfo.InvariantCulture);
                    }
                }
            }

            if (filterParams != null && intensities.Length > 0 && ((filterParams.ApplyTrimmingToMs1 && msOrder.Value == 1) || (filterParams.ApplyTrimmingToMsMs && msOrder.Value > 1)))
            {
                WindowModeHelper(ref intensities, ref masses, filterParams, low, high);
            }

            Array.Sort(masses, intensities);
            var mzmlMzSpectrum = new MzSpectrum(masses, intensities, false);

            double rtInMinutes        = double.NaN;
            string scanFilter         = null;
            double?injectionTime      = null;
            int    oneBasedScanNumber = oneBasedIndex;

            if (_mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].scanList.scan[0].cvParam != null)
            {
                foreach (Generated.CVParamType cv in _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].scanList.scan[0].cvParam)
                {
                    if (cv.accession.Equals(_retentionTime))
                    {
                        rtInMinutes = double.Parse(cv.value, CultureInfo.InvariantCulture);
                        if (cv.unitName == "second")
                        {
                            rtInMinutes /= 60;
                        }
                    }
                    if (cv.accession.Equals(_filterString))
                    {
                        scanFilter = cv.value;
                    }
                    if (cv.accession.Equals(_ionInjectionTime))
                    {
                        injectionTime = double.Parse(cv.value, CultureInfo.InvariantCulture);
                    }
                    if (cv.accession.Equals(_oneBasedScanNumber)) //get the real one based spectrum number (if available), the other assumes they are in order. This is present in .mgf->.mzml conversions from MSConvert
                    {
                        oneBasedScanNumber = int.Parse(cv.value);
                    }
                }
            }

            if (msOrder.Value == 1)
            {
                return(new MsDataScan(
                           mzmlMzSpectrum,
                           oneBasedScanNumber,
                           msOrder.Value,
                           isCentroid.Value,
                           polarity,
                           rtInMinutes,
                           new MzRange(low, high),
                           scanFilter,
                           analyzer,
                           tic,
                           injectionTime,
                           null,
                           nativeId));
            }

            double selectedIonMz        = double.NaN;
            int?   selectedIonCharge    = null;
            double?selectedIonIntensity = null;

            foreach (Generated.CVParamType cv in _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].precursorList.precursor[0].selectedIonList.selectedIon[0].cvParam)
            {
                if (cv.accession.Equals(_selectedIonMz))
                {
                    selectedIonMz = double.Parse(cv.value, CultureInfo.InvariantCulture);
                }
                if (cv.accession.Equals(_precursorCharge))
                {
                    selectedIonCharge = int.Parse(cv.value, CultureInfo.InvariantCulture);
                }
                if (cv.accession.Equals(_peakIntensity))
                {
                    selectedIonIntensity = double.Parse(cv.value, CultureInfo.InvariantCulture);
                }
            }

            double?isolationMz   = null;
            double lowIsolation  = double.NaN;
            double highIsolation = double.NaN;

            if (_mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].precursorList.precursor[0].isolationWindow != null)
            {
                foreach (Generated.CVParamType cv in _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].precursorList.precursor[0].isolationWindow.cvParam)
                {
                    if (cv.accession.Equals(_isolationWindowTargetMZ))
                    {
                        isolationMz = double.Parse(cv.value, CultureInfo.InvariantCulture);
                    }
                    if (cv.accession.Equals(_isolationWindowLowerOffset))
                    {
                        lowIsolation = double.Parse(cv.value, CultureInfo.InvariantCulture);
                    }
                    if (cv.accession.Equals(_isolationWindowUpperOffset))
                    {
                        highIsolation = double.Parse(cv.value, CultureInfo.InvariantCulture);
                    }
                }
            }

            DissociationType dissociationType = DissociationType.Unknown;

            if (_mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].precursorList.precursor[0].activation.cvParam != null)
            {
                foreach (Generated.CVParamType cv in _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].precursorList.precursor[0].activation.cvParam)
                {
                    dissociationDictionary.TryGetValue(cv.accession, out dissociationType);
                }
            }
            double?monoisotopicMz = null;

            if (_mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].scanList.scan[0].userParam != null)
            {
                foreach (var userParam in _mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].scanList.scan[0].userParam)
                {
                    if (userParam.name.EndsWith("Monoisotopic M/Z:"))
                    {
                        monoisotopicMz = double.Parse(userParam.value, CultureInfo.InvariantCulture);
                    }
                }
            }

            int?precursorScanNumber;

            if (_mzMLConnection.run.spectrumList.spectrum[oneBasedIndex - 1].precursorList.precursor[0].spectrumRef == null)
            {
                precursorScanNumber = null;
            }
            else
            {
                precursorScanNumber = GetOneBasedPrecursorScanNumber(_mzMLConnection, oneBasedIndex);
            }

            return(new MsDataScan(
                       mzmlMzSpectrum,
                       oneBasedIndex,
                       msOrder.Value,
                       isCentroid.Value,
                       polarity,
                       rtInMinutes,
                       new MzRange(low, high),
                       scanFilter,
                       analyzer,
                       tic,
                       injectionTime,
                       null,
                       nativeId,
                       selectedIonMz,
                       selectedIonCharge,
                       selectedIonIntensity,
                       isolationMz,
                       lowIsolation + highIsolation,
                       dissociationType,
                       precursorScanNumber,
                       monoisotopicMz
                       ));
        }
Exemplo n.º 18
0
        /// <summary>
        /// Allows access to a .raw file one scan at a time via an open dynamic connection. Returns null if the raw file does not contain the
        /// scan number specified. Use InitiateDynamicConnection to open a dynamic connection before using this method.
        /// </summary>
        public MsDataScan GetOneBasedScanFromDynamicConnection(int oneBasedScanNumber, IFilteringParams filterParams = null)
        {
            if (dynamicConnection == null)
            {
                throw new MzLibException("The dynamic connection has not been created yet!");
            }

            if (oneBasedScanNumber > dynamicConnection.RunHeaderEx.LastSpectrum || oneBasedScanNumber < dynamicConnection.RunHeaderEx.FirstSpectrum)
            {
                return(null);
            }

            return(ThermoRawFileReaderData.GetOneBasedScan(dynamicConnection, filterParams, oneBasedScanNumber));
        }
Exemplo n.º 19
0
        /// <summary>
        /// This method is designed to break a scan up into windows and take the top N peaks (by intensity)
        /// from each window, then merge the results as the scan's new mass spectrum
        /// </summary>
        /// <param name="intensities"></param>
        /// <param name="mArray"></param>
        /// <param name="filteringParams"></param>
        public static void WindowModeHelper(ref double[] intensities, ref double[] mArray, IFilteringParams filteringParams)
        {
            List <double> mzResults        = new List <double>();
            List <double> intensityResults = new List <double>();

            int windowSize = intensities.Length / filteringParams.NumberOfWindows.Value;

            // window must always have at least one peak in it
            if (windowSize < 1)
            {
                windowSize = 1;
            }

            int windowPeakIndexMinimum = 0;
            int windowPeakIndexMaximum = windowSize - 1;

            // this loop breaks a scan up into "windows" (e.g., a scan with 100 peaks
            // divided into 10 windows would have 10 peaks per window) and takes the top N peaks per window.
            // the results of each trimmed window are concatenated into mzResults and intensityResults
            for (int i = 0; i < filteringParams.NumberOfWindows; i++)
            {
                // make the last window end at the end of the spectrum
                // this is to prevent rounding errors in windowSize from cutting off the end of the spectrum
                if (i == filteringParams.NumberOfWindows - 1)
                {
                    windowPeakIndexMaximum = intensities.Length - 1;
                }

                // avoid index out of range problems
                if (windowPeakIndexMinimum >= intensities.Length)
                {
                    break;
                }

                // determine the valid peaks given filtering conditions for this window
                var windowIntensities = new double[windowPeakIndexMaximum - windowPeakIndexMinimum + 1];
                Array.Copy(intensities, windowPeakIndexMinimum, windowIntensities, 0, windowIntensities.Length);

                var windowMzs = new double[windowPeakIndexMaximum - windowPeakIndexMinimum + 1];
                Array.Copy(mArray, windowPeakIndexMinimum, windowMzs, 0, windowMzs.Length);

                int numPeaksToTakeInThisWindow = TopNpeakHelper(ref windowIntensities, ref windowMzs, filteringParams);

                // merge results of this window into the global results
                intensityResults.AddRange(windowIntensities.Take(numPeaksToTakeInThisWindow));
                mzResults.AddRange(windowMzs.Take(numPeaksToTakeInThisWindow));

                // set up for the next window
                windowPeakIndexMinimum = windowPeakIndexMaximum + 1;
                windowPeakIndexMaximum = windowPeakIndexMinimum + windowSize;
            }

            // convert merged results to array and sort by m/z
            mArray      = mzResults.ToArray();
            intensities = intensityResults.ToArray();

            Array.Sort(mArray, intensities);
        }
Exemplo n.º 20
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.º 21
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.º 22
0
        public static void WindowModeHelper(ref double[] intensities, ref double[] mArray, IFilteringParams filteringParams)
        {
            List <double> mzResults        = new List <double>();
            List <double> intensityResults = new List <double>();

            //windowNum is the number of windows
            for (int i = 0; i < filteringParams.NumberOfWindows; i++)
            {
                int temp          = (i == filteringParams.NumberOfWindows) ? intensities.Length - i * (intensities.Length / filteringParams.NumberOfWindows.Value) : intensities.Length / filteringParams.NumberOfWindows.Value;
                var mzTemp        = new double[temp];
                var intensityTemp = new double[temp];

                Buffer.BlockCopy(mArray, sizeof(double) * temp * i, mzTemp, 0, sizeof(double) * temp);
                Buffer.BlockCopy(intensities, sizeof(double) * temp * i, intensityTemp, 0, sizeof(double) * temp);

                int numPeaks = TopNpeakHelper(intensities, mArray, filteringParams);
                Array.Resize(ref intensityTemp, numPeaks);
                Array.Resize(ref mzTemp, numPeaks);
                mzResults.AddRange(mzTemp);
                intensityResults.AddRange(intensityTemp);
            }
            mArray      = mzResults.ToArray();
            intensities = intensityResults.ToArray();
        }
Exemplo n.º 23
0
        /// <summary>
        /// Loads all scan data from a Thermo .raw file.
        /// </summary>
        public static ThermoRawFileReader LoadAllStaticData(string filePath, IFilteringParams filterParams = null, int maxThreads = -1)
        {
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException();
            }

            Loaders.LoadElements();

            // I don't know why this line needs to be here, but it does...
            var temp = RawFileReaderAdapter.FileFactory(filePath);

            var threadManager   = RawFileReaderFactory.CreateThreadManager(filePath);
            var rawFileAccessor = threadManager.CreateThreadAccessor();

            if (!rawFileAccessor.IsOpen)
            {
                throw new MzLibException("Unable to access RAW file!");
            }

            if (rawFileAccessor.IsError)
            {
                throw new MzLibException("Error opening RAW file!");
            }

            if (rawFileAccessor.InAcquisition)
            {
                throw new MzLibException("RAW file still being acquired!");
            }

            rawFileAccessor.SelectInstrument(Device.MS, 1);
            var msDataScans = new MsDataScan[rawFileAccessor.RunHeaderEx.LastSpectrum];

            Parallel.ForEach(Partitioner.Create(0, msDataScans.Length), new ParallelOptions {
                MaxDegreeOfParallelism = maxThreads
            }, (fff, loopState) =>
            {
                IRawDataPlus myThreadDataReader = threadManager.CreateThreadAccessor();
                myThreadDataReader.SelectInstrument(Device.MS, 1);

                for (int s = fff.Item1; s < fff.Item2; s++)
                {
                    try
                    {
                        var scan       = GetOneBasedScan(myThreadDataReader, filterParams, s + 1);
                        msDataScans[s] = scan;
                    }
                    catch (Exception ex)
                    {
                        throw new MzLibException("Error reading scan " + (s + 1) + ": " + ex.Message);
                    }
                }
            });

            rawFileAccessor.Dispose();

            string sendCheckSum;

            using (FileStream stream = File.OpenRead(filePath))
            {
                using (SHA1Managed sha = new SHA1Managed())
                {
                    byte[] checksum = sha.ComputeHash(stream);
                    sendCheckSum = BitConverter.ToString(checksum)
                                   .Replace("-", string.Empty);
                }
            }

            SourceFile sourceFile = new SourceFile(
                @"Thermo nativeID format",
                @"Thermo RAW format",
                sendCheckSum,
                @"SHA-1",
                filePath,
                Path.GetFileNameWithoutExtension(filePath));

            return(new ThermoRawFileReader(msDataScans, sourceFile));
        }
Exemplo n.º 24
0
        public override MsDataScan GetOneBasedScanFromDynamicConnection(int scanNumber, IFilteringParams filterParams = null)
        {
            if (reader == null)
            {
                throw new MzLibException("Cannot get scan; the dynamic data connection to " + FilePath + " has been closed!");
            }

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

                return(Mgf.GetNextMsDataOneBasedScanFromConnection(reader, new HashSet <int>(), filterParams, scanNumber));
            }
            else
            {
                throw new MzLibException("The specified scan number: " + scanNumber + " does not exist in " + FilePath);
            }
        }