]> git.donarmstrong.com Git - ape.git/blob - R/read.dna.R
4b2ddd8e2a65dd7b664071251fd17824320a160e
[ape.git] / R / read.dna.R
1 ## read.dna.R (2013-01-04)
2
3 ##   Read DNA Sequences in a File
4
5 ## Copyright 2003-2012 Emmanuel Paradis
6
7 ## This file is part of the R-package `ape'.
8 ## See the file ../COPYING for licensing issues.
9
10 read.FASTA <- function(file)
11 {
12     sz <- file.info(file)$size
13     x <- readBin(file, "raw", sz)
14     if (Sys.info()[1] == "Windows") {
15         icr <- which(x == as.raw(0x0d)) # CR
16         x <- x[-icr]
17     }
18     res <- .Call("rawStreamToDNAbin", x, PACKAGE = "ape")
19     class(res) <- "DNAbin"
20     res
21 }
22
23 read.dna <- function(file, format = "interleaved", skip = 0,
24                      nlines = 0, comment.char = "#",
25                      as.character = FALSE, as.matrix = NULL)
26 {
27     findFirstNucleotide <- function(x) {
28         ## actually find the 1st non-blank character
29         ## just in case: pat.base <- "[-AaCcGgTtUuMmRrWwSsYyKkVvHhDdBbNn?]{10}"
30         tmp <- regexpr("[[:blank:]]+", x[1]) # consider only a single string
31         tmp[1] + attr(tmp, "match.length")
32     }
33     getTaxaNames <- function(x) {
34         x <- sub("^['\" ]+", "", x) # remove the leading quotes and spaces
35         x <- sub("['\" ]+$", "", x) #   "     "  trailing  "     "    "
36         x
37     }
38     getNucleotide <- function(x) {
39         x <- gsub(" ", "", x)
40         x <- strsplit(x, NULL)
41         tolower(unlist(x))
42     }
43     formats <- c("interleaved", "sequential", "fasta", "clustal")
44     format <- match.arg(format, formats)
45     if (format == "fasta") {
46         obj <- read.FASTA(file)
47     } else {
48         X <- scan(file = file, what = "", sep = "\n", quiet = TRUE,
49                   skip = skip, nlines = nlines, comment.char = comment.char)
50         if (format %in% formats[1:2]) {
51             ## need to remove the possible leading spaces and/or tabs in the first line
52             fl <- gsub("^[[:blank:]]+", "", X[1])
53             fl <- as.numeric(unlist(strsplit(fl, "[[:blank:]]+")))
54             if (length(fl) != 2 || any(is.na(fl)))
55                 stop("the first line of the file must contain the dimensions of the data")
56             n <- fl[1]
57             s <- fl[2]
58             obj <- matrix("", n, s)
59             X <- X[-1]
60         }
61         switch(format,
62                "interleaved" = {
63                    start.seq <- findFirstNucleotide(X[1])
64                    one2n <- 1:n
65                    taxa <- getTaxaNames(substr(X[one2n], 1, start.seq - 1))
66                    X[one2n] <- substr(X[one2n], start.seq, nchar(X[one2n]))
67                    nl <- length(X)
68                    for (i in one2n)
69                        obj[i, ] <- getNucleotide(X[seq(i, nl, n)])
70                },
71                "sequential" = {
72                    taxa <- character(n)
73                    j <- 1L # line number
74                    for (i in 1:n) {
75                        start.seq <- findFirstNucleotide(X[j])
76                        taxa[i] <- getTaxaNames(substr(X[j], 1, start.seq - 1))
77                        sequ <- getNucleotide(substr(X[j], start.seq, nchar(X[j])))
78                        j <- j + 1L
79                        while (length(sequ) < s) {
80                            sequ <- c(sequ, getNucleotide(X[j]))
81                            j <- j + 1L
82                        }
83                        obj[i, ] <- sequ
84                    }
85                    taxa <- getTaxaNames(taxa)
86                },
87                "clustal" = {
88                    X <- X[-1] # drop the line with "Clustal bla bla..."
89                    ## find where the 1st sequence starts
90                    start.seq <- findFirstNucleotide(X[1])
91                    ## find the lines with *********....
92                    nspaces <- paste("^ {", start.seq - 1, "}", sep = "", collapse = "")
93                    stars <- grep(nspaces, X)
94                    ## we now know how many sequences in the file:
95                    n <- stars[1] - 1
96                    taxa <- getTaxaNames(substr(X[1:n], 1, start.seq - 1))
97                    ## need to remove the sequence names before getting the sequences:
98                    X <- substr(X, start.seq, nchar(X))
99                    nl <- length(X)
100                    ## find the length of the 1st sequence:
101                    tmp <- getNucleotide(X[seq(1, nl, n + 1)])
102                    s <- length(tmp)
103                    obj <- matrix("", n, s)
104                    obj[1, ] <- tmp
105                    for (i in 2:n)
106                        obj[i, ] <- getNucleotide(X[seq(i, nl, n + 1)])
107                })
108     }
109     if (format != "fasta") {
110         rownames(obj) <- taxa
111         if (!as.character) obj <- as.DNAbin(obj)
112     } else {
113         LENGTHS <- unique(unlist(lapply(obj, length)))
114         allSameLength <- length(LENGTHS) == 1
115         if (is.logical(as.matrix)) {
116             if (as.matrix && !allSameLength)
117                 stop("sequences in FASTA file not of the same length")
118         } else {
119             as.matrix <- allSameLength
120         }
121         if (as.matrix) {
122             taxa <- names(obj)
123             n <- length(obj)
124             y <- matrix(as.raw(0), n, LENGTHS)
125             for (i in seq_len(n)) y[i, ] <- obj[[i]]
126             obj <- y
127             rownames(obj) <- taxa
128             class(obj) <- "DNAbin"
129         }
130         if (as.character) obj <- as.character(obj)
131     }
132     obj
133 }