analyse_adult.R 7.55 KB
Newer Older
matbuoro's avatar
matbuoro committed
1
2
3
rm(list=ls())   # Clear memory


matbuoro's avatar
matbuoro committed
4

matbuoro's avatar
matbuoro committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
##------------------ R PACKAGES ------------------------------##
library(R2OpenBUGS)
library(rjags) # require to use "read.bugsdata" function
library(coda)
library(mcmcplots)
# library(dclone)
# library(snow)
# require(ggmcmc)


##-----------------------------INFO ----------------------------------##
year <- "2016"
site <- "Bresle"
stade <- "adult"


## WORKING DIRECTORY:
work.dir<-paste("/home/basp-meco88/Documents/RESEARCH/PROJECTS/ORE/Abundance",site,stade,sep="/")
setwd(work.dir)

matbuoro's avatar
matbuoro committed
25
26
27
# cleaning
system("rm bugs/*")

matbuoro's avatar
matbuoro committed
28
29
30
31
32
33
34
35
36
37
38

##-----------------------------DATA ----------------------------------##
source(paste('data/data_',stade,'.R',sep="")) # creation du fichier Rdata
load(paste('data/data_',stade,"_",year,'.Rdata',sep="")) # chargement des données


#----------------------------PARAMETERS---------------------------------##
source(paste('parameters_',stade,'.R',sep="")) # chargement des paramètres


#------------------------INITS----------------------------------##
matbuoro's avatar
matbuoro committed
39
40
41
42
43
44
#if(!file.exists(paste('inits/inits_',stade,year,'.Rdata',sep=""))){
if(!file.exists(paste("inits/init-",site,"-",stade,year,".txt",sep=""))){
  source(paste('inits/inits_',stade,'.R',sep="")) # création des inits des données
  #load(paste('inits/inits_',stade,year,'.Rdata',sep=""))
}
#load(paste('inits/inits_',stade,'.Rdata',sep="")) # chargement des inits
matbuoro's avatar
matbuoro committed
45
46
#if(site == "Bresle" && stade == "adult") {inits <- list(read.bugsdata(paste("inits/init-",site,"-",stade,year,".txt",sep="")))}
#if(site == "Nivelle") {inits <- list(read.bugsdata(paste("inits/init-",site,"-",stade,year,".txt",sep="")))}
matbuoro's avatar
matbuoro committed
47
inits.tmp <- read.bugsdata(paste("inits/init-",site,"-",stade,year,".txt",sep=""))
matbuoro's avatar
matbuoro committed
48
inits <- rep(list(inits.tmp),2)
matbuoro's avatar
matbuoro committed
49
50

#------------------------MODEL----------------------------------##
matbuoro's avatar
matbuoro committed
51
52
model <- paste("model/model_",stade,"-",site,".R",sep="") # path of the model
if(site == "Scorff" && stade == "smolt") {model <- paste("model/model_",stade,"-",site,"_",year,".R",sep="")} # le modèle Scorrf pour les smolt peut changer tous les ans suivant conditions
matbuoro's avatar
matbuoro committed
53
54
model

matbuoro's avatar
matbuoro committed
55
56
57
58
filename <- file.path(work.dir, model)
#system(paste("cp",model,paste(stade,"-",site,".txt",sep=""),sep=""))


matbuoro's avatar
matbuoro committed
59
#---------------------------ANALYSIS-----------------------------##
matbuoro's avatar
matbuoro committed
60
nChains = 2 #length(inits) # Number of chains to run.
matbuoro's avatar
matbuoro committed
61
adaptSteps = 1000 # Number of steps to "tune" the samplers.
matbuoro's avatar
matbuoro committed
62
63
64
nburnin=1000 # Number of steps to "burn-in" the samplers.
nstore=5000 # Total number of steps in chains to save.
nthin=1 # Number of steps to "thin" (1=keep every step).
matbuoro's avatar
matbuoro committed
65
66
67
68
69
70
#nPerChain = ceiling( ( numSavedSteps * thinSteps ) / nChains ) # Steps per chain.

### Start of the run ###
start.time = Sys.time(); cat("Start of the run\n"); 

######### BUGS ##########
matbuoro's avatar
matbuoro committed
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# fit <- bugs(
#   data
#   ,inits
#   ,model.file = filename
#   ,parameters
#   ,n.chains = nChains, n.iter = nstore + nburnin, n.burnin = nburnin, n.thin = nthin
#   ,DIC=FALSE
#   ,codaPkg = FALSE, clearWD=FALSE
#   #,debug=TRUE
#   ,working.directory=paste(work.dir,"bugs",sep="/")
# )

SEED <- floor(runif(2, 100000, 999999))
cl <- makePSOCKcluster(nChains)
## fitting the model with OpenBUGS
## using the preferred R2OpenBUGS interface
fit <- bugs.parfit(cl, data, parameters, filename,
                   n.iter=nstore + nburnin, n.thin=nthin,
                   seed=SEED,
                   program="openbugs",
                   DIC=FALSE,
                   #codaPkg = FALSE, clearWD=FALSE,
                   #debug=TRUE,
                   working.directory=paste(work.dir,"bugs",sep="/")
matbuoro's avatar
matbuoro committed
95
)
matbuoro's avatar
matbuoro committed
96
stopCluster(cl)
matbuoro's avatar
matbuoro committed
97

