Skip to content
This repository has been archived by the owner on Jul 29, 2020. It is now read-only.

Commit

Permalink
Small change to Week 7 lecture...
Browse files Browse the repository at this point in the history
... plus added HW3 solution
  • Loading branch information
James-Thorson committed May 8, 2018
1 parent 20bf182 commit e5e2dea
Show file tree
Hide file tree
Showing 3 changed files with 158 additions and 0 deletions.
73 changes: 73 additions & 0 deletions Week 3 -- Temporal Models/Homework solution/HW3.r
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
library(TMB)

setwd("/Users/jiecao/Desktop/hw3_soln")
CPUE = FishData::download_catch_rates( survey="Eastern_Bering_Sea", species_set="Gadus chalcogrammus", error_tol=0.01, localdir=paste0(getwd(),"/") )
B_t = tapply( CPUE[,'Wt'], INDEX=CPUE[,'Year'], FUN=mean )
log_yt <- log(B_t)

#Run TMB model
compile("gompertz.cpp")
dyn.load(dynlib("gompertz"))

N = length(log_yt)
data <- list(log_yt = log_yt,model_switch=1)
parameters <- list(pop_par=c(1,0.5), log_sigma = -1,log_x0 = 4, log_xt = rep(mean(log_yt), N))

#data <- list(log_yt = log_yt,model_switch=2)
#parameters <- list(pop_par=c(0.6,100), log_sigma = -1,log_x0 = 4, log_xt = rep(mean(log_yt), N))

obj <- MakeADFun(data, parameters, random = "log_xt", DLL = "gompertz")
obj$hessian <- FALSE
opt <- do.call("optim", obj)
sd <- sdreport(obj)

# extract fixed effects:
fixed <- summary(sd, "fixed")
# extract estimated process:
log_xt <- summary(sd, "random")[, "Estimate"]
log_xt_se <- summary(sd, "random")[, "Std. Error"]

# simulation
n_sim = 100
sim <- replicate(n_sim, {
simdata <- obj$simulate()
obj2 <- MakeADFun(list(log_yt=c(simdata$log_yt[1:31],rep(NA,5)),model_switch=1), parameters, random = "log_xt", DLL = "gompertz", silent = TRUE)
TMBhelper::Optimize( obj=obj2, newtonsteps=1)
c( true = simdata$log_xt[32:36],
est = summary(sdreport(obj2), "random")[, "Estimate"][32:36],
sd = summary(sdreport(obj2), "random")[, "Std. Error"][32:36])
})

# calculate coverage
cal_coverage <- function (true, est, sd, interval){
low = est - qnorm(interval/2) * sd
high = est + qnorm(interval/2) * sd
return(true > low & true < high)
}

gom.matrix = matrix(NA,nrow=n_sim,ncol=5)
for(i in 1:n_sim){
for(t in 1:5){
gom.matrix[i,t]=cal_coverage(sim[t,i],sim[t+5,i],sim[t+10,i],0.5)
}
}
apply(gom.matrix,2,sum)

# ricker
parameters2 <- list(pop_par=c(0.6,100), log_sigma = -1,log_x0 = 4, log_xt = rep(mean(log_yt), N))
sim2 <- replicate(n_sim, {
simdata <- obj$simulate()
obj3 <- MakeADFun(list(log_yt=c(simdata$log_yt[1:31],rep(NA,5)),model_switch=2), parameters2, random = "log_xt", DLL = "gompertz", silent = TRUE)
TMBhelper::Optimize( obj=obj3, newtonsteps=1)
c( true = simdata$log_xt[32:36],
est = summary(sdreport(obj3), "random")[, "Estimate"][32:36],
sd = summary(sdreport(obj3), "random")[, "Std. Error"][32:36])
})

ricker.matrix = matrix(NA,nrow=n_sim,ncol=5)
for(i in 1:n_sim){
for(t in 1:5){
ricker.matrix[i,t]=cal_coverage(sim2[t,i],sim2[t+5,i],sim2[t+10,i],0.5)
}
}
apply(ricker.matrix,2,sum)
85 changes: 85 additions & 0 deletions Week 3 -- Temporal Models/Homework solution/gompertz.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@

// State-space Gompertz model
#include <TMB.hpp>

// Function for detecting NAs
template<class Type>
bool isNA(Type x){
return R_IsNA(asDouble(x));
}

template<class Type>
Type objective_function<Type>::operator() ()
{
// data:
DATA_VECTOR(log_yt);
DATA_INTEGER(model_switch);

// parameters:
PARAMETER_VECTOR(pop_par); // population growth rate parameter //density dependence parameter
PARAMETER(log_sigma); // log(process SD) = log(obs SD)
PARAMETER(log_x0);
PARAMETER_VECTOR(log_xt); // state

// transform the parameters
Type sigma = exp(log_sigma);

// reports
ADREPORT(sigma)

int n = log_yt.size(); // get time series length
Type nll = 0.0; // initialize negative log likelihood

nll -= dnorm(log_xt[0], log_x0, sigma, true) ;

Type m;

// process model:
for(int i = 1; i < n; i++){
if(model_switch == 1){
m = pop_par[0]+pop_par[1]*log_xt[i-1] ; //Gompertz model
}
if(model_switch == 2){
m = log_xt[i-1] + pop_par[0]*(1-exp(log_xt[i-1])/pop_par[1]) ; //Ricker model
}
nll -= dnorm(log_xt[i], m, sigma, true); //likelihood for random effects
}

// observation model:
for(int i = 0; i < n; i++){
if(!isNA(log_yt[i])){
nll -= dnorm(log_yt[i], log_xt[i], sigma, true); //likelihood for observations
}
}

SIMULATE{
log_xt[0] = rnorm(log_x0,sigma);
log_yt[0] = rnorm(log_xt[0],sigma);
for (int i = 1; i < n; i++){
log_xt[i] = rnorm(pop_par[0]+pop_par[1]*log_xt[i-1], sigma);
log_yt[i] = rnorm(log_xt[i], sigma);
}
REPORT(log_xt);
REPORT(log_yt);
}

return nll;
}


















Binary file not shown.

0 comments on commit e5e2dea

Please sign in to comment.