Search in sources :

Example 1 with MSDKRuntimeException

use of io.github.msdk.MSDKRuntimeException in project mzmine2 by mzmine.

the class IsotopePeakScannerTask method setUpDiffAutoCarbon.

/**
 * This calculates the isotope pattern using ExtendedIsotopePattern and creates an
 * ArrayList<Double> that will contain the mass shift for every expected isotope peak relative to
 * the one with the lowest mass.
 *
 * @return
 */
private double[][] setUpDiffAutoCarbon() {
    // ArrayList<Double> diff = new ArrayList<Double>(2);
    double[][] diff;
    if (scanType == ScanType.AUTOCARBON) {
        String[] strPattern = new String[carbonRange];
        ExtendedIsotopePattern[] patternBuffer = new ExtendedIsotopePattern[carbonRange];
        // in the following for we calculate up the patterns
        for (int p = 0; p < carbonRange; p++) {
            if (p + autoCarbonMin != 0)
                strPattern[p] = "C" + (p + autoCarbonMin) + element;
            else
                strPattern[p] = element;
            try {
                patternBuffer[p] = (ExtendedIsotopePattern) IsotopePatternCalculator.calculateIsotopePattern(strPattern[p], 0.001, mergeWidth, charge, polarityType, true);
                patternBuffer[p] = (ExtendedIsotopePattern) IsotopePatternCalculator.removeDataPointsBelowIntensity(patternBuffer[p], minPatternIntensity);
            } catch (Exception e) {
                logger.warning("The entered Sum formula is invalid.");
                return null;
            }
        }
        int sizeCounter = 0;
        // if they dont fit we null them
        for (int p = 0; p < carbonRange; p++) {
            if (patternBuffer[p].getNumberOfDataPoints() >= autoCarbonMinPatternSize) {
                sizeCounter++;
            } else {
                patternBuffer[p] = null;
            }
        }
        if (sizeCounter == 0)
            throw new MSDKRuntimeException("Min pattern size excludes every calculated isotope pattern.\nPlease increase min pattern intensity for more data points or decrease the minimum pattern size.");
        logger.info("about to add " + sizeCounter + " patterns to the scan.");
        diff = new double[sizeCounter][];
        int addCounter = 0;
        pattern = new ExtendedIsotopePattern[sizeCounter];
        for (int p = 0; p < carbonRange; p++) {
            if (patternBuffer[p] == null)
                continue;
            pattern[addCounter] = patternBuffer[p];
            DataPoint[] points = patternBuffer[p].getDataPoints();
            diff[addCounter] = new double[points.length];
            if (maxPatternSize < diff[addCounter].length) {
                maxPatternSize = diff[addCounter].length;
                maxPatternIndex = addCounter;
            }
            for (int i = 0; i < pattern[addCounter].getNumberOfDataPoints(); i++) {
                diff[addCounter][i] = points[i].getMZ() - points[0].getMZ();
            }
            addCounter++;
        }
    } else /* if(scanType == ScanType.SPECIFIC) */
    {
        diff = new double[1][];
        pattern = new ExtendedIsotopePattern[1];
        pattern[0] = (ExtendedIsotopePattern) IsotopePatternCalculator.calculateIsotopePattern(element, 0.001, mergeWidth, charge, polarityType, true);
        pattern[0] = (ExtendedIsotopePattern) IsotopePatternCalculator.removeDataPointsBelowIntensity(pattern[0], minPatternIntensity);
        DataPoint[] points = pattern[0].getDataPoints();
        diff[0] = new double[points.length];
        if (maxPatternSize < diff[0].length) {
            maxPatternSize = diff[0].length;
            maxPatternIndex = 0;
        }
        for (int i = 0; i < pattern[0].getNumberOfDataPoints(); i++) {
            diff[0][i] = points[i].getMZ() - points[0].getMZ();
        }
    }
    logger.info("diff set up...");
    return diff;
}
Also used : DataPoint(net.sf.mzmine.datamodel.DataPoint) SimpleDataPoint(net.sf.mzmine.datamodel.impl.SimpleDataPoint) MSDKRuntimeException(io.github.msdk.MSDKRuntimeException) ExtendedIsotopePattern(net.sf.mzmine.datamodel.impl.ExtendedIsotopePattern) DataPoint(net.sf.mzmine.datamodel.DataPoint) SimpleDataPoint(net.sf.mzmine.datamodel.impl.SimpleDataPoint) MSDKRuntimeException(io.github.msdk.MSDKRuntimeException)

