Search in sources :

Example 66 with Feature

use of net.sf.mzmine.datamodel.Feature in project mzmine2 by mzmine.

the class PCADataset method run.

@Override
public void run() {
    status = TaskStatus.PROCESSING;
    logger.info("Computing PCA projection plot");
    // Generate matrix of raw data (input to PCA)
    final boolean useArea = (parameters.getParameter(ProjectionPlotParameters.peakMeasurementType).getValue() == PeakMeasurementType.AREA);
    if (selectedRows.length == 0) {
        this.status = TaskStatus.ERROR;
        errorMessage = "No peaks selected for PCA plot";
        return;
    }
    if (selectedRawDataFiles.length == 0) {
        this.status = TaskStatus.ERROR;
        errorMessage = "No raw data files selected for PCA plot";
        return;
    }
    double[][] rawData = new double[selectedRawDataFiles.length][selectedRows.length];
    for (int rowIndex = 0; rowIndex < selectedRows.length; rowIndex++) {
        PeakListRow peakListRow = selectedRows[rowIndex];
        for (int fileIndex = 0; fileIndex < selectedRawDataFiles.length; fileIndex++) {
            RawDataFile rawDataFile = selectedRawDataFiles[fileIndex];
            Feature p = peakListRow.getPeak(rawDataFile);
            if (p != null) {
                if (useArea)
                    rawData[fileIndex][rowIndex] = p.getArea();
                else
                    rawData[fileIndex][rowIndex] = p.getHeight();
            }
        }
    }
    int numComponents = xAxisPC;
    if (yAxisPC > numComponents)
        numComponents = yAxisPC;
    // Scale data and do PCA
    Preprocess.scaleToUnityVariance(rawData);
    // Replace NaN values with 0.0
    for (int i = 0; i < rawData.length; i++) {
        for (int j = 0; j < rawData[i].length; j++) {
            if (Double.isNaN(rawData[i][j]))
                rawData[i][j] = 0.0;
        }
    }
    PCA pcaProj = new PCA(rawData, numComponents);
    projectionStatus = pcaProj.getProjectionStatus();
    double[][] result = pcaProj.getState();
    if (status == TaskStatus.CANCELED)
        return;
    component1Coords = result[xAxisPC - 1];
    component2Coords = result[yAxisPC - 1];
    ProjectionPlotWindow newFrame = new ProjectionPlotWindow(peakList, this, parameters);
    newFrame.setVisible(true);
    status = TaskStatus.FINISHED;
    logger.info("Finished computing projection plot.");
}
Also used : PeakListRow(net.sf.mzmine.datamodel.PeakListRow) RawDataFile(net.sf.mzmine.datamodel.RawDataFile) Feature(net.sf.mzmine.datamodel.Feature) PCA(jmprojection.PCA)

Example 67 with Feature

use of net.sf.mzmine.datamodel.Feature 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)

Example 68 with Feature

use of net.sf.mzmine.datamodel.Feature in project mzmine2 by mzmine.

the class SimplePeakListRow method getAllMS2Fragmentations.

@Override
@Nonnull
public Scan[] getAllMS2Fragmentations() {
    ArrayList<Scan> allMS2ScansList = new ArrayList<>();
    for (Feature peak : this.getPeaks()) {
        RawDataFile rawData = peak.getDataFile();
        int[] scanNumbers = peak.getAllMS2FragmentScanNumbers();
        if (scanNumbers != null) {
            for (int scanNumber : scanNumbers) {
                Scan scan = rawData.getScan(scanNumber);
                allMS2ScansList.add(scan);
            }
        }
    }
    return allMS2ScansList.toArray(new Scan[allMS2ScansList.size()]);
}
Also used : RawDataFile(net.sf.mzmine.datamodel.RawDataFile) ArrayList(java.util.ArrayList) Scan(net.sf.mzmine.datamodel.Scan) Feature(net.sf.mzmine.datamodel.Feature) Nonnull(javax.annotation.Nonnull)

