A new blog on various actuarial stuffs...

The aim of this blog is sharing information of interest in the actuarial world. We consider informative contents as well as implementation tools in financial, life and pension actuarial matters.

Friday, 31 December 2010

Python - R interop : RPy2 2.2 offers more powerful interactions capabilities


Among the new features in the upcoming version 2.2.0, there is the possibility to write in Python the functions to be passed to higher-order R functions. In other words, it is becoming possible to write a Python function and expose it to R in such a way that the embedded R engine can call it.
As an example, let's consider the R function optim() that looks for optimal parameters for a given cost function. The cost function should be passed in the call to optim() as it will be repeatedly called as the parameter space is explored, and it is now possible to write that cost function in Python, as the code below demonstrates it.

from rpy2.robjects.vectors import FloatVector
from rpy2.robjects.packages import importr
import rpy2.rinterface as ri
stats = importr('stats')

# Rosenbrock Banana function as a cost function
# (as in the R man page for optim())
def cost_f(x):
    x1 = x[0]
    x2 = x[1]
    return 100 * (x2 - x1 * x1)**2 + (1 - x1)**2

# wrap the function f so it can be exposed to R
cost_fr = ri.rternalize(cost_f)

# starting parameters
start_params = FloatVector((-1.2, 1))

# call R's optim()
res = stats.optim(start_params, cost_fr)
The example is working verbatim with today's snapshot of the code repository (branch version_2.2.x), although few modifications might be needed in the future. Although this is development code and version 2.2.0 is scheduled to be released some time next year, the documentation already outlines this feature

No comments:

Post a Comment

Note: only a member of this blog may post a comment.