test.tree.CWM-fun.R 17.4 KB
Newer Older
1
################################
Georges Kunstler's avatar
Georges Kunstler committed
2
## function for test.tree.CWM
3
4
source("R/utils/plot.R")

Georges Kunstler's avatar
Georges Kunstler committed
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
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
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232

load.processed.data <- function(path,file.name="data.tree.tot.csv"){
    fname <- file.path(path,file.name )
    if(file.exists(fname)){
      data <- read.csv(fname, stringsAsFactors = FALSE)
      return(data)
  }else{return(NULL)}
}

load_all_processed_data <- function(set,pathdir){
  data <- list()
  ecocodes <- list_all_processed_data(set,pathdir)
     for (ecocode.select in ecocodes) {
    data[[ecocode.select]] <- load.processed.data(file.path(pathdir, set,ecocode.select))
     }
  data  
}

list_all_processed_data <- function(set,pathdir){
sub(paste(pathdir,"/",set,"/",sep=""),"",list.dirs(paste(pathdir,"/",set,sep="")))[-1]
}



## test range of data
fun.test.one.var.q <- function(t,t.q.01,t.q.9){
qq <- quantile(t,probs=c(0.1,0.9),na.rm=TRUE)
res <- (qq[1]<t.q.01) |(qq[2] >t.q.9)
return(res)
}

fun.test.one.var.data.q <- function(i,data,var.name,t.q.01.vec,t.q.9.vec){
fun.test.one.var.q(data[[var.name[i]]],t.q.01.vec[i],t.q.9.vec[i])
}


# test range D G BA.G 
fun.test.range.vars.q <- function(data.tree,set){
vars.name <-  c( "D",  "dead","G","BA.G")
t.q.01.vec <- c(9.9,0,-2,-80)
t.q.9.vec <- c(200,1,10,100)
vec.test <- sapply(1:4,fun.test.one.var.data.q,data.tree,vars.name,t.q.01.vec,t.q.9.vec)
if(any(vec.test))
  stop(paste("Var",
        paste(vars.name[vec.test],collapse=" ") ,
       "quantile 0.1 or 0.9 out of range for set",set))
}




############################
########## TEST FUNCTIONS
#################################

##### FOR PLOT TYPE DATA


## test functions for Wood density for one indiv
fun.test.CWM.plot.r <- function(data,data.TRAITS,data.tree){
    repeat{
      res <- fun.test.CWM.plot(data.t=data,data.TRAITS,data.tree)
      if(!is.na(res)){
        break
      }
    }
return(res)
}

## fun compute CWM for test
fun.compute.CWM.test.plot <- function(samp.id,samp.plot,data,data.TRAITS){
    BA.a <- BA.fun(data[["D"]][data[["obs.id"]]!=samp.id &
                                  data[["plot"]] ==samp.plot] ,
                   weights =data[["weights"]][data[["obs.id"]]!=samp.id &
                                  data[["plot"]] ==samp.plot])
    sp.a.f <- factor(data[["sp"]])[data[["obs.id"]]!=samp.id &
                                  data[["plot"]] ==samp.plot]
    BA.n <- tapply(BA.a,INDEX=sp.a.f,FUN=sum,na.rm=TRUE)
    BA.n.no0 <- BA.n[!is.na(BA.n)]
    sp.n <-  as.character(names(BA.n.no0))
    mat.t <- fun.trait.format(trait="Wood.density",traits.data=data.TRAITS,vec.sp=sp.n)
    res.fill <- sum(BA.n.no0*mat.t[,3])/sum(BA.n.no0)
return(res.fill)
}

sample.safe <- function(x,...){
if (length(x)==1){
    res <- sample(c(x,x),...)
}else{
res <- sample(x,...)
 }
return(res)
}


