lmer.run.nolog.R 11.7 KB
Newer Older
Georges Kunstler's avatar
Georges Kunstler committed
1
2
###########################
###########################
3
### FUNCTION TO RUN LMER ESTIMATION WITH NO logBA
Georges Kunstler's avatar
Georges Kunstler committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
library(lme4)


get.ecoregions.for.set <- function(set, base.dir = "./output/processed/"){
  sub(paste(base.dir,set,"/",sep=""),"",list.dirs(paste(base.dir,set,sep="")))[-1]
}

run.models.for.set.all.traits  <- function(set,model.file,fun.model,  traits =
         c("SLA", "Wood.density","Max.height","Leaf.N","Seed.mass"),type.filling, std,...){
  for(trait in traits)
   run.multiple.model.for.set.one.trait(model.file,fun.model, trait, set, type.filling=type.filling, std=std,...)
}

run.multiple.model.for.set.one.trait <- function(model.files,fun.model, trait, set,type.filling, ecoregions = get.ecoregions.for.set(set), std, ...){
  for (m in model.files)
Georges Kunstler's avatar
Georges Kunstler committed
19
      try(run.model.for.set.one.trait (m, fun.model,trait, set,type.filling=type.filling,std=std, ...))
Georges Kunstler's avatar
Georges Kunstler committed
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
}


run.model.for.set.one.trait <- function(model.file,fun.model, trait, set,type.filling, ecoregions = get.ecoregions.for.set(set), std, ...){
    fun.model <- match.fun(fun.model)
  for (e in ecoregions)
    try(fun.model(model.file, trait, set, e, type.filling=type.filling,std=std,...))
}


#=====================================================================
# Run lmer() (in package lme4) for one ecoregion, one trait, one model
#=====================================================================
model.files.lmer.1 <- c("R/analysis/model.lmer/model.lmer.LOGLIN.E.R",
                 "R/analysis/model.lmer/model.lmer.LOGLIN.R.R",
                 "R/analysis/model.lmer/model.lmer.LOGLIN.ER.R")
model.files.lmer.2 <- c("R/analysis/model.lmer/model.lmer.LOGLIN.nocomp.R",
                 "R/analysis/model.lmer/model.lmer.LOGLIN.AD.R",
                 "R/analysis/model.lmer/model.lmer.LOGLIN.simplecomp.R")

model.files.lmer.Tf.1 <- c("R/analysis/model.lmer/model.lmer.LOGLIN.E.Tf.R",
                 "R/analysis/model.lmer/model.lmer.LOGLIN.R.Tf.R",
                 "R/analysis/model.lmer/model.lmer.LOGLIN.ER.Tf.R")
model.files.lmer.Tf.2 <- c("R/analysis/model.lmer/model.lmer.LOGLIN.nocomp.Tf.R",
                 "R/analysis/model.lmer/model.lmer.LOGLIN.AD.Tf.R",
                 "R/analysis/model.lmer/model.lmer.LOGLIN.HD.Tf.R",
                 "R/analysis/model.lmer/model.lmer.LOGLIN.simplecomp.Tf.R")


fun.test.if.multi.census <- function(data){
return("tree.id" %in% names(data))
}

fun.call.lmer <- function(formula,df.lmer){
   lmer.output <- lmer(formula=formula,data=df.lmer,REML = FALSE)
   return(lmer.output)
}


fun.call.lmer.and.save <- function(formula,df.lmer,path.out,std){
   lmer.output <- lmer(formula=formula,data=df.lmer,REML = FALSE)
   print(summary(lmer.output))
if(std) {   saveRDS(lmer.output,file=file.path(path.out, "results.no.std.nolog.rds"))
  }else{saveRDS(lmer.output,file=file.path(path.out, "results.nolog.rds"))
  }
}

