I am trying to use the Rcpp sample function, but I want to sample without replacement and with unequal probability. However I am struggling to understand what form the argument sugar::probs_t probs should take, because I cannot find the definition.
sugar::probs_t is a typedef of Nullable< Vector<REALSXP> > (see the inst/include/Rcpp/sugar/functions/sample.h code file). So, if you pass it a Rcpp::NumericVector, then everything should be fine.
As you didn't provide any example code, lets look at an implementation in the unit test file for sugar:
// [[Rcpp::export]]
NumericVector sample_dbl(NumericVector x, int sz, bool rep = false, sugar::probs_t p = R_NilValue)
{
return sample(x, sz, rep, p);
}
Related
I'm trying to generate multinomial random variables as fast as possible. And I learned that gsl_ran_multinomial could be a good choice. However, I tried to use it based on the answer in this post: https://stackoverflow.com/a/23100665/21039115, and the results were always wrong.
In detail, my code is
// [[Rcpp::export]]
arma::ivec rmvn_gsl(int K, arma::vec prob) {
gsl_rng *s = gsl_rng_alloc(gsl_rng_mt19937); // Create RNG seed
arma::ivec temp(K);
gsl_ran_multinomial(s, K, 1, prob.begin(), (unsigned int *) temp.begin());
gsl_rng_free(s); // Free memory
return temp;
}
And the result was something like
rmvn_gsl(3, c(0.2, 0.7, 0.1))
[,1]
[1,] 1
[2,] 0
[3,] 0
which is ridiculous.
I was wondering if there was any problem exist in the code... I couldn't find any other examples to compare. I appreciate any help!!!
UPDATE:
I found the primary problem here is that I didn't set a random seed, and it seems that gsl has its own default seed (FYI: https://stackoverflow.com/a/32939816/21039115). Once I set the seed by time, the code worked. But I will go with rmultinom since it can even be faster than gsl_ran_multinomial based on microbenchmark.
Anyway, #Dirk Eddelbuettel provided a great example of implementing gsl_ran_multinomial below. Just pay attention to the random seeds issue if someone met the same problem as me.
Here is a complete example taking a double vector of probabilities and returning an unsigned integer vector (at the compiled level) that is mapped to an integer vector by the time we are back in R:
Code
#include <RcppGSL.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
// [[Rcpp::depends(RcppGSL)]]
// [[Rcpp::export]]
std::vector<unsigned int> foo(int n, const std::vector <double> p) {
int k = p.size();
std::vector<unsigned int> nv(k);
gsl_rng_env_setup();
gsl_rng *s = gsl_rng_alloc(gsl_rng_mt19937); // Create RNG instance
gsl_ran_multinomial(s, k, n, &(p[0]), &(nv[0]));
gsl_rng_free(s);
return nv;
}
/*** R
foo(400, c(0.1, 0.2, 0.3, 0.4))
*/
Output
> Rcpp::sourceCpp("~/git/stackoverflow/75165241/answer.cpp")
> foo(400, c(0.1, 0.2, 0.3, 0.4))
[1] 37 80 138 145
>
I'm mostly curious about the general pattern that's best practice to implement algorithms where we we're marching along indices on opposite ends of an array.
Here's an example problem from leetcode.
Problem Statement
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Example Solution
class Solution {
public:
int trap(int A[], int n) {
int left=0; int right=n-1;
int res=0;
int maxleft=0, maxright=0;
while(left<=right){
if(A[left]<=A[right]){
if(A[left]>=maxleft) maxleft=A[left];
else res+=maxleft-A[left];
left++;
}
else{
if(A[right]>=maxright) maxright= A[right];
else res+=maxright-A[right];
right--;
}
}
return res;
}
};
I've really enjoyed Haskell because of how elegant the solutions tend to be but I'm wondering if sometimes it's better to be able to fall back on imperative programming like is an option in OCaml
I am working on a research project that an Alloy generated instance holds entities (such as Signatures, Fields, Relations or Tuples) that resemble a programming language (such as java, c, etc).
For example, there are entities for Arithmetic operations (such as Add, Sub, Multiply, etc), for Relational operations (such equals, greater than, less than or equal, etc.) for variables, constants, and so on.
A tree view and graph view examples (max of two integers algorithm) of the model solution (instance found) are showing next. Those figures were extracted from Alloy Analyzer GUI.
My question is there a quick way to convert that alloy instance to any common language source code (Java would be the preferred language)?
Or should I do everything (Sigs, Fields, Atoms, language brackets, indentation, etc) by starting this way (going through an A4Solution) to build a kind of translator?
The main goal here is to build a Java program that is able to convert an Alloy instance to a Java source code file ready to compile and run.
//max of 2 integers' java source code at mymax2.java file
class MyMax2 {
public static void main(String[] args) {
int x;
int y;
int res;
if(y <= X) {
res = x;
} else {
res = y;
}
}
}
Finally, convert from XML to Java, by starting this way is not a desired option.
Thank you for help me on :)
Yours is really a formatted printing problem, with a tree as the data input. The tree is roughly an Abstract Syntax Tree (AST).
Do a post-order transversal of the tree, adding in the sensible text to each node as you travel back up the tree.
This means your "text for the node" function will look like a visitor, with lots of "policies" for each node type; however, there will be some wrinkles to address when it comes to variable scoping. Basically, the position of the declaration seems to be lost in your AST, and so you will have to write some code to cache the variable names in play, and define them in the upper blocks.
Since it might be ambiguous which block you would "unroll" your "variables to be declared" as you collapse your tree from the bottom up, your code will not be 100% identical to the input code. For example
public static void main(String[] args) {
int x;
if (x > 3) {
int y = 3 + x;
return x + y;
} else {
return 4;
}
}
might (after a full round trip of being converted to AST and back) read as
public static void main(String[] args) {
int x;
int y;
if (x > 3) {
y = 3 + x;
return x + y;
} else {
return 4;
}
}
Also, this assumes your AST has a pretty tight fit to the target programming language. For example, if you wanted to convert the presented AST to Prolog; you would quickly find out that the constructs in your AST are a poor fit for Prolog generation.
Should you need some direction, look into Pretty Printers which leverage most of the components of a compiler, with the exception that after they have their AST, they process it back out as source code.
There are a few wrinkles, but nothing too severe (provided your AST isn't missing a critical piece of information for the reverse back to source code).
Is there a way to raise a matrix to a power of 0.5 in Rcpp or RcppArmadillo? I don't want the element-wise power because I know that can be done by using pow function.
If you are asking about a function expm(), I am using one by wrapping around the code from the namesake CRAN package expm in my (incomplete) RcppKalman package on GitHub:
#include <RcppArmadillo.h>
/* Interface to expm package. */
typedef enum { Ward_2, Ward_1, Ward_buggy_octave } precond_type;
/* Matrix exponential exp(x), where x is an (n x n) matrix. Result z
* is an (n x n) matrix. Mostly lifted from the core of function
* expm() of package Matrix, which is itself based on the function of
* the same name in Octave. */
void (*expmat)(double *x, int n, double *z, precond_type precond_kind);
extern "C" void R_init_RcppKalman(DllInfo *dll) {
expmat = (void (*) (double*, int,
double*, precond_type)) R_GetCCallable("expm", "expm");
}
//' This function computes the exponential of a matrix.
//'
//' This functions calls the \code{expm} function from the eponymous package
//' \pkg{expm}. This is implemented via a registered function call, and does
//' not required explicit linking at the C level. However, the \pkg{expm} package
//' is imported in order to access its registered function at the C level.
//' [...]
// [[Rcpp::export]]
arma::mat expm(arma::mat x) {
arma::mat z(x.n_rows, x.n_cols);
(*expmat)(x.begin(), x.n_rows, z.begin(), Ward_2);
return z;
}
Some of the strange-looking stuff in the file is just the mechanics of getting expm from that package. The arma::mat expm(arma::mat x) function is pretty regular (and I guess I should make it const & as well).
Edit: Re-reading your question, I think I misunderstood. You were not asking for the matrix exponential. But then .... what exactly is it your are asking for if it is not element-wise?
I am getting all kinds of errors when passing my array to this function. The function is suppose to have the user enter a name and a score and store them in 2 seperate arrays, one for the names, one for the scores. I believe I have to use pointers but have no idea on how to use them. I don't want the answer, just a push in the right direction. Here is the code:
#include <iostream>
int InputData(int &, char, int);
using namespace std;
int main()
{
char playerName[100][20];
int score[100];
int numPlayers = 0;
InputData(numPlayers, playerName, score);
return 0;
}
int InputData(int &numPlayers, char playerName[][20], int score[])
{
while (numPlayers <= 100)
{
cout << "Enter Player Name (Q to quit): ";
cin.getline(playerName, 100, ā\nā);
if ((playerName[numPlayers] = 'Q') || (playerName[numPlayers] = 'q'))
return 0;
cout << "Enter score for " << playerName[numPlayers] <<": ";
cin >> score[numPlayers];
numPlayers++;
}
}
Ok, I made some more changes and the errors are less, must be getting close, Lol!
This looks like a school assignment and I applaud you for not asking for the answer. There are several ways to do it, but you are already fairly close in the approach that you are using. When you pass an array reference, you do not want to include the length of the array. For example, the parameter int score[100] should be int score[]. The exception, especially in your scenario, is with multidimensional arrays. In this case, you want to use char playerName[][20]. Your function declaration also needs to change to match. Don't forget InputData returns an int. Your declarations and function call are correct; you just need to adjust your function signature.
Keeping the errors aside -
InputData(numPlayers, playerName, score, size);
// ^^^^ size is no where declared
// resulting Undeclared indentifier error
Prototype mentions of taking 3 arguments but calling the function passing 4 parameters.
Hint regarding errors:
An 1D array decays to a pointer pointing to first element in the array while passing to a function.
A 2D array decays to a pointer pointing to the 1D array ( i.e., T[][size] ) while passing to a function.
Return type of main() should be int.
It seems with the given hints you corrected most of the errors. But you forgot to change the prototype. So, change -
int InputData(int &, char, int);
to
int InputData(int &, char[][20], int[]);
Why aren't you using std::string array for player names ? Use it and remove rest of the errors. Good luck.