Custom Function with Known Gradients

Hi,

I’m having some difficulties following the wiki entries https://github.com/stan-dev/math/wiki/Adding-a-new-function-with-known-gradients and https://github.com/stan-dev/stan/wiki/Contributing-New-Functions-to-Stan for implementing a function with known gradients. I have added the function to the namespace math::stan as described in the first entry and using only C++ it also seems to work correctly:

int main() {

    stan::math::var x = 4.0;

    stan::math::var y = stan::math::foo(x);
    printf("foo(%.2f) = %.2f\n", x.val(), y.val());

    std::vector<stan::math::var> theta;
    theta.push_back(x);
    std::vector<double> g;
    y.grad(theta, g);
    printf("dfoo(%.2f) = %.2f\n", x.val(), g[0]);

    return 0;
}

However, now I would like to use the function within a Stan program. So, I added the line
add("foo", DOUBLE_T, DOUBLE_T);
to the function_signatures.h. But for the Stan program

functions {}
model {
  for (i in 1:11) {
    print(foo(i + 0.0));
  }
}

I receive the error

SYNTAX ERROR, MESSAGE(S) FROM PARSER:
No matches for: _
_ foo(real)

Are there any steps that I’m missing?

My function is declared as

namespace bar {

  double foo(double x)
  {
    return x * x;
  }

  double d_foo(double x)
  {
    return 2 * x;
  }

}

and

namespace stan {
  namespace math {

    double foo(double x) {
      return bar::foo(x);
    }

    var foo(const var& x) {
      double a = x.val();
      double fa = bar::foo(a);
      double dfa_da = bar::d_foo(a);
      return var(new precomp_v_vari(fa, x.vi_, dfa_da));
    }

  }
}

Any help will be appreciated!

Regards,
Jonas

Operating System: OS X 10.12
Interface Version: RStan 2.16.2
Compiler/Toolkit: clang-900.0.38

Did you rebuild the Stan compiler after that? You need to in order for that change to take hold.

I’m not sure if that’s easy to do from within RStan. I’m going to guess it’s on the rstan wiki somewhere.

Thanks for the quick reply. Could you specify what you mean by rebuilding the Stan compiler?

I downloaded the StanHeaders and RStan tar balls. Then I added the files to the StanHeaders and installed both packages from source. First the StanHeaders, then RStan. I assume these steps would rebuild the Stan compiler?

I built everything from scratch again, now it’s working. Thanks for the help!

3 Likes

@Jonas_K, sorry about that! I missed your reply from almost a week ago.

I’m glad you got it working! I’ve done it a bunch of times, but I always have to look up instructions.

2 Likes