# test one random plot
fun.test.CWM.plot <- function(data.t,data.TRAITS,data.tree) {
     res <- NA
     # randomly select a census
     data <- subset(data.t,subset=data.t[["census"]] == sample.safe(unique(data.t[["census"]]),1))
     data.tree.t <- subset(data.tree,subset=data.tree[["census"]] == unique(data[["census"]]))
     # randomly select an individual
     samp.id <- sample.safe(data[["obs.id"]],1)
     samp.sp <-  data[["sp"]][data[["obs.id"]]==samp.id]
     samp.plot <-  data[["plot"]][data[["obs.id"]]==samp.id]
     if(!is.na(data.TRAITS[data.TRAITS[["sp"]]==samp.sp,"Wood.density.mean"]) &
          !data.TRAITS[data.TRAITS[["sp"]]==samp.sp,"Wood.density.genus"] &
          !is.na(data[["Wood.density.CWM.fill"]][data[["obs.id"]]==samp.id])) {
          test.focal <- all.equal(data.TRAITS[data.TRAITS[["sp"]]==samp.sp,"Wood.density.mean"],
               data[["Wood.density.focal"]][data[["obs.id"]]==samp.id])
          res.fill <- fun.compute.CWM.test.plot(samp.id,samp.plot,data.tree.t,data.TRAITS)
          test.cwm.fill <- all.equal(res.fill,data[["Wood.density.CWM.fill"]][data[["obs.id"]]==samp.id])
          res <- all(c(test.focal,test.cwm.fill)==TRUE)
          if (is.na(res.fill)) res <- NA
          }
     return(res)
     }

#################################
## test function XY type data set



fun.test.CWM.XY.r <- function(data,data.TRAITS,data.tree,Rlim){
    repeat{
      res <- fun.test.CWM.XY(data.r=data,data.TRAITS,data.tree,Rlim=Rlim)
      if(!is.na(res)){
        break
      }
    }
return(res)
}

 fun.compute.test <- function(obs.id.t, obs.id, xy.table, diam, sp, Rlim) {
        # compute distance to the focal tree
        dist.t <- as.vector(((outer(xy.table[obs.id == obs.id.t, "x"],
                                        xy.table[,"x"], FUN = "-"))^2
                                 + (outer(xy.table[obs.id == obs.id.t, "y"],
                                          xy.table[,"y"], FUN = "-"))^2))
        select <- (dist.t < Rlim^2) & obs.id !=obs.id.t 
        ### compute BA in radius Rlim
        res.BA.t <- tapply(BA.fun(diam[select], weights = 1/(pi * Rlim^2)), INDEX = sp[select],
            FUN = sum, na.rm = TRUE)
        res.BA.t[is.na(res.BA.t)] <- 0
        names.sp <- names(res.BA.t)
        res.BA.t <- as.vector(res.BA.t)
        names(res.BA.t) <- names.sp
        return((res.BA.t))
    }
    
fun.compute.CWM.trait.test <-  function(samp.id,data,Rlim,data.TRAITS){
## library(Rcpp)
## sourceCpp("R/process.data/georges.cpp")
## BA.a <- BA.fun(data[['D']], weights = 1/(pi * Rlim^2))
## i.t <- seq_len(length(obs.id))[obs.id==i]
## BA.n <- areas_by_species_within_neighbourhood(idx=i.t - 1L,
##               x=data[,"x"], y=data[,"y"], r=Rlim, d=BA.a, type=as.vector(sp.num) - 1L, n_types=sp.length)

    
    BA.n <- fun.compute.test(obs.id.t=samp.id, obs.id=data[["obs.id"]],
                             xy.table=as.matrix(subset(data,select=c("x","y"))),
                   diam=data[["D"]], sp=data[["sp"]], Rlim=Rlim)
    sp.n <- as.character(names(BA.n)[BA.n>0])
    BA.n <- BA.n[BA.n>0]
    mat.t <- fun.trait.format(trait="Wood.density",traits.data=data.TRAITS,vec.sp=sp.n)
    res.fill <- sum(BA.n * mat.t[,3])/sum(BA.n)
return(res.fill)
}


###################
   
