-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsos_functions.R
1896 lines (1598 loc) · 68.9 KB
/
sos_functions.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
read.meta.data.full.analyses.df <- function (dart_data, basedir, species, dataset,
nas = "-")
{ #this function keeps lat, long, site, annd samples in the dms$meta$analyses df
metafile <- paste(basedir, species, "/meta/", species, "_",
dataset, "_meta.xlsx", sep = "")
if (file.exists(metafile)) {
cat("\n")
cat(" Reading data file:", metafile, "\n")
}
else {
cat(" Fatal Error: the metadata file", metafile, "does not exist \n")
stop()
}
m <- read.xlsx(metafile, sheet = 1, colNames = TRUE)
if (any(names(m) == "sample") & any(names(m) == "lat") &
any(names(m) == "long")) {
cat(" Found sample, lat and long columns in metadata \n")
}
else {
cat(" Fatal Error: did not find important sample, lat or long column in metadata \n")
stop()
}
dart_samples <- dart_data$sample_names
mm <- match(dart_samples, m$sample)
mi <- intersect(m$sample, dart_samples)
mm_real <- which(m$sample %in% mi)
num_dart_samples <- nrow(dart_data$gt)
num_meta_samples <- nrow(m)
num_match_samples <- length(mm_real)
if (num_match_samples > 1) {
cat(" Found metadata for ", num_meta_samples, " samples \n")
cat(" This includes overlap with ", num_match_samples,
" samples \n")
cat(" out of ", num_dart_samples, "in DArT genotypes \n")
}
else {
cat(" Fatal Error: no matching sample information between meta-data and DArT genotypes \n")
stop()
}
missing_in_meta <- rownames(dart_data$gt)[is.na(m$sample[mm])]
meta_ordered <- m[mm_real, ]
sample_names <- as.character(meta_ordered$sample)
site <- as.character(meta_ordered$site)
lat <- as.numeric(meta_ordered$lat)
long <- as.numeric(meta_ordered$long)
cat(" Adding analysis fields to meta data list \n")
an <- meta_ordered[, 1:(ncol(meta_ordered))]
# an <- an[, -which(names(an) %in% c("sample", "site", "lat", "long"))]
analyses <- as.matrix(an)
analyses <- apply(analyses, c(1, 2), trimws)
meta_data <- list(sample_names = sample_names, site = site,
lat = lat, long = long, analyses = analyses)
return(meta_data)
}
read.meta.data.new <- function (dart_data, basedir, species, dataset,
nas = "-")
{
metafile <- paste(basedir, species, "/meta/", species, "_",
dataset, "_meta.xlsx", sep = "")
if (file.exists(metafile)) {
cat("\n")
cat(" Reading data file:", metafile, "\n")
}
else {
cat(" Fatal Error: the metadata file", metafile, "does not exist \n")
stop()
}
m <- read.xlsx(metafile, sheet = 1, colNames = TRUE)
if (any(names(m) == "sample") & any(names(m) == "lat") &
any(names(m) == "long")) {
cat(" Found sample, lat and long columns in metadata \n")
}
else {
cat(" Fatal Error: did not find important sample, lat or long column in metadata \n")
stop()
}
dart_samples <- dart_data$sample_names
mm <- match(dart_samples, m$sample)
mi <- intersect(m$sample, dart_samples)
mm_real <- which(m$sample %in% mi)
num_dart_samples <- nrow(dart_data$gt)
num_meta_samples <- nrow(m)
num_match_samples <- length(mm_real)
if (num_match_samples > 1) {
cat(" Found metadata for ", num_meta_samples, " samples \n")
cat(" This includes overlap with ", num_match_samples,
" samples \n")
cat(" out of ", num_dart_samples, "in DArT genotypes \n")
}
else {
cat(" Fatal Error: no matching sample information between meta-data and DArT genotypes \n")
stop()
}
missing_in_meta <- rownames(dart_data$gt)[is.na(m$sample[mm])]
meta_ordered <- m[mm_real, ]
sample_names <- as.character(meta_ordered$sample)
site <- as.character(meta_ordered$site)
lat <- as.numeric(meta_ordered$lat)
long <- as.numeric(meta_ordered$long)
cat(" Adding analysis fields to meta data list \n")
an <- meta_ordered[, 1:(ncol(meta_ordered))]
an <- an[, -which(names(an) %in% c("sample", "site", "lat", "long"))]
analyses <- as.matrix(an)
meta_data <- list(sample_names = sample_names, site = site,
lat = lat, long = long, analyses = analyses)
return(meta_data)
}
classifier_function <- function(qdf, plateau){
qdf$dominant_pop <- colnames(qdf[,(2:(plateau+1))])[apply(qdf[,(2:(plateau+1))],1,which.max)]
qdf$dom_pop_proportion <- apply(qdf[,(2:(plateau+1))],1,max)
return(qdf)
}
metadata.read <- function(species){ # read in metadata exported from rnr database
meta <- fread(paste(species, "/meta/",species,"_meta.csv", sep=""))
meta1 <- meta %>% select_if(~!all(is.na(.))) # remove columns of all NA
colnames(meta1)[colnames(meta1) == 'NSWnumber'] <- 'sample'
colnames(meta1)[colnames(meta1) == 'decimalLatitude'] <- 'lat'
colnames(meta1)[colnames(meta1) == 'decimalLongitude'] <- 'long'
colnames(meta1)[colnames(meta1) == 'locality'] <- 'site'
###sample, site, lat, long, and then 2 analysis columns with any name..
return(meta1)
}
custom.read <- function(species, dataset){
file <- paste(species, "/meta/",species,"_", dataset, "_meta.xlsx", sep="")
custom <- read_excel(file,
col_names=TRUE, sheet=1)
return(custom)
}
#test
#used to remove samples with high missingness
remove.by.missingness <-function(dms_o, missingness){
dms <- dms_o
na_per_row <- rowSums(is.na(dms[["gt"]]))/ncol(dms[["gt"]])
high_missing <- which(na_per_row > missingness)
if(length(high_missing)==0){
print("There are no high missing samples")
return(dms_o)
} else{
sample_names <- names(high_missing)
names(high_missing) <- NULL
dms$gt <- dms$gt[-high_missing, ]
dms$sample_names <- dms$sample_names[-high_missing]
if("site" %in% names(dms$meta)){
dms$meta$site <- dms$meta$site[-high_missing]}
if("lat" %in% names(dms$meta)){
dms$meta$lat <- dms$meta$lat[-high_missing]}
if("long" %in% names(dms$meta)){
dms$meta$long <- dms$meta$long[-high_missing]}
if("sample_names" %in% names(dms$meta)){
dms$meta$sample_names <- dms$meta$sample_names[-high_missing]}
if("analyses" %in% names(dms$meta)){
dms$meta$analyses <- dms$meta$analyses[-high_missing,]}
return(dms)
if(isFALSE(unique(sample_names %in% rownames(dms$gt)))){
print("Samples have been successfully removed from dms$gt")}
else{stop("Huston, we have a problem (with dms$gt)")}
if(isFALSE(unique(sample_names %in% dms$sample_names))){
print("Samples have been successfully removed from dms$sample_names") }
else{stop("Huston, we have a problem (with dms$sample_names)")}
if(isTRUE(identical(rownames(dms[["gt"]]), dms$sample_names))){
print("Samples are in order")}
else(stop("Huston, we have a problem (these eggs scrambled)"))
paste(length(high_missing), "samples have been removed due missingness >", missingness)
return(dms)
}
}
dart.remove.samples <- remove.by.missingness
remove.by.meta <- function(dms, meta){
missing <- which(!(rownames(dms$gt) %in% meta$sample))
dms$gt <- dms$gt[-missing, ]
dms$sample_names <- dms$sample_names[-missing]
return(dms)}
remove.by.list <-function(dms, list){ # list of samples to keep
missing <- which(!(dms$sample_names %in% list))
if(length(missing)!=0){
cat(length(missing))
dms$gt <- dms$gt[-missing, ]
dms$sample_names <- dms$sample_names[-missing]
meta_names <- which(!names(dms$meta) %in% "analyses") # get the meta that re not called "analyses"
for(i in meta_names){
main_meta <- dms$meta[[i]]
dms$meta[[i]] <- main_meta[-missing]
}
dms$meta$analyses <- dms$meta$analyses[-missing,]
}
return(dms)}
remove.by.maf <- function(dms, maf){
ds <- dms$gt
keepers <- get_minor_allele_frequencies(ds)
dms$gt <- ds[,which(keepers>=maf)]
dms$locus_names <- dms$locus_names[which(keepers>=maf)]
dms$locus_repro <- dms$locus_repro[which(keepers>=maf)]
dms$locus_pos <- dms$locus_pos[which(keepers>=maf)]
dms$locus_nuc <- dms$locus_nuc[which(keepers>=maf)]
return(dms)
}
#continuous colour variable PCA
pca_grad_funct <- function(df, x, y, n1,n2, group, gn, colour1, colour2){
lat_p <- ggplot(df, aes(x={{x}}, y={{y}}, color={{group}}))+geom_point()+theme_bw()+
scale_colour_gradient(low = paste(colour1), high = paste(colour2), na.value="lightgrey")+
labs(color=paste(gn), x=pcnames[n1], y=pcnames[n2])+
theme(legend.position="bottom", legend.text = element_text(angle = 45, vjust = 0, hjust = 0.15))
return(lat_p)
}
#categorical colour variable PCA
pca_cat_funct <- function(df, x, y,n1,n2, group, gn){
plot <- ggplot({{df}}, aes(x={{x}}, y={{y}}, colour={{group}}))+
geom_point()+theme_bw()+
theme(legend.position="bottom")+
labs(color=paste(gn),x=pcnames[n1], y=pcnames[n2])
return(plot)
}
#continuous colour variable PCA
pca_grad_funct2 <- function(df, x, y, n1,n2, group, gn, colour1, colour2){
lat_p <- ggplot(df, aes(x={{x}}, y={{y}}, color={{group}}))+geom_point()+theme_bw()+
scale_colour_gradient(low = paste(colour1), high = paste(colour2), na.value="lightgrey")+
theme(legend.position="bottom", legend.text = element_text(angle = 45, vjust = 0, hjust = 0.15))
return(lat_p)
}
#categorical colour variable PCA
pca_cat_funct2 <- function(df, x, y,n1,n2, group, gn){
plot <- ggplot({{df}}, aes(x={{x}}, y={{y}}, colour={{group}}))+
geom_point()+theme_bw()+
theme(legend.position="bottom")
return(plot)
}
named_list_maker <- function(variables, palette, num){
var <- as.character(unique(na.omit(variables)))
getPalette2 <- colorRampPalette(brewer.pal(n={num}, paste({palette})))
colz <- getPalette2(length(var)) #get palette for bargraphs
names(colz) <- var
return(colz)
}
# where bs is basic stats and old is the variable to group by (in this case,)
bstat_summary <- function(bs, old){
Ho <- colMeans(bs$Ho) # A table with number of populations columns and number of loci rows– of observed heterozygosities
He <- colMeans(bs$Hs, na.rm=TRUE) # A table –with umber of populations columns and number of loci rows– of observed gene diversities (aka expected heterozygosity)
Fis <- colMeans(bs$Fis, na.rm=TRUE)
n1 <- as.data.frame(table(old)) # samples per site
n <- n1[,2]
out <- data.frame(Ho,He,Fis)
table <- cbind(out,n)
table$Site <- rownames(table)
rownames(table) <- NULL
table <- table[,c(5,1,2,3,4)]
return(table)
}
geo_heat_function <- function(matrix){
palette <- colorRamp2(c(0, max(matrix)), c("white", "#80B1D3"))
geo <- Heatmap(matrix, col=palette,
row_names_gp = gpar(fontsize = 8),
column_names_gp = gpar(fontsize = 8),
row_names_max_width = unit(15, "cm"),
border_gp = gpar(col = "black", lty = 1),
name="Distance (km)",
cluster_columns = FALSE,
cluster_rows=FALSE,
row_order=order(rownames(matrix)),
column_order=order(colnames(matrix))
)
return(geo)
}
gene_heat_function <- function(matrix, font){
gene_col <- colorRamp2(c(0,0.5,1), c("#8DD3C7", "white", "#FB8072"))
gene <- Heatmap(matrix, col=gene_col,
row_names_gp = gpar(fontsize = 8),
column_names_gp = gpar(fontsize = 8),
row_names_max_width = unit(15, "cm"),
border_gp = gpar(col = "black", lty = 1),
cluster_columns = FALSE,
cluster_rows=FALSE,
row_order=order(rownames(matrix)),
column_order=order(colnames(matrix)),
name="Pairwise Fst",
cell_fun = function(j, i, x, y, width, height, fill) {
grid.text(sprintf("%.3f", matrix[i, j]), x, y, gp = gpar(fontsize = font))})
}
geo_heat_function2 <- function(matrix, axistext){
palette <- colorRamp2(c(0, max(matrix)), c("white", "#80B1D3"))
geo <- Heatmap(matrix, col=palette,
row_names_gp = gpar(fontsize = {{axistext}}),
column_names_gp = gpar(fontsize = {{axistext}}),
row_names_max_width = unit(15, "cm"),
border_gp = gpar(col = "black", lty = 1),
name="Distance (km)",
cluster_columns = TRUE,
cluster_rows=TRUE
)
return(geo)
}
gene_heat_function2 <- function(matrix,geo,anno1, anno2, insidetext, axistext){
gene_col <- colorRamp2(c(0,0.5,1), c("#8DD3C7", "white", "#FB8072"))
gene <- Heatmap(matrix, bottom_annotation = anno1, right_annotation = anno2,
col=gene_col,
row_names_gp = gpar(fontsize = {{axistext}}),
column_names_gp = gpar(fontsize = {{axistext}}),
row_names_max_width = unit(15, "cm"),
border_gp = gpar(col = "black", lty = 1),
# cluster_columns = FALSE,
# cluster_rows=FALSE,
# row_order=order(rownames(matrix)),
column_order=column_order(geo),
name="Pairwise Fst",
cell_fun = function(j, i, x, y, width, height, fill) {
grid.text(sprintf("%.3f", matrix[i, j]), x, y, gp = gpar(fontsize = {{insidetext}}))})
}
admix_plotter <- function(data, splitby, textsize, textangle){
plot <- ggplot(data, aes(x=sample_names, y=Q, fill=population))+
geom_bar(position="stack", stat="identity")+
theme_few()+labs(y="Admixture\ncoefficient (Q)", x=element_blank(),
fill="Source\npopulation")+scale_fill_manual(values=colz)+
facet_grid(cols=vars({{splitby}}), scales = "free_x", space = "free_x")+
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1,
size=4), strip.text.x = element_text(size = 6))+
scale_y_continuous(limits = c(0,1.001), expand=c(0,0))+
theme(strip.text.x = element_text(angle = textangle, size=textsize), panel.spacing = unit(0.07, "lines"))
return(plot)
}
scatterpie_plot_function <- function(df, x, scale_fill, xlim, ylim, r){
plot <- ggplot(ozmaps::abs_ste) + geom_sf(fill="#f9f9f9", colour="grey") +
coord_sf(xlim = xlim, ylim = ylim) + labs(y=element_blank(), x=element_blank(), fill="Source\npopulation")+
geom_scatterpie(aes(x=long.y, y=lat.y, group =x, r = {r}),data =df,
cols=colnames(df)[3:(plateau+2)], alpha=1, size=0.01, colour="black")+#
theme_few()+theme(axis.text.x = element_text(angle=90) )+ scale_fill_manual(values=scale_fill)
return(plot)
}
map_plot_function <- function(df, colour, xlim, ylim, legend){
plot <- ggplot(ozmaps::abs_ste) + geom_sf(fill="#f9f9f9", colour="grey") +
coord_sf(xlim = xlim, ylim = ylim) +
labs(y=element_blank(), x=element_blank(), fill=legend)+
geom_point(data = df, mapping = aes(x = long, y = lat, fill={{colour}}),
colour="black",pch=21, size=2)+theme_few()+
theme(legend.key.size = unit(0, 'lines'), axis.text.x = element_text(angle=90),
legend.margin=margin(0,0,0,0), legend.box.margin=margin(-5,-5,-5,-5))+
guides(colour = guide_legend(title.position = "top", ncol=1))
return(plot)
}
map_plot_function2 <- function(df, colour, xlim, ylim, legend){
plot <- ggplot(ozmaps::abs_ste) + geom_sf(fill="#f9f9f9", colour="grey") +
coord_sf(xlim = xlim, ylim = ylim) +
labs(y=element_blank(), x=element_blank(), fill=legend)+
geom_point(data = df, mapping = aes(x = long.y, y = lat.y, fill={{colour}}),
colour="black",pch=21, size=2)+theme_few()+
theme(legend.key.size = unit(0, 'lines'), axis.text.x = element_text(angle=90),
legend.margin=margin(0,0,0,0), legend.box.margin=margin(-5,-5,-5,-5))+
guides(fill = guide_legend(title.position = "top", ncol=1))
return(plot)
}
new.read.dart.xls.onerow <- function (basedir, species, dataset, topskip, nmetavar, nas = "-",
altcount = TRUE, euchits = FALSE, misschar = "-", seq2fa = FALSE,
fnum = fnum)
{
require(readxl)
datafile <- paste(basedir, species, "/dart_raw/Report-",
dataset, ".xlsx", sep = "")
if (file.exists(datafile)) {
cat("\n")
cat(" Reading data file:", datafile, "\n")
x <- read_excel(datafile, sheet = 4, skip = topskip,
col_names = TRUE, na = nas)
if (any(colnames(x) == "AlleleID")) {
}
else {
cat(" Dataset does not include variable AlleleID... Check names... \n")
if (any(colnames(x) == "CloneID")) {
cat(" CloneID column found... proceeding with CloneID as names of loci. \n")
colnames(x)[colnames(x) == "CloneID"] <- "AlleleID"
}
else {
cat(" Locus names cannot be assigned. Error. \n")
stop()
}
}
if (any(names(x) == "RepAvg")) {
cat(" includes key variable RepAvg\n\n")
}
else {
cat(" Warning: Dataset does not include variable RepAvg! Check for errors\n\n")
stop()
}
NACloneID <- is.na(x$CloneID)
if (any(NACloneID)) {
num_NACloneID <- length(which(NACloneID))
cat(" Found ", num_NACloneID, " missing CloneID values. Removing from data. \n\n")
x <- x[-which(NACloneID), ]
}
else {
cat(" No missing CloneID values. \n\n")
}
if (!euchits) {
cat(" Ignoring information on DArT locus alignment to Eucalyptus genome \n\n")
}
else {
cat(" Saving information on DArT locus alignment to Eucalyptus genome \n")
aln_save_status <- save.eucalypt.genome.hits(x, basedir,
species, dataset)
}
locus_labels <- as.character(x$CloneID)
locus_names <- as.character(lapply(strsplit(as.matrix(locus_labels),
split = "[|]"), function(x) x[1]))
locus_repro <- as.numeric(x$RepAvg)
locus_calls <- as.numeric(x$CallRate)
locus_pos <- as.integer(x$SnpPosition)
locus_SNP <- as.character(x$SNP)
locus_nuc <- as.character(lapply(strsplit(as.matrix(locus_SNP),
split = "[:]"), function(x) x[2]))
num_snps <- nrow(x)
num_loci <- length(unique(locus_names))
num_cols <- ncol(x)
num_samp <- num_cols - nmetavar
cat(" Initial data scan -- \n")
cat(" Samples: ", num_samp, " \n")
cat(" SNPs: ", num_snps, " \n")
cat(" Loci: ", num_loci, " \n\n")
tgt <- x[, (nmetavar + 1):num_cols]
gt <- as.matrix(t(tgt))
sample_names <- colnames(x)[(nmetavar + 1):num_cols]
colnames(gt) <- as.vector(locus_labels)
cat(" Creating a DArT data list containing: \n")
cat(" Genotypes -- $gt \n")
cat(" Sample Names -- $sample_names \n")
cat(" Locus Names -- $locus_names \n")
cat(" Locus Reproducibility Scores -- $locus_repro \n")
cat(" Position of SNP in locus -- $locus_pos \n")
cat(" Data filtering treatments -- $treatment \n")
cat(" Position of SNP in locus -- $locus_pos \n")
cat(" Method of data encoding gt -- $encoding \n")
cat(" Nucleotides in this SNP -- $locus_nuc \n\n")
treatment <- "raw"
encoding <- "DArT"
dart_data <- list(gt = gt, sample_names = sample_names,
locus_names = locus_names, locus_repro = locus_repro,
locus_pos = locus_pos, locus_nuc = locus_nuc, encoding = encoding,
treatment = treatment)
if (altcount) {
dart_data <- encode.dart2altcount(dart_data)
}
else {
cat(" Warning: genotypes encoded in dart onerow format, 1=hom alt, 2=het \n\n")
}
return(dart_data)
}
else {
datafile <- paste(basedir, species, "/dart_raw/Report_",
dataset, "_SNP_mapping_2.csv", sep = "")
cat("\n")
cat(" Reading data file:", datafile, "\n")
x <- read.delim(datafile, sep = ",", na = "-", stringsAsFactors = FALSE,
header = FALSE)
rows_before_gt <- max(which(x[, 1] == "*"))
cols_before_gt <- max(which(x[1, ] == "*"))
colnames(x) <- x[rows_before_gt + 1, ]
x <- x[-(1:(rows_before_gt + 1)), ]
if (any(colnames(x) == "AlleleID")) {
}
else {
cat(" Dataset does not include variable AlleleID... Check names... \n")
if (any(colnames(x) == "CloneID")) {
cat(" CloneID column found... proceeding with CloneID as names of loci. \n")
colnames(x)[colnames(x) == "CloneID"] <- "AlleleID"
}
else {
cat(" Locus names cannot be assigned. Error. \n")
stop()
}
}
if (any(colnames(x) == "RepAvg")) {
}
else {
cat(" Dataset does not include variable RepAvg... Check names... \n")
stop()
}
NAID <- is.na(x$AlleleID)
if (any(NAID)) {
num_NAID <- length(which(NAID))
cat(" Found ", num_NAID, " missing AlleleID values. Removing from data. \n\n")
x <- x[-which(NAID), ]
}
if (!seq2fa) {
}
else {
cat(" Writing sequences to a fasta file \n")
seq_fname <- write_allele_seq_fasta(x, basedir, species,
dataset)
}
locus_labels <- as.character(x$AlleleID)
locus_names <- as.character(lapply(strsplit(as.matrix(locus_labels),
split = "[|]"), function(x) x[1]))
locus_repro <- as.numeric(x$RepAvg)
locus_calls <- as.numeric(x$CallRate)
locus_pos <- as.integer(x$SnpPosition)
locus_SNP <- as.character(x$SNP)
locus_nuc <- as.character(lapply(strsplit(as.matrix(locus_SNP),
split = "[:]"), function(x) x[2]))
num_snps <- nrow(x)
num_loci <- length(unique(locus_names))
num_cols <- ncol(x)
num_samp <- num_cols - cols_before_gt
cat(" Initial data scan -- \n")
cat(" Samples: ", num_samp, " \n")
cat(" SNPs: ", num_snps, " \n")
cat(" Loci: ", num_loci, " \n\n")
tgt <- x[, (cols_before_gt + 1):num_cols]
gt <- as.matrix(t(tgt))
class(gt) <- "numeric"
sample_names <- colnames(x)[(cols_before_gt + 1):num_cols]
colnames(gt) <- as.vector(locus_labels)
cat(" Creating a DArT data list containing: \n")
cat(" Genotypes -- $gt \n")
cat(" Sample Names -- $sample_names \n")
cat(" Locus Names -- $locus_names \n")
cat(" Locus Reproducibility Scores -- $locus_repro \n")
cat(" Position of SNP in locus -- $locus_pos \n")
cat(" Data filtering treatments -- $treatment \n")
cat(" Position of SNP in locus -- $locus_pos \n")
cat(" Method of data encoding gt -- $encoding \n")
cat(" Nucleotides in this SNP -- $locus_nuc \n\n")
treatment <- "raw"
encoding <- "DArT"
dart_data <- list(gt = gt, sample_names = sample_names,
locus_names = locus_names, locus_repro = locus_repro,
locus_pos = locus_pos, locus_nuc = locus_nuc, encoding = encoding,
treatment = treatment)
if (altcount) {
dart_data <- encode.dart2altcount(dart_data)
}
else {
cat(" Warning: genotypes encoded in dart onerow format, 1=hom alt, 2=het \n\n")
}
return(dart_data)
}
}
individual_kinship_by_pop <- function(dart_data, basedir, species, dataset, pop, maf=0.1, mis=0.2, as_bigmat=TRUE) {
require(SNPRelate)
popvec <- unique(pop)
kinlist <- list()
nsamp <- nrow(dart_data$gt)
igds_file <- dart2gds(dart_data, basedir, species, dataset)
igds <- snpgdsOpen(igds_file)
for (i in 1:length(popvec)) {
ipop <- popvec[i]
isamps <- which(pop == ipop)
iout <- snpgdsIBDMoM(igds, sample.id=rownames(dart_data$gt)[isamps] , maf=maf, missing.rate=mis, num.thread=1, kinship=TRUE)
ikout <- iout$kinship
rownames(ikout) <- rownames(dart_data$gt)[isamps]
colnames(ikout) <- rownames(dart_data$gt)[isamps]
kinlist[[ ipop ]] <- ikout
}
snpgdsClose(igds)
if (as_bigmat) {
bigmat <- matrix( rep(0, nsamp*nsamp ), nrow=nsamp )
rownames(bigmat) <- rep("", nrow(bigmat))
colnames(bigmat) <- rep("", nrow(bigmat))
istart <- 1
for (i in 1:length(kinlist)) {
im <- kinlist[[i]]
iN <- nrow(im)
if (istart == 1) {
istop = iN
} else {
istop = istop + iN
}
cat(istart, istop, "\n")
bigmat[istart:istop, istart:istop] <- im
rownames(bigmat)[istart:istop] <- rownames(im)
colnames(bigmat)[istart:istop] <- rownames(im)
istart = istart + iN
}
return(bigmat)
} else {
return(kinlist)
}
}
dart2newhy <- function(dart_data, basedir, species, dataset,meta=NULL) {
if (dart_data$encoding == "altcount") {
cat(" Dart data object for ", dataset, "in species", species, "\n")
cat(" Dart data object found with altcount genotype encoding. Commencing conversion to lfmm. \n")
nh_gt <- dart_data$gt
} else {
cat(" Fatal Error: The dart data object does not appear to have altcount genotype encoding. \n"); stop()
}
if (is.null(meta)) {
cat(" Meta data file not specified \n")
} else {
cat("Meta info included in samples file \n")
meta=meta
}
nh_gt[ nh_gt == 0 ] <- 11
nh_gt[ nh_gt == 1 ] <- 12
nh_gt[ nh_gt == 2 ] <- 22
nh_gt[ is.na(nh_gt) ] <- 0
treatment <- dart_data$treatment
dir <- paste(basedir, species, "/popgen",sep="")
if(!dir.exists(dir)) {
cat(" Directory: ", dir, " does not exist and is being created. \n")
dir.create(dir)
} else {
cat(" Directory: ", dir, " already exists... content might be overwritten. \n")
}
dir <- paste(basedir, species, "/popgen/",treatment,sep="")
if(!dir.exists(dir)) {
cat(" Directory: ", dir, " does not exist and is being created. \n")
dir.create(dir)
} else {
cat(" Directory: ", dir, " already exists... \n")
}
nh_dir <- paste(RandRbase,species,"/popgen/",treatment,"/newhy", sep="")
if(!dir.exists(nh_dir)) {
cat(" NewHybrids directory: ", nh_dir, " does not exist and is being created. \n")
dir.create(nh_dir)
} else {
cat(" NewHybrids directory: ", nh_dir, " already exists, content will be overwritten. \n")
}
nh_gt_file <- paste(nh_dir,"/",species,"_",dataset,".txt",sep="")
nh_H_file <- paste(nh_dir,"/",species,"_",dataset,"_header.txt",sep="")
nh_S_file <- paste(nh_dir,"/",species,"_",dataset,"_samples.txt",sep="")
nh_L_file <- paste(nh_dir,"/",species,"_",dataset,"_loci.txt",sep="")
nS <- nrow(nh_gt); vS <- 1:nS; mS <- cbind(vS,rownames(nh_gt), meta)
nL <- ncol(nh_gt); vL <- paste("L", 1:nL, sep=""); mL <- cbind(vL, colnames(nh_gt))
write.table(mS, file=nh_S_file, sep=",",quote=FALSE, row.names = FALSE, col.names = FALSE)
write.table(mL, file=nh_L_file, sep=" ",quote=FALSE, row.names = FALSE, col.names = FALSE)
sink(nh_gt_file)
cat(c("NumIndivs ", nS, "\n"))
cat(c("NumLoci ", nL, " \n"))
cat(c("Digits 1\n"))
cat(c("Format Lumped \n\n"))
sink()
write(c("LocusNames", vL), ncolumns=(nL+1), file=nh_gt_file, sep=" ", append=TRUE)
sink(nh_gt_file, append = TRUE); cat(c("\n")); sink()
write.table(cbind(vS, nh_gt), file=nh_gt_file, sep=" ",quote=FALSE, row.names = FALSE, col.names = FALSE, append=TRUE)
return(nh_dir)
}
common_allele_count <- function(gt, w=NULL, cthresh=1) {
# estimate allele frequencies
if (is.null(w)) {
alt_counts <- colSums(gt)
ref_counts <- colSums(2-gt)
} else {
if(nrow(gt) == length(w)) {
#makes a matrix the same size as gt with 0 and 1 where every column is w vector
wm <- matrix(rep(w,ncol(gt)),ncol=ncol(gt),byrow=FALSE)
alt_counts <- colSums(gt*wm) #alternative allele counts for samples where w=1
ref_counts <- colSums((2-gt)*wm) # main allele counts where w=1
} else {
cat(" weights supplied: must have length equal to number of rows in gt \n")
}
}
min_counts <- alt_counts #minor allele count is alt count
for ( i in 1:ncol(gt) ) {
if ( isTRUE(alt_counts[i] > ref_counts[i])) {
min_counts[i] <- ref_counts[i] #if ref allele count is less than alt count, alt is minor allele
}
}
minor_allele_counts <- min_counts
number_common_alleles <- length(which( min_counts >= cthresh ))
return( list(number_common_alleles=number_common_alleles, minor_allele_counts=minor_allele_counts) )
}
opt_calculator <- function(gt, group_df,N_t_vec){ # input is hirsuta+abgma gt and cluster df
groups <- unique(group_df$"cluster")
out <- vector()
cat(groups)
for(i in 1:length(groups)){
#get the names of the samples in the current group being analysed
names <- as.vector(group_df[group_df$"cluster"==groups[i], "sample_names"])
main_gt2 <- gt[which(rownames(gt) %in% names),] #cut the gt matrix down to only have samples from the group
max_wts <- rep(2, nrow(main_gt2))
solutions <- bigger_optimisation(N_t_vec, main_gt2, max_wts)
out <- c(out, list(solutions))
}
names(out) <- groups
return(out)
}
# opt_calculator <- function(gt, group_df){ # input is hirsuta+abgma gt and cluster df
# groups <- unique(group_df$"cluster")
# out <- vector()
# for(i in 1:length(groups)){
# #get the names of the samples in the current group being analysed
# names <- as.vector(group_df[group_df$"cluster"==groups[i], "sample_names"])
# main_gt2 <- gt[which(rownames(gt) %in% names),] #cut the gt matrix down to only have samples from the group
# max_wts <- rep(2, nrow(main_gt2))
# out_list <- list()
# if( nrow(main_gt2)<20){
# N_t_vec <- c(5,10, nrow(main_gt2))
# }else{
# N_t_vec <- c(20, nrow(main_gt2))
# }
#
# for ( i in 1:length(N_t_vec) ) {
#
# N_t <- N_t_vec[i]
# cat("\n Running ", N_t, " ...\n")
#
# initial_weights = rep(0, nrow(main_gt2))
# initial_weights[sample(c(1:nrow(main_gt2)))[1:N_t]] <- 1
# out_list[[ i ]] <- run_optimization_set(main_gt2, N_t, max_wts, initial_weights)
#
# }
#
# solutions <- out_list[[1]]$nei_opt$weight[num_steps,]
# for (i in 2:length(N_t_vec)) {
# solutions <- cbind(solutions, out_list[[i]]$nei_opt$weight[num_steps,])
# }
#
# colnames(solutions) <- as.character(N_t_vec)
# solutions <- as.data.frame(solutions)
# solutions$Sample <- rownames(main_gt2)
#
# out <- c(out, list(solutions))
#
# }
# names(out) <- groups
# return(out)
# }
dif_function <- function(x,y){
present <- sum(x==2 & y==2)
all <- sum(y==2)
out <- present/all
return(out)
}
allele_sum <- function(x, min){
c_al_sum <- sum(x != 2, na.rm=TRUE)
prop <- c_al_sum/length(x)
if(prop<(1-min) & prop >min){
out <- 2 # has both alleles
} else{
out <- 1 # has one allele
}
return(out)
}
prop_calculator <- function(major_gt, min1, minor_gt, min2, group_df){
groups <- unique(group_df$"cluster")
out <- vector()
for(i in 1:length(groups)){
#get the names of the samples in the current group being analysed
names <- as.vector(group_df[group_df$"cluster"==groups[i], "sample_names"])
main_gt2 <- major_gt[which(rownames(major_gt) %in% names),] #cut the gt matrix down to only have samples from the group
minor_gt2 <- minor_gt[which(rownames(minor_gt) %in% names),]
# proportion of the total minor alleles present in the major population that are present in the minor population
maj_acount <- apply(main_gt2, 2, allele_sum, min1)
min_acount <- apply(minor_gt2, 2, allele_sum, min2)
prop <- dif_function(min_acount, maj_acount)
out <- c(out, prop)
names(out)[i] <- groups[i]
}
return(out)
}
bigger_optimisation <- function(N_t_vec, gt, max_wts){
out_list <- list()
gt2 <- gt
if(nrow(gt2)==0){stop("GT is empty")}
else{
multi <- floor(max(N_t_vec)/nrow(gt2))
if(multi>10){
solutions2 <- cat("Requested population is more than 10x the size of source")
}else{
if(multi>0){
for(i in 1:multi){
gt2 <- rbind(gt2, gt2) # make the df bigger
}
}
for ( i in 1:length(N_t_vec) ) {
N_t <- N_t_vec[i]
cat("\n Running ", N_t, " ...\n")
initial_weights = rep(0, nrow(gt2))
initial_weights = rep(0, nrow(gt2))
initial_weights[sample(c(1:nrow(gt2)))[1:N_t]] <- 1 #randomly makes n_t number of them equal to 1
out_list[[ i ]] <- run_optimization_set(gt2, N_t, max_wts, initial_weights)
plot(out_list[[i]]$nei_opt$value, main = paste("max_T=",max_t))
}
solutions <- out_list[[1]]$nei_opt$weight[num_steps,]
for (i in 2:length(N_t_vec)) {
solutions <- cbind(solutions, out_list[[i]]$nei_opt$weight[num_steps,])
}
colnames(solutions) <- paste0("n",as.character(N_t_vec))
solutions <- as.data.frame(solutions)
solutions$Sample <- rownames(gt)
solutions2 <- aggregate(.~Sample, data=solutions, sum)
}
return(solutions2)
}}
#for the venn diagram alleles
get_minor_allele_frequencies <- function( gt ) {
alleles <- 2*(colSums(!is.na(gt))) # total number of alleles for a locus (all samples in gt)
alt_freq <- colSums(gt,na.rm=TRUE) / (alleles) # get the allele frequencies (altcount data can be summed because 0=homo1, 1=het, 2=homo2)
ref_freq <- 1-alt_freq # get the alternative allele frequency
min_freq <- alt_freq
for ( i in 1:ncol(gt) ) { # assign the minor allele to smaller value
if ( isTRUE(alt_freq[i] > ref_freq[i] )) {
min_freq[i] <- ref_freq[i]
}
}
return(min_freq) # return minor allele frequency for each locus in gt
}
# filter <- function(x){ # find maf BAD
# if (length(which(!is.na(x)))==0){ # if everything is NA, MAF= 0
# maf <- 0
# }else{
# a2_freq <- sum(x, na.rm = TRUE)/(length(which(!is.na(x)))*2) # data is altcount where homo2=0 heter0=1, homo2=2, so allele2 count is sum
# a1_freq <- 1-a2_freq #allele 1 frequency
# if(a1_freq<a2_freq){ #choose the smaller allele frequency
# maf <- a1_freq
# }else{
# maf<- a2_freq
# }
# }
# return(maf)
# }
single_site_genepop_basicstats <- function(dms, min, group){
# This function makes the genepop file for a dms with a single group (eg one species from one site),
# and then runs basicstats on that genepop. It removes loci where MAF is < min specified in the input.
# Also, loci should be filtered by missingness using `remove.poor.quality.snps(dms, min_repro=0.96,max_missing=0.3)` before usage.
# This method is based on Jasons dart2genepop but is suitable for single group datasets.
ds <- dms$gt
keepers <- get_minor_allele_frequencies(ds)
ds <- ds[,which(keepers>=min)]
cat(paste(ncol(ds))," loci are being used\n")
if (ncol(ds) >=10){
# make into genepop format
old <- c("0","1","2", NA)
new <- c("0101","0102","0202","0000")
ds[ds %in% old] <- new[match(ds, old, nomatch = 0000)]
# write genepop file
gf <- paste0(species, "/popgen/genepop_",group,".gen")
cat(paste0("genepop file: ",species, " with MAF ", paste0(min)),
file=gf,sep="\n")
cat(colnames(ds),file=gf,sep="\n", append=TRUE)
cat("pop",file=gf,sep="\n", append=TRUE)
for (i in 1:nrow(ds)){
cat(c("pop1,", ds[i,], "\n"),file=gf,sep="\t", append=TRUE)
}
cat("pop",file=gf,sep="\n", append=TRUE)
for (i in 1:2){
cat(c("pop2,", ds[i,], "\n"),file=gf,sep="\t", append=TRUE)
}
# do basic stats
bs <- diveRsity::basicStats(infile = gf, outfile = NULL,
fis_ci = FALSE, ar_ci = TRUE,
ar_boots = 1000,
rarefaction = FALSE, ar_alpha = 0.05)
# return(bs)
# extract the stats
npop <- 1
result <- as.data.frame(mat.or.vec(npop,11))
measurement_names <- rownames(bs$main_tab[[1]])
population_names <- names(bs$main_tab) #ls() rearranges the names
rownames(result) <- {{group}}
colnames(result) <- measurement_names
for (r in 1:npop) {
popstats <- bs$main_tab[[r]][,"overall"] ##extract from a list
result[r,] <- popstats}
result$loci <- ncol(ds)
return(result)
} else{
print(paste("WARNING: not enough loci for", group))
return(NULL)
}
}
multi_site_genepop_basicstats <- function(dms, min, group, grouping){
# This function makes the genepop file for a dms with multiple groups with low differentiation (eg one species from multiple sites).
# After creating the genepop file, this function runs basicstats. It removes loci where MAF is < min specified in the input for the
# entire set rather than per group.