Example 2 with MSDKRuntimeException

use of io.github.msdk.MSDKRuntimeException in project mzmine2 by mzmine.

the class SortDataFilesModule method runModule.

@Override
@Nonnull
public ExitCode runModule(@Nonnull MZmineProject project, @Nonnull ParameterSet parameters, @Nonnull Collection<Task> tasks) {
    List<RawDataFile> dataFiles = Arrays.asList(parameters.getParameter(SortDataFilesParameters.dataFiles).getValue().getMatchingRawDataFiles());
    RawDataTreeModel model = null;
    if (project instanceof MZmineProjectImpl) {
        model = ((MZmineProjectImpl) project).getRawDataTreeModel();
    } else if (MZmineCore.getDesktop() instanceof MainWindow) {
        ProjectTree tree = ((MainWindow) MZmineCore.getDesktop()).getMainPanel().getRawDataTree();
        model = (RawDataTreeModel) tree.getModel();
    }
    if (model == null)
        throw new MSDKRuntimeException("Cannot find raw data file tree model for sorting. Different MZmine project impl?");
    final DefaultMutableTreeNode rootNode = model.getRoot();
    // Get all tree nodes that represent selected data files, and remove
    // them from
    final ArrayList<DefaultMutableTreeNode> selectedNodes = new ArrayList<DefaultMutableTreeNode>();
    for (int row = 0; row < rootNode.getChildCount(); row++) {
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) rootNode.getChildAt(row);
        Object selectedObject = selectedNode.getUserObject();
        if (dataFiles.contains(selectedObject)) {
            selectedNodes.add(selectedNode);
        }
    }
    // Get the index of the first selected item
    final ArrayList<Integer> positions = new ArrayList<Integer>();
    for (DefaultMutableTreeNode node : selectedNodes) {
        int nodeIndex = rootNode.getIndex(node);
        if (nodeIndex != -1)
            positions.add(nodeIndex);
    }
    if (positions.isEmpty())
        return ExitCode.ERROR;
    int insertPosition = Collections.min(positions);
    // Sort the data files by name
    Collections.sort(selectedNodes, new Comparator<DefaultMutableTreeNode>() {

        @Override
        public int compare(DefaultMutableTreeNode o1, DefaultMutableTreeNode o2) {
            return o1.getUserObject().toString().compareTo(o2.getUserObject().toString());
        }
    });
    // Reorder the nodes in the tree model
    for (DefaultMutableTreeNode node : selectedNodes) {
        model.removeNodeFromParent(node);
        model.insertNodeInto(node, rootNode, insertPosition);
        insertPosition++;
    }
    return ExitCode.OK;
}
Also used : DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) ArrayList(java.util.ArrayList) ProjectTree(net.sf.mzmine.desktop.impl.projecttree.ProjectTree) RawDataFile(net.sf.mzmine.datamodel.RawDataFile) MainWindow(net.sf.mzmine.desktop.impl.MainWindow) MSDKRuntimeException(io.github.msdk.MSDKRuntimeException) RawDataTreeModel(net.sf.mzmine.desktop.impl.projecttree.RawDataTreeModel) MZmineProjectImpl(net.sf.mzmine.project.impl.MZmineProjectImpl) Nonnull(javax.annotation.Nonnull)

Example 3 with MSDKRuntimeException

use of io.github.msdk.MSDKRuntimeException in project mzmine2 by mzmine.

the class GnpsGcExportAndSubmitTask method run.

