-
Notifications
You must be signed in to change notification settings - Fork 16
/
GBS-Chip-Gmatrix.R
2835 lines (2714 loc) · 147 KB
/
GBS-Chip-Gmatrix.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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/echo Source me don't execute me
KGDver <- "1.3.0"
cat("KGD version:",KGDver,"\n")
if (!exists("nogenos")) nogenos <- FALSE
if (!exists("gform")) gform <- "uneak"
if (!exists("genofile")) genofile <- "HapMap.hmc.txt"
if (!exists("sampdepth.thresh")) sampdepth.thresh <- 0.01
if (!exists("snpdepth.thresh")) snpdepth.thresh <- 0.01
if (!exists("maf.thresh")) maf.thresh <- 1e-9
if (!exists("hirel.thresh")) hirel.thresh <- 0.9
if (!exists("iemm.thresh")) iemm.thresh <- 0.05
if (!exists("triallelic.thresh")) triallelic.thresh <- 0.005 # if third allele present in higher than this proportion, then discard SNP, otherwise discard 3rd & 4th allele calls (currently only for ANGSD data)
if (!exists("cex.pointsize")) cex.pointsize <- 1
if (!exists("functions.only")) functions.only <- FALSE
if (!exists("alleles.keep")) alleles.keep <- FALSE
if (!exists("outlevel")) outlevel <- 9
if (!exists("use.Rcpp")) use.Rcpp <- TRUE
if (!exists("nThreads")) nThreads <- 4 # 0 means use all available
if (!exists("negC")) negC <- "" # empty string will bypass negC checks
if (!exists("negCsettings")) negCsettings <- list()
if (!exists("QQprobpts")) QQprobpts <- c(0.5,0.8,0.9,0.95,0.99)
# function to locate Rcpp file (assume it is in the same directory as this file and this file was 'sourced')
pathToCppFile = function() {
cpp.name <- "GBS-Rcpp-functions.cpp"
this.file <- NULL
for (i in -(1:sys.nframe())) {
if (identical(sys.function(i), base::source)) {
f <- sys.frame(i)
if (!f$chdir)
this.file <- normalizePath(f$ofile)
break
}
}
if (!is.null(this.file)) {
source.dir <- dirname(this.file)
return(file.path(source.dir, cpp.name))
}
else {
# assume it is in the current working directory
return(cpp.name)
}
}
# load C++ functions
# compiling can take ~10 seconds, so we cache the file (under ~/R/RcppCache)
# it will only be recompiled when the C++ file changes or is moved
have_rcpp <- FALSE
if (require(Rcpp) & use.Rcpp) {
# RcppArmadillo is also required, but we don't need to load it here
if (is.element("RcppArmadillo", installed.packages()[,"Package"])) {
have_rcpp <- TRUE
cpp.path <- pathToCppFile()
cat("Loading C++ functions:", cpp.path, "\n")
sourceCpp(file = cpp.path, showOutput = TRUE,
cacheDir = file.path(path.expand("~"), "R", "RcppCache"))
}
}
### depth2K functions
r_depth2K <- function(depthvals) 1/2^depthvals # convert depth to K value assuming binomial
# select R or Rcpp version of depth2K depending on whether Rcpp is installed
if (have_rcpp) {
depth2K <- function(depthvals) {
# Rcpp version only works with matrix as input, so fallback to R version otherwise
if (is.matrix(depthvals)) {
result <- rcpp_depth2K(depthvals, nThreads)
} else {
result <- r_depth2K(depthvals)
}
return(result)
}
} else {
depth2K <- r_depth2K
}
# convert depth to K value assuming beta-binomial with parameters alpha=beta=alph. Inf gives binomial
r_depth2Kbb <- function(depthvals, alph=Inf) {
if (alph==Inf) 1/2^depthvals else beta(alph,depthvals+alph)/beta(alph,alph)
}
# select R or Rcpp version depending on whether Rcpp is installed
if (have_rcpp) {
depth2Kbb <- function(depthvals, alph=Inf) {
# Rcpp version only works with matrix as input, so fallback to R version otherwise
if (is.matrix(depthvals) & alph < Inf) {
if(alph < Inf) {
result <- rcpp_depth2Kbb(depthvals, nThreads, alph)
} else {
result <- depth2K(depthvals)
}
} else {
result <- r_depth2Kbb(depthvals, alph)
}
return(result)
}
} else {
depth2Kbb <- r_depth2Kbb
}
# convert depth to K value modp model. prob of seeing same allele as last time is modp (usually >= 0.5)
r_depth2Kmodp <- function(depthvals, modp=0.5 ) {
Kvals <- 0.5*modp^(depthvals-1)
Kvals[depthvals==0] <- 1
Kvals
}
# select R or Rcpp version depending on whether Rcpp is installed
if (have_rcpp) {
depth2Kmodp <- function(depthvals, modp=0.5) {
# Rcpp version only works with matrix as input, so fallback to R version otherwise
if (is.matrix(depthvals)) {
result <- rcpp_depth2Kmodp(depthvals, modp, nThreads)
} else {
result <- r_depth2Kmodp(depthvals, modp)
}
return(result)
}
} else {
depth2Kmodp <- r_depth2Kmodp
}
depth2Kchoose <- function(dmodel="bb",param) { # function to choose redefine depth2K
if (!dmodel=="modp") dmodel <- "bb"
if (missing(param) & dmodel=="bb") param <- Inf
if (missing(param) & dmodel=="modp") param <- 0.5
if (dmodel=="bb") depth2K <- function(depthvals) depth2Kbb(depthvals,alph=param)
if (dmodel=="modp") depth2K <- function(depthvals) depth2Kmodp(depthvals,modp=param)
depth2K
}
readGBS <- function(genofilefn = genofile, usedt="recommended") {
if(exists("depth")) rm(depth,inherits=TRUE)
gform <<- tolower(gform)
if (gform == "chip") readChip(genofilefn)
if (gform == "angsdcounts") readANGSD(genofilefn)
if (gform == "tagdigger") readTD(genofilefn)
if (gform == "vcf") read.vcf(genofilefn)
if (gform %in% c("uneak","tassel")) readTassel(genofilefn, usedt=usedt)
ndups <- sum(duplicated(seqID))
if(ndups>0) cat("Warning: ",ndups,"duplicated seqIDs, 1st one is:",seqID[duplicated(seqID)][1],"\n")
}
readTD <- function(genofilefn0 = genofile, skipcols=0) {
havedt <- require("data.table")
ghead <- scan(genofilefn0, what = "", nlines = 1, sep = ",", quote="", quiet=TRUE)
if(skipcols > 0) ghead <- ghead[-(1:skipcols)]
nsnps <<- (length(ghead) - 1)/2
SNPinfo <- read.table(text=ghead[-1],sep="_",fill=TRUE,stringsAsFactors=FALSE)
SNP_Names <<- SNPinfo[2*seq(nsnps),1]
refalleles <<- SNPinfo[2*seq(nsnps)-1,2]
altalleles <<- SNPinfo[2*seq(nsnps),2]
cat("Data file has", nsnps, "SNPs \n")
print(table(refalleles,altalleles))
isgzfile <- grepl(".gz",genofilefn0) #gz unzipping will only work on linux systems
if(nogenos) {
if(.Platform$OS.type == "unix") { # faster to cut in unix than to scan whole file for first field
if(isgzfile) seqID <<- read.table(text=system(paste("zcat",genofilefn0, "| cut -f 1 -d,"), intern = TRUE, ignore.stderr = TRUE),header=FALSE, stringsAsFactors=FALSE)[,1]
if(!isgzfile) seqID <<- read.table(text=system(paste("cut",genofilefn0, "-f 1 -d,"), intern = TRUE, ignore.stderr = TRUE),header=FALSE, stringsAsFactors=FALSE)[,1]
} else {
seqID <<- scan(genofilefn0, what="",skip=1,quote="",flush=TRUE, quiet=TRUE) # 1st column only
}
nind <<- length(seqID)
}
if(!nogenos) {
if (havedt) {
if ( (packageVersion("data.table") < "1.12" | suppressMessages(!require("R.utils"))) & isgzfile) {
genosin <- fread(paste("gunzip -c",genofilefn0),sep=",",header=TRUE,showProgress=FALSE)
} else {
genosin <- fread(genofilefn0,sep=",",header=TRUE)
}
if(skipcols > 0) genosin <- genosin[,-(1:skipcols)]
seqID <<- as.character(as.matrix(genosin[,1])[,1]) # (Allows any name for first col), also convert to vector from data.table
nind <<- length(seqID)
alleles <<- as.matrix(genosin[,-1,with=FALSE])
} else {
genosin <- scan(genofilefn0, skip = 1, sep = ",", what = c(list(seqID = ""), rep(list(0), 2*nsnps)), quote="", quiet=TRUE)
seqID <<- as.character(genosin[[1]])
nind <<- length(seqID)
alleles <<- matrix(0, nrow = nind, ncol = 2 * nsnps)
for (isnp in seq(2*nsnps)) alleles[, isnp] <<- genosin[[isnp+1]]
}
}
cat("Data file has", nind, "samples \n")
invisible(NULL)
}
readANGSD <- function(genofilefn0 = genofile) {
ghead <- scan(genofilefn0, what = "", nlines = 1, sep = "\t", quote="")
nind <<- (length(ghead) - 1) / 4
if (nind != floor(nind)) nind <<- length(ghead) / 4
if (nind != floor(nind)) print("Incorrect number of columns")
seqID <<- substr(ghead,1,nchar(ghead)-2)[seq(4,4*nind,4)]
if(nogenos) cat("Warning: No SNP info yet with gform ANGSDcounts and nogenos\n")
if(!nogenos) {
genosin <- scan(genofilefn0, skip = 1, sep = "\t", flush=TRUE, what = rep(list(integer(0)), 4*nind), quote="")
nsnps <<- length(genosin[[1]])
SNP_Names <<- paste0("SNP",formatC(seq(nsnps),width=nchar(nsnps),flag="0")) # with leading zeros
alleles4 <- matrix(aperm(array(unlist(genosin,use.names=FALSE),dim =c(nsnps,4,nind)), c(3,2,1)), nrow=nind)
# cols in sets of 4 alleles, rows are samples (temporary, until relevant alleles extracted)
acounts <- matrix(colSums(alleles4),ncol=4,byrow=TRUE)
acountord <- t(apply(acounts,1,order,decreasing=TRUE))
SNP.discard <- which(acounts[cbind(1:nsnps,acountord[,3])] / rowSums(acounts) > triallelic.thresh)
snpcols <- sort(c(seq(0,4*(nsnps-1),4)+acountord[,1],seq(0,4*(nsnps-1),4)+acountord[,2]))
alleles <<- alleles4[,snpcols]
if(length(SNP.discard) > 0) {
alleles <<- alleles[,-c(2*SNP.discard-1,2*SNP.discard)]
nsnps <<- nsnps - length(SNP.discard)
SNP_Names <<- SNP_Names[-SNP.discard]
cat(length(SNP.discard),"SNP(s) removed with 3rd allele frequency >",triallelic.thresh,"\n")
}
}
invisible(NULL)
}
read.vcf <- function(vcffile=genofile) { # uses AD then GT if either/both available
# Needs data.table and (for .gz files) R.utils
if(!require(data.table)) stop("data.table package required for read.vcf")
if(nogenos) cat("Warning: No SNP or sample info yet with gform VCF and nogenos\n")
if(!nogenos) {
vcfin <- fread(vcffile,skip="#CHROM") # skip headers until #CHROM found on a row
if(colnames(vcfin)[1]=="V1") {
cat("Correcting added first column name, remove trailing (blank?) column (ignore fread warning below)\n")
colnames(vcfin)[1:ncol(vcfin)-1] <- colnames(vcfin)[2:ncol(vcfin)]
vcfin[,ncol(vcfin)] <- NULL
}
SNP_Names <<- vcfin$ID
refalleles <<- vcfin$REF
altalleles <<- vcfin$ALT
nsnps <<- length(SNP_Names)
formatcol <- which(colnames(vcfin)=="FORMAT")
seqID <<- colnames(vcfin)[-(1:formatcol)]
nind <<- length(seqID)
chrom <<- vcfin$`#CHROM`
pos <<- vcfin$POS
if(all(SNP_Names==".")) SNP_Names <<- paste(chrom,as.integer(pos),sep="_")
nfields <- 1+ lengths(regmatches(vcfin$FORMAT,gregexpr(":",vcfin$FORMAT)))
tempformats <- read.table(text=vcfin$FORMAT,sep=":",fill=TRUE,stringsAsFactors=FALSE,col.names=paste0("V",1:max(nfields)))
gthave = apply(tempformats=="GT",1,any)
gtpos = unlist(apply(tempformats=="GT",1,which))
adhave = apply(tempformats=="AD",1,any)
adpos = unlist(apply(tempformats=="AD",1,which))
genon <<- matrix(NA,nrow=nind,ncol=nsnps)
if(any(gthave)) {
cat("(Initially) reading genotypes from GT field\n")
tempgt <- read.table(text=as.matrix(vcfin[gthave,-(1:formatcol)]),sep=":",fill=TRUE,stringsAsFactors=FALSE)[matrix(c(1:(nind*sum(gthave)),rep(gtpos,nind)),ncol=2,dimnames=list(NULL,c("row","col")))]
tempgt[tempgt=="."] <- "./."
genongt <- t(matrix(rowSums(read.table(text=gsub("/","|",tempgt),sep="|",na.strings=".")),nrow=sum(gthave)))
genon[,which(gthave)] <<- genongt
}
depth <<- matrix(Inf, nrow = nind, ncol = nsnps)
if(any(adhave)) {
cat("Reading allelic depths from AD field\n")
tempad <- read.table(text=as.matrix(vcfin[adhave,-(1:formatcol)]),sep=":",fill=TRUE,stringsAsFactors=FALSE)[matrix(c(1:(nind*sum(adhave)),rep(adpos,nind)),ncol=2,dimnames=list(NULL,c("row","col")))]
tempad2 <- read.table(text=sub(".","0,0",sub(".,.","0,0",tempad,fixed=TRUE),fixed=TRUE),sep=",")
ref <- t(matrix(tempad2[,1],nrow=sum(adhave)))
alt <- t(matrix(tempad2[,2],nrow=sum(adhave)))
genonad <- trunc((2*ref/(ref+alt))-1)+1
genon[,which(adhave)] <<- genonad
alleles <<- matrix(Inf, nrow = nind, ncol = 2 * nsnps)
alleles[,seq(1, 2 * nsnps - 1, 2)[which(adhave)]] <<- ref
alleles[,seq(2, 2 * nsnps, 2)[which(adhave)]] <<- alt
depth[,which(adhave)] <<- ref + alt
p <<- calcp()
} else {
p <<- colMeans(genon, na.rm = TRUE)/2 # same as pg further down
}
depth[is.na(genon)] <<- 0
if(!any(adhave)) gform <- "chip"
}
invisible(NULL)
}
readChip <- function(genofilefn0 = genofile) {
ghead <- scan(genofilefn0,what="",nlines=1,sep=",", quote="", quiet=TRUE)
SNP_Names <<- ghead[-1]
nsnps <<- length(SNP_Names)
cat("Data file has", nsnps, "SNPs \n")
if(nogenos) cat("Warning: No sample info yet with gform chip data and nogenos\n")
if(!nogenos) {
genost <- scan(genofilefn0,what="",skip=1,sep=",", quote="", quiet=TRUE) # read as text ... easier to pull out elements than list of nsnps+1
snpnums <- ((1:length(genost))-1) %% (nsnps+1)
genon <<- matrix(as.numeric(genost[which(snpnums !=0)]) ,ncol=nsnps,byrow=TRUE)
genon[genon >2 | genon <0] <- NA
seqID <<- genost[which(snpnums ==0)]
nind <<- length(seqID)
cat("Data file has", nind, "samples \n")
rm(genost)
depth <<- matrix(Inf, nrow = nind, ncol = nsnps)
depth[is.na(genon)] <<- 0
p <<- colMeans(genon, na.rm = TRUE)/2 # same as pg further down
}
invisible(NULL)
}
readTassel <- function(genofilefn0 = genofile, usedt="recommended") {
havedt <- FALSE # problem with read.table(text= when > 2bill
if(usedt=="always") havedt <- require("data.table")
gsep <- switch(gform, uneak = "|", tassel = ",")
ghead <- scan(genofilefn0, what = "", nlines = 1, sep = "\t", quote="", quiet=TRUE)
nind <<- length(ghead) - switch(gform, uneak = 6, tassel = 2)
cat("Data file has", nind, "samples \n")
seqID <<- switch(gform, uneak = ghead[2:(nind + 1)], tassel = ghead[-(1:2)])
# find SNPs without reading all genos (perhaps do this only if nogenos is TRUE if its taking too long)
if(gform=="uneak") SNP_Names <<- scan(genofilefn0, what="",skip=1,quote="",flush=TRUE, quiet=TRUE) # 1st column only
if(gform=="tassel") {
tempin <- scan(genofilefn0, what=list(CHROM = "", POS = 0),skip=1,quote="",flush=TRUE, quiet=TRUE) # 1st 2 columns only
chrom <<- tempin$CHROM
pos <<- tempin$POS
SNP_Names <<- paste(chrom,as.integer(pos),sep="_")
}
nsnps <<- length(SNP_Names)
cat("Data file has", nsnps, "SNPs \n")
if(usedt=="recommended" & nsnps * nind > 2^30) havedt <- FALSE # problem with read.table(text= when > 2bill
if(!nogenos) {
if (havedt & gform=="tassel") {
isgzfile <- grepl(".gz",genofilefn0) #gz unzipping will only work on linux systems
if ( packageVersion("data.table") < "1.12" & isgzfile) {
genosin <- fread(paste("gunzip -c",genofilefn0),sep="\t",header=TRUE,showProgress=FALSE)
} else {
genosin <- fread(genofilefn0,sep="\t",header=TRUE)
}
# alleles <<- as.matrix(reshape(data.frame(ids=rep(1:nind,nsnps),snps=rep(1:nsnps,each=nind),
# read.table(text= t(as.matrix(genosin[,-(1:2),with=FALSE])),sep=",")),
# direction="wide",idvar="ids",timevar="snps"))[,-1]
# dcast syntax dcast(data.table(ids ...), ids ~ snps,value.var = c("V1","V2" )) puts all V1 then all V2 so need to rearrange ...
tempalleles <- as.matrix(dcast(data.table(ids=rep(1:nind,nsnps),snps=rep(1:nsnps,each=nind),
read.table(text= t(as.matrix(genosin[,-(1:2),with=FALSE])),sep=",")),
ids ~ snps,value.var = c("V1","V2" ))[,-1])
alleles <<- matrix(0,nrow=nind, ncol=2*nsnps)
alleles[,seq(1, 2 * nsnps - 1, 2)] <<- tempalleles[,1:nsnps]
alleles[,seq(2, 2 * nsnps, 2)] <<- tempalleles[,nsnps+(1:nsnps)]
} else { # use scan to read input
if (gform == "tassel") genosin <- scan(genofilefn0, skip = 1, sep = "\t", what = c(list(chrom = "", coord = 0), rep(list(""), nind)), quote="", quiet=TRUE)
if (gform == "uneak") genosin <- scan(genofilefn0, skip = 1, sep = "\t", what = c(list(chrom = ""), rep(list(""), nind), list(hetc1 = 0, hetc2 = 0, acount1 = 0, acount2 = 0, p = 0)), quote="", quiet=TRUE)
alleles <<- matrix(0, nrow = nind, ncol = 2 * nsnps)
for (iind in 1:nind) alleles[iind, ] <<- matrix(as.numeric(unlist(strsplit(genosin[[iind + switch(gform, uneak = 1, tassel = 2)]], split = gsep,
fixed = TRUE))), nrow = 1)
if (gform == "uneak") AFrq <<- genosin[[length(genosin)]]
}
}
unadepth <- which(is.na(alleles))
if(length(unadepth)>0) alleles[unadepth] <<- 0
invisible(NULL)
}
parkGBS <- function() {
#refalleles altalleles # swapped Dec 23
if(!exists("alleles")) {
alleles <- matrix(0,nrow=nind, ncol=2*nsnps)
tempalleles <- matrix(0,nrow=nind,ncol=nsnps)
tempalleles[which(genon == 0)] <- depth[which(genon==0)]
tempalleles[which(genon == 1)] <- depth[which(genon==1)]/2
alleles[,seq(2, 2 * nsnps, 2)] <- tempalleles # count of alt alleles
tempalleles[which(genon == 2)] <- depth[which(genon==2)]
tempalleles[which(genon == 0)] <- 0
alleles[,seq(1, 2 * nsnps - 1, 2)] <- tempalleles # count of ref alleles
}
parkeddata <- list(nsnps=nsnps,SNP_Names=SNP_Names, seqID = seqID, nind=nind, alleles = alleles)
if(exists("AFrq")) parkeddata <- append(parkeddata,list(AFrq=AFrq))
parkeddata
}
activateGBS <- function(GBSobj) {
if(!is.null(GBSobj)) {
nsnps <<- GBSobj$nsnps; SNP_Names <<- GBSobj$SNP_Names; seqID <<- GBSobj$seqID; nind <<- GBSobj$nind; alleles <<- GBSobj$alleles
if("AFrq" %in% names(GBSobj)) AFrq <<- GBSobj$AFrq
if(exists("depth")) rm(depth, p, genon, inherits=TRUE)
} else cat("GBSobj is invalid\n")
invisible(NULL)
}
joinGBS <- function(join1, join2=NULL, replace=TRUE, uniqueSNPs=FALSE) {
if(is.null(join2)) join2 <- parkGBS()
cat("Joining set 1",join1$nind,"ind x",join1$nsnps,"SNPs, set 2",join2$nind,"ind x",join2$nsnps,"SNPs\n")
if(uniqueSNPs) join1$SNP_Names <- make.names(c(join2$SNP_Names,join1$SNP_Names),unique=TRUE)[join2$nsnps+(1:join1$nsnps)]
SNP_Names <- unique( c(join1$SNP_Names,join2$SNP_Names))
nsnps <- length(SNP_Names)
nind <- join1$nind+join2$nind
seqID <- c(join1$seqID,join2$seqID)
snppos1 <- match(join1$SNP_Names,SNP_Names)
snppos2 <- match(join2$SNP_Names,SNP_Names)
alleles <- matrix(0,nrow=nind,ncol=2*nsnps)
alleles[1:join1$nind,as.vector(rbind(snppos1*2-1,snppos1*2))] <- join1$alleles
alleles[join1$nind+(1:join2$nind),as.vector(rbind(snppos2*2-1,snppos2*2))] <- join2$alleles
if(any(duplicated(seqID))) cat(sum(duplicated(seqID)),"samples with seqID already present (kept separate). Consider using mergeSamples(seqID)\n")
# scoping problems if mergeSamples used inside this function
outobj <- NULL
if(replace) {
nsnps <<- nsnps; SNP_Names <<- SNP_Names; seqID <<- seqID; nind <<- nind; alleles <<- alleles
if(exists("depth")) rm(depth,genon, pos=1)
if(exists("AFrq")) rm(AFrq, pos=1)
} else {
outobj <- list(nsnps=nsnps,SNP_Names=SNP_Names, seqID = seqID, nind=nind, alleles = alleles)
}
invisible(outobj)
}
samp.remove <- function (samppos=NULL, keep=FALSE) {
if(keep) samppos <- setdiff(1:nind,samppos)
if(length(samppos)>0) {
# if(gform != "chip") alleles <<- alleles[-samppos, ]
# if(gform == "chip" & exists("alleles") & alleles.keep) alleles <<- alleles[-samppos,]
if(exists("alleles")) alleles <<- alleles[-samppos,,drop=FALSE]
if(exists("depth")) depth <<- depth[-samppos, ,drop=FALSE]
if(exists("genon")) genon <<- genon[-samppos,,drop=FALSE]
if(exists("sampdepth")) sampdepth <<- sampdepth[-samppos]
if(exists("samples")) samples <<- samples[-samppos,,drop=FALSE]
seqID <<- seqID[-samppos]
nind <<- nind - length(samppos)
}
}
snp.remove <- function(snppos=NULL, keep=FALSE) {
if(keep) snppos <- setdiff(1:nsnps,snppos)
if (length(snppos) > 0) {
SNP_Names <<- SNP_Names[-snppos]
nsnps <<- length(SNP_Names)
if(exists("p")) p <<- p[-snppos]
if(exists("depth")) depth <<- depth[, -snppos,drop=FALSE]
if(exists("genon")) genon <<- genon[, -snppos,drop=FALSE]
if(exists("samples")) samples <<- samples[,-snppos,drop=FALSE]
if(exists("chrom")) chrom <<- chrom[-snppos]
if(exists("pos")) pos <<- pos[-snppos]
if(exists("refalleles")) refalleles <<- refalleles[-snppos]
if(exists("altalleles")) altalleles <<- altalleles[-snppos]
if(exists("AFrq")) AFrq <<- AFrq[-snppos]
if (exists("alleles")) {
uremovea <- sort(c(2 * snppos, 2 * snppos - 1)) # allele positions
if(exists("RAcounts")) RAcounts <<- RAcounts[-snppos, ,drop=FALSE]
alleles <<- alleles[, -uremovea,drop=FALSE]
if(exists("allelecounts")) allelecounts <<- allelecounts[uremovea]
}
}
}
negCreport <- function(negpos,removeneg=FALSE) {
if(length(negpos)>0) {
negCstats <- data.frame(seqID=seqID[negpos], callrate= 1 - rowSums(depth[negpos,,drop=FALSE] == 0)/nsnps, sampdepth=rowMeans(depth[negpos,,drop=FALSE]), stringsAsFactors = FALSE)
write.csv(negCstats, "negCStats.csv", row.names = FALSE)
removetxt <- ""; if(removeneg) removetxt <- "removed"
cat(length(negpos),"Negative controls", removetxt,"\n mean call rate = ",mean(negCstats$callrate),
"\n max call rate = ",max(negCstats$callrate),
"\n mean depth = ",mean(negCstats$sampdepth),
"\n max depth = ",max(negCstats$sampdepth), "\n")
if(removeneg) samp.remove(negpos)
negCstats
} else
invisible(NULL)
}
HWpops <- function(snpsubset, indsubset, populations=NULL, depthmat = depth) {
if (missing(snpsubset)) snpsubset <- 1:nsnps
if (missing(indsubset)) indsubset <- 1:nind
if (is.null(populations)) populations <- rep("A",nind)
popnames <- unique(populations[indsubset])
npops <- length(popnames)
HWdis <- matrix(NA,nrow=npops,ncol=length(snpsubset)); rownames(HWdis) <- popnames #initialise
l10LRT <- x2star <- l10pstar <- maf <- HWdis
for(ipop in 1:npops) {
thigroup <- popnames[ipop]
indgroup <- intersect(indsubset,which(populations==thigroup))
naa <- colSums(genon[indgroup,snpsubset,drop=FALSE] == 2, na.rm = TRUE)
nab <- colSums(genon[indgroup,snpsubset,drop=FALSE] == 1, na.rm = TRUE)
nbb <- colSums(genon[indgroup,snpsubset,drop=FALSE] == 0, na.rm = TRUE)
n1 <- 2 * naa + nab
n2 <- nab + 2 * nbb
n <- n1 + n2 #n alleles
p1 <- n1/n
p2 <- 1 - p1
HWdis[ipop,] <- naa/(naa + nab + nbb) - p1 * p1
x2 <- (naa + nab + nbb) * HWdis[ipop,]^2/(p1^2 * p2^2)
LRT <- 2 * (n * log(n) + naa * log(pmax(1, naa)) + nab * log(pmax(1, nab)) + nbb * log(pmax(1, nbb)) - (n/2) * log(n/2) - n1 * log(n1) - n2 *
log(n2) - nab * log(2)) # n is # alleles = 2* n obs
# l10p <- -log10(exp(1)) * pchisq(x2, 1, lower.tail = FALSE, log.p = TRUE)
l10LRT[ipop,] <- -log10(exp(1)) * pchisq(LRT, 1, lower.tail = FALSE, log.p = TRUE)
Kdepth <- depth2K(depthmat[indgroup,snpsubset,drop=FALSE])
Kdepth[depthmat[indgroup,snpsubset,drop=FALSE]==0] <- NA
esnphetstar <- 2*p1*p2*(1-2*colMeans(Kdepth,na.rm=TRUE))
osnphetstar <- nab/(naa + nab + nbb)
x2star[ipop,] <- colSums(1-2*Kdepth,na.rm=TRUE)*(1-osnphetstar/esnphetstar)^2 # corrected Nov 2018
l10pstar[ipop,] <- -log10(exp(1)) * pchisq(x2star[ipop,], 1, lower.tail = FALSE, log.p = TRUE)
maf[ipop,] <- ifelse(p1 > 0.5, p2, p1)
}
outobj <- list( HWdis=HWdis, l10LRT=l10LRT, x2star=x2star, l10pstar=l10pstar, maf=maf)
if(npops>1) outobj <- c(outobj, list(l10pstar.pop = -log10(exp(1)) * pchisq(colSums(x2star,na.rm=TRUE), colSums(!is.na(x2star)), lower.tail = FALSE, log.p = TRUE) ))
outobj
}
finplot <- function(HWdiseq=HWdis, MAF=maf, plotname="finplot", finpalette=palette.aquatic, finxlim=c(0,0.5), finylim=c(-0.25, 0.25)) {
depthtrans <- function(x) round(20 * log(-log(1/(x + 0.9)) + 1.05)) # to compress colour scale at higher depths
depthpoints <- c(0.5, 5, 50, 250) # legend points
transpoints <- depthtrans(depthpoints)
mindepthplot <- 0.1
maxdepthplot <- 256
maxtrans <- depthtrans(maxdepthplot)
legend_image <- as.raster(matrix(rev(finpalette[1:maxtrans]), ncol = 1))
png(paste0(plotname,".png"), width = 960, height = 960, pointsize = cex.pointsize * 18)
if(whitedist(finpalette) < 25) par(bg="grey")
plot(HWdiseq ~ MAF, col = finpalette[depthtrans(pmax(mindepthplot, pmin(snpdepth, maxdepthplot)))], cex = 0.8,
xlab = "Minor allele frequency", ylab = "Hardy-Weinberg disequilibrium", cex.lab = 1.5, xlim=finxlim, ylim=finylim)
rasterImage(legend_image, 0.05, -0.2, 0.07, -0.1)
text(x = 0.1, y = -0.2 + 0.1 * transpoints/maxtrans, labels = format(depthpoints))
text(x = 0.075, y = -0.075, labels = "SNP Depth", cex = 1.2)
dev.off()
}
HWsigplot <- function(HWdiseq=HWdis, MAF=maf, ll=l10LRT, plotname="HWdisMAFsig", finpalette=palette.aquatic, finxlim=c(0,0.5), finylim=c(-0.25, 0.25),
llname=expression('-log'[10]*' LRT'), sortord=ll) {
sigtrans <- function(x) round(sqrt(x) * 40/max(sqrt(ll),na.rm=TRUE)) + 1 # to compress colour scale at higher LRT
sigpoints <- c(0.5, 2, 5, 20, 50, 200, 500) # legend points
sigpoints <- sigpoints[union(1:2,which(sigpoints < max(ll,na.rm=TRUE)))]
if(length(sigpoints) > 5) sigpoints <- sigpoints[seq(1,length(sigpoints),2)]
transpoints <- sigtrans(sigpoints)
maxtrans <- sigtrans(max(ll,na.rm=TRUE))
legend_image <- as.raster(matrix(rev(finpalette[1:maxtrans]), ncol = 1))
plotord <- 1:length(MAF)
if(!is.null(sortord)) plotord <- order(sortord)
png(paste0(plotname,".png"), width = 640, height = 640, pointsize = cex.pointsize * 15)
if(whitedist(finpalette) < 25) par(bg="grey")
plot(HWdiseq[plotord] ~ MAF[plotord], col = finpalette[sigtrans(ll)][plotord], cex = 0.8, xlab = "Minor Allele Frequency",
ylab = "Hardy-Weinberg disequilibrium", cex.lab = 1.5, xlim=finxlim, ylim=finylim)
rasterImage(legend_image, 0.05, -0.2, 0.07, -0.1)
text(x = 0.1, y = -0.2 + 0.1 * transpoints/maxtrans, labels = format(sigpoints))
text(x = 0.075, y = -0.075, labels = llname, cex = 1.2)
dev.off()
}
finclass <- function(HWdiseq=HWdis, MAF=maf, colobj, classname=NULL, plotname="finclass", finxlim=c(0,0.5), finylim=c(-0.25, 0.25)) {
if(missing(colobj)) colobj <- list(collabels="",collist="black",sampcol=rep("black",length(MAF)))
plotord <- 1:length(MAF) # fixed for now, keep in case want to allow reordering
png(paste0(plotname,".png"), width = 640, height = 640, pointsize = cex.pointsize * 15)
plot(HWdiseq[plotord] ~ MAF[plotord], col = colobj$sampcol[plotord], cex = 0.8, xlab = "Minor Allele Frequency",
ylab = "Hardy-Weinberg disequilibrium", cex.lab = 1.5, xlim=finxlim, ylim=finylim)
legend(0.05, -0.075, legend=colobj$collabels,col=colobj$collist,pch=1,title=classname)
dev.off()
}
x2starplots <- function () {
HWsigplot(ll=l10pstar,llname=expression('-log'[10]*'p X'^2*'*'), finpalette=colorRampPalette(c("deepskyblue2","red"))(50))
yaxpts <- quantile(x2star,QQprobpts, na.rm=TRUE) # NA when max depth is 1
png("X2star-QQ.png", width = 480, height = 480, pointsize = cex.pointsize * 12)
par(mar = c(5.1, 4.1, 4.1, 4.1))
qqplot(qchisq(ppoints(nsnps), df = 1), x2star, cex=0.75, main = parse(text = "Hardy-Weinberg ~~ X^2~~ '* Q-Q Plot'"),
xlab = parse(text = "Theoretical ~~ (chi[1]^2) ~~ Quantiles"), ylab = "Sample Quantiles")
ytck <- axis(side=4, tick=FALSE, labels=FALSE)
axis(side=4, at=ytck, labels = signif(-log10(exp(1)) * pchisq(ytck, 1, lower.tail = FALSE, log.p = TRUE),3))
mtext(text= expression('-log'[10]*'p X'^2*'*'), side=4, line=3)
if(length(QQprobpts) > 0) {
for(ipt in 1:length(QQprobpts)) {
lines(x=c(0,xaxpts[ipt],xaxpts[ipt]),y=c(yaxpts[ipt],yaxpts[ipt],0), col="grey")
}
text(x=xaxpts/4,y=yaxpts,labels=QQprobpts, pos=3, col="grey")
}
dev.off()
}
HDplot <- function(plotname="HDplot", colourtype = "depth", finpalette=palette.aquatic, HDxlim=c(0,1), HDylim=c(-Inf, Inf), HDcol=NULL,
sortcol = "asc") {
# from Mckinney Mol Ecol Res 2017
# colourtype can be "depth", "HW" (use l10LRT), "HW*" (use l10pstar)
# sortcol can be "asc", "desc" or ""
if(!exists("alleles")) cat("Cannot produce HD plots without alleles object\n")
if(exists("alleles")) {
if(!colourtype %in% c("depth", "HW", "HW*")) colourtype <- "depth"
if(!sortcol %in% c("asc","desc")) sortcol <- ""
if(!exists("HD.saved.KGD")) {
HD.saved.KGD <<- TRUE
Het <<- colSums(genon == 1, na.rm=TRUE) / (nind * SNPcallrate)
SNPN <<- colSums(depth * (genon ==1), na.rm=TRUE)
SNPNA <<- colSums(alleles[, seq(1, 2 * nsnps - 1, 2)] * (genon ==1), na.rm=TRUE)
storage.mode(SNPN) <- storage.mode(SNPNA) <- "integer"
}
SNPz <- (SNPN/2 - SNPNA)/sqrt(SNPN * 0.5 * 0.5) # denom is SNPsd
if(colourtype == "depth") {
colourvar <- snpdepth
legendlab <- "SNP Depth"
colvtrans <- function(x) round(20 * log(-log(1/(x + 0.9)) + 1.05)) # to compress colour scale at higher depths
colvpoints <- c(0.5, 5, 50, 250) # legend points
mincolvplot <- 0.1
maxcolvplot <- 256
}
if(colourtype=="HW") {colourvar <- l10LRT; legendlab <- expression('-log'[10]*' LRT')}
if(colourtype=="HW*") {colourvar <- l10pstar; legendlab <- expression('-log'[10]*'p X'^2*'*')}
if(grepl("^HW", colourtype)) {
mincolvplot <- 0
maxcolvplot <- max(colourvar,na.rm=TRUE)
colvtrans <- function(x) round(sqrt(x) * 40/max(sqrt(colourvar),na.rm=TRUE)) + 1 # to compress colour scale at higher LRT
colvpoints <- c(0.5, 2, 5, 20, 50, 200, 500) # legend points
colvpoints <- colvpoints[union(1:2,which(colvpoints < maxcolvplot))]
if(length(colvpoints) > 5) colvpoints <- colvpoints[seq(1,length(colvpoints),2)]
}
maxtrans <- colvtrans(maxcolvplot)
mintrans <- colvtrans(mincolvplot)
transpoints <- colvtrans(colvpoints)
HDxlim[2] <- HDxlim[2] + 0.13 # make some room for legend
legend_image <- as.raster(matrix(rev(finpalette[1:maxtrans]), ncol = 1))
HDc <- HDcol
if(is.null(HDcol)) HDc <- finpalette[colvtrans(pmax(mincolvplot, pmin(colourvar, maxcolvplot)))]
uplot <- which(SNPN > 0)
if( HDylim[1] == -Inf) HDylim[1] <- min(SNPz[uplot])
if( HDylim[2] == Inf) HDylim[2] <- max(SNPz[uplot])
plotch <- rep(1,nsnps)
plotch[which(SNPz > HDylim[2])] <- 94 # ^
plotch[which(SNPz < HDylim[1])] <- 118 # v
plotord <- 1:nsnps
if(is.null(HDcol)) {
if(sortcol == "asc") plotord <- order(colourvar)
if(sortcol == "desc") plotord <- order(colourvar, decreasing = TRUE)
}
png(paste0(plotname,".png"), width = 960, height = 960, pointsize = cex.pointsize * 18)
if(whitedist(finpalette) < 25) par(bg="grey")
plot(pmax(pmin(SNPz,HDylim[2]),HDylim[1])[plotord][uplot] ~ Het[plotord][uplot], col = HDc[plotord][uplot], cex = 0.8, pch = plotch[plotord][uplot],
xlab = "Proportion of heterozygotes (H)", ylab = "Read ratio deviation (D)", cex.lab = 1.5, xlim=HDxlim, ylim=HDylim)
# frame.plot = FALSE,
if(is.null(HDcol)) {
x0 <- 0.96 # lhs of key
rect((x0-.05)*HDxlim[2], 1.1*HDylim[1]+0.05*HDylim[2], (x0+.13)*HDxlim[2], 0.85*HDylim[1]+0.15*HDylim[2], col="white", border="grey", xpd=NA)
rasterImage(legend_image, x0*HDxlim[2], HDylim[1], (x0+0.04)*HDxlim[2], 0.9*HDylim[1]+0.1*HDylim[2])
text(x = (x0+0.07)*HDxlim[2], y = HDylim[1] + 0.1*(HDylim[2]-HDylim[1]) * (transpoints-mintrans)/(maxtrans-mintrans), labels = format(colvpoints), xpd=NA, cex=0.8)
text(x = (x0+0.03)*HDxlim[2], y =0.88*HDylim[1]+0.12*HDylim[2], labels = legendlab, cex = 1, xpd=NA)
}
dev.off()
}
}
mafplot <- function(MAF=maf,plotname="MAF", barcol="grey", doplot=TRUE, ...) {
if(doplot) png(paste0(plotname,".png"), pointsize = cex.pointsize * 12)
histinfo <- hist(MAF, breaks = 50, xlab = "Minor Allele Frequency", col = barcol, plot= doplot, ...)
if(doplot) dev.off()
if(doplot) histinfo <- paste(plotname," png output created")
histinfo
}
na.zero <- function (x) {
x[is.na(x)] <- 0
return(x)
}
calcp <- function(indsubset, pmethod="A") {
if(!pmethod == "G") pmethod <- "A"
if (missing(indsubset)) indsubset <- 1:nind
if(exists("depth")) if(any(depth==Inf)) pmethod <- "G"
if (pmethod == "A") {
if (nrow(alleles) == nind) {
alleles <- alleles[indsubset,,drop=FALSE] # alleles not repaced in parent env
if(any(alleles==Inf)) {
hetInf <- alleles[,seq(2, 2 * nsnps, 2)] * alleles[,seq(1, 2 * nsnps - 1, 2)]
alleles <- pmin(alleles,2) # perhaps a bit approx? only use if genon not available
uInf <- which(hetInf==Inf, arr.ind=TRUE)
uInf[,2] <- 2*uInf[,2]
alleles[uInf] <- alleles[uInf]/2
uInf[,2] <- uInf[,2]-1
alleles[uInf] <- alleles[uInf]/2
}
RAcountstemp <- matrix(colSums(alleles), ncol = 2, byrow = TRUE) # 1 row per SNP, ref and alt allele counts
afreqs <- RAcountstemp[, 1]/rowSums(RAcountstemp) # p for ref allele - based on # reads, not on inferred # alleles
} else {
afreqs <- NULL
print("Error: alleles is wrong size for pmethod A, using pmethod G instead")
pmethod <- "G"
}
}
if (pmethod == "G") afreqs <- colMeans(genon[indsubset,,drop=FALSE], na.rm = TRUE)/2 # allele freq assuming genotype calls
afreqs
}
redosamples <- function() { # sample 1 read per genotype (not actually redo'ing the first time which is usually in GBSsummary)
samples <<- genon
samples[na.zero(genon) == 1] <<- 2* (sample.int(2, sum(genon == 1, na.rm=TRUE), replace = TRUE) - 1) # allows genon to have > .Machine$integer.max elements
}
alleles2g <- function(dogenon=TRUE,dodepth=TRUE) {
if(dodepth) depth <<- alleles[, seq(1, 2 * nsnps - 1, 2),drop=FALSE] + alleles[, seq(2, 2 * nsnps, 2),drop=FALSE]
if(dogenon) {
genon <<- alleles[, seq(1, 2 * nsnps - 1, 2), drop=FALSE]/depth
if(max(alleles)==Inf) {
atemp <- alleles
atemp[alleles==Inf] <- 1e6
dtemp <- atemp[, seq(1, 2 * nsnps - 1, 2), drop=FALSE] + atemp[, seq(2, 2 * nsnps, 2), drop=FALSE]
genon <<- atemp[, seq(1, 2 * nsnps - 1, 2), drop=FALSE]/dtemp
}
genon <<- trunc(2*genon-1)+1
}
}
GBSsummary <- function() {
gform <- tolower(gform)
depthinfo <- FALSE
havedepth <- exists("depth") # if depth present, assume it and genon are correct & shouldn't be recalculated (as alleles may be the wrong one)
if(havedepth & !gform %in% c("vcf","chip")) cat("Warning: depth object already exists - reusing\n")
repeat{ # repeat samp checks + snp checks until no more removed
if(gform != "chip") {
if (!havedepth) alleles2g(dogenon=FALSE) #create depth
if(is.null(dim(depth))) depth <<- matrix(depth,nrow=nind,ncol=nsnps)
# storage.mode(depth) <- "integer"
if (nchar(negC) > 0) negCstats <<- negCreport(negpos=do.call(grep,c(list(negC,seqID),negCsettings)),removeneg=TRUE) # check and report negative controls
if (have_rcpp & storage.mode(depth)=="integer") {
sampdepth.max <- rcpp_rowMaximums(depth, nThreads)
} else {
sampdepth.max <- apply(depth, 1, max)
}
sampdepth <<- rowMeans(depth)
depthinfo <- TRUE; if(min(depth)==Inf) depthinfo <- FALSE
ssraw <- data.frame(seqID, sampdepth); if (exists("negCstats")) ssraw <- rbind(negCstats[,c(1,3)],ssraw)
if(depthinfo) write.csv(ssraw, "SampleStatsRaw.csv", row.names = FALSE)
u0 <- which(sampdepth.max == 0)
u1 <- setdiff(which(sampdepth.max == ifelse(sampdepth.thresh==0,0,1) | sampdepth < sampdepth.thresh), u0)
nmax0 <- length(u0)
nmax1 <- length(u1)
seqID.removed <<- character(0)
if (nmax0 > 0) {
cat(nmax0, "samples with no calls (maximum depth = 0) removed:\n")
seqID.removed <<- seqID[u0]
print(data.frame(indnum = u0, seqID = seqID.removed, sampdepth = sampdepth[u0]))
}
if (nmax1 > 0) {
cat(nmax1, "samples with maximum depth of 1 and/or mean depth <", sampdepth.thresh, "removed:\n")
print(data.frame(indnum = u1, seqID = seqID[u1], sampdepth = sampdepth[u1]))
seqID.removed <<- c(seqID.removed, seqID[u1])
}
samp.remove(union(u0, u1))
if (!gform == "chip") {
if (!havedepth) alleles2g(dodepth = FALSE) # create genon
if(outlevel > 7) redosamples()
}
gc()
docalcp <- FALSE
if (!exists("p") | length(seqID.removed) > 0) docalcp <- TRUE
if (exists("p")) if (length(p) != nsnps) docalcp <- TRUE
if (docalcp) { # not redone e.g. after merge
p <<- calcp()
if (is.null(p)) {
cat("alleles not available, using genotype method for p\n")
p <<- calcp(pmethod="G")
}
}
if(exists("genosin")) rm(genosin)
} #end GBS-specific
write.csv(data.frame(seqID = seqID), "seqID.csv", row.names = FALSE)
snpdepth <<- colMeans(depth)
uremove <- which(p < maf.thresh | p > 1-maf.thresh | snpdepth < snpdepth.thresh) # | is.nan(p) # is this needed too? implies depth=0
nmaf0 <- length(which(p < maf.thresh | p > 1-maf.thresh))
cat(nmaf0, "SNPs with MAF <",maf.thresh,"and", length(uremove)-nmaf0, "SNPs with no data or with depth <", snpdepth.thresh, "removed\n")
snp.remove(uremove)
if(length(uremove)==0) break
havedepth <- TRUE
} # samp and snp removes
cat("Analysing", nind, "individuals and", nsnps, "SNPs\n")
###### compare allele frequency estimates from allele counts and from genotype calls (& from input file, if uneak format)
pg <<- colMeans(genon, na.rm = TRUE)/2 # allele freq assuming genotype calls
if(outlevel > 4) {
png("AlleleFreq.png", width = 960, height = 960, pointsize = cex.pointsize * 18)
p.lab <- "Allele frequency from allele counts"
pg.lab <- "Allele frequency from genotype calls"
AF.lab <- "Allele frequency given"
if (outlevel > 6 & exists("AFrq")) pairs(cbind(pg, p, AFrq), col = "#80808020", pch = 16, cex = 0.8, labels = c(pg.lab, p.lab, AF.lab))
if (outlevel < 7 | !exists("AFrq")) plot(pg ~ p, col="#80808020", pch=16, cex=0.8, xlab=p.lab, ylab=pg.lab)
dev.off()
}
# calc some overall snp stats
HWstats <- HWpops(depthmat = depth)
HWdis <<- HWstats$HWdis[1,]; l10LRT <<- HWstats$l10LRT[1,]; x2star <<- HWstats$x2star[1,]; l10pstar <<- HWstats$l10pstar[1,]; maf <<- HWstats$maf[1,]
LRT <- qchisq(-log(10)*l10LRT, 1, lower.tail = FALSE, log.p = TRUE)
sampdepth <<- rowMeans(depth) # recalc after removing SNPs and samples
#if(outlevel > 4) sampdepth.med <<- apply(depth, 1, median)
if(outlevel > 4) {
if (have_rcpp & storage.mode(depth)=="integer") {
sampdepth.med <<- rcpp_rowMedians(depth, nThreads)
} else {
sampdepth.med <<- apply(depth, 1, median)
}
}
depth0 <- rowSums(depth == 0)
snpdepth <<- colMeans(depth)
missrate <- sum(as.numeric(depth == 0))/nrow(depth)/ncol(depth)
cat("Proportion of missing genotypes: ", missrate, "Callrate:", 1-missrate,"\n")
callrate <<- 1 - rowSums(depth == 0)/nsnps # sample callrate, after removing SNPs, samples
SNPcallrate <<- 1 - colSums(depth == 0)/nind
png("CallRate.png", width = 480, height = 480, pointsize = cex.pointsize * 12)
hist(callrate, seq(0,1,0.02), col = "cornflowerblue", border = "cornflowerblue", main = "Histogram of sample call rates", xlab = "Call rate (proportion of SNPs scored)")
dev.off()
png("SNPCallRate.png", width = 480, height = 480, pointsize = cex.pointsize * 12)
# suggested by Jaroslav Klapste (Scion)
hist(SNPcallrate, seq(0,1,0.02), col = "cornflowerblue", border = "cornflowerblue", main = "Histogram of SNP call rates", xlab = "Call rate (proportion of samples scored)")
dev.off()
if (!depthinfo) write.csv(data.frame(seqID, callrate), "SampleStats.csv", row.names = FALSE)
if (depthinfo) {
write.csv(data.frame(seqID, callrate, sampdepth), "SampleStats.csv", row.names = FALSE)
sampdepth.scored <- sampdepth * nsnps/(nsnps - depth0)
ufinite <- which(sampdepth < Inf)
haschip <- (length(ufinite) < nind)
noninf <- ""; if (haschip) noninf <- "(non-chip)"
cat("Mean sample depth:", mean(sampdepth), "\n")
if(haschip) cat("Mean sample depth (non-chip):", mean(sampdepth[ufinite]), "\n")
if(length(ufinite) > 0) {
if(outlevel > 4) {
png("SampDepth.png", width = 480, height = 480, pointsize = cex.pointsize * 12)
plot(sampdepth[ufinite] ~ sampdepth.med[ufinite], col = "#80808080", pch = 16, cex = 1.2, main = paste("Sample Depth",noninf), xlab = "Median", ylab = "Mean")
dev.off()
}
png("SampDepth-scored.png", width = 480, height = 480, pointsize = cex.pointsize * 12)
plot(sampdepth.scored[ufinite] ~ sampdepth[ufinite], col = "#80808080", pch = 16, cex = 1.2, main = paste("Sample Depth",noninf), xlab = "Mean", ylab = "Mean with depth>0")
dev.off()
png("SampDepthHist.png", width = 480, height = 480, pointsize = cex.pointsize * 12)
hist(sampdepth[ufinite], 100, col = "cornflowerblue", border = "cornflowerblue", main = paste("Histogram of mean sample depth",noninf), xlab = "Mean sample depth")
dev.off()
png("SampDepthCR.png", width = 480, height = 480, pointsize = cex.pointsize * 12)
plot(sampdepth[ufinite] ~ callrate[ufinite], col = "#80808080", pch = 16, cex = 1.2, main = paste("Sample Depth v Call rate",noninf), xlab = "Sample call rate", ylab = "Mean sample depth")
dev.off()
}
ufinite <- which(snpdepth < Inf)
haschip <- (length(ufinite) < nsnps)
noninf <- ""; if (haschip) noninf <- "(non-chip)"
if(length(ufinite) >0 ) {
png("SNPDepthHist.png", width = 480, height = 480, pointsize = cex.pointsize * 12)
hist(snpdepth[ufinite], 100, col = "cornflowerblue", border = "cornflowerblue", main = paste("Histogram of mean SNP depth",noninf), xlab = "Mean SNP depth")
dev.off()
png("SNPDepth.png", width = 640, height = 640, pointsize = cex.pointsize * 15)
plot(SNPcallrate[ufinite] ~ snpdepth[ufinite], log="x", col = "#80808080", pch = 16, cex = 1, main = paste("SNP Depth",noninf), ylab = "SNP Call rate (proportion of samples scored)",
xlab = "Mean SNP depth (log scale)")
dev.off()
}
}
xaxpts <<- qchisq(QQprobpts,df=1)
finplot()
x2starplots()
if(outlevel > 9) HWsigplot(plotname="HWdisMAFsig-raw")
if(outlevel > 4) {
yaxpts <- quantile(LRT,QQprobpts, na.rm=TRUE)
png("LRT-QQ.png", width = 480, height = 480, pointsize = cex.pointsize * 12)
qqplot(qchisq(ppoints(nsnps), df = 1), LRT, cex=0.75, main = "Hardy-Weinberg LRT Q-Q Plot",
xlab = parse(text = "Theoretical ~~ (chi[1]^2) ~~ Quantiles"), ylab = "Sample Quantiles")
if(length(QQprobpts) > 0) {
for(ipt in 1:length(QQprobpts)) {
lines(x=c(0,xaxpts[ipt],xaxpts[ipt]),y=c(yaxpts[ipt],yaxpts[ipt],0), col="grey")
}
text(x=xaxpts/4,y=yaxpts,labels=QQprobpts, pos=3, col="grey")
}
dev.off()
png("LRT-hist.png", width = 480, height = 480, pointsize = cex.pointsize * 12)
hist(LRT, breaks = 50, col = "grey", xlab = "Hardy Weinberg likelihood ratio test statistic")
dev.off()
}
mafplot()
######### depth[depth < 2] <<- 1.1 # not using depth values <2 after this so set to >1 to avoid 0 divisor note do not use depth.max <2 though
fcolo <<- rep("black", nind) # modify this to specify colours for individuals in the plots
}
palette.aquatic <- colorRampPalette(c(rgb(200, 200, 200, max = 255), "blue"))(50) # grey to blue
palette.terrain <- terrain.colors(50)
palette.temperature <- colorRampPalette(c("blue","white","red"))(50)
whitedist <- function(pal) min(colSums(abs(col2rgb(pal)-matrix(255,nrow=3,ncol=length(pal)))))
if(!functions.only) {
readGBS()
GBSsummary()
} # !functions.only
################## functions
upper.vec <- function(sqMatrix,diag=FALSE) as.vector(sqMatrix[upper.tri(sqMatrix,diag=diag)])
corner <- function(mtx, size=6L) print(mtx[1:size,1:size])
eqline <- function(a=0,b=1,col="red",lwd=2, ...) abline(a=a,b=b,col=col,lwd=lwd, ...)
colMax <- function(x, na.rm = FALSE) apply(x,2,max,na.rm=na.rm)
rowMax <- function(x, na.rm = FALSE) apply(x,1,max,na.rm=na.rm)
rowMin <- function(x, na.rm = FALSE) apply(x,1,min,na.rm=na.rm)
colMin <- function(x, na.rm = FALSE) apply(x,2,min,na.rm=na.rm)
colwhich.Max <- function(x, na.rm = FALSE) apply(x,2,which.max)
rowwhich.Max <- function(x, na.rm = FALSE) apply(x,1,which.max)
colwhich.Min <- function(x, na.rm = FALSE) apply(x,2,which.min)
rowwhich.Min <- function(x, na.rm = FALSE) apply(x,1,which.min)
which.max.arr <- function(x) arrayInd(which.max(x),dim(x),dimnames(x)) # used by posCreport
#seq2samp <- function(seqIDvec=seqID) read.table(text=seqIDvec,sep="_",stringsAsFactors=FALSE,fill=TRUE)[,1] # might not get number of cols right
seq2samp1 <- function(seqIDvec=seqID, splitby="_", ...) sapply(strsplit(seqIDvec,split=splitby, ...),"[",1)
seq2samp <- function(seqIDvec=seqID, splitby="_",nparts=NULL,dfout=FALSE, ...){
if(is.null(nparts)) {
sampout <- sapply(strsplit(seqIDvec,split=splitby, ...),"[",1)
} else {
nparts <- as.integer(nparts)
if(nparts < 2) nparts <- 2
nsep <- nchar(gsub(paste0("[^",splitby,"]"),"",seqIDvec))
seqIDvec1 <- paste0(seqIDvec, strrep(splitby,pmax(0,nparts-1-nsep)))
if(splitby %in% c(".","$","^","|","?","*","+","(",")")) splitby <- paste0("\\",splitby)
stringpart <- paste(rep("(\\S*)",nparts),collapse=splitby) # * means 0 or more times
stringpart <- paste(rep("(.*)",nparts),collapse=splitby)
seqIDexpr <- paste0("^",stringpart,"$")
sampout <- gsub(seqIDexpr,"\\1",seqIDvec1)
if(dfout) {
sampout <- as.data.frame(sampout,stringsAsFactors=FALSE)
for(ipart in 2:nparts) sampout <- cbind(sampout, gsub(seqIDexpr,paste0("\\",ipart),seqIDvec1),stringsAsFactors=FALSE)
colnames(sampout) <- paste0("V",1:nparts)
}
}
sampout
}
colourby <- function(colgroup, nbreaks=0, col.name=NULL, symbgroup=NULL, symb.name=NULL,groupsort=FALSE,grouporder=NULL, maxlight=1,alpha=1,
reverse=FALSE,symbset=NULL, stdpal= "rainbow", hclpals=character(0),pal.upper=1, nacolour="black") {
#maxlight is maximum lightness between 0 and 1
#nbreaks is suggested # breaks
isgroups <- (nbreaks==0)
npals <- length(hclpals)
if(isgroups) {
collabels <- unique(colgroup)
if(!is.null(nacolour)) collabels <- na.omit(collabels)
if(groupsort) collabels <- sort(collabels,na.last=TRUE)
if(!is.null(grouporder)) if(length(grouporder)==length(collabels)) collabels <- collabels[grouporder]
}
if(!isgroups) {
histinfo <- hist(colgroup,nbreaks,plot=FALSE)
collabels <- histinfo$mids
colgroup <- collabels[cut(colgroup,breaks = histinfo$breaks, labels=FALSE, include.lowest=TRUE)] # redefine input
} else collabels <- as.character(collabels)
ncol <- length(collabels)
if( tryCatch(is.matrix(col2rgb(stdpal[1])), error=function(e) FALSE)) {collist <- stdpal; stdpal <- "rainbow"}
if(stdpal=="rainbow") collist <- rainbow(ncol)
if(grepl("heat",stdpal)) collist <- heat.colors(ncol)
if(grepl("terrain",stdpal)) collist <- terrain.colors(ncol)
if(grepl("topo",stdpal)) collist <- topo.colors(ncol)
if(grepl("cm",stdpal)) collist <- cm.colors(ncol)
if(ncol > 8 & isgroups) collist[seq(2,ncol,2)] <- rgb((t(col2rgb(collist[seq(2,ncol,2)]))+matrix(127,ncol=3,nrow=floor(ncol/2)))/2,maxColorValue = 255) # darken every 2nd one
if(npals > 0 & exists("hcl.colors")) {
for(ipal in 1:npals) {
addcols <- hcl.colors(ceiling(ncol/(npals*pal.upper)),pal=hclpals[ipal])[1:ceiling(ncol/npals)]
if(ipal==1) collist <- addcols else collist <- c(collist,addcols)
}
collist <- collist[1:ncol] # trim if needed
}
lightness <- colSums( col2rgb(collist))/(3*255)
collist <- rgb(t(col2rgb(collist) %*% diag(pmin(lightness,rep(maxlight,length(lightness))) / lightness)), maxColorValue = 255)
if(alpha < 1) {
rgbcols <- col2rgb(collist)
collist <- rgb(rgbcols[1,],rgbcols[2,],rgbcols[3,],alpha*255,maxColorValue=255)
}
if(reverse) collist <- rev(collist)
sampcol <- collist[match(colgroup,collabels)]
sampcol[is.na(sampcol)] <- nacolour
outlist <- list(collabels=collabels,collist=collist,sampcol=sampcol)
if(!is.null(col.name)) outlist <- c(outlist,col.name=col.name)
if (all(as.integer(symbset)==symbset)) {
if(is.null(symbgroup)) {
symblist <- suppressWarnings(symbset + rep(0,ncol)) # uses R recycle
sampsymb <- symblist[match(colgroup,collabels)]
sampsymb[is.na(sampsymb)] <- 1 # make sure no NAs
outlist <- c(outlist,list(symblist=symblist,sampsymb=sampsymb))
} else {
symblabels <- unique(symbgroup)
if(groupsort) symblabels <- sort(symblabels,na.last=TRUE)
nsymb <- length(symblabels)
if(length(symbset) < nsymb) symbset <- union(symbset,1:nsymb)[1:nsymb] # augment with unused from 1,2, ...
sampsymb <- symbset[match(symbgroup,symblabels)]
sampsymb[is.na(sampsymb)] <- 1 # make sure no NAs
outlist <- c(outlist,list(symblabels = symblabels, symblist=symbset,sampsymb=sampsymb))
if(!is.null(symb.name)) outlist <- c(outlist,symb.name=symb.name)
}
}
outlist
}
changecol <- function(colobject,colposition,newcolour) {# provide new colours to colourby object
if(length(colposition)>0) {
if(length(colposition) != length(newcolour)) stop("Error: colposition and newcolour are different lengths")
oldcolour <- colobject$collist
colobject$collist[colposition] <- newcolour
colobject$sampcol <- colobject$collist[match(colobject$sampcol,oldcolour)]
}
colobject
}
# fade (Lumley+)
fade <- function(colors,alpha) {
if(alpha <= 1) alpha <- alpha*255
rgbcols <- col2rgb(colors)
rgb(rgbcols[1,],rgbcols[2,],rgbcols[3,],alpha,max=255)
}
# fadeco fade a colour object (based on Lumley's fade)
fadeco <- function(colobject,alpha) {
colobject$collist <- fade(colobject$collist, alpha)
colobject$sampcol <- fade(colobject$sampcol, alpha)
colobject
}
coloursub <- function(colobj, indsubset) {
#subset a colour object