org.rosuda.JRI
Class Rengine

java.lang.Object
  extended by java.lang.Thread
      extended by org.rosuda.JRI.Rengine
All Implemented Interfaces:
Runnable

public class Rengine
extends Thread

Rengine class is the interface between an instance of R and the Java VM. Due to the fact that R has no threading support, you can run only one instance of R withing a multi-threaded application. There are two ways to use R from Java: individual call and full event loop. See the Rengine constructor for details.

Important note: All methods starting with rni (R Native Interface) are low-level native methods that should be avoided if a high-level methods exists. They do NOT attempt any synchronization, so it is the duty of the calling program to ensure that the invocation is safe (see getRsync() for details). At some point in the future when the high-level API is complete they should become private. However, currently this high-level layer is not complete, so they are available for now.

All rni methods use long type to reference SEXPs on R side. Those reference should never be modified or used in arithmetics - the only reason for not using an extra interface class to wrap those references is that rni methods are all native methods and therefore it would be too expensive to handle the unwrapping on the C side.

jri methods are called internally by R and invoke the corresponding method from the even loop handler. Those methods should usualy not be called directly.


Nested Class Summary
 
Nested classes/interfaces inherited from class java.lang.Thread
Thread.State, Thread.UncaughtExceptionHandler
 
Field Summary
static int DEBUG
          debug flag.
 int idleDelay
          this value specifies the time (in ms) to spend sleeping between checks for R shutdown requests if R event loop is not used.
 
Fields inherited from class java.lang.Thread
MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY
 
Constructor Summary
Rengine(String[] args, boolean runMainLoop, RMainLoopCallbacks initialCallbacks)
          create and start a new instance of R.
 
Method Summary
 void addMainLoopCallbacks(RMainLoopCallbacks c)
          Add a handler for R callbacks.
 void assign(String sym, boolean[] val)
          assign values of an array of booleans to a symbol in R (creating a logical vector).
 void assign(String sym, double[] val)
          assign values of an array of doubles to a symbol in R (creating an integer vector).
 void assign(String sym, int[] val)
          assign values of an array of integers to a symbol in R (creating a numeric vector).
 void assign(String sym, REXP r)
          assign a content of a REXP to a symbol in R.
 void assign(String sym, String ct)
          assign a string value to a symbol in R.
 void assign(String sym, String[] val)
          assign values of an array of strings to a symbol in R (creating a character vector).
 void end()
          attempt to shut down R.
 REXP eval(String s)
          Parses and evaluates an R expression and returns the result.
 REXP eval(String s, boolean convert)
          Parses and evaluates an R expression and returns the result.
static Rengine getMainEngine()
          return the current main R engine instance.
 Mutex getRsync()
          returns the synchronization mutex for this engine.
