Partial differentiation?

Hi all,

we are trying to implement a Stan model that includes partial differentiation of a formula with respect to some of the parameters in the model. In R it’s possible to implement it in the following way (very simple example):

# Define function to be differentiated
f = expression(alpha + beta1*x + beta2*y)

# Define values
x = 2
y = 1
alpha = 0.2
beta1 = 0.5
beta2 = 0.7

# Get derivative
x_deriv = eval(stats::D(f, 'x'))
y_deriv = eval(stats::D(f, 'y'))

Is there any equivalent way of doing this in Stan, specifically in the model section?
Or how is the best way to implement this if there currently is no equivalent?

Thanks!

2 Likes

You just have to code the derivative by hand, as given by D()

2 Likes

Thanks for your answer. We were hoping that there would be a more elegant way to do this, since the derivative can be quite lengthy when coding it (especially when doing partial differentiation with respect to several variables individually). But maybe that’s the best way to go.

1 Like

You can automate it without too much stress using some basic regex, if it’s something you have to do a lot of. e.g. search for all ‘<-’ and replace with ‘=’, find the left hand side bits and insert 'real ’ etc.

2 Likes