File: readNCL.R

package info (click to toggle)
r-cran-phylobase 0.8.6-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,308 kB
  • sloc: cpp: 306; ansic: 247; xml: 135; lisp: 38; sh: 9; makefile: 5
file content (435 lines) | stat: -rw-r--r-- 17,520 bytes parent folder | download | duplicates (5)
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
### This file contains the source code for the functions:
###  - readNCL (generic function)
###  - readNexus (wrapper for readNCL importing Nexus files)
###  - readNewick (wrapper for readNCL importing Newick files)

##' Create a \code{phylo4}, \code{phylo4d} or \code{data.frame} object
##' from a NEXUS or a Newick file
##'
##' \code{readNexus} reads a NEXUS file and outputs a \code{phylo4},
##' \code{phylo4d} or \code{data.frame} object.
##'
##' \code{readNewick} reads a Newick file and outputs a \code{phylo4}
##' or \code{phylo4d} object.
##'
##' \code{readNexus} is used internally by both \code{readNexus} and
##' \code{readNewick} to extract data held in a tree files,
##' specifically in NEXUS files from DATA, CHARACTER or TREES
##' blocks.
##'
##' The \code{type} argument specifies which of these is returned:
##'
##' \describe{
##'
##'   \item{data}{will only return a \code{data.frame} of the contents
##' of all DATA and CHARACTER blocks.}
##'
##'   \item{tree}{will only return a \code{phylo4} object of the
##' contents of the TREES block.}
##'
##'   \item{all}{if only data or a tree are present in the file, this
##' option will act as the options above, returning either a
##' \code{data.frame} or a \code{phylo4} object respectively. If both
##' are present then a \code{phylo4d} object is returned containing
##' both.}
##'
##' }
##'
##' The function returns \code{NULL} if the \code{type} of
##' data requested is not present in the file, or if neither data nor
##' tree blocks are present.
##'
##' Depending on the context \code{readNexus} will call either the
##' \code{phylo4} or \code{phylo4d} constructor. The \code{phylo4d}
##' constructor will be used with \code{type="all"}, or if the option
##' \code{check.node.labels="asdata"} is invoked.
##'
##' \code{readNewick} imports Newick formatted tree files and will
##' return a \code{phylo4} or a \code{phylo4d} object if the option
##' \code{check.node.labels="asdata"} is invoked.
##'
##' For both \code{readNexus} and \code{readNewick}, the options for
##' \code{check.node.labels} can take the values:
##'
##' \describe{
##'
##' \item{keep}{the node labels of the trees will be passed as node
##' labels in the \code{phylo4} object}
##'
##' \item{drop}{the node labels of the trees will be ignored in the
##' \code{phylo4} object}
##'
##' \item{asdata}{the node labels will be passed as data and a
##' \code{phylo4d} object will be returned.}
##'
##' }
##'
##' If you use the option \code{asdata} on a file with no node labels,
##' a warning message is issued, and is thus equivalent to the value
##' \code{drop}.
##'
##' For both \code{readNexus} and \code{readNewick}, additional
##' arguments can be passed to the constructors such as \code{annote},
##' \code{missing.data} or \code{extra.data}. See the \sQuote{Details}
##' section of \code{\link{phylo4d-methods}} for the complete list of
##' options.
##'
##' @name Import Nexus and Newick files
##' @docType methods
##' @param file a NEXUS file for \code{readNexus} or a file that
##'     contains Newick formatted trees for \code{readNewick}.
##' @param simplify If TRUE, if there are multiple trees in the file,
##' only the first one is returned; otherwise a list of
##' \code{phylo4(d)} objects is returned if the file contains multiple
##' trees.
##' @param type Determines which type of objects to return, if present
##'     in the file (see Details).
##' @param spacesAsUnderscores In the NEXUS file format white spaces
##'     are not allowed in taxa labels and are represented by
##'     underscores. Therefore, NCL converts underscores found in taxa
##'     labels in the NEXUS file into white spaces
##'     (e.g. \code{species_1} will become \code{"species 1"}. If you
##'     want to preserve the underscores, set as TRUE, the default).
##' @param char.all If \code{TRUE}, returns all characters, even those
##'     excluded in the NEXUS file
##' @param polymorphic.convert If \code{TRUE}, converts polymorphic
##'     characters to missing data
##' @param levels.uniform If \code{TRUE}, uses the same levels for all
##'     characters
##' @param quiet If \code{FALSE} the output of the NCL interface is
##'     printed. This is mainly for debugging purposes. This option
##'     can considerably slow down the process if the tree is big or
##'     there are many trees in the file.
##' @param check.node.labels Determines how the node labels in the
##'     NEXUS or Newick files should be treated in the phylo4 object,
##'     see Details for more information.
##' @param return.labels Determines whether state names (if
##'     \code{TRUE}) or state codes should be returned.
##' @param file.format character indicating the format of the
##'     specified file (either \dQuote{\code{newick}} or
##'     \dQuote{\code{nexus}}). It's more convenient to just use
##'     \code{readNexus}  or \code{readNewick}.
##' @param check.names logical. If \sQuote{TRUE} then the names of the
##'     characters from the NEXUS file are checked to ensure that they
##'     are syntactically valid variable names and are not duplicated.
##'     If necessary they are adjusted using \sQuote{make.names}.
##' @param convert.edge.length logical. If \code{TRUE} negative edge
##'     lengths are replaced with 0. At this time \code{phylobase}
##'     does not accept objects with negative branch lengths, this
##'     workaround allows to import trees with negative branch
##'     lengths.
##' @param \dots Additional arguments to be passed to phylo4 or
##'     phylo4d constructor (see Details)
##' @return Depending on the value of \code{type} and the contents of
##'     the file, one of: a \code{data.frame}, a \linkS4class{phylo4}
##'     object, a \linkS4class{phylo4d} object or \code{NULL}.  If
##'     several trees are included in the NEXUS file and the option
##'     \code{simplify=FALSE} a list of \linkS4class{phylo4} or
##'     \linkS4class{phylo4d} objects is returned.
##' @note Underscores in state labels (i.e. trait or taxon names) will
##' be translated to spaces. Unless \code{check.names=FALSE}, trait
##' names will be converted to valid R names (see
##' \code{\link{make.names}}) on input to R, so spaces will be
##' translated to periods.
##' @author Brian O'Meara, Francois Michonneau, Derrick Zwickl
##' @seealso the \linkS4class{phylo4d} class, the \linkS4class{phylo4}
##'     class
##' @export
##' @rdname readNexus
##' @aliases readNCL
##' @keywords misc

