]> git.donarmstrong.com Git - ape.git/blob - R/DNA.R
new code for reading FASTA files
[ape.git] / R / DNA.R
1 ## DNA.R (2012-12-27)
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     ans <- NextMethod("[", drop = drop)
62     class(ans) <- "DNAbin"
63     ans
64 }
65
66 as.matrix.DNAbin <- function(x, ...)
67 {
68     if (is.list(x)) {
69         if (length(unique(unlist(lapply(x, length)))) != 1)
70           stop("DNA sequences in list not of the same length.")
71         nms <- names(x)
72         n <- length(x)
73         s <- length(x[[1]])
74         x <- matrix(unlist(x), n, s, byrow = TRUE)
75         rownames(x) <- nms
76         class(x) <- "DNAbin"
77     }
78     x
79 }
80
81 as.list.DNAbin <- function(x, ...)
82 {
83     if (is.list(x)) return(x)
84     if (is.null(dim(x))) obj <- list(x) # cause is.vector() doesn't work
85     else { # matrix
86         n <- nrow(x)
87         obj <- vector("list", n)
88         for (i in 1:n) obj[[i]] <- x[i, ]
89         names(obj) <- rownames(x)
90     }
91     class(obj) <- "DNAbin"
92     obj
93 }
94
95 rbind.DNAbin <- function(...)
96 ### works only with matrices for the moment
97 {
98     obj <- list(...)
99     n <- length(obj)
100     if (n == 1) return(obj[[1]])
101     for (i in 1:n)
102         if (!is.matrix(obj[[1]]))
103             stop("the 'rbind' method for \"DNAbin\" accepts only matrices")
104     NC <- unlist(lapply(obj, ncol))
105     if (length(unique(NC)) > 1)
106         stop("matrices do not have the same number of columns.")
107     for (i in 1:n) class(obj[[i]]) <- NULL
108     for (i in 2:n) obj[[1]] <- rbind(obj[[1]], obj[[i]])
109     structure(obj[[1]], class = "DNAbin")
110 }
111
112 cbind.DNAbin <-
113     function(..., check.names = TRUE, fill.with.gaps = FALSE,
114              quiet = FALSE)
115 ### works only with matrices for the moment
116 {
117     obj <- list(...)
118     n <- length(obj)
119     if (n == 1) return(obj[[1]])
120     for (i in 1:n)
121         if (!is.matrix(obj[[1]]))
122             stop("the 'cbind' method for \"DNAbin\" accepts only matrices")
123     NR <- unlist(lapply(obj, nrow))
124     for (i in 1:n) class(obj[[i]]) <- NULL
125     if (check.names) {
126         nms <- unlist(lapply(obj, rownames))
127         if (fill.with.gaps) {
128             NC <- unlist(lapply(obj, ncol))
129             nms <- unique(nms)
130             ans <- matrix(as.raw(4), length(nms), sum(NC))
131             rownames(ans) <- nms
132             from <- 1
133             for (i in 1:n) {
134                 to <- from + NC[i] - 1
135                 tmp <- rownames(obj[[i]])
136                 nmsi <- tmp[tmp %in% nms]
137                 ans[nmsi, from:to] <- obj[[i]][nmsi, , drop = FALSE]
138                 from <- to + 1
139             }
140         } else {
141             tab <- table(nms)
142             ubi <- tab == n
143             nms <- names(tab)[which(ubi)]
144             ans <- obj[[1]][nms, , drop = FALSE]
145             for (i in 2:n)
146                 ans <- cbind(ans, obj[[i]][nms, , drop = FALSE])
147             if (!quiet && !all(ubi))
148                 warning("some rows were dropped.")
149         }
150     } else {
151         if (length(unique(NR)) > 1)
152             stop("matrices do not have the same number of rows.")
153         ans <- matrix(unlist(obj), NR)
154         rownames(ans) <- rownames(obj[[1]])
155     }
156     class(ans) <- "DNAbin"
157     ans
158 }
159
160 c.DNAbin <- function(..., recursive = FALSE)
161 {
162     if (!all(unlist(lapply(list(...), is.list))))
163         stop("the 'c' method for \"DNAbin\" accepts only lists")
164     structure(NextMethod("c"), class = "DNAbin")
165 }
166
167 print.DNAbin <- function(x, printlen = 6, digits = 3, ...)
168 {
169     if (is.list(x)) {
170         n <- length(x)
171         nms <- names(x)
172         if (n == 1) {
173             cat("1 DNA sequence in binary format stored in a list.\n\n")
174             nTot <- length(x[[1]])
175             cat("Sequence length:", nTot, "\n\n")
176             cat("Label:", nms, "\n\n")
177         } else {
178             cat(n, "DNA sequences in binary format stored in a list.\n\n")
179             tmp <- unlist(lapply(x, length))
180             nTot <- sum(tmp)
181             mini <- range(tmp)
182             maxi <- mini[2]
183             mini <- mini[1]
184             if (mini == maxi)
185                 cat("All sequences of same length:", maxi, "\n")
186             else {
187                 cat("Mean sequence length:", round(mean(tmp), 3), "\n")
188                 cat("   Shortest sequence:", mini, "\n")
189                 cat("    Longest sequence:", maxi, "\n")
190             }
191             TAIL <- "\n\n"
192             if (printlen < n) {
193                 nms <- nms[1:printlen]
194                 TAIL <- "...\n\n"
195             }
196             cat("\nLabels:", paste(nms, collapse = " "), TAIL)
197         }
198     } else {
199         nTot <- length(x)
200         if (is.matrix(x)) {
201             nd <- dim(x)
202             nms <- rownames(x)
203             cat(nd[1], "DNA sequences in binary format stored in a matrix.\n\n")
204             cat("All sequences of same length:", nd[2], "\n")
205             TAIL <- "\n\n"
206             if (printlen < nd[1]) {
207                 nms <- nms[1:printlen]
208                 TAIL <- "...\n\n"
209             }
210             cat("\nLabels:", paste(nms, collapse = " "), TAIL)
211         } else {
212             cat("1 DNA sequence in binary format stored in a vector.\n\n")
213             cat("Sequence length:", nTot, "\n\n")
214         }
215     }
216     if (nTot <= 1e6) {
217         cat("Base composition:\n")
218         print(round(base.freq(x), digits))
219     } else cat("More than 1 million nucleotides: not printing base composition\n")
220 }
221
222 as.DNAbin <- function(x, ...) UseMethod("as.DNAbin")
223
224 ._cs_ <- c("a", "g", "c", "t", "r", "m", "w", "s", "k",
225            "y", "v", "h", "d", "b", "n", "-", "?")
226
227 ._bs_ <- c(136, 72, 40, 24, 192, 160, 144, 96, 80,
228            48, 224, 176, 208, 112, 240, 4, 2)
229
230 as.DNAbin.character <- function(x, ...)
231 {
232     n <- length(x)
233     ans <- raw(n)
234     for (i in 1:15)
235       ans[which(x == ._cs_[i])] <- as.raw(._bs_[i])
236     ans[which(x == "-")] <- as.raw(4)
237     ans[which(x == "?")] <- as.raw(2)
238     if (is.matrix(x)) {
239         dim(ans) <- dim(x)
240         dimnames(ans) <- dimnames(x)
241     }
242     class(ans) <- "DNAbin"
243     ans
244 }
245
246 as.DNAbin.alignment <- function(x, ...)
247 {
248     n <- x$nb
249     x$seq <- tolower(x$seq)
250     ans <- matrix("", n, nchar(x$seq[1]))
251     for (i in 1:n)
252         ans[i, ] <- strsplit(x$seq[i], "")[[1]]
253     rownames(ans) <- gsub(" +$", "", gsub("^ +", "", x$nam))
254     as.DNAbin.character(ans)
255 }
256
257 as.DNAbin.list <- function(x, ...)
258 {
259     obj <- lapply(x, as.DNAbin)
260     class(obj) <- "DNAbin"
261     obj
262 }
263
264 as.character.DNAbin <- function(x, ...)
265 {
266     f <- function(xx) {
267         ans <- character(length(xx))
268         for (i in 1:15)
269           ans[which(xx == ._bs_[i])] <- ._cs_[i]
270         ans[which(xx == 4)] <- "-"
271         ans[which(xx == 2)] <- "?"
272         if (is.matrix(xx)) {
273             dim(ans) <- dim(xx)
274             dimnames(ans) <- dimnames(xx)
275         }
276         ans
277     }
278     if (is.list(x)) lapply(x, f) else f(x)
279 }
280
281 base.freq <- function(x, freq = FALSE, all = FALSE)
282 {
283     f <- function(x)
284         .C("BaseProportion", x, as.integer(length(x)), double(17),
285            DUP = FALSE, NAOK = TRUE, PACKAGE = "ape")[[3]]
286
287     if (is.list(x)) {
288         BF <- rowSums(sapply(x, f))
289         n <- sum(sapply(x, length))
290     } else {
291         n <- length(x)
292         BF <-.C("BaseProportion", x, as.integer(n), double(17),
293                 DUP = FALSE, NAOK = TRUE, PACKAGE = "ape")[[3]]
294     }
295
296     names(BF) <- c("a", "c", "g", "t", "r", "m", "w", "s",
297                    "k", "y", "v", "h", "d", "b", "n", "-", "?")
298     if (all) {
299         if (!freq) BF <- BF / n
300     } else {
301         BF <- BF[1:4]
302         if (!freq) BF <- BF / sum(BF)
303     }
304     BF
305 }
306
307 Ftab <- function(x, y = NULL)
308 {
309     if (is.null(y)) {
310         if (is.list(x)) {
311             y <- x[[2]]
312             x <- x[[1]]
313             if (length(x) != length(y))
314                 stop("'x' and 'y' not of same lenght")
315         } else { # 'x' is a matrix
316             y <- x[2, , drop = TRUE]
317             x <- x[1, , drop = TRUE]
318         }
319     } else {
320         x <- as.vector(x)
321         y <- as.vector(y)
322         if (length(x) != length(y))
323             stop("'x' and 'y' not of same lenght")
324     }
325     out <- matrix(0, 4, 4)
326     k <- c(136, 40, 72, 24)
327     for (i in 1:4) {
328         a <- x == k[i]
329         for (j in 1:4) {
330             b <- y == k[j]
331             out[i, j] <- sum(a & b)
332         }
333     }
334     dimnames(out)[1:2] <- list(c("a", "c", "g", "t"))
335     out
336 }
337
338 GC.content <- function(x) sum(base.freq(x)[2:3])
339
340 seg.sites <- function(x)
341 {
342     if (is.list(x)) x <- as.matrix(x)
343     if (is.vector(x)) n <- 1
344     else { # 'x' is a matrix
345         n <- dim(x)
346         s <- n[2]
347         n <- n[1]
348     }
349     if (n == 1) return(integer(0))
350     ans <- .C("SegSites", x, as.integer(n), as.integer(s),
351               integer(s), DUP = FALSE, NAOK = TRUE, PACKAGE = "ape")
352     which(as.logical(ans[[4]]))
353 }
354
355 dist.dna <- function(x, model = "K80", variance = FALSE, gamma = FALSE,
356                      pairwise.deletion = FALSE, base.freq = NULL,
357                      as.matrix = FALSE)
358 {
359     MODELS <- c("RAW", "JC69", "K80", "F81", "K81", "F84", "T92", "TN93",
360                 "GG95", "LOGDET", "BH87", "PARALIN", "N", "TS", "TV",
361                 "INDEL", "INDELBLOCK")
362     imod <- pmatch(toupper(model), MODELS)
363     if (is.na(imod))
364         stop(paste("'model' must be one of:",
365                    paste("\"", MODELS, "\"", sep = "", collapse = " ")))
366     if (imod == 11 && variance) {
367         warning("computing variance not available for model BH87")
368         variance <- FALSE
369     }
370     if (gamma && imod %in% c(1, 5:7, 9:17)) {
371         warning(paste("gamma-correction not available for model", model))
372         gamma <- FALSE
373     }
374     if (is.list(x)) x <- as.matrix(x)
375     nms <- dimnames(x)[[1]]
376     n <- dim(x)
377     s <- n[2]
378     n <- n[1]
379
380     if (imod %in% c(4, 6:8)) {
381         BF <- if (is.null(base.freq)) base.freq(x) else base.freq
382     } else BF <- 0
383
384     if (imod %in% 16:17) pairwise.deletion <- TRUE
385
386     if (!pairwise.deletion) {
387         keep <- .C("GlobalDeletionDNA", x, n, s,
388                    rep(1L, s), PACKAGE = "ape")[[4]]
389         x <- x[, as.logical(keep)]
390         s <- dim(x)[2]
391     }
392     Ndist <- if (imod == 11) n*n else n*(n - 1)/2
393     var <- if (variance) double(Ndist) else 0
394     if (!gamma) gamma <- alpha <- 0
395     else alpha <- gamma <- 1
396     d <- .C("dist_dna", x, as.integer(n), as.integer(s), imod,
397             double(Ndist), BF, as.integer(pairwise.deletion),
398             as.integer(variance), var, as.integer(gamma),
399             alpha, DUP = FALSE, NAOK = TRUE, PACKAGE = "ape")
400     if (variance) var <- d[[9]]
401     d <- d[[5]]
402     if (imod == 11) {
403         dim(d) <- c(n, n)
404         dimnames(d) <- list(nms, nms)
405     } else {
406         attr(d, "Size") <- n
407         attr(d, "Labels") <- nms
408         attr(d, "Diag") <- attr(d, "Upper") <- FALSE
409         attr(d, "call") <- match.call()
410         attr(d, "method") <- model
411         class(d) <- "dist"
412         if (as.matrix) d <- as.matrix(d)
413     }
414     if (variance) attr(d, "variance") <- var
415     d
416 }
417
418 image.DNAbin <- function(x, what, col, bg = "white", xlab = "", ylab = "",
419                          show.labels = TRUE, cex.lab = 1, legend = TRUE, ...)
420 {
421     what <-
422         if (missing(what)) c("a", "g", "c", "t", "n", "-") else tolower(what)
423     if (missing(col))
424         col <- c("red", "yellow", "green", "blue", "grey", "black")
425     n <- (dx <- dim(x))[1] # number of sequences
426     s <- dx[2] # number of sites
427     y <- integer(N <- length(x))
428     ncl <- length(what)
429     col <- rep(col, length.out = ncl)
430     brks <- 0.5:(ncl + 0.5)
431     sm <- 0L
432     for (i in ncl:1) {
433         k <- ._bs_[._cs_ == what[i]]
434         sel <- which(x == k)
435         if (L <- length(sel)) {
436             y[sel] <- i
437             sm <- sm + L
438         } else {
439             what <- what[-i]
440             col <- col[-i]
441             brks <- brks[-i]
442         }
443     }
444     dim(y) <- dx
445     ## if there's no 0 in y, must drop 'bg' from the cols passed to image:
446     if (sm == N) {
447         leg.co <- co <- col
448         leg.txt <- toupper(what)
449     } else {
450         co <- c(bg, col)
451         leg.txt <- c(toupper(what), "others")
452         leg.co <- c(col, bg)
453         brks <- c(-0.5, brks)
454     }
455     yaxt <- if (show.labels) "n" else "s"
456     graphics::image.default(1:s, 1:n, t(y), col = co, xlab = xlab,
457                             ylab = ylab, yaxt = yaxt, breaks = brks, ...)
458     if (show.labels)
459         mtext(rownames(x), side = 2, line = 0.1, at = 1:n,
460               cex = cex.lab, adj = 1, las = 1)
461     if (legend) {
462         psr <- par("usr")
463         xx <- psr[2]/2
464         yy <- psr[4] * (0.5 + 0.5/par("plt")[4])
465         legend(xx, yy, legend = leg.txt, pch = 22, pt.bg = leg.co,
466                pt.cex = 2, bty = "n", xjust = 0.5, yjust = 0.5,
467                horiz = TRUE, xpd = TRUE)
468     }
469 }
470
471 where <- function(x, pattern)
472 {
473     pat <- as.DNAbin(strsplit(pattern, NULL)[[1]])
474     p <- as.integer(length(pat))
475
476     foo <- function(x, pat, p) {
477         s <- as.integer(length(x))
478         if (s < p) stop("sequence shorter than the pattern")
479         ans <- .C("where", x, pat, s, p, integer(s), 0L,
480                   DUP = FALSE, NAOK = TRUE, PACKAGE = "ape")
481         n <- ans[[6]]
482         if (n) ans[[5]][seq_len(n)] - p + 2L else integer()
483     }
484
485     if (is.list(x)) return(lapply(x, foo, pat = pat, p = p))
486     if (is.matrix(x)) {
487         n <- nrow(x)
488         res <- vector("list", n)
489         for (i in seq_along(n))
490             res[[i]] <- foo(x[i, , drop = TRUE], pat, p)
491         names(res) <- rownames(x)
492         return(res)
493     }
494     foo(x, pat, p) # if x is a vector
495 }