Using seamless R in Rcpp function - rcpp

I thought I have seen before that you can write a Rcpp function and use R code inside of it. I just can't find the link anymore and using google doesn't help at all. Can you provide me an example or a link where it will be explained how to do it?

The key is the /*** R ... */ expression at the bottom, see the 'Rcpp Attributes' vignette.
So for the code
#include <Rcpp.h>
// [[Rcpp::export]]
void reallyWorks() {
Rcpp::Rcout << "Oh, wow, it works" << std::endl;
}
/*** R
reallyWorks()
*/
we get the expected behaviour straight from sourceCpp():
> sourceCpp("/tmp/soQ.cpp")
> reallyWorks()
Oh, wow, it works
>

Related

Uninitialized local variable 'state' used

So I want to create a program which allows users to map buttons to keyboard presses using c++ with Visual Studio 2015. I have been having a ton of trouble with Xinput and I was hoping someone could help me with one simple problem which makes no sense seeing as I have defined it.
So my problem is I get one error which says unresolved external symbol _XinputGetState#8 referenced in function _main.
Here is my code:
#include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <Xinput.h>
using namespace std;
int main() {
XINPUT_STATE state;
ZeroMemory(&state, sizeof(XINPUT_STATE));
if (XInputGetState(0, &state) == ERROR_SUCCESS)
{
cout << "It worked!" << endl;
}
bool A_button_pressed = ((state.Gamepad.wButtons & XINPUT_GAMEPAD_A) != 0);
cout << A_button_pressed << endl;
}
In general unresolved external symbols means that a library needed for the function is not linked.
In this case:
XInputGetState() requires XInputLib.lib and Xinput9_1_0.lib.
This can be resolved by adding the libraries in the project settings or via:
#pragma comment(lib,"XInput.lib")
#pragma comment(lib,"Xinput9_1_0.lib")

When does using RNGScope make a difference?

In Rcpp documentation, I often find the recommendation to place Rcpp::RNGScope scope; before using random draws within Rcpp. I wondered what exactly this does, because I've only ever seen it described as "ensures RNG state gets set/reset".
Then, I tested a bit, but I can't seem to come up with an example where doing this makes any difference. I used an example from here. My tests were:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector noscope() {
Rcpp::Function rt("rt");
return rt(5, 3);
}
// [[Rcpp::export]]
NumericVector withscope() {
RNGScope scope;
Rcpp::Function rt("rt");
return rt(5, 3);
}
and then
set.seed(45)
noscope() # [1] 0.6438 -0.6082 -1.9710 -0.1402 -0.6482
set.seed(45)
withscope() # [1] 0.6438 -0.6082 -1.9710 -0.1402 -0.6482
set.seed(45)
rt(5, 3) # [1] 0.6438 -0.6082 -1.9710 -0.1402 -0.6482
So, my question is twofold. First, when does RNGScope make a difference, and what exactly does it do different from not using it? Second, does anyone have a code example which shows different results with and without it?
If RNGScope was deprecated in a newer release, then I'm sorry for asking.
When using Rcpp attributes, the automagically generated interface to your code will automatically insert the appropriate construction of the RNGScope object -- so it's already being done for you behind the scenes in this case. For example, if you write sourceCpp(..., verbose = TRUE), you'll see output like this:
Generated extern "C" functions
--------------------------------------------------------
#include <Rcpp.h>
RcppExport SEXP sourceCpp_38808_timesTwo(SEXP xSEXP) {
BEGIN_RCPP
Rcpp::RObject __result;
Rcpp::RNGScope __rngScope;
Rcpp::traits::input_parameter< NumericVector >::type x(xSEXP);
__result = Rcpp::wrap(timesTwo(x));
return __result;
END_RCPP
}
Note the automatic construction of the RNGScope object.
You only need to construct that object manually if you are operating outside of the realm of Rcpp attributes.
This all becomes a little clearer once you read the original documentation in the Writing R Extensions manual, Section 6.3, "Random Numbers".
All that RNGScope scope does is the automagic calls to "get" and "put" in order to keep the state of the RNG sane.
The problem with your test code, as explained by Kevin, is that it already happens for you. So you can only test by going through .Call() by hand, in which case you will for sure leave the RNG in a mess if you use it and do not get/put properly.

using malloc in dgels function of lapacke

