nimble-dev / nimble

The base NIMBLE package for R
http://R-nimble.org
BSD 3-Clause "New" or "Revised" License
160 stars 24 forks source link

C++ problem with compound calls to recycling-rule code using function arguments #1395

Closed perrydv closed 10 months ago

perrydv commented 10 months ago

This issue came from a user on nimble-users on 1/11/24.

testNimble <- nimbleFunction(
  run = function(r = double(2)) {
    returnType(double(2))
    return( r + r^2 )
  })
cTestNimble <- compileNimble(testNimble)

testR <- function(r) { r + r^2 }

testInput <- matrix(c(0  ,0.2,0.4,0.6,0.8,1  ), ncol=2)

print("expected output:"); print(testR(testInput))
print("uncompile nimble output:"); print(testNimble(testInput))
print("compiled nimble output:"); print(cTestNimble(testInput))

The second column of matrix output is wrong. The problem occurs only when using a recycling-rule function (the fairly new pow_int for pow_int(r, 2) in this case) with a matrix input, compounded with another operation (r+ in this case), when both operations have as their arguments variables which are function arguments (r and r in this example).

The following two cases do not display this problem:

testNimble <- nimbleFunction(
  run = function(r = double(2)) {
    returnType(double(2))
    a <- 2 # by assigning 2 to a variable, pow instead of pow_int is used on the next line; no bug
    return( r + r^a )
  })
cTestNimble <- compileNimble(testNimble)

testNimble <- nimbleFunction(
  run = function(r = double(2)) {
    returnType(double(2))
    t <- r # by making a local copy, different Eigen handling is invoked; no bug
    ans <- t+ t^2
    return( ans )
  })
cTestNimble <- compileNimble(testNimble)