Search in sources :

Example 6 with PeakSorter

use of net.sf.mzmine.util.PeakSorter in project mzmine2 by mzmine.

the class PeakExtenderTask method run.

/**
 * @see Runnable#run()
 */
public void run() {
    setStatus(TaskStatus.PROCESSING);
    logger.info("Running peak extender on " + peakList);
    // We assume source peakList contains one datafile
    RawDataFile dataFile = peakList.getRawDataFile(0);
    // Create a new deisotoped peakList
    extendedPeakList = new SimplePeakList(peakList + " " + suffix, peakList.getRawDataFiles());
    // Sort peaks by descending height
    Feature[] sortedPeaks = peakList.getPeaks(dataFile);
    Arrays.sort(sortedPeaks, new PeakSorter(SortingProperty.Height, SortingDirection.Descending));
    // Loop through all peaks
    totalPeaks = sortedPeaks.length;
    Feature oldPeak;
    for (int ind = 0; ind < totalPeaks; ind++) {
        if (isCanceled())
            return;
        oldPeak = sortedPeaks[ind];
        if (oldPeak.getHeight() >= minimumHeight) {
            Feature newPeak = this.getExtendedPeak(oldPeak);
            // Get previous pekaListRow
            PeakListRow oldRow = peakList.getPeakRow(oldPeak);
            // keep old ID
            int oldID = oldRow.getID();
            SimplePeakListRow newRow = new SimplePeakListRow(oldID);
            PeakUtils.copyPeakListRowProperties(oldRow, newRow);
            newRow.addPeak(dataFile, newPeak);
            extendedPeakList.addRow(newRow);
        }
        // Update completion rate
        processedPeaks++;
    }
    // Add new peakList to the project
    project.addPeakList(extendedPeakList);
    // Add quality parameters to peaks
    QualityParameters.calculateQualityParameters(extendedPeakList);
    // Load previous applied methods
    for (PeakListAppliedMethod proc : peakList.getAppliedMethods()) {
        extendedPeakList.addDescriptionOfAppliedTask(proc);
    }
    // Add task description to peakList
    extendedPeakList.addDescriptionOfAppliedTask(new SimplePeakListAppliedMethod("Peak extender", parameters));
    // Remove the original peakList if requested
    if (removeOriginal)
        project.removePeakList(peakList);
    logger.info("Finished peak extender on " + peakList);
    setStatus(TaskStatus.FINISHED);
}
Also used : SimplePeakListRow(net.sf.mzmine.datamodel.impl.SimplePeakListRow) PeakListRow(net.sf.mzmine.datamodel.PeakListRow) RawDataFile(net.sf.mzmine.datamodel.RawDataFile) SimplePeakListAppliedMethod(net.sf.mzmine.datamodel.impl.SimplePeakListAppliedMethod) PeakListAppliedMethod(net.sf.mzmine.datamodel.PeakList.PeakListAppliedMethod) PeakSorter(net.sf.mzmine.util.PeakSorter) SimplePeakList(net.sf.mzmine.datamodel.impl.SimplePeakList) SimplePeakListAppliedMethod(net.sf.mzmine.datamodel.impl.SimplePeakListAppliedMethod) Feature(net.sf.mzmine.datamodel.Feature) SimplePeakListRow(net.sf.mzmine.datamodel.impl.SimplePeakListRow) DataPoint(net.sf.mzmine.datamodel.DataPoint)

Example 7 with PeakSorter

use of net.sf.mzmine.util.PeakSorter in project mzmine2 by mzmine.

the class ADAPChromatogramBuilderTask method run.

/**
 * @see Runnable#run()
 */
