test-analyse-dyn.Rmd 10.3 KB
Newer Older
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
1
---
2
title: "test arctic analyse"
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
3 4 5
author: "Isabelle Boulangeat"
date: "6/01/2019"
output: html_document
6 7
editor_options: 
  chunk_output_type: console
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
8 9 10 11 12 13
---

# Prepare datasets

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, eval=TRUE)
14 15
library(dplyr)
library(ggplot2)
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
16 17 18 19 20 21 22 23 24
```
## Load climate

```{r}
temp = read.table("shrubhub/ARCfunc_timeseries_temp.txt", h=T, sep="\t", encoding = "UTF-8", comment.char="", quote = "")
precip = read.table("shrubhub/ARCfunc_timeseries_prec.txt", h=T, sep="\t", encoding = "UTF-8", comment.char="", quote = "")

climato = read.table("shrubhub/TVC_SITE_SUBSITE_UPDATED2016_snow_GSL_GST_CHELSAclimatologies.txt", h=T, sep="\t", encoding = "UTF-8", comment.char="", quote = "")
climato$SiteSubsite = paste(climato$SITE, climato$SUBSITE, sep=":")
25 26 27
# climato_zeroNA = as.matrix(climato[,grep("GST", names(climato))])
# climato_zeroNA[which(is.na(climato_zeroNA[]))] = 0
# climato[,grep("GST", names(climato))] = climato_zeroNA
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
28 29
```

30
## Load species cover data
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
```{r, fig=TRUE}
load("coverc_sub.rdata")
hist(coverc.sub$COVER)
summary(coverc.sub$COVER)
```

## Filter out treatment plots

```{r}
cover.sub = coverc.sub[which(coverc.sub$TRTMT =="CTL"),]
```

## filter out un-repeated plots

```{r, fig=TRUE}
cover.sub = cover.sub[which(cover.sub$RepeatedPlots ==1),]
hist(asin(sqrt(cover.sub$COVER/100)), breaks =21, col = "lightblue")
summary(cover.sub$COVER)
```

51 52

## filter out years > 2014 because of missing in climatologies
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
53
```{r, fig=TRUE}
54
cover.dom = cover.sub[which(cover.sub$YEAR<2014),]
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
55 56 57 58 59 60
```

## create species-specific dataset

```{r}
SPECIES = "Vaccinium vitis-idaea"
61
SPECIES = "Betula nana"
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
62 63 64 65 66 67 68
# SPECIES = "Salix arctica"
# SPECIES = "Salix pulchra"
# SPECIES = "Vaccinium uliginosum"
# ----

source("R_fct/shape_data.r")

69 70
spdat = create_dataset(SPECIES, cover.dom, climato=climato)
#spdat = create_dataset(SPECIES, cover.dom, sp.distri.path= "ArcticShrubCurrent/Betula.nana_cur_pc_n.img", climato=climato)
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
71 72
```
The steps of `create_dataset`:
73
- only subsites where the species have been seen (then ok for N=1)
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
74 75 76 77
- extract plot info
- build transition table
- merge with plot info
- calculate interval (years)
78
- tag transition types
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
79 80 81
- combine with climate (5 years earlier average)
- merge all

82 83 84 85 86 87 88
## anomalies
```{r}
spdat$GSL_anom = spdat$GSL-spdat$GSL_av
spdat$GST_anom = spdat$GST-spdat$GST_av
spdat$snowDays_anom = spdat$snowDays-spdat$snow_days_av
```

Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
89 90 91 92
## some checks

```{r}
table(spdat$trType)
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
nrow(spdat)
```
Here it means that 617 successive observations of presences are outside of the species distribution range!!
```{r}
#unique(spdat[which(spdat$trType=="present"&spdat$distriArea==0),c("SUBSITE", "y0", "y1", "st0", "st1", "SoilMoist", "distriArea")])
```

# Data exploration

```{r, fig=TRUE, fig.width=10}
spdat$trType = factor(spdat$trType)
levels(spdat$trType) <- c("AA", "COLO", "EXT", "PP")

