glmer.run.R 8.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
###########################
###########################
### FUNCTION TO RUN GLMER ESTIMATION
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, ...){
  for(trait in traits)
   run.multiple.model.for.set.one.trait(model.file,fun.model, trait, set, type.filling=type.filling, ...)
}

run.multiple.model.for.set.one.trait <- function(model.files,fun.model, trait, set,type.filling, ecoregions = get.ecoregions.for.set(set),  ...){
  for (m in model.files)
    try(run.model.for.set.one.trait (m, fun.model,trait, set,type.filling=type.filling, ...))
}


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


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

model.files.glmer.Tf.1 <- c("R/analysis/model.glmer/model.glmer.LOGLIN.E.Tf.R",
41
                 "R/analysis/model.glmer/model.glmer.LOGLIN.R.Tf.R",
42
43
44
                 "R/analysis/model.glmer/model.glmer.LOGLIN.ER.Tf.R")
model.files.glmer.Tf.2 <- c("R/analysis/model.glmer/model.glmer.LOGLIN.nocomp.Tf.R",
                 "R/analysis/model.glmer/model.glmer.LOGLIN.AD.Tf.R",
45
                 "R/analysis/model.glmer/model.glmer.LOGLIN.HD.Tf.R",
46
47
48
49
50
51
52
53
54
55
56
57
58
                 "R/analysis/model.glmer/model.glmer.LOGLIN.simplecomp.Tf.R")


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

fun.call.glmer.and.save <- function(formula,df.lmer,path.out){
   Start <- Sys.time()
   glmer.output <- glmer(formula=formula,data=df.lmer,family=binomial)
   end <- Sys.time()
   print(end - Start)
   print(summary(glmer.output))
59
   saveRDS(glmer.output,file=file.path(path.out, "glmer.results.no.std.rds"))
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
}

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


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


#============================================================
# Function to prepare data for lmer
#============================================================
load.and.prepare.data.for.glmer <- function(trait, set, ecoregion,
                                  min.obs, sample.size, type.filling,  
                                  base.dir = "output/processed/"){
    ### load data
98
    data.tree.tot <- read.csv(file.path(base.dir, set,ecoregion,"data.tree.tot.no.std.csv"), stringsAsFactors = FALSE)
99
100
101
102
103
104
105
106
107
108
    fun.data.for.glmer(data.tree.tot,trait,type.filling=type.filling)
}

fun.select.data.for.analysis <- function(data.tree,abs.CWM.tntf,perc.neigh,BATOT,min.obs,
                                         min.perc.neigh=0.90,min.BA.G=-50,max.BA.G=150){
## remove tree with NA
data.tree <- subset(data.tree,subset=(!is.na(data.tree[["dead"]])) &
                                     (!is.na(data.tree[["D"]])) )
## remove tree with zero
data.tree <- subset(data.tree,subset=data.tree[["D"]]>9.9)             
109
## select species with missing traits 
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
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
185
186
187
188
189
190
191
192
193
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
fun.get.the.variables.for.glmer.tree.id <- function(data.tree,BATOT,CWM.tn,abs.CWM.tntf,tf,min.BA.G=50){
dead <- data.tree[["dead"]]
logD <- fun.center.and.standardized.var(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(dead=dead,
            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))
}

fun.get.the.variables.for.glmer.no.tree.id <- function(data.tree,BATOT,CWM.tn,abs.CWM.tntf,tf,min.BA.G=50){
dead <- data.tree[["dead"]]
logD <- fun.center.and.standardized.var(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(dead=dead,
            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.glmer <-  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',"log",sep=".")
abs.CWM.tntf <- paste(trait,"abs.CWM",'fill',"log",sep=".")
tf <- paste(trait,"focal",sep=".")
BATOT <- "BATOT.log"
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
glmer.data <- fun.get.the.variables.for.glmer.no.tree.id(data.tree,BATOT,CWM.tn,abs.CWM.tntf,tf)
    return(glmer.data)
}