nlmixr2 / blog

The nlmixr2 blog
0 stars 1 forks source link

blog/2024-05-08-user-functions/ #35

Open utterances-bot opened 3 months ago

utterances-bot commented 3 months ago

nlmixr2/rxode2 user functions | nlmixr2

nlmixr: open source nonlinear mixed-effects modeling for R.

https://blog.nlmixr2.org/blog/2024-05-08-user-functions/

zebulon2 commented 3 months ago

Thank you for implementing this feature, very useful. One thing though: when using a model in a text file, and loading it using rxode2(filename='my_model.txt') is it possible to declare the user function in the same file than the model itself? Or to import the code defining the r user function from another file? Thanks for your answer.

billdenney commented 3 months ago

I'm pretty sure that you cannot put the model into the text file. The text file ('my_model.txt' in your example) has to be the rxode2 model, itself.

The function would need to be defined in the R environment before loading, something like:

my_function <- function(x, y) x*y
mod <- rxode2(filename='my_model.txt')
zebulon2 commented 3 months ago

Thank you. Indeed this is what I suspected. Would be nice if rxode2() could accept not only a model textfile, but also supplementary code, since it now supports user-defined functions, which need to be defined outside of the model.

billdenney commented 3 months ago

A workaround can be to create a .R file that does the following:

my_function <- function(x, y) x/y

writeLines("
C2 <- my_function(centr, V2)

# time-derivative assignment
d/dt(centr) <- F*KA*depot - CL*C2 - Q*C2 + Q*C3;
", "modelFile.rxode2")
mod <- rxode2(filename='modelFile.rxode2')
unlink("modelFile.rxode2")

Then, you can source() the .R file and have a similar effect.

mattfidler commented 3 months ago

In C, yes this is available:

If you write your user code in C, and in a separate file, you can specify this too.

In the documention you have

extraC Extra c code to include in the model. This can be useful to specify functions in the model. These C functions should usually take double precision arguments, and return double precision values.

However it doesn't allow a single file for a model.

In R this isn't available

I have added a feature request here:

https://github.com/nlmixr2/rxode2/issues/761

Since rxode2 supports nlmixr2 style functions as well, another possibility is adding user functions in the user function definition. Probably more thought about the best way to acheive this would be good.

zebulon2 commented 2 months ago

Many thanks all for the answers and suggestions, and for opening a feature request.