]> git.donarmstrong.com Git - ape.git/blob - R/DNA.R
31ef4bb5988916a26a1346ecaf8d585c16d182d5
[ape.git] / R / DNA.R
1 ## DNA.R (2012-11-28)
2
3 ##   Manipulations and Comparisons of DNA Sequences
4
5 ## Copyright 2002-2012 Emmanuel Paradis
6
7 ## This file is part of the R-package `ape'.
8 ## See the file ../COPYING for licensing issues.
9
10 labels.DNAbin <- function(object, ...)
11 {
12     if (is.list(object)) return(names(object))
13     if (is.matrix(object)) return(rownames(object))
14     NULL
15 }
16
17 del.gaps <- function(x)
18 {
19     deleteGaps <- function(x) {
20         i <- which(x == 4)
21         if (length(i)) x[-i] else x
22     }
23
24     if (!inherits(x, "DNAbin")) x <- as.DNAbin(x)
25     if (is.matrix(x)) {
26         n <- dim(x)[1]
27         y <- vector("list", n)
28         for (i in 1:n) y[[i]] <- x[i, ]
29         names(y) <- rownames(x)
30         x <- y
31         rm(y)
32     }
33     if (!is.list(x)) return(deleteGaps(x))
34     x <- lapply(x, deleteGaps)
35     class(x) <- "DNAbin"
36     x
37 }
38
39 as.alignment <- function(x)
40 {
41     if (is.list(x)) n <- length(x)
42     if (is.matrix(x)) n <- dim(x)[1]
43     seq <- character(n)
44     if (is.list(x)) {
45         nam <- names(x)
46         for (i in 1:n)
47           seq[i] <- paste(x[[i]], collapse = "")
48     }
49     if (is.matrix(x)) {
50         nam <- dimnames(x)[[1]]
51         for (i in 1:n)
52           seq[i] <- paste(x[i, ], collapse = "")
53     }
54     obj <- list(nb = n, seq = seq, nam = nam, com = NA)
55     class(obj) <- "alignment"
56     obj
57 }
58
59 "[.DNAbin" <- function(x, i, j, drop = FALSE)
60 {
61     oc <- oldClass(x)
62     class(x) <- NULL
63     if (is.matrix(x)) {
64         if (nargs() == 2 && !missing(i)) ans <- x[i]
65         else {
66             nd <- dim(x)
67             if (missing(i)) i <- 1:nd[1]
68             if (missing(j)) j <- 1:nd[2]
69             ans <- x[i, j, drop = drop]
70         }
71     } else {
72         if (missing(i)) i <- 1:length(x)
73         ans <- x[i]
74     }
75     class(ans) <- oc
76     ans
77 }
78
79 as.matrix.DNAbin <- function(x, ...)
80 {
81     if (is.list(x)) {
82         if (length(unique(unlist(lapply(x, length)))) != 1)
83           stop("DNA sequences in list not of the same length.")
84         nms <- names(x)
85         n <- length(x)
86         s <- length(x[[1]])
87         x <- matrix(unlist(x), n, s, byrow = TRUE)
88         rownames(x) <- nms
89         class(x) <- "DNAbin"
90     }
91     x
92 }
93
94 as.list.DNAbin <- function(x, ...)
95 {
96     if (is.list(x)) return(x)
97     if (is.null(dim(x))) obj <- list(x) # cause is.vector() doesn't work
98     else { # matrix
99         n <- nrow(x)
100         obj <- vector("list", n)
101         for (i in 1:n) obj[[i]] <- x[i, ]
102         names(obj) <- rownames(x)
103     }
104     class(obj) <- "DNAbin"
105     obj
106 }
107
108 rbind.DNAbin <- function(...)
109 ### works only with matrices for the moment
110 {
111     obj <- list(...)
112     n <- length(obj)
113     if (n == 1) return(obj[[1]])
114     for (i in 1:n)
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")
123 }
124
125 cbind.DNAbin <-
126     function(..., check.names = TRUE, fill.with.gaps = FALSE,
127              quiet = FALSE)
128 ### works only with matrices for the moment
129 {
130     obj <- list(...)
131     n <- length(obj)
132     if (n == 1) return(obj[[1]])
133     for (i in 1:n)
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
138     if (check.names) {
139         nms <- unlist(lapply(obj, rownames))
140         if (fill.with.gaps) {
141             NC <- unlist(lapply(obj, ncol))
142             nms <- unique(nms)
143             ans <- matrix(as.raw(4), length(nms), sum(NC))
144             rownames(ans) <- nms
145             from <- 1
146             for (i in 1:n) {
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]
151                 from <- to + 1
152             }
153         } else {
154             tab <- table(nms)
155             ubi <- tab == n
156             nms <- names(tab)[which(ubi)]
157             ans <- obj[[1]][nms, , drop = FALSE]
158             for (i in 2:n)
159                 ans <- cbind(ans, obj[[i]][nms, , drop = FALSE])
160             if (!quiet && !all(ubi))
161                 warning("some rows were dropped.")
162         }
163     } else {
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]])
168     }
169     class(ans) <- "DNAbin"
170     ans
171 }
172
173 c.DNAbin <- function(..., recursive = FALSE)
174 {
175     if (!all(unlist(lapply(list(...), is.list))))
176         stop("the 'c' method for \"DNAbin\" accepts only lists")
177     structure(NextMethod("c"), class = "DNAbin")
178 }
179
180 print.DNAbin <- function(x, printlen = 6, digits = 3, ...)
181 {
182     if (is.list(x)) {
183         n <- length(x)
184         nms <- names(x)
185         if (n == 1) {
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")
190         } else {
191             cat(n, "DNA sequences in binary format stored in a list.\n\n")
192             tmp <- unlist(lapply(x, length))
193             nTot <- sum(tmp)
194             mini <- range(tmp)
195             maxi <- mini[2]
196             mini <- mini[1]
197             if (mini == maxi)
198                 cat("All sequences of same length:", maxi, "\n")
199             else {
200                 cat("Mean sequence length:", round(mean(tmp), 3), "\n")
201                 cat("   Shortest sequence:", mini, "\n")
202                 cat("    Longest sequence:", maxi, "\n")
203             }
204             TAIL <- "\n\n"
205             if (printlen < n) {
206                 nms <- nms[1:printlen]
207                 TAIL <- "...\n\n"
208             }
209             cat("\nLabels:", paste(nms, collapse = " "), TAIL)
210         }
211     } else {
212         nTot <- length(x)
213         if (is.matrix(x)) {
214             nd <- dim(x)
215             nms <- rownames(x)
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")
218             TAIL <- "\n\n"
219             if (printlen < nd[1]) {
220                 nms <- nms[1:printlen]
221                 TAIL <- "...\n\n"
222             }
223             cat("\nLabels:", paste(nms, collapse = " "), TAIL)
224         } else {
225             cat("1 DNA sequence in binary format stored in a vector.\n\n")
226             cat("Sequence length:", nTot, "\n\n")
227         }
228     }
229     if (nTot <= 1e6) {
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")
233 }
234
235 as.DNAbin <- function(x, ...) UseMethod("as.DNAbin")
236
237 ._cs_ <- c("a", "g", "c", "t", "r", "m", "w", "s", "k",
238            "y", "v", "h", "d", "b", "n", "-", "?")
239
240 ._bs_ <- c(136, 72, 40, 24, 192, 160, 144, 96, 80,
241            48, 224, 176, 208, 112, 240, 4, 2)
242
243 as.DNAbin.character <- function(x, ...)
244 {
245     n <- length(x)
246     ans <- raw(n)
247     for (i in 1:15)
248       ans[which(x == ._cs_[i])] <- as.raw(._bs_[i])
249     ans[which(x == "-")] <- as.raw(4)
250     ans[which(x == "?")] <- as.raw(2)
251     if (is.matrix(x)) {
252         dim(ans) <- dim(x)
253         dimnames(ans) <- dimnames(x)
254     }
255     class(ans) <- "DNAbin"
256     ans
257 }
258
259 as.DNAbin.alignment <- function(x, ...)
260 {
261     n <- x$nb
262     x$seq <- tolower(x$seq)
263     ans <- matrix("", n, nchar(x$seq[1]))
264     for (i in 1:n)
265         ans[i, ] <- strsplit(x$seq[i], "")[[1]]
266     rownames(ans) <- gsub(" +$", "", gsub("^ +", "", x$nam))
267     as.DNAbin.character(ans)
268 }
269
270 as.DNAbin.list <- function(x, ...)
271 {
272     obj <- lapply(x, as.DNAbin)
273     class(obj) <- "DNAbin"
274     obj
275 }
276
277 as.character.DNAbin <- function(x, ...)
278 {
279     f <- function(xx) {
280         ans <- character(length(xx))
281         for (i in 1:15)
282           ans[which(xx == ._bs_[i])] <- ._cs_[i]
283         ans[which(xx == 4)] <- "-"
284         ans[which(xx == 2)] <- "?"
285         if (is.matrix(xx)) {
286             dim(ans) <- dim(xx)
287             dimnames(ans) <- dimnames(xx)
288         }
289         ans
290     }
291     if (is.list(x)) lapply(x, f) else f(x)
292 }
293
294 base.freq <- function(x, freq = FALSE, all = FALSE)
295 {
296     if (is.list(x)) x <- unlist(x)
297     n <- length(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", "-", "?")
302     if (all) {
303         if (!freq) BF <- BF / n
304     } else {
305         BF <- BF[1:4]
306         if (!freq) BF <- BF / sum(BF)
307     }
308     BF
309 }
310
311 Ftab <- function(x, y = NULL)
312 {
313     if (is.null(y)) {
314         if (is.list(x)) {
315             y <- x[[2]]
316             x <- x[[1]]
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]
322         }
323     } else {
324         x <- as.vector(x)
325         y <- as.vector(y)
326         if (length(x) != length(y))
327             stop("'x' and 'y' not of same lenght")
328     }
329     out <- matrix(0, 4, 4)
330     k <- c(136, 40, 72, 24)
331     for (i in 1:4) {
332         a <- x == k[i]
333         for (j in 1:4) {
334             b <- y == k[j]
335             out[i, j] <- sum(a & b)
336         }
337     }
338     dimnames(out)[1:2] <- list(c("a", "c", "g", "t"))
339     out
340 }
341
342 GC.content <- function(x) sum(base.freq(x)[2:3])
343
344 seg.sites <- function(x)
345 {
346     if (is.list(x)) x <- as.matrix(x)
347     if (is.vector(x)) n <- 1
348     else { # 'x' is a matrix
349         n <- dim(x)
350         s <- n[2]
351         n <- n[1]
352     }
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]]))
357 }
358
359 dist.dna <- function(x, model = "K80", variance = FALSE, gamma = FALSE,
360                      pairwise.deletion = FALSE, base.freq = NULL,
361                      as.matrix = FALSE)
362 {
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)
367     if (is.na(imod))
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")
372         variance <- FALSE
373     }
374     if (gamma && imod %in% c(1, 5:7, 9:17)) {
375         warning(paste("gamma-correction not available for model", model))
376         gamma <- FALSE
377     }
378     if (is.list(x)) x <- as.matrix(x)
379     nms <- dimnames(x)[[1]]
380     n <- dim(x)
381     s <- n[2]
382     n <- n[1]
383
384     if (imod %in% c(4, 6:8)) {
385         BF <- if (is.null(base.freq)) base.freq(x) else base.freq
386     } else BF <- 0
387
388     if (imod %in% 16:17) pairwise.deletion <- TRUE
389
390     if (!pairwise.deletion) {
391         keep <- .C("GlobalDeletionDNA", x, n, s,
392                    rep(1L, s), PACKAGE = "ape")[[4]]
393         x <- x[, as.logical(keep)]
394         s <- dim(x)[2]
395     }
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]]
405     d <- d[[5]]
406     if (imod == 11) {
407         dim(d) <- c(n, n)
408         dimnames(d) <- list(nms, nms)
409     } else {
410         attr(d, "Size") <- n
411         attr(d, "Labels") <- nms
412         attr(d, "Diag") <- attr(d, "Upper") <- FALSE
413         attr(d, "call") <- match.call()
414         attr(d, "method") <- model
415         class(d) <- "dist"
416         if (as.matrix) d <- as.matrix(d)
417     }
418     if (variance) attr(d, "variance") <- var
419     d
420 }
421
422 image.DNAbin <- function(x, what, col, bg = "white", xlab = "", ylab = "",
423                          show.labels = TRUE, cex.lab = 1, legend = TRUE, ...)
424 {
425     what <-
426         if (missing(what)) c("a", "g", "c", "t", "n", "-") else tolower(what)
427     if (missing(col))
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))
432     ncl <- length(what)
433     col <- rep(col, length.out = ncl)
434     brks <- 0.5:(ncl + 0.5)
435     sm <- 0L
436     for (i in ncl:1) {
437         k <- ._bs_[._cs_ == what[i]]
438         sel <- which(x == k)
439         if (L <- length(sel)) {
440             y[sel] <- i
441             sm <- sm + L
442         } else {
443             what <- what[-i]
444             col <- col[-i]
445             brks <- brks[-i]
446         }
447     }
448     dim(y) <- dx
449     ## if there's no 0 in y, must drop 'bg' from the cols passed to image:
450     if (sm == N) {
451         leg.co <- co <- col
452         leg.txt <- toupper(what)
453     } else {
454         co <- c(bg, col)
455         leg.txt <- c(toupper(what), "others")
456         leg.co <- c(col, bg)
457         brks <- c(-0.5, brks)
458     }
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, ...)
462     if (show.labels)
463         mtext(rownames(x), side = 2, line = 0.1, at = 1:n,
464               cex = cex.lab, adj = 1, las = 1)
465     if (legend) {
466         psr <- par("usr")
467         xx <- psr[2]/2
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)
472     }
473 }
474
475 where <- function(x, pattern)
476 {
477     pat <- as.DNAbin(strsplit(pattern, NULL)[[1]])
478     p <- as.integer(length(pat))
479
480     foo <- function(x, pat, p) {
481         s <- as.integer(length(x))
482         if (s < p) stop("sequence shorter than the pattern")
483         ans <- .C("where", x, pat, s, p, integer(s), 0L,
484                   DUP = FALSE, NAOK = TRUE, PACKAGE = "ape")
485         n <- ans[[6]]
486         if (n) ans[[5]][seq_len(n)] - p + 2L else integer()
487     }
488
489     if (is.list(x)) return(lapply(x, foo, pat = pat, p = p))
490     if (is.matrix(x)) {
491         n <- nrow(x)
492         res <- vector("list", n)
493         for (i in seq_along(n))
494             res[[i]] <- foo(x[i, , drop = TRUE], pat, p)
495         names(res) <- rownames(x)
496         return(res)
497     }
498     foo(x, pat, p) # if x is a vector
499 }