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