GithubHelp home page GithubHelp logo

kaskr / adcomp Goto Github PK

View Code? Open in Web Editor NEW
169.0 52.0 80.0 35.39 MB

AD computation with Template Model Builder (TMB)

License: Other

Makefile 0.08% R 3.32% C++ 93.14% CMake 0.21% C 1.16% HTML 0.02% TeX 0.51% Emacs Lisp 0.16% Shell 0.08% CSS 0.05% JavaScript 0.08% Cuda 0.96% Rez 0.22% GDB 0.01%

adcomp's Introduction

Template Model Builder (TMB)

Build Status

TMB is an R package with functionality similar to ADMB. It requires R at least version 3.0.0 and development tools needed to install R packages from source. Standard install instructions are available here.

Install the development version (Linux)

It is recommended to install TMB into your local R package library (if you do not yet have a local R package library, create one by running install.packages("") from the R prompt and follow the instructions). The package is installed from the command line by entering the adcomp folder and typing

make install

To build the user manual type

make pdf

Once the package is successfully installed it can be tested by starting R and running

library(TMB)
runExample(all=TRUE)

To build API-Function reference see instructions here. Once the documentation is built open dox/html/index.html in your web browser. Use the search field to find functions and their documentation.

It is recommended to test that models can be changed, re-compiled and re-loaded without problems:

setwd("tmb_syntax")
source("test_reload.R")

If everything works as intended this script should display "TRUE". The script has only been observed to fail for certain combinations of Linux and the gcc compiler, see below.

Advanced notes

Metis orderings

For large 3D random field models the ordering algorithms shipping with R's Matrix package are far from optimal. To get better orderings available run the extended TMB install script (Linux/Mac only):

make install-metis-full

The new orderings are available from R through the function runSymbolicAnalysis(). For a quick example of how to use it try the ar1_4D example:

cd tmb_examples
make ar1_4D

You should see a significant speedup.

Issues with library unloading

On recent versions of gcc the following problem may be encountered: When the user cpp file is changed, re-compiled and re-loaded, the changes do not take place. To see if you are affected by this issue, assuming your compiled DLL is called "mymodel.so", try running:

readelf -s mymodel.so | grep UNIQUE