readNCL <- function(file, simplify=FALSE, type=c("all", "tree","data"),
                    spacesAsUnderscores = TRUE, char.all=FALSE,
                    polymorphic.convert=TRUE, levels.uniform=FALSE, quiet=TRUE,
                    check.node.labels=c("keep", "drop", "asdata"), return.labels=TRUE,
                    file.format=c("nexus", "newick"), check.names=TRUE,
                    convert.edge.length=FALSE, ...) {


    type <- match.arg(type)
    file.format <- match.arg(file.format)

    check.node.labels <- match.arg(check.node.labels)

    if (type == "all" || type == "data") {
        returnData <- TRUE
    }
    else {
        returnData <- FALSE
    }
    if (type == "all" || type == "tree") {
        returnTrees <- TRUE
    }
    else {
        returnTrees <- FALSE
    }

    ## GetNCL returns a list containing:
    ##  $taxaNames: names of the taxa (from taxa block, implied or declared)
    ##  $treeNames: the names of the trees
    ##  $trees: a vector of (untranslated) Newick strings
    ##  $dataTypes: data type for each character block of the nexus file (length = number of chr blocks)
    ##  $nbCharacters: number of characters in each block (length = number of chr blocks)
    ##  $charLabels: the labels for the characters, i.e. the headers of the data frame to be returned
    ##    (length = number of chr blocks * sum of number of characters in each block)
    ##  $nbStates: the number of states of each character (equals 0 for non-standard types, length = number
    ##    of characters)
    ##  $stateLabels: the labels for the states of the characters, i.e. the levels of the factors to be returned
    ##  $dataChr: string that contains the data to be returned

    ncl <- rncl::rncl(file = file, file.format = file.format, spacesAsUnderscores = spacesAsUnderscores,
                      char.all = char.all, polymorphic.convert = polymorphic.convert,
                      levels.uniform = levels.uniform)


    ## Return Error message
    if (length(ncl) == 1 && names(ncl) == "ErrorMsg") {
        stop(ncl$ErrorMsg)
    }

    if (!quiet) message(ncl)

    ## Disclaimer
    if (!length(grep("\\{", ncl$dataChr)) && return.labels && !polymorphic.convert) {
        stop("At this stage, it's not possible to use the combination: ",
             "return.labels=TRUE and polymorphic.convert=FALSE for datasets ",
             "that contain polymorphic characters.")
    }

    if (returnData && length(ncl$dataChr)) {
        tipData <- vector("list", length(ncl$dataChr))
        for (iBlock in 1:length(ncl$dataTypes)) {
            chrCounter <- ifelse(iBlock == 1, 0, sum(ncl$nbCharacters[1:(iBlock-1)]))
            if (ncl$dataTypes[iBlock] == "Continuous") {
                for (iChar in 1:ncl$nbCharacters[iBlock]) {
                    i <- chrCounter + iChar
                    tipData[[i]] <- eval(parse(text=ncl$dataChr[i]))
                    names(tipData)[i] <- ncl$charLabels[i]
                }
            }
            else {
                if (ncl$dataTypes[iBlock] == "Standard") {
                    iForBlock <- integer(0)
                    for (iChar in 1:ncl$nbCharacters[iBlock]) {
                        i <- chrCounter + iChar
                        iForBlock <- c(iForBlock, i)
                        lblCounterMin <- ifelse(i == 1, 1, sum(ncl$nbStates[1:(i-1)]) + 1)
                        lblCounter <- seq(lblCounterMin, length.out=ncl$nbStates[i])
                        tipData[[i]] <- eval(parse(text=ncl$dataChr[i]))
                        names(tipData)[i] <- ncl$charLabels[i]
                        tipData[[i]] <- as.factor(tipData[[i]])

                        lbl <- ncl$stateLabels[lblCounter]
                        if (return.labels) {
                            if (any(nchar(gsub("\\s|_", "", lbl)) == 0)) {
                                warning("state labels are missing for \'", ncl$charLabels[i],
                                        "\', the option return.labels is thus ignored.")
                            }
                            else {
                                levels(tipData[[i]]) <- lbl
                            }
                        }
                    }
                    if (levels.uniform) {
                        allLevels <- character(0)
                        for (j in iForBlock) {
                            allLevels <- union(allLevels, levels(tipData[[j]]))
                        }
                        for (j in iForBlock) {
                            levels(tipData[[j]]) <- allLevels
                        }
                    }
                }
                else {
                    warning("This datatype is not currently supported by phylobase")
                    next
                    ## FIXME: different datatypes in a same file isn't going to work
                }
            }
        }
        tipData <- data.frame(tipData, check.names=check.names)
        if (length(ncl$taxaNames) == nrow(tipData)) {
            rownames(tipData) <- ncl$taxaNames
        }
        else stop("phylobase doesn't deal with multiple taxa block at this time.")
    }
    else {
        tipData <- NULL
    }

    if (returnTrees && length(ncl$trees) > 0) {
        listTrees <- vector("list", length(ncl$trees))

        for (i in 1:length(ncl$trees)) {

            isRooted <- is_rooted(ncl$parentVector[[i]])

            edgeMat <- get_edge_matrix(ncl$parentVector[[i]], isRooted)

            edgeLgth <- get_edge_length(ncl$branchLengthVector[[i]],
                                        ncl$parentVector[[i]],
                                        isRooted)

            tipLbl <- ncl$taxonLabelVector[[i]]

            if (convert.edge.length) {
                edgeLgth[edgeLgth < 0] <- 0
            }

            if (check.node.labels == "asdata" &&
                !has_node_labels(ncl$nodeLabelsVector[[i]])) {
                warning("Could not use value \"asdata\" for ",
                        "check.node.labels because there are no ",
                        "labels associated with the tree")
                check.node.labels <- "drop"
            }


            if (has_node_labels(ncl$nodeLabelsVector[[i]]) &&
                !identical(check.node.labels, "drop")) {
                nodeLbl <- ncl$nodeLabelsVector[[i]]
                rootNd <- attr(edgeMat, "root")
                nodeLbl[rootNd] <- nodeLbl[1]
                node_pos <- (length(tipLbl)+1):length(nodeLbl)
                nodeLbl <- nodeLbl[node_pos]

                if (identical(check.node.labels, "asdata")) {
                    tr <- phylo4(x = edgeMat,
                                 edge.length = edgeLgth,
                                 tip.label = tipLbl)
                    nodeDt <- label_to_data(nodeLbl, row.names = node_pos)
                    tr <- phylo4d(tr, node.data = nodeDt)
                } else {

                    tr <- phylo4(x = edgeMat,
                                 edge.length = edgeLgth,
                                 tip.label = tipLbl,
                                 node.label = nodeLbl)
                }
            } else {
                tr <- phylo4(x = edgeMat,
                             edge.length = edgeLgth,
                             tip.label = tipLbl)


            }

            listTrees[[i]] <- tr
            if (simplify) break
        }

        if (length(listTrees) == 1 || simplify)
            listTrees <- listTrees[[1]]

    } else {
        listTrees <- NULL
    }

###
    switch(type,
           "data" = {
               if (is.null(tipData)) {
                   toRet <- NULL
               }
               else {
                   toRet <- tipData
               }
           },
           "tree" = {
               if (is.null(listTrees)) {
                   toRet <- NULL
               }
               else {
                   toRet <- listTrees
               }
           },
           "all" = {
               if (is.null(tipData) && is.null(listTrees)) {
                   toRet <- NULL
               }
               else if (is.null(tipData)) {
                   toRet <- listTrees
               }
               else if (is.null(listTrees)) {
                   toRet <- tipData
               }
               else {
                   if (length(listTrees) > 1) {
                       toRet <- lapply(listTrees, function(tr)
                                       addData(tr, tip.data=tipData, ...))
                   }
                   else toRet <- addData(listTrees, tip.data=tipData, ...)
               }
           })
    toRet
}


