本文整理汇总了Java中org.rosuda.REngine.Rserve.RConnection类的典型用法代码示例。如果您正苦于以下问题:Java RConnection类的具体用法?Java RConnection怎么用?Java RConnection使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
RConnection类属于org.rosuda.REngine.Rserve包,在下文中一共展示了RConnection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: executeStringFunction
import org.rosuda.REngine.Rserve.RConnection; //导入依赖的package包/类
/**
* Executes an R function (return: String)
*
* @param function
* name of the R function
* @param parameters
* array of parameters required by the function
*
* TODO: make more generic - not just for Strings ...
*/
public static String executeStringFunction(RConnection conn, String function, String[] parameters) {
try {
// create request
String request = "try(" + function + "(";
for (String parameter : parameters) {
request += parameter + ",";
}
// remove last ","
request = request.substring(0, request.length() - 1);
request += "))";
// execute function
REXP xp = conn.parseAndEval(request);
if (xp.inherits("try-error")) {
close(conn);
throw new IOException("failed to execute function '" + function + "'; \nrequest: " + request
+ "; \nError: " + xp.asString());
}
String retval = xp.asString();
return retval;
}
catch (Exception e) {
return null;
}
}
示例2: getRServeConnection
import org.rosuda.REngine.Rserve.RConnection; //导入依赖的package包/类
/**
* Get an R connection
*
* @param host
* @param workspace
* @return {@link RConnection} rConnection - a connection to RServer
*/
private static RConnection getRServeConnection(String host, String workspace) {
try {
// establish R connection
RConnection conn = new RConnection(host);
// check connection
if (conn == null || !conn.isConnected())
throw new IOException("Failed to establish RServe connection");
// set workspace
if (workspace != null) {
REXP xp = conn.parseAndEval("try(setwd('" + workspace.replace("\\", "\\\\") + "'))");
if (xp.inherits("try-error"))
throw new IOException("Failed to load R workspace; \nError: " + xp.asString());
}
return conn;
}
catch (Exception e) {
return null;
}
}
示例3: attemptStarts
import org.rosuda.REngine.Rserve.RConnection; //导入依赖的package包/类
private RConnection attemptStarts(String host, int port) throws InterruptedException, IOException, RserveException {
startRserve();
int attempt = 1;
RConnection con = null;
while (attempt <= START_ATTEMP_COUNT) {
try {
Thread.sleep(START_ATTEMPT_SLEEP); // wait for R to startup, then establish connection
con = newConnection(host, port);
break;
}
catch (RserveException rse) {
if (attempt >= 5) {
throw rse;
}
attempt++;
}
}
return con;
}
示例4: logGenericRProcess
import org.rosuda.REngine.Rserve.RConnection; //导入依赖的package包/类
public static void logGenericRProcess(RConnection rCon, String message) {
String msg = prepareMessage(message);
StringBuilder evalString = new StringBuilder();
evalString.append("cat(\"[GenericRProcess @ ");
evalString.append(format.format(new Date(System.currentTimeMillis())));
evalString.append("] ");
evalString.append(msg);
evalString.append("\\n\")");
try {
rCon.eval(evalString.toString());
}
catch (RserveException e) {
LOGGER.warn("Could not log message '" + msg + "'", e);
}
}
示例5: log
import org.rosuda.REngine.Rserve.RConnection; //导入依赖的package包/类
public static void log(RConnection rCon, String message) {
String msg = prepareMessage(message);
StringBuilder evalString = new StringBuilder();
evalString.append("cat(\"[WPS4R @ ");
evalString.append(format.format(new Date(System.currentTimeMillis())));
evalString.append("] ");
evalString.append(msg);
evalString.append("\\n\")");
try {
rCon.eval(evalString.toString());
}
catch (RserveException e) {
LOGGER.warn("Could not log message '" + msg + "'", e);
}
}
示例6: tearDown
import org.rosuda.REngine.Rserve.RConnection; //导入依赖的package包/类
@PreDestroy
public void tearDown() {
try {
if(LOGGER.isInfoEnabled()) {
LOGGER.info("Shuting down Rserve daemon....");
}
RConnection rConnection = rConnectionFactory.getConnection();
rConnection.shutdown();
rConnectionFactory.releaseConnection(rConnection);
if(LOGGER.isInfoEnabled()) {
LOGGER.info("Shutdown signal sent to Rserve daemon");
}
} catch(Exception e) {
LOGGER.error("Unexpected error shuting down RServe", e);
}
}
示例7: ksTest
import org.rosuda.REngine.Rserve.RConnection; //导入依赖的package包/类
@Test
public void ksTest() throws Exception{
RConnection rConnectionMock = mock(RConnection.class);
when(rConnectionMock.parseAndEval(anyString())).thenReturn(new REXPGenericVector(new RList(new REXP[]{new REXPDouble(new double[]{0.15})})));
when(rConnectionFactory.getConnection()).thenReturn(rConnectionMock);
REXPDouble demoVars = getDemoContinuousVars().get(0);
rServeEngineProviderService.ksTest(demoVars, demoVars);
verify(rConnectionMock, times(1)).assign(eq("x"), any(REXP.class));
verify(rConnectionMock, times(1)).assign(eq("y"), any(REXP.class));
ArgumentCaptor<String> rCommand = ArgumentCaptor.forClass(String.class);
verify(rConnectionMock, times(1)).parseAndEval(rCommand.capture());
assertThat(rCommand.getValue()).isEqualTo("ks.test(x, y)['p.value']");
}
示例8: removeFile
import org.rosuda.REngine.Rserve.RConnection; //导入依赖的package包/类
/**
* Remove a file on the RServer.
* @param filename File to remove
*/
public void removeFile(final String filename) throws REngineException {
// Test if the file exists
final RConnection c = getRConnection();
try {
REXP exists = c.eval("file.exists(\"" + filename + "\")");
if (exists.asInteger() == 1) {
c.voidEval("file.remove(\"" + filename + "\")");
}
} catch (RserveException | REXPMismatchException e) {
throw new REngineException(c, "RServe exception: " + e);
}
}
示例9: executeRCode
import org.rosuda.REngine.Rserve.RConnection; //导入依赖的package包/类
/**
* Execute a R code.
* @param source code to execute
* @throws REngineException if an error while executing the code
*/
public void executeRCode(final String source) throws REngineException {
if (source == null) {
return;
}
final RConnection c = getRConnection();
try {
// Execute the source
c.voidEval("source(\"" + source + "\")");
} catch (RserveException e) {
throw new REngineException(c, "RServe exception: " + e);
}
}
示例10: CellHTS2
import org.rosuda.REngine.Rserve.RConnection; //导入依赖的package包/类
public CellHTS2(ScreenResult screenResult,
String title,
String reportsPath,
String saveRObjectsPath) throws RserveException, REngineException,
REXPMismatchException {
this.screenResult = screenResult;
this.rConnection = new RConnection();
this.arrayDimensions = calculateArrayDimensions(screenResult);
this.title = title;
this.reportsPath = reportsPath;
if (!StringUtils.isEmpty(saveRObjectsPath)) {
this.saveRObjectsPath = saveRObjectsPath;
File file = new File(saveRObjectsPath);
if (file.exists()) {
this.saveRObjects = true;
}
else {
log.error(saveRObjectsPath +
"does not exist (cellHTS2.saveRObjects.directory system property); R objects will not be saved");
}
}
}
示例11: tt
import org.rosuda.REngine.Rserve.RConnection; //导入依赖的package包/类
@Test
@Ignore
public void tt () throws Exception {
SimpleDatasetBuilder s = new SimpleDatasetBuilder ();
s.setParserFactories (asList (new SuperCsvParserFactory ()));
s.setValueStoreBuilder (new MapBackedValueStoreBuilder ());
RConnection c = new RConnection ();
c.assign ("ds", new REXPString (mapper.writeValueAsString (s.build (new MockTsvInput ("mock", "id\tsa\tsb\tsc\n" +
"g1\t.1\t.2\t.3\n" +
"g2\t.4\t.5\t.6")))));
System.out.println (mapper.readValue (c.eval ("m <- NMF::nmf (jsonlite::fromJSON (ds), rank = 3);"
+
"w <- NMF::basis (m);"
+
"h <- NMF::coef (m);"
+
"jsonlite::toJSON (list (w = w, h = list (matrix = h)), auto_unbox = TRUE)")
.asString (),
Nmf.class));
}
示例12: RContainer
import org.rosuda.REngine.Rserve.RConnection; //导入依赖的package包/类
/**
* <p>
* The RContainer constructor opens a connection (an RConnection) to either
* local or remote RServe, and combines the object with the current Vaadin
* main window. Thus, the main window must have been set earlier with
* {@link com.vaadin.Application#setMainWindow(Window)} for the grahics to
* work. See {@link RContainer#RContainer(Application, String, int)} for
* accessing remote R Servers.
* </p>
*
* <p>
* Example:<br>
* {@code Window main = new Window("My Fabulous Analysis App");}<br>
* {@code setMainWindow(main);}<br>
* {@code RContainer R = new RContainer(main.getApplication());}
* </p>
*
* @param app
* Vaadin Application reference. Needed in the construction of
* StreamResource objects for R graphics.
*/
public RContainer() {
try {
rc = new RConnection();
rc.parseAndEval("library('Cairo')");
} catch (Exception e) {
if (verboseErrors) {
Notification.show("RVaadin: Could not connect to R.",
Notification.Type.ERROR_MESSAGE);
}
e.printStackTrace();
}
/*
* Random session identifier for this particular R connection (used to
* e.g. tell the browser not to cache the images)
*/
rand = new Random((new GregorianCalendar()).getTimeInMillis());
String chars = "abcdefghijklmnopqrstuvwxyz";
sessionID = getRandomString(rand, chars, 10);
}
示例13: request
import org.rosuda.REngine.Rserve.RConnection; //导入依赖的package包/类
/** sends a request with one string parameter attached
@param cmd command
@param par parameter - length and DT_STRING will be prepended
@return returned packet or <code>null</code> if something went wrong */
public RPacket request(int cmd, String par) {
try {
byte[] b=par.getBytes(RConnection.transferCharset);
int sl=b.length+1;
if ((sl&3)>0) sl=(sl&0xfffffc)+4; // make sure the length is divisible by 4
byte[] rq=new byte[sl+5];
int i;
for(i=0;i<b.length;i++)
rq[i+4]=b[i];
while (i<sl) { // pad with 0
rq[i+4]=0; i++;
};
setHdr(DT_STRING,sl,rq,0);
return request(cmd,rq);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
示例14: stop
import org.rosuda.REngine.Rserve.RConnection; //导入依赖的package包/类
public void stop() {
println("stopping R daemon... " + conf, Level.INFO);
if (!conf.isLocal()) {
throw new UnsupportedOperationException(
"Not authorized to stop a remote R daemon: "
+ conf.toString());
}
try {
RConnection s = conf.connect();
if (s == null || !s.isConnected()) {
println("R daemon already stoped.", Level.INFO);
return;
}
s.shutdown();
} catch (Exception ex) {
// ex.printStackTrace();
println(ex.getMessage(), Level.ERROR);
}
/*
* if (br != null) { try { br.close(); } catch (IOException ex) {
* ex.printStackTrace(); println(ex.getMessage()); } }
*/
// if (pw != null) {
// pw.close();
// }
// process.destroy();
println("R daemon stoped.", Level.INFO);
log = null;
}
示例15: isRserveRunning
import org.rosuda.REngine.Rserve.RConnection; //导入依赖的package包/类
/** check whether Rserve is currently running (on local machine and default port).
@return <code>true</code> if local Rserve instance is running, <code>false</code> otherwise
*/
public static boolean isRserveRunning() {
try {
RConnection c = new RConnection();
System.err.println("Rserve is running.");
c.close();
return true;
} catch (Exception e) {
System.err.println("First connect try failed with: " + e.getMessage());
}
return false;
}