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


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 <- "YEAR"
site <- "SITE"
stade <- "STADE"


## WORKING DIRECTORY:
work.dir<-paste("Rep",site,stade,sep="/")
setwd(work.dir)

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

#------------------------MODEL----------------------------------##
matbuoro's avatar
matbuoro committed
50
model <- paste("model/model_",stade,"-",site,".R",sep="") # path of the model
matbuoro's avatar
matbuoro committed
51
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
52
53
model

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


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

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

######### BUGS ##########
fit <- bugs(
  data
  ,inits
matbuoro's avatar
matbuoro committed
73
  ,model.file = filename
matbuoro's avatar
matbuoro committed
74
75
76
  ,parameters
  ,n.chains = nChains, n.iter = nstore + nburnin, n.burnin = nburnin, n.thin = nthin
  ,DIC=FALSE
matbuoro's avatar
matbuoro committed
77
  ,codaPkg = FALSE, clearWD=FALSE
matbuoro's avatar
matbuoro committed
78
  #,debug=TRUE
matbuoro's avatar
matbuoro committed
79
  ,working.directory=paste(work.dir,"bugs",sep="/")
matbuoro's avatar
matbuoro committed
80
81
)

matbuoro's avatar
matbuoro committed
82
83
84
## cleaning
system("rm bugs/CODA*")

matbuoro's avatar
matbuoro committed
85
86
### Save inits ###
# save last values for inits
matbuoro's avatar
matbuoro committed
87
88
89
90
# inits <- fit$last.values
# if(site == "Nivelle") {
#   save(inits,file=paste('inits/inits_',stade,year,'.Rdata',sep=""))
#   }
matbuoro's avatar
matbuoro committed
91

matbuoro's avatar
matbuoro committed
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119

######### 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
120
121
save(fit,file=paste('results/Results_',stade,"_",year,'.RData',sep=""))
write.table(fit$summary,file=paste('results/Results_',stade,"_",year,'.csv',sep=""),sep=";")
matbuoro's avatar
matbuoro committed
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
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
     
#------------------------------------------------------------------------------
# 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")
  gelman.diag(fit.mcmc[,which(varnames(fit.mcmc)%in%parameterstotest)])
}


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]) 
#}
dev.off()


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