Custom Templated as and wrap Functions within Rcpp.
James Joseph Balamuta —
written Jun 25, 2016 —
source
Introduction
Consider a need to be able to interface with a data type that is not
presently supported by Rcpp. The data type might come from a new library, or
from within one of our own applications. In either cases, Rcpp is faced with an issue of
consciousness as the new data type is not similar to known types so the
autocoversion or seamless R to C++ integration cannot be applied
correctly. The issue is two-fold as we need to consider both directions:
Converting from R to C++ using Rcpp::as<T>(obj)
Converting from C++ to R using Rcpp::wrap(obj)
Luckily, there is a wonderful Rcpp vignette called
Extending Rcpp
that addresses custom objects. However, the details listed are more
abstracted than one would like. So, I am going to try to take you through the
steps with a bit of commentary. Please note that the approach used is via
Templates and partial specialization and will result in some nice
automagic at the end.
The overview of the discussion will focus on:
Stage 1 - Forward Declarations
Stage 2 - Including the Rcpp Header
Stage 3 - Implementation of Forward Declarations
Stage 4 - Testing Functionality
Stage 5 - All together
Explanation of Stages
Stage 1 - Forward Declarations
In the first stage, we must declare our intent to the features we wish to use
prior to engaging Rcpp.h. To do so, we will load a different header file
and add some definitions to the Rcpp::traits namespace.
Principally, when we start writing the file, the first header that we must
load is RcppCommon.h and not the usual Rcpp.h!! If we do not place
the forward declaration prior to the Rcpp.h call, we will be unable to
appropriately register our extension.
Then, we must add in the different plugin markup for sourceCpp() to set the
appropriate flags during the compilation of the code. After the plugins, we
will include the actual headers that we want to use. In this document, we
will focus on Boost headers for the concrete example. Lastly, we must
add two special Rcpp function declaration, Rcpp::as<T>(obj) and
Rcpp::wrap(obj), within the Rcpp::traits namespace. To enable multiple types,
we must create an Exporter class instead of a more direct call to template
<> ClassName as( SEXP ).
Stage 2 - Include the Rcpp.h header
It might seem frivolous to have a stage just to declare import order, but if
Rcpp.h is included before the forward declaration then Rcpp::traits is
not updated and we enter the abyss. Template programming can be delicate,
respecting this include order is one of many small details one must get right.
Thus:
Stage 3 - Implementing the Declarations
Now, we must actually implement the forward declarations. In particular, the
only implementation that will be slightly problematic is the as<> since the
wrap() is straight forward.
wrap()
To implement wrap() we must appeal to a built-in type conversion index
within Rcpp which is called
Rcpp::traits::r_sexptype_traits<T>::rtype. From
this, we are able to obtain an int containing the RTYPE and then
construct an Rcpp::Vector. For the construction of a matrix, the same ideas
hold true.
as()
For as<>(), we need to consider the template that will be passed
in. Furthermore, we setup a typedef directly underneath the Exporter
class definition to easily define an OUT object to be used within the
get() method. Outside of that, we use the same trick to move back and forth
from a C++ T template type to an R type (implemented as one of several
SEXP types).
In order to accomplish the as<>, or the direct port from R to C++, I had to
do something dirty: I copied the vector contents. The code that governs
this output is given within the get() of the Exporter class. You may wish
to spend some time looking into changing the assignment using pointers
perhaps. I am not very well versed with ublas so I did not see an easy
approach to resolve the pointer pass.
Stage 4 - Testing
Okay, let’s see if what we worked on paid off (spoiler It did!
spoiler). To check, we should look at two different areas:
Trace diagnostics within the function and;
An automagic test.
Both of which are given below. Note that I’ve opted to shorten the ublas
setup to just be:
Trace Diagnostics
Test Call:
Results:
Converting from Rcpp::NumericVector to ublas::vector<double>
Running output test with ublas::vector<double>
1
2
3
4
Converting from ublas::vector<double> to Rcpp::NumericVector
Running output test with Rcpp::NumericVector
1
2
3
4
This test performed as expected. Onto the next test!
Automagic test
Test Call:
Results:
[1] 1.0 2.0 3.2 1.2
Success!
Stage 5 - All together
Here is the combination of the above code chunks given by stage. If you copy
and paste this into your .cpp file, then everything should work. If not,
let me know.
Closing Remarks
Whew… That was a lot. Hopefully, the above provided enough information as
you may want to extend this post’s content past 1D vectors to perhaps a
ublas::matrix and so on. In addition, then you now have the autoconvert
magic of Rcpp for ublas::vector<double>! Moreover, all one needs to do is
specify the either the parameters or return type of the function to be
ublas::vector<double> – and Voilà, automagic conversion!