@Override
public void run() {
    final AbstractTask thistask = this;
    setStatus(TaskStatus.PROCESSING);
    List<AbstractTask> list = new ArrayList<>(3);
    // add mgf export task
    list.add(addAdapMgfTask(parameters));
    // add csv quant table
    list.add(addQuantTableTask(parameters, null));
    // finish listener to submit
    final File fileName = file;
    final File folder = file.getParentFile();
    new AllTasksFinishedListener(list, true, // succeed
    l -> {
        try {
            LOG.info("succeed" + thistask.getStatus().toString());
            if (submit) {
                GnpsGcSubmitParameters param = parameters.getParameter(GnpsGcExportAndSubmitParameters.SUBMIT).getEmbeddedParameters();
                submit(fileName, param);
            }
            // open folder
            try {
                if (openFolder && Desktop.isDesktopSupported()) {
                    Desktop.getDesktop().open(folder);
                }
            } catch (Exception ex) {
            }
        } finally {
            // finish task
            if (thistask.getStatus() == TaskStatus.PROCESSING)
                thistask.setStatus(TaskStatus.FINISHED);
        }
    }, lerror -> {
        setErrorMessage("GNPS-GC submit was not started due too errors while file export");
        thistask.setStatus(TaskStatus.ERROR);
        throw new MSDKRuntimeException("GNPS-GC submit was not started due too errors while file export");
    }, // cancel if one was cancelled
    listCancelled -> cancel()) {

        @Override
        public void taskStatusChanged(Task task, TaskStatus newStatus, TaskStatus oldStatus) {
            super.taskStatusChanged(task, newStatus, oldStatus);
            // show progress
            progress.getAndSet(getProgress());
        }
    };
    MZmineCore.getTaskController().addTasks(list.toArray(new AbstractTask[list.size()]));
    // wait till finish
    while (!(isCanceled() || isFinished())) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            LOG.log(Level.SEVERE, "Error in GNPS-GC export/submit task", e);
        }
    }
}
Also used : CSVExportTask(net.sf.mzmine.modules.peaklistmethods.io.csvexport.CSVExportTask) AdapMgfExportTask(net.sf.mzmine.modules.peaklistmethods.io.adap.mgfexport.AdapMgfExportTask) Task(net.sf.mzmine.taskcontrol.Task) AbstractTask(net.sf.mzmine.taskcontrol.AbstractTask) AbstractTask(net.sf.mzmine.taskcontrol.AbstractTask) MSDKRuntimeException(io.github.msdk.MSDKRuntimeException) ArrayList(java.util.ArrayList) AllTasksFinishedListener(net.sf.mzmine.taskcontrol.AllTasksFinishedListener) TaskStatus(net.sf.mzmine.taskcontrol.TaskStatus) File(java.io.File) MSDKRuntimeException(io.github.msdk.MSDKRuntimeException)

Example 4 with MSDKRuntimeException

use of io.github.msdk.MSDKRuntimeException in project mzmine2 by mzmine.

the class MZDistributionHistoTask method run.

/**
 * @see Runnable#run()
 */
public void run() {
    setStatus(TaskStatus.PROCESSING);
    logger.info("Starting to build mz distribution histogram for " + dataFile);
    // all selected scans
    scans = scanSelection.getMatchingScans(dataFile);
    totalScans = scans.length;
    // histo data
    DoubleArrayList data = new DoubleArrayList();
    for (Scan scan : scans) {
        if (isCanceled())
            return;
        // retention time in range
        if (!useRTRange || rtRange.contains(scan.getRetentionTime())) {
            // go through all mass lists
            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();
            // insert all mz in order and count them
            Arrays.stream(mzValues).mapToDouble(dp -> dp.getMZ()).filter(mz -> mzRange.contains(mz)).forEach(mz -> data.add(mz));
            processedScans++;
        }
    }
    if (!data.isEmpty()) {
        // to array
        double[] histo = new double[data.size()];
        for (int i = 0; i < data.size(); i++) histo[i] = data.get(i);
        // create histogram dialog
        EHistogramDialog dialog = new EHistogramDialog("m/z distribution", "m/z", new HistogramData(histo), binWidth);
        dialog.setVisible(true);
    } else {
        throw new MSDKRuntimeException("Data was empty. Review your selected filters.");
    }
    setStatus(TaskStatus.FINISHED);
    logger.info("Finished mz distribution histogram on " + dataFile);
}
Also used : HistogramData(net.sf.mzmine.modules.visualization.mzhistogram.chart.HistogramData) Scan(net.sf.mzmine.datamodel.Scan) Arrays(java.util.Arrays) EHistogramDialog(net.sf.mzmine.modules.visualization.mzhistogram.chart.EHistogramDialog) TaskStatus(net.sf.mzmine.taskcontrol.TaskStatus) Range(com.google.common.collect.Range) RawDataFile(net.sf.mzmine.datamodel.RawDataFile) Logger(java.util.logging.Logger) DataPoint(net.sf.mzmine.datamodel.DataPoint) MassList(net.sf.mzmine.datamodel.MassList) DoubleArrayList(it.unimi.dsi.fastutil.doubles.DoubleArrayList) ParameterSet(net.sf.mzmine.parameters.ParameterSet) AbstractTask(net.sf.mzmine.taskcontrol.AbstractTask) MZmineProject(net.sf.mzmine.datamodel.MZmineProject) MSDKRuntimeException(io.github.msdk.MSDKRuntimeException) ScanSelection(net.sf.mzmine.parameters.parametertypes.selectors.ScanSelection) HistogramData(net.sf.mzmine.modules.visualization.mzhistogram.chart.HistogramData) DataPoint(net.sf.mzmine.datamodel.DataPoint) EHistogramDialog(net.sf.mzmine.modules.visualization.mzhistogram.chart.EHistogramDialog) MSDKRuntimeException(io.github.msdk.MSDKRuntimeException) Scan(net.sf.mzmine.datamodel.Scan) DoubleArrayList(it.unimi.dsi.fastutil.doubles.DoubleArrayList) MassList(net.sf.mzmine.datamodel.MassList) DataPoint(net.sf.mzmine.datamodel.DataPoint)

