Example
I have an Rcpp function where I would like to call boost::posix_time::time_from_string().
I've taken the example code from the boost documentation and translated it to a c++ function using Rcpp
library(Rcpp)
cppFunction(
includes = '
#include <boost/date_time/posix_time/posix_time.hpp>
',
code = '
void time_test() {
std::string t = "2002-01-20 23:59:59.000";
boost::posix_time::ptime pt(boost::posix_time::time_from_string(t));
Rcpp::Rcout << "time from string: " << pt << std::endl;
}
',
depends = "BH"
)
However, this doesn't compile.
I've seen a few comments saying you need to link to -lboost_date_time, such as this line in Dirk's RcppBDT library
// The next function uses the non-stream-based parsing in Boost Date_Time
// and requires _linking_ with -lboost_date_time which makes the (otherwise
// header-only) build more complicate
// // [ [ Rcpp::export ] ]
// Rcpp::DatetimeVector charToPOSIXctNS(Rcpp::CharacterVector sv) {
// ... code omitted ...
// }
Question
How do you provide the appropriate links to lboost_date_time, other than including the posix_time.hpp header, so that one can use time_from_string()?
Extra Info
It's possible to use other functions from the boost/date_time library, as demonstrated by this function, so what makes time_from_string() different?
cppFunction(
includes = '
#include <boost/date_time/posix_time/posix_time.hpp>
',
code = '
void time_test() {
Rcpp::Datetime dt("2002-01-20 23:59:59.000");
boost::posix_time::hours h( dt.getHours() );
boost::posix_time::minutes m( dt.getMinutes() );
boost::posix_time::seconds s( dt.getSeconds() );
Rcpp::Rcout << h << std::endl;
Rcpp::Rcout << m << std::endl;
Rcpp::Rcout << s << std::endl;
}
',
depends = "BH"
)
time_test()
# 12:00:00
# 00:59:00
# 00:00:59
As you already found out, you need to link with boost at the system level. The BH package is not sufficient. So first you have to install the required boost library. On Debian (dervied) Linux systems this can be done via
sudo apt-get install libboost-date-time-dev
Then you need to tell R to add -I/path/to/boost/headers and -L/path/to/boost/libraries -lboost_date_time to the compiler flags. You can do this by setting appropriate environment variables:
library(Rcpp)
Sys.setenv(PKG_LIBS="-L/usr/lib -lboost_date_time", PKG_CPPFLAGS="-I/usr/include")
cppFunction(
includes = '
#include <boost/date_time/posix_time/posix_time.hpp>
',
code = '
void time_test() {
std::string t = "2002-01-20 23:59:59.000";
boost::posix_time::ptime pt(boost::posix_time::time_from_string(t));
Rcpp::Rcout << "time from string: " << pt << std::endl;
}
'
)
Notes:
One could also define a Rcpp plugin for this.
In my case -I... and -L... are unnecessary, since the library is installed in a standard location. One does need these flags in other cases, though.
Related
New to CPP and RCPP
I am putting together an R package with RCPP.
Here are my steps:
Transfer to directory with package.
Run compileAttributes(pkgdir = ".",verbose=TRUE)
Then run build and install from devtools.
I want one of my CPP functions to print a message whenever it is invoked.
So i added :
Rcpp::Rcout << "Hello World!" << std::endl;
I then went through steps 1 to 3 above. But no cigar. Not even a cigarillo.
Ideally, I want it to print out an integer value i, somthing like
Sample code.
Rcpp::Rcout << i << std::endl;
SO far, it compiles and the function runs - but no printout of the dear variable. HELP! An example of my function is below. I suspect there is some standard way to either pass the values to R or to simply print from CPP.
# include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::plugins(cpp11)]]
using namespace Rcpp ;
arma::mat sillyme (arma::mat FE) {
arma::mat FEE = FE ;
Rcpp::Rcout << "Hello World!" << std::endl;
Rcpp::Rcout << FE.n_rows << std::endl;
return(FEE) ;
}
On my system (Ubuntu 20.04, R 4.0.0), this works just as expected (after adding a // [[Rcpp::export]] attribute to make sure the function is callable from R):
sillyme(diag(2))
# Hello World!
# 2
# [,1] [,2]
# [1,] 1 0
# [2,] 0 1
i am new to C++ and PCL. i wish to save the values of pointer in while loop and wanted to display the saved one . Here is part of my code . Please guide how to save the value of "coefficients->values[0] ,coefficients->values[1], coefficients->values[2], coefficients->values[3]" in an array each time loop runs.
// While 20% of the original cloud is still there
while (cloud_filtered->points.size () > 0.20 * nr_points)
{
// Segment the largest planar component from the remaining cloud
seg.setInputCloud (cloud_filtered);
seg.segment (*inliers, *coefficients);
if (inliers->indices.size () == 0)
{
std::cerr << "Could not estimate a planar model for the given dataset." << std::endl;
break;
}
std::cerr << "Model coefficients: " << coefficients->values[0] << " "
<< coefficients->values[1] << " "
<< coefficients->values[2] << " "
<< coefficients->values[3] << std::endl;
}
I am assuming that you are following this example code since the snippet you added in your question is almost to same. If this is the case, then you can declare a std::vector<pcl::ModelCoefficients> just before the while loop and push the coefficients into that like
std::vector<pcl::ModelCoefficients> coeffs;
while(...){
...
coeffs.push_back(*coefficients);
}
Also check the documentation for pcl::ModelCoefficients here which is nothing but a header and a vector of floats. Note that defining the coeffs as a vector of shared pointers and pushing pointers to the coefficients will not work in this case since previously pushed coefficients will be overwritten by seg.segment(*inliers, *coefficients);.
when using Rcpp, I want to use function abs, I just write Rcpp::abs(-1), but always an error:
no matching function for call to abs
Actually when I write Rcpp:ab, there are some hint that there exists Rcpp::abs(). I have tried some other function Rcpp::NumericVector, it works. I know I can use std::abs(-1), I just wonder why Rcpp::abs(-1) do not work, my system is windows, and I install Rtools.
Rcpp::abs() requires an Rcpp object, e.g. *Vector and *Matrix.
Unfortunately, -1 is of a primitive type, e.g. not an Rcpp object.
So, the following would work:
#include <Rcpp.h>
// [[Rcpp::export]]
void show_rcpp_abs() {
Rcpp::NumericVector A = NumericVector::create(-1);
Rcpp::Rcout << "A" << Rcpp::abs(A) << std::endl;
double B = std::abs(-1.0);
Rcpp::Rcout << "B" << B << std::endl;
}
I have a document in a *.css (Cascading Style Sheets) like format, but it has its own keywords. Actually it is a personalized css (I call it *.pss), with own tags and properties. here I have an excerpt:
/* CSS like style sheet file *.pss */
#include "otherStyleSheet.pss";
/* comment */
[propertyID="1230000"] {
fillColor : #f3f1ed;
minSize : 5;
lineWidth : 3;
}
/* sphere */
[propertyID="124???|123000"] {
lineType : dotted;
}
/* square */
[propertyID="125???"] {
lineType : thinline;
}
/* ring */
[propertyID="133???"] {
lineType : thickline;
[hasInnerRing=true] {
innerLineType : thinline;
}
}
I would like to parse it very easily, is there already something Ready-To-Use from Qt? What would be the easiest way?
Since *.css has its own keywords, I am NOT interessted in CSS parsers.
My further intention after parsing that *.pss is to store its properties in a Model structure .
There's nothing public within Qt. You're of course free to use the Qt's private CSS parser - you can copy it and modify to fit your needs.
See qtbase/src/gui/text/qcssparser_p.h, in qtbase/src/gui/text.
The good news is that for the example you've shown above, the modifications would be very minor. Qt's CSS parser already supports #import, so we only additional bit of syntax you have is the nested selector syntax. Without that syntax, you can use QCss::Parser as-is. The parser was written in a flexible fashion, where you don't need to worry about formal CSS keywords: it will still let you access all the declarations, whether they make sense from the formal CSS point of view or not.
Iterating the parse tree is as simple as it gets:
int main() {
QCss::Parser parser(pss);
QCss::StyleSheet styleSheet;
if (!parser.parse(&styleSheet))
return 1;
for (auto rule : styleSheet.styleRules) {
qDebug() << "** Rule **";
for (auto sel : rule.selectors) {
for (auto bSel : sel.basicSelectors)
qDebug() << bSel;
}
for (auto decl : rule.declarations)
qDebug() << decl;
}
}
The output is what we'd expect:
** Rule **
BasicSelector "propertyID"="1230000"
Declaration "fillColor" = '#f3f1ed' % QColor(ARGB 1, 0.952941, 0.945098, 0.929412)
Declaration "minSize" = '5' % 5
Declaration "lineWidth" = '3'
** Rule **
BasicSelector "propertyID"="124???|123000"
Declaration "lineType" = 'dotted'
** Rule **
BasicSelector "propertyID"="125???"
Declaration "lineType" = 'thinline'
** Rule **
BasicSelector "propertyID"="133???"
Declaration "lineType" = 'thickline'
We have to implement the debug stream operators for QCss classes ourselves:
QDebug operator<<(QDebug dbg, const QCss::AttributeSelector & sel) {
QDebugStateSaver saver(dbg);
dbg.noquote().nospace() << "\"" << sel.name << "\"";
switch (sel.valueMatchCriterium) {
case QCss::AttributeSelector::MatchEqual:
dbg << "="; break;
case QCss::AttributeSelector::MatchContains:
dbg << "~="; break;
case QCss::AttributeSelector::MatchBeginsWith:
dbg << "^="; break;
case QCss::AttributeSelector::NoMatch:
break;
}
if (sel.valueMatchCriterium != QCss::AttributeSelector::NoMatch && !sel.value.isEmpty())
dbg << "\"" << sel.value << "\"";
return dbg;
}
QDebug operator<<(QDebug dbg, const QCss::BasicSelector & sel) {
QDebugStateSaver saver(dbg);
dbg.noquote().nospace() << "BasicSelector";
if (!sel.elementName.isEmpty())
dbg << " #" << sel.elementName;
for (auto & id : sel.ids)
dbg << " id:" << id;
for (auto & aSel : sel.attributeSelectors)
dbg << " " << aSel;
return dbg;
}
When traversing the declaration, the QCss::parser already interprets some standard values for us, e.g. colors, integers, etc.
QDebug operator<<(QDebug dbg, const QCss::Declaration & decl) {
QDebugStateSaver saver(dbg);
dbg.noquote().nospace() << "Declaration";
dbg << " \"" << decl.d->property << "\" = ";
bool first = true;
for (auto value : decl.d->values) {
if (!first) dbg << ", ";
dbg << "\'" << value.toString() << "\'";
first = false;
}
if (decl.d->property == "fillColor")
dbg << " % " << decl.colorValue();
else if (decl.d->property == "minSize") {
int i;
if (decl.intValue(&i)) dbg << " % " << i;
}
return dbg;
}
Finally, the boilerplate and the stylesheet to be parsed:
// https://github.com/KubaO/stackoverflown/tree/master/questions/css-like-parser-31583622
#include <QtGui>
#include <private/qcssparser_p.h>
const char pss[] =
"/* #include \"otherStyleSheet.pss\"; */ \
[propertyID=\"1230000\"] { \
fillColor : #f3f1ed; \
minSize : 5; \
lineWidth : 3; \
} \
\
/* sphere */ \
[propertyID=\"124???|123000\"] { \
lineType : dotted; \
} \
\
/* square */ \
[propertyID=\"125???\"] { \
lineType : thinline; \
} \
\
/* ring */ \
[propertyID=\"133???\"] { \
lineType : thickline; \
/*[hasInnerRing=true] { \
innerLineType : thinline; \
}*/ \
}";
Support for nested selectors/rules can be implemented by modifying the parser source. The change needed to make Parser::parseRuleset recursive is very minor. I'll leave this as the exercise for the reader :)
All in all, I'd think that reusing the existing parser is much easier than rolling your own, especially as your users will inevitably wish you to support more and more of the CSS spec.
I know two possibilities:
boost::spirit and here you can find a good introduction to the boost::spirit parser framework
I would recommend to write your own recursive descent parser
Due to the fact, that your personalized *.pss is not that complex as a CSS (simple bracketing etc.), I would recommend 2.
Well, I'm guessing you don't want to be in the business of writing an Object parser, you would just be reinventing JSON, or YAML, or the like. So your best bet is to make your formatting conform to a known configuration or object notation language and then parse it with some library for the language you are using. With very minor modification, the format you describe above could become HOCON, which is a very nice superset of JSON, and has syntax much closer to what you are using:
https://github.com/typesafehub/config/blob/master/HOCON.md
You could then parse it with a HOCON parsing library, and voila, you would have in-memory objects you can model or store any way you please. I believe Qt is C++ based? There is a hocon library for C, I don't know about C++, and I'm guessing you would need to write a Qt plug-in to wrap the HOCON parsing from some other language.
The other option is to use a CSS->object parser like this one:
https://github.com/reworkcss/css
Which you may need to fork and modify to your needs. Either way, I'm guessing that to integrate into a Qt app you will need a plug-in that handles some call-out to a command-line process or other code module.
New to Rcpp I am testing how to retrieve and use a nested list from R with a known structure without copying parts of the list again. The small code example (with embedded R code) seems to work (cout is used for debugging).
The list rL retrieved from R may be very big so I do not want to reallocate memory (copy parts of rL). Do the current code copy parts of rL?
Best Lars
#include <Rcpp.h>
#include <iostream>
using namespace Rcpp;
using namespace std;
// [[Rcpp::export]]
SEXP testing(const List rL) {
List L(rL);
SEXP sL2(L["L2"]);
List L2(sL2);
SEXP sStateGrpL2(L2["stateGroups"]);
List stateGrpL2(sStateGrpL2);
SEXP sStateAllocL2(L2["stateAlloc"]);
CharacterVector stateAllocL2(sStateAllocL2);
SEXP sActionGrpL2(L2["actionGroups"]);
List actionGrpL2(sActionGrpL2);
SEXP sActionAllocL2(L2["actionAlloc"]);
List actionAllocL2(sActionAllocL2);
vector<string> stateLabels;
vector<string> actionLabels;
CharacterVector actionNames;
for(int n2 = 0; n2< as<int>(L2["stages"]); n2++) {
stateLabels = as< vector<string> >(stateGrpL2[as<string>(stateAllocL2[n2])]);
int s2Size = stateLabels.size();
SEXP sAllocA(actionAllocL2[n2]);
List allocA(sAllocA);
actionNames = as<CharacterVector>(allocA[0]);
cout << "stage:" << n2 << " sN:" << as<string>(stateAllocL2[n2]) << "\n";
for (int s2=0; s2<s2Size; ++s2) {
cout << " s:" << stateLabels[s2] << " aN:" << actionNames[s2] << "\n";
actionLabels = as< vector<string> >(actionGrpL2[ as<string>(actionNames[s2]) ]);
int a2Size = actionLabels.size();
for (int a2=0; a2<a2Size; ++a2) {
cout << " a:" << actionLabels[a2] << "\n";
}
}
}
return wrap(0);
}
/*** R
L <- list( L2=list(stages=2,
stateGroups=list(s1Grp=c("a","b","c"),s2Grp=c("d","e")),
stateAlloc = c(rep("s1Grp",1),rep("s2Grp",1)),
actionGroups = list(a1Grp=c("terminate","keep"), a2Grp=c("finish")),
actionAlloc = list(list( rep("a1Grp",3) ),
list( c("a1Grp","a2Grp") )
)
)
)
testing(L)
*/
You write:
The list rL may be very big so I do not want to use new memory (copy
parts of rL). Is this the way to do it?
Pretty much (as far as I can tell from a glance at your code).
All exchange with R uses SEXP types where the P stands for pointer -- these are shallow proxy objects which will not be copied. It uses / reuses the R object memory.
So if you profile / memory-profile this it should behave similarly for N=10 and N=1e5. But the proof is in the pudding...
A few things :
The loop test n2< as<int>(L2["stages"]) is both hard to read and
inefficient as it is calculated at each iteration. You should
definitely do it just once.
All of your as< vector<string> > create deep copies and does not
take advantage of the R's string cache. Can't you use a
CharacterVector instead ?