]> git.donarmstrong.com Git - ape.git/blob - R/read.nexus.R
a few bug fixes especially in plot.phylo()
[ape.git] / R / read.nexus.R
1 ## read.nexus.R (2010-09-27)
2
3 ##   Read Tree File in Nexus Format
4
5 ## Copyright 2003-2009 Emmanuel Paradis and 2010 Klaus Schliep
6
7 ## This file is part of the R-package `ape'.
8 ## See the file ../COPYING for licensing issues.
9
10 .treeBuildWithTokens <- function(x)
11 {
12     ## remove potential node labels; see ?read.nexus for justification
13     node.label <- gsub("[:;].*$", "", strsplit(x, ")")[[1]][-1])
14     has.node.labels <- FALSE
15     if (any(node.label != "")) {
16         x <- gsub(")[^:]*:", "):", x)
17         x <- gsub(")[^:]*;", ");", x) # if there's no root edge
18         has.node.labels <- TRUE
19     }
20     phy <- .Call("treeBuildWithTokens", x, PACKAGE = "ape")
21     dim(phy[[1]]) <- c(length(phy[[1]])/2, 2)
22     nms <- c("edge", "edge.length", "Nnode", "root.edge")
23     if (length(phy) == 3) nms <- nms[-4]
24     names(phy) <- nms
25     if (has.node.labels) phy$node.label <- node.label
26     class(phy) <- "phylo"
27     phy
28 }
29
30 clado.build <- function(tp)
31 {
32     add.internal <- function() {
33         edge[j, 1] <<- current.node
34         node <<- node + 1
35         edge[j, 2] <<- current.node <<- node
36         index[node] <<- j # set index
37         j <<- j + 1
38     }
39     add.terminal <- function() {
40         edge[j, 1] <<- current.node
41         edge[j, 2] <<- tip
42         index[tip] <<- j # set index
43         tip.label[tip] <<- tpc[k]
44         k <<- k + 1
45         tip <<- tip + 1
46         j <<- j + 1
47     }
48     go.down <- function() {
49         l <- index[current.node]
50         node.label[current.node - nb.tip] <<- tpc[k]
51         k <<- k + 1
52         current.node <<- edge[l, 1]
53     }
54     if (!length(grep(",", tp))) {
55         obj <- list(edge = matrix(c(2, 1), 1, 2), Nnode = 1)
56         tp <- unlist(strsplit(tp, "[\\(\\);]"))
57         obj$tip.label <- tp[2]
58         if (tp[3] != "") obj$node.label <- tp[3]
59         class(obj) <- "phylo"
60         return(obj)
61     }
62     tsp <- unlist(strsplit(tp, NULL))
63     tp <- gsub(")", ")NA", tp)
64     tp <- gsub(" ", "", tp)
65     tpc <- unlist(strsplit(tp, "[\\(\\),;]"))
66     tpc <- tpc[tpc != ""]
67     skeleton <- tsp[tsp == "(" | tsp == ")" | tsp == "," | tsp == ";"]
68     nsk <- length(skeleton)
69     nb.node <- length(skeleton[skeleton == ")"])
70     nb.tip <- length(skeleton[skeleton == ","]) + 1
71     ## We will assume there is an edge at the root;
72     ## if so, it will be removed and put in a vector
73     nb.edge <- nb.node + nb.tip
74     node.label <- character(nb.node)
75     tip.label <- character(nb.tip)
76
77     edge <- matrix(NA, nb.edge, 2)
78     current.node <- node <- nb.tip + 1 # node number
79     edge[nb.edge, 1] <- 0    # see comment above
80     edge[nb.edge, 2] <- node #
81
82     index <- numeric(nb.edge + 1)
83     index[node] <- nb.edge
84     ## j: index of the line number of edge
85     ## k: index of the line number of tpc
86     ## tip: tip number
87     j <- k <- tip <- 1
88     for (i in 2:nsk) {
89         if (skeleton[i] == "(") add.internal()      # add an internal branch (on top)
90         if (skeleton[i] == ",") {
91             if (skeleton[i - 1] != ")") add.terminal()   # add a terminal branch
92         }
93         if (skeleton[i] == ")") {
94             if (skeleton[i - 1] == ",") {   # add a terminal branch and go down one level
95                 add.terminal()
96                 go.down()
97             }
98             if (skeleton[i - 1] == ")") go.down()   # go down one level
99         }
100     }
101     edge <- edge[-nb.edge, ]
102     obj <- list(edge = edge, tip.label = tip.label,
103                 Nnode = nb.node, node.label = node.label)
104     obj$node.label <-
105         if (all(obj$node.label == "NA")) NULL
106         else gsub("^NA", "", obj$node.label)
107     class(obj) <- "phylo"
108     obj
109 }
110
111 read.nexus <- function(file, tree.names = NULL)
112 {
113     X <- scan(file = file, what = "", sep = "\n", quiet = TRUE)
114     ## remove all comments
115     ## (this might not work if there are square brackets within the comments)
116     LEFT <- grep("\\[", X)
117     RIGHT <- grep("\\]", X)
118     if (length(LEFT)) { # in case there are no comments at all
119         w <- LEFT == RIGHT
120         if (any(w)) { # in case all comments use at least 2 lines
121             s <- LEFT[w]
122             X[s] <- gsub("\\[[^]]*\\]", "", X[s])
123             ## The above regexp was quite tough to find: it makes
124             ## possible to delete series of comments on the same line:
125             ##       ...[...]xxx[...]...
126             ## without deleting the "xxx". This regexp is in three parts:
127             ##       \\[      [^]]*       \\]
128             ## where [^]]* means "any character, except "]", repeated zero
129             ## or more times" (note that the ']' is not escaped here).
130             ## The previous version was:
131             ##       X[s] <- gsub("\\[.*\\]", "", X[s])
132             ## which deleted the "xxx". (EP  2008-06-24)
133         }
134         w <- !w
135         if (any(w)) {
136             s <- LEFT[w]
137             X[s] <- gsub("\\[.*", "", X[s])
138             sb <- RIGHT[w]
139             X[sb] <- gsub(".*\\]", "", X[sb])
140             if (any(s < sb - 1))
141                 X <- X[-unlist(mapply(":", (s + 1), (sb - 1)))]
142         }
143     }
144     endblock <- grep("END;|ENDBLOCK;", X, ignore.case = TRUE)
145     semico <- grep(";", X)
146     i1 <- grep("BEGIN TREES;", X, ignore.case = TRUE)
147     i2 <- grep("TRANSLATE", X, ignore.case = TRUE)
148     translation <- if (length(i2) == 1 && i2 > i1) TRUE else FALSE
149     if (translation) {
150         end <- semico[semico > i2][1]
151         x <- X[(i2 + 1):end] # assumes there's a 'new line' after "TRANSLATE"
152         ## x <- gsub("TRANSLATE", "", x, ignore.case = TRUE)
153         x <- unlist(strsplit(x, "[,; \t]"))
154         x <- x[nzchar(x)]
155         TRANS <- matrix(x, ncol = 2, byrow = TRUE)
156         TRANS[, 2] <- gsub("['\"]", "", TRANS[, 2])
157         n <- dim(TRANS)[1]
158     }
159     start <-
160         if (translation) semico[semico > i2][1] + 1
161         else semico[semico > i1][1]
162     end <- endblock[endblock > i1][1] - 1
163     tree <- X[start:end]
164     rm(X)
165     tree <- gsub("^.*= *", "", tree)
166     ## check whether there are empty lines from the above manips:
167     tree <- tree[tree != ""]
168     semico <- grep(";", tree)
169     Ntree <- length(semico)
170     ## are some trees on several lines?
171     if (Ntree == 1 && length(tree) > 1) STRING <- paste(tree, collapse = "") else {
172         if (any(diff(semico) != 1)) {
173             STRING <- character(Ntree)
174             s <- c(1, semico[-Ntree] + 1)
175             j <- mapply(":", s, semico)
176             if (is.list(j)) {
177                 for (i in 1:Ntree)
178                     STRING[i] <- paste(tree[j[[i]]], collapse = "")
179             } else {
180                 for (i in 1:Ntree)
181                     STRING[i] <- paste(tree[j[, i]], collapse = "")
182             }
183         } else STRING <- tree
184     }
185     rm(tree)
186     STRING <- gsub(" ", "", STRING)
187     colon <- grep(":", STRING)
188     if (!length(colon)) {
189         trees <- lapply(STRING, clado.build)
190     } else if (length(colon) == Ntree) {
191         trees <-
192             if (translation) lapply(STRING, .treeBuildWithTokens)
193             else lapply(STRING, tree.build)
194     } else {
195         trees <- vector("list", Ntree)
196         trees[colon] <- lapply(STRING[colon], tree.build)
197         nocolon <- (1:Ntree)[!1:Ntree %in% colon]
198         trees[nocolon] <- lapply(STRING[nocolon], clado.build)
199         if (translation) {
200             for (i in 1:Ntree) {
201                 tr <- trees[[i]]
202                 for (j in 1:n) {
203                     ind <- which(tr$tip.label[j] == TRANS[, 1])
204                     tr$tip.label[j] <- TRANS[ind, 2]
205                 }
206                 if (!is.null(tr$node.label)) {
207                     for (j in 1:length(tr$node.label)) {
208                         ind <- which(tr$node.label[j] == TRANS[, 1])
209                         tr$node.label[j] <- TRANS[ind, 2]
210                     }
211                 }
212                 trees[[i]] <- tr
213             }
214             translation <- FALSE
215         }
216     }
217     for (i in 1:Ntree) {
218         tr <- trees[[i]]
219         ## Check here that the root edge is not incorrectly represented
220         ## in the object of class "phylo" by simply checking that there
221         ## is a bifurcation at the root
222         if (!translation) n <- length(tr$tip.label)
223         ROOT <- n + 1
224         if (sum(tr$edge[, 1] == ROOT) == 1 && dim(tr$edge)[1] > 1) {
225             stop(paste("There is apparently two root edges in your file: cannot read tree file.\n  Reading NEXUS file aborted at tree no.", i, sep = ""))
226         }
227     }
228     if (Ntree == 1) {
229         trees <- trees[[1]]
230         if (translation) {
231             trees$tip.label <-
232                 if (length(colon)) TRANS[, 2] else
233                 TRANS[, 2][as.numeric(trees$tip.label)]
234         }
235     } else {
236         if (!is.null(tree.names)) names(trees) <- tree.names
237         if (translation) {
238             if (length(colon) == Ntree) # .treeBuildWithTokens() was used
239                 attr(trees, "TipLabel") <- TRANS[, 2]
240             else { # reassign the tip labels then compress
241                 for (i in 1:Ntree)
242                     trees[[i]]$tip.label <-
243                         TRANS[, 2][as.numeric(trees[[i]]$tip.label)]
244                 trees <- .compressTipLabel(trees)
245             }
246         }
247         class(trees) <- "multiPhylo"
248     }
249     if (length(grep("[\\/]", file)) == 1)
250         if (!file.exists(file)) # suggestion by Francois Michonneau
251             file <- paste(getwd(), file, sep = "/")
252     attr(trees, "origin") <- file
253     trees
254 }