run.lmer <- function (model.file, trait, set, ecoregion,
                      min.obs=10, sample.size=NA,
                      type.filling,std) {
    require(lme4)
    source(model.file, local = TRUE)
    model <- load.model()
    #= Path for output
    path.out <- output.dir.lmer(model$name, trait, set,
                                ecoregion,type.filling=type.filling)
    print(path.out)
    dir.create(path.out, recursive=TRUE, showWarnings=FALSE)
    cat("run lmer for model",model.file," for set",
         set,"ecoregion",ecoregion,"trait",
         trait,"\n")
      df.lmer <- load.and.prepare.data.for.lmer(trait, set, ecoregion,
                                           min.obs, sample.size,
                                         type.filling=type.filling,std=std) # return a DF
     test.if.multi.census <- fun.test.if.multi.census(df.lmer)
     cat("Ok data with Nobs",nrow(df.lmer),
         "multiple census", test.if.multi.census ,"\n")
        #= Run model
      if(test.if.multi.census){
        fun.call.lmer.and.save(formula=model$lmer.formula.tree.id,df.lmer,path.out,std=std)
      }else{
        fun.call.lmer.and.save(formula=model$lmer.formula,df.lmer,path.out,std=std)
      }
}


## ## new function to compute boot ci
##  fun.ci.boot <- function(df.lmer,formula,path.out,level=0.95,nsim=500){
##      require(boot)
##      require(multicore)
##         bb <- boot(data=df.lmer, statistic=boot.fun,R= nsim,formula=formula)
##         bci <- lapply(seq_along(bb$t0), boot.out = bb, boot::boot.ci, 
##             type = "perc", conf = level)
##         citab <- t(sapply(bci, function(x) x[["percent"]][4:5]))
##         a <- (1 - level)/2
##         a <- c(a, 1 - a)
##         pct <- paste('CI',round(a, 3),sep='.')
##         dimnames(citab) <- list(names(bb[["t0"]]), pct)
##         saveRDS(citab,file=file.path(path.out, "results.ci.no.std.rds"))
## }

## boot.fun <- function(data, indices, formula){
##  df.lmer <- data[indices,] # select obs. in bootstrap sample
##  res <- fun.call.lmer(formula=formula,df.lmer)
##  fixef(res)
##  }



#========================================================================

output.dir.lmer <- function (model, trait, set, ecoregion,type.filling) {
  file.path("output/lmer", set,ecoregion,trait,type.filling,model)
}


#============================================================
# Function to prepare data for lmer
#============================================================
load.and.prepare.data.for.lmer <- function(trait, set, ecoregion,
                                  min.obs, sample.size, type.filling,  
                                  base.dir = "output/processed/",std){
    ### load data
if(std) {   data.tree.tot <- read.csv(file.path(base.dir, set,ecoregion,"data.tree.tot.no.std.csv"),
                              stringsAsFactors = FALSE)}else{
    data.tree.tot <- read.csv(file.path(base.dir, set,ecoregion,"data.tree.tot.csv"),
                              stringsAsFactors = FALSE)}

    fun.data.for.lmer(data.tree.tot,trait,type.filling=type.filling)
}

Georges Kunstler's avatar
Georges Kunstler committed
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
## remove outlier following Condit approach
fun.remove.outlier.Condit <- function(data.tree){

data.tree[['G']][!(trim.positive.growth(data.tree[['G']]) &
trim.negative.growth(dbh1=data.tree[['D']]*10,
                     dbh2=data.tree[['D']]*10 +
                     data.tree[['year']]*data.tree[['G']]))] <- NA

data.tree[['BA.G']][!(trim.positive.growth(data.tree[['G']]) &
trim.negative.growth(data.tree[['D']]*10,dbh2=data.tree[['D']]*10 +
                     data.tree[['year']]*data.tree[['G']]))] <- NA

return(data.tree)
}