public void run() {
    boolean writeChromCDF = true;
    setStatus(TaskStatus.PROCESSING);
    logger.info("Started chromatogram builder on " + dataFile);
    scans = scanSelection.getMatchingScans(dataFile);
    int[] allScanNumbers = scanSelection.getMatchingScanNumbers(dataFile);
    List<Double> rtListForChromCDF = new ArrayList<Double>();
    // Check if the scans are properly ordered by RT
    double prevRT = Double.NEGATIVE_INFINITY;
    for (Scan s : scans) {
        if (isCanceled()) {
            return;
        }
        if (writeChromCDF) {
            rtListForChromCDF.add(s.getRetentionTime());
        }
        if (s.getRetentionTime() < prevRT) {
            setStatus(TaskStatus.ERROR);
            final String msg = "Retention time of scan #" + s.getScanNumber() + " is smaller then the retention time of the previous scan." + " Please make sure you only use scans with increasing retention times." + " You can restrict the scan numbers in the parameters, or you can use the Crop filter module";
            setErrorMessage(msg);
            return;
        }
        prevRT = s.getRetentionTime();
    }
    // Check if the scans are MS1-only or MS2-only.
    int minMsLevel = Arrays.stream(scans).mapToInt(Scan::getMSLevel).min().orElseThrow(() -> new IllegalStateException("Cannot find the minimum MS level"));
    int maxMsLevel = Arrays.stream(scans).mapToInt(Scan::getMSLevel).max().orElseThrow(() -> new IllegalStateException("Cannot find the maximum MS level"));
    if (minMsLevel != maxMsLevel) {
        MZmineCore.getDesktop().displayMessage(null, "MZmine thinks that you are running ADAP Chromatogram builder on both MS1- and MS2-scans. " + "This will likely produce wrong results. " + "Please, set the scan filter parameter to a specific MS level");
    }
    // Create new feature list
    newPeakList = new SimplePeakList(dataFile + " " + suffix, dataFile);
    // make a list of all the data points
    // sort data points by intensity
    // loop through list
    // add data point to chromatogrm or make new one
    // update mz avg and other stuff
    // 
    // make a list of all the data points
    List<ExpandedDataPoint> allMzValues = new ArrayList<ExpandedDataPoint>();
    for (Scan scan : scans) {
        if (isCanceled())
            return;
        MassList massList = scan.getMassList(massListName);
        if (massList == null) {
            setStatus(TaskStatus.ERROR);
            setErrorMessage("Scan " + dataFile + " #" + scan.getScanNumber() + " does not have a mass list " + massListName);
            return;
        }
        DataPoint[] mzValues = massList.getDataPoints();
        if (mzValues == null) {
            setStatus(TaskStatus.ERROR);
            setErrorMessage("Mass list " + massListName + " does not contain m/z values for scan #" + scan.getScanNumber() + " of file " + dataFile);
            return;
        }
        for (DataPoint mzPeak : mzValues) {
            ExpandedDataPoint curDatP = new ExpandedDataPoint(mzPeak, scan.getScanNumber());
            allMzValues.add(curDatP);
        // corespondingScanNum.add(scan.getScanNumber());
        }
    }
    // Integer[] simpleCorespondingScanNums = new Integer[corespondingScanNum.size()];
    // corespondingScanNum.toArray(simpleCorespondingScanNums );
    ExpandedDataPoint[] simpleAllMzVals = new ExpandedDataPoint[allMzValues.size()];
    allMzValues.toArray(simpleAllMzVals);
    // sort data points by intensity
    Arrays.sort(simpleAllMzVals, new DataPointSorter(SortingProperty.Intensity, SortingDirection.Descending));
    // Exit if no peaks
    if (simpleAllMzVals.length == 0) {
        progress = 1.0;
        setStatus(TaskStatus.FINISHED);
        logger.info("Finished chromatogram builder with no peaks on " + dataFile);
        return;
    }
    double maxIntensity = simpleAllMzVals[0].getIntensity();
    // count starts at 1 since we already have added one with a single point.
    // Stopwatch stopwatch = Stopwatch.createUnstarted();
    // stopwatch2 = Stopwatch.createUnstarted();
    // Stopwatch stopwatch3 = Stopwatch.createUnstarted();
    progress = 0.0;
    double progressStep = (simpleAllMzVals.length > 0) ? 0.5 / simpleAllMzVals.length : 0.0;
    for (ExpandedDataPoint mzPeak : simpleAllMzVals) {
        progress += progressStep;
        if (isCanceled()) {
            return;
        }
        if (mzPeak == null || Double.isNaN(mzPeak.getMZ()) || Double.isNaN(mzPeak.getIntensity())) {
            continue;
        }
        // ////////////////////////////////////////////////
        Range<Double> containsPointRange = rangeSet.rangeContaining(mzPeak.getMZ());
        Range<Double> toleranceRange = mzTolerance.getToleranceRange(mzPeak.getMZ());
        if (containsPointRange == null) {
            // skip it entierly if the intensity is not high enough
            if (mzPeak.getIntensity() < minIntensityForStartChrom) {
                continue;
            }
            // look +- mz tolerance to see if ther is a range near by.
            // If there is use the proper boundry of that range for the
            // new range to insure than NON OF THE RANGES OVERLAP.
            Range<Double> plusRange = rangeSet.rangeContaining(toleranceRange.upperEndpoint());
            Range<Double> minusRange = rangeSet.rangeContaining(toleranceRange.lowerEndpoint());
            Double toBeLowerBound;
            Double toBeUpperBound;
            double cur_max_testing_mz = mzPeak.getMZ();
            // chromatogram so that none of the points are overlapping.
            if ((plusRange == null) && (minusRange == null)) {
                toBeLowerBound = toleranceRange.lowerEndpoint();
                toBeUpperBound = toleranceRange.upperEndpoint();
            } else if ((plusRange == null) && (minusRange != null)) {
                // the upper end point of the minus range will be the lower
                // range of the new one
                toBeLowerBound = minusRange.upperEndpoint();
                toBeUpperBound = toleranceRange.upperEndpoint();
            } else if ((minusRange == null) && (plusRange != null)) {
                toBeLowerBound = toleranceRange.lowerEndpoint();
                toBeUpperBound = plusRange.lowerEndpoint();
            // double tmp_this = plusRange.upperEndpoint();
            // System.out.println("tmp_this");
            } else if ((minusRange != null) && (plusRange != null)) {
                toBeLowerBound = minusRange.upperEndpoint();
                toBeUpperBound = plusRange.lowerEndpoint();
            } else {
                toBeLowerBound = 0.0;
                toBeUpperBound = 0.0;
            }
            if (toBeLowerBound < toBeUpperBound) {
                Range<Double> newRange = Range.open(toBeLowerBound, toBeUpperBound);
                ADAPChromatogram newChrom = new ADAPChromatogram(dataFile, allScanNumbers);
                newChrom.addMzPeak(mzPeak.getScanNumber(), mzPeak);
                newChrom.setHighPointMZ(mzPeak.getMZ());
                rangeToChromMap.put(newRange, newChrom);
                // also need to put it in the set -> this is where the range can be efficiently found.
                rangeSet.add(newRange);
            } else if (toBeLowerBound.equals(toBeUpperBound) && plusRange != null) {
                ADAPChromatogram curChrom = rangeToChromMap.get(plusRange);
                curChrom.addMzPeak(mzPeak.getScanNumber(), mzPeak);
            } else
                throw new IllegalStateException(String.format("Incorrect range [%f, %f] for m/z %f", toBeLowerBound, toBeUpperBound, mzPeak.getMZ()));
        } else {
            // In this case we do not need to update the rangeSet
            ADAPChromatogram curChrom = rangeToChromMap.get(containsPointRange);
            curChrom.addMzPeak(mzPeak.getScanNumber(), mzPeak);
            // update the entry in the map
            rangeToChromMap.put(containsPointRange, curChrom);
        }
    }
    // System.out.println("search chroms (ms): " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
    // System.out.println("making new chrom (ms): " + stopwatch2.elapsed(TimeUnit.MILLISECONDS));
    // finish chromatograms
    Set<Range<Double>> ranges = rangeSet.asRanges();
    Iterator<Range<Double>> RangeIterator = ranges.iterator();
    List<ADAPChromatogram> buildingChromatograms = new ArrayList<ADAPChromatogram>();
    progressStep = (ranges.size() > 0) ? 0.5 / ranges.size() : 0.0;
    while (RangeIterator.hasNext()) {
        if (isCanceled()) {
            return;
        }
        progress += progressStep;
        Range<Double> curRangeKey = RangeIterator.next();
        ADAPChromatogram chromatogram = rangeToChromMap.get(curRangeKey);
        chromatogram.finishChromatogram();
        // And remove chromatograms who dont have a certian number of continous points above the
        // IntensityThresh2 level.
        double numberOfContinuousPointsAboveNoise = chromatogram.findNumberOfContinuousPointsAboveNoise(IntensityThresh2);
        if (numberOfContinuousPointsAboveNoise < minimumScanSpan) {
            // requirements");
            continue;
        } else {
            buildingChromatograms.add(chromatogram);
        }
    }
    ADAPChromatogram[] chromatograms = buildingChromatograms.toArray(new ADAPChromatogram[0]);
    // Sort the final chromatograms by m/z
    Arrays.sort(chromatograms, new PeakSorter(SortingProperty.MZ, SortingDirection.Ascending));
    // Add the chromatograms to the new feature list
    for (Feature finishedPeak : chromatograms) {
        SimplePeakListRow newRow = new SimplePeakListRow(newPeakID);
        newPeakID++;
        newRow.addPeak(dataFile, finishedPeak);
        newPeakList.addRow(newRow);
    // finishedPeak.outputChromToFile();
    }
    // Add new peaklist to the project
    project.addPeakList(newPeakList);
    // Add quality parameters to peaks
    QualityParameters.calculateQualityParameters(newPeakList);
    progress = 1.0;
    setStatus(TaskStatus.FINISHED);
    logger.info("Finished chromatogram builder on " + dataFile);
}
Also used : Feature(net.sf.mzmine.datamodel.Feature) SimplePeakListRow(net.sf.mzmine.datamodel.impl.SimplePeakListRow) DataPoint(net.sf.mzmine.datamodel.DataPoint) PeakSorter(net.sf.mzmine.util.PeakSorter) SimplePeakList(net.sf.mzmine.datamodel.impl.SimplePeakList) Range(com.google.common.collect.Range) DataPoint(net.sf.mzmine.datamodel.DataPoint) DataPointSorter(net.sf.mzmine.util.DataPointSorter) Scan(net.sf.mzmine.datamodel.Scan) MassList(net.sf.mzmine.datamodel.MassList)

