Calling R writeRaster from Python with rpy2 - python

I am using an R package within my Python code to import, process and save a GeoTIFF raster. The importing and processing works just fine, but I struggle to save the raster file again. This is a simplified version of the code I'm running:
import rpy2.rinterface as ri
import rpy2.robjects as rob
import rpy2.robjects.packages as rpackages
raster = rpackages.importr('raster')
r_raster = raster.raster(geotiff_input_path)
# r_raster = process_raster(r_raster)
raster.writeRaster(r_raster, geotiff_output_path, overwrite=True)
However, the code fails with AttributeError: module 'raster' has no attribute 'writeRaster'.
I seem to misunderstand how to call writeRaster properly.

Related

How to use rpy2 (V3.4.5) with R's tidyr nest()?

My attempt to use rpy2 in a Jupyter (iPython) notebook fails at the point where I wish to use tidyr::nest() to make a dataframe that has some elements which are a series. (This cannot be avoided, it is necessary for the next step of the analysis.)
After trying many things (including advice from the package home I've managed to get most of the way to the end, failing to understand rpy2 with tidyr::nest at the last step. (Some of the following example may be superfluous.)
How can I fix this?
% Import packages
from rpy2 import robjects
from rpy2.robjects import Formula, Environment
from rpy2.robjects.vectors import IntVector, FloatVector
from rpy2.robjects.lib import grid
from rpy2.robjects.packages import importr, data
from rpy2.rinterface_lib.embedded import RRuntimeError
import warnings
base = importr('base')
datasets = importr('datasets')
from functools import partial
import rpy2.robjects.lib.tidyr as tidyr
from collections import OrderedDict
from rpy2.robjects.vectors import (StrVector,
IntVector)
from rpy2.robjects.lib.tidyr import DataFrame
from rpy2.robjects import rl
tidyr = importr('tidyr')
dplyr = importr('dplyr')
% Obtain the R dataset "iris"
iris = data(datasets).fetch('iris')['iris']
% Use only two columns necessary for the "tidyr::nest" trial
dataf = (
DataFrame(iris)
.select(base.c(1,5))
)
print(dataf.head())
% Failure occurs below
irisNested = tidyr.nest(dataf, data=rl('Sepal.Length'))
EDIT: This isn't a question anymore, as it turns out my original effort was correct. A fragment of another attempt to solve the problem caused it to fail. However, I asked the question as I didn't find the various sources of help available provided a clear way to address my issue, I felt I made a lucky educated guess.
import rpy2.robjects as ro
from rpy2.robjects import pandas2ri
pandas2ri.activate()
Removing this solves the problem.

Rpy2: calling to function conaining dots

I'm tring to run a R function in Pyton via Jupyter Notebook.
the problem is, that my function name (from mice lib) - containing dot.
the name of the function is md.pattern, and this is the code that I'm tring to run:
from rpy2.robjects.packages import importr
mice = importr('mice')
mice.md.pattern(train)
and this is the error that I get:
AttributeError: module 'mice' has no attribute 'md'
I also tried to run:
from rpy2.robjects.packages import importr
mice = importr('mice')
pattern = robjects.r("md.pattern")
mice.pattern(train)
and get the same error.
Beside the suggested answer in the comments, the doc suggests that the following should work:
mice.md_pattern(train)
https://rpy2.github.io/doc/v3.3.x/html/introduction.html#importing-packages

Syntax for rpy2 base.with function

I'm trying to figure out rpy2 for plotting some graphs. I'd like to be able to use the with function that's part of R's base like it's used it the following R code:
with(res, plot(log2FoldChange, -log10(pvalue), pch=20, main="Volcano plot", xlim=c(-2.5,2)))
with(subset(res, padj<.05 ), points(log2FoldChange, -log10(pvalue), pch=20, col="red"))
Where res is a dataframe and log2FoldChange and pvalue are columns from that dataframe.
When I import the base package using rpy2's importr I can see that 'with' is in the object by doing:
from rpy2.robjects.packages import importr
base = importr('base')
dir(base)
However, I can't seem to figure out the correct syntax:
from rpy2.robjects.packages import importr
from rpy2 import robjects
base = importr('base')
base.with(res, robjects.r.plot(log2FoldChange, padj))
File "<stdin>", line 1
base.with(res, robjects.r.plot(log2FoldChange, padj))
^
SyntaxError: invalid syntax
Unfortunately, searching for something like 'base.with' has proven intractable. My question: what is the syntax for using 'base.with' in rpy2 python code?
Alternatively, while using 'with' is the most R forward approach to doing this, perhaps there's a more rpy2 friendly approach to this same problem that I'm unaware of.
Python might be getting a conflict with its own with() command which requires a space right after it. This is the challenge of interfacing with another language.
Try running the command natively in R syntax wrapped around the robjects function. Below I pass Python objects into R's global environment scope.
import rpy2.robjects as ro
ro.globalenv['res'] = res_frompy
ro.globalenv['log2FoldChang'] = log2FoldChang_frompy
ro.globalenv['padj'] = padj_frompy
ro.r('with(res, plot(log2FoldChange, padj))')

numpy2ri conversion problem with rpy2 2.2.2

I am using rpy2-2.2.2 with the new free Enthought python distribution that includes numpy 1.6.0 and python 2.7.2. I easy_installed rpy2 which resulted in v. 2.2.2 being installed and all tests were successful.
The problem I'm having is with code I wrote that worked fine with rpy2 2.1.8 and python 2.6. The issue is in converting from numpy to R for arrays.
Here is a snippet of the relevant code:
import rpy2
import rpy2.rinterface as rinterface
import rpy2.robjects as rob
import rpy2.rlike.container as rlc
import numpy as np
import rpy2.robjects.numpy2ri
r = rob.r
...
HGr = rob.conversion.py2ri(HG_reg)
RHSr = rob.conversion.py2ri(RHS)
#
CalData = rlc.TaggedList([HGr,RHSr],tags=('hg','rhs'))
CalData = rob.DataFrame(CalData)
r('''library(pls)''')
#rob.globalEnv["HGr"] = HGr
#rob.globalEnv["RHSr"] = RHSr
rob.globalenv["CalData"] = CalData
# perform the PLS regression
if wetlflag:
HGresults = r.plsr(r("hg ~ rhs.1 + rhs.2 + rhs.3 + rhs.4"),data=CalData,validation="LOO")
I will gladly admit it's not the most elegant way to do things, but it worked before and now when I need to provide results all is broken (!). The error I get is the following:
Traceback (most recent call last):
File "Mercury_PLS_WL_DF.py", line 224, in <module>
HGr = rob.conversion.py2ri(HG_reg)
File "/Library/Frameworks/Python.framework/Versions/7.1/lib/python2.7/site-packages/rpy2-2.2.2dev_20110726-py2.7-macosx-10.5-i386.egg/rpy2/robjects/__init__.py", line 134, in default_py2ri
raise(ValueError("Nothing can be done for the type %s at the moment." %(type(o))))
ValueError: Nothing can be done for the type <type 'numpy.ndarray'> at the moment.
I found the discussion here and got the impression that numpy arrays are now automatically converted to R arrays, but commenting out the rob.conversion.py2ri(HG_reg) statements and using the numpy arrays directly also seems to fail. Am I missing something obvious? Why would this break between 2.1.8 and 2.2.2?
From http://rpy.sourceforge.net/rpy2/doc-2.2/html/numpy.html#from-numpy-to-rpy2:
Warning
In earlier versions of rpy2, the import was all that was needed to have the conversion. A side-effect when importing a module can lead to problems, and there is now an extra step to make the conversion active: call the function rpy2.robjects.activate().
So put rpy2.robjects.activate() after the import and you should be fine.

Converting python objects for rpy2

The following code is supposed to create a heatmap in rpy2
import numpy as np
from rpy2.robjects import r
data = np.random.random((10,10))
r.heatmap(data)
However, it results in the following error
Traceback (most recent call last):
File "z.py", line 8, in <module>
labRow=rowNames, labCol=colNames)
File "C:\Python25\lib\site-packages\rpy2\robjects\__init__.py", line 418, in __call__
new_args = [conversion.py2ri(a) for a in args]
File "C:\Python25\lib\site-packages\rpy2\robjects\__init__.py", line 93, in default_py2ri
raise(ValueError("Nothing can be done for the type %s at the moment." %(type(o))))
ValueError: Nothing can be done for the type <type 'numpy.ndarray'> at the moment.
From the documentation I learn that r.heatmap expects "a numeric matrix". How do I convert np.array to the required data type?
You need to add
import rpy2.robjects.numpy2ri
rpy2.robjects.numpy2ri.activate()
See more in rpy2 documentation numpy section (here for the older 2.x version)
Prior to 2.2.x the import alone was sufficient.
That import alone is sufficient to
switch an automatic conversion of
numpy objects into rpy2 objects.
Why make this an optional import,
while it could have been included in
the function py2ri() (as done in the
original patch submitted for that
function) ?
Although both are valid and reasonable
options, the design decision was taken
in order to decouple rpy2 from numpy
the most, and do not assume that
having numpy installed automatically
meant that a programmer wanted to use
it.
For rpy2 2.2.4 I had to add:
import rpy2.robjects.numpy2ri
rpy2.robjects.numpy2ri.activate()
For me (2.2.1) the following also worked (as documented on http://rpy.sourceforge.net/rpy2/doc-2.2/html/numpy.html):
import rpy2.robjects as ro
from rpy2.robjects.numpy2ri import numpy2ri
ro.conversion.py2ri = numpy2ri

Categories