/
clade_continuous.R
408 lines (387 loc) · 13.6 KB
/
clade_continuous.R
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
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
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
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
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
#' Influential Clade Detection - Trait Evolution Continuous Characters
#'
#' Fits models for trait evolution of continuous characters,
#' detecting influential clades
#'
#' @param data Data frame containing species traits with row names matching tips
#' in \code{phy}.
#' @param phy A phylogeny (class 'phylo') matching \code{data}.
#' @param model The evolutionary model (see Details).
#' @param trait.col The column in the provided data frame which specifies the
#' trait to analyse (which should be a factor with two level)
#' @param clade.col The column in the provided data frame which specifies the
#' clades (a character vector with clade names).
#' @param n.species Minimum number of species in a clade for the clade to be
#' included in the leave-one-out deletion analysis. Default is \code{5}.
#' @param n.sim Number of simulations for the randomization test.
#' @param bounds settings to constrain parameter estimates. See \code{\link[geiger]{fitContinuous}}
#' @param n.cores number of cores to use. If 'NULL', number of cores is detected.
#' @param track Print a report tracking function progress (default = TRUE)
#' @param ... Further arguments to be passed to \code{\link[geiger]{fitContinuous}}
#' @details
#' This function sequentially removes one clade at a time,
#' fits a model of continuous character evolution using \code{\link[geiger]{fitContinuous}},
#' repeats this many times (controlled by \code{n.sim}), stores the results and calculates
#' the effects on model parameters Currently, only binary continuous traits are supported.
#'
#' Additionally, to account for the influence of the number of species on each
#' clade (clade sample size), this function also estimates a null distribution
#' expected for the number of species in a given clade. This is done by fitting
#' models without the same number of species as in the given clade.The number of
#' simulations to be performed is set by 'n.sim'. To test if the
#' clade influence differs from the null expectation for a clade of that size,
#' a randomization test can be performed using 'summary(x)'.
#'
#' Different evolutionary models from \code{fitContinuous} can be used, i.e. \code{BM},\code{OU},
#' \code{EB}, \code{trend}, \code{lambda}, \code{kappa}, \code{delta} and \code{drift}.
#'
#' See \code{\link[geiger]{fitContinuous}} for more details on evolutionary models.
#'
#' Output can be visualised using \code{sensi_plot}.
#'
#' @return The function \code{tree_continuous} returns a list with the following
#' components:
#' @return \code{call}: The function call
#' @return \code{data}: The original full data frame.
#' @return \code{full.model.estimates}: Parameter estimates (rate of evolution \code{sigsq}
#' and where applicable \code{optpar}), root state \code{z0},
#' AICc for the full model without deleted clades.
#' @return \code{sensi.estimates}: Parameter estimates (sigsq and optpar), (percentual) difference
#' in parameter estimate compared to the full model (DIFsigsq, sigsq.perc, DIFoptpar, optpar.perc),
#' AICc and z0 for each repeat with a clade removed.
#' @return \code{null.dist}: A data frame with estimates for the null distributions
#' for all clades analysed.
#' @return \code{errors}: Clades where deletion resulted in errors.
#' @return \code{clade.col}: Which column was used to specify the clades?
#' @return \code{optpar}: Transformation parameter used (e.g. \code{lambda}, \code{kappa} etc.)
#' @author Gijsbert Werner & Gustavo Paterno
#' @seealso \code{\link[geiger]{fitContinuous}}
#' @references
#'
#' Paterno, G. B., Penone, C. Werner, G. D. A.
#' \href{http://doi.wiley.com/10.1111/2041-210X.12990}{sensiPhy:
#' An r-package for sensitivity analysis in phylogenetic
#' comparative methods.} Methods in Ecology and Evolution
#' 2018, 9(6):1461-1467
#'
#' Yang Z. 2006. Computational Molecular Evolution. Oxford University Press: Oxford.
#'
#' Harmon Luke J, Jason T Weir, Chad D Brock, Richard E Glor, and Wendell Challenger. 2008.
#' GEIGER: investigating evolutionary radiations. Bioinformatics 24:129-131.
#'
#' @examples
#' \dontshow{
#' #Load data:
#' data("primates")
#' #Model trait evolution accounting for influential clades
#' clade_cont<-clade_continuous(data=primates$data,phy = primates$phy[[1]],model="BM",
#' trait.col = "adultMass",clade.col="family",n.sim=1,n.species=20,n.cores = 2,track=TRUE)
#' }
#' \dontrun{
#' data("primates")
#' #Model trait evolution accounting for phylogenetic uncertainty
#' clade_cont<-clade_continuous(data=primates$data,phy = primates$phy[[1]], model="OU",
#' trait.col = "adultMass",clade.col="family",n.sim=30,n.species=10,n.cores = 2,track=TRUE)
#' #Print summary statistics
#' summary(clade_cont)
#' sensi_plot(clade_cont,graph="all")
#' sensi_plot(clade_cont,clade="Cercopithecidae",graph = "sigsq")
#' sensi_plot(clade_cont,clade="Cercopithecidae",graph = "optpar")
#' #Change the evolutionary model, tree transformation or minimum number of species per clade
#' clade_cont2<-clade_continuous(data=primates$data,phy = primates$phy[[1]],model="delta",
#' trait.col = "adultMass",clade.col="family",n.sim=30,n.species=5,n.cores = 2,track=TRUE)
#' summary(clade_cont2)
#' sensi_plot(clade_cont2)
#' clade_cont3<-clade_continuous(data=primates$data,phy = primates$phy[[1]],model="BM",
#' trait.col = "adultMass",clade.col="family",n.sim=30,n.species=5,n.cores = 2,track=TRUE)
#' summary(clade_cont3)
#' sensi_plot(clade_cont3,graph="sigsq")
#' }
#' @export
clade_continuous <- function(data,
phy,
model,
trait.col,
clade.col,
n.species = 5,
n.sim = 20,
bounds = list(),
n.cores = NULL,
track = TRUE,
...) {
# Error checking:
if (is.null(model))
stop("model must be specified, e.g. 'OU' or 'lambda'")
if (!inherits(data, "data.frame"))
stop("data must be class 'data.frame'")
if (missing(clade.col))
stop("clade.col not defined. Please, define the",
" column with clade names.")
if (!inherits(phy, "phylo"))
stop("phy must be class 'phylo'")
if (model == "white")
stop("the white-noise (non-phylogenetic) model is not allowed")
if (model == "drift" &
ape::is.ultrametric(phy))
stop(
"A drift model is unidentifiable for ultrametric trees., see ?fitContinuous for details"
)
if (length(which(!phy$tip.label %in% rownames(data))) > 0)
stop("not all tips are present in data, prune tree")
if (length(which(!rownames(data) %in% phy$tip.label)) > 0)
stop("not all data species are present in tree, remove superfluous data points")
else
#Calculates the full model, extracts model parameters
full.data <- data
phy <- phy
if (is.na(match(clade.col, names(full.data)))) {
stop("Names column '", clade.col, "' not found in data frame'")
}
# Identify CLADES to use and their sample size
wc <- table(full.data[, clade.col]) > n.species
uc <- table(full.data[, clade.col])[wc]
#k <- names(which(table(full.data[,clade.col]) > n.species ))
if (length(uc) == 0)
stop(
paste(
"There is no clade with more than ",
n.species,
" species. Change 'n.species' to fix this
problem",
sep = ""
)
)
# FULL MODEL PARAMETERS:
trait_vec_full <- full.data[, trait.col]
names(trait_vec_full) <- rownames(full.data)
N <- nrow(full.data)
mod.0 <-
geiger::fitContinuous(
phy = phy,
dat = trait_vec_full,
model = model,
bounds = bounds,
ncores = n.cores,
...
)
sigsq.0 <- mod.0$opt$sigsq
aicc.0 <- mod.0$opt$aicc
if (model == "BM") {
optpar.0 <- NA
}
if (model == "OU") {
optpar.0 <- mod.0$opt$alpha
}
if (model == "EB") {
optpar.0 <- mod.0$opt$a
}
if (model == "trend") {
optpar.0 <- mod.0$opt$slope
}
if (model == "lambda") {
optpar.0 <- mod.0$opt$lambda
}
if (model == "kappa") {
optpar.0 <- mod.0$opt$kappa
}
if (model == "delta") {
optpar.0 <- mod.0$opt$delta
}
if (model == "drift") {
optpar.0 <- mod.0$opt$drift
}
#Create dataframe to store estmates for each clade
sensi.estimates <-
data.frame(
"clade" = I(as.character()),
"N.species" = numeric(),
"sigsq" = numeric(),
"DIFsigsq" = numeric(),
"sigsq.perc" = numeric(),
"optpar" = numeric(),
"DIFoptpar" = numeric(),
"optpar.perc" = numeric(),
"z0" = numeric(),
"aicc" = numeric()
)
# Create dataframe store simulations (null distribution)
null.dist <-
data.frame(
"clade" = rep(names(uc), each = n.sim),
"sigsq" = numeric(length(uc) * n.sim),
"DIFsigsq" = numeric(length(uc) * n.sim),
"optpar" = numeric(length(uc) * n.sim),
"DIFoptpar" = numeric(length(uc) * n.sim)
)
### START LOOP between CLADES:
# counters:
aa <- 1
bb <- 1
errors <- NULL
if (track == TRUE)
pb <- utils::txtProgressBar(min = 0,
max = length(uc) * n.sim,
style = 3)
for (A in names(uc)) {
### Number of species in clade A
cN <- as.numeric(uc[names(uc) == A])
### Fit reduced model (without clade)
crop.data <- full.data[!full.data[, clade.col] %in% A, ]
crop.phy <-
ape::drop.tip(phy, setdiff(phy$tip.label, rownames(crop.data)))
crop.trait_vec <- crop.data[, trait.col]
names(crop.trait_vec) <- rownames(crop.data)
mod = try(geiger::fitContinuous(
phy = crop.phy,
dat = crop.trait_vec,
model = model,
bounds = bounds,
ncores = n.cores,
...
),
TRUE)
sigsq <- mod$opt$sigsq
z0 <- mod$opt$z0
aicc <- mod$opt$aicc
DIFsigsq <- sigsq - sigsq.0
sigsq.perc <-
round((abs(DIFsigsq / sigsq.0)) * 100,
digits = 1)
if (model == "BM") {
optpar <- NA
}
if (model == "OU") {
optpar <- mod$opt$alpha
}
if (model == "EB") {
optpar <- mod$opt$a
}
if (model == "trend") {
optpar <- mod$opt$slope
}
if (model == "lambda") {
optpar <- mod$opt$lambda
}
if (model == "kappa") {
optpar <- mod$opt$kappa
}
if (model == "delta") {
optpar <- mod$opt$delta
}
if (model == "drift") {
optpar <- mod$opt$drift
}
DIFoptpar <- optpar - optpar.0
optpar.perc <-
round((abs(DIFoptpar / optpar.0)) * 100,
digits = 1)
# Store reduced model parameters:
estim.simu <- data.frame(
A,
cN,
sigsq,
DIFsigsq,
sigsq.perc,
optpar,
DIFoptpar,
optpar.perc,
z0,
aicc,
stringsAsFactors = F
)
sensi.estimates[aa,] <- estim.simu
### START LOOP FOR NULL DIST:
# number of species in clade A:
for (i in 1:n.sim) {
exclude <- sample(1:N, cN)
crop.data <- full.data[-exclude, ]
crop.phy <-
ape::drop.tip(phy, setdiff(phy$tip.label, rownames(crop.data)))
crop.trait_vec <- crop.data[, trait.col]
names(crop.trait_vec) <- rownames(crop.data)
mod = try(geiger::fitContinuous(
phy = crop.phy,
dat = crop.trait_vec,
model = model,
bounds = bounds,
ncores = n.cores,
...
),
TRUE)
if (isTRUE(class(mod) == "try-error")) {
error <- i
names(error) <- rownames(full.data$data)[i]
errors <- c(errors, error)
next
}
else
sigsq <- mod$opt$sigsq
aicc <- mod$opt$aicc
DIFsigsq <- sigsq - sigsq.0
if (model == "BM") {
optpar <- NA
}
if (model == "OU") {
optpar <- mod$opt$alpha
}
if (model == "EB") {
optpar <- mod$opt$a
}
if (model == "trend") {
optpar <- mod$opt$slope
}
if (model == "lambda") {
optpar <- mod$opt$lambda
}
if (model == "kappa") {
optpar <- mod$opt$kappa
}
if (model == "delta") {
optpar <- mod$opt$delta
}
if (model == "drift") {
optpar <- mod$opt$drift
}
DIFoptpar <- optpar - optpar.0
null.dist[bb,] <- data.frame(clade = as.character(A),
sigsq,
DIFsigsq,
optpar,
DIFoptpar)
if (track == TRUE)
utils::setTxtProgressBar(pb, bb)
bb <- bb + 1
}
aa <- aa + 1
}
if (track == TRUE)
on.exit(close(pb))
#OUTPUT
#full model estimates:
param0 <- list(
sigsq = sigsq.0,
optpar = optpar.0,
z0 <- mod.0$opt$z0,
aicc = aicc.0
)
#Generates output:
res <- list(
call = match.call(),
data = full.data,
full.model.estimates = param0,
sensi.estimates = sensi.estimates,
null.dist = null.dist,
errors = errors,
optpar = model,
clade.col = clade.col
)
class(res) <- "sensiClade.TraitEvol"
### Warnings:
if (length(res$errors) > 0) {
warning("Some clades deletion presented errors, please check: output$errors")
}
else {
res$errors <- "No errors found."
}
return(res)
}