i am trying to use dgels function of lapacke:
when i use it with malloc fucntion. it doesnot give correct value.
can anybody tell me please what is the mistake when i use malloc and create a matrix?
thankyou
/* Calling DGELS using row-major order */
#include <stdio.h>
#include <lapacke.h>
#include <conio.h>
#include <malloc.h>
int main ()
{
double a[3][2] = {{1,0},{1,1},{1,2}};
double **outputArray;
int designs=3;
int i,j,d,i_mal;
lapack_int info,m,n,lda,ldb,nrhs;
double outputArray[3][1] = {{6},{0},{0}};*/
outputArray = (double**) malloc(3* sizeof(double*));
for(i_mal=0;i_mal<3;i_mal++)
{
outputArray[i_mal] = (double*) malloc(1* sizeof(double));
}
for (i=0;i<designs;i++)
{
printf("put first value");
scanf("%lf",&outputArray[i][0]);
}
m = 3;
n = 2;
nrhs = 1;
lda = 2;
ldb = 1;
info = LAPACKE_dgels(LAPACK_ROW_MAJOR,'N',m,n,nrhs,*a,lda,*outputArray,ldb);
for(i=0;i<m;i++)
{
for(j=0;j<nrhs;j++)
{
printf("%lf ",outputArray[i][j]);
}
printf("\n");
}
getch();
return (info);
}
The problem may come from outputArray not being contiguous in memory. You may use something like this instead :
outputArray = (double**) malloc(3* sizeof(double*));
outputArray[0]=(double*) malloc(3* sizeof(double));
for (i=0;i<designs;i++){
outputArray[i]=&outputArray[0][i];
}
Don't forget to free the memory !
free(outputArray[0]);
free(outputArray);
Edit : Contiguous means that you have to allocate the memory for all values at once. See http://www.fftw.org/doc/Dynamic-Arrays-in-C_002dThe-Wrong-Way.html#Dynamic-Arrays-in-C_002dThe-Wrong-Way : some packages, like fftw or lapack require this feature for optimization. As you were calling malloc three times, you created three parts and things went wrong.
If you have a single right hand side, there is no need for a 2D array (double**). outputArray[i] is a double*, that is, the start of the i-th row ( row major). The right line may be outputArray[i]=&outputArray[0][i*nrhs]; if you have many RHS.
By doing this in your code, you are building a 3 rows, one column, that is one RHS. The solution, is of size n=2. It should be outputArray[0][0] , outputArray[1][0]. I hope i am not too wrong, check this on simple cases !
Bye,

how to convert mpf_class to String

Hello and sorry for my basic English. I'm trying to convert from mpf_class to a String. I know there is a function (get_str()) but it show me only digits and its exponent separated. I want to get the whole expression in a string. I tried using ostreamstring and it work but I want to know if there is another way to do that. Let me know if I made myself clear.
Basically what I did was:
std::ostringstream show;
mpf_class result, Afact,Bfact,Cfact;
result=Afact*Bfact/Cfact;
show << result;
ui->lineEdit_5->setText(QString::fromStdString(show.str()));
As you can see, I'm working in a QT project and I need to show the result in a QLineEdit and with ostreamstring it works. I just was wondering if there is a gmp function to do that. thanks
Not sure whether this can help you, but you can actually print an mpf_class object and use I/O manipulators on it as a typical float object.
Here is my code
#include <gmpxx.h>
#include <iostream>
#include <iomanip>
int main(void) {
mpf_class a;
a = 3141592653589793.2;
std::cout << a << std::endl;
// Outputs 3.14159e+15
std::cout << std::uppercase << std::showpos << std::setprecision(3) << a << std::endl;
// Outputs +3.14E+15
}
Then you can use an std::ostringstream object instead of std::cout.
Reference: https://gmplib.org/manual/C_002b_002b-Formatted-Output.html

why do I get the out of date message in visual c++ 2010 express

So I'm starting a book called " Beginning c++ Through Game Programming, third edition, by Michael Dawson" and the very fist program I tried to run didn't work. I even tried just using the source code. Here it is:
// Game Over
// A first C++ program
#include <iostream>
int main()
{
std::cout << "Game Over!" << std::endl;
return 0;
}
If this is what you see, just check the checkbox at the bottom and hit "Yes". That will keep it from popping up. It's not an error in your code.
Otherwise, you need to post the error message you are receiving.
Based on various comments I'd made for the default of pre-compiled headers under VC++ and to leave the window open until enter is pressed use the following:
#include "stdafx.h"
#include <iostream>
int main()
{
std::cout << "Game Over!" << std::endl;
cin.ignore();
return 0;
}

Resources