Search in sources :

Example 1 with RSessionWrapper

use of net.sf.mzmine.util.R.RSessionWrapper in project mzmine2 by mzmine.

the class HeatMapTask method run.

public void run() {
    errorMsg = null;
    setStatus(TaskStatus.PROCESSING);
    logger.info("Heat map plot");
    if (plegend) {
        newPeakList = groupingDataset(selectedParameter, referenceGroup.toString());
    } else {
        newPeakList = modifySimpleDataset(selectedParameter, referenceGroup.toString());
    }
    if (newPeakList.length == 0 || newPeakList[0].length == 0) {
        setStatus(TaskStatus.ERROR);
        setErrorMessage("The data for heat map is empty.");
        return;
    }
    try {
        // Load gplots library
        String[] reqPackages = { "gplots" };
        rSession = new RSessionWrapper(this.rEngineType, "HeatMap analysis module", reqPackages, null);
        rSession.open();
        finishedPercentage = 0.3f;
        if (outputType.contains("png")) {
            if (height < 500 || width < 500) {
                setStatus(TaskStatus.ERROR);
                setErrorMessage("Figure height or width is too small. " + "Minimun height and width is 500.");
                return;
            }
        }
        rSession.eval("dataset<- matrix(\"\",nrow =" + newPeakList[0].length + ",ncol=" + newPeakList.length + ")");
        if (plegend) {
            rSession.eval("stars<- matrix(\"\",nrow =" + newPeakList[0].length + ",ncol=" + newPeakList.length + ")");
        }
        // assing the values to the matrix
        for (int row = 0; row < newPeakList[0].length; row++) {
            for (int column = 0; column < newPeakList.length; column++) {
                int r = row + 1;
                int c = column + 1;
                double value = newPeakList[column][row];
                if (plegend) {
                    String pValue = pValueMatrix[column][row];
                    rSession.eval("stars[" + r + "," + c + "] = \"" + pValue + "\"");
                }
                if (!Double.isInfinite(value) && !Double.isNaN(value)) {
                    rSession.eval("dataset[" + r + "," + c + "] = " + value);
                } else {
                    rSession.eval("dataset[" + r + "," + c + "] = NA");
                }
            }
        }
        finishedPercentage = 0.4f;
        rSession.eval("dataset <- apply(dataset, 2, as.numeric)");
        // Assign row names to the data set
        rSession.assign("rowNames", rowNames);
        rSession.eval("rownames(dataset)<-rowNames");
        // Assign column names to the data set
        rSession.assign("colNames", colNames);
        rSession.eval("colnames(dataset)<-colNames");
        finishedPercentage = 0.5f;
        // Remove the rows with too many NA's. The distances between
        // rows can't be calculated if the rows don't have
        // at least one sample in common.
        rSession.eval("d <- as.matrix(dist(dataset))");
        rSession.eval("d[upper.tri(d)] <- 0");
        rSession.eval("naindices <- na.action(na.omit(d))");
        rSession.eval("if (! is.null(naindices)) dataset <- dataset[-naindices,]");
        finishedPercentage = 0.8f;
        String marginParameter = "margins = c(" + columnMargin + "," + rowMargin + ")";
        rSession.eval("br<-c(seq(from=min(dataset,na.rm=T),to=0,length.out=256)," + "seq(from=0.00001,to=max(dataset,na.rm=T),length.out=256))", false);
        // Convert the path to R-compatible string
        final String escapedOutputFileName = Rsession.toRpath(outputFile);
        // Possible output file types
        if (outputType.contains("pdf")) {
            rSession.eval("pdf(\"" + escapedOutputFileName + "\", height=" + height + ", width=" + width + ")");
        } else if (outputType.contains("fig")) {
            rSession.eval("xfig(\"" + escapedOutputFileName + "\", height=" + height + ", width=" + width + ", horizontal = FALSE, pointsize = 12)");
        } else if (outputType.contains("svg")) {
            // Load RSvgDevice library
            rSession.loadPackage("RSvgDevice");
            rSession.eval("devSVG(\"" + escapedOutputFileName + "\", height=" + height + ", width=" + width + ")");
        } else if (outputType.contains("png")) {
            rSession.eval("png(\"" + escapedOutputFileName + "\", height=" + height + ", width=" + width + ")");
        }
        if (plegend) {
            rSession.eval("heatmap.2(dataset," + marginParameter + ", trace=\"none\", col=bluered(length(br)-1)," + " breaks=br, cellnote=stars, notecol=\"black\"" + ", notecex=" + starSize + ", na.color=\"grey\")", false);
        } else {
            rSession.eval("heatmap.2(dataset," + marginParameter + ", trace=\"none\", col=bluered(length(br)-1)," + " breaks=br, na.color=\"grey\")", false);
        }
        rSession.eval("dev.off()", false);
        // Stands for a (void) collect!
        this.rSession.runOnlyOnline();
        // Done: Refresh R code stack
        this.rSession.clearCode();
        finishedPercentage = 1.0;
        // Turn off R instance, once task ended gracefully.
        if (!isCanceled())
            rSession.close(false);
    } catch (RSessionWrapperException e) {
        if (!isCanceled()) {
            errorMsg = "'R computing error' during heatmap generation. \n" + e.getMessage();
        }
    } catch (Exception e) {
        if (!isCanceled()) {
            errorMsg = "'Unknown error' during heatmap generation. \n" + e.getMessage();
        }
    }
    // Turn off R instance, once task ended UNgracefully.
    try {
        if (!isCanceled())
            if (rSession != null)
                rSession.close(isCanceled());
    } catch (RSessionWrapperException e) {
        if (!isCanceled()) {
            // 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);
    } else {
        setStatus(TaskStatus.FINISHED);
    }
}
Also used : RSessionWrapper(net.sf.mzmine.util.R.RSessionWrapper) RSessionWrapperException(net.sf.mzmine.util.R.RSessionWrapperException) RSessionWrapperException(net.sf.mzmine.util.R.RSessionWrapperException) MathException(org.apache.commons.math.MathException)

Example 2 with RSessionWrapper

use of net.sf.mzmine.util.R.RSessionWrapper in project mzmine2 by mzmine.

the class DeconvolutionTask method run.

@Override
public void run() {
    errorMsg = null;
    if (!isCanceled()) {
        setStatus(TaskStatus.PROCESSING);
        LOG.info("Started peak deconvolution on " + originalPeakList);
        // Check raw data files.
        if (originalPeakList.getNumberOfRawDataFiles() > 1) {
            setStatus(TaskStatus.ERROR);
            setErrorMessage("Peak deconvolution can only be performed on feature lists with a single raw data file");
        } else {
            try {
                // Peak resolver.
                final MZmineProcessingStep<PeakResolver> resolver = parameters.getParameter(PEAK_RESOLVER).getValue();
                if (resolver.getModule().getRequiresR()) {
                    // Check R availability, by trying to open the
                    // connection.
                    String[] reqPackages = resolver.getModule().getRequiredRPackages();
                    String[] reqPackagesVersions = resolver.getModule().getRequiredRPackagesVersions();
                    String callerFeatureName = resolver.getModule().getName();
                    REngineType rEngineType = resolver.getModule().getREngineType(resolver.getParameterSet());
                    this.rSession = new RSessionWrapper(rEngineType, callerFeatureName, reqPackages, reqPackagesVersions);
                    this.rSession.open();
                } else {
                    this.rSession = null;
                }
                // Deconvolve peaks.
                newPeakList = resolvePeaks(originalPeakList, this.rSession);
                if (!isCanceled()) {
                    // Add new peaklist to the project.
                    project.addPeakList(newPeakList);
                    // Add quality parameters to peaks
                    QualityParameters.calculateQualityParameters(newPeakList);
                    // Remove the original peaklist if requested.
                    if (parameters.getParameter(AUTO_REMOVE).getValue()) {
                        project.removePeakList(originalPeakList);
                    }
                    setStatus(TaskStatus.FINISHED);
                    LOG.info("Finished peak recognition on " + originalPeakList);
                }
                // Turn off R instance.
                if (this.rSession != null)
                    this.rSession.close(false);
            } catch (RSessionWrapperException e) {
                errorMsg = "'R computing error' during CentWave detection. \n" + e.getMessage();
            } catch (Exception e) {
                errorMsg = "'Unknown error' during CentWave detection. \n" + e.getMessage();
            } catch (Throwable t) {
                setStatus(TaskStatus.ERROR);
                setErrorMessage(t.getMessage());
                LOG.log(Level.SEVERE, "Peak deconvolution error", t);
            }
            // Turn off R instance, once task ended UNgracefully.
            try {
                if (this.rSession != null && !isCanceled())
                    rSession.close(isCanceled());
            } catch (RSessionWrapperException e) {
                if (!isCanceled()) {
                    // 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 : RSessionWrapper(net.sf.mzmine.util.R.RSessionWrapper) REngineType(net.sf.mzmine.util.R.REngineType) RSessionWrapperException(net.sf.mzmine.util.R.RSessionWrapperException) RSessionWrapperException(net.sf.mzmine.util.R.RSessionWrapperException)

Example 3 with RSessionWrapper

use of net.sf.mzmine.util.R.RSessionWrapper 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 4 with RSessionWrapper

use of net.sf.mzmine.util.R.RSessionWrapper in project mzmine2 by mzmine.

the class BaselineCorrectionTask method run.

@Override
public void run() {
    errorMsg = null;
    // Update the status of this task.
    setStatus(TaskStatus.PROCESSING);
    try {
        // Check R availability, by trying to open the connection.
        String[] reqPackages = this.baselineCorrectorProcStep.getModule().getRequiredRPackages();
        String callerFeatureName = this.baselineCorrectorProcStep.getModule().getName();
        this.rSession = new RSessionWrapper(rEngineType, callerFeatureName, reqPackages, null);
        this.rSession.open();
        this.baselineCorrectorProcStep.getModule().initProgress(origDataFile);
        final RawDataFile correctedDataFile = this.baselineCorrectorProcStep.getModule().correctDatafile(this.rSession, origDataFile, baselineCorrectorProcStep.getParameterSet(), this.commonParameters);
        // If this task was canceled, stop processing.
        if (!isCanceled() && correctedDataFile != null) {
            this.correctedDataFile = correctedDataFile;
            // Add the newly created file to the project
            this.project.addFile(this.correctedDataFile);
            // Remove the original data file if requested.
            if (removeOriginal) {
                project.removeFile(origDataFile);
            }
            // Set task status to FINISHED
            setStatus(TaskStatus.FINISHED);
            LOG.info("Baseline corrected " + origDataFile.getName());
        }
        // Turn off R instance, once task ended gracefully.
        if (!isCanceled())
            this.rSession.close(false);
    } catch (IOException | RSessionWrapperException e) {
        if (!isCanceled()) {
            errorMsg = "'R computing error' during baseline correction. \n" + e.getMessage();
        }
    } catch (Exception e) {
        if (!isCanceled()) {
            errorMsg = "'Unknown error' during baseline correction. \n" + e.getMessage();
        }
    }
    this.baselineCorrectorProcStep.getModule().setAbortProcessing(origDataFile, true);
    // Turn off R instance, once task ended UNgracefully.
    try {
        if (!isCanceled())
            this.rSession.close(isCanceled());
    } catch (RSessionWrapperException e) {
        if (!isCanceled()) {
            // 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);
    }
    // ...
    this.baselineCorrectorProcStep.getModule().clearProgress(origDataFile);
}
Also used : RSessionWrapper(net.sf.mzmine.util.R.RSessionWrapper) RawDataFile(net.sf.mzmine.datamodel.RawDataFile) IOException(java.io.IOException) RSessionWrapperException(net.sf.mzmine.util.R.RSessionWrapperException) RSessionWrapperException(net.sf.mzmine.util.R.RSessionWrapperException) IOException(java.io.IOException)

Example 5 with RSessionWrapper

use of net.sf.mzmine.util.R.RSessionWrapper in project mzmine2 by mzmine.

the class PeakResolverSetupDialog method parametersChanged.

@Override
public void parametersChanged() {
    if (preview != null && preview.isSelected()) {
        final PeakListRow previewRow = (PeakListRow) comboPeak.getSelectedItem();
        if (previewRow != null) {
            LOG.finest("Loading new preview peak " + previewRow);
            ticPlot.removeAllTICDataSets();
            ticPlot.addTICDataset(new ChromatogramTICDataSet(previewRow.getPeaks()[0]));
            // Auto-range to axes.
            ticPlot.getXYPlot().getDomainAxis().setAutoRange(true);
            ticPlot.getXYPlot().getDomainAxis().setAutoTickUnitSelection(true);
            ticPlot.getXYPlot().getRangeAxis().setAutoRange(true);
            ticPlot.getXYPlot().getRangeAxis().setAutoTickUnitSelection(true);
            updateParameterSetFromComponents();
            // If there is some illegal value, do not load the preview but
            // just exit.
            ArrayList<String> errors = new ArrayList<String>();
            if (!parameterSet.checkParameterValues(errors)) {
                LOG.fine("Illegal parameter value: " + errors);
                return;
            }
            // Load the intensities and RTs into array.
            final Feature previewPeak = previewRow.getPeaks()[0];
            // Resolve peaks.
            Feature[] resolvedPeaks = {};
            RSessionWrapper rSession;
            try {
                if (peakResolver.getRequiresR()) {
                    // Check R availability, by trying to open the
                    // connection.
                    String[] reqPackages = peakResolver.getRequiredRPackages();
                    String[] reqPackagesVersions = peakResolver.getRequiredRPackagesVersions();
                    String callerFeatureName = peakResolver.getName();
                    REngineType rEngineType = peakResolver.getREngineType(parameters);
                    rSession = new RSessionWrapper(rEngineType, callerFeatureName, reqPackages, reqPackagesVersions);
                    rSession.open();
                } else {
                    rSession = null;
                }
                CenterFunction mzCenterFunction = new CenterFunction(CenterMeasure.MEDIAN);
                // preview doesn't show msms scans
                // set it to be default searching range
                resolvedPeaks = peakResolver.resolvePeaks(previewPeak, parameters, rSession, mzCenterFunction, 0, 0);
                // Turn off R instance.
                if (rSession != null)
                    rSession.close(false);
            } catch (RSessionWrapperException e) {
                throw new IllegalStateException(e.getMessage());
            } catch (Throwable t) {
                LOG.log(Level.SEVERE, "Peak deconvolution error", t);
                MZmineCore.getDesktop().displayErrorMessage(this, t.toString());
            }
            // Add resolved peaks to TIC plot.
            final int peakCount = Math.min(MAX_PEAKS, resolvedPeaks.length);
            for (int i = 0; i < peakCount; i++) {
                final XYDataset peakDataSet = new PeakDataSet(resolvedPeaks[i]);
                ticPlot.addPeakDataset(peakDataSet);
            }
            // Check peak count.
            if (resolvedPeaks.length > MAX_PEAKS) {
                // MZmineCore.getDesktop().displayMessage(this,
                // "Too many peaks detected, please adjust parameter values");
                MZmineCore.getDesktop().displayMessage(this, "Too many peaks detected. Not all of the peaks might be displayed");
            }
        }
    }
}
Also used : PeakDataSet(net.sf.mzmine.modules.visualization.tic.PeakDataSet) RSessionWrapper(net.sf.mzmine.util.R.RSessionWrapper) REngineType(net.sf.mzmine.util.R.REngineType) ArrayList(java.util.ArrayList) Feature(net.sf.mzmine.datamodel.Feature) RSessionWrapperException(net.sf.mzmine.util.R.RSessionWrapperException) PeakListRow(net.sf.mzmine.datamodel.PeakListRow) XYDataset(org.jfree.data.xy.XYDataset) CenterFunction(net.sf.mzmine.util.maths.CenterFunction)

Aggregations

RSessionWrapper (net.sf.mzmine.util.R.RSessionWrapper)5 RSessionWrapperException (net.sf.mzmine.util.R.RSessionWrapperException)5 Feature (net.sf.mzmine.datamodel.Feature)2 REngineType (net.sf.mzmine.util.R.REngineType)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Set (java.util.Set)1 TreeSet (java.util.TreeSet)1 DataPoint (net.sf.mzmine.datamodel.DataPoint)1 PeakListRow (net.sf.mzmine.datamodel.PeakListRow)1 RawDataFile (net.sf.mzmine.datamodel.RawDataFile)1 Scan (net.sf.mzmine.datamodel.Scan)1 SimpleDataPoint (net.sf.mzmine.datamodel.impl.SimpleDataPoint)1 PeakDataSet (net.sf.mzmine.modules.visualization.tic.PeakDataSet)1 ParameterSet (net.sf.mzmine.parameters.ParameterSet)1 CenterFunction (net.sf.mzmine.util.maths.CenterFunction)1 MathException (org.apache.commons.math.MathException)1 XYDataset (org.jfree.data.xy.XYDataset)1