Example 5 with MSDKRuntimeException

use of io.github.msdk.MSDKRuntimeException in project mzmine2 by mzmine.

the class LibrarySubmitTask method submitGNPS.

/**
 * Submit json library entry to GNPS webserver
 *
 * @param json
 */
private void submitGNPS(String json) {
    try {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            MultipartEntity entity = new MultipartEntity();
            // ######################################################
            // NEEDED
            // user pass and json entry
            // 
            entity.addPart("username", new StringBody(USER));
            entity.addPart("password", new StringBody(PASS));
            entity.addPart("spectrum", new StringBody(json));
            // job description is not entry description
            entity.addPart("description", new StringBody(SOURCE_DESCRIPTION));
            HttpPost httppost = new HttpPost(GNPS_LIBRARY_SUBMIT_URL);
            httppost.setEntity(entity);
            log.info("Submitting GNPS library entry " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                writeResults("GNPS submit entry response status: " + response.getStatusLine(), Result.INFO);
                log.info("GNPS submit entry response status: " + response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    log.info("GNPS submit entry response content length: " + resEntity.getContentLength());
                    writeResults("GNPS submit entry response content length: " + resEntity.getContentLength(), Result.SUCCED);
                    String body = IOUtils.toString(resEntity.getContent());
                    String url = "https://gnps.ucsd.edu/ProteoSAFe/status.jsp?task=" + body;
                    log.log(Level.INFO, "Submission task: " + url);
                    writeResults(url, Result.SUCCED, true);
                    EntityUtils.consume(resEntity);
                } else {
                    log.warning("Not submitted to GNPS:\n" + json);
                    writeResults("Not submitted to GNPS\n" + json, Result.ERROR);
                }
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    } catch (IOException e) {
        log.log(Level.SEVERE, "Error while submitting GNPS job", e);
        throw new MSDKRuntimeException(e);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) MSDKRuntimeException(io.github.msdk.MSDKRuntimeException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) IOException(java.io.IOException)

Aggregations

MSDKRuntimeException (io.github.msdk.MSDKRuntimeException)9 ArrayList (java.util.ArrayList)5 RawDataFile (net.sf.mzmine.datamodel.RawDataFile)4 File (java.io.File)3 Nonnull (javax.annotation.Nonnull)3 AbstractTask (net.sf.mzmine.taskcontrol.AbstractTask)3 Task (net.sf.mzmine.taskcontrol.Task)3 TaskStatus (net.sf.mzmine.taskcontrol.TaskStatus)3 IOException (java.io.IOException)2 DefaultMutableTreeNode (javax.swing.tree.DefaultMutableTreeNode)2 DataPoint (net.sf.mzmine.datamodel.DataPoint)2 Scan (net.sf.mzmine.datamodel.Scan)2 MainWindow (net.sf.mzmine.desktop.impl.MainWindow)2 ProjectTree (net.sf.mzmine.desktop.impl.projecttree.ProjectTree)2 CSVExportTask (net.sf.mzmine.modules.peaklistmethods.io.csvexport.CSVExportTask)2 MZmineProjectImpl (net.sf.mzmine.project.impl.MZmineProjectImpl)2 AllTasksFinishedListener (net.sf.mzmine.taskcontrol.AllTasksFinishedListener)2 Range (com.google.common.collect.Range)1 DoubleArrayList (it.unimi.dsi.fastutil.doubles.DoubleArrayList)1 Arrays (java.util.Arrays)1