Search in sources :

Example 1 with REXPMismatchException

use of org.rosuda.REngine.REXPMismatchException in project dataverse by IQSS.

the class RDATAFileReader method getDataFrameInformation.

/**
 * Runs an R-script that extracts meta-data from the *original* Rdata
 * object, then parses its output and creates DataVariable objects.
 *
 * @throws IOException if something bad happens?
 */
private void getDataFrameInformation() {
    LOG.fine("RDATAFileReader: Entering `getDataFrameInformation` function");
    // Store variable names
    String[] variableNames = {};
    String parentDirectory = mRWorkspace.getRdataFile().getParent();
    String fileInfoScript = new StringBuilder("").append(String.format("load(\"%s\")\n", mRWorkspace.getRdataAbsolutePath())).append(String.format("setwd(\"%s\")\n", parentDirectory)).append(RSCRIPT_GET_DATASET).append("\n").append(RSCRIPT_DATASET_INFO_SCRIPT).toString();
    try {
        RRequest request = mRequestBuilder.build();
        request.script(fileInfoScript);
        RList fileInformation = request.eval().asList();
        RList metaInfo = fileInformation.at("meta.info").asList();
        int varQnty = 0;
        variableNames = fileInformation.at("varNames").asStrings();
        // mDataTypes = fileInformation.at("dataTypes").asStrings();
        // Initialize variables:
        List<DataVariable> variableList = new ArrayList<>();
        for (String varName : variableNames) {
            DataVariable dv = new DataVariable();
            dv.setName(varName);
            dv.setLabel(varName);
            // TODO:
            // Check if variables have real descriptive labels defined,
            // via the mechanismm provided by that special optional package...
            // (?) -- L.A.
            dv.setInvalidRanges(new ArrayList<>());
            dv.setSummaryStatistics(new ArrayList<>());
            dv.setUnf("UNF:6:XYZXYZXYZ");
            dv.setCategories(new ArrayList<>());
            variableList.add(dv);
            dv.setFileOrder(varQnty);
            dv.setDataTable(dataTable);
            // variableLabels.put(varName, varName);
            // variableNameList.add(varName);
            varQnty++;
        }
        dataTable.setVarQuantity(new Long(varQnty));
        dataTable.setDataVariables(variableList);
        // Get the Variable Meta Data Table while Populating
        processVariableInfo(metaInfo, dataTable);
        if (fileInformation.at("caseQnty") != null) {
            int caseQuantity = 0;
            try {
                caseQuantity = fileInformation.at("caseQnty").asInteger();
            } catch (REXPMismatchException rexp) {
            // bummer! - but not fatal.
            }
            if (caseQuantity > 0) {
                dataTable.setCaseQuantity(new Long(caseQuantity));
            }
        }
    } catch (REXPMismatchException ex) {
        LOG.warning("RDATAFileReader: Could not put information correctly");
    } catch (Exception ex) {
        ex.printStackTrace();
        LOG.warning(ex.getMessage());
    }
}
Also used : REXPMismatchException(org.rosuda.REngine.REXPMismatchException) DataVariable(edu.harvard.iq.dataverse.datavariable.DataVariable) NamingException(javax.naming.NamingException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) REXPMismatchException(org.rosuda.REngine.REXPMismatchException) RList(org.rosuda.REngine.RList)

Example 2 with REXPMismatchException

use of org.rosuda.REngine.REXPMismatchException in project rsession by yannrichet.

the class RserveSession method asList.

@Override
public Map asList(Object o) throws ClassCastException {
    if (o == null) {
        return null;
    }
    if (o instanceof Map) {
        return (Map) o;
    }
    if (!(o instanceof REXP)) {
        throw new IllegalArgumentException("[asList] Not an REXP object: " + o);
    }
    if (((REXP) o).isNull()) {
        return null;
    }
    try {
        RList l = ((REXP) o).asList();
        Map m = new HashMap(l.size());
        for (String k : l.keys()) {
            m.put(k, cast(l.at(k)));
        }
        return m;
    } catch (REXPMismatchException ex) {
        throw new ClassCastException("[asList] Cannot cast to matrix " + o);
    }
}
Also used : HashMap(java.util.HashMap) RList(org.rosuda.REngine.RList) REXPMismatchException(org.rosuda.REngine.REXPMismatchException) REXPString(org.rosuda.REngine.REXPString) HashMap(java.util.HashMap) Map(java.util.Map) REXP(org.rosuda.REngine.REXP)

