]> git.donarmstrong.com Git - ape.git/blob - R/DNA.R
few corrections and fixes
[ape.git] / R / DNA.R
1 ## DNA.R (2009-10-02)
2
3 ##   Manipulations and Comparisons of DNA Sequences
4
5 ## Copyright 2002-2009 Emmanuel Paradis
6
7 ## This file is part of the R-package `ape'.
8 ## See the file ../COPYING for licensing issues.
9
10 del.gaps <- function(x)
11 {
12     deleteGaps <- function(x) {
13         i <- which(x == 4)
14         if (length(i)) x[-i] else x
15     }
16
17     if (!inherits(x, "DNAbin")) x <- as.DNAbin(x)
18     if (is.matrix(x)) {
19         n <- dim(x)[1]
20         y <- vector("list", n)
21         for (i in 1:n) y[[i]] <- x[i, ]
22         names(y) <- rownames(x)
23         x <- y
24         rm(y)
25     }
26     if (!is.list(x)) return(deleteGaps(x))
27     x <- lapply(x, deleteGaps)
28     class(x) <- "DNAbin"
29     x
30 }
31
32 as.alignment <- function(x)
33 {
34     if (is.list(x)) n <- length(x)
35     if (is.matrix(x)) n <- dim(x)[1]
36     seq <- character(n)
37     if (is.list(x)) {
38         nam <- names(x)
39         for (i in 1:n)
40           seq[i] <- paste(x[[i]], collapse = "")
41     }
42     if (is.matrix(x)) {
43         nam <- dimnames(x)[[1]]
44         for (i in 1:n)
45           seq[i] <- paste(x[i, ], collapse = "")
46     }
47     obj <- list(nb = n, seq = seq, nam = nam, com = NA)
48     class(obj) <- "alignment"
49     obj
50 }
51
52 "[.DNAbin" <- function(x, i, j, drop = TRUE)
53 {
54     oc <- oldClass(x)
55     class(x) <- NULL
56     if (is.matrix(x)) {
57         if (nargs() == 2 && !missing(i)) ans <- x[i]
58         else {
59             nd <- dim(x)
60             if (missing(i)) i <- 1:nd[1]
61             if (missing(j)) j <- 1:nd[2]
62             ans <- x[i, j, drop = drop]
63         }
64     } else {
65         if (missing(i)) i <- 1:length(x)
66         ans <- x[i]
67     }
68     class(ans) <- oc
69     ans
70 }
71
72 as.matrix.DNAbin <- function(x, ...)
73 {
74     if (is.list(x)) {
75         if (length(unique(unlist(lapply(x, length)))) != 1)
76           stop("DNA sequences in list not of the same length.")
77         nms <- names(x)
78         n <- length(x)
79         s <- length(x[[1]])
80         x <- matrix(unlist(x), n, s, byrow = TRUE)
81         rownames(x) <- nms
82         class(x) <- "DNAbin"
83     }
84     x
85 }
86
87 rbind.DNAbin <- function(...)
88 ### works only with matrices for the moment
89 {
90     obj <- list(...)
91     n <- length(obj)
92     if (n == 1) return(obj[[1]])
93     NC <- unlist(lapply(obj, ncol))
94     if (length(unique(NC)) > 1)
95         stop("matrices do not have the same number of columns.")
96     for (i in 1:n) class(obj[[i]]) <- NULL
97     for (i in 2:n) obj[[1]] <- rbind(obj[[1]], obj[[i]])
98     structure(obj[[1]], class = "DNAbin")
99 }
100
101 cbind.DNAbin <-
102     function(..., check.names = TRUE, fill.with.gaps = FALSE,
103              quiet = FALSE)
104 ### works only with matrices for the moment
105 {
106     obj <- list(...)
107     n <- length(obj)
108     if (n == 1) return(obj[[1]])
109     NR <- unlist(lapply(obj, nrow))
110     for (i in 1:n) class(obj[[i]]) <- NULL
111     if (check.names) {
112         nms <- unlist(lapply(obj, rownames))
113         if (fill.with.gaps) {
114             NC <- unlist(lapply(obj, ncol))
115             nms <- unique(nms)
116             ans <- matrix(as.raw(4), length(nms), sum(NC))
117             rownames(ans) <- nms
118             from <- 1
119             for (i in 1:n) {
120                 to <- from + NC[i] - 1
121                 tmp <- rownames(obj[[i]])
122                 nmsi <- tmp[tmp %in% nms]
123                 ans[nmsi, from:to] <- obj[[i]][nmsi, , drop = FALSE]
124                 from <- to + 1
125             }
126         } else {
127             tab <- table(nms)
128             ubi <- tab == n
129             nms <- names(tab)[which(ubi)]
130             ans <- obj[[1]][nms, , drop = FALSE]
131             for (i in 2:n)
132                 ans <- cbind(ans, obj[[i]][nms, , drop = FALSE])
133             if (!quiet && !all(ubi))
134                 warning("some rows were dropped.")
135         }
136     } else {
137         if (length(unique(NR)) > 1)
138             stop("matrices do not have the same number of rows.")
139         ans <- matrix(unlist(obj), NR)
140         rownames(ans) <- rownames(obj[[1]])
141     }
142     class(ans) <- "DNAbin"
143     ans
144 }
145
146 c.DNAbin <- function(..., recursive = FALSE)
147     structure(NextMethod("c"), class = "DNAbin")
148
149 print.DNAbin <- function(x, ...)
150 {
151     n <- 1 # <- if is.vector(x)
152     if (is.list(x)) n <- length(x)
153     else if (is.matrix(x)) n <- dim(x)[1]
154     if (n > 1) cat(n, "DNA sequences in binary format.\n")
155     else cat("1 DNA sequence in binary format.\n")
156 }
157
158 summary.DNAbin <- function(object, printlen = 6, digits = 3, ...)
159 {
160     if (is.list(object)) {
161         n <- length(object)
162         nms <- names(object)
163         if (n == 1) {
164             cat("1 DNA sequence in binary format stored in a list.\n\n")
165             cat("Sequence length:", length(object[[1]]), "\n\n")
166             cat("Label:", nms, "\n\n")
167         } else {
168             cat(n, "DNA sequences in binary format stored in a list.\n\n")
169             tmp <- unlist(lapply(object, length))
170             mini <- min(tmp)
171             maxi <- max(tmp)
172             if (mini == maxi)
173                 cat("All sequences of same length:", maxi, "\n")
174             else {
175                 cat("Mean sequence length:", round(mean(tmp), 3), "\n")
176                 cat("   Shortest sequence:", mini, "\n")
177                 cat("    Longest sequence:", maxi, "\n")
178             }
179             TAIL <- "\n\n"
180             if (printlen < n) {
181                 nms <- nms[1:printlen]
182                 TAIL <- "...\n\n"
183             }
184             cat("\nLabels:", paste(nms, collapse = " "), TAIL)
185         }
186     } else if (is.matrix(object)) {
187         nd <- dim(object)
188         nms <- rownames(object)
189         cat(nd[1], "DNA sequences in binary format stored in a matrix.\n\n")
190         cat("All sequences of same length:", nd[2], "\n")
191         TAIL <- "\n\n"
192         if (printlen < nd[1]) {
193             nms <- nms[1:printlen]
194             TAIL <- "...\n\n"
195         }
196         cat("\nLabels:", paste(nms, collapse = " "), TAIL)
197     } else {
198         cat("1 DNA sequence in binary format stored in a vector.\n\n")
199         cat("Sequence length:", length(object), "\n\n")
200     }
201     cat("Base composition:\n")
202     print(round(base.freq(object), digits))
203 }
204
205 as.DNAbin <- function(x, ...) UseMethod("as.DNAbin")
206
207 ._cs_<- letters[c(1, 7, 3, 20, 18, 13, 23, 19, 11, 25, 22, 8, 4, 2, 14)]
208
209 ._bs_<- c(136, 72, 40, 24, 192, 160, 144, 96, 80, 48, 224, 176, 208, 112, 240)
210
211 as.DNAbin.character <- function(x, ...)
212 {
213     n <- length(x)
214     ans <- raw(n)
215     for (i in 1:15)
216       ans[which(x == ._cs_[i])] <- as.raw(._bs_[i])
217     ans[which(x == "-")] <- as.raw(4)
218     ans[which(x == "?")] <- as.raw(2)
219     if (is.matrix(x)) {
220         dim(ans) <- dim(x)
221         dimnames(ans) <- dimnames(x)
222     }
223     class(ans) <- "DNAbin"
224     ans
225 }
226
227 as.DNAbin.alignment <- function(x, ...)
228 {
229     n <- x$nb
230     x$seq <- tolower(x$seq)
231     ans <- matrix("", n, nchar(x$seq[1]))
232     for (i in 1:n)
233         ans[i, ] <- strsplit(x$seq[i], "")[[1]]
234     rownames(ans) <- gsub(" +$", "", gsub("^ +", "", x$nam))
235     as.DNAbin.character(ans)
236 }
237
238 as.DNAbin.list <- function(x, ...)
239 {
240     obj <- lapply(x, as.DNAbin)
241     class(obj) <- "DNAbin"
242     obj
243 }
244
245 as.character.DNAbin <- function(x, ...)
246 {
247     f <- function(xx) {
248         ans <- character(length(xx))
249         for (i in 1:15)
250           ans[which(xx == ._bs_[i])] <- ._cs_[i]
251         ans[which(xx == 4)] <- "-"
252         ans[which(xx == 2)] <- "?"
253         if (is.matrix(xx)) {
254             dim(ans) <- dim(xx)
255             dimnames(ans) <- dimnames(xx)
256         }
257         ans
258     }
259     if (is.list(x)) lapply(x, f) else f(x)
260 }
261
262 base.freq <- function(x, freq = FALSE)
263 {
264     if (is.list(x)) x <- unlist(x)
265     n <- length(x)
266     BF <- .C("BaseProportion", x, n, double(4), freq,
267              DUP = FALSE, NAOK = TRUE, PACKAGE = "ape")[[3]]
268     names(BF) <- letters[c(1, 3, 7, 20)]
269     BF
270 }
271
272 GC.content <- function(x) sum(base.freq(x)[2:3])
273
274 seg.sites <- function(x)
275 {
276     if (is.list(x)) x <- as.matrix(x)
277     if (is.vector(x)) n <- 1
278     else { # 'x' is a matrix
279         n <- dim(x)
280         s <- n[2]
281         n <- n[1]
282     }
283     if (n == 1) return(integer(0))
284     ans <- .C("SegSites", x, n, s, integer(s),
285               DUP = FALSE, NAOK = TRUE, PACKAGE = "ape")
286     which(as.logical(ans[[4]]))
287 }
288
289 dist.dna <- function(x, model = "K80", variance = FALSE, gamma = FALSE,
290                      pairwise.deletion = FALSE, base.freq = NULL,
291                      as.matrix = FALSE)
292 {
293     MODELS <- c("RAW", "JC69", "K80", "F81", "K81", "F84", "T92", "TN93",
294                 "GG95", "LOGDET", "BH87", "PARALIN", "N")
295     imod <- pmatch(toupper(model), MODELS)
296     if (is.na(imod))
297         stop(paste("'model' must be one of:",
298                    paste("\"", MODELS, "\"", sep = "", collapse = " ")))
299     if (imod == 11 && variance) {
300         warning("computing variance temporarily not available for model BH87.")
301         variance <- FALSE
302     }
303     if (gamma && imod %in% c(1, 5:7, 9:12)) {
304         warning(paste("gamma-correction not available for model", model))
305         gamma <- FALSE
306     }
307     if (is.list(x)) x <- as.matrix(x)
308     nms <- dimnames(x)[[1]]
309     n <- dim(x)
310     s <- n[2]
311     n <- n[1]
312     BF <- if (is.null(base.freq)) base.freq(x) else base.freq
313     if (!pairwise.deletion) {
314         keep <- .C("GlobalDeletionDNA", x, n, s,
315                    rep(1L, s), PACKAGE = "ape")[[4]]
316         x <- x[,  as.logical(keep)]
317         s <- dim(x)[2]
318     }
319     Ndist <- if (imod == 11) n*n else n*(n - 1)/2
320     var <- if (variance) double(Ndist) else 0
321     if (!gamma) gamma <- alpha <- 0
322     else alpha <- gamma <- 1
323     d <- .C("dist_dna", x, n, s, imod, double(Ndist), BF,
324             as.integer(pairwise.deletion), as.integer(variance),
325             var, as.integer(gamma), alpha, DUP = FALSE, NAOK = TRUE,
326             PACKAGE = "ape")
327     if (variance) var <- d[[9]]
328     d <- d[[5]]
329     if (imod == 11) {
330         dim(d) <- c(n, n)
331         dimnames(d) <- list(nms, nms)
332     } else {
333         attr(d, "Size") <- n
334         attr(d, "Labels") <- nms
335         attr(d, "Diag") <- attr(d, "Upper") <- FALSE
336         attr(d, "call") <- match.call()
337         attr(d, "method") <- model
338         class(d) <- "dist"
339         if (as.matrix) d <- as.matrix(d)
340     }
341     if (variance) attr(d, "variance") <- var
342     d
343 }