Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.rosuda.JRI.REXP;
- import org.rosuda.JRI.RMainLoopCallbacks;
- import org.rosuda.JRI.Rengine;
- /**
- * Wrapper for Robust PCA R method
- *
- * Documentation: http://cran.r-project.org/web/packages/rrcov/index.html
- *
- * In order to work in Windows, the next environmental variables have to be set:
- * PATH = %YOUR_PATH_TO_R%\R-3.0.2\library\rJava\jri\x64;%YOUR_PATH_TO_R%\R-3.0.2\bin\x64
- * R_DOC_DIR = %YOUR_PATH_TO_R%\R-3.0.2\doc
- * R_HOME = %YOUR_PATH_TO_R%\R-3.0.2
- * R_INCLUDE_DIR = %YOUR_PATH_TO_R%\R-3.0.2\include
- * R_SHARE_DIR = %YOUR_PATH_TO_R%\R-3.0.2\share
- *
- *
- *
- * Beware with Windows environmental variables extension: it's alphabetical!!
- * For example, you can't use %R_HOME% in PATH variable.
- * http://bit.ly/IK2EW2
- *
- * JRI library is provided by rJava package
- * install.packages('rJava', repos='http://cran.ma.imperial.ac.uk/')
- *
- * rrcov package has to be installed in the R library
- * install.packages('rrcov', repos='http://cran.ma.imperial.ac.uk/')
- *
- * @author Manuel Martin <draxus@gmail.com>
- *
- */
- public class RobustPCA {
- private Rengine re = null; // initialized in constructor or autowired
- private int NUMBER_OF_COMPONENTS;
- public RobustPCA(){
- NUMBER_OF_COMPONENTS = 0;
- }
- public RobustPCA(int components) throws Exception{
- if (components<0){
- throw new Exception(this, "The number of components has to be positive");
- }
- NUMBER_OF_COMPONENTS = components;
- }
- private void runREngine(){
- if (!Rengine.versionCheck()) {
- System.err.println("** Version mismatch - Java files don't match library version.");
- System.exit(1);
- }
- System.out.println("Creating Rengine");
- re = new Rengine(null, false, new TextConsole());
- System.out.println("Rengine created, waiting for R");
- if (!re.waitForR()) {
- System.out.println("Cannot load R");
- }
- }
- protected void finalize() throws Throwable{
- //close R engine
- if (re!=null){
- re.eval("q()");
- re.end();
- re = null;
- }
- }
- public double[][] process(double[][] input) throws Exception{
- // Assuming that input is a matrix of size nxp
- if(input.length < input[0].length){
- throw new Exception(this, "The number of instances must be greater than the number of attributes to perform Robust PCA");
- }
- if(re == null){
- runREngine();
- }
- else{ //restart REngine for re-training
- re.eval("q()");
- re.end();
- re = null;
- runREngine();
- }
- // Create the matrix in R (except the predicted variables)
- re.eval("m <- " + matrixToR(input));
- // Load library rrcov
- REXP loaded = re.eval("library(rrcov)",false);
- if(loaded==null){
- throw new Exception(this, "The library rrcov has not been found");
- }
- // Remove missing values
- re.eval("m <- na.omit(m)");
- // Robust PCA
- REXP pca = re.eval("pca <- PcaCov(m, k="+NUMBER_OF_COMPONENTS+")"); //don't need to store in Java because REngine is the same
- if(pca==null){
- throw new Exception(this, "There was an error computing PcaCov");
- }
- REXP x = re.eval("scores <- scale(m, center=pca@center, scale=FALSE) %*% pca@loadings");
- double newData[][] = x.asDoubleMatrix();
- // Clean workspace
- re.eval("rm(m)");
- return newData;
- }
- private String matrixToR(double[][] matrix){
- String matrixString = "";
- for(int i=0; i<matrix.length; i++){
- for(int j=0; j<matrix[i].length; j++){
- if (Double.isNaN((Double) matrix[i][j])){ //missing value
- matrixString += "NA,";
- }
- else{
- matrixString += String.valueOf(matrix.[i][j]) + ",";
- }
- }
- }
- matrixString = matrixString.substring(0, matrixString.length()-1); //remove the last comma
- // Matrix creation in R
- return "matrix(c("+matrixString+"), nrow="+matrix.length+", ncol="+matrix[0].length+", byrow=TRUE)";
- }
- }
- 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) {
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement