-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextractLineages.Rmd
291 lines (212 loc) · 12.1 KB
/
extractLineages.Rmd
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
---
title: "COVID-19 Germany introductions"
subtitle: "Extract Germany transmission lineages (BEAST + DTA MCC trees)"
author: "BRICS"
date: '`r format(Sys.time(), "Last modified: %d %b %Y")`'
output:
github_document:
toc: true
toc_depth: 2
layout: page
editor_options:
chunk_output_type: inline
params:
inputpath : "../../../data/phylogenetic/"
cluster_f : DTA
nreps : 2000
minsize : 100
ncores : 40
uklimit : "2020-01-23"
metadata : "../results/gisaid-20210602-metadata-sampled-unsampled.tsv"
intreepath : "../results/beast/run/all/"
outputpath : "../results/beast/run/lin-samp/"
---
```{r rsetup, include=FALSE}
library(tictoc)
library(dplyr)
library(lubridate)
library(ape)
library(tidytree)
library(parallel)
library(beastio)
library(ggplot2)
source("treeutils.R")
source("clusterutils.R")
inputpath <- params$inputpath
outputpath <- params$outputpath
intreepath <- params$intreepath
cluster_f <- params$cluster_f
replicates <- params$nreps
minsize <- params$minsize
ncores <- params$ncores
uklimit <- decimal_date(as.Date(params$uklimit))
figpath <- paste0(outputpath, "figures/")
cachepath <- paste0(outputpath, "cache/")
dir.create(outputpath, recursive = TRUE, showWarnings = FALSE)
dir.create(figpath, recursive = TRUE, showWarnings = FALSE)
knitr::opts_chunk$set(tidy=FALSE, cache=FALSE, cache.path = cachepath, cache.lazy = FALSE,
dev="png", dpi=150, fig.path=figpath,
message=FALSE, error=FALSE, warning=TRUE, echo=FALSE)
#metadata <- read.csv(paste0(inputpath, "metadata.csv"))
metadata <- read.table(params$metadata, sep="\t", head=TRUE, na.strings=c("NA", ""), fill=TRUE, stringsAsFactors=FALSE, quote="|")
metadata$sample_date <- ymd(metadata$Collection.date)
metadata$decimal_date <- decimal_date(metadata$sample_date)
metadata$taxon_label <- metadata$Accession.ID
#metadata$taxon_label <- gsub("/", "_", as.character(metadata$sequence_name))
treefiles <- list.files(path = intreepath, pattern = "*.combined.trees.xz$")
# treefiles <- list.files(path = intreepath, pattern = "*.tree$")
# treefiles <- list.files(path = "../results/trees/", pattern = "*.trees$")
lineageLimit = sapply(treefiles, function (x) { if (length(grep("^B.1.1.7", x)) > 0) return( decimal_date(as.Date("2020-12-20"))); return(uklimit); } )
```
```{r functions}
extractTreeClusters <- function(i, tree, metadata, treefile, treepath, maxheight, minsize, saveTrees=TRUE) {
# Extract clusters
prefix <- paste0(strsplit(treefile, "-")[[1]][1], "_",cluster_f,"_")
treetable <- getClusterTable(tree, "Germany", prefix = prefix, maxheight = maxheight, debug = FALSE)
#treetable[grepl("^inode[0-9]+$", treetable$taxon),]$types = "coalescent"
write.csv(treetable, paste0(treepath, gsub("\\.combined.trees.xz", "_", treefile), i, ".treetable.csv"), quote=FALSE, row.names=TRUE)
# write.csv(treetable, paste0(treepath, gsub("\\.tree", "_", treefile), i, ".treetable.csv"), quote=FALSE, row.names=TRUE)
# Should remove singletons?
clusterSamples <- treetable[treetable$types == "sample" & !grepl("^inode[0-9]+$", treetable$taxon), ]
clusterMeta <- droplevels(metadata[match(clusterSamples$taxon, metadata$taxon_label), ])
clusterMeta$cluster <- clusterSamples$cluster[match(clusterMeta$taxon_label, clusterSamples$taxon)]
# Save summary file
clusterSizes <- table(clusterMeta$cluster)
clusterNames <- names(clusterSizes)[clusterSizes > 1]
clusterSingles <- names(clusterSizes)[clusterSizes == 1]
mostrecent <- max(clusterMeta$decimal_date)
tmrcas <- sapply(clusterNames, function(x) mostrecent - max(treetable$heights[treetable$cluster == x], na.rm = TRUE))
oldest <- sapply(clusterNames, function(x) min(clusterMeta$decimal_date[clusterMeta$cluster == x], na.rm = TRUE))
newest <- sapply(clusterNames, function(x) max(clusterMeta$decimal_date[clusterMeta$cluster == x], na.rm = TRUE))
seqs <- sapply(clusterNames, function(x) sum(clusterMeta$cluster == x, na.rm = TRUE))
if (length(tmrcas) == 0) {
treeClusterStats <- data.frame(matrix(ncol=8, nrow=0))
colnames(treeClusterStats) <- c("cluster", "seqs", "tmrca", "tmrca_calendar",
"oldest", "mostrecent", "treefile", "tree")
} else {
treeClusterStats <- data.frame(cluster=clusterNames, seqs=seqs, tmrca=tmrcas, tmrca_calendar=round_date(date_decimal(tmrcas), unit="day"),
oldest=oldest, mostrecent=newest, treefile=treefile, tree=i)
}
if (saveTrees) {
# Extract and save trees for all clusters with >minsize tips
clusterpath <- paste0(treepath, gsub("\\.treess.xz", "_", treefile), i, "/")
# clusterpath <- paste0(treepath, gsub("\\.tree", "_", treefile), i, "/")
dir.create(clusterpath, recursive = TRUE, showWarnings = FALSE)
bigClusters <- names(seqs)[which(seqs >= minsize)]
for (cluster in bigClusters) {
clusterIds <- as.character(na.omit(clusterSamples$taxon[clusterSamples$cluster == cluster,drop=TRUE]))
clusterMRCA <- getMRCA(tree@phylo, clusterIds)
#clustertable <- treetable[treetable$cluster == cluster & !is.na(treetable$cluster), ]
#clustertable <- clustertable[order(clustertable$heights, decreasing=TRUE), ]
#clusterMRCA2 <- as.numeric(rownames(clustertable)[1])
clusterTree <- treeio::tree_subset(tree, clusterMRCA, levels_back=0)
#write.tree(clusterTree@phylo, paste0(clusterpath, cluster, ".tree"))
write.beast(clusterTree, paste0(clusterpath, cluster, ".tree"))
}
}
return(treeClusterStats)
}
```
# Summary
This notebook extracts TMRCAs and other summary statistics of the `r cluster_f` clusters across all replicate trees from BEAST.
## Input
- Metadata table in `.csv` format. Should contain a `sequence_name` and `sample_date` column.
- Set of trees for each treefile with DTA reconstructions save in `r intreepath`.
## Steps
- Extract a table of nodes and heights for each lineage in each tree.
- Extract TMRCAs and sizes for each lineage in each tree.
- Extract subtrees for all lineages with at least `r minsize` tips.
- Extract lineage assignment for all UK sequences in each tree replicate.
## Output
- `.csv` files with nodes and heights for each lineage in each tree.
- `.csv` file with lineage assignments for all UK sequences in each tree replicate.
- `.Rds` files for each tree (easier to load, since it's already a treedata data structure).
- Newick trees for all lineages with at least `r minsize` tips.
# Extract clusters
```{r extractClusters, eval=TRUE, message=FALSE, warning=FALSE, cache=TRUE, results="asis"}
#tic(cat(paste0("\n\nTotal time for ", replicates, " trees: ", replicates)))
#clusterStats <- c()
firstRound <- TRUE
for (treefile in treefiles) {
tic(cat(paste0("\n\n**Loading ", treefile, ":** ")))
trees <- read.beast.groups(paste0(intreepath, treefile), groupsize = 50, skip=0, ntrees=replicates, debug=FALSE)
treemeta <- droplevels(metadata[match(trees[[1]]@phylo$tip.label, metadata$taxon_label), ])
mostrecent <- max(treemeta$decimal_date)
toc()
treeLimit <- lineageLimit[treefile]
cat(paste0("\n\n - Most recent tip: ", format.Date(round_date(date_decimal(mostrecent), unit = "day")), " (", mostrecent, ")\n"))
cat(paste0(" - Maximum UK node height: ", mostrecent - treeLimit, "\n\n"))
tic(cat("\n - Saving and compressing: "))
#DEBUG:saveRDS(trees, file=paste0(outputpath, treefile, ".Rds"), compress = TRUE)
toc()
tic(cat("\n - Extract clusters from trees: "))
treepath <- paste0(outputpath, gsub("\\.combined.trees.xz", "", treefile), "/")
# treepath <- paste0(outputpath, gsub("\\.tree", "", treefile), "/")
dir.create(treepath, recursive = TRUE, showWarnings = FALSE)
#DEBUG: statList <- mclapply(seq_len(length(trees)), function(i) extractTreeClusters(i, trees[[i]], metadata, treefile, treepath, (mostrecent - treeLimit), minsize), mc.cores = ncores)
statList <- mclapply(seq_len(length(trees)), function(i) extractTreeClusters(i, trees[[i]], metadata, treefile, treepath, (mostrecent - treeLimit), minsize, saveTrees=FALSE), mc.cores = ncores)
treeClusterStats <- statList[[1]]
for (i in 2:length(statList)) {
treeClusterStats <- rbind(treeClusterStats, statList[[i]])
}
write.csv(treeClusterStats, paste0(outputpath, gsub("\\.combined.trees.xz", "_", treefile), cluster_f,".csv"), row.names=FALSE, quote=FALSE)
# write.csv(treeClusterStats, paste0(outputpath, gsub("\\.tree", "_", treefile), cluster_f,".csv"), row.names=FALSE, quote=FALSE)
#clusterStats <- rbind(clusterStats, treeClusterStats)
if (firstRound) {
cat(paste("file created", paste0(outputpath, "clusters_",cluster_f,".csv")))
write.table(treeClusterStats, paste0(outputpath, "clusters_",cluster_f,".csv"), row.names=FALSE, quote=FALSE, sep=",")
} else {
cat(paste("file appended", paste0(outputpath, "clusters_",cluster_f,".csv")), treefile)
write.table(treeClusterStats, paste0(outputpath, "clusters_",cluster_f,".csv"), row.names=FALSE, quote=FALSE, col.names=FALSE, append = TRUE, sep=",")
}
firstRound <- FALSE
toc()
}
#write.csv(clusterStats, paste0(outputpath, "clusters_",cluster_f,".csv"), row.names=FALSE, quote=FALSE)
#toc()
```
# Extract cluster samples
```{r extractClusterSamples, results="asis", eval=TRUE}
treedirs <- gsub("\\.combined.trees.xz", "", treefiles)
allSamples <- c()
firstRound <- TRUE
for (dir in treedirs) {
tic(cat(paste0("\n\nProcessing ", dir, ": ")))
treesamples <- NULL
treetables <- list.files(path = paste0(outputpath, dir, "/"), pattern = "*.treetable.csv$")
reps <- c()
for (i in 1:length(treetables)) {
rep <- treetables[i] %>% sub(".treetable.csv", "", .) %>% sub("_", "", .) %>% sub(dir, "", .) %>% as.numeric
reps <- c(reps, rep)
treetable <- read.csv(paste0(outputpath, dir, "/", treetables[i]))
#ukseqs <- droplevels(treetable[treetable$location == "UK" & treetable$types == "sample", c("taxon", "cluster")])
ukseqs <- droplevels(treetable[treetable$location == "Germany" & treetable$types == "sample", c("taxon", "cluster")])
colnames(ukseqs) <- c("taxon", paste0("tree", rep))
if (is.null(treesamples)) {
treesamples <- ukseqs[order(ukseqs$taxon), ]
} else {
# Reorder
ukseqs <- ukseqs[match(treesamples$taxon, ukseqs$taxon), ]
# Check and bind
if (all(ukseqs$taxon == treesamples$taxon)) {
treesamples[[paste0("tree",rep)]] <- ukseqs[[paste0("tree",rep)]]
} else {
stop(sprintf("Tree %d contains different UK taxa", rep))
}
}
}
#allSamples <- rbind(allSamples, treesamples[, c(1, order(reps)+1)])
if (firstRound) {
write.table(treesamples[, c(1, order(reps)+1)], paste0(outputpath, "clusterSamples_",cluster_f,".csv"), quote=FALSE, row.names=FALSE, sep=",")
} else {
write.table(treesamples[, c(1, order(reps)+1)], paste0(outputpath, "clusterSamples_",cluster_f,".csv"), quote=FALSE, row.names=FALSE, col.names=FALSE, append = TRUE, sep=",")
}
firstRound <- FALSE
toc()
}
#write.csv(allSamples, paste0(outputpath, "clusterSamples_",cluster_f,".csv"), quote=FALSE, row.names=FALSE)
```
# Session info
```{r sessionInfo, results='markup'}
sessionInfo()
```