Assessing R packages in Python - python

I am using rpy2 to call R packages in Python and I am facing technical problems. Some functions in R packages have a dot "." in their names, so it is hard for Python to identify these functions. For example, there is a function called "Granger.conditional()" in the R package called "grangers". When I use rpy2 to call the function like this:
grangers = rpackages.importr('grangers')
res = grangers.Granger.conditional(trnsetmdl_i.iloc[:, i], trnsetmdl_i.iloc[:, j], trnsetmdl_i.iloc[:, k])
I am getting the following error message:
Traceback (most recent call last):
File "D:/CMAPSSRUL/TimeSeriesModelling/GrangerCausality/ConditionalGC.py", line 53, in <module>
res = grangers.Granger.conditional(trnsetmdl_i.iloc[:, i], trnsetmdl_i.iloc[:, j], trnsetmdl_i.iloc[:, k])
AttributeError: module 'grangers' has no attribute 'Granger'
Anyone has solutions to this problem?

The answer to the question is in the documentation:
https://rpy2.github.io/doc/v3.2.x/html/robjects_rpackages.html#importing-r-packages
Also, I see from your error message that you are using Windows. Note that rpy2 is not supported, and pre-built binaries you may have found are almost certainly several releases behind the current one.

Related

Why am I getting "module 'rpy2.robjects.conversion' has no attribute 'py2rpy'" error?

I'm trying to convert a pandas dataframe into an R dataframe using the guide here. The code I have so far is:
import pandas as pd
import rpy2.robjects as ro
from rpy2.robjects import pandas2ri
from rpy2.robjects.conversion import localconverter
pd_df = pd.DataFrame({'int_values': [1, 2, 3],
'str_values': ['abc', 'def', 'ghi']})
with localconverter(ro.default_converter + pandas2ri.converter):
r_from_pd_df = ro.conversion.py2rpy(pd_df)
However, this is giving me the following error:
Traceback (most recent call last):
File <my_file_ref>, line 13, in <module>
r_from_pd_df = ro.conversion.py2rpy(pd_df)
AttributeError: module 'rpy2.robjects.conversion' has no attribute 'py2rpy'
I have found this relevant question where the OP refers to function names being changed however doesn't explain what the changes are. I've tried looking at the module but I'm not quite advanced enough to be able to make sense of it.
The accepted answer refers to checking versions which I've done and I'm definitely using rpy2 v3.3.3 which is the same as the guide I'm following.
Has anyone encountered this error and found a solution?
The section of the rpy2 documentation you are pointing out is built by running the code example. This is means that the example did work with the corresponding version of rpy2.
I am not sure you are using that version of rpy2 at runtime? For example, add print(rpy2.__version__) to check that this is the case.
For what is worth, the latest release in the rpy2 3.3.x series is 3.3.6 and there is probably no good reason to stay with 3.3.3. Otherwise rpy2 3.4.0 was just released; if using R 4.0 or greater, or the latest release of the R packages dplyr or ggplot2 together with their rpy2 wrapper, I would recommend to use that release.
[PS: I just tried your example with rpy2-3.4.0 and it runs without error]

Python module Cupy function gives error when using cupy.einsum()

I am dealing with a problem with Cupy. I am currently using Cupy and it works great at a very satisfactory high speed. But I have a problem when I use cupy.einsum() method
I am using the same syntax with Numpy without any error. But when using Cupy it gives me an error. Here is the code section
import numpy as np
A = np.random.randn(2,3,10)
B = np.random.randn(3,4)
C = np.einsum('ijk,jl->ijl',A,B)
This works quite well and I get the result that I want consistently. However, when I write the same code with Cupy
import cupy as cp
A = cp.random.randn(2,3,10)
B = cp.random.randn(3,4)
C = cp.einsum('ijk,jl->ijl',A,B)
When I run this, A and B are calculated. But It gives me an error when calculating C. This is the error:
Traceback (most recent call last):
File "", line 4, in
C = cp.einsum('ijk,jl->ijl',A,B)
File
"C:\Users\Okan\anaconda3\lib\site-packages\cupy\linalg\einsum.py",
line 389, in einsum
result_dtype = cupy.result_type(*operands) if dtype is None else dtype
File "<array_function internals>", line 6, in result_type
TypeError: no implementation found for 'numpy.result_type' on types
that implement array_function: [<class 'cupy.core.core.ndarray'>]
I would be so glad if you have an idea or solution about this issue.
Thank you.
For those who are experiencing the same problem, open a new environment in Conda and install the python version above 3.9. After that, when you install cupy by
conda install cupy
it will directly install the latest version (v.7.8 or higher). The problem was based on the version of the cupy. After upgarding, the problem fixed.

Open3d Python, Type error using TriangleMesh.create_from_point_cloud_alpha_shape()