If this gives any output it is not possible to unload the library, and R will have to be restarted every time the model is re-compiled. There are at least two alternative solutions to this problem:

  1. Use gcc with compilation flag -fno-gnu-unique (version 4.8.3 and newer): Add CXX = g++ -fno-gnu-unique to a file ~/.R/Makevars (create it if it doesn't exist).

  2. Use the clang compiler instead of gcc: Install clang and add CXX = clang++ to a file ~/.R/Makevars (create it if it doesn't exist).

Note: If you have precompiled TMB using precompile() prior to (1) or (2) you must repeat the precompilation with the new compiler settings.

adcomp's People

Contributors

aforren1 avatar alko989 avatar bbolker avatar bradbell avatar brianstock avatar calbertsen avatar casperwberg avatar colemonnahan avatar fishfollower avatar jaganmn avatar jgbabyn avatar johnrsibert avatar kaskr avatar kklot avatar lentinj avatar mebrooks avatar mmaechler avatar skaug avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

adcomp's Issues

Using segment and head break something.

I have a situation where I would like to calculate the mean and standard deviation of a subset of a vector of parameters. The reason is that I have fewer than 5 levels of a block effect, so I am fitting it as fixed effect rather than random. I'm fitting separate intercepts for each level of the block effect as if they were random intercepts. I've created an example to match the problem.

This is the R code to simulate the data

library(TMB)
trap_sd=5
date_sd=3
resid_sd=1
ndates=30
ntraps=5
mu=5
trt_eff=10
dev_trap=rnorm(ntraps, 0, trap_sd)#random deviates
dev_date=rnorm(ndates, 0, date_sd)#random deviates
dat=expand.grid(trap=factor(1:ntraps), date=factor(1:ndates), trt=c(0,1))
dat0=transform(dat, y=mu+trt_eff*trt + dev_trap[trap] + dev_date[date])
dat0$y=dat0$y+rnorm(nrow(dat0),0,resid_sd)
X=model.matrix(~-1+trap+trt, data=dat0)#fixed effects
Z=model.matrix(~-1+date, data=dat0)#random effects

I call this FE.cpp

#include <TMB.hpp>                                

template<class Type>
Type objective_function<Type>::operator() ()
{
    DATA_VECTOR(y);
    DATA_MATRIX(X);                             
    DATA_MATRIX(Z);
    DATA_INTEGER(ntraps);
    PARAMETER(log_re_sd);
    Type re_sd=exp(log_re_sd);
    ADREPORT(re_sd);
    PARAMETER(log_resid_sd);
    Type resid_sd=exp(log_resid_sd);
    ADREPORT(resid_sd);
    PARAMETER_VECTOR(beta);
    PARAMETER_VECTOR(dev);

    //OUTPUT INFO ON TRAP DISTRIBUTION
//  vector<Type> dev_trap=beta.head(ntraps);
    vector<Type> dev_trap=beta.segment(0,ntraps);
    Type mu=dev_trap.mean();
    ADREPORT(mu);
    Type trap_sd=sqrt((dev_trap-mu).square().mean());
    ADREPORT(trap_sd);

    //CALCULATE NLL
    Type nll;       
    vector<Type> Xbeta= X*beta;
    vector<Type> Zdev= Z*dev;
    for(int i=0; i<y.size(); i++)
    {
        nll-= dnorm(y(i), Xbeta(i)+Zdev(i), resid_sd, true);
    }
    for(int i=0; i<dev.size(); i++)
    {
        nll-= dnorm(dev(i), Type(0), re_sd, true);
    }           
    return nll;
}

Then R code to run the model

compile("FE.cpp", "-g -O0")
dyn.load("FE.so")
obj=MakeADFun(data=list(y=dat0$y, X=X, Z=Z, ntraps=ntraps),
            parameters=list(log_re_sd=0, log_resid_sd=1, beta=rep(0, ncol(X)), dev=rep(0, ncol(Z))),
            random=c("dev"), DLL="FE")
opt = nlminb(obj $par, obj $fn, obj $gr)
sdr=sdreport(obj) 
sdr

If I comment out this following code, then std.error estimates look good in sdr.
The problem occurs if I use .head() or .segment()

    //OUTPUT INFO ON TRAP DISTRIBUTION
//  vector<Type> dev_trap=beta.head(ntraps);
    vector<Type> dev_trap=beta.segment(0,ntraps);
    Type mu=dev_trap.mean();
    ADREPORT(mu);
    Type trap_sd=sqrt((dev_trap-mu).square().mean());
    ADREPORT(trap_sd);

"simple" example requires the bbmle package

The last line of the "simple" example requires the bbmle package, but it is not a stated dependency. The specific line in question is:

> summary(as.mle2(opt))
Loading required package: bbmle
Maximum likelihood estimation

Call:
mle(minuslogl = fn)

Coefficients:
          Estimate Std. Error
beta   52.01368218 0.20168426
beta   30.24055912 0.20183450
logsdu -0.15779083 0.12012879
logsd0  0.03326357 0.06674019

-2 log L: 750.1344 
Warning message:
In library(package, lib.loc = lib.loc, character.only = TRUE, logical.return = TRUE,  :
  there is no package called ‘bbmle’

Phases?

Hello:

I feel like there was an issue about phases posted, but I can't seem to find it. Does TMB currently have a phases feature similar to ADMB? The fixed parameters of a gompertz equation are giving me problems. I'd like to set each fixed parameter in a separate phase, as well as a different phase for the random effects. I just needed to be pointed in the right direction.

Thanks,
Brandon

.block for arrays

Is .block() not implemented for arrays in TMB? It works the way I expect for matrices, but the corresponding operations on arrays fail.

So, for example, I can run this code which creates a 3X3 matrix and fills the upper corner of that matrix from the upper corner of another matrix:

matrix<Type> Bmat(3,3); 
Bmat.block(0,0,2,2) = Amat.block(0,0,2,2)

The same code on arrays won't work:

array<Type> Barray(3,3); 
Barray.block(0,0,2,2) = Aarray.block(0,0,2,2)

The error occurs when calling MakeADFun() and is as follows:

TMB has received an error from Eigen. The following condition was not met: a_startRow >= 0 && blockRows >= 0 && a_startRow <= xpr.rows() - blockRows && a_startCol >= 0 && blockCols >= 0 && a_startCol <= xpr.cols() - blockCols Please check your matrix-vector bounds etc., or run your program through a debugger.

The error message doesn't make sense, however as all of these conditions are met (in the above example array/matrix A is much larger than array/matrix B, so a 2X2 block starting at index (0,0) definitely does exist).

Issues with library unloading

From the main page:

On recent versions of gcc the following problem may be encountered: When the user cpp file is changed, re-compiled
and re-loaded, the changes does not take place. To see if you are affected by this issue, assuming your compiled DLL
is called "mymodel.so", try running:

readelf -s mymodel.so | grep UNIQUE

If this gives a lot of output it is not possible to unload the library, and R will have to be restarted every time

the model is re-compiled. A workaround is to use clang++ instead of gcc.

The following works for me using gcc in both Windows and Linux:

Initially, first look that mymodel.so (mymodel.dll in Windows) is loaded:
getLoadedDLLs()

In practice, just run the following to unload mymodel.so (mymodel.dll), without the need to restart R:

Clear dyn.load'ed files

dyn.unload(dynlib("mymodel")) # First attempt
gc() # Garbage Collection
dyn.unload(dynlib("mymodel")) # Second attempt
getLoadedDLLs() #Verify that second attempt works

-John

Mac installation

I found a missing step in the installation process for people using OS X Mavericks.

The solution is to open a terminal and type
curl -O http://r.research.att.com/libs/gfortran-4.8.2-darwin13.tar.bz2
sudo tar fvxz gfortran-4.8.2-darwin13.tar.bz2 -C /

I found the solution at this site http://www.thecoatlessprofessor.com/programming/rcpp-rcpparmadillo-and-os-x-mavericks-lgfortran-and-lquadmath-error

Here's the output before doing that missing step.
~ cd adcomp/
~/adcomp make install
make build-package
R CMD build --resave-data=no TMB

  • checking for file ‘TMB/DESCRIPTION’ ... OK
  • preparing ‘TMB’:
  • checking DESCRIPTION meta-information ... OK
  • cleaning src
  • checking for LF line-endings in source and make files
  • checking for empty or unneeded directories
  • building ‘TMB_1.0.tar.gz’

R CMD INSTALL --preclean TMB_1.0.tar.gz

  • installing to library ‘/Library/Frameworks/R.framework/Versions/3.1/Resources/library’
  • installing source package ‘TMB’ ...
    ** libs
    clang -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/Matrix/include" -fPIC -Wall -mtune=core2 -g -O2 -c external_metis.c -o external_metis.o
    clang -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/Matrix/include" -fPIC -Wall -mtune=core2 -g -O2 -c local_stubs.c -o local_stubs.o
    clang -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/Matrix/include" -fPIC -Wall -mtune=core2 -g -O2 -c solve_subset.c -o solve_subset.o
    clang -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include -I"/Library/Frameworks/R.framework/Versions/3.1/Resources/library/Matrix/include" -fPIC -Wall -mtune=core2 -g -O2 -c utils.c -o utils.o
    clang -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L/usr/local/lib -o TMB.so external_metis.o local_stubs.o solve_subset.o utils.o -L/Library/Frameworks/R.framework/Resources/lib -lRlapack -L/Library/Frameworks/R.framework/Resources/lib -lRblas -L/usr/local/lib/gcc/x86_64-apple-darwin13.0.0/4.8.2 -lgfortran -lquadmath -lm -F/Library/Frameworks/R.framework/.. -framework R -Wl,-framework -Wl,CoreFoundation
    ld: warning: directory not found for option '-L/usr/local/lib/gcc/x86_64-apple-darwin13.0.0/4.8.2'
    ld: library not found for -lquadmath
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    make[1]: *** [TMB.so] Error 1
    ERROR: compilation failed for package ‘TMB’
  • removing ‘/Library/Frameworks/R.framework/Versions/3.1/Resources/library/TMB’
    make: *** [install] Error 1

Rinterface() picks up names from comments

If we do the following

template("foo.cpp")
Rinterface("foo.cpp")

we get

library(TMB)
dyn.load("foo.so")
MakeADFun(
 data=list(
  a=,
  name=,
  name=,
  1=,
  1=,
  name=,
  name=,
  name=,
  )
 ),
 parameters=list(
  x=,
  name=,
  name=,
  name=,
  1=,
 )
)

Note the presence of "name=" and "1=" here - these are being picked up from within comments, which is not ideal. Regular expressions could be used to strip the comments from the template before parsing:

Hessian matrix

Hello All

I am a new user with little experience with cpp so be nice to me.

obj$fn and obj$gr in TMB examples return the function value to minimize, and its gradient.
obj$he() is there too, and it seems to return the hessian.
When I run obj$he(par) I get the error message:

Error in .Call("tmb_invQ_tril_halfdiag", L, PACKAGE = "TMB") :
'L' is missing

None of the examples use the hessian in nlminb so I am thinking this error is expected and
TMB is not returning the hessian function,

Am I correct?

thks noel cadigan

Delta-method for expectation of derived variables

Hi all,

It appears that sdreport() uses the delta-method to approximate the variance of derived values (specified as ADREPORT() outputs), but does not use the delta-method to approximate their expected values (and instead just reports f( E(theta) ) rather than E( f(theta) ), where theta are the estimated parameters, E(theta) are their MLE estimates, and f(theta) is the ADREPORT() computations).

Is it possible to add this computation? On first blush, it seems feasible given your AD calculation of the hessian -- but I don't fully understand the implication of the "generalized delta-method" computations used by sdreport().

cheers,
Jim

runExample(all=TRUE)

I received an error when running all examples as stated on github site. James Thorson suggested running the first example individually and that worked, The code for the run/error is shown below. After I ran first example separately then the runExample(all=TRUE) worked. --jeff

R version 3.0.2 (2013-09-25) -- "Frisbee Sailing"
Copyright (C) 2013 The R Foundation for Statistical Computing
Platform: i386-w64-mingw32/i386 (32-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

This is RMark 2.1.8

[Previously saved workspace restored]

library(TMB)
Loading required package: Matrix

Attaching package: ‘TMB’

The following object is masked from ‘package:stats’:

optimize

runExample(all=TRUE)
Building example ar1xar1
make: Nothing to be done for `all'.
Build time 0.43 seconds

Running example ar1xar1

require(TMB)

set.seed(123)

n <- 50 ## Size of problem = n*n

======================= Simulate separable 2D GMRF

- With exponential correlation in both directions

- phi1 = 1-lag correlation in 1st .... [TRUNCATED]

simgmrf <- function(n1,n2,phi1,phi2){

  • u <- matrix(rnorm(n1*n2),n1,n2)
  • L1 <- t(chol(ar1corr(n1,phi1)))
  • L2 <- t(chol(ar1corr(n2,phi2)))
  • .... [TRUNCATED]

======================= Simulate data

phi1=exp(-1/(.1*n)) ## Correlation range=10% of grid size first dimension

phi2=exp(-1/(.2*n)) ## Correlation range=20% of grid size second dimension

eta <- simgmrf(n,n,phi1,phi2)

N <- rpois(length(eta),exp(eta))

d <- expand.grid(x=factor(1:n),y=factor(1:n))

d$N <- N

======================= Parameterization of phi

f <- function(x) 2/(1 + exp(-2 * x)) - 1

invf <- function(y) -0.5 * log(2/(y + 1) - 1)

======================= Fit model

dyn.load(dynlib("ar1xar1"))

obj <- MakeADFun(data=list(N=N),

  •              parameters=list(
    
  •                eta=matrix(0,n,n),
    
  •                transf_phi1=invf(0 .... [TRUNCATED] 
    
    Order of parameters:
    [1] "eta" "transf_phi1" "transf_phi2"
    Not matching template order:
    [1] "\003\001‘\a\002" "`\a" "transf_phi2"
    Your parameter list has been re-ordered.
    (Disable this warning with checkParameterOrder=FALSE)
    Error in retape() : PARAMETER COMPONENT NOT A VECTOR!

Enter a frame number, or 0 to exit

1: runExample(all = TRUE)
2: lapply(exnames, runExample, thisR = thisR, clean = clean, ...)
3: FUN(c("ar1xar1", "ar1xar1_parallel", "atomic", "atomic_parallel", "linreg_parallel", "randomregression", "rw", "simple", "sumtest")[[1]], ...)
4: source(paste(name, ".R", sep = ""), echo = TRUE)
5: withVisible(eval(ei, envir))
6: eval(ei, envir)
7: eval(expr, envir, enclos)
8: ar1xar1.R#35: MakeADFun(data = list(N = N), parameters = list(eta = matrix(0, n, n), transf_phi1 = invf(0.5), transf_phi2 = invf(0.5)), random = c("eta"))
9: retape()

cholesky decomposition

I am working on a model with a correlated random walk.
Not too many time steps, but the dimension of the "state" (i.e. nsites) can be large (250-500)
The sites are irregular, and the correlation is a separable type.
The covariance matrix of the state is below

nll for RW
MVNORM_t neg_log_density(cov);
for(int j = 0;j < nweeks;++j){
nll+=neg_log_density(vector(log_dev.col(j)));
}

If I set nsites to be small (50 or so) then my code works but not when nsites is larger.
R just hangs, and used much memory.

Note sure what is going on but an easier route is to generate correlated RW using independent standard normal random deviates and chol(Cov).
Is there a way I can do this?

matrix cov(nsites,nsites);
matrix corr(nsites,nsites);
for (i=0;i<nsites;i++){
corr(i,i)=one;
for ( j=0;j<i;j++)
{
corr(i,j)=exp(log_ar(0)_dist_lat(i,j) + log_ar(1)_dist_lon(i,j));
corr(j,i)=corr(i,j);
}
}
Type den = (one - ar(0)ar(0))(one - ar(1)_ar(1));
cov=var_sp_corr/den;

using CppAD function that requires class definition

I'm trying to replicate an example from the lsoda function in R. I can't seem to get a class definition correct to use with the CppAD::Runge45 function.
I keep getting conversion errors about = signs. I think I'm just pushing errors around and not solving them.

These are the examples I found that use Runge45. The first link is the one I've tried to follow
http://moby.ihme.washington.edu/bradbell/dismod_ode/eigen_ode2.cpp.xml
http://www.coin-or.org/CppAD/Doc/runge45_1.cpp.xml
http://www.coin-or.org/CppAD/Doc/runge45_2.cpp.xml
http://www.coin-or.org/CppAD/Doc/ode_evaluate.hpp.htm

Here's the example using lsoda

library(deSolve)
SPCmod <- function(t, x, parms) {
  with(as.list(c(parms, x)), {
    dS <- .01 - b*S*P + g*C     #substrate
    dP <- c*S*P  - d*C*P           #producer
    dC <- e*P*C  - f*C             #consumer
    res <- c(dS, dP, dC)
    list(res)
  })
}

## Parameters 
parms  <- c(b = 0.0, c = 0.1, d = 0.1, e = 0.1, f = 0.1, g = 0.0)

## vector of timesteps
times  <- seq(0, 100, length = 40)

## external signal with rectangle impulse

## Start values for steady state
y <- xstart <- c(S = 1, P = 1, C = 1)

## Solving
out <-  lsoda(xstart, times, SPCmod, parms) 

## Plotting
mf <- par("mfrow")
plot(out, main = c("substrate", "producer", "consumer"))
plot(out[,"P"], out[,"C"], type = "l", xlab = "producer", ylab = "consumer")
par(mfrow = mf)

This is the C++ code I'm attempting to compile

#include <TMB.hpp>
#include <cppad/runge_45.hpp>      // for CppAD::Runge45

template<class Type>
class Fun {
        private:
        Type b_;
        Type c_;
        Type d_;
        Type e_;
        Type f_;
        Type g_;
    public:
        // set f = x'(t)
        void Ode(const Type &t, const CppAD::vector<Type> &x, const CppAD::vector<Type> &f)
        {
            f[0] =  .01 - b_*x[0]*x[1] + g_*x[2];
            f[1] = c_*x[0]*x[1]  - d_*x[1]*x[2];
            f[2] = e_*x[1]*x[2]  - f_*x[2];
            return;
        }
        void setpars(const Type& b, const Type& c, const Type& d, const Type& e, const Type& f, const Type& g)
        {
            b_=b;
            c_=c;
            d_=d;
            e_=e;
            f_=f;
            g_=g;
        }   
};

template<class Type>
Type objective_function<Type>::operator() ()
{
    DATA_VECTOR(times);
    DATA_VECTOR(x0);
    DATA_SCALAR(b);
    DATA_SCALAR(c);
    DATA_SCALAR(d);
    DATA_SCALAR(e);
    DATA_SCALAR(f);
    DATA_SCALAR(g);

    PARAMETER(dum);
    int n=times.size();
    int m=x0.size();
    matrix<Type> x(n,m);
    x.row(0)=x0;
    Type nll;       
    Fun<Type> F;
    F.setpars(b,c,d,e,f,g);

    Type xi;
    Type ti;
    Type tf;

    for(int i=0; i<1; i++)
    {
        xi=x.row(i);
        ti=times[i];
        tf=times[i+1];
//      x.row(i+1)=CppAD::Runge45(F, 1, ti, tf, xi); //This caused errors about the '='. so ignore for now.
        vector<Type> test =CppAD::Runge45(F, 1, ti, tf, xi);
    }
    ADREPORT(x);

    nll= -dnorm(dum, Type(0), Type(1), true);
    return nll;
}   

using this R code (run after lsoda example)

library(TMB)

dat=list(x0=xstart, times=times, b = 0.0, c = 0.1, d = 0.1, e = 0.1, f = 0.1, g = 0.0)
pars=list(dum=0)

compile("testRunge45.cpp")
dyn.load("testRunge45.so")
mod= MakeADFun(dat, pars, DLL="testRunge45")
fit = nlminb(mod $par, mod $fn, mod $gr)
(sd<-sdreport(fit))

Documentation of importance sampler?

Hi all,

Is there any documentation of the importance sampler option "MCcontrol" in "MakeADFun"?

I know this is an option too in in ADMB-RE, and imagine its more accurate when the marginal probability of random effects are not quadratic. However, its not clear how sampling locations are chosen, or comparable across function calls. Also, should this option always be checked for important applications? Are there any best-practices recommendations?

Any guidance is appreciated,
Jim

Probability distributions

It would be nice to have most probability distributions in TMB.

What do people think about the following conventions?

  • Use R naming conventions dnorm(), dpois() etc. for function names and arguments
    (This way we can refer to R for documentation)
  • We only need cumulative distirbutions (p... and q...) for continuous distributions.
    The purpose here is to use the transformation trick qgamma(pnorm(u))
    to generate a gamma distributed random effect.

Hans

REPORT option?

Hi all,

I don't see in the examples any feature for outputting derived quantities during the final model evalation, without using the ADREPORT() option (which then tries to calculate standard errors for each element). This can be useful for calculating diagnostic outputs, and calculating standard errors because computationally infeasible if you have a lot of diagnostics.

If this feature does not already exist, I suggest adding a new command REPORT() that makes a new slot in the object arising from a call to sdreport() that contains values (but not standard errors) for anything called via REPORT(). Or perhaps the values could be obtained after optimization but before calling sdreport().

Jim

"map" not working for PARAMETER_MATRIX objects

Hi all,

I've been using the "map" input to MakeADFun() to turn off and aggregate parameters when using PARAMETER and PARAMETER_VECTOR objects, and find it to be very useful! However, I'm now trying to "turn off" elements of a PARAMETER_MATRIX, and get the error matrix:

Error in retape() :
Error when reading the variable: 'ln_VarInfl'. Please check data and parameters.

Is it possible to enable maps for PARAMETER_MATRIX?

jim

sdreport() breaks when there's exactly 1 ADREPORT number

When there's exactly 1 ADREPORT number, then sdreport() gives the error
Error in Dphi %% Vtheta %% t(Dphi) : non-conformable arguments

It looks like it's because in this case, Dphi is a vector instead of a matrix.
I'm pasting code for a reproducible example with 3 parameters. Dphi is a vector of length 3 in the case with 1 ADREPORT number or a 2-by-3 matrix in the case with 2 ADREPORT numbers.

I also made a new version of sdreport that catches this case. Do you want me to fork and offer this solution? I'm open to trying it for the learning experience.

library(TMB)
seed.set(111)

Set Parameter Values

mu=.5
sigma_proc=2
sigma_obs=3
nt=50
x0=1

Simulate Random Walk

x=cumsum(c(x0, rnorm(nt-1, mu, sd= sigma_proc)))
obs=x+rnorm(nt, sd= sigma_obs)

Write Model for TMB with 1 ADREPORT object

cat(file="rand_walk_1sd.cpp","

include <TMB.hpp>

template
Type objective_function::operator() ()
{
DATA_VECTOR(obs);

PARAMETER(mu);                               
PARAMETER(log_sigma_proc);                                        
PARAMETER(log_sigma_obs);                                        
PARAMETER_VECTOR(x);
Type nll;          
Type sigma_proc = exp(log_sigma_proc);
Type sigma_obs = exp(log_sigma_obs);
ADREPORT(sigma_proc);
//ADREPORT(sigma_obs);

int nt=obs.size()-1;
nll=0;

for(int t=0; t<=nt-1; t++)
{
    nll+= -dnorm(x(t+1)-x(t), mu, sigma_proc, 1);
}   
for(int t=0; t<=nt; t++)
{
    nll+= -dnorm(obs(t), x(t), sigma_obs, 1);
}   
return nll;

}
")
compile("rand_walk_1sd.cpp")
dyn.load("rand_walk_1sd.so")

Write Model for TMB with 2 ADREPORT objects

cat(file="rand_walk_2sd.cpp","

include <TMB.hpp>

template
Type objective_function::operator() ()
{
DATA_VECTOR(obs);

PARAMETER(mu);                               
PARAMETER(log_sigma_proc);                                        
PARAMETER(log_sigma_obs);                                        
PARAMETER_VECTOR(x);
Type nll;          
Type sigma_proc = exp(log_sigma_proc);
Type sigma_obs = exp(log_sigma_obs);
ADREPORT(sigma_proc);
ADREPORT(sigma_obs);

int nt=obs.size()-1;
nll=0;

for(int t=0; t<=nt-1; t++)
{
    nll+= -dnorm(x(t+1)-x(t), mu, sigma_proc, 1);
}   
for(int t=0; t<=nt; t++)
{
    nll+= -dnorm(obs(t), x(t), sigma_obs, 1);
}   
return nll;

}
")
compile("rand_walk_2sd.cpp")
dyn.load("rand_walk_2sd.so")

Get Data and Initial Parameter Values into TMB Format

data=list(obs=obs)
pars=list(mu=0, log_sigma_proc=0, log_sigma_obs=0, x=obs)

Run the model

mod1=MakeADFun(data,pars,random=c("x"), DLL="rand_walk_1sd")
opt1= nlminb(mod1$par, mod1$fn, mod1$gr)
mod2=MakeADFun(data,pars,random=c("x"), DLL="rand_walk_2sd")
opt2= nlminb(mod2$par, mod2$fn, mod2$gr)

View Estimates

sdreport(mod1)#This breaks
sdreport(mod2)

sdreport2=
function (obj, par.fixed = NULL, hessian.fixed = NULL, getJointPrecision = FALSE)
{ # obj=mod1; par.fixed = NULL; hessian.fixed = NULL; getJointPrecision = FALSE
if (is.null(obj$env$ADGrad) & (!is.null(obj$env$random)))
stop("Cannot calculate sd's without type ADGrad available in object for random effect models.")
obj2 <- MakeADFun(obj$env$data, obj$env$parameters, type = "ADFun",
ADreport = TRUE, DLL = obj$env$DLL)
r <- obj$env$random
if (is.null(par.fixed)) {
par <- obj$env$last.par.best
if (!is.null(r))
par.fixed <- par[-r]
else par.fixed <- par
gradient.fixed <- obj$gr(par.fixed)
}else {
gradient.fixed <- obj$gr(par.fixed)
par <- obj$env$last.par
}
if (is.null(hessian.fixed)) {
hessian.fixed <- optimHess(par.fixed, obj$fn, obj$gr)
}
pdHess <- !is.character(try(chol(hessian.fixed), silent = TRUE))
Vtheta <- solve(hessian.fixed)
if (!is.null(r)) {
hessian.random <- obj$env$spHess(par, random = TRUE)
L <- obj$env$L.created.by.newton
if (!is.null(L)) {
updateCholesky(L, hessian.random)
hessian.random@factors <- list(SPdCholesky = L)
}
}
simpleCase <- is.null(r)
phi <- try(obj2$fn(par), silent = TRUE)
if (is.character(phi) | length(phi) == 0) {
simpleCase <- TRUE
phi <- numeric(0)
}else {
Dphi <- obj2$gr(par)
if (!is.null(r)) {
Dphi.random <- Dphi[, r]
Dphi.fixed <- Dphi[, -r]
if (all(Dphi.random == 0)) {
simpleCase <- TRUE
Dphi <- Dphi.fixed
}
}
}
if (simpleCase) {
if (length(phi) > 0) {
if(length(phi)==1){
cov <- t(Dphi) %% Vtheta %% Dphi
}else{
cov <- Dphi %% Vtheta %% t(Dphi)
}
}else cov <- matrix(, 0, 0)
}else {
tmp <- solve(hessian.random, t(Dphi.random))
tmp <- as.matrix(tmp)
term1 <- Dphi.random %% tmp
f <- obj$env$f
w <- rep(0, length(par))
reverse.sweep <- function(i) {
w[r] <- tmp[, i]
-f(par, order = 1, type = "ADGrad", rangeweight = w)[-r]
}
A <- t(sapply(seq(length = length(phi)), reverse.sweep)) +
Dphi.fixed
term2 <- A %
% (Vtheta %% t(A))
cov <- term1 + term2
}
sd <- sqrt(diag(cov))
ans <- list(value = phi, sd = sd, cov = cov, par.fixed = par.fixed,
cov.fixed = Vtheta, pdHess = pdHess, gradient.fixed = gradient.fixed)
if (!is.null(r)) {
if (is(L, "dCHMsuper") | is(L, "dCHMsimpl")) {
ihessian.random <- .Call("tmb_invQ", L, PACKAGE = "TMB")
iperm <- Matrix::invPerm(L@perm + 1L)
diag.term1 <- diag(ihessian.random)[iperm]
f <- obj$env$f
w <- rep(0, length(par))
reverse.sweep <- function(i) {
w[i] <- 1
f(par, order = 1, type = "ADGrad", rangeweight = w)[r]
}
nonr <- setdiff(seq(length = length(par)), r)
tmp <- sapply(nonr, reverse.sweep)
A <- solve(hessian.random, tmp)
diag.term2 <- rowSums((A %
% Vtheta) * A)
ans$par.random <- par[r]
ans$diag.cov.random <- diag.term1 + diag.term2
if (getJointPrecision) {
G <- hessian.random %% A
M1 <- cbind2(hessian.random, G)
M2 <- cbind2(t(G), as.matrix(t(A) %
% G) + hessian.fixed)
M <- rbind2(M1, M2)
M <- forceSymmetric(M, uplo = "L")
dn <- c(names(par)[r], names(par[-r]))
dimnames(M) <- list(dn, dn)
p <- Matrix::invPerm(c(r, (1:length(par))[-r]))
ans$jointPrecision <- M[p, p]
}
}else {
warning("Could not report sd's of full randomeffect vector.")
}
}
class(ans) <- "sdreport"
ans
}

sdreport2(mod1)
sdreport2(mod2)

possible recursion error

I am trying to solve for F in the Baranov catch equation, similar to
http://www.admb-project.org/examples/admb-tricks/adjoint-code-1/AdJointCodeBaranov.pdf

I have included the following code directly in my cpp file

int niter = 7;
F = one;
Type CF, derCF;

for(int i=0;i<niter;i++){
vector Z = F_p_ave_F + mp;
vector eZ = exp(Type(-1.0)Z);
vector Mort = Type(1.0) - eZ;
CF = F
((np1_Mort_p_ave_F/Z).sum());
derCF = (np1_p_ave_F_(Mort_mp/Z + eZ_F_p_ave_F)/Z).sum();
F += ((projC - CF)/derCF);
}

CF is the model value for catch, and derCF is the derivative of CF with respect to F

If I set niter =1 then no problem, but not a good solution for F
If niter>1 then I get the error:

iter: 1 Error in if (m < 0) { : missing value where TRUE/FALSE needed
outer mgc: NaN

Suggestions to fix this are greatly appreciated.

noel

pow() function

Is there a function in TMB that is like the pow function in ADMB?
I need to raise a parameter to the power of a data object. The exponent (data) is between 0 and 30.

Where are the "current best" random effect values in the "ADFun" object

There's several circumstances in which an analyst will want to access both "random" and "fixed" coefficients in the ADFun object, e.g., (1) changing all values and re-starting the optimizer to check convergence; (2) restarting from previously saved values; etc.

Its pretty obvious that obj$par returns the fixed effect values. However, obj also contains the "current best" random-effect values. How can you access these values?

As always, sorry if this is documented somewhere I haven't seen,
Jim

Importance sampler for mixture models?

I'm hoping to implement a state-space model that includes Markov-switches between "regimes", which represent different parameter values for the function representing the expected value of changes over time.

This model will almost certainly result in a probability for random effects (states) that is bimodal (conditional on fixed effects), and hence cannot be estimated using the Laplace Approximation. Is the importance sampler working for "small" random effect models? If so, is there an example that would show recommended settings (i.e., how many importance values to use)?

jim

Clang++ in fedora 19

When trying to use the clang compiler on redhat 19, using the latest version of TMB, I get the following error message:

compile('gadgetLite.cpp', CXX='clang++')
clang++ -I/usr/include/R -DNDEBUG -I/home/bthe/r/x86_64/library/TMB/include -DTMB_SAFEBOUNDS -DLIB_UNLOAD=R_unload_gadgetLite -DWITH_LIBTMB -I/usr/local/include -fpic -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -c gadgetLite.cpp -o gadgetLite.o
clang: error: unknown argument: '-fstack-protector-strong'
make: *** [gadgetLite.o] Error 1

Info on the clang compiler:
clang version 3.4 (tags/RELEASE_34/final)
Target: x86_64-redhat-linux-gnu
Thread model: posix

FAQ needs content.

The new TMB user have many questions. Many of of these should be answered in the FAQ of the TMB wiki: https://github.com/kaskr/adcomp/wiki/FAQ.

Please help adding content:

  • Remember back what your early questions were.
  • When you get help, consider adding FAQ entry
  • Better with a too long FAQ than too short (it is quick to remove entries).

Hans

data objects

sam_data.R, sdv_multi_data.R, and spatial_data.R should go into built in datasets that can be accessed using data()

GitHub repo name is confusing

Hi,

My first TMB model is nearing completion, and I am deeply impressed with it. It's a wonderful tool that you have created. Based on my experiences so far, here are two suggestions that sprung to mind
- It might be good to setup a mailing-discussion list. This issues-tracker seems to be working informally in that way, but maybe it would be good to have a proper mailing-list (a la ADMB), where people can ask dumb questions, as well as the technical ones.. (the-sushi: now done)

  • It might also be useful to move the address of this repository up to a higher level, so that it becomes a project in its own right - I've always been a bit confused about finding it, as it is part of Kaspers github account, and adcomp is not the most obvious place to look for TMB :-) https://github.com/TMB is already taken, but I'm sure you could find a creative alternative..

Mark

need DATA_INTEGER_VECTOR

Hi,

I'm unable to compile a model and I believe it is because I'm trying to access elements of one vector using elements of a data vector that are not integers.

The reason is that data is missing on some integer dates

Lynx rufus, from Idaho, GPPD data set 212.

obs=c(346,675,802,1478,1173,756,861,972,854,1161,1318,901,901,
1173,608,811,903,584,1179,1020,1129,966)
obsdates=c(1956,1957,1958,1959,1960,1961,1962,1963,1964,1965,1970,1971,
1972,1973,1974,1975,1976,1977,1978,1979,1980,1981)

I've narrowed the problem down to this line of cpp code

nll+= -dpois(obs(i), exp(x(obsdates(i))), 1);

Even just nll+= exp(x(obsdates(i))); gives the same error.

I can send you the cpp file if it helps.

The first error I get is

compile("GSS.cpp")
Note: Using Makevars in /Users/molliebrooks1/.R/Makevars
clang++ -I/Library/Frameworks/R.framework/Resources/include -DNDEBUG -I/Library/Frameworks/R.framework/Versions/3.1/Resources/library/TMB/include -DTMB_SAFEBOUNDS -DLIB_UNLOAD=R_unload_GSS -I/usr/local/include -I/usr/local/include/freetype2 -I/opt/X11/include -fPIC -mtune=core2 -g -O2 -c GSS.cpp -o GSS.o
In file included from GSS.cpp:1:
In file included from /Library/Frameworks/R.framework/Versions/3.1/Resources/library/TMB/include/TMB.hpp:35:
In file included from /Library/Frameworks/R.framework/Versions/3.1/Resources/library/TMB/include/tmbutils/tmbutils.cpp:7:
/Library/Frameworks/R.framework/Versions/3.1/Resources/library/TMB/include/tmbutils/vector.cpp:69:20: error: no member named 'size' in 'CppAD::AD'
this->resize(x.size());
~ ^
GSS.cpp:30:30: note: in instantiation of function template specialization 'tmbutils::vector::vector<AD, double>' requested here
nll+= -dpois(obs(i), exp(x(obsdates(i))), 1);
^

Safe mode?

I don't see a discussion page, and maybe this belongs there instead.

I was wondering if there's a "safe mode" option when building a model? compile() will catch some bugs, but bugs related to walking out of arrays will generally pass compile() but then crash R when running MakeADFun(). This is obviously disruptive when working from within R. Is there any suggestion for dealing with this?

Cheers,
jim

Is obj$env documented?

If in R you write obj <- MakeADFun(data...........
then obj$env contains a lot of interesting objects.

My knowledge about R environments is limited.
How are they typically documented? Is there TMB docs?

Hans

Supressing output

This is a trivial question, but is there a way to suppress the output. tracemgc=FALSE and tracepar=FALSE don't seem to do it. I found the cat function in MakeADFun for tracemgc, and it seems that setting it to FALSE should do the trick.

Thanks,
Chasco

"posfun" command for cpp declaration of model

Hi all,

Just a quick note that many state-space implementations require a function similar to "posfun" in ADMB, where a scalar of class Type is returned unchanged if above a certain threshold, but is returned at the threshold if below the threshold, and where the objective function is modified to penalize instances where it is below the threshold.

For example, an implementation of a state-space theta-logistic model requires posfun if using a lognormal process error (rather than the normal process error here:
https://groups.nceas.ucsb.edu/non-linear-modeling/projects/theta/ADMB/theta.tpl)

Cheers,
Jim

LaPack error

Dear Sir / Madam,

Recently I started looking into TMB for stock assessment and used the sam example available here on github. I had to modify the code slightly (include the posibility for an ssb survey) and the parameter estimation works fine (comparing output with the ADMB configuration of the same model).

Unfortunately however, whenever I try to generate the sdreport() I'm running into problem.

Error in solve.default(hessian.fixed) : Lapack routine dgesv: system
is exactly singular: U[20,20] = 0'

I would very much appreciate any help on this error on how to resolve it.

The one change I had to make in the loop where observations are treated where I'm not completely certain I did the right thing is here:

old:
var=varLogObs(CppAD::Integer(keyVarObs(f-1,a)));

new:
if(ft==3){
var=exp(2.0*logSdSSB(0));;
}else{
var=varLogObs(CppAD::Integer(keyVarObs(f-1,a)));

Looking forward to any suggestions on this.

Kind regards,

Niels

how does SEPARABLE work?

Hi all,

I am posting here so that any response can be archived. Please write directly for model-details if my description is not sufficient.

I am working on a spatiotemporal model, which could be "separable", i.e., N(t+1) is independent of N(t-1) conditional on fixed N(t). So, e.g., in ADMB-RE it would be computationally superior to specify N as random, rather than specifying "innovations" in the transition Epsilon as random (because Epsilon is not separable).

I understand that TMB "automatically" detects sparseness in the random effects (maybe I'm wrong). I also know that TMB has a SEPARABLE() command that exists when specifying priors on random fields, AR processes, etc., and a GMRF() command that exists for spatial fields.

So:

  1. What does SEPARABLE() do?
  2. Is it still true that its better (for speed and/or memory) to specify models by specifying states as random rather than innovations?
  3. If specifying via states, you have to calculate the "implied" innovation term, which is then penalized. Can this implied innovation (a matrix object) then be put into the GMRF() call?

And, as always, thanks for the amazing software and statistical improvements!

jim

Passing missing values via NA or NaN?

Hi all,

I'm trying to find a simple way to account for missing values in a model in TMB. Specifically, I wonder if there's a way to pass a vector of scalars as data (i.e., via DATA_VECTOR) where some of the elements are NA or NaN values from R. I could then use a logical test to evaluate whether each element is NA or NaN in TMB, and proceed with a likelihood computation (or something else) if they aren't NA or NaN. This would be easier than passing two vectors, one corresponding to values, and one corresponding to an indicator variable for missing values.

Any advice on what is possible for pass missing values between R and TMB, and vice versa?

cheers,
Jim

Model selection and validation

Hi,

I have added two qns to the FAQ that are very-frequently asked questions in my life:

  • How do I choose betweeen models fitted with TMB? e.g. how can I get a conditional AIC? Is it possible to extract a DIC value based on an estimated number of parameters, as is done in INLA?
  • How do I validate a model fitted with TMB? The linear modelling world has a large set of residual diagnostic tools that can be used to check (qualitatively) for appropriate model specification (e.g. Tukey-anscombe, QQplots, plot residuals vs explanatory variables). How do I approach this type of thing in the context of a TMB model (with e.g. non-Gaussian observation models)?

I'd love to hear some wisdom regarding this recurring question... Put another way, what would be the minimum that you would need to include in a paper to "prove" (ha, ha!) that your model is appropriate....

Mark

Best practices for distributing TMB and R code

Hi all,

I'm starting to plan projects where I'd like to distribute models using TMB code as stand-alone, encapsulated functions in R (i.e. index standardization, growth analysis, etc.).

I imagine that CRAN will not accept packages using TMB (because TMB isn't in CRAN), but could imagine using R-forge for cross-platform (at least windows and linux) package builds:

  1. Is there any better option I'm missing? (I'd prefer not to just source functions into the R environment)
  2. Is there any tutorial on how to bundle a package to build directly out of GitHub (as TMB itself does)?

Jim

nlminb issues

Hi,

I am hittting some problems with using the nlminb optimiser - in particular I get a lot of these errors:
Not improving much - will try early exit...PD hess?: FALSE

When the optimiser exits, I get a message:
false convergence (8)
which accordingly to the nlminb documentation means
"false convergence: the gradient ∇ f (x) may be computed incorrectly, the other stopping toler-
ances may be too tight, or either f or ∇ f may be discontinuous near the current iterate x"
Additionally, the parameter values that are returned are outside some of the bounds that I have applied to the model...

How should I get around this? Does anyone have any wisdom or good tips on getting your beautiful TMB model to converge properly..

Cheers,

Mark

ADREPORT appears to have trouble with matrix<Type> objects...

... although I might be misunderstanding something.

I've tried:
1.
ADREPORT( obj );
1.
for(int i=0;i<n_cols;i++){
for(int j=0;j<n_rows;j++){
ADREPORT( mean_y.col(i)(j) );
}
}

where
matrix obj;
has had individual cells assigned to values for which I'd like to get report statements.

and neither seems to work.

Splines

What is the best way to do splines in TMB? The splinedesign function in R gets you a long way, but in particular, how can the spline smoothness best be incorporated into the likelihood?

Mark

Cheat sheet of allowable DATA and PARAMETER input types?

Hi all,

I'm trying to read in a matrix of index values, so a matrix version of DATA_FACTOR and DATA_INTEGER. Does this exist? More importantly, is there a cheat sheet for all these allowable input types? It took me some trial and error to find DATA_SCALAR as a one-length vector of doubles.

cheers
Jim

Function documentation

Hello All

Is there documentation or a list of functions that have been written for TMB.
I noticed dnorm is there, and lgamma
What else?

Some of the programs I am trying to convert from ADMB to TMB use the ADMB function cumd_norm().
I was hoping there would be a TMB standard normal CDF (i..e qnorm in R) function.
Does nayone know if this exists in TMB?

regards
Noel Cadigan

Wiki pages are born

The TMB wiki pages (right hand side buttom in github) are now filled with (some) content. All registered github users have write access. Feel free to edit.

Hans

Two short comments on the best place find the path for the examples directory and the use of Vectorize

  1. In each example I changed, e.g.:
    dyn.load(dynlib("simple"))
    to:
    dyn.load(paste(system.file("examples", package = "TMB"), dynlib("simple"), sep = "/"))

Doing this allows each example to run as a separate entity and there would be no need to change the working directory in the runExample() function unless the exfolder argument is used, in which case the code could be:

if (!is.null(exfolder)) {
cwd <- getwd()
on.exit(setwd(cwd))
setwd(exfolder)
}

  1. Using Vectorize() on file.exists does nothing [seen in install_windows.R()] and works fine without it:

file.exists
function (...)
.Internal(file.exists(c(...)))

Vectorize(file.exists)
function (...)
.Internal(file.exists(c(...)))

This is similar to why the first example under the Vectorize() help file uses rep.int() not rep()

rep
function (x, ...) .Primitive("rep")

Vectorize(rep)
function (x, ...) .Primitive("rep")

rep.int
function (x, times)
.Internal(rep.int(x, times))

Vectorize(rep.int)
function (x, times)
{
args <- lapply(as.list(match.call())[-1L], eval, parent.frame())
names <- if (is.null(names(args)))
character(length(args))
else names(args)
dovec <- names %in% vectorize.args
do.call("mapply", c(FUN = FUN, args[dovec], MoreArgs = list(args[!dovec]),
SIMPLIFY = SIMPLIFY, USE.NAMES = USE.NAMES))
}

Best practices for distributing TMB and R code

Hi all,

I'm starting to plan projects where I'd like to distribute the code as a stand-alone, encapsulated functions (i.e. index standardization, growth analysis, etc.).

I imagine that CRAN will not accept packages using TMB (because TMB isn't in CRAN), but could imagine using R-forge for cross-platform (at least windows and linux) package builds:

  1. Is there any better option I'm missing? (I'd prefer not to just source functions into the R environment)
  2. Is there any tutorial on how to bundle a package to build directly out of GitHub (as TMB itself does)?

Jim

GMRF and space-time examples

Hi,

I'm trying to setup a simple GMRF problem as a prelude to a full 3D space-time setup. However, I am struggling to understand the syntax of the GMRF field. Some good examples (of both types) in the documentation would be very handy here... I can supply the R code of a minimum working example, if someone can do the cpp....

Mark

newtonOption smartsearch option

Perhaps this is covered somewhere and as a newbie I am just not finding it. But a bunch of the example R code has lines like:

newtonOption(smartsearch=FALSE)

(or same with "smartsearch=TRUE, I think to reset in case it was previously changed from default). When I do help(newtonOption) I get back it is an internal function. Did not see anything about this showing up in issues and my search on this on the site mainly turned up examples like the above in R code. In one place I saw a comment something like "The inner is expected to be quadratic" associated with setting this option to "FALSE"

Mainly at this point trying to figure out when to set TRUE or FALSE (default is TRUE). For theta-logistic example I changed it from "FALSE" to "TRUE" and it did not change the results, so I suspect this is efficiency issue and maybe something I can ignore but given many examples reset this option thought I would ask.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.