Search in sources :

Example 76 with Feature

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

the class GroupMS2Task method run.

@Override
public void run() {
    try {
        setStatus(TaskStatus.PROCESSING);
        totalRows = list.getNumberOfRows();
        // for all features
        for (PeakListRow row : list.getRows()) {
            for (Feature f : row.getPeaks()) {
                if (getStatus() == TaskStatus.ERROR)
                    return;
                if (isCanceled())
                    return;
                RawDataFile raw = f.getDataFile();
                IntArrayList scans = new IntArrayList();
                int best = f.getRepresentativeScanNumber();
                double frt = f.getRT();
                double fmz = f.getMZ();
                Range<Double> rtRange = f.getRawDataPointsRTRange();
                int i = best;
                // left
                while (i > 1) {
                    i--;
                    Scan scan = raw.getScan(i);
                    if (scan != null) {
                        if ((!limitRTByFeature || rtRange.contains(scan.getRetentionTime())) && rtTol.checkWithinTolerance(frt, scan.getRetentionTime())) {
                            if (scan.getPrecursorMZ() != 0 && mzTol.checkWithinTolerance(fmz, scan.getPrecursorMZ()))
                                scans.add(i);
                        } else {
                            // end of loop - out of tolerance
                            break;
                        }
                    }
                }
                int[] scanNumbers = raw.getScanNumbers();
                // right
                while (i < scanNumbers[scanNumbers.length - 1]) {
                    i++;
                    Scan scan = raw.getScan(i);
                    // scanID does not have to be contiguous
                    if (scan != null) {
                        if ((!limitRTByFeature || rtRange.contains(scan.getRetentionTime())) && rtTol.checkWithinTolerance(frt, scan.getRetentionTime())) {
                            if (scan.getPrecursorMZ() != 0 && mzTol.checkWithinTolerance(fmz, scan.getPrecursorMZ()))
                                scans.add(i);
                        } else {
                            // end of loop - out of tolerance
                            break;
                        }
                    }
                }
                // set list to feature
                f.setAllMS2FragmentScanNumbers(scans.toIntArray());
            }
            processedRows++;
        }
        setStatus(TaskStatus.FINISHED);
        LOG.info("Finished adding all MS2 scans to their features in " + list.getName());
    } catch (Throwable t) {
        t.printStackTrace();
        setErrorMessage(t.getMessage());
        setStatus(TaskStatus.ERROR);
        LOG.log(Level.SEVERE, "Error while adding all MS2 scans to their feautres", t);
    }
}
Also used : PeakListRow(net.sf.mzmine.datamodel.PeakListRow) RawDataFile(net.sf.mzmine.datamodel.RawDataFile) Scan(net.sf.mzmine.datamodel.Scan) IntArrayList(it.unimi.dsi.fastutil.ints.IntArrayList) Feature(net.sf.mzmine.datamodel.Feature)

Example 77 with Feature

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

the class DuplicateFilterTask method copyPeak.

public Feature copyPeak(Feature peak) {
    // Copy the peaks.
    final Feature newPeak = new SimpleFeature(peak);
    PeakUtils.copyPeakProperties(peak, newPeak);
    return newPeak;
}
Also used : SimpleFeature(net.sf.mzmine.datamodel.impl.SimpleFeature) Feature(net.sf.mzmine.datamodel.Feature) SimpleFeature(net.sf.mzmine.datamodel.impl.SimpleFeature)

Example 78 with Feature

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

the class DuplicateFilterTask method checkSameSingleFeatureRTMZ.

/**
 * Has one feature within RT and mzTolerance in at least one raw data file
 *
 * @param rawFiles
 * @param firstRow
 * @param secondRow
 * @param mzTolerance
 * @param rtTolerance
 * @return
 */
private boolean checkSameSingleFeatureRTMZ(RawDataFile[] rawFiles, PeakListRow firstRow, PeakListRow secondRow, MZTolerance mzTolerance, RTTolerance rtTolerance) {
    // at least one similar feature in one raw data file
    for (RawDataFile raw : rawFiles) {
        Feature f1 = firstRow.getPeak(raw);
        Feature f2 = secondRow.getPeak(raw);
        // Compare m/z and rt
        if (f1 != null && f2 != null && mzTolerance.checkWithinTolerance(f1.getMZ(), f2.getMZ()) && rtTolerance.checkWithinTolerance(f1.getRT(), f2.getRT()))
            return true;
    }
    return false;
}
Also used : RawDataFile(net.sf.mzmine.datamodel.RawDataFile) SimpleFeature(net.sf.mzmine.datamodel.impl.SimpleFeature) Feature(net.sf.mzmine.datamodel.Feature)