Example 3 with REXPMismatchException

use of org.rosuda.REngine.REXPMismatchException in project rsession by yannrichet.

the class RserveSession method silentlyRawEval.

/**
 * Silently (ie no log) launch R command and return value.
 *
 * @param expression R expression to evaluate
 * @param tryEval encapsulate command in try() to cacth errors
 * @return REXP R expression
 */
@Override
public REXP silentlyRawEval(String expression, boolean tryEval) {
    // assert connected : "R environment not initialized.";
    if (!connected) {
        log(HEAD_EXCEPTION + "R environment not initialized.", Level.ERROR);
        return null;
    }
    if (expression == null) {
        return null;
    }
    if (expression.trim().length() == 0) {
        return null;
    }
    for (EvalListener b : eval) {
        b.eval(expression);
    }
    REXP e = null;
    synchronized (R) {
        try {
            if (SINK_OUTPUT) {
                R.eval(".f <- file('" + fixPathSeparator(SINK_FILE) + "',open='wt')");
                R.eval("sink(.f,type='output')");
            }
            if (SINK_MESSAGE) {
                R.eval(".fm <- file('" + fixPathSeparator(SINK_FILE) + ".m',open='wt')");
                R.eval("sink(.fm,type='message')");
            }
            if (tryEval) {
                e = R.parseAndEval("try(eval(parse(text='" + expression.replace("'", "\\'") + "')),silent=FALSE)");
            } else {
                e = R.parseAndEval(expression);
            }
        } catch (Exception ex) {
            log(HEAD_EXCEPTION + ex.getMessage() + "\n  " + expression, Level.ERROR);
        } finally {
            if (SINK_OUTPUT) {
                try {
                    R.parseAndEval("sink(type='output')");
                    lastOuput = R.parseAndEval("paste(collapse='\n',readLines('" + fixPathSeparator(SINK_FILE) + "'))").asString();
                    log(lastOuput, Level.OUTPUT);
                } catch (Exception ex) {
                    lastOuput = ex.getMessage();
                    log(lastOuput, Level.WARNING);
                } finally {
                    try {
                        // because Renjin.sink() do not properly close connection, so calling it explicitely
                        R.eval("close(.f)");
                        R.parseAndEval("unlink('" + fixPathSeparator(SINK_FILE) + "')");
                    } catch (Exception ex) {
                        log(HEAD_EXCEPTION + ex.getMessage(), Level.ERROR);
                    }
                }
            }
            if (SINK_MESSAGE) {
                try {
                    R.parseAndEval("sink(type='message')");
                    lastMessage = R.parseAndEval("paste(collapse='\n',readLines('" + fixPathSeparator(SINK_FILE) + ".m'))").asString();
                    log(lastMessage, Level.INFO);
                } catch (Exception ex) {
                    lastMessage = ex.getMessage();
                    log(lastMessage, Level.WARNING);
                } finally {
                    try {
                        // because Renjin.sink() do not properly close connection, so calling it explicitely
                        R.eval("close(.fm)");
                        R.parseAndEval("unlink('" + fixPathSeparator(SINK_FILE) + ".m')");
                    } catch (Exception ex) {
                        log(HEAD_EXCEPTION + ex.getMessage(), Level.ERROR);
                    }
                }
            }
        }
    }
    if (tryEval && e != null) {
        try {
            if (e.inherits("try-error")) /*e.isString() && e.asStrings().length > 0 && e.asString().toLowerCase().startsWith("error")*/
            {
                log(HEAD_EXCEPTION + e.asString() + "\n  " + expression, Level.WARNING);
                e = null;
            }
        } catch (REXPMismatchException ex) {
            log(HEAD_ERROR + ex.getMessage() + "\n  " + expression, Level.ERROR);
            return null;
        }
    }
    return e;
}
Also used : REXPMismatchException(org.rosuda.REngine.REXPMismatchException) REXP(org.rosuda.REngine.REXP) RserveException(org.rosuda.REngine.Rserve.RserveException) IOException(java.io.IOException) REngineException(org.rosuda.REngine.REngineException) REXPMismatchException(org.rosuda.REngine.REXPMismatchException)