fun.test.CWM.XY <- function(data.r,data.TRAITS,data.tree,Rlim){
    res <- NA
data.t <- subset(data.r,subset=data.r[["cluster"]] == sample.safe(unique(data.r[["cluster"]]),1))
data.tree.t <- subset(data.tree,subset=data.tree[["cluster"]] == unique(data.t[["cluster"]]))
# randomly select a census
data <- subset(data.t,subset=data.t[["census"]] == sample.safe(unique(data.t[["census"]]),1))
data.tree.d <- subset(data.tree.t,subset=data.tree.t[["census"]] == unique(data[["census"]]))

# randomly select an individual
samp.id <- sample.safe(data[["obs.id"]],1)
samp.sp <- data[["sp"]][data[["obs.id"]]==samp.id]
if(!is.na(data.TRAITS[data.TRAITS[["sp"]]==samp.sp,"Wood.density.mean"]) &
   !data.TRAITS[data.TRAITS[["sp"]]==samp.sp,"Wood.density.genus"] &
   !is.na(data[["Wood.density.CWM.fill"]][data[["obs.id"]]==samp.id])){
    test.focal <- all.equal(data.TRAITS[data.TRAITS[["sp"]]==samp.sp,"Wood.density.mean"] ,
                            data[["Wood.density.focal"]][data[["obs.id"]]==samp.id])
    res.fill <- fun.compute.CWM.trait.test(samp.id,data.tree.d,Rlim,data.TRAITS)
    test.cwm.fill <- all.equal(res.fill,data[["Wood.density.CWM.fill"]][data[["obs.id"]]==samp.id])
    res <- all(c(test.focal,test.cwm.fill)==TRUE)
    if(is.na(res.fill)) res <- NA
 }
 return(res)
}


### FUNCTION TO TEST IF CWM VALUE OK
fun.test.value.one.ecoregion.I <- function(data.CWM,set,ecocode.select,path.formatted = "output/formatted" ){
    data.tree <- read.csv(file.path(path.formatted, set, "tree.csv"), stringsAsFactors = FALSE)
    data.traits <- read.csv(file.path(path.formatted, set, "traits.csv"), stringsAsFactors = FALSE)
    data.traits <- fun.std.data(data.traits)
    # remove nas
    data.tree <- subset(data.tree, subset = !is.na(data.tree[["D"]]))
    data.tree <- subset(data.tree,subset=data.tree$ecocode==ecocode.select)
    # test if same dim
    if (nrow(data.CWM) !=length(data.tree[["obs.id"]])) stop("data.CWM not good dim")
    ### test CWM for Wood.density
    for (i in 1:10){
        if (!fun.test.CWM.plot.r(data.CWM,data.TRAITS=data.traits,data.tree=data.tree))
        stop(paste("CWM index for Wood.density WRONG for",set))
    }
}

fun.test.value.one.ecoregion.B <- function(data.CWM,set,ecocode.select,path.formatted = "output/formatted" ){
    data.tree <- read.csv(file.path(path.formatted, set, "tree.csv"), stringsAsFactors = FALSE)
    data.traits <- read.csv(file.path(path.formatted, set, "traits.csv"), stringsAsFactors = FALSE)
    data.traits <- fun.std.data(data.traits)
    # remove nas
    data.tree <- subset(data.tree, subset = !is.na(data.tree[["D"]]))
    data.tree <- subset(data.tree,subset=data.tree$ecocode==ecocode.select)
    ### test CWM for Wood.density
   for (i in 1:10){ test.res <- fun.test.CWM.XY.r(data.CWM,data.TRAITS=data.traits,data.tree=data.tree,Rlim=15)
    if (!test.res) stop(paste("CWM index for Wood.density WRONG for",set))
                }
}


233
#### compute description of each table
Georges Kunstler's avatar
Georges Kunstler committed
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
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
fun.perc.non.missing <- function(i,var.name,var.names.perc,data){
sel <- data[[var.names.perc[i]]]>0.9 & !is.na(data[[var.names.perc[i]]])
  return(  sum(!is.na((data[[var.name[i]]])[sel]))/length(data[[var.name[i]]][sel]))
}

fun.num.sup.0.9.sp <- function(i,var.name,var.names.perc,data){
return(sum(data[[var.names.perc[i]]]>0.9 & !is.na(data[[var.names.perc[i]]]) & !is.na(data[[var.name[i]]])))
}


