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