Aggregations

Feature (net.sf.mzmine.datamodel.Feature)7 PeakSorter (net.sf.mzmine.util.PeakSorter)7 SimplePeakList (net.sf.mzmine.datamodel.impl.SimplePeakList)5 SimplePeakListRow (net.sf.mzmine.datamodel.impl.SimplePeakListRow)5 DataPoint (net.sf.mzmine.datamodel.DataPoint)4 PeakListRow (net.sf.mzmine.datamodel.PeakListRow)3 RawDataFile (net.sf.mzmine.datamodel.RawDataFile)3 MassList (net.sf.mzmine.datamodel.MassList)2 PeakListAppliedMethod (net.sf.mzmine.datamodel.PeakList.PeakListAppliedMethod)2 Scan (net.sf.mzmine.datamodel.Scan)2 SimpleFeature (net.sf.mzmine.datamodel.impl.SimpleFeature)2 SimplePeakListAppliedMethod (net.sf.mzmine.datamodel.impl.SimplePeakListAppliedMethod)2 Range (com.google.common.collect.Range)1 Vector (java.util.Vector)1 IsotopePattern (net.sf.mzmine.datamodel.IsotopePattern)1 SimpleDataPoint (net.sf.mzmine.datamodel.impl.SimpleDataPoint)1 SimpleIsotopePattern (net.sf.mzmine.datamodel.impl.SimpleIsotopePattern)1 DataPointSorter (net.sf.mzmine.util.DataPointSorter)1