forked from cran/PopGenome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadSNP.R
404 lines (285 loc) · 10.3 KB
/
readSNP.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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
readSNP <- function(folder, populations=FALSE,outgroup=FALSE, gffpath=FALSE, CHR=FALSE, ref.chr=FALSE, snp.window.size=FALSE, parallized=FALSE, ffpackagebool=TRUE, include.unknown=FALSE)
{
if(!file.exists(folder)){stop("Cannot find folder !")}
if(ref.chr[1]!=FALSE){
if(!file.exists(ref.chr)){
stop("Cannot read reference chromosome")
}
}
if(ref.chr[1]!=FALSE && gffpath==FALSE){
stop("Do not find the GFF/GTF file !")
}
if(file.exists("SNPRObjects")){unlink("SNPRObjects",recursive=TRUE)}
if(file.exists("GFFRObjects")){unlink("GFFRObjects",recursive=TRUE)}
### DEFAULT VALUES for readData()
# include.unknown <- FALSE
# parallized <- FALSE
progress_bar_switch <- TRUE
FAST <- TRUE
big.data <- TRUE
SNP.DATA <- TRUE
#### ----------------------------
liste <- list.files(folder,full.names=TRUE)
# Init
f.data <- vector("list",length(liste))
f.data2 <- vector("list",length(liste))
if(CHR[1]!=FALSE){
cat("Read chromosome ", CHR[1], " \n ")
}else{
cat("Read all chromosomes "," \n ")
}
cat("\n")
individuals <- character(length(liste))
col.specify <- c(rep("character",2),"integer",rep("character",2),rep("NULL",4))
col.specify2 <- c(rep("factor",2),"integer",rep("factor",2),rep("NULL",4)) # for read.table.ffdf FIXME
cat("Reading files ... \n")
## PROGRESS #########################
# progr <- progressBar()
#####################################
for (xx in 1:length(liste)){
cat("Reading file: ",liste[[xx]], ": ",xx ," of ", length(liste), "\n" )
if(CHR[1]!=FALSE){
CHR <- as.character(CHR)
my_pos <- .Call("find_lines_SNP",liste[[xx]],CHR)
f.data[[xx]] <- read.table(file=liste[[xx]],
skip=my_pos[1] - 1, nrows=my_pos[2] - my_pos[1],
sep="\t",colClasses=col.specify)
}else{
#f.data[[xx]] <- read.table.ffdf(file=liste[[xx]])
f.data[[xx]] <- read.table(file=liste[[xx]],
sep="\t",colClasses=col.specify)
}
# Split by chromosomes
chr <- f.data[[xx]][,2]
individuals[xx] <- as.character(f.data[[xx]][1,1])
# chr ids like chr1 or 1
if(nchar(chr[1])>1){
chr.pos <- match(1:5,substr(chr,4,4))
}else{
chr.pos <- match(1:5,chr)
}
chromosomes <- which(!is.na(chr.pos)) # which chromosomes are in the file ?
chr.pos <- chr.pos[!is.na(chr.pos)]
chr.pos <- c(chr.pos,length(chr))
f.split.data <- vector("list",length(chr.pos)-1)
ids <- 1
for (yy in 1:(length(chr.pos)-1)){
block <- ids:chr.pos[yy + 1]
ref_alt <- as.matrix(f.data[[xx]][block,4:5])
ref_alt <- .Call("code_nucs",ref_alt)
reference.pos <- f.data[[xx]][block,3]
#if(ffpackagebool){
f.split.data[[yy]] <- ff(cbind(ref_alt,reference.pos),dim=c(dim(ref_alt)[1],3))
#}else{
#f.split.data[[yy]] <- cbind(ref_alt,reference.pos)
#}
ids <- chr.pos[yy+1]+1
}
f.data2[[xx]] <- f.split.data # seperated by chromosomes
if(CHR[1]==FALSE){
# delete(f.data[[xx]])
f.data[[xx]] <- NA
}
# PROGRESS #######################################################
# progr <- progressBar(xx,length(liste), progr)
###################################################################
}
# RAM freischaufeln !
rm(ref_alt)
rm(reference.pos)
rm(f.data)
rm(f.split.data)
gc()
gc()
# cat("Create Matrix ...\n")
POS <- NULL
SNP.MATRICES <- vector("list",length(chr.pos)-1)
SNP.POS <- vector("list",length(chr.pos)-1)
cat("\n")
cat("Prepare ... \n")
# Create SNP Matrix for each Chromosome
## PROGRESS #########################
progr <- progressBar()
#####################################
## FOR LOOP START over Chromosomes
for (yy in 1:(length(chr.pos)-1)){
# get positions ------------------------------------
for(xx in 1:length(liste)){
POS <- c(POS,f.data2[[xx]][[yy]][,3])
# for saving memory space
if(!xx%%50){
POS <- unique(POS)
}
}
# --------------------------------------------------
POS <- sort(unique(POS))
if(ffpackagebool){
SNP.MATRIX <- ff (NA,dim=c(length(liste),length(POS)), vmode="integer")
}else{
SNP.MATRIX <- matrix(NA,length(liste),length(POS))
}
SNP.POS[[yy]] <- POS
# check what Positions are currently unvisited
# fill reference first !!!
visited <- vector(,length(POS))
for(xx in 1:length(liste)){
# -- neu
# IDS <- .Call("my_match_C",f.data2[[xx]][[yy]][,3],POS)
# not.na <- IDS!=-1
# Keep <- IDS
# IDS <- IDS[not.na]
# -- neu ende
# ---alt
IDS <- match(f.data2[[xx]][[yy]][,3],POS)
not.na <- !is.na(IDS)
Keep <- IDS
IDS <- IDS[not.na]
# --- alt ende
# welche POS noch nicht besucht
IDS <- IDS[!visited[IDS]]
if(length(IDS)==0){next}
IDS2 <- match(IDS,Keep)
fill.mat <- f.data2[[xx]][[yy]][,1][IDS2]
fill.mat <- matrix(rep(fill.mat,length(liste)),length(liste),length(fill.mat),byrow=TRUE)
SNP.MATRIX[,IDS] <- fill.mat
visited[IDS] <- TRUE
if(all(visited)){break}
}
rm(fill.mat)
rm(visited)
gc()
# fill subsitution !
for(xx in 1:length(liste)){
# -- neu
# IDS <- .Call("my_match_C",f.data2[[xx]][[yy]][,3],POS)
# not.na <- IDS!=-1
# IDS <- IDS[not.na]
# -- neu ende
# alt ----
IDS <- match(f.data2[[xx]][[yy]][,3],POS)
not.na <- !is.na(IDS)
IDS <- IDS[not.na]
# alt ende
SNP.MATRIX[xx,IDS] <- f.data2[[xx]][[yy]][,2] # fill substitution
}
rm(POS)
rm(IDS)
gc()
rownames(SNP.MATRIX) <- individuals
SNP.MATRICES[[yy]] <- SNP.MATRIX
rm(SNP.MATRIX)
POS <- NULL
# PROGRESS #######################################################
progr <- progressBar(yy,(length(chr.pos)-1), progr)
###################################################################
}
### FOR LOOP END over all Chromosomes
#----------------------------------------- Create R Objects ----------------------------------------
dir.create("SNPRObjects")
too.big <- FALSE
for ( qq in 1:length(SNP.MATRICES) ) {
# If there are more than 100000 SNPs
if(snp.window.size[1]!=FALSE){
too.big <- TRUE
snp.regions <- seq(1,length(SNP.POS[[qq]]),by=snp.window.size)
snp.regions <- c(snp.regions,length(SNP.POS[[qq]])+1)
for( xx in 1:(length(snp.regions)-1) ){
CHUNK.MATRIX <- SNP.MATRICES[[qq]][,snp.regions[xx]:(snp.regions[xx+1]-1)]
o_b_j_sub <- list(matrix=CHUNK.MATRIX,
reference=NaN,positions=SNP.POS[[qq]][snp.regions[xx]:(snp.regions[xx+1]-1)])
save(o_b_j_sub,file=file.path(getwd(),"SNPRObjects",paste(xx,"chunk_","chr",chromosomes[qq],sep="")))
}
# delete.ff(SNP.MATRICES[[qq]])
SNP.MATRICES[[qq]] <- NA
gc()
}else{
o_b_j_sub <- list(matrix=SNP.MATRICES[[qq]][,],reference=NaN,positions=SNP.POS[[qq]])
save(o_b_j_sub,file=file.path(getwd(),"SNPRObjects",paste("chr",chromosomes[qq],sep="")))
# delete.ff(SNP.MATRICES[[qq]])
SNP.MATRICES[[qq]] <- NA
gc()
}
}
#####--------------- corresponding GFF- File ------------------------#
rm(o_b_j_sub)
gc()
if(gffpath[1]!=FALSE){
cat("\n")
cat("GFF information ...")
cat("\n")
#skip=my_pos[1] - 1, nrows=my_pos[2] - my_pos[1]
if(CHR[1]!=FALSE){
my_pos <- .Call("find_lines_GFF",gffpath,CHR)
gff.table <- read.table(gffpath,sep="\t",colClasses=c(rep("character",3),rep("integer",2),rep("character",2),"character","NULL"),
skip = my_pos[1] - 1, nrows = my_pos[2] - my_pos[1] + 1)
}else{
gff.table <- read.table(gffpath,sep="\t",colClasses=c(rep("character",3),rep("integer",2),rep("character",2),"character","NULL"))
}
dir.create("GFFRObjects")
### sort GFF file
POS <- gff.table[,4]
names(POS) <- 1:length(POS)
POS <- sort(POS)
ids <- as.numeric(names(POS))
gff.table <- gff.table[ids,,drop=FALSE]
## vorletzte Zeile integer draus wegen GFF3 "." -> 0
vorl <- gff.table[,8]
punkte <- which(vorl==".")
if(length(punkte)>0){
vorl[punkte] <- 0
gff.table[,8] <- as.integer(vorl)
}else{
gff.table[,8] <- as.integer(gff.table[,8])
}
#-------------------------
seq.names <- gff.table[,1]
# If the data for one chromosome is too big !!!
if(too.big){
# - works only for one chromosome
# ---------------------------------
IDSS <- grep(CHR,seq.names)
gff.table <- gff.table[IDSS,,drop=FALSE]
# for every chunk of ONE chromosome
for( xx in 1:(length(snp.regions)-1) ){
# get the region
pos1 <- SNP.POS[[1]][snp.regions[xx]]
pos2 <- SNP.POS[[1]][(snp.regions[xx+1]-1)]
#cat(pos1,"-",pos2," \n")
SUB_GFF <- split.GFF(gff.table,pos1,pos2)
o_b_j_sub <- SUB_GFF
save(o_b_j_sub,file=file.path(getwd(),"GFFRObjects",paste(xx,"chunk_","chr",CHR[1],sep="")))
}
}else{
for(i in chromosomes){
pos <- grep(i,seq.names)
o_b_j_sub <- gff.table[pos,]
save(o_b_j_sub,file=file.path(getwd(),"GFFRObjects",paste("chr",i,sep="")))
}
}
gffpath <- file.path(getwd(),"GFFRObjects")
}
######### --------------- End of get GFF ---------------------------------#
path <- file.path(getwd(),"SNPRObjects")
cat("\n")
cat("Calculation ... \n")
res <- readData(path,populations=populations,outgroup=outgroup,include.unknown=include.unknown,gffpath=gffpath,format="RData",
parallized=parallized,progress_bar_switch=progress_bar_switch,
FAST=FAST,big.data=big.data,SNP.DATA=SNP.DATA)
if(too.big){
res <- concatenate_to_whole_genome(res,length([email protected]))
[email protected] <- paste("chr",CHR[1],sep="")
}
# Loeschen des Verzeichnisses
unlink("SNPRObjects", recursive=TRUE)
if(gffpath[1]!=FALSE){
unlink("GFFRObjects", recursive=TRUE)
}
if(ref.chr[1]!=FALSE){
cat("\n")
cat("Synonymous positions ...")
cat("\n")
res <- set.synnonsyn(res,ref.chr=ref.chr)
}
gc()
return(res)
}