## check if the implicit root is dichotomous
is_rooted <- function(parentVector) {
    tab_edg <- table(parentVector)
    if (tabulate(parentVector)[which(parentVector == 0)] > 2)
        FALSE
    else TRUE
}


## Returns the edge matrix from the parentVector (the i^th element is
## the descendant element of node i)
get_edge_matrix <- function(parentVector, isRooted) {
    edgeMat <- cbind(ancestor = parentVector,
                     descendant = 1:length(parentVector))
    rootNd <- edgeMat[which(edgeMat[, 1] == 0), 2]
    if (!isRooted) {
        edgeMat <- edgeMat[-which(edgeMat[, 1] == 0), ]
    }
    attr(edgeMat, "root") <- rootNd
    edgeMat
}

## Returns the edge lengths (missing are represented by -999)
get_edge_length <- function(branchLengthVector, parentVector, isRooted) {
    edgeLgth <- branchLengthVector
    if (isRooted) {
        edgeLgth[which(parentVector == 0)] <- NA
    } else {
        edgeLgth <- edgeLgth[which(parentVector != 0)]
    }
    edgeLgth[edgeLgth == -999] <- NA
    edgeLgth
}

## Tests whether there are node labels
has_node_labels <- function(nodeLabelsVector) {
    any(nzchar(nodeLabelsVector))
}

##' @rdname readNexus
##' @aliases readNexus
##' @export
readNexus <- function (file, simplify=FALSE, type=c("all", "tree", "data"),
                       char.all=FALSE, polymorphic.convert=TRUE,
                       levels.uniform=FALSE, quiet=TRUE,
                       check.node.labels=c("keep", "drop", "asdata"),
                       return.labels=TRUE, check.names=TRUE, convert.edge.length=FALSE,
                       ...) {

    return(readNCL(file=file, simplify=simplify, type=type, char.all=char.all,
                   polymorphic.convert=polymorphic.convert, levels.uniform=levels.uniform,
                   quiet=quiet, check.node.labels=check.node.labels,
                   return.labels=return.labels, file.format="nexus",
                   check.names=check.names, convert.edge.length=convert.edge.length, ...))
}

##' @rdname readNexus
##' @aliases readNewick
##' @export
readNewick <- function(file, simplify=FALSE, quiet=TRUE,
                       check.node.labels=c("keep", "drop", "asdata"),
                       convert.edge.length=FALSE, ...) {

    return(readNCL(file=file, simplify=simplify, quiet=quiet,
                   check.node.labels=check.node.labels, file.format="newick",
                   convert.edge.length=convert.edge.length, ...))
}