I would like to add a density function with known partial derivatives. But I am not sure which way is the correct way in Stan Style. The computation of my partials is quite long and there are around 4 to 7 partials to be computed. I already searched in stan/math/prim/prob how others implemented the partials. It seems they did it in the same file as the density with the operands_and_partials environment. Is this the only way to implement partials?
I wonder whether it is legitimate to outsource the computation of the partials into an own file, but then: where to save it … could anyone help or post a link with information on how to add such functions?
There’s a section of operands & partials in the Math paper. You’ll be able to find an example of how normal_lpdf is implemented there. The current version of normal_lpdf, which is easier to read, looks different from the paper but the idea is the same.
Technically…yes. But I’m not sure I 100% understand the question.
Hey @yizhang, thanks for your answer! I had a look into the paper. But it is still not fully clear to me how to correctly implement the partials.
I also looked at the normal_lpdf file and the implementation of the partials there. It seems to me that the whole computation is just about 30 lines long and all takes place in the same file (normal_lpdf) as the computation of the density itself.
Due to infinite sums in my density the computation of the partial derivatives is quite longish, about 100 lines each partial and I have 4 partials. So, my question was whether I should write all the partials in one file my_function_lpdf. This would be a very long and rather confusing file.
Or whether it is possible in Stan Style to outsource the computation of the partials into own files my_function_lpdf_partial_1, my_function_lpdf_partial_2, and so on. Then the question arises where to save these files. I have not seen any function where the implementation of the partials was done in this way. I searched in the stan/math/prim/prob folder for files that only include the implementation of partial derivatives but unfortunately I have not found any.
I think it is reasonable to start with them all in the same file. A suggestion for an alternative organization may come up during code review, at which time it should be rather simple to move the code around if necessary
Tastes vary across the C++ world on file size, but I think everyone agrees functions should be broken down into manageable and testable chunks. So I’d suggest pulling those 100 lines out into functions that get called by the implementation of the density. That helps with code readability and adds implicit doc.