Reputation: 383
I would like to write a Python wrapper around the R library Rdtq (https://github.com/cran/Rdtq). That library (or rather, the class instance) takes as main inputs two functions: the drift f(x) and diffusion g(x). For instance,
my_drift = function(x) { -x }
my_diff = function(x) { rep(1,length(x)) }
Since I am writing a wrapper around the Rdtq class, I would like to pass the drift and diffusion function directly from Python, ideally via lambda function
my_python_drift(x) = lambda x: -x
my_python_diff(x) = lambda x: np.ones(len(x))
and so on. So more generally, my question is: Can I pass a Python lambda (or global) function as parameter to R, via rpy2?
Upvotes: 0
Views: 544
Reputation: 107707
Consider using rpy2's SignatureTranslatedAnonymousPackage (STAP) to import arbitrary R code as available package in Python environment. To demonstrate, below translates the Rdtq github written in R to Python using rpy2
:
R
# Loading required package: Rdtq
require(Rdtq)
# Assigning drift and diff functions
mydrift = function(x) { -x }
mydiff = function(x) { rep(1,length(x)) }
# Running rdtq()
test = rdtq(h=0.1, k=0.01, bigm=250, init=0, fT=1,
drift=mydrift, diffusion=mydiff, method="sparse")
# Plotting output
plot(test$xvec, test$pdf, type='l')
Python
from rpy2 import robjects
from rpy2.robjects.packages import STAP
from rpy2.robjects.packages import importr
# Loading required package: Rdtq
Rdtq = importr('Rdtq')
fct_string = """
my_drift <- function(x) { -x }
my_diff <- function(x) { rep(1,length(x)) }
"""
# Creating package with above drift and diff methods
my_fcts = STAP(fct_string, "my_fcts")
# Running rdtq() --notice per Python's model: all methods are period qualified
test = Rdtq.rdtq(h=0.1, k=0.01, bigm=250, init=0, fT=1,
drift=my_fcts.my_drift(), diffusion=my_fcts.my_diff(), method="sparse")
# Load plot function
plot = robjects.r.plot
# Plotting by name index
plot(test[test.names.index('xvec')], test[test.names.index('pdf')], type='l')
Upvotes: 1