matbuoro's avatar
matbuoro committed
98
99
100
101
102
103
104
105
106
107
## cleaning
system("rm bugs/CODA*")

### Save inits ###
# save last values for inits
# inits <- fit$last.values
# if(site == "Nivelle") {
#   save(inits,file=paste('inits/inits_',stade,year,'.Rdata',sep=""))
#   }

matbuoro's avatar
matbuoro committed
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135

######### JAGS ##########
## Compile & adapt
#Create, initialize, and adapt the model:
# fit <- jags.model(
#   model,
#   data,inits,
#   n.chains=nChains,
#   n.adapt = adaptSteps)

# # Run JAGS in parallel. Each Chain is sent to a seperate core.
# cl <- makeSOCKcluster(nChains)                       # Request 3 cores. /!\ Need to check how many core  your computer has
# fit.mcmc <- jags.parfit(cl,
#                         data,
#                         parameters,
#                         model.dir,
#                         inits,
#                         n.chains=nChains,n.adapt=adaptSteps,n.update=nburnin,n.iter=nstore*nthin, thin=nthin
# )
# stopCluster(cl) #### /!\ Really important to do!

# duration of the run 
end.time = Sys.time()
elapsed.time = difftime(end.time, start.time, units='mins')
cat("Sample analyzed after ", elapsed.time, ' minutes\n')


## BACKUP
matbuoro's avatar
matbuoro committed
136
save(fit,file=paste('results/Results_',stade,"_",year,'.RData',sep=""))
matbuoro's avatar
matbuoro committed
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
write.table(fit$summary,file=paste('results/Results_',stade,"_",year,'.csv',sep=""),sep=";")
     
#------------------------------------------------------------------------------
# EXAMINE THE RESULTS
fit.mcmc <- as.mcmc(fit) # using bugs

# DIAGNOSTICS:
parameterstotest <-parameters # all parameters
# parameterstotest <- c(
#   "epsilon_p"
# )

# Start writing to an output file
sink(paste('results/Diagnostics_',stade,"_",year,'.txt',sep=""))

cat("=============================\n")
cat("DIAGNOSTICS\n")
cat("=============================\n")

if (nChains > 1) {
  cat("Convergence: gelman-Rubin R test\n")
matbuoro's avatar
matbuoro committed
158
  gelman.diag(fit.mcmc[,which(varnames(fit.mcmc)%in%parameterstotest)],multivariate=TRUE)
matbuoro's avatar
matbuoro committed
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
}


cat("\n---------------------------\n")
cat("Heidelberger and Welch's convergence diagnostic\n")
cat("
heidel.diag is a run length control diagnostic based on a criterion of relative accuracy for the estimate of the mean. The default setting corresponds to a relative accuracy of two significant digits.

heidel.diag also implements a convergence diagnostic, and removes up to half the chain in order to ensure that the means are estimated from a chain that has converged.
\n")
heidel.diag(fit.mcmc[,which(varnames(fit.mcmc)%in%parameterstotest)], eps=0.1, pvalue=0.05)

cat("\n---------------------------\n")
cat("Geweke's convergence diagnostic\n")
cat("
Geweke (1992) proposed a convergence diagnostic for Markov chains based on a test for equality of the means of the first and last part of a Markov chain (by default the first 10% and the last 50%).
If the samples are drawn from the stationary distribution of the chain, the two means are equal and Geweke's statistic has an asymptotically standard normal distribution. 
The test statistic is a standard Z-score: the difference between the two sample means divided by its estimated standard error. The standard error is estimated from the spectral density at zero and so takes into account any autocorrelation.

The Z-score is calculated under the assumption that the two parts of the chain are asymptotically independent, which requires that the sum of frac1 and frac2 be strictly less than 1.
\n")
geweke.diag(fit.mcmc[,which(varnames(fit.mcmc)%in%parameterstotest)], frac1 = 0.1, frac2 = 0.5)

cat("\n---------------------------\n")
cat("Raftery and Lewis's diagnostic\n")
raftery.diag(fit.mcmc[,which(varnames(fit.mcmc)%in%parameterstotest)], q=0.025, r=0.005, s=0.95, converge.eps=0.001)

# Stop writing to the file
sink()


## Plot the chains:
pdf(paste('results/Results_',stade,"_",year,'.pdf',sep=""))
#for (i in 1:5){
traplot(fit.mcmc[,which(varnames(fit.mcmc)%in%parameterstotest)])
# caterplot(fit.mcmc,parameters[i]) 
#}
matbuoro's avatar
matbuoro committed
196
gelman.plot(fit.mcmc[,which(varnames(fit.mcmc)%in%parameterstotest)])
matbuoro's avatar
matbuoro committed
197
198
199
200
201
dev.off()


#------------------------------------------------------------------------------
## SUMMARY
matbuoro's avatar
matbuoro committed
202
#if(site == "Scorff" && stade == "adult") {source("summary_adult.R")}
matbuoro's avatar
matbuoro committed
203
204
if(site == "Nivelle" && stade == "tacon") {source("analyse_coda_tacon.R")}