bp <- ggplot(na.omit(spdat), aes(fill=trType, y=snowDays, x=trType)) +
    geom_point() +
    ggtitle("Snow") +
    facet_wrap(~SUBSITE) +
    theme(legend.position="none") +
    xlab("")
bp
```

```{r, fig=TRUE, fig.width=10}
bp <- ggplot(na.omit(spdat), aes(fill=trType, y=GST, x=trType)) +
    geom_point() +
    ggtitle("GST") +
    facet_wrap(~SUBSITE) +
    theme(legend.position="none") +
    xlab("")
bp
```

```{r, fig=TRUE, fig.width=10}
bp <- ggplot(na.omit(spdat), aes(fill=trType, y=GSL, x=trType)) +
    geom_point() +
    ggtitle("GSL") +
    facet_wrap(~SUBSITE) +
    theme(legend.position="none") +
    xlab("")
bp
```

```{r, fig=TRUE, fig.width=10}
bp <- ggplot(na.omit(spdat), aes(fill=trType, y=SoilMoist, x=trType)) +
    geom_point() +
    ggtitle("GSL") +
    facet_wrap(~SUBSITE) +
    theme(legend.position="none") +
    xlab("")
bp
```

Events observed total
```{r, fig=TRUE, fig.width=10}
tab = spdat %>%
  group_by(SUBSITE) %>% count(trType)

bp <- ggplot(tab, aes(fill=trType, y=n, x=trType)) +
    geom_bar(position="dodge", stat="identity") +
    ggtitle("Events") +
    facet_wrap(~SUBSITE) +
    theme(legend.position="none") +
    xlab("")
bp
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
157 158
```

159 160 161 162 163 164 165 166 167 168 169 170 171
Events observed change
```{r, fig=TRUE, fig.width=10}
tab2 = tab[which(tab$trType%in%c("COLO", "EXT")),]
bp <- ggplot(tab2, aes(fill=trType, y=n, x=trType)) +
    geom_bar(position="dodge", stat="identity") +
    ggtitle("Events") +
    facet_wrap(~SUBSITE) +
    theme(legend.position="none") +
    xlab("")
bp
```


Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
172 173 174 175 176 177 178 179 180 181
# Fit

## Cleaning-Ajustments

```{r, fig=TRUE}
hist(spdat$interval)
```

```{r}
spdat = spdat[spdat$interval<10,]
182 183 184 185 186
#spdat = unique(spdat[, -which(colnames(spdat)=="TotalCover")])
#spdat = na.omit(spdat)
# spdat = spdat[-which(is.nan(spdat$distriArea)),]
# spdat = spdat[-which(spdat$distriArea==0),]
selectVars = c("snowDays", "GSL", "GST", "SoilMoist", "TotalCover")
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
187 188

spdat$SoilMoist = factor(spdat$SoilMoist)
189
levels(spdat$SoilMoist) = c(-1,0,1)
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
190 191 192 193 194 195 196 197 198 199 200 201
spdat$SoilMoist = as.numeric(as.character(spdat$SoilMoist))
head(spdat)
dim(spdat)
```

## Build data object for LD fit

```{r}
require(LaplacesDemon)
source("R_fct/model_fct.r")

nvars = length(selectVars)
202 203
dat.ext = scale(spdat[which(spdat$trType%in%c("PP", "EXT")),selectVars])
dat.ext[,"SoilMoist"] = spdat[which(spdat$trType%in%c("PP", "EXT")),"SoilMoist"]
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
204

205 206
parm.names.ext = as.parm.names(list(aE=rep(0, 1+nvars)))
nbetas.ext = length(parm.names.ext)
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
207