fun.compute.percentage.species.genus <- function(data){

perc.gymno <- sum( data[['Phylo.group']]=='Gymnosperm' &
                 !is.na(data[['Phylo.group']]))/sum(!is.na(data[['Phylo.group']]))
perc.ev <- sum(data[['Pheno.T']]=='EV'
               &!is.na(data[['Pheno.T']]))/sum(!is.na(data[['Pheno.T']]))
    
traits.name <- c("Leaf.N","Seed.mass","SLA","Wood.density","Max.height")
var.name.sp <- paste(traits.name,"abs.CWM.species",sep=".")
var.name.genus <- paste(traits.name,"abs.CWM.genus",sep=".")
var.name.fill <- paste(traits.name,"abs.CWM.fill",sep=".")
var.name.perc.genus <- paste(traits.name,"perc.genus",sep=".")
var.name.perc.species <- paste(traits.name,"perc.species",sep=".")
perc.non.missing.sp <- lapply(1:length(var.name.sp),fun.perc.non.missing,var.name.sp,var.name.perc.species,data)
num.non.missing.sp <- lapply(1:length(var.name.fill),fun.num.sup.0.9.sp,var.name.fill,
                             var.name.perc.species,data)
num.non.missing.genus <- lapply(1:length(var.name.fill),fun.num.sup.0.9.sp,var.name.fill,
                                var.name.perc.genus,data)
perc.non.missing.genus <- lapply(1:length(var.name.sp),fun.perc.non.missing,
                                 var.name.genus,var.name.perc.genus,data)
perc.genus <- lapply(var.name.perc.genus,function(i,data) mean(data[[i]],na.rm=TRUE),data)
perc.species <- lapply(var.name.perc.species,function(i,data) mean(data[[i]],na.rm=TRUE),data)
perc.genus.ql <- lapply(var.name.perc.genus,function(i,data) quantile(data[[i]],probs=0.05,na.rm=TRUE),data)
perc.species.ql <- lapply(var.name.perc.species,function(i,data) quantile(data[[i]],probs=0.05,na.rm=TRUE),data)
perc.genus.qh <- lapply(var.name.perc.genus,function(i,data) quantile(data[[i]],probs=0.95,na.rm=TRUE),data)
perc.species.qh <- lapply(var.name.perc.species,function(i,data) quantile(data[[i]],probs=0.95,na.rm=TRUE),data)
vec.res <- c(nrow(data),perc.gymno,perc.ev,num.non.missing.sp,
             num.non.missing.genus,perc.non.missing.sp,perc.non.missing.genus,
             perc.genus,perc.species,perc.genus.ql,perc.species.ql,perc.genus.qh,perc.species.qh)
names(vec.res) <- c('num.obs','perc.gymno','perc.ev',paste(traits.name,"num.sp",sep="."),
                    paste(traits.name,"num.genus",sep="."),
                    var.name.sp,var.name.genus,var.name.perc.genus,var.name.perc.species,
                    paste(var.name.perc.genus,"ql",sep="."),paste(var.name.perc.species,"ql",sep="."),
                    paste(var.name.perc.genus,"qh",sep="."),paste(var.name.perc.species,"qh",sep="."))
return(vec.res)
}    


fun.test.set.ecocode.tree.CWM.I <- function(data,set,ecocode.select){
fun.test.value.one.ecoregion.I(data.CWM=data,set,ecocode.select)
fun.test.range.vars.q(data=data,set)
cat(set,ecocode.select,"OK \n")
}

fun.test.set.tree.CWM.I <- function(set,filedir){
  ecocodes <- list_all_processed_data(set,filedir)
  print(ecocodes)
  list.perc <- list()
     for (ecocode.select in ecocodes) {
    data.temp <- load.processed.data(file.path(filedir, set,ecocode.select))
    if(!is.data.frame(data.temp)) next;
    fun.test.set.ecocode.tree.CWM.I(data.temp,set,ecocode.select)
    list.perc[[ecocode.select]] <- fun.compute.percentage.species.genus(data.temp)
    fun.test.range.vars.q(data.temp,paste(set,ecocode.select))
     }
mat.perc <- do.call("rbind",list.perc)
df.perc <-  data.frame(set=rep(set,nrow(mat.perc)),ecocode=rownames(mat.perc),
                       mat.perc,stringsAsFactors = FALSE)
return(df.perc)
cat(set,"OK \n")
}

fun.test.set.ecocode.tree.CWM.B <- function(data,set,ecocode.select){
fun.test.value.one.ecoregion.B(data.CWM=data,set,ecocode.select)
fun.test.range.vars.q(data=data,set)
cat(set,ecocode.select,"OK \n")
}


