Package dao

Source Code of dao.RCommand

package dao;


// import gui.JLatexPanel;
import gui.JRClientPanel;
import helper.Helper;
import dao.Rdao;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.rosuda.JRI.REXP;
import org.rosuda.JRI.Rengine;

import java.util.List;
import java.util.Arrays;


public class RCommand {

    private static Log log = LogFactory.getLog(RCommand.class);

    private static Rengine rengine;
    private static List<String> requiredLibs = Arrays.asList(new String[] {
        "ISOP", "rJava", "JavaGD", "xtable"
    });
 
    public static Rengine getRengine() {
        if (rengine == null) {
            try {
                System.out.println("Rengine Trying to construct rengine");
                rengine = new Rengine(null, false, new Rdao());
            } catch (Exception e) {
                System.out.println("Rengine construct Error");
                e.printStackTrace(); // neue Exception bauen nochmal fragen
                // TODO: handle exception
            }
           
            System.out.println("Rengine created, waiting for R");
            // the engine creates R is a new thread, so we should wait until it's ready
            if (!rengine.waitForR()) {
                System.out.println("Cannot load R");
                return null;
            }

            eval("print( 'Welcome to ISOP for R' )");
            require(requiredLibs);
            eval("Sys.setenv('JAVAGD_CLASS_NAME'='dao/JavaGD')");
            eval("JavaGD()");
            log.info("R initialized");
        }
       
        return rengine;

        // return null;
    }   
 
    public static String[] getNames(String dataset) {
        return evalStrings("names(" + dataset + ")");
    }
 
    public static String getName(String dataset, int i) {
        String[] buf = evalStrings("names(" + dataset + ")");

        if ((buf == null) || (buf.length < i)) {
            return "#ERROR";
        }
        return buf[i];
    }
   
    public static String[] getRowNames(String dataset) {
      if (evalBool("is.vector(" + dataset + ")"))
      return getNames(dataset);

        return evalStrings("dimnames(" + dataset + ")[[1]]");
    }
 
    public static String getRowName(String dataset, int i) {
      if (evalBool("is.vector(" + dataset + ")"))
      return getName(dataset, i);

      String[] buf = evalStrings("dimnames(" + dataset + ")[[1]]");

        if ((buf == null) || (buf.length < i)) {
            return "#ERROR";
        }
        return buf[i];
    }
   
    public static String[] getColNames(String dataset) {
      if (evalBool("is.vector(" + dataset + ")")) {
        String[] bla = { "(Value)" };
        return bla;
      }
     

      return evalStrings("dimnames(" + dataset + ")[[2]]");
    }
 
    public static String getColName(String dataset, int i) {
      if (evalBool("is.vector(" + dataset + ")"))
      return "(Value)";

      String[] buf = evalStrings("dimnames(" + dataset + ")[[2]]");

        if ((buf == null) || (buf.length < i)) {
            return "#ERROR";
        }
        return buf[i];
    }
   
    public static Double getValue(String dataset, int row, int col) {
        // TODO: handle ints too?
      if (evalBool("is.vector(" + dataset + ")"))
          return getValue(dataset, row);
      return evalDouble(
                "as.double(" + dataset + "[[" + row + "," + col + "]])");
    }
   
    public static Double getValue(String vector, int pos) {
        // TODO: handle ints too?
        log.debug(
                "getting: " + vector + "[[" + pos + "]] = "
                + evalDouble(vector + "[[" + pos + "]]"));
        return evalDouble("as.double(" + vector + "[[" + pos + "]])");
    }
 
    public static int getRowCount(String dataset) {
      if (evalBool("is.vector(" + dataset + ")"))
          return getLength(dataset);
        return evalInt("dim(" + dataset + ")[[1]]");
    }

    public static int getColCount(String dataset) {
      if (evalBool("is.vector(" + dataset + ")"))
          return 1;
        return evalInt("dim(" + dataset + ")[[2]]");
    }
   
    public static int getLength(String vector) {
        return evalInt("length(" + vector + ")");
    }
   
    public static boolean require(List<String> librarys) {
        boolean ret = true;

        for (String lib : librarys) {
            ret &= evalBool("require( " + lib + ")");
        }
        return ret;
    }

    public static String[] evalStrings(String evalstr) {
        REXP x = getRengine().eval(evalstr);

        if (x != null && x.asStringArray() != null) {
            return x.asStringArray()
        }
        return null;
    }
 
    public static String evalString(String evalstr) {
        REXP x = getRengine().eval(evalstr);

        if (x != null && x.asStringArray() != null) {
            return x.asStringArray()[1]
        }
        return "lala";
    }
 
    public static double[] evalDoubles(String evalstr) {
        REXP x = getRengine().eval(evalstr);

        if (x != null && x.asDoubleArray() != null) {
            return x.asDoubleArray()
        }
        return null;
    }
 
    public static Double evalDouble(String evalstr) {
        REXP x = getRengine().eval(evalstr);

        if (x != null && x.asDoubleArray() != null) {
            // TODO: try sinnvoll?
            try {
                return x.asDoubleArray()[0]
            } catch (Exception e) {
                return 0.0;
            }
        }
        return 0.0;
    }
 