208
MyData.ext <- list(N = nrow(dat.ext), dat=dat.ext, mon.names = c("logLik") , parm.names= parm.names.ext,
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
209
var.aE = 1:(nvars),
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
aE.pos = grep("aE", parm.names.ext),
PA.pos = spdat$trType[which(spdat$trType%in%c("PP", "EXT"))]=="EXT",
PP.pos = spdat$trType[which(spdat$trType%in%c("PP", "EXT"))]=="PP",
invlogit_ = invlogit_,
itime = spdat$interval[which(spdat$trType%in%c("PP", "EXT"))],
nbetas = nbetas.ext)

#--
dat.colo = scale(spdat[which(spdat$trType%in%c("AA", "COLO")),selectVars])
dat.colo[,"SoilMoist"] = spdat[which(spdat$trType%in%c("AA", "COLO")),"SoilMoist"]

parm.names.colo = as.parm.names(list(aC=rep(0, 1+nvars)))
nbetas.colo = length(parm.names.colo)

MyData.colo<- list(N = nrow(dat.colo), dat=dat.colo, mon.names = c("logLik") , parm.names= parm.names.colo,
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
225
var.aC = 1:(nvars),
226 227 228
aC.pos = grep("aC", parm.names.colo),
AP.pos = spdat$trType[which(spdat$trType%in%c("AA", "COLO"))]=="COLO",
AA.pos = spdat$trType[which(spdat$trType%in%c("AA", "COLO"))]=="AA",
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
229
invlogit_ = invlogit_,
230 231 232
density = rep(1, nrow(dat.colo)),
itime = spdat$interval[which(spdat$trType%in%c("AA", "COLO"))],
nbetas = nbetas.colo)
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
233 234 235 236

```

## Fit
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
```{r, eval=TRUE, fig=TRUE}
summary(dat.colo)
dat.colo = data.frame(dat.colo)
dat.colo$colo.event = as.numeric(MyData.colo$AP.pos)
colo.mod = glm(colo.event~ snowDays + TotalCover, family = "binomial", data = dat.colo)

colo.mod = glm(colo.event~ (snowDays + GSL + GST + TotalCover) * SoilMoist, data = dat.colo)
require(MASS)
stepMod.colo  = stepAIC(colo.mod, direction = "both")
summary(stepMod.colo)

pred = predict(stepMod.colo,new=dat.colo,"response")
require(fmsb)
(R2 = NagelkerkeR2(stepMod.colo)$R2)
require(ROCR)
perf = performance(prediction(pred, dat.colo$colo.event), "auc")
(AUC = perf@y.values[[1]])
(coeff = summary(stepMod.colo)$coefficients)
(vars = rownames(coeff)[-1])
(effect = coeff[-1,1])
barplot(effect)
# pval = coeff[-1,4]
```

```{r, fig=TRUE}

summary(dat.ext)
dat.ext = data.frame(dat.ext)
dat.ext$ext.event = as.numeric(MyData.ext$PA.pos)
ext.mod = glm(ext.event~  TotalCover, family = "binomial", data = dat.ext)
summary(ext.mod)

require(MASS)
stepMod.ext  = stepAIC(ext.mod, direction = "both")
summary(stepMod.ext)

