package businesslogic;
import java.io.*;
import java.awt.Frame;
import java.awt.FileDialog;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Properties;
import org.rosuda.JRI.Rengine;
import org.rosuda.JRI.REXP;
import org.rosuda.JRI.RList;
import org.rosuda.JRI.RVector;
import org.rosuda.JRI.RMainLoopCallbacks;
import com.sun.tools.doclets.internal.toolkit.util.Group;
import java.lang.Math;
import javax.naming.InitialContext;
class TextConsole implements RMainLoopCallbacks
{
public void rWriteConsole(Rengine re, String text, int oType) {
System.out.print(text);
}
public void rBusy(Rengine re, int which) {
System.out.println("rBusy("+which+")");
}
public String rReadConsole(Rengine re, String prompt, int addToHistory) {
System.out.print(prompt);
try {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s=br.readLine();
return (s==null||s.length()==0)?s:s+"\n";
} catch (Exception e) {
System.out.println("jriReadConsole exception: "+e.getMessage());
}
return null;
}
public void rShowMessage(Rengine re, String message) {
System.out.println("rShowMessage \""+message+"\"");
}
public String rChooseFile(Rengine re, int newFile) {
FileDialog fd = new FileDialog(new Frame(), (newFile==0)?"Select a file":"Select a new file", (newFile==0)?FileDialog.LOAD:FileDialog.SAVE);
fd.show();
String res=null;
if (fd.getDirectory()!=null) res=fd.getDirectory();
if (fd.getFile()!=null) res=(res==null)?fd.getFile():(res+fd.getFile());
return res;
}
public void rFlushConsole (Rengine re) {
}
public void rLoadHistory (Rengine re, String filename) {
}
public void rSaveHistory (Rengine re, String filename) {
}
}
public class RInterface {
private static String[] m_args = {"--no-save","--no-restore-data"};
private static Rengine m_re = null;
private static boolean m_mainloop = true;
private final static DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
public RInterface()
{
try {
initiateRengine();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public RInterface(boolean dummy)
{
try {
initiateRengineforGraphprinting();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Rengine initiateRengineforGraphprinting() throws Exception
{
if(m_re == null)
{
// Properties prop = System.getProperties();
//
// if(prop.contains("R_DOC_DIR") == false)
// {
// prop.put("R_DOC_DIR", "/Library/Frameworks/R.framework/Resources/doc");
// prop.put("R_HOME", "/Library/Frameworks/R.framework/Resources");
// prop.put("R_INCLUDE_DIR", "/Library/Frameworks/R.framework/Resources/include");
// prop.put("R_SHARE_DIR", "/Library/Frameworks/R.framework/Resources/share");
// System.setProperties(prop);
// prop = System.getProperties();
// }
// just making sure we have the right version of everything
if (!Rengine.versionCheck()) {
System.err.println("** Version mismatch - Java files don't match library version.");
throw new Exception("** Version mismatch - Java files don't match library version.");
}
System.out.println("Creating Rengine (with arguments)");
// 1) we pass the arguments from the command line
// 2) we won't use the main loop at first, we'll start it later
// (that's the "false" as second argument)
// 3) the callbacks are implemented by the TextConsole class above
m_re = new Rengine(null, false, new TextConsole());
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 (!m_re.waitForR()) {
System.out.println("Cannot load R");
throw new Exception ("Cannot load R");
}
}
m_re.eval("library(igraph)");
m_re.eval("source(\"repl_ids.r\")");
return m_re;
}
public static Rengine initiateRengine() throws Exception
{
if(m_re == null)
{
// Properties prop = System.getProperties();
//
// if(prop.contains("R_DOC_DIR") == false)
// {
// prop.put("R_DOC_DIR", "/Library/Frameworks/R.framework/Resources/doc");
// prop.put("R_HOME", "/Library/Frameworks/R.framework/Resources");
// prop.put("R_INCLUDE_DIR", "/Library/Frameworks/R.framework/Resources/include");
// prop.put("R_SHARE_DIR", "/Library/Frameworks/R.framework/Resources/share");
// System.setProperties(prop);
// prop = System.getProperties();
// }
// just making sure we have the right version of everything
if (!Rengine.versionCheck()) {
System.err.println("** Version mismatch - Java files don't match library version.");
throw new Exception("** Version mismatch - Java files don't match library version.");
}
System.out.println("Creating Rengine (with arguments)");
// 1) we pass the arguments from the command line
// 2) we won't use the main loop at first, we'll start it later
// (that's the "false" as second argument)
// 3) the callbacks are implemented by the TextConsole class above
m_re = new Rengine(m_args, false, new TextConsole());
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 (!m_re.waitForR()) {
System.out.println("Cannot load R");
throw new Exception ("Cannot load R");
}
// m_re.eval("library(igraph)");
m_re.eval("library(statnet)");
}
return m_re;
}
public static void closeRengine() throws Exception
{
if(m_re != null)
{
if (m_mainloop == true) {
// so far we used R as a computational slave without REPL
// now we start the loop, so the user can use the console
System.out.println("Now the console is yours ... have fun");
m_re.startMainLoop();
} else {
//m_re.eval("quit(save=\"no\")");
m_re.eval("rm(xs=ls()");
m_re.end();
m_re.waitForR();
System.out.println("end");
}
}
}
// public boolean pushValues(EdgeListVectors i_edgelistvector)
// {
// try {
// initiateRengine();
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// return false;
// }
//
// m_re.eval("library(statnet)");
//
// m_re.assign("a", i_edgelistvector.getM_source());
// m_re.assign("b", i_edgelistvector.getM_target());
// m_re.assign("c", i_edgelistvector.getM_kind());
// m_re.eval("mymatrix <- matrix(c(a,b), " + String.valueOf(i_edgelistvector.getM_source().length) + ")");
// m_re.eval("mynetwork <- network(mymatrix, directed = FALSE, matrix.type = \"edgelist\")");
//
// return true;
// }
public Hashtable<String, double[]> calculateMeasures(EdgeListVectors i_edgelistvector)
{
Hashtable <String,double[]>tmp_res = new Hashtable<String,double[]>();
try{
double[] tmpdouble = new double[]{0.0};
double[] tmpdoubleactor = new double[i_edgelistvector.getM_numberofelements()];
initiateRengine();
if(i_edgelistvector.getM_source().length == 0)
{
tmp_res.put("degree", tmpdouble);
tmp_res.put("closeness", tmpdouble);
tmp_res.put("betweenness", tmpdouble);
}
else
{
m_re.assign("a", i_edgelistvector.getM_source());
m_re.assign("b", i_edgelistvector.getM_target());
m_re.assign("c", i_edgelistvector.getM_kind());
m_re.eval("mymatrix <- matrix(c(a,b), " + String.valueOf(i_edgelistvector.getM_source().length) + ")");
m_re.eval("mynetwork <- network(mymatrix, directed = FALSE, matrix.type = \"edgelist\")");
tmpdouble[0] = m_re.eval("centralization(mynetwork, degree, mode=\"graph\")", true).asDouble();
tmp_res.put("degree", tmpdouble);
tmpdouble[0] = m_re.eval("centralization(mynetwork, closeness, mode=\"graph\")", true).asDouble();
tmp_res.put("closeness", tmpdouble);
tmpdouble[0] = m_re.eval("centralization(mynetwork, betweenness, mode=\"graph\")", true).asDouble();
tmp_res.put("betweenness", tmpdouble);
tmpdoubleactor = m_re.eval("degree(mynetwork,gmode=\"graph\",cmode=\"freeman\", rescale=TRUE)").asDoubleArray();
tmp_res.put("actordegree", tmpdoubleactor);
tmpdoubleactor = m_re.eval("closeness(mynetwork,gmode=\"graph\",cmode=\"undirected\", rescale=TRUE)").asDoubleArray();
tmp_res.put("actorcloseness", tmpdoubleactor);
tmpdoubleactor = m_re.eval("betweenness(mynetwork,gmode=\"graph\",cmode=\"undirected\", rescale=TRUE)").asDoubleArray();
tmp_res.put("actorbetweenness", tmpdoubleactor);
int xy = 0;
//m_re.startMainLoop();
}
} catch (Exception e){
System.out.print("EX: " + e);
e.printStackTrace();
return null;
}
return tmp_res;
}
public void keyActorPlot(CentralityEntity l_ce) throws Exception
{
try{
EdgeListVectors l_edgelistvector = l_ce.getEdgelistVectors();
Hashtable<Double, Double> l_mappingtable = l_ce.getM_mappingtable();
Iterator<Double> l_mapping_it = l_mappingtable.keySet().iterator();
double[] l_old_id = new double[l_mappingtable.size()], l_new_id = new double[l_mappingtable.size()];
String[] l_color_coredeveloper = new String[l_mappingtable.size()];
double [] tmp_ids = new double[l_mappingtable.size()];
int i = 0, j = 0;
while (l_mapping_it.hasNext())
{
l_old_id[i] = l_mapping_it.next();
l_new_id[i] = l_mappingtable.get(l_old_id[i]);
i++;
}
if(l_edgelistvector.getM_source().length == 0)
{
throw new Exception("No data for generating graph available");
}
else
{
double[] a = l_edgelistvector.getM_source(), b = l_edgelistvector.getM_target(),x = new double[2*a.length];
for(i = 0, j = 0; j < l_edgelistvector.getM_source().length; i+=2, j++)
{
x[i] = a[j]-1;
x[i+1] = b[j]-1;
}
m_re.assign("old_id", l_old_id);
m_re.assign("new_id", l_new_id);
m_re.assign("a", x);
m_re.eval("mygraph <- graph(a, directed = FALSE)");
m_re.eval("cent<-data.frame(bet=betweenness(mygraph),eig=evcent(mygraph)$vector)");
m_re.eval("res<-lm(eig~bet,data=cent)$residuals");
m_re.eval("cent<-transform(cent,res=res)");
m_re.eval("l<-layout.fruchterman.reingold(mygraph,niter = 500)");
m_re.eval("V(mygraph)$size<-abs(res)*10");
m_re.eval("nodes<-as.vector(V(mygraph)+1)");
m_re.eval("nodes <- repl_ids(nodes,old_id, new_id)");
tmp_ids = m_re.eval("nodes").asDoubleArray();
for(int y=0; y < l_mappingtable.size(); y++)
{
if(CentralityEntity.m_coredeveloper.contains((long)tmp_ids[y]) == true)
{
l_color_coredeveloper[y]="red";
}
else
{
l_color_coredeveloper[y]="blue";
}
}
m_re.assign("new_color",l_color_coredeveloper);
//m_re.eval("nodes[which(abs(res)<.35)]<-NA");
m_re.eval("plot(mygraph, layout = l, vertex.label = nodes, vertex.label.dist=0.25, vertex.label.color=new_color, edge.width=1, main=\"GroupID: "
+ l_ce.getM_group_id() + "\", sub=\"Start: " + df.format(l_ce.getM_begin().toDate()) + " End: " + df.format(l_ce.getM_end().toDate()) + "\")");
//m_re.startMainLoop();
}
} catch (Exception e){
System.out.print("EX: " + e);
e.printStackTrace();
}
}
public static void calculateBetweennes(EdgeListVectors i_edgelistvector)
{
/* High-level API - do not use RNI methods unless there is no other way
to accomplish what you want */
try {
initiateRengine();
REXP x;
m_re.eval("library(statnet)");
m_re.eval("library(igraph)");
// push a boolean array
m_re.assign("a", i_edgelistvector.getM_source());
m_re.assign("b", i_edgelistvector.getM_target());
m_re.assign("c", i_edgelistvector.getM_kind());
m_re.eval("mymatrix <- matrix(c(a,b), " + String.valueOf(i_edgelistvector.getM_source().length) + ")", false);
m_re.eval("mynetwork <- network(mymatrix, directed = FALSE, matrix.type = \"edgelist\")", false);
m_re.eval("set.edge.attribute(mynetwork, \"kind\", c(c), 1:"+ String.valueOf(i_edgelistvector.getM_source().length) +")");
// re.eval("plot(mynetwork,displayisolates = TRUE, edge.col = \"kind\", vertex.cex = 0.7)");
m_re.eval("plot(mynetwork,displayisolates = TRUE, vertex.cex = 0.7)");
closeRengine();
} catch (Exception e) {
System.out.println("EX:"+e);
e.printStackTrace();
}
}
public static void main(String[] args) {
double s[] = {4,5,4,4};
double t[] = {2,2,3,5};
double k[] = {1,1,1,1};
EdgeListVectors bla = new EdgeListVectors(s,t,k);
calculateBetweennes(bla);
m_re = null;
try {
initiateRengine();
m_re.assign("s", s);
m_re.eval("s");
m_re.startMainLoop();
closeRengine();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}