Georges Kunstler's avatar
Georges Kunstler committed
157
fun.select.data.for.analysis <- function(data.tree,abs.CWM.tntf,perc.neigh,BATOT,min.obs,
Georges Kunstler's avatar
Georges Kunstler committed
158
159
160
                                         min.perc.neigh=0.90,min.BA.G=-60,max.BA.G=500){


Georges Kunstler's avatar
Georges Kunstler committed
161
162
163
## remove tree with NA
data.tree <- subset(data.tree,subset=(!is.na(data.tree[["BA.G"]])) &
                                     (!is.na(data.tree[["D"]])) )
Georges Kunstler's avatar
Georges Kunstler committed
164
165
166
167
## remove outlier
data.tree <- fun.remove.outlier.Condit(data.tree)


Georges Kunstler's avatar
Georges Kunstler committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
## remove tree with zero
data.tree <- subset(data.tree,subset=data.tree[["BA.G"]]>min.BA.G & data.tree[["BA.G"]]<max.BA.G &
                                     data.tree[["D"]]>9.9)             
## select species with no missing traits 
data.tree <- data.tree[(!is.na(data.tree[[abs.CWM.tntf]]) &
                    !is.na(data.tree[[BATOT]])),]
# select  species with minimum obs    
data.tree <- subset(data.tree,subset=data.tree[["sp"]] %in%
                    names(table(factor(data.tree[["sp"]])))[table(factor(data.tree[["sp"]]))>min.obs])
# select  obs abov min perc.neigh   
data.tree <- subset(data.tree,subset=data.tree[[perc.neigh]] > min.perc.neigh & !is.na(data.tree[[perc.neigh]]))
return(data.tree)
}

fun.center.and.standardized.var <- function(x){
return((x-mean(x))/sd(x))
}

### get variables for lmer
Georges Kunstler's avatar
Georges Kunstler committed
187
fun.get.the.variables.for.lmer.tree.id <- function(data.tree,BATOT,CWM.tn,abs.CWM.tntf,tf,min.BA.G=60){
Georges Kunstler's avatar
Georges Kunstler committed
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
logG <- fun.center.and.standardized.var(log(data.tree[["BA.G"]]+min.BA.G))
logD <- log(data.tree[["D"]])
species.id <- unclass(factor(data.tree[["sp"]]))
tree.id <- unclass(factor(data.tree[["tree.id"]]))
plot.species.id <- unclass(factor(paste(data.tree[["plot"]],data.tree[["sp"]],sep="")))
#= multiply CWMs by BATOT
sumTnTfBn.abs <- data.tree[[abs.CWM.tntf]]*data.tree[[BATOT]]
sumTnBn <- data.tree[[CWM.tn]]*data.tree[[BATOT]]
sumTfBn <- data.tree[[tf]]*data.tree[[BATOT]]
sumTnTfBn.diff <- sumTnBn-sumTfBn
sumBn <- data.tree[[BATOT]]
return(data.frame(logG=logG,
            logD=logD,
            species.id=species.id,
            tree.id=tree.id,
            plot.species.id=plot.species.id,
            sumTnTfBn.diff=sumTnTfBn.diff,
            sumTnTfBn.abs=sumTnTfBn.abs,
            Tf=data.tree[[tf]],
            sumTnBn=sumTnBn,
            sumTfBn=sumTfBn,
            sumBn=sumBn))
}