Example 69 with Feature

use of net.sf.mzmine.datamodel.Feature in project mzmine2 by mzmine.

the class SimplePeakListRow method getBestFragmentation.

@Override
public Scan getBestFragmentation() {
    Double bestTIC = 0.0;
    Scan bestScan = null;
    for (Feature peak : this.getPeaks()) {
        Double theTIC = 0.0;
        RawDataFile rawData = peak.getDataFile();
        int bestScanNumber = peak.getMostIntenseFragmentScanNumber();
        Scan theScan = rawData.getScan(bestScanNumber);
        if (theScan != null) {
            theTIC = theScan.getTIC();
        }
        if (theTIC > bestTIC) {
            bestTIC = theTIC;
            bestScan = theScan;
        }
    }
    return bestScan;
}
Also used : RawDataFile(net.sf.mzmine.datamodel.RawDataFile) Scan(net.sf.mzmine.datamodel.Scan) Feature(net.sf.mzmine.datamodel.Feature)

Example 70 with Feature

use of net.sf.mzmine.datamodel.Feature in project mzmine2 by mzmine.

the class NeutralLossFilterTask method copyPeakRow.

/**
 * Create a copy of a feature list row.
 *
 * @param row the row to copy.
 * @return the newly created copy.
 */
private static PeakListRow copyPeakRow(final PeakListRow row) {
    // Copy the feature list row.
    final PeakListRow newRow = new SimplePeakListRow(row.getID());
    PeakUtils.copyPeakListRowProperties(row, newRow);
    // Copy the peaks.
    for (final Feature peak : row.getPeaks()) {
        final Feature newPeak = new SimpleFeature(peak);
        PeakUtils.copyPeakProperties(peak, newPeak);
        newRow.addPeak(peak.getDataFile(), newPeak);
    }
    return newRow;
}
Also used : SimplePeakListRow(net.sf.mzmine.datamodel.impl.SimplePeakListRow) PeakListRow(net.sf.mzmine.datamodel.PeakListRow) SimplePeakListRow(net.sf.mzmine.datamodel.impl.SimplePeakListRow) Feature(net.sf.mzmine.datamodel.Feature) SimpleFeature(net.sf.mzmine.datamodel.impl.SimpleFeature) SimpleFeature(net.sf.mzmine.datamodel.impl.SimpleFeature)

Aggregations

Feature (net.sf.mzmine.datamodel.Feature)115 PeakListRow (net.sf.mzmine.datamodel.PeakListRow)70 RawDataFile (net.sf.mzmine.datamodel.RawDataFile)60 SimplePeakListRow (net.sf.mzmine.datamodel.impl.SimplePeakListRow)41 DataPoint (net.sf.mzmine.datamodel.DataPoint)35 SimpleFeature (net.sf.mzmine.datamodel.impl.SimpleFeature)35 SimplePeakList (net.sf.mzmine.datamodel.impl.SimplePeakList)25 Scan (net.sf.mzmine.datamodel.Scan)22 PeakList (net.sf.mzmine.datamodel.PeakList)20 ArrayList (java.util.ArrayList)17 SimplePeakListAppliedMethod (net.sf.mzmine.datamodel.impl.SimplePeakListAppliedMethod)16 IsotopePattern (net.sf.mzmine.datamodel.IsotopePattern)15 PeakIdentity (net.sf.mzmine.datamodel.PeakIdentity)15 SimpleDataPoint (net.sf.mzmine.datamodel.impl.SimpleDataPoint)13 PeakListAppliedMethod (net.sf.mzmine.datamodel.PeakList.PeakListAppliedMethod)10 MassList (net.sf.mzmine.datamodel.MassList)9 HashMap (java.util.HashMap)8 Vector (java.util.Vector)8 ScanSelection (net.sf.mzmine.parameters.parametertypes.selectors.ScanSelection)7 TreeMap (java.util.TreeMap)6