-
Notifications
You must be signed in to change notification settings - Fork 64
/
sequences.R
317 lines (233 loc) · 8.88 KB
/
sequences.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
######################################
##
## The code below implements import
## from alignement data.
##
######################################
################
# DNAbin2genind
################
DNAbin2genind <- function(x, pop=NULL, exp.char=c("a","t","g","c"), polyThres=1/100){
## MISC CHECKS ##
if(!inherits(x,"DNAbin")) stop("x is not a DNAbin object")
if(is.list(x)) {
x <- as.matrix(x)
}
if(is.null(colnames(x))) {
colnames(x) <- 1:ncol(x)
}
## FUNCTION TO PROCESS ONE LOCUS ##
## INPUTS:
## locus is a column of a DNAbin matrix
## posi is the index of this column
## OUTPUTS:
## returns NULL if no polymorphism
## returns a disjonctive table with named columns otherwise
## column names are given as [position.allele]
processLocus <- function(locus, posi){
vec <- as.character(locus)
vec[!vec %in% exp.char] <- NA
N <- sum(!is.na(vec)) # N: number of sequences
if(N==0 || sum(table(vec)/N >= polyThres )<2) return(NULL) # escape if untyped locus or no SNPs
alleles <- unique(na.omit(vec))
## vec[!vec %in% alleles] <- NA # this would replace rare alleles by NAs
out <- sapply(alleles, function(e) 1*(vec==e))
colnames(out) <- paste(posi, alleles, sep=".")
return(out)
}
## PROCESS ALL LOCI ##
## get disjonctive matrix ##
## system.time(res@tab <- Reduce(cbind, lapply(1:ncol(x), function(i) processLocus(x[,i], i)))) # works, but Reduce is real slow
temp <- lapply(1:ncol(x), function(i) processLocus(x[,i], i)) # process all loci, return a list
col.names <- unlist(sapply(temp, colnames))
temp <- as.matrix(data.frame(temp[!sapply(temp, is.null)])) # remove NULL slots, list -> matrix
if(is.null(temp) || ncol(temp)==0){
cat("\nNo polymorphism detected - returning NULL.\n")
return(NULL)
}
## sort out col/row names ##
## check if col.names is in matrix format and change to vector format
if(inherits(col.names, "matrix")) col.names <- as.vector(col.names)
colnames(temp) <- col.names # restore correct names
rownames(temp) <- rownames(x)
## create genind output ##
res <- genind(temp, ploidy=1, pop=pop, type="codom")
rm(temp) # remove temp
gc() # collect garbage
res$call <- match.call()
return(res)
} # end DNAbin2genind
####################
## alignment2genind
####################
alignment2genind <- function(x, pop=NULL, exp.char=c("a","t","g","c"), na.char="-", polyThres=1/100){
## misc checks
## if(!require(seqinr)) stop("The package seqinr is required.")
if(!inherits(x,"alignment")) stop("x is not a alignment object")
N <- length(x$seq)
if(!is.null(x$nam) && length(x$nam)!=N) stop("Inconsistent names in x (length of x$nam and x$seq do not match). ")
## check that na.char does not overide specified exp.char
if(!is.null(na.char) && na.char %in% exp.char){
na.char <- na.char[!na.char %in% exp.char]
if(length(na.char)==0) na.char <- NULL
}
## convert alignment to matrix of characters
mat <- sapply(x$seq, s2c, USE.NAMES=FALSE)
if(nrow(mat)!=x$nb){
mat <- t(mat)
}
rownames(mat) <- x$nam
if(is.null(colnames(x))) {
colnames(mat) <- 1:ncol(mat)
}
## replace NAs
if(is.null(na.char)){
if(is.null(exp.char)) stop("both exp.char and na.char are NULL")
temp <- paste(exp.char, collapse="", sep="")
if(any(exp.char=="-")) {
temp <- paste("-",temp, sep="") # string '-' must begin the regexp
}
temp <- paste("[^", temp, "]", sep="") # anything but the expected is NA
mat <- gsub(temp,NA,mat)
} else {
temp <- paste(na.char, collapse="", sep="")
if(any(na.char=="-")) {
temp <- paste("-",temp, sep="") # string '-' must start the regexp
}
temp <- paste("[", temp, "]", sep="")
mat <- gsub(temp,NA,mat)
}
## keep only columns with polymorphism (i.e., SNPs)
isPoly <- function(vec){
N <- sum(!is.na(vec)) # N: number of sequences
temp <- table(vec)/N
if(sum(temp > polyThres) >= 2) return(TRUE)
return(FALSE)
}
toKeep <- apply(mat, 2, isPoly)
if(sum(toKeep)==0) stop("No polymorphic site detected")
mat <- mat[,toKeep, drop=FALSE]
## build output
res <- df2genind(mat, pop=pop, ploidy=1, ncode=1, type="codom")
res$call <- match.call()
if(!is.null(x$com)){
res@other$com <- x$com
}
return(res)
} # end alignment2genind
## #################
## ## findMutations
## #################
## ## GENERIC
## findMutations <- function(...){
## UseMethod("findMutations")
## }
## ## METHOD FOR DNABIN
## findMutations.DNAbin <- function(x, from=NULL, to=NULL, ...){
## ## CHECKS ##
## if(!require(ape)) stop("the ape package is needed")
## if(!inherits(x,"DNAbin")) stop("x is not a DNAbin object")
## x <- as.matrix(x)
## ## function to pull out mutations from sequence a to b ##
## NUCL <- c('a','t','g','c')
## f1 <- function(a,b){
## seqa <- as.character(x[a,])
## seqb <- as.character(x[b,])
## temp <- which(seqa != seqb)
## ori <- seqa[temp]
## mut <- seqb[temp]
## names(ori) <- names(mut) <- temp
## toRemove <- !ori %in% NUCL | !mut %in% NUCL
## ori <- ori[!toRemove]
## mut <- mut[!toRemove]
## if(all(toRemove)) return(NULL)
## res <- data.frame(ori,mut)
## names(res) <- rownames(x)[c(a,b)]
## res$short <- paste(row.names(res),":",res[,1],"->",res[,2],sep="")
## return(res)
## }
## ## GET LIST OF PAIRS TO COMPARE ##
## ## handle NULL
## if(is.null(from)) from <- 1:nrow(x)
## if(is.null(to)) to <- 1:nrow(x)
## ## get pairs
## pairs <- expand.grid(from, to)
## ## remove unwanted comparisons
## pairs <- pairs[pairs[,1]!=pairs[,2],,drop=FALSE]
## ## GET NUMBER OF MUTATIONS ##
## out <- lapply(1:nrow(pairs), function(i) f1(pairs[i,1], pairs[i,2]))
## names(out) <- paste(rownames(x)[pairs[,1]], rownames(x)[pairs[,2]],sep="->")
## return(out)
## } # end findMutations
## ##################
## ## graphMutations
## ##################
## ## GENERIC
## graphMutations <- function(...){
## UseMethod("graphMutations")
## }
## ## METHOD FOR DNABIN
## graphMutations.DNAbin <- function(x, from=NULL, to=NULL, plot=TRUE, edge.curved=TRUE, ...){
## if(!require(igraph)) stop("igraph is required")
## ## GET MUTATIONS ##
## x <- findMutations(x, from=from, to=to)
## ## GET GRAPH ##
## from <- gsub("->.*","",names(x))
## to <- gsub(".*->","",names(x))
## vnames <- sort(unique(c(from,to)))
## dat <- data.frame(from,to,stringsAsFactors=FALSE)
## out <- graph.data.frame(dat, directed=TRUE, vertices=data.frame(vnames, label=vnames))
## ## SET ANNOTATIONS FOR THE BRANCHES ##
## annot <- unlist(lapply(x, function(e) paste(e$short, collapse="\n")))
## E(out)$label <- annot
## E(out)$curved <- edge.curved
## ## PLOT / RETURN ##
## if(plot) plot(out, ...)
## return(out)
## } # end graphMutations
## ###############
## ## transiProb
## ###############
## ##
## ## proba/distance based on transition prob from one sequence to another
## ## time is taken into account
## ## output: matrix with term proba(rowIdx to colIdx)
## ##
## transiProb <- function(x, mu, dates, result=c("prob","dist")){
## ## MISC CHECKS ##
## if(!inherits(x,"DNAbin")) stop("x is not a DNAbin object")
## if(!require(ape)) stop("The package ape is required.")
## result <- match.arg(result)
## ## COMPUTATIONS ##
## ## get numbers of differing nucleotides between sequences
## seq.length <- ncol(as.matrix(x))
## D <- as.matrix(dist.dna(x, model="raw")) * seq.length
## ## if(sum(D-round(D)) > 1e-10){ # make sure we've got integers there
## ## warning("Number of nucleotides are not all integers")
## ## }
## D <- round(D)
## ## compute matrix T (time between sequences)
## if(inherits(dates,"POSIXct")){ # dates in POSIXct format
## temp <- outer(dates, dates, difftime, unit="days")
## T <- -matrix(as.numeric(temp),ncol=length(dates))
## } else { # dates are numeric
## T <- -outer(dates, dates, "-")
## }
## ## spot negative times
## toSetToNull <- T < 1e-15
## ## compute proba(no change @ a site) term
## mu <- mu/365 # express mu per day
## p1 <- exp(-T*mu) + (1-exp(-T*mu))/4
## p1[toSetToNull] <- 0
## res <- dbinom(D, size=seq.length, prob=(1-p1))
## ## PROCESS/RETURN RESULT
## if(result=="prob"){ # return probabilities
## res[toSetToNull] <- 0
## diag(res) <- 1
## } else { # return d = -log(proba)
## res <- -log(res)
## res[toSetToNull] <- 1e15
## diag(res) <- 0
## }
## return(res)
## } # end transiProb