Search in sources :

Example 6 with REXPMismatchException

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

the class RserveSession method silentlyVoidEval.

/**
 * Silently (ie no log) launch R command without return value.
 *
 * @param expression R expresison to evaluate
 * @param tryEval encapsulate command in try() to cacth errors
 * @return succeeded ?
 */
@Override
public boolean silentlyVoidEval(String expression, boolean tryEval) {
    // assert connected : "R environment not initialized.";
    if (!connected) {
        log(HEAD_EXCEPTION + "R environment not initialized.", Level.ERROR);
        return false;
    }
    if (expression == null) {
        return false;
    }
    if (expression.trim().length() == 0) {
        return true;
    }
    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);
            return false;
        } 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(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(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);
                return false;
            }
        } catch (REXPMismatchException ex) {
            log(HEAD_ERROR + ex.getMessage() + "\n  " + expression, Level.ERROR);
            return false;
        }
    }
    return true;
}
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 7 with REXPMismatchException

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

the class RDATAFileReader method processVariableInfo.

/**
 * Get a HashMap matching column number to meta-data used in re-creating R
 * Objects
 *
 * @param metaInfo an "RList" Object containing indices - type, type.string,
 * class, levels, and format.
 * @param dataTable a dataverse DataTable object
 */
private void processVariableInfo(RList metaInfo, DataTable dataTable) throws IOException {
    // list(type = 1, type.string = "integer", class = class(values), levels = NULL, format = NULL)
    Integer variableType = -1;
    String variableTypeName = "", variableFormat = "";
    String[] variableLevels = null;
    for (int k = 0; k < metaInfo.size(); k++) {
        try {
            // Meta-data for a column in the data-set
            RList columnMeta = metaInfo.at(k).asList();
            // Extract information from the returned list
            variableType = !columnMeta.at("type").isNull() ? columnMeta.at("type").asInteger() : null;
            variableTypeName = !columnMeta.at("type.string").isNull() ? columnMeta.at("type.string").asString() : null;
            variableLevels = !columnMeta.at("levels").isNull() ? columnMeta.at("levels").asStrings() : new String[0];
            variableFormat = !columnMeta.at("format").isNull() ? columnMeta.at("format").asString() : null;
            LOG.fine("variable type: " + variableType);
            LOG.fine("variable type name: " + variableTypeName);
            LOG.fine("variable format: " + variableFormat);
            for (String variableLevel : variableLevels) {
                LOG.fine("variable level: " + variableLevel);
            }
            if (variableTypeName == null || variableTypeName.equals("character") || variableTypeName.equals("other")) {
                // This is a String:
                dataTable.getDataVariables().get(k).setTypeCharacter();
                dataTable.getDataVariables().get(k).setIntervalDiscrete();
            } else if (variableTypeName.equals("integer")) {
                dataTable.getDataVariables().get(k).setTypeNumeric();
                dataTable.getDataVariables().get(k).setIntervalDiscrete();
            } else if (variableTypeName.equals("numeric") || variableTypeName.equals("double")) {
                dataTable.getDataVariables().get(k).setTypeNumeric();
                dataTable.getDataVariables().get(k).setIntervalContinuous();
            } else if (variableTypeName.startsWith("Date")) {
                dataTable.getDataVariables().get(k).setTypeCharacter();
                dataTable.getDataVariables().get(k).setIntervalDiscrete();
                dataTable.getDataVariables().get(k).setFormat(variableFormat);
                // instead:
                if (variableTypeName.equals("Date")) {
                    dataTable.getDataVariables().get(k).setFormatCategory("date");
                } else if (variableTypeName.equals("DateTime")) {
                    dataTable.getDataVariables().get(k).setFormatCategory("time");
                }
            } else if (variableTypeName.equals("factor")) {
                // All R factors are *string* factors!
                dataTable.getDataVariables().get(k).setTypeCharacter();
                dataTable.getDataVariables().get(k).setIntervalDiscrete();
                if (variableLevels != null && variableLevels.length > 0) {
                    // yes, this is a factor, with levels defined.
                    LOG.fine("this is a factor.");
                    boolean ordered = false;
                    if (variableFormat != null && variableFormat.equals("ordered")) {
                        LOG.fine("an ordered factor, too");
                        ordered = true;
                    }
                    for (int i = 0; i < variableLevels.length; i++) {
                        VariableCategory cat = new VariableCategory();
                        cat.setValue(variableLevels[i]);
                        // Sadly, R factors don't have descriptive labels;
                        cat.setLabel(variableLevels[i]);
                        if (ordered) {
                            cat.setOrder(i + 1);
                        }
                        /* cross-link the variable and category to each other: */
                        cat.setDataVariable(dataTable.getDataVariables().get(k));
                        dataTable.getDataVariables().get(k).getCategories().add(cat);
                    }
                    dataTable.getDataVariables().get(k).setOrderedCategorical(ordered);
                }
            } else // we turn R factors into - above.
            if ("logical".equals(variableTypeName)) {
                dataTable.getDataVariables().get(k).setFormatCategory("Boolean");
                dataTable.getDataVariables().get(k).setTypeNumeric();
                dataTable.getDataVariables().get(k).setIntervalDiscrete();
                String[] booleanFactorLabels = new String[2];
                booleanFactorLabels[0] = "FALSE";
                booleanFactorLabels[1] = "TRUE";
                String[] booleanFactorValues = new String[2];
                booleanFactorValues[0] = "0";
                booleanFactorValues[1] = "1";
                for (int i = 0; i < 2; i++) {
                    VariableCategory cat = new VariableCategory();
                    cat.setValue(booleanFactorValues[i]);
                    // Sadly, R factors don't have descriptive labels;
                    cat.setLabel(booleanFactorLabels[i]);
                    /* cross-link the variable and category to each other: */
                    cat.setDataVariable(dataTable.getDataVariables().get(k));
                    dataTable.getDataVariables().get(k).getCategories().add(cat);
                }
            }
        // Store the meta-data in a hashmap (to return later)
        } catch (REXPMismatchException ex) {
            // If something went wrong, then it wasn't meant to be for that column.
            // And you know what? That's okay.
            ex.printStackTrace();
            LOG.fine(String.format("Could not process variable %d of the data frame.", k));
        }
    }
}
Also used : VariableCategory(edu.harvard.iq.dataverse.datavariable.VariableCategory) RList(org.rosuda.REngine.RList) REXPMismatchException(org.rosuda.REngine.REXPMismatchException)

Example 8 with REXPMismatchException

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

the class RserveSession method cat.

// <editor-fold defaultstate="collapsed" desc="Conveniency static String methods">
public static String cat(RList list) {
    if (list == null || list.names == null) {
        return null;
    }
    try {
        StringBuffer sb = new StringBuffer("\t");
        double[][] data = new double[list.names.size()][];
        for (int i = 0; i < list.size(); i++) {
            String n = list.keyAt(i);
            sb.append(n + "\t");
            data[i] = list.at(n).asDoubles();
        }
        sb.append("\n");
        for (int i = 0; i < data[0].length; i++) {
            sb.append((i + 1) + "\t");
            for (int j = 0; j < data.length; j++) {
                sb.append(data[j][i] + "\t");
            }
            sb.append("\n");
        }
        return sb.toString();
    } catch (REXPMismatchException r) {
        return "(Not a numeric dataframe)\n" + new REXPList(list).toDebugString();
    }
}
Also used : REXPMismatchException(org.rosuda.REngine.REXPMismatchException) REXPString(org.rosuda.REngine.REXPString) REXPList(org.rosuda.REngine.REXPList)

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