moving a sparse matrix from R to Java

I have a very big sparse matrix that I want to send to Java function. I wrote a java code to accomplish that but it is slow so I'm searching for a better solution. I sent from R 3 arrays as follows

TMPmat <- as(mySpMat, "TsparseMatrix")
ia=TMPmat@i
ja=TMPmat@j
x=TMPmat@x
# order by row
ro=order(ia)
myfun(.jarray(ia[ro],dispatch=T),.jarray(ja[ro],dispatch=T), .jarray(x[ro],dispatch=T)

In Java side I'm building ArrayList of sparse vectors the code looks like:

    int[] ci=new int[nc];
    double[] vals=new double[nc];
    for(int i=0; i < ia.length && ro < nc; ro++){
        int nv=0;

        while(i < ia.length && ro == ia[i]){
            ci[nv]=ja[i];
            vals[nv]=x[i];
            nv++;
            i++;
        }

        if(nv==0){// add empty row
            newList.add(Vectors.sparse(nc,new int[]{0},new double[] {0.0}));
            continue;
        }
        int[] ciL=Arrays.copyOf(ci, nv);
        double[] vaL=Arrays.copyOf(vals, nv);
        newList.add(Vectors.sparse(nc,ciL,vaL));
    }

I need to send from R an int[][] containing the indices of each row and double[][] containing the actual values of the nonzero elements.

Upvotes: 1

Views: 85

Answers (1)

A much faster solution but I think not yet the optimal: The R code looks like:

A = Matrix::sparseMatrix(i=c(1,1,2,3,4,5),j=c(1,2,1,1,2,1),
             x=c(0.5,0.5,1,1,1,1),dims=c(5, 2))
ia=A@i
p=A@p
x=A@x
myfun(.jarray(ia,dispatch=T),.jarray(p,dispatch=T),.jarray(x,dispatch=T), 
  nr=nrow(A))

The Java code:

int[] ci=new int[nr];
double[] va=new double[nr];
for(int r=0;r < nr;r++) {
    System.arraycopy(ia,p[r],ci,0,p[r+1]-p[r]);
    System.arraycopy(x,p[r],va,0,p[r+1]-p[r]);
    int[] ciL=Arrays.copyOf(ci,p[r+1]-p[r]);
    double[] vaL=Arrays.copyOf(va,p[r+1]-p[r]);

    newList.add(Vectors.sparse(nr,ciL,vaL));
}

Upvotes: 1

Related Questions