    public static int evalInt(String evalstr) {
        REXP x = getRengine().eval(evalstr);

        if (x != null && x.asIntArray() != null) {
            return x.asIntArray()[0];
       
        log.error("Error while evaling" + evalstr);
        return -1;
    }
 
    public static boolean evalBool(String evalstr) {
        REXP x = getRengine().eval(evalstr);

        if (x != null && x.asBool() != null) {
            return x.asBool().isTRUE();
       
        log.error("Error while evaling" + evalstr);
        return false;
    }

    // Depricated
    /*
     public static String[] getHeaders() {
     return evalStrings("names(" + Constants.R_DATASET + ")");
     }
    
    
     public static String getHeader(int i) {
     String[] buf = evalStrings("names(" + Constants.R_DATASET + ")");

     if ((buf == null) || (buf.length < i)) {
     return "#ERROR";
     }
     return buf[i];
     }
    
     public static Double getValue(int row, int col) {
     // TODO: handle ints too?
     log.debug(
     "getting: isop.matrix[[" + row + "," + col + "]] = "
     + evalDouble("isop.matrix[[" + row + "," + col + "]]"));
     return evalDouble("as.double(isop.matrix[[" + row + "," + col + "]])");
     }
    
     public static int getRowCount() {
     return evalInt("dim(" + Constants.R_DATASET + ")[[1]]");
     }

     public static int getColCount() {
     return evalInt("dim(" + Constants.R_DATASET + ")[[2]]");
     }
     */

 
    /*
     Make sure that the data file is saved in your working directory.
     You can check to see what your working directory is by starting R,
     and typing getwd(). If you wish to use a different directory as your
     starting directory, use setwd("dirpath"), where "dirpath" is the full
     directory path of the directory you would like to use as your working
     directory.  After setting your working directory, load data using one
     of the following methods:    
     1. If your dataset is in a tab- or space-
     delimited .txt file, use read.table("mydata.txt")   erledigt
    
     2. If your dataset is a comma separated table,
     use read.csv("mydata.csv").   
    
     3. To import SPSS, Stata, and other data files,
     use the foreign package, which automatically preserves field
     characteristics for each variable. Thus, variables classed as dates
     in Stata are automatically translated into values in the date class
     for R. For example:        > library(foreign)                           # Load the foreign package.         > stata.data <- read.dta("mydata.dta")       # For Stata data.       > spss.data <- read.spss("mydata.sav", to.data.frame = TRUE) # For SPSS. 
    
     */

 
    public static boolean exists(String varname) {
        return evalBool("exists(\"" + varname + "\")");
    }
 
    public static void remove(String varname) {
        log.info("removing " + varname + "from R");
        eval("rm(\"" + varname + "\")");
    }
   
    public static void runSweave(String filename) {
        eval("library(tools)");
        log.info(System.getProperty("user.dir"));
        eval("Sweave(\"" + filename + "\")");
        log.info(System.getProperty("user.dir"));
    }
   
    public static void evalprint(String command) {
        log.info("Performing & printing Command: " + command);
        JRClientPanel.writeHistory(command);
        rengine.eval("print(" + command + ")");
    }
 
    public static void eval(String command) {
        log.info("Performing Command: " + command);
        JRClientPanel.writeHistory(command);
        Rengine re = getRengine();

        if (re == null) {
            Helper.ok("aaaah");
        }
        re.eval(command);
    }

    /*
     //rdao.getRengine()
     String evalstr = "[" +  + "]";
    
     REXP x = getRengine().eval(evalstr);
     if (x != null && x.asStringArray()!=null) {
     String buf[] = x.asStringArray();
     for (int i=0;i<buf.length;i++)
     log.info(i + ": " + buf[i] + " " + buf.length);
     }
    
    
     /*
    
     evalstr = "isopmatrix<-read.spss(\"" + path + "\")";
    
     x = getRengine().eval(evalstr);
     if (x != null && x.asStringArray()!=null) {
     String buf[] = x.asStringArray();
     for (int i=0;i<buf.length;i++)
     log.info(i + ": " + buf[i] + " " + buf.length);
     }
    
     evalstr = "names(isopmatrix)";
    
     x = getRengine().eval(evalstr);
     if (x != null && x.asStringArray()!=null) {
     String buf[] = x.asStringArray();
     for (int i=0;i<buf.length;i++)
     log.info(i + ": " + buf[i] + " " + buf.length);
     }
    
     evalstr = "print(isopmatrix)";
    
     x = getRengine().eval(evalstr);
     if (x != null && x.asStringArray()!=null) {
     String buf[] = x.asStringArray();
     for (int i=0;i<buf.length;i++)
     log.info(i + ": " + buf[i] + " " + buf.length);
     }
    
     evalstr = "print(length(isopmatrix))";
     //String evalstr = ".libPaths()"
     //REXP rexp = rdao.getRengine().eval(evalstr);
     log.info(evalstr);
     /*
     log.info(rexp.toString());
     log.info(rexp.asIntArray());
     log.info(rexp.asStringArray());
     log.info(rexp.rtype + ", " + rexp.xp);
    
     x = getRengine().eval(evalstr);
     if (x != null && x.asStringArray()!=null) {
     String buf[] = x.asStringArray();
     for (int i=0;i<buf.length;i++)
     log.info(i + ": " + buf[i] + " " + buf.length);
     }
    
     rdao.getRengine().eval("print(length(isopmatrix))");
     log.info("print(length(isopmatrix))");
     rdao.getRengine().eval("library(foreign)");
     log.info(Constants.R_DATASET + "<-read.spss(\""+ path +"\")");
     rdao.getRengine().eval(Constants.R_DATASET + "<-read.spss("+ path +")");
     rdao.getRengine().eval("print(length(" + Constants.R_DATASET + "))");
     */
TOP

Related Classes of dao.RCommand

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.