Example 79 with Feature

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

the class CameraSearchTask method cameraSearch.

/**
 * Perform CAMERA search.
 *
 * @param rawFile raw data file of feature list to process.
 */
private void cameraSearch(final RawDataFile rawFile) {
    LOG.finest("Detecting peaks.");
    errorMsg = null;
    try {
        String[] reqPackages = { "CAMERA" };
        String[] reqPackagesVersions = { CAMERA_VERSION };
        this.rSession = new RSessionWrapper(this.rEngineType, "Camera search feature", reqPackages, reqPackagesVersions);
        this.rSession.open();
        // Create empty peaks matrix.
        this.rSession.eval("columnHeadings <- c('mz','mzmin','mzmax','rt','rtmin','rtmax','into','intb','maxo','sn')");
        this.rSession.eval("peaks <- matrix(nrow=0, ncol=length(columnHeadings))");
        this.rSession.eval("colnames(peaks) <- columnHeadings");
        // Initialize.
        final Feature[] peaks = peakList.getPeaks(rawFile);
        progress = 0.0;
        // Initialize scan map.
        final Map<Scan, Set<DataPoint>> peakDataPointsByScan = new HashMap<Scan, Set<DataPoint>>(rawFile.getNumOfScans(MS_LEVEL));
        int dataPointCount = 0;
        for (final int scanNumber : rawFile.getScanNumbers(MS_LEVEL)) {
            // Create a set to hold data points (sorted by m/z).
            final Set<DataPoint> dataPoints = new TreeSet<DataPoint>(ASCENDING_MASS_SORTER);
            // Add a dummy data point.
            dataPoints.add(new SimpleDataPoint(0.0, 0.0));
            dataPointCount++;
            // Map the set.
            peakDataPointsByScan.put(rawFile.getScan(scanNumber), dataPoints);
        }
        // Add peaks.
        // 80 percents for building peaks list.
        double progressInc = 0.8 / (double) peaks.length;
        for (final Feature peak : peaks) {
            // Get peak data.
            Range<Double> rtRange = null;
            Range<Double> intRange = null;
            final double mz = peak.getMZ();
            // Get the peak's data points per scan.
            for (final int scanNumber : peak.getScanNumbers()) {
                final Scan scan = rawFile.getScan(scanNumber);
                if (scan.getMSLevel() != MS_LEVEL) {
                    throw new IllegalStateException("CAMERA can only process feature lists from MS-level " + MS_LEVEL);
                }
                // Copy the data point.
                final DataPoint dataPoint = peak.getDataPoint(scanNumber);
                if (dataPoint != null) {
                    final double intensity = dataPoint.getIntensity();
                    peakDataPointsByScan.get(scan).add(new SimpleDataPoint(mz, intensity));
                    dataPointCount++;
                    // Update RT & intensity range.
                    final double rt = scan.getRetentionTime();
                    if (rtRange == null) {
                        rtRange = Range.singleton(rt);
                        intRange = Range.singleton(intensity);
                    } else {
                        rtRange = rtRange.span(Range.singleton(rt));
                        intRange = intRange.span(Range.singleton(intensity));
                    }
                }
            }
            // Set peak values.
            final double area = peak.getArea();
            final double maxo = intRange == null ? peak.getHeight() : intRange.upperEndpoint();
            final double rtMin = (rtRange == null ? peak.getRawDataPointsRTRange() : rtRange).lowerEndpoint();
            final double rtMax = (rtRange == null ? peak.getRawDataPointsRTRange() : rtRange).upperEndpoint();
            // Add peak row.
            this.rSession.eval(// mz
            "peaks <- rbind(peaks, c(" + mz + ", " + mz + // mzmin: use the same as mz.
            ", " + mz + // mzmax: use the same as mz.
            ", " + peak.getRT() + // rt
            ", " + rtMin + // rtmin
            ", " + rtMax + // rtmax
            ", " + area + // into: peak area.
            ", " + area + // intb: doesn't affect result, use area.
            ", " + maxo + // maxo
            ", " + SIGNAL_TO_NOISE + "))", false);
            progress += progressInc;
        }
        // 20 percents (5*4) for building pseudo-isotopes groups.
        progressInc = 0.05;
        // Create R vectors.
        final int scanCount = peakDataPointsByScan.size();
        final double[] scanTimes = new double[scanCount];
        final int[] scanIndices = new int[scanCount];
        final double[] masses = new double[dataPointCount];
        final double[] intensities = new double[dataPointCount];
        // Fill vectors.
        int scanIndex = 0;
        int pointIndex = 0;
        for (final int scanNumber : rawFile.getScanNumbers(MS_LEVEL)) {
            final Scan scan = rawFile.getScan(scanNumber);
            scanTimes[scanIndex] = scan.getRetentionTime();
            scanIndices[scanIndex] = pointIndex + 1;
            scanIndex++;
            for (final DataPoint dataPoint : peakDataPointsByScan.get(scan)) {
                masses[pointIndex] = dataPoint.getMZ();
                intensities[pointIndex] = dataPoint.getIntensity();
                pointIndex++;
            }
        }
        // Set vectors.
        this.rSession.assign("scantime", scanTimes);
        this.rSession.assign("scanindex", scanIndices);
        this.rSession.assign("mass", masses);
        this.rSession.assign("intensity", intensities);
        // Construct xcmsRaw object
        this.rSession.eval("xRaw <- new(\"xcmsRaw\")");
        this.rSession.eval("xRaw@tic <- intensity");
        this.rSession.eval("xRaw@scantime <- scantime * " + SECONDS_PER_MINUTE);
        this.rSession.eval("xRaw@scanindex <- as.integer(scanindex)");
        this.rSession.eval("xRaw@env$mz <- mass");
        this.rSession.eval("xRaw@env$intensity <- intensity");
        // Create the xcmsSet object.
        this.rSession.eval("xs <- new(\"xcmsSet\")");
        // Set peaks.
        this.rSession.eval("xs@peaks <- peaks");
        // Set file (dummy) file path.
        this.rSession.eval("xs@filepaths  <- ''");
        // Set sample name.
        this.rSession.assign("sampleName", peakList.getName());
        this.rSession.eval("sampnames(xs) <- sampleName");
        // Create an empty xsAnnotate.
        this.rSession.eval("an <- xsAnnotate(xs, sample=1)");
        // Group by RT.
        this.rSession.eval("an <- groupFWHM(an, sigma=" + fwhmSigma + ", perfwhm=" + fwhmPercentage + ')');
        progress += progressInc;
        switch(parameters.getParameter(CameraSearchParameters.ORDER).getValue()) {
            case CameraSearchParameters.GROUP_CORR_FIRST:
                // Split groups by correlating peak shape (need to set xraw to raw
                // data).
                this.rSession.eval("an <- groupCorr(an, calcIso=FALSE, xraw=xRaw, cor_eic_th=" + corrThreshold + ", pval=" + corrPValue + ')');
                progress += progressInc;
                // Identify isotopes.
                this.rSession.eval("an <- findIsotopes(an, maxcharge=" + isoMaxCharge + ", maxiso=" + isoMaxCount + ", ppm=" + isoMassTolerance.getPpmTolerance() + ", mzabs=" + isoMassTolerance.getMzTolerance() + ')');
                progress += progressInc;
                break;
            default:
                // case CameraSearchParameters.FIND_ISOTOPES_FIRST
                // Identify isotopes.
                this.rSession.eval("an <- findIsotopes(an, maxcharge=" + isoMaxCharge + ", maxiso=" + isoMaxCount + ", ppm=" + isoMassTolerance.getPpmTolerance() + ", mzabs=" + isoMassTolerance.getMzTolerance() + ')');
                // this.rSession.eval("write.csv(getPeaklist(an),
                // file='/Users/aleksandrsmirnov/test_camera.csv')");
                progress += progressInc;
                // Split groups by correlating peak shape (need to set xraw to raw
                // data).
                this.rSession.eval("an <- groupCorr(an, calcIso=" + String.valueOf(calcIso).toUpperCase() + ", xraw=xRaw, cor_eic_th=" + corrThreshold + ", pval=" + corrPValue + ')');
                progress += progressInc;
        }
        this.rSession.eval("an <- findAdducts(an, polarity='" + polarity + "')");
        // Get the feature list.
        this.rSession.eval("peakList <- getPeaklist(an)");
        // Extract the pseudo-spectra and isotope annotations from the peak
        // list.
        rSession.eval("pcgroup <- as.integer(peakList$pcgroup)");
        rSession.eval("isotopes <- peakList$isotopes");
        rSession.eval("adducts <- peakList$adduct");
        final int[] spectra = (int[]) rSession.collect("pcgroup");
        final String[] isotopes = (String[]) rSession.collect("isotopes");
        final String[] adducts = (String[]) rSession.collect("adducts");
        // Done: Refresh R code stack
        this.rSession.clearCode();
        // Add identities.
        if (spectra != null) {
            addPseudoSpectraIdentities(peaks, spectra, isotopes, adducts);
        }
        progress += progressInc;
        // Turn off R instance, once task ended gracefully.
        if (!this.userCanceled)
            this.rSession.close(false);
    } catch (RSessionWrapperException e) {
        if (!this.userCanceled) {
            errorMsg = "'R computing error' during CAMERA search. \n" + e.getMessage();
            e.printStackTrace();
        }
    } catch (Exception e) {
        if (!this.userCanceled) {
            errorMsg = "'Unknown error' during CAMERA search. \n" + e.getMessage();
            e.printStackTrace();
        }
    }
    // Turn off R instance, once task ended UNgracefully.
    try {
        if (!this.userCanceled)
            this.rSession.close(this.userCanceled);
    } catch (RSessionWrapperException e) {
        if (!this.userCanceled) {
            // Do not override potential previous error message.
            if (errorMsg == null) {
                errorMsg = e.getMessage();
            }
        } else {
        // User canceled: Silent.
        }
    }
    // Report error.
    if (errorMsg != null) {
        setErrorMessage(errorMsg);
        setStatus(TaskStatus.ERROR);
    }
}
Also used : TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) ParameterSet(net.sf.mzmine.parameters.ParameterSet) Set(java.util.Set) RSessionWrapper(net.sf.mzmine.util.R.RSessionWrapper) HashMap(java.util.HashMap) Feature(net.sf.mzmine.datamodel.Feature) DataPoint(net.sf.mzmine.datamodel.DataPoint) SimpleDataPoint(net.sf.mzmine.datamodel.impl.SimpleDataPoint) RSessionWrapperException(net.sf.mzmine.util.R.RSessionWrapperException) RSessionWrapperException(net.sf.mzmine.util.R.RSessionWrapperException) SimpleDataPoint(net.sf.mzmine.datamodel.impl.SimpleDataPoint) DataPoint(net.sf.mzmine.datamodel.DataPoint) SimpleDataPoint(net.sf.mzmine.datamodel.impl.SimpleDataPoint) TreeSet(java.util.TreeSet) Scan(net.sf.mzmine.datamodel.Scan)