fun.test.set.tree.CWM.B <- function(set,filedir){
  ecocodes <- list_all_processed_data(set,filedir)
  list.perc <- list()
     for (ecocode.select in ecocodes) {
    data.temp <- load.processed.data(file.path(filedir, set,ecocode.select))
    if(!is.data.frame(data.temp)) next;
    fun.test.set.ecocode.tree.CWM.B(data.temp,set,ecocode.select)
    list.perc[[ecocode.select]] <- fun.compute.percentage.species.genus(data.temp)
    fun.test.range.vars.q(data.temp,paste(set,ecocode.select))
     }
mat.perc <- do.call("rbind",list.perc)
df.perc <-  data.frame(set=rep(set,nrow(mat.perc)),ecocode=rownames(mat.perc),mat.perc)
return(df.perc)
cat(set,"OK \n")
}

## FUNCTION TO LOAD ALL SET IN ONE BIG DATA SET
fun.load.set.in.big.file <- function(set,filedir,type){
 ecocodes <- list_all_processed_data(set,filedir)
 # loqd first ecoregion
  ecocode.select <- ecocodes[1] 
  data.temp <- load.processed.data(file.path(filedir, set,ecocode.select),
                                   "data.tree.tot.global.csv")
 data.all <- data.frame(set=rep(set,nrow(data.temp)),
                        data.temp)
 ## other
 if (length(ecocodes)>1){
     for (ecocode.select in ecocodes[-1]) {
        data.temp <- load.processed.data(file.path(filedir, set,ecocode.select))
        data.temp <- data.frame(set=rep(set,nrow(data.temp)),
                        data.temp)
        data.all <- rbind(data.all,data.temp)
       }
 }


 if (type=='B'){
   data.all <- data.all[,!names(data.all) %in% c( "x" ,   "y" )]
  }
if (type=='I'){
  data.all <- data.all[,!names(data.all) %in% "weights"]
  }
return(data.all)
}    
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452


#### PLOT VAR PER SET

## plot hist of each var 
fun.hist.var <- function(data,var,...){
tryCatch(hist(data[[var]],xlab=var,main=unique(data[['set']]),...),
         warning=function(w) print('warnings'),
         error=function(e){print(paste(unique(data[['set']]),'do not have value for',var));
                           plot(0,0,main=unique(data[['set']]))})
 }   

fun.hist.var.set <- function(data,var,...){
par(mfrow=c(5,3),mar=c(4.5,3.5,0.5,0.5),mgp=c(1.5,0.5,0))
by(data,INDICES=data[['set']],FUN=fun.hist.var,var=var,xlim=range(data[[var]],na.rm=TRUE),...)
}

fun.plot.xy <- function(data,var.x,var.y,...){
tryCatch(plot(data[[var.x]],data[[var.y]],xlab=var.x,ylab=var.y,main=unique(data[['set']]),...),
         warning=function(w) print('warnings'),
         error=function(e){print(paste(unique(data[['set']]),'do not have value for',var.x,'or',var.y));
                           plot(0,0,main=unique(data[['set']]))})

 }   


fun.plot.xy.set <- function(data,var.x,var.y,...){
       par(mfrow=c(5,3),mar=c(4.5,3.5,0.5,0.5),mgp=c(1.5,0.5,0))
       by(data,INDICES=data[['set']],FUN=fun.plot.xy,var.x=var.x,var.y=var.y,
          xlim=range(data[[var.x]],na.rm=TRUE),
          ylim=range(data[[var.y]],na.rm=TRUE),...)
      } 


fun.plot.hist.trait.per.set <- function(data){
trait.name <- c("Leaf.N","Seed.mass","SLA","Wood.density","Max.height")
name.var <- c("focal",
              "CWM.fill",
              "abs.CWM.fill")
   for (i in name.var){
      for (t in trait.name){
       var.temp <- paste(t,i,sep=".")
       to.pdf(fun.hist.var.set(data,var=var.temp),
              paste("figs/test.processed/fig",t,i,"pdf",sep="."))
      } 
    }
}


## 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)
}    


#####
## function compute FD per plot
## TODO
fun.compute.sd.var.cluster <- function(data,var){
cluster.unique.id <- paste(data[['set'],data[['ecocode']],data[['cluster']])
tapply(data[[var]],INDEX=cluster.unique.id,FUN=sd,na.rm=TRUE)       
}