I am trying to use open3d to create an "alphahull" around a set of 3d points using TriangleMesh. However I get a TypeError.
import open3d as o3d
import numpy as np
xx =np.asarray([[10,21,18], [31,20,25], [36,20,24], [33,19,24], [22,25,13], [25,19,24], [22,26,10],[29,19,24]])
cloud = o3d.geometry.PointCloud()
cloud.points = o3d.utility.Vector3dVector(xx)
mesh = o3d.geometry.TriangleMesh.create_from_point_cloud_alpha_shape(pcd=cloud, alpha=10.0)
output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: create_from_point_cloud_alpha_shape(): incompatible function arguments. The following argument types are supported:
1. (pcd: open3d.open3d.geometry.PointCloud, alpha: float, tetra_mesh: open3d::geometry::TetraMesh, pt_map: List[int]) -> open3d.open3d.geometry.TriangleMesh
The error says the object I am passing the function is the wrong type. But when I check the type I get this:
>>print(type(cloud))
<class 'open3d.open3d.geometry.PointCloud'>
Please can someone help me with this error?
Note: A comment on this post Python open3D no attribute 'create_coordinate_frame' suggested it might be a problem with the installation and that a solution was to compile the library from source. So I compiled the library from source. After this ran
make install-pip-package. Though I am not sure it completed correctly because I couldn't import open3d in python yet; see output of installation: https://pastebin.com/sS2TZfTL
(I wasn't sure if that command was supposed to complete the installation, or if you were still required to run pip? After I ran python3 -m pip install Open3d I could import the library in python.)
Bug in bindings of current release (v0.9.0):
https://github.com/intel-isl/Open3D/issues/1621
Fix for master:
https://github.com/intel-isl/Open3D/pull/1624
Workaround:
tetra_mesh, pt_map = o3d.geometry.TetraMesh.create_from_point_cloud(pcd)
mesh = o3d.geometry.TriangleMesh.create_from_point_cloud_alpha_shape(pcd, alpha, tetra_mesh, pt_map)

Reticulate not sharing state between R/Python cells or Python/Python cells in RMarkdown

I'm trying to get Reticulate working in RMarkdown, per the setup instructions. However, I am unable to share state between separate Python cells or Python and R cells, as the docs indicate I should be able to. Here is my setup and output:
Cell 1 (Setup):
{r}
library(reticulate)
path_to_python <- "/Users/User/anaconda3/bin/python"
use_python(path_to_python)
knitr::knit_engines$set(python = reticulate::eng_python)
py_available(initialize = TRUE)
Output:
[1] TRUE
Cell 2 (set variable in Python):
{python}
x = 2
Cell 3 (attempt to access Python variable in R):
{r}
py$x
Output:
Error in py_get_attr_impl(x, name, silent) : AttributeError: module '__main__' has no attribute 'x'
Cell 4 (set variable in R):
{r}
x <- 2
Cell 5 (attempt to access R variable in Python):
{python}
r.x
Output:
Traceback (most recent call last):
File "/var/folders/2b/dgy6vs4n3lbfy2xqwc3gqq9m0000gn/T/RtmpTqIR6P/chunk-code-108b44104ec28.txt", line 1, in <module> r.x NameError: name 'r' is not defined
Cell 6 (attempt to access previous Python variable in subsequent Python cell):
{python}
x
Output:
Traceback (most recent call last):
File "/var/folders/2b/dgy6vs4n3lbfy2xqwc3gqq9m0000gn/T/RtmpTqIR6P/chunk-code-108b44520d158.txt", line 1, in <module> x NameError: name 'x' is not defined
Any help or advice would be much-appreciated! I have already attempted pointing reticulate at different Conda environments and Python installations with no luck. Thanks!
I think I've figured this out. I misunderstood the reticulate documentation, taking it to mean I could share state between Python cells interactively in RStudio. After perusing the open issues on Github, it appears RStudio integration is still being worked on. When employing knitr directly to knit a document, I get the expected behavior with shared state between cells.
This is fixed in current RStudio e.g. 1.2.1114. But if you are like me stuck with RStudio Server Pro 1.1.456 a workaround is to use reticulate::repl_python() to run python chunks by copy pasting them into a python console. You can close and open the console again if you need to run an R chunk in between - the state will be maintained. When you are done hacking around you can knit the whole file without problems.

TypeError with PAMIE

I am getting a TypeError with a very simple script on PAMIE, and I'm not sure what I can do. I had found an answer suggesting that the library, pywin32 might not have set a self argument for this particular method (getElementsByTagName) but I don't know for sure, as I don't know where to find the definition of it.
from PAM30 import PAMIE
ie = PAMIE()
ie.navigate('google.com')
ie.getButtons()
ie.quit()
print 'done'
The error is:
Traceback (most recent call last):
File "c:\pamie1.py", line 1, in <module>
from PAM30 import PAMIE
File "C:\Python27\Lib\site-packages\PAM30.py", line 678, in getButtons
return self.getElementsList("input", filter)
File "C:\Python27\Lib\site-packages\PAM30.py", line 939, in getElementsList
elements = self._ie.Document.getElementsByTagName(tag)
TypeError: getElementsByTagName() takes exactly 1 argument (2 given)
Here's the offending line in PAM30
elements = self._ie.Document.getElementsByTagName(tag)
where _ie_ is
self._ie = win32com.client.dynamic.Dispatch('InternetExplorer.Application')
I'm using Windows 7x64 with Python2.7 32bit
sourceforge bug link
"Workaround" seems to be enable Compatibility View (Tools > Compatibility
View settings > Display all websites in Compatibility View).
it is a bug of IE.
Work around - Change in PAMIE30
elements = self._ie.Document.getElementsByTagName(tag)
to
elements = self._ie.Document.body.all.tags(tag)
This will work without the need to use Compatibility View!
Modify this line:
elements = self._ie.Document.getElementsByTagName(tag)
to
elements = self._ie.Document.Body.getElementsByTagName(tag)

Categories

Resources