pred = predict(stepMod.ext,new=dat.ext,"response")
require(fmsb)
(R2 = NagelkerkeR2(stepMod.ext)$R2)
require(ROCR)
perf = performance(prediction(pred, dat.ext$ext.event), "auc")
(AUC = perf@y.values[[1]])
(coeff = summary(stepMod.ext)$coefficients)
(vars = rownames(coeff)[-1])
(effect = coeff[-1,1])
barplot(effect)
```
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
284 285 286 287

```{r, eval=FALSE}
source("R_fct/fit_LP.r")
test_model(MyData, loglik_fct)
288 289 290 291 292 293
test_model(MyData.ext, ext_model)
test_model(MyData.colo, colo_model)
#save.image("test-analyse.RData")
#0--
load("test-analyse.RData")
library(LaplacesDemon)
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
294 295 296 297 298
#----
ffit = first.fit(MyData, loglik_fct)
Consort(ffit)
sfit = second.fit(MyData, ffit,loglik_fct)
Consort(sfit)
299
tfit = third.fit(MyData, sfit,loglik_fct)
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
300
Consort(tfit)
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
save.image(file= "outputs/tfit_BN.RData")
#---
ffit = first.fit(MyData.ext, ext_model)
Consort(ffit)
sfit = second.fit(MyData.ext, ffit,ext_model)
Consort(sfit)
tfit = third.fit(MyData.ext, sfit,ext_model)
Consort(tfit)
save.image(file= "outputs/tfit_ext_BN.RData")
#---
ffit = first.fit(MyData.colo, colo_model)
Consort(ffit)
sfit = second.fit(MyData.colo, ffit,colo_model)
Consort(sfit)
tfit = third.fit(MyData.colo, sfit,colo_model)
Consort(tfit)
save.image(file= "outputs/tfit_colo_BN.RData")

```

## plot variables
```{r, fig=TRUE, fig.width=8}
load("outputs/tfit_BN.RData")
source("R_fct/graphs.r")
efCE = plot.effects(tfit, selectVars)
efCE
```

```{r, fig=TRUE, fig.width=8}
load("outputs/tfit_ext_BN.RData")
eff_ext = plot.effects(tfit, selectVars)
eff_ext
```
```{r, fig=TRUE, fig.width=8}
load("outputs/tfit_colo_BN.RData")
eff_colo = plot.effects(tfit, selectVars)
eff_colo
```
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
339

340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
# ## compute lambda
 ```{r, fig=TRUE, eval=FALSE}
# mean.posterior.aC = Fit.mcmc$Summary2[1:6, "Mean"]
# mean.posterior.aE = Fit.mcmc$Summary2[7:12, "Mean"]
# library(dplyr)
# proj.dat = unique(spdat[, c("SUBSITE", "N", "SoilMoist", "y1")])
# Nlast = unlist(lapply(split(proj.dat, proj.dat$SUBSITE), function(x){x[which.max(x$y1),"N"]}))
# proj.dat = merge(unique(proj.dat[,-c(2,4)]), data.frame(SUBSITE = names(Nlast), N = Nlast))
# proj.dat_all = proj.dat.shape(proj.dat, year = 2012, climato)
# proj.dat_all$SoilMoist = factor(proj.dat_all$SoilMoist)
# levels(proj.dat_all$SoilMoist) = c(1:3)
# proj.dat_all$SoilMoist = as.numeric(as.character(proj.dat_all$SoilMoist))
# proj.dat_all = merge(proj.dat_all, unique(spdat[,c("distriArea","SUBSITE")]), by = "SUBSITE")
# 
# proj.dat_dat = proj.dat_all[,vars]
# proj.dat_dat = scale(proj.dat_dat, center = attributes(dat)$`scaled:center`, scale = attributes(dat)$`scaled:scale`)
# logit_alphaC = tcrossprod(mean.posterior.aC, as.matrix(cbind(rep(1, nrow(proj.dat)), proj.dat_dat)))
# logit_alphaE = tcrossprod(mean.posterior.aE, as.matrix(cbind(rep(1, nrow(proj.dat)), proj.dat_dat)))
# 
# aC.fct=as.vector(invlogit_(logit_alphaC, 1))
# aE.fct=as.vector(invlogit_(logit_alphaE, 1))
# 
# proj.dat_all$lambda = 1-aE.fct/aC.fct
# 
# bp <- ggplot(na.omit(proj.dat_all), aes(x=distriArea, y=lambda, group=distriArea)) +
#   geom_boxplot(alpha=0.3, width=0.2, outlier.size = 0) +
#   geom_point()
# bp
Boulangeat Isabelle's avatar
Boulangeat Isabelle committed
368
```