Georges Kunstler's avatar
Georges Kunstler committed
212
fun.get.the.variables.for.lmer.no.tree.id <- function(data.tree,BATOT,CWM.tn,abs.CWM.tntf,tf,min.BA.G=60){
Georges Kunstler's avatar
Georges Kunstler committed
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
logG <- fun.center.and.standardized.var(log(data.tree[["BA.G"]]+min.BA.G))
logD <- log(data.tree[["D"]])
species.id <- unclass(factor(data.tree[["sp"]]))
tree.id <- unclass(factor(data.tree[["tree.id"]]))
plot.species.id <- unclass(factor(paste(data.tree[["plot"]],data.tree[["sp"]],sep="")))
#= multiply CWMs by BATOT
sumTnTfBn.abs <- data.tree[[abs.CWM.tntf]]*data.tree[[BATOT]]
sumTnBn <- data.tree[[CWM.tn]]*data.tree[[BATOT]]
sumTfBn <- data.tree[[tf]]*data.tree[[BATOT]]
sumTnTfBn.diff <- sumTnBn-sumTfBn
sumBn <- data.tree[[BATOT]]
return(data.frame(logG=logG,
            logD=logD,
            species.id=species.id,
            plot.species.id=plot.species.id,
            sumTnTfBn.diff=sumTnTfBn.diff,
            sumTnTfBn.abs=sumTnTfBn.abs,
            Tf=data.tree[[tf]],
            sumTnBn=sumTnBn,
            sumTfBn=sumTfBn,
            sumBn=sumBn))
}

#============================================================
# Function to prepare data for lmer with new CWM data
# that will be used in a simple linear model
#============================================================
fun.data.for.lmer <-  function(data.tree,trait,min.obs=10,type.filling='species') {
if(! trait %in%  c("SLA", "Leaf.N","Seed.mass","SLA","Wood.density","Max.height")) stop("need trait to be in SLA Leaf.N Seed.mass SLA Wood.density or  Max.height ")
# get vars names
CWM.tn <- paste(trait,"CWM",'fill',sep=".")
abs.CWM.tntf <- paste(trait,"abs.CWM",'fill',sep=".")
tf <- paste(trait,"focal",sep=".")
BATOT <- "BATOT"
perc.neigh <- paste(trait,"perc",type.filling,sep=".")
data.tree <- fun.select.data.for.analysis(data.tree,abs.CWM.tntf,perc.neigh,BATOT,min.obs)
#= DATA LIST FOR JAGS
if (length(table(table(data.tree[["tree.id"]])))>1){
lmer.data <- fun.get.the.variables.for.lmer.tree.id(data.tree,BATOT,CWM.tn,abs.CWM.tntf,tf)
}
if (length(table(table(data.tree[["tree.id"]])))<2){
lmer.data <- fun.get.the.variables.for.lmer.no.tree.id(data.tree,BATOT,CWM.tn,abs.CWM.tntf,tf)
}
    return(lmer.data)
}



Georges Kunstler's avatar
Georges Kunstler committed
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
## remove growth outliers

##' .. remove too negative growth based on Condit R package with param fitted to BCI ..
##'
##' .. taken from trim.growth function in CTFS.R ..
##' @title trim.negative.growth
##' @param dbh1 in mm
##' @param dbh2 in mm
##' @param slope not to be changed
##' @param intercept 
##' @param err.limit 
##' @return a vector TRUE FALSE with FALSE outlier to be removed
##' @author Kunstler
trim.negative.growth <- function(dbh1,dbh2,slope=0.006214,
                        intercept=.9036,err.limit=5){
stdev.dbh1 <- slope*dbh1+intercept
bad.grow <- which(dbh2<=(dbh1-err.limit*stdev.dbh1))
accept <- rep(TRUE,length(dbh1))
accept[bad.grow] <- FALSE
accept[is.na(dbh1) | is.na(dbh2) | dbh2<=0 | dbh1<=0] <- FALSE
return(accept)
}

##' .. remove too high growth ..
##'
##' .. taken from trim.growth in Condit CTFS R package ..
##' @title trim.positive.growth
##' @param growth in mm
##' @param maxgrow in mm 
##' @return TRUE FALSE vector with FALSE outlier
##' @author Kunstler
trim.positive.growth <- function(growth,maxgrow=75){
bad.grow <- which(growth>maxgrow)
accept <- rep(TRUE,length(growth))
accept[bad.grow] <- FALSE
accept[is.na(growth)] <- FALSE
return(accept)
}