Example 4 with REXPMismatchException

use of org.rosuda.REngine.REXPMismatchException in project rsession by yannrichet.

the class RserveSession method set.

/**
 * Set R data.frame in R env.
 *
 * @param varname R list name
 * @param data numeric data in list
 * @param names names of columns
 * @return succeeded ?
 */
@Override
public boolean set(String varname, double[][] data, String... names) {
    RList list = buildRList(data, names);
    log(HEAD_SET + varname + " <- " + list, Level.INFO);
    try {
        synchronized (R) {
            R.assign(varname, REXP.createDataFrame(list));
        }
    } catch (REXPMismatchException re) {
        re.printStackTrace();
        log(HEAD_ERROR + " RList " + list.toString() + " not convertible as dataframe.", Level.ERROR);
        return false;
    } catch (RserveException ex) {
        log(HEAD_EXCEPTION + ex.getMessage() + "\n  set(String varname=" + varname + ",double[][] data, String... names)", Level.ERROR);
        return false;
    }
    return true;
}
Also used : RList(org.rosuda.REngine.RList) REXPMismatchException(org.rosuda.REngine.REXPMismatchException) RserveException(org.rosuda.REngine.Rserve.RserveException)

Example 5 with REXPMismatchException

use of org.rosuda.REngine.REXPMismatchException in project rsession by yannrichet.

the class RserveSession method putFile.

/**
 * Send user filesystem file in r environement (like data)
 *
 * @param localfile File to send
 * @param remoteFile filename in R env.
 */
public void putFile(File localfile, String remoteFile) {
    if (!localfile.exists()) {
        synchronized (R) {
            log(HEAD_ERROR + IO_HEAD + R.getLastError() + "\n  file " + localfile.getAbsolutePath() + " does not exists.", Level.ERROR);
        }
    }
    try {
        if (silentlyRawEval("file.exists('" + remoteFile.replace("\\", "/") + "')", TRY_MODE).asInteger() == 1) {
            silentlyVoidEval("file.remove('" + remoteFile.replace("\\", "/") + "')", TRY_MODE);
            log(IO_HEAD + "Remote file " + remoteFile + " deleted.", Level.INFO);
        }
    } catch (REXPMismatchException ex) {
        log(HEAD_ERROR + ex.getMessage() + "\n  putFile(File localfile=" + localfile.getAbsolutePath() + ", String remoteFile=" + remoteFile + ")", Level.ERROR);
        return;
    }
    InputStream is = null;
    OutputStream os = null;
    synchronized (R) {
        try {
            os = R.createFile(remoteFile);
            is = new BufferedInputStream(new FileInputStream(localfile));
            IOUtils.copy(is, os);
            log(IO_HEAD + "File " + remoteFile + " sent.", Level.INFO);
            is.close();
            os.close();
        } catch (IOException e) {
            log(HEAD_ERROR + IO_HEAD + R.getLastError() + ": file " + remoteFile + " not writable.\n" + e.getMessage(), Level.ERROR);
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) REXPMismatchException(org.rosuda.REngine.REXPMismatchException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream)

Aggregations

REXPMismatchException (org.rosuda.REngine.REXPMismatchException)8 RList (org.rosuda.REngine.RList)4 IOException (java.io.IOException)3 REXP (org.rosuda.REngine.REXP)3 RserveException (org.rosuda.REngine.Rserve.RserveException)3 REXPString (org.rosuda.REngine.REXPString)2 REngineException (org.rosuda.REngine.REngineException)2 DataVariable (edu.harvard.iq.dataverse.datavariable.DataVariable)1 VariableCategory (edu.harvard.iq.dataverse.datavariable.VariableCategory)1 BufferedInputStream (java.io.BufferedInputStream)1 BufferedOutputStream (java.io.BufferedOutputStream)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1 HashMap (java.util.HashMap)1 Map (java.util.Map)1 NamingException (javax.naming.NamingException)1 REXPList (org.rosuda.REngine.REXPList)1