3 ## Manipulations and Comparisons of DNA Sequences
5 ## Copyright 2002-2012 Emmanuel Paradis
7 ## This file is part of the R-package `ape'.
8 ## See the file ../COPYING for licensing issues.
10 labels.DNAbin <- function(object, ...)
12 if (is.list(object)) return(names(object))
13 if (is.matrix(object)) return(rownames(object))
17 del.gaps <- function(x)
19 deleteGaps <- function(x) {
21 if (length(i)) x[-i] else x
24 if (!inherits(x, "DNAbin")) x <- as.DNAbin(x)
27 y <- vector("list", n)
28 for (i in 1:n) y[[i]] <- x[i, ]
29 names(y) <- rownames(x)
33 if (!is.list(x)) return(deleteGaps(x))
34 x <- lapply(x, deleteGaps)
39 as.alignment <- function(x)
41 if (is.list(x)) n <- length(x)
42 if (is.matrix(x)) n <- dim(x)[1]
47 seq[i] <- paste(x[[i]], collapse = "")
50 nam <- dimnames(x)[[1]]
52 seq[i] <- paste(x[i, ], collapse = "")
54 obj <- list(nb = n, seq = seq, nam = nam, com = NA)
55 class(obj) <- "alignment"
59 "[.DNAbin" <- function(x, i, j, drop = FALSE)
64 if (nargs() == 2 && !missing(i)) ans <- x[i]
67 if (missing(i)) i <- 1:nd[1]
68 if (missing(j)) j <- 1:nd[2]
69 ans <- x[i, j, drop = drop]
72 if (missing(i)) i <- 1:length(x)
79 as.matrix.DNAbin <- function(x, ...)
82 if (length(unique(unlist(lapply(x, length)))) != 1)
83 stop("DNA sequences in list not of the same length.")
87 x <- matrix(unlist(x), n, s, byrow = TRUE)
94 as.list.DNAbin <- function(x, ...)
96 if (is.list(x)) return(x)
97 if (is.null(dim(x))) obj <- list(x) # cause is.vector() doesn't work
100 obj <- vector("list", n)
101 for (i in 1:n) obj[[i]] <- x[i, ]
102 names(obj) <- rownames(x)
104 class(obj) <- "DNAbin"
108 rbind.DNAbin <- function(...)
109 ### works only with matrices for the moment
113 if (n == 1) return(obj[[1]])
115 if (!is.matrix(obj[[1]]))
116 stop("the 'rbind' method for \"DNAbin\" accepts only matrices")
117 NC <- unlist(lapply(obj, ncol))
118 if (length(unique(NC)) > 1)
119 stop("matrices do not have the same number of columns.")
120 for (i in 1:n) class(obj[[i]]) <- NULL
121 for (i in 2:n) obj[[1]] <- rbind(obj[[1]], obj[[i]])
122 structure(obj[[1]], class = "DNAbin")
126 function(..., check.names = TRUE, fill.with.gaps = FALSE,
128 ### works only with matrices for the moment
132 if (n == 1) return(obj[[1]])
134 if (!is.matrix(obj[[1]]))
135 stop("the 'cbind' method for \"DNAbin\" accepts only matrices")
136 NR <- unlist(lapply(obj, nrow))
137 for (i in 1:n) class(obj[[i]]) <- NULL
139 nms <- unlist(lapply(obj, rownames))
140 if (fill.with.gaps) {
141 NC <- unlist(lapply(obj, ncol))
143 ans <- matrix(as.raw(4), length(nms), sum(NC))
147 to <- from + NC[i] - 1
148 tmp <- rownames(obj[[i]])
149 nmsi <- tmp[tmp %in% nms]
150 ans[nmsi, from:to] <- obj[[i]][nmsi, , drop = FALSE]
156 nms <- names(tab)[which(ubi)]
157 ans <- obj[[1]][nms, , drop = FALSE]
159 ans <- cbind(ans, obj[[i]][nms, , drop = FALSE])
160 if (!quiet && !all(ubi))
161 warning("some rows were dropped.")
164 if (length(unique(NR)) > 1)
165 stop("matrices do not have the same number of rows.")
166 ans <- matrix(unlist(obj), NR)
167 rownames(ans) <- rownames(obj[[1]])
169 class(ans) <- "DNAbin"
173 c.DNAbin <- function(..., recursive = FALSE)
175 if (!all(unlist(lapply(list(...), is.list))))
176 stop("the 'c' method for \"DNAbin\" accepts only lists")
177 structure(NextMethod("c"), class = "DNAbin")
180 print.DNAbin <- function(x, printlen = 6, digits = 3, ...)
186 cat("1 DNA sequence in binary format stored in a list.\n\n")
187 nTot <- length(x[[1]])
188 cat("Sequence length:", nTot, "\n\n")
189 cat("Label:", nms, "\n\n")
191 cat(n, "DNA sequences in binary format stored in a list.\n\n")
192 tmp <- unlist(lapply(x, length))
198 cat("All sequences of same length:", maxi, "\n")
200 cat("Mean sequence length:", round(mean(tmp), 3), "\n")
201 cat(" Shortest sequence:", mini, "\n")
202 cat(" Longest sequence:", maxi, "\n")
206 nms <- nms[1:printlen]
209 cat("\nLabels:", paste(nms, collapse = " "), TAIL)
216 cat(nd[1], "DNA sequences in binary format stored in a matrix.\n\n")
217 cat("All sequences of same length:", nd[2], "\n")
219 if (printlen < nd[1]) {
220 nms <- nms[1:printlen]
223 cat("\nLabels:", paste(nms, collapse = " "), TAIL)
225 cat("1 DNA sequence in binary format stored in a vector.\n\n")
226 cat("Sequence length:", nTot, "\n\n")
230 cat("Base composition:\n")
231 print(round(base.freq(x), digits))
232 } else cat("More than 1 million nucleotides: not printing base composition\n")
235 as.DNAbin <- function(x, ...) UseMethod("as.DNAbin")
237 ._cs_ <- c("a", "g", "c", "t", "r", "m", "w", "s", "k",
238 "y", "v", "h", "d", "b", "n", "-", "?")
240 ._bs_ <- c(136, 72, 40, 24, 192, 160, 144, 96, 80,
241 48, 224, 176, 208, 112, 240, 4, 2)
243 as.DNAbin.character <- function(x, ...)
248 ans[which(x == ._cs_[i])] <- as.raw(._bs_[i])
249 ans[which(x == "-")] <- as.raw(4)
250 ans[which(x == "?")] <- as.raw(2)
253 dimnames(ans) <- dimnames(x)
255 class(ans) <- "DNAbin"
259 as.DNAbin.alignment <- function(x, ...)
262 x$seq <- tolower(x$seq)
263 ans <- matrix("", n, nchar(x$seq[1]))
265 ans[i, ] <- strsplit(x$seq[i], "")[[1]]
266 rownames(ans) <- gsub(" +$", "", gsub("^ +", "", x$nam))
267 as.DNAbin.character(ans)
270 as.DNAbin.list <- function(x, ...)
272 obj <- lapply(x, as.DNAbin)
273 class(obj) <- "DNAbin"
277 as.character.DNAbin <- function(x, ...)
280 ans <- character(length(xx))
282 ans[which(xx == ._bs_[i])] <- ._cs_[i]
283 ans[which(xx == 4)] <- "-"
284 ans[which(xx == 2)] <- "?"
287 dimnames(ans) <- dimnames(xx)
291 if (is.list(x)) lapply(x, f) else f(x)
294 base.freq <- function(x, freq = FALSE, all = FALSE)
296 if (is.list(x)) x <- unlist(x)
298 BF <-.C("BaseProportion", x, as.integer(n), double(17),
299 DUP = FALSE, NAOK = TRUE, PACKAGE = "ape")[[3]]
300 names(BF) <- c("a", "c", "g", "t", "r", "m", "w", "s",
301 "k", "y", "v", "h", "d", "b", "n", "-", "?")
303 if (!freq) BF <- BF / n
306 if (!freq) BF <- BF / sum(BF)
311 Ftab <- function(x, y = NULL)
317 if (length(x) != length(y))
318 stop("'x' and 'y' not of same lenght")
319 } else { # 'x' is a matrix
320 y <- x[2, , drop = TRUE]
321 x <- x[1, , drop = TRUE]
326 if (length(x) != length(y))
327 stop("'x' and 'y' not of same lenght")
329 out <- matrix(0, 4, 4)
330 k <- c(136, 40, 72, 24)
335 out[i, j] <- sum(a & b)
338 dimnames(out)[1:2] <- list(c("a", "c", "g", "t"))
342 GC.content <- function(x) sum(base.freq(x)[2:3])
344 seg.sites <- function(x)
346 if (is.list(x)) x <- as.matrix(x)
347 if (is.vector(x)) n <- 1
348 else { # 'x' is a matrix
353 if (n == 1) return(integer(0))
354 ans <- .C("SegSites", x, as.integer(n), as.integer(s),
355 integer(s), DUP = FALSE, NAOK = TRUE, PACKAGE = "ape")
356 which(as.logical(ans[[4]]))
359 dist.dna <- function(x, model = "K80", variance = FALSE, gamma = FALSE,
360 pairwise.deletion = FALSE, base.freq = NULL,
363 MODELS <- c("RAW", "JC69", "K80", "F81", "K81", "F84", "T92", "TN93",
364 "GG95", "LOGDET", "BH87", "PARALIN", "N", "TS", "TV",
365 "INDEL", "INDELBLOCK")
366 imod <- pmatch(toupper(model), MODELS)
368 stop(paste("'model' must be one of:",
369 paste("\"", MODELS, "\"", sep = "", collapse = " ")))
370 if (imod == 11 && variance) {
371 warning("computing variance not available for model BH87")
374 if (gamma && imod %in% c(1, 5:7, 9:17)) {
375 warning(paste("gamma-correction not available for model", model))
378 if (is.list(x)) x <- as.matrix(x)
379 nms <- dimnames(x)[[1]]
384 if (imod %in% c(4, 6:8)) {
385 BF <- if (is.null(base.freq)) base.freq(x) else base.freq
388 if (imod %in% 16:17) pairwise.deletion <- TRUE
390 if (!pairwise.deletion) {
391 keep <- .C("GlobalDeletionDNA", x, n, s,
392 rep(1L, s), PACKAGE = "ape")[[4]]
393 x <- x[, as.logical(keep)]
396 Ndist <- if (imod == 11) n*n else n*(n - 1)/2
397 var <- if (variance) double(Ndist) else 0
398 if (!gamma) gamma <- alpha <- 0
399 else alpha <- gamma <- 1
400 d <- .C("dist_dna", x, as.integer(n), as.integer(s), imod,
401 double(Ndist), BF, as.integer(pairwise.deletion),
402 as.integer(variance), var, as.integer(gamma),
403 alpha, DUP = FALSE, NAOK = TRUE, PACKAGE = "ape")
404 if (variance) var <- d[[9]]
408 dimnames(d) <- list(nms, nms)
411 attr(d, "Labels") <- nms
412 attr(d, "Diag") <- attr(d, "Upper") <- FALSE
413 attr(d, "call") <- match.call()
414 attr(d, "method") <- model
416 if (as.matrix) d <- as.matrix(d)
418 if (variance) attr(d, "variance") <- var
422 image.DNAbin <- function(x, what, col, bg = "white", xlab = "", ylab = "",
423 show.labels = TRUE, cex.lab = 1, legend = TRUE, ...)
426 if (missing(what)) c("a", "g", "c", "t", "n", "-") else tolower(what)
428 col <- c("red", "yellow", "green", "blue", "grey", "black")
429 n <- (dx <- dim(x))[1] # number of sequences
430 s <- dx[2] # number of sites
431 y <- integer(N <- length(x))
433 col <- rep(col, length.out = ncl)
434 brks <- 0.5:(ncl + 0.5)
437 k <- ._bs_[._cs_ == what[i]]
439 if (L <- length(sel)) {
449 ## if there's no 0 in y, must drop 'bg' from the cols passed to image:
452 leg.txt <- toupper(what)
455 leg.txt <- c(toupper(what), "others")
457 brks <- c(-0.5, brks)
459 yaxt <- if (show.labels) "n" else "s"
460 graphics::image.default(1:s, 1:n, t(y), col = co, xlab = xlab,
461 ylab = ylab, yaxt = yaxt, breaks = brks, ...)
463 mtext(rownames(x), side = 2, line = 0.1, at = 1:n,
464 cex = cex.lab, adj = 1, las = 1)
468 yy <- psr[4] * (0.5 + 0.5/par("plt")[4])
469 legend(xx, yy, legend = leg.txt, pch = 22, pt.bg = leg.co,
470 pt.cex = 2, bty = "n", xjust = 0.5, yjust = 0.5,
471 horiz = TRUE, xpd = TRUE)