rJava: using java/lang/Vector with a certain template class - r

I'm currently programming an R-script which uses a java .jar that makes use of the java/lang/Vector class, which in this case uses a class in a method that is not native. In java source code:
public static Vector<ClassName> methodname(String param)
I found nothing in the documentation of rJava on how to handle a template class like vector and what to write when using jcall or any other method.
I'm currently trying to do something like this:
v <- .jnew("java/util/Vector")
b <- .jcall(v, returnSig = "Ljava/util/Vector", method = "methodname",param)
but R obviously throws an exception:
method methodname with signature (Ljava/lang/String;)Ljava/util/Vector not found
How do I work the template class into this command? Or for that matter, how do I create a vector of a certain class in the first place? Is this possible?

rJava does not know java generics, there is no syntax that will create a Vector of a given type. You can only create Vectors of Objects.
Why are you sticking with the old .jcall api when you can use the J system, which lets you use java objects much more nicely:
> v <- new( J("java.util.Vector") )
> v$add( 1:10 )
[1] TRUE
> v$size()
[1] 1
# code completion
> v$
v$add( v$getClass() v$removeElement(
v$addAll( v$hashCode() v$removeElementAt(
v$addElement( v$indexOf( v$retainAll(
v$capacity() v$insertElementAt( v$set(
v$clear() v$isEmpty() v$setElementAt(
v$clone() v$iterator() v$setSize(
v$contains( v$lastElement() v$size()
v$containsAll( v$lastIndexOf( v$subList(
v$copyInto( v$listIterator( v$toArray(
v$elementAt( v$listIterator() v$toArray()
v$elements() v$notify() v$toString()
v$ensureCapacity( v$notifyAll() v$trimToSize()
v$equals( v$remove( v$wait(
v$firstElement() v$removeAll( v$wait()
v$get( v$removeAllElements()

Related

Trying to access R class methods and fields within Python using rpy2

I am using rpy2 to import a library from CRAN repository called "MatrixEQTL" to run in within Python using importr, here is my attempt:
import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
robjects.r('install.packages("MatrixEQTL")')
mtrql = importr('MatrixEQTL')
I am trying to access both class fields as well as class methods but I failed here is what the class looks like when printing into the python shell:
# to view class SlicedData of MatrixEQTL R package
print(mtrql.SlicedData)
Generator for class "SlicedData":
Class fields:
Name: dataEnv nSlices1 rowNameSlices
Class: environment numeric list
Name: columnNames fileDelimiter fileSkipColumns
Class: character character numeric
Name: fileSkipRows fileSliceSize fileOmitCharacters
Class: numeric numeric character
Class Methods:
"Clear", "show#envRefClass", "nSlices", "getRefClass", "export",
"initialize", "CombineInOneSlice", "callSuper", "initFields", "nCols",
"getClass", "RowStandardizeCentered", "import", "SaveFile", "RowReorder",
"setSlice", "getSlice", "RowReorderSimple", "CreateFromMatrix", "nRows",
"ResliceCombined", "LoadFile", "ColumnSubsample", "SetNanRowMean",
"setSliceRaw", "getSliceRaw", "copy", "RowMatrixMultiply", "usingMethods",
"GetAllRowNames", "RowRemoveZeroEps", "field", ".objectParent",
"IsCombined", "untrace", "trace", "Clone", "GetNRowsInSlice",
".objectPackage", "show", "FindRow"
Reference Superclasses:
"envRefClass"
I want to access for instance class field say fileDelimiter and also class Methods say LoadFile but I couldn't, here is also my attempt to access class method LoadFile and the error message that generated:
# If I try to run this without "()"
data = mtrql.SlicedData
load_my_file = data.LoadFile(file)
data = data.LoadFile(file)
AttributeError: 'DocumentedSTFunction' object has no attribute 'LoadFile'
# And that's my attempt for when adding "()" to the class name
data = mtrql.SlicedData
load_my_file = data.LoadFile(file)
data = data.LoadFile(file)
AttributeError: 'RS4' object has no attribute 'LoadFile'
I tried to look for a solution to this issue but I wasn't successful, please help me understand and solve this issue.
Thank you so much in advance.
mtrql.SlicedData is a "Generator", that is a constructor. In R that means a function (that will return an instance of the class), which is why mtrql.SlicedData is an R function with rpy2.
Consider the following example from the R documentation (https://rdrr.io/r/methods/Introduction.html):
import rpy2.robjects as ro
Pos = ro.r("""
setClass("Pos", slots = c(latitude = "numeric", longitude = "numeric",
altitude = "numeric"))
""")
With rpy2, the object Pos is an R function:
>>> type(Pos)
rpy2.robjects.functions.SignatureTranslatedFunction
However that function object has an S3 class in R (there are several OOP systems in R, 2 of them coexisting in standard R unfortunately).
>>> tuple(Pos.rclass)
('classGeneratorFunction',)
A specific print function is implemented for this S3 class, and it will use the attributes package and className for the object (the R function-that-is-in-fact-a-Generator) to display all the info about the clas you are seeing.
Since this is a constructor, to create an instance you can do:
pos = Pos()
or
pos = Pos(latitude=0, longitude=0, altitude=-10)
The instance will have instance attributes (and methods)
>>> tuple(pos.list_attrs())
('latitude', 'longitude', 'altitude', 'class')
>>> tuple(pos.do_slot('altitude'))
(-10,)
With your specific example, you probably want something like:
slidata = mtrql.SlicedData()
slidata.do_slot('LoadFile')(file)
The documentation can provide more information about R S4 classes in rpy2, and how to make wrapper classes in Python that map attributes and methods.
https://rpy2.github.io/doc/v3.3.x/html/robjects_oop.html#s4-objects

R dependend package seems not available in package

I can't figure out what I'm missing. Following Situation:
I wrote a R-Package lets call it "pkg_A"
It depends on "Rcpp" and I have a Module loaded and a class set up like :
Rcpp::loadModule("pkg_A_modul", what = "pkg_A_cppClass_A")
cppClass_A <- setRcppClass(
Class = "pkg_A_cppClass_A",
CppClass = "pkg_A_cppClass_A",
module = "pkg_A_modul",
fields = c(
remark = "character"
)
)
and a additional constructor
classA <- function(a,b){
# some stuff
tmpObj <- cppClass_A()
# some more stuff
return(tmpObj)
}
class(classA ) <- "classA "
The only Thing what I export to the NAMESPACE is the classA function/class.
That all works fine and I can build that package without any warnings and even can check it with "--as-cran" flag.
Now I want to build a second package on top of that package, lets call that "pkg_B" Therefore I list "pkg_A" in the DESCRIPTION Depends of "pkg_B"
as well as I load the class with importFrom(pkg_A, classA) in the NAMESPACE of "pkg_B".
Now I want to implement a class
classB <- setRefClass(
"classB",
contains = c("classA"),
fields = c( b = "numeric)
)
But when I now want to build "pkg_B" I get the error:
Error in getClass(what, where = where) : "classA" is not a defined
class
I also tried to use the "pkg_A_cppClass_A" instead or imprt the whole pkg_A or use pkg_A::classA. Nothing changed.
Hope the question is complete enough. If you missing some info let me know.
Thankful for any suggestions!

using matlab production server(MPS) and webfigure

I would like to know how to pass a plot from matlab to be displayed as a webfigure on a servlet page. Note that I'm using the MPS. Hence I'm not packaging the matlab code into java but just using a client proxy to the matlab function.
My eg matlab function:
function varargout = mymagicplot(in,displayPlot)
x = magic(in);
varargout{1} = x;
if (strcmp(displayPlot, 'Plot'))
varargout{2} = {plot(x)};
end
On the servlet side:
interface MatlabMagic {
public Object[] mymagicplot(int num_outargs, int size, String plotOption) throws IOException, MATLABException;
}
Question is how to code the display of the plot as a webfigure on the servlet page?
I tried a workaround by splitting my matlab code into two functions.
First function is used by the client proxy.
function m = mymagic(in)
m = magic(in);
end
Second function is packaged into java classes by the library compiler.
function returnfigure = mygetwebfiguremagicplot(in)
h = figure;
set(h, 'Visible', 'off');
plot(in);
returnfigure = webfigure(h);
close(h);
end
In this way, I can access the mymagic function .ctf in the MPS to return the results to the servlet and plot it as a webfigure using the java classes created from the second function matlab code.
This is just one possible workable solution that I can think of.

r reference classes - do they have static field members/variables?

I have been playing a little with R's R5 class system to see what it can and can't do. In that process I have stumbled upon what looks like static class field members (which does not appear to be in the documentation - but i could have missed it)
[2014 update]
Warning !!! : The following code does not work with R version >= 3.0
This post, its answers and particularly the comments provide useful insights and reminders about the R5 OO-system and the R language in general. However it is probably a bad idea to cultivate the idiom of using the environment of the R5 class instances directly.
[end 2014 update]
In the following code, the first field is the classic definition of an instance field variable. The second definition appears to create a static class field using an accessor method. I would like to know if this use is kosher (or is my code example simply coincidental). The third field use creates a quasi-private instant field variable using an accessor method.
assertClass <- function(x, className, R5check=FALSE) {
# simple utility function
stopifnot(class(x)[1] == className)
if(R5check) stopifnot(is(x, 'envRefClass'))
}
A <- setRefClass('A',
fields = list(
# 1. public, typed, instance field
myPublicInstanceVar = 'character',
# 2. this assignment appears static
# but if the field me.static.private
# was declared in the field list
# it would be a local instance var
myPrivateStaticVar = function(x) {
if (!missing(x)) {
assertClass(x, 'character')
me.static.private <<- x
}
me.static.private
},
# 3. quasi-private, typed, instance field
myPrivateInstanceVar = function(x) {
if (!missing(x)) {
assertClass(x, 'character')
.self$me.private <<- x
}
.self$me.private
}
),
methods = list(
initialize = function (c='default') {
myPublicInstanceVar <<- c
myPrivateStaticVar <<- c
myPrivateInstanceVar <<- c
}
)
)
# test instantiation
instance1.of.A <- A$new('first instance')
str(instance1.of.A)
instance2.of.A <- A$new('second instance')
str(instance1.of.A)
str(instance2.of.A)
instance3.of.A <- getRefClass('A')$new('third instance')
instance3.of.A$myPrivateStaticVar <- 'Third instance - changed'
print(instance1.of.A$myPrivateStaticVar)
print(instance2.of.A$myPrivateStaticVar)
print(instance3.of.A$myPrivateStaticVar)
str(instance1.of.A)
str(instance2.of.A)
str(instance3.of.A)
# but not really private ...
instance1.of.A$myPublicInstanceVar # works
instance1.of.A$me.static.private # DOES NOT WORK - where is this variable stored
instance1.of.A$me.private # works
# till death do us part
instance3.of.A <- NULL
gc()
str(instance1.of.A)
str(instance2.of.A)
str(instance3.of.A)
If you run this code - you can see that the second field variable appears to operate as a static class member. What is less clear to me is where the reference class keeps this field (hence my comment in the penultimate line above).
The short answer - based on Hadley's comments above - is no. R's reference classes do not have static variables.

Documentation of squared bracket `[` function

I have a function in R that looks somewhat like this:
setMethod('[', signature(x="stack"),definition=function(x,i,j,drop){
new('class', as(x, "SpatialPointsDataFrame")[i,]) })
I use it to get a single element out of a stacked object. For the package I'm building I need a .Rd file to document the function. I stored it as [.Rd but somehow the R CMD check does not see this. It returns:
Undocumented S4 methods: generic '[' and siglist 'MoveStack,ANY,ANY'
The [.Rd file starts with these lines:
\name{[}
\alias{[}
\alias{[,stack,ANY,ANY-method}
\docType{methods}
\title{Returns an object from a stack}
\description{Returning a single object}
\usage{
\S4method{\[}{stack,ANY,ANY}(x,i,y,drop)
}
Any idea how I make R CMD check aware of this file?
If you look at the source code of the sp package, for example SpatialPolygons-class.Rd, the Methods section:
\section{Methods}{
Methods defined with class "SpatialPolygons" in the signature:
\describe{
\item{[}{\code{signature(obj = "SpatialPolygons")}: select subset of (sets of) polygons; NAs are not permitted in the row index}
\item{plot}{\code{signature(x = "SpatialPolygons", y = "missing")}:
plot polygons in SpatialPolygons object}
\item{summary}{\code{signature(object = "SpatialPolygons")}: summarize object}
\item{rbind}{\code{signature(object = "SpatialPolygons")}: rbind-like method}
}
}
method for [ is defined.
Name and class of the file are
\name{SpatialPolygons-class}
\alias{[,SpatialPolygons-method}
If you look at the help page for ?SpatialPolygons you should see
> Methods
>
> Methods defined with class "SpatialPolygons" in the signature:
>
> [ signature(obj = "SpatialPolygons"): select subset of (sets of)
> polygons; NAs are not permitted in the row index
>
So I would venture a guess that if you specify a proper (ASCII named) file name, give it an alias as in the above example, you should be fine.

Resources