Example 80 with Feature

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

the class NistMsSearchTask method writeSpectraFile.

/**
 * Writes a search spectrum file for the given row and its neighbours.
 *
 * @param peakRow the row.
 * @param neighbourRows its neighbouring rows.
 * @return the file.
 * @throws IOException if an i/o problem occurs.
 */
private File writeSpectraFile(final PeakListRow peakRow, final Collection<PeakListRow> neighbourRows) throws IOException {
    final File spectraFile = File.createTempFile(SPECTRA_FILE_PREFIX, SPECTRA_FILE_SUFFIX);
    spectraFile.deleteOnExit();
    final BufferedWriter writer = new BufferedWriter(new FileWriter(spectraFile));
    try {
        LOG.finest("Writing spectra to file " + spectraFile);
        // Write header.
        final PeakIdentity identity = peakRow.getPreferredPeakIdentity();
        final String name = SPECTRUM_NAME_PREFIX + peakRow.getID() + (identity == null ? "" : " (" + identity + ')') + " of " + peakList.getName();
        writer.write("Name: " + name.substring(0, Math.min(SPECTRUM_NAME_MAX_LENGTH, name.length())));
        writer.newLine();
        writer.write("Num Peaks: " + neighbourRows.size());
        writer.newLine();
        for (final PeakListRow row : neighbourRows) {
            final Feature peak = row.getBestPeak();
            final int charge = peak.getCharge();
            final double mass = (peak.getMZ() - ionType.getAddedMass()) * (charge == 0 ? 1.0 : (double) charge);
            writer.write(mass + "\t" + peak.getHeight());
            writer.newLine();
        }
    } finally {
        // Close the open file.
        writer.close();
    }
    return spectraFile;
}
Also used : SimplePeakIdentity(net.sf.mzmine.datamodel.impl.SimplePeakIdentity) PeakIdentity(net.sf.mzmine.datamodel.PeakIdentity) PeakListRow(net.sf.mzmine.datamodel.PeakListRow) FileWriter(java.io.FileWriter) File(java.io.File) Feature(net.sf.mzmine.datamodel.Feature) BufferedWriter(java.io.BufferedWriter)

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