static long getVersion()
          API version of the Rengine itself; see also rniGetVersion() for binary version.
 REXP idleEval(String s)
          This method is very much like eval(String), except that it is non-blocking and returns null if the engine is busy.
 REXP idleEval(String s, boolean convert)
          This method is very much like eval(String,boolean), except that it is non-blocking and returns null if the engine is busy.
 void jriBusy(int which)
          JRI: R_Busy call-back from R
 String jriChooseFile(int newFile)
          JRI: R_ChooseFile call-back from R
 void jriFlushConsole()
          JRI: R_FlushConsole call-back from R
 void jriLoadHistory(String filename)
          JRI: R_loadhistory call-back from R
 String jriReadConsole(String prompt, int addToHistory)
          JRI: R_ReadConsole call-back from R.
 void jriSaveHistory(String filename)
          JRI: R_savehistory call-back from R
 void jriShowMessage(String message)
          JRI: R_ShowMessage call-back from R
 void jriWriteConsole(String text)
          JRI: R_WriteConsole call-back from R
 void rniAssign(String name, long exp, long rho)
          RNI: assign a value to an environment
 long rniCAR(long exp)
          RNI: get CAR of a dotted-pair list (LISTSXP)
 long rniCDR(long exp)
          RNI: get CDR of a dotted-pair list (LISTSXP)
 long rniCons(long head, long tail)
          RNI: create a dotted-pair list (LISTSXP)
 long rniEval(long exp, long rho)
          RNI: evaluate R expression (do NOT use directly unless you know exactly what you're doing, where possible use eval(java.lang.String) instead).
 int rniExpType(long exp)
          RNI: get the SEXP type
 long rniGetAttr(long exp, String name)
          RNI: get an attribute
 int[] rniGetBoolArrayI(long exp)
          RNI: get the contents of a logical vector in its integer array form
 double[] rniGetDoubleArray(long exp)
          RNI: get the contents of a numeric vector
 int[] rniGetIntArray(long exp)
          RNI: get the contents of an integer vector
 long[] rniGetList(long exp)
          RNI: retrieve CAR part of a dotted-part list recursively as an array of references
 String rniGetString(long exp)
          RNI: get the contents of the first entry of a character vector
 String[] rniGetStringArray(long exp)
          RNI: get the contents of a character vector
 String rniGetSymbolName(long sym)
          RNI: retrieve name of a symbol (c.f.
 long[] rniGetVector(long exp)
          RNI: get the contents of a generic vector (aka list)
static long rniGetVersion()
          RNI: return the API version of the native library
 void rniIdle()
          RNI: run other event handlers in R
 boolean rniInherits(long exp, String cName)
          RNI: determines whether an R object instance inherits from a specific class (S3 for now)
 long rniInstallSymbol(String sym)
          RNI: install a symbol name
 long rniParse(String s, int parts)
          RNI: parses a string into R expressions (do NOT use directly unless you know exactly what you're doing, where possible use eval(java.lang.String) instead).
 void rniProtect(long exp)
          RNI: protect an R object (c.f.
 long rniPutBoolArray(boolean[] a)
          RNI: create a boolean vector
 long rniPutBoolArrayI(int[] a)
          RNI: create a boolean vector from an integer vector
 long rniPutDoubleArray(double[] a)
          RNI: create a numeric vector
 long rniPutIntArray(int[] a)
          RNI: create an integer vector
 long rniPutList(long[] cont)
          RNI: create a dotted-pair list (LISTSXP)
 long rniPutString(String s)
          RNI: create a character vector of the length 1
 long rniPutStringArray(String[] a)
          RNI: create a character vector
 long rniPutVector(long[] exps)
          RNI: create a generic vector (aka a list)
 void rniRunMainLoop()
          RNI: run the main loop.
 void rniSetAttr(long exp, String name, long attr)
          RNI: set an attribute
 int rniStop(int flag)
          RNI: interrupt the R process (if possible)
 long rniTAG(long exp)
          RNI: get TAG of a dotted-pair list (LISTSXP)
 void rniUnprotect(int count)
          RNI: unprotect last count references (c.f.
 void run()
          The implementation of the R thread.
 void startMainLoop()
          if Rengine was initialized with runMainLoop=false then this method can be used to start the main loop at a later point.
static boolean versionCheck()
          check API version of this class and the native binary.
 boolean waitForR()
          check the state of R
 
Methods inherited from class java.lang.Thread
activeCount, checkAccess, countStackFrames, currentThread, destroy, dumpStack, enumerate, getAllStackTraces, getContextClassLoader, getDefaultUncaughtExceptionHandler, getId, getName, getPriority, getStackTrace, getState, getThreadGroup, getUncaughtExceptionHandler, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, setContextClassLoader, setDaemon, setDefaultUncaughtExceptionHandler, setName, setPriority, setUncaughtExceptionHandler, sleep, sleep, start, stop, stop, suspend, toString, yield
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

DEBUG

public static int DEBUG
debug flag. Set to value >0 to enable debugging messages. The verbosity increases with increasing number


idleDelay

public int idleDelay
this value specifies the time (in ms) to spend sleeping between checks for R shutdown requests if R event loop is not used. The default is 200ms. Higher values lower the CPU usage but may make R less responsive to shutdown attempts (in theory it should not matter because Thread.stop() uses interrupt to awake from the idle sleep immediately, but some implementation may not honor that).

Since:
JRI 0.3
Constructor Detail

Rengine

public Rengine(String[] args,
               boolean runMainLoop,
               RMainLoopCallbacks initialCallbacks)
create and start a new instance of R.

Parameters:
args - arguments to be passed to R. Please note that R requires the presence of certain arguments (e.g. --save or --no-save or equivalents), so passing an empty list usually doesn't work.
runMainLoop - if set to true the the event loop will be started as soon as possible, otherwise no event loop is started. Running loop requires initialCallbacks to be set correspondingly as well.
initialCallbacks - an instance implementing the RMainLoopCallbacks interface that provides methods to be called by R
Method Detail

getVersion

public static long getVersion()
API version of the Rengine itself; see also rniGetVersion() for binary version. It's a good idea for the calling program to check the versions of both and abort if they don't match. This should be done using versionCheck()

Returns:
version number as long in the form 0xMMmm

versionCheck

public static boolean versionCheck()
check API version of this class and the native binary. This is usually a good idea to ensure consistency.

Returns:
true if the API version of the Java code and the native library matches, false otherwise

getMainEngine

public static Rengine getMainEngine()
return the current main R engine instance. Since there can be only one true R instance at a time, this is also the only instance. This may not be true for future versions, though.

Returns:
current instance of the R engine or null if no R engine was started yet.

rniParse

public long rniParse(String s,
                     int parts)
RNI: parses a string into R expressions (do NOT use directly unless you know exactly what you're doing, where possible use eval(java.lang.String) instead). Note that no synchronization is performed!

Parameters:
s - string to parse
parts - number of expressions contained in the string
Returns:
reference to the resulting list of expressions

rniEval

public long rniEval(long exp,
                    long rho)
RNI: evaluate R expression (do NOT use directly unless you know exactly what you're doing, where possible use eval(java.lang.String) instead). Note that no synchronization is performed!

Parameters:
exp - reference to the expression to evaluate
rho - environment to use for evaluation (or 0 for global environemnt)
Returns:
result of the evaluation

rniProtect

public void rniProtect(long exp)
RNI: protect an R object (c.f. PROTECT macro in C)

Parameters:
exp - reference to protect
Since:
API 1.5, JRI 0.3

rniUnprotect

public void rniUnprotect(int count)
RNI: unprotect last count references (c.f. UNPROTECT in C)

Parameters:
count - number of references to unprotect
Since:
API 1.5, JRI 0.3

rniGetString

public String rniGetString(long exp)
RNI: get the contents of the first entry of a character vector

Parameters:
exp - reference to STRSXP
Returns:
contents or null if the reference is not STRSXP

rniGetStringArray

public String[] rniGetStringArray(long exp)
RNI: get the contents of a character vector

Parameters:
exp - reference to STRSXP
Returns:
contents or null if the reference is not STRSXP

rniGetIntArray

public int[] rniGetIntArray(long exp)
RNI: get the contents of an integer vector

Parameters:
exp - reference to INTSXP
Returns:
contents or null if the reference is not INTSXP

rniGetBoolArrayI

public int[] rniGetBoolArrayI(long exp)
RNI: get the contents of a logical vector in its integer array form

Parameters:
exp - reference to LGLSXP
Returns:
contents or null if the reference is not LGLSXP
Since:
API 1.6, JRI 0.3-2

rniGetDoubleArray

public double[] rniGetDoubleArray(long exp)
RNI: get the contents of a numeric vector

Parameters:
exp - reference to REALSXP
Returns:
contents or null if the reference is not REALSXP

rniGetVector

public long[] rniGetVector(long exp)
RNI: get the contents of a generic vector (aka list)

Parameters:
exp - reference to VECSXP
Returns:
contents as an array of references or null if the reference is not VECSXP

rniPutString

public long rniPutString(String s)
RNI: create a character vector of the length 1

Parameters:
s - initial contents of the first entry
Returns:
reference to the resulting STRSXP

rniPutStringArray

public long rniPutStringArray(String[] a)
RNI: create a character vector

Parameters:
a - initial contents of the vector
Returns:
reference to the resulting STRSXP

rniPutIntArray

public long rniPutIntArray(int[] a)
RNI: create an integer vector

Parameters:
a - initial contents of the vector
Returns:
reference to the resulting INTSXP

rniPutBoolArrayI

public long rniPutBoolArrayI(int[] a)
RNI: create a boolean vector from an integer vector

Parameters:
a - initial contents of the vector
Returns:
reference to the resulting LGLSXP
Since:
API 1.6, JRI 0.3-2

rniPutBoolArray

public long rniPutBoolArray(boolean[] a)
RNI: create a boolean vector

Parameters:
a - initial contents of the vector
Returns:
reference to the resulting LGLSXP
Since:
API 1.6, JRI 0.3-2

rniPutDoubleArray

public long rniPutDoubleArray(double[] a)
RNI: create a numeric vector

Parameters:
a - initial contents of the vector
Returns:
reference to the resulting REALSXP

rniPutVector

public long rniPutVector(long[] exps)
RNI: create a generic vector (aka a list)

Parameters:
exps - initial contents of the vector consisiting of an array of references
Returns:
reference to the resulting VECSXP

rniGetAttr

public long rniGetAttr(long exp,
                       String name)
RNI: get an attribute

Parameters:
exp - reference to the object whose attribute is requested
name - name of the attribute
Returns:
reference to the attribute or 0 if there is none

rniSetAttr

public void rniSetAttr(long exp,
                       String name,
                       long attr)
RNI: set an attribute

Parameters:
exp - reference to the object whose attribute is to be modified
name - attribute name
attr - reference to the object to be used as teh contents of the attribute

rniInherits

public boolean rniInherits(long exp,
                           String cName)
RNI: determines whether an R object instance inherits from a specific class (S3 for now)

Parameters:
exp - reference to an object
cName - name of the class to check
Returns:
true if cName inherits from class cName (see inherits in R)
Since:
API 1.5, JRI 0.3

rniCons

public long rniCons(long head,
                    long tail)
RNI: create a dotted-pair list (LISTSXP)

Parameters:
head - CAR
tail - CDR (must be a reference to LISTSXP or 0)
Returns:
reference to the newly created LISTSXP

rniCAR

public long rniCAR(long exp)
RNI: get CAR of a dotted-pair list (LISTSXP)

Parameters:
exp - reference to the list
Returns:
reference to CAR of the list (head)

rniCDR

public long rniCDR(long exp)
RNI: get CDR of a dotted-pair list (LISTSXP)

Parameters:
exp - reference to the list
Returns:
reference to CDR of the list (tail)

rniTAG

public long rniTAG(long exp)
RNI: get TAG of a dotted-pair list (LISTSXP)

Parameters:
exp - reference to the list
Returns:
reference to TAG of the list (tail)

rniPutList

public long rniPutList(long[] cont)
RNI: create a dotted-pair list (LISTSXP)

Parameters:
cont - contents as an array of references
Returns:
reference to the newly created LISTSXP
Since:
API 1.5, JRI 0.3

rniGetList

public long[] rniGetList(long exp)
RNI: retrieve CAR part of a dotted-part list recursively as an array of references

Parameters:
exp - reference to a dotted-pair list (LISTSXP)
Returns:
contents of the list as an array of references

rniGetSymbolName

public String rniGetSymbolName(long sym)
RNI: retrieve name of a symbol (c.f. PRINTNAME)

Parameters:
sym - reference to a symbol
Returns:
name of the symbol or null on error or if exp is no symbol
Since:
API 1.5, JRI 0.3

rniInstallSymbol

public long rniInstallSymbol(String sym)
RNI: install a symbol name

Parameters:
sym - symbol name
Returns:
reference to SYMSXP referencing the symbol
Since:
API 1.5, JRI 0.3

rniGetVersion

public static long rniGetVersion()
RNI: return the API version of the native library

Returns:
API version of the native library

rniStop

public int rniStop(int flag)
RNI: interrupt the R process (if possible)

Parameters:
flag - currently ignored, must be set to 0
Returns:
result code (currently unspecified)

rniAssign

public void rniAssign(String name,
                      long exp,
                      long rho)
RNI: assign a value to an environment

Parameters:
name - name
exp - value
rho - environment (use 0 for the global environment)

rniExpType

public int rniExpType(long exp)
RNI: get the SEXP type

Parameters:
exp - reference to a SEXP
Returns:
type of the expression (see xxxSEXP constants)

rniRunMainLoop

public void rniRunMainLoop()
RNI: run the main loop.
Note: this is an internal method and it doesn't return until the loop exits. Don't use directly!


rniIdle

public void rniIdle()
RNI: run other event handlers in R


addMainLoopCallbacks

public void addMainLoopCallbacks(RMainLoopCallbacks c)
Add a handler for R callbacks. The current implementation supports only one handler at a time, so call to this function implicitly removes any previous handlers


startMainLoop

public void startMainLoop()
if Rengine was initialized with runMainLoop=false then this method can be used to start the main loop at a later point. It has no effect if the loop is running already. This method returns immediately but the loop will be started once the engine is ready. Please note that there is currently no way of stopping the R thread if the R event loop is running other than using quit command in R which closes the entire application.


jriWriteConsole

public void jriWriteConsole(String text)
JRI: R_WriteConsole call-back from R

Parameters:
text - text to disply

jriBusy

public void jriBusy(int which)
JRI: R_Busy call-back from R

Parameters:
which - state

jriReadConsole

public String jriReadConsole(String prompt,
                             int addToHistory)
JRI: R_ReadConsole call-back from R.

Parameters:
prompt - prompt to display before waiting for the input.
Note: implementations should block for input. Returning immediately is usually a bad idea, because the loop will be cycling.
addToHistory - flag specifying whether the entered contents should be added to history
Returns:
content entered by the user. Returning null corresponds to an EOF and usually causes R to exit (as in q()).

jriShowMessage

public void jriShowMessage(String message)
JRI: R_ShowMessage call-back from R

Parameters:
message - message

jriLoadHistory

public void jriLoadHistory(String filename)
JRI: R_loadhistory call-back from R

Parameters:
filename - name of the history file

jriSaveHistory

public void jriSaveHistory(String filename)
JRI: R_savehistory call-back from R

Parameters:
filename - name of the history file

jriChooseFile

public String jriChooseFile(int newFile)
JRI: R_ChooseFile call-back from R

Parameters:
newFile - flag specifying whether an existing or new file is requested
Returns:
name of the selected file or null if cancelled

jriFlushConsole

public void jriFlushConsole()
JRI: R_FlushConsole call-back from R


eval

public REXP eval(String s)
Parses and evaluates an R expression and returns the result. Has the same effect as calling eval(s, true).

Parameters:
s - expression (as string) to parse and evaluate
Returns:
resulting expression or null if something wnet wrong

eval

public REXP eval(String s,
                 boolean convert)
Parses and evaluates an R expression and returns the result.

Parameters:
s - expression (as string) to parse and evaluate
convert - if set to true the resulting REXP will contain native representation of the contents, otherwise an empty REXP will be returned. Depending on the back-end an empty REXP may or may not be used to convert the result at a later point.
Returns:
resulting expression or null if something wnet wrong
Since:
JRI 0.3

idleEval

public REXP idleEval(String s)
This method is very much like eval(String), except that it is non-blocking and returns null if the engine is busy.

Parameters:
s - string to evaluate
Returns:
result of the evaluation or null if the engine is busy

idleEval

public REXP idleEval(String s,
                     boolean convert)
This method is very much like eval(String,boolean), except that it is non-blocking and returns null if the engine is busy.

Parameters:
s - string to evaluate
convert - flag denoting whether an empty or fully-converted REXP should be returned (see eval(String,boolean) for details)
Returns:
result of the evaluation or null if the engine is busy
Since:
JRI 0.3

getRsync

public Mutex getRsync()
returns the synchronization mutex for this engine. If an external code needs to use RNI calls, it should do so only in properly protected environment secured by this mutex. Usually the procedure should be as follows:
        boolean obtainedLock = e.getRsync().safeLock();
        try {
                // use RNI here ...
        } finally {
                if (obtainedLock) e.getRsync().unlock();
        }
        

Returns:
synchronization mutex
Since:
JRI 0.3

waitForR

public boolean waitForR()
check the state of R

Returns:
true if R is alive and false if R died or exitted

end

public void end()
attempt to shut down R. This method is asynchronous.


run

public void run()
The implementation of the R thread. This method should not be called directly.

Specified by:
run in interface Runnable
Overrides:
run in class Thread

assign

public void assign(String sym,
                   String ct)
assign a string value to a symbol in R. The symbol is created if it doesn't exist already.

Parameters:
sym - symbol name. The symbol name is used as-is, i.e. as if it was quoted in R code (for example assigning to "foo$bar" has the same effect as `foo$bar`<- and NOT foo$bar<-).
ct - contents
Since:
JRI 0.3

assign

public void assign(String sym,
                   REXP r)
assign a content of a REXP to a symbol in R. The symbol is created if it doesn't exist already.

Parameters:
sym - symbol name. The symbol name is used as-is, i.e. as if it was quoted in R code (for example assigning to "foo$bar" has the same effect as `foo$bar`<- and NOT foo$bar<-).
r - contents as REXP. currently only raw references and basic types (int, double, int[], double[], boolean[]) are supported.
Since:
JRI 0.3

assign

public void assign(String sym,
                   double[] val)
assign values of an array of doubles to a symbol in R (creating an integer vector).
equals to calling assign(String, REXP).

Parameters:
sym - symbol name
val - double array to assign
Since:
JRI 0.3

assign

public void assign(String sym,
                   int[] val)
assign values of an array of integers to a symbol in R (creating a numeric vector).
equals to calling assign(String, REXP).

Parameters:
sym - symbol name
val - integer array to assign
Since:
JRI 0.3

assign

public void assign(String sym,
                   boolean[] val)
assign values of an array of booleans to a symbol in R (creating a logical vector).
equals to calling assign(String, REXP).

Parameters:
sym - symbol name
val - boolean array to assign
Since:
JRI 0.3-2

assign

public void assign(String sym,
                   String[] val)
assign values of an array of strings to a symbol in R (creating a character vector).
equals to calling assign(String, REXP).

Parameters:
sym - symbol name
val - string array to assign
Since:
JRI 0.3