AD: Convert R object to AD

View source: R/advector.R

ADR Documentation

Description

Signify that this object should be given an AD interpretation if evaluated in an active AD context. Otherwise, keep object as is.

Usage

AD(x, force = FALSE)

Arguments

x

Object to be converted.

force

Logical; Force AD conversion even if no AD context? (for debugging)

Details

AD is a generic constructor, converting plain R structures to RTMB objects if in an autodiff context. Otherwise, it does nothing (and adds virtually no computational overhead).

AD knows the following R objects:

  • Numeric objects from base, such as numeric(), matrix(), array(), are converted to class advector with other attributes kept intact.

  • Complex objects from base, such as complex(), are converted to class adcomplex.

  • Sparse matrices from Matrix, such as Matrix(), Diagonal(), are converted to adsparse which is essentially a dgCMatrix with advector x-slot.

AD provides a reliable way to avoid problems with method dispatch when mixing operand types. For instance, sub assigning x[i] <- y may be problematic when x is numeric and y is advector. A prior statement x <- AD(x) solves potential method dispatch issues and can therefore be used as a reliable alternative to ADoverload.

Examples

## numeric object to AD
AD(numeric(4), force=TRUE)
## complex object to AD
AD(complex(4), force=TRUE)
## Convert sparse matrices (Matrix package) to AD representation
F <- MakeTape(function(x) {
  M <- AD(Matrix::Matrix(0,4,4))
  M[1,] <- x
  D <- AD(Matrix::Diagonal(4))
  D@x[] <- x
  M + D
}, 0)
F(2)

RTMB documentation built on Sept. 12, 2024, 6:45 a.m.