forked from dmgatti/MUGA_reference_data
/
GigaMUGA_Reference_QC.Rmd
executable file
·791 lines (660 loc) · 37.7 KB
/
GigaMUGA_Reference_QC.Rmd
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
---
title: "Reference Data QC: GigaMUGA"
site: workflowr::wflow_site
output:
workflowr::wflow_html:
toc: true
toc_float: true
toc_collapsed: true
toc_depth: 3
code_folding: hide
editor_options:
chunk_output_type: console
---
# GigaMUGA Annotations
```{r setup, echo=FALSE, include=FALSE}
knitr::opts_chunk$set(message = FALSE)
# require(tidyverse)
# ^ this if running locally
require(fst)
require(dplyr)
require(tidyr)
require(stringr)
require(parallel)
# ^ these if running on sumner
require(data.table)
require(purrr)
require(furrr)
require(qtl2)
require(magrittr)
require(DT)
require(plotly)
require(progress)
require(ape)
require(RColorBrewer)
require(tictoc)
require(furrr)
require(vroom)
today <- format(Sys.Date(), format="%Y%m%d")
QCtheme <- theme_bw() +
theme(panel.grid = element_blank(),
axis.text = element_text(colour = "black"),
axis.title = element_text(colour = "black"))
###########################################
# Functions to aid in pulling in QC'd genotypes to be written in last chunk
###########################################
writeReferenceGenotypes <- function(founder_file, nonfounder_file){
if(file.exists(paste0("data/GigaMUGA/",founder_file))){
founder_sample_genos <- fst::read.fst(paste0("data/GigaMUGA/GigaMUGA_founder_sample_genotypes/",founder_file)) %>%
dplyr::filter(!marker %in% above.cutoff$marker) # should be clean, but just in case
non_founder_sample_genos <- fst::read.fst(paste0("data/GigaMUGA/GigaMUGA_reference_genotypes/",nonfounder_file)) %>%
dplyr::filter(!sample_id %in% colnames(founder_sample_genos)[-1],
!sample_id %in% bad_samples$sample_id,
!marker %in% above.cutoff$marker) %>%
dplyr::select(sample_id, marker, genotype) %>%
dplyr::mutate(genotype = dplyr::if_else(genotype == "-", true = "N", false = genotype)) %>%
tidyr::pivot_wider(names_from = sample_id, values_from = genotype)
reference_sample_genos <- founder_sample_genos %>%
dplyr::left_join(., non_founder_sample_genos)
reference_sample_genos[is.na(reference_sample_genos)] <- "N"
return(reference_sample_genos)
} else if(founder_file %in% c("M","Y")){
non_founder_sample_genos_int <- fst::read.fst(paste0("data/GigaMUGA/GigaMUGA_reference_genotypes/",nonfounder_file))
if(founder_file == "M"){
M_markers <- read.csv("output/GigaMUGA/GigaMUGA_founder_consensus_genotypes_chrM.csv") %>%
dplyr::select(marker)
M_markers <- M_markers$marker
reference_sample_genos <- non_founder_sample_genos_int %>%
dplyr::filter(marker %in% M_markers) %>%
dplyr::select(sample_id, marker, genotype) %>%
dplyr::mutate(genotype = dplyr::if_else(genotype == "-", true = "N", false = genotype)) %>%
tidyr::pivot_wider(names_from = sample_id, values_from = genotype)
} else {
Y_markers <- read.csv("output/GigaMUGA/GigaMUGA_founder_consensus_genotypes_chrY.csv") %>%
dplyr::select(marker)
Y_markers <- Y_markers$marker
reference_sample_genos <- non_founder_sample_genos_int %>%
dplyr::filter(marker %in% Y_markers) %>%
dplyr::select(sample_id, marker, genotype) %>%
dplyr::mutate(genotype = dplyr::if_else(genotype == "-", true = "N", false = genotype)) %>%
tidyr::pivot_wider(names_from = sample_id, values_from = genotype)
}
return(reference_sample_genos)
} else {
non_founder_sample_genos_int <- fst::read.fst(paste0("data/GigaMUGA/GigaMUGA_reference_genotypes/",nonfounder_file)) %>%
dplyr::filter(!sample_id %in% bad_samples$sample_id,
!marker %in% above.cutoff$marker) %>%
dplyr::select(sample_id, marker, genotype)
if(nrow(non_founder_sample_genos_int) > 0){
non_founder_sample_genos <- non_founder_sample_genos_int %>%
dplyr::mutate(genotype = dplyr::if_else(genotype == "-", true = "N", false = genotype)) %>%
tidyr::pivot_wider(names_from = sample_id, values_from = genotype)
reference_sample_genos <- non_founder_sample_genos
reference_sample_genos[is.na(reference_sample_genos)] <- "N"
return(reference_sample_genos)
} else {
print("NO REFERENCE GENOTYPES")
}
}
}
writeFounderConsensusGenotypes <- function(founder_file){
founder_consensus_genos <- read.csv(paste0("data/GigaMUGA/GigaMUGA_founder_consensus_genotypes/",founder_file))
rownames(founder_consensus_genos) <- NULL
colnames(founder_consensus_genos) <- c("marker",
"A/J","C57BL/6J","129S1/SvImJ","NOD/ShiLtJ",
"NZO/HILtJ","CAST/EiJ","PWK/PhJ","WSB/EiJ")
founder_consensus_genos %<>%
dplyr::filter(!marker %in% above.cutoff$marker)
return(founder_consensus_genos)
}
writeReferenceIntensities <- function(nonfounder_file){
chr <- strsplit(strsplit(nonfounder_file,"_")[[1]][[4]],"[.]")[[1]][[1]]
if(chr %in% c("M","Y")){
reference_sample_intensities <- fst::read.fst(paste0("data/GigaMUGA/GigaMUGA_reference_genotypes/",nonfounder_file)) %>%
dplyr::select(sample_id, marker, X, Y)
if(chr == "M"){
M_markers <- read.csv("output/GigaMUGA/GigaMUGA_founder_consensus_genotypes_chrM.csv") %>%
dplyr::select(marker)
M_markers <- M_markers$marker
reference_x_intensities <- reference_sample_intensities %>%
dplyr::filter(marker %in% M_markers) %>%
dplyr::select(-Y) %>%
tidyr::pivot_wider(names_from = sample_id, values_from = X)
reference_y_intensities <- reference_sample_intensities %>%
dplyr::filter(marker %in% M_markers) %>%
dplyr::select(-X) %>%
tidyr::pivot_wider(names_from = sample_id, values_from = Y)
} else {
Y_markers <- read.csv("output/GigaMUGA/GigaMUGA_founder_consensus_genotypes_chrY.csv") %>%
dplyr::select(marker)
Y_markers <- Y_markers$marker
reference_x_intensities <- reference_sample_intensities %>%
dplyr::filter(marker %in% Y_markers) %>%
dplyr::select(-Y) %>%
tidyr::pivot_wider(names_from = sample_id, values_from = X)
reference_y_intensities <- reference_sample_intensities %>%
dplyr::filter(marker %in% Y_markers) %>%
dplyr::select(-X) %>%
tidyr::pivot_wider(names_from = sample_id, values_from = Y)
}
} else {
reference_sample_intensities <- fst::read.fst(paste0("data/GigaMUGA/GigaMUGA_reference_genotypes/",nonfounder_file)) %>%
dplyr::filter(!sample_id %in% bad_samples$sample_id,
!marker %in% above.cutoff$marker) %>%
dplyr::select(sample_id, marker, X, Y)
reference_x_intensities <- reference_sample_intensities %>%
dplyr::select(-Y) %>%
tidyr::pivot_wider(names_from = sample_id, values_from = X)
reference_y_intensities <- reference_sample_intensities %>%
dplyr::select(-X) %>%
tidyr::pivot_wider(names_from = sample_id, values_from = Y)
}
if(nrow(reference_x_intensities) == 0){
print("NO REFERENCE INTENSITIES")
} else {
return(list(reference_x_intensities, reference_y_intensities))
}
}
###########################################
# Function to quickly pull strain names from non-founder samples
# Inputs:
# Sample IDs
# Outputs:
# Character vector of strains
###########################################
findStrain <- function(x){
# Decompose strain from mouse ID for males
m_strains <- strsplit(x, split = "m")[[1]]
# If the string was actually split using "m" the sample was male
if(TRUE %in% str_detect(m_strains, pattern = "X12")){
# If there was a 129 or similar mouse with an m in the strain name, some collapsing needs to occur
X129_strains <- paste(strsplit(x, split = "m")[[1]][[1]], sep = "m", collapse = "m")
return(X129_strains)
} else if(length(m_strains) == 1){
f_strains <- strsplit(x, split = "f")[[1]][[1]]
return(f_strains)
} else {
return(m_strains[[1]][[1]])
}
}
```
## Loading in data from Sumner analyses
```{r}
load("data/GigaMUGA/GigaMUGA_QC_Results.RData")
load("data/GigaMUGA/GigaMUGA_SexCheck_Results.RData")
load("data/GigaMUGA/GigaMUGA_BadSamples_BadMarkers.RData")
gm_metadata <- vroom::vroom("data/GigaMUGA/gm_uwisc_v2.csv")
```
## Marker QC: Searching for missing genotype calls
```{r Markers with high "N" counts among reference samples}
no.calls <- control_allele_freqs_df %>%
dplyr::ungroup() %>%
dplyr::filter(genotype == "N") %>%
tidyr::pivot_wider(names_from = genotype,
values_from = n) %>%
dplyr::left_join(., gm_metadata) %>%
dplyr::select(marker, chr, bp_grcm39, freq) %>%
dplyr::mutate(chr = as.factor(chr))
## Identifying markers with missing genotypes at a frequency higher than the 95th percentile of "N" frequencies across all markers
cutoff <- quantile(no.calls$freq, probs = seq(0,1,0.05))[[19]]
```
Of `r length(unique(as.factor(control_allele_freqs_df$marker)))` markers, `r nrow(no.calls)` failed to genotype at least one sample, and `r nrow(above.cutoff)` markers failed to genotype at least `r cutoff*100`% of samples.
```{r Plotting no calls, echo=FALSE}
# Distribution of N frequencies across all markers. Dotted line indicates the 95th percentile of N frequencies (cutoff).
ggplot(no.calls, mapping = aes(x = freq)) +
geom_histogram(bins = 100) +
scale_x_continuous(breaks = seq(0,1,0.1)) +
geom_vline(xintercept = cutoff, linetype = 2) +
QCtheme +
labs(x = "Fraction of mice with missing genotypes",
y = "Number of markers")
```
## Sample QC
### Searching for samples with poor marker representation
In a similar fashion, we calculated the number of reference samples with missing genotypes. Repeated observations of samples/strains with identical names meant that genotype counts for each marker among them couldn't be grouped and tallied, so determining no-call frequency occurred column-wise. Mouse over individual samples to see the number of markers with missing genotypes for each sample.
```{r Reference samples with high missingness}
## Interactive plot of the number of missing genotypes for each sample.
bad_sample_cutoff <- quantile(n.calls.strains.df$n.no.calls, probs = seq(0,1,0.05))[20]
sampleQC <- ggplot(n.calls.strains.df,
mapping = aes(x = reorder(sample_id,n.no.calls),
y = n.no.calls,
text = paste("Sample:", sample_id))) +
geom_point() +
QCtheme +
theme(axis.text.x = element_blank(),
axis.ticks.x = element_blank()) +
geom_hline(yintercept = bad_sample_cutoff, linetype = 2) +
labs(x = "Number of mice with missing genotypes",
y = "Number of markers")
ggplotly(sampleQC, tooltip = c("text","y"))
```
### Validating sex of reference samples
We next validated the sexes of each sample using sex chromosome probe intensities. We paired up probe intensities, joined available metadata, and filtered down to only markers covering the X and Y chromosomes. Then we flagged markers with high missingness across all samples, as well as samples with high missingness among all markers.The first round of inferring predicted sexes used a rough search of the sample name for expected nomenclature convention, which includes a sex denotation.
```{r Preliminary sex prediction}
## Tabulating the number of samples for each predicted sex
predicted.sex.table <- predicted.sexes %>%
dplyr::group_by(predicted.sex) %>%
dplyr::count()
```
This captured `r predicted.sex.table[which(predicted.sex.table$predicted.sex == "f"),2]$n` female samples, `r predicted.sex.table[which(predicted.sex.table$predicted.sex == "m"),2]$n` male samples, leaving `r predicted.sex.table[which(predicted.sex.table$predicted.sex == "unknown"),2]$n` samples of unknown predicted sex from nomenclature alone.
```{r Predicted sex table, eval=FALSE, include=FALSE}
# Table of samples for which sex could not be predicted from sample name alone. Using one marker is fine as an example as the sample info for each marker is identical.
predicted.sexes %>%
dplyr::filter(predicted.sex == "unknown")
```
After predicting the sexes of the vast majority of reference samples, we visualized the average probe intensity among X Chromosome markers for each sample, labeling them by predicted sex. Samples colored black were unabled to have their sex inferred by the sample name, but cluster well with mice for which sex could be inferred. Conversely, some samples' predicted sex is discordant with X and Y Chromosome marker intensities (i.e. blue samples that cluster with mostly orange samples, and vice versa). Mouse over individual dots to view the sample, as well as whether it was flagged for having many markers with missing genotype information. In many cases, pulling substrings of sample names as the sex of the sample was too sensitive and misclassified samples.
```{r Predicted sex visualization}
predicted.sex.plot.palettes <- sex.chr.intensities %>%
dplyr::ungroup() %>%
dplyr::distinct(sample_id, predicted.sex, high_missing_sample) %>%
dplyr::mutate(predicted.sex.palette = dplyr::case_when(predicted.sex == "f" ~ "#5856b7",
predicted.sex == "m" ~ "#eeb868",
predicted.sex == "unknown" ~ "black"))
predicted.sex.palette <- predicted.sex.plot.palettes$predicted.sex.palette
names(predicted.sex.palette) <- predicted.sex.plot.palettes$predicted.sex
mean.x.intensities.by.sex.plot <- sex.chr.intensities %>%
dplyr::mutate(high_missing_sample = dplyr::if_else(high_missing_sample == "FLAG",
true = "Bad Samples",
false = "Good Samples")) %>%
ggplot(., mapping = aes(x = mean.x.chr.int,
y = mean.y.int,
colour = predicted.sex,
text = sample_id)) +
geom_point() +
scale_colour_manual(values = predicted.sex.palette) +
facet_grid(.~high_missing_sample) +
QCtheme
ggplotly(mean.x.intensities.by.sex.plot,
tooltip = c("text"))
```
Because the split between inferred sexes of good samples was so distinct, we used k-means clustering to quickly match the clusters to sexed samples and assign or re-assign sexes to samples with unknown or apparently incorrect sex information, respectively. Samples highlighted above were also re-evaluated using strain-specific marker information.
```{r kmeans clustering}
# Prints a table of all samples with an option to view whether a sample had its sex redesignated.
reSexed_samples_table <- reSexed_samples %>%
dplyr::mutate(resexed = predicted.sex != inferred.sex)
reSexed_samples_table %>%
dplyr::select(sample_id, resexed, predicted.sex, inferred.sex) %>%
DT::datatable(., filter = "top",
escape = FALSE)
```
The plot below demonstrates that this clustering technique does a pretty good job at capturing the information we want. Moving forward with sample QC we used the reassigned inferred sexes of the samples.
```{r kmeans plotting}
# Interactive scatter plot of intensities similar to above, but recolors and outlines samples based on redesignated sexes.
reSexed.plot <- ggplot(reSexed_samples_table %>%
dplyr::arrange(inferred.sex),
mapping = aes(x = mean.x.chr.int,
y = mean.y.int,
fill = inferred.sex,
colour = predicted.sex,
text = sample_id,
label = resexed)) +
geom_point(shape = 21,size = 3, alpha = 0.7) +
scale_colour_manual(values = predicted.sex.palette) +
scale_fill_manual(values = predicted.sex.palette) +
QCtheme
ggplotly(reSexed.plot,
tooltip = c("text","label"))
```
Visualizing the corrected sex assignments, we can see two samples that stand out of the clusters: FAM and JAXMP_cookii_TH_BC19281. Because the X and Y probe intensities were supplied to k-means clustering independently in this datasest and the values for each channel were intermediate in this sample, FAM was predicted as female using the y channel and male using the x channel data. Because FAM is not a CC/DO founder or a sample representative of non-musculus species, we assigned this sample to the "unknown" sex category. JAXMP_cookii_TH_BC19281 clustered with both sexes in a similar fashion, but because of genetic divergence between its genome and the mouse reference genome from which probes were designed, the irregular probe intensity data is not unexpected. For this reason, and the Y channel data being much more consistent with female sample, we categorized this sample as female.
### Validating reference sample genetic backgrounds
A key component of sample QC for our purposes is knowing that markers that we expect to deliver the consensus genotype (*i.e.* in a cross) actually provide us the correct strain information and allow us to correctly infer haplotypes.
```{r founder sample breakdown}
# Count up samples for each founder and resulting cross and display a table
# Dam names = row names; Sire name = column names
founder_sample_table <- founderSamples %>%
dplyr::group_by(dam,sire) %>%
dplyr::count() %>%
tidyr::pivot_wider(names_from = sire, values_from = n)
DT::datatable(founder_sample_table, escape = FALSE,
options = list(columnDefs = list(list(width = '20%', targets = c(8)))))
```
From the table, we can see that all possible pairwise combinations of CC/DO founder strains are represented, with the exception of (NZO/HILtJxCAST/EiJ)F1 and (NZO/HILtJxPWK/PhJ)F1. These missing samples could be interesting; these two crosses have been previously noted as "reproductively incompatible" in the [literature](https://link.springer.com/article/10.1007/s00335-008-9135-8). We constructed a rough dendrogram from good marker genotypes to determine whether samples cluster according to known relationships among founder strains. Edge colors represent rough clustering into six groups - three of which contain samples derived from wild-derived founder strains and their F1 hybrids with other founder strains.
```{r founder sample dendrogram, fig.width=10, fig.height=10}
recoded_wide_geno_files <- list.files("data/GigaMUGA/GigaMUGA_founder_sample_dendrogram_genos//", pattern = "gm_widegenos_chr")
recoded_wide_sample_genos_list <- list()
for(i in 1:length(recoded_wide_geno_files)){
recoded_wide_sample_genos_list[[i]] <- fst::read.fst(path = paste0("data/GigaMUGA/GigaMUGA_founder_sample_dendrogram_genos/",recoded_wide_geno_files[[i]]))
}
recoded_wide_sample_genos <- Reduce(dplyr::bind_cols,recoded_wide_sample_genos_list)
sample_id_cols <- recoded_wide_sample_genos %>%
dplyr::select(contains("sample_id"))
recoded_wide_sample_genos_nosamps <- recoded_wide_sample_genos %>%
dplyr::select(-contains("sample_id"))
rownames(recoded_wide_sample_genos_nosamps) <- sample_id_cols[,1]
# Scaling the genotype matrix, then calculating euclidean distance between all samples
dd <- dist(scale(recoded_wide_sample_genos_nosamps), method = "euclidean")
hc <- hclust(dd, method = "ward.D2")
# Plotting sample distances as a dendrogram
dend_colors = c("slateblue", # classical strains
"blue",
qtl2::CCcolors[6:8]) # official colors for wild-derived CC/DO founder strains
clus8 = cutree(hc, 5)
plot(as.phylo(hc), type = "f", cex = 0.5, tip.color = dend_colors[clus8],
no.margin = T, label.offset = 1, edge.width = 0.5)
```
From here we curated a set of consensus genotypes for each CC/DO founder strain by identifying alleles that were fixed across replicate samples from each founder strain. Where there were discrepancies or missing genotypes among these samples, we used reconstructed haplotypes from over 950 DO mice to impute the genotypes for these sites. The consensus genotypes for intersecting markers between two founder strains were combined ("crossed") to form predicted genotypes for each F1 hybrid of CC/DO founders. Then, the genotypes of each CC/DO founder F1 hybrid were compared directly to what was predicted, and the concordance shown below is the proportion of markers of each individual that match this prediction.
```{r fig.width=10, fig.height=5}
chr_concordance_files <- list.files("data/GigaMUGA/GigaMUGA_founder_sample_concordance/")
chr_concordance_list <- list()
for(i in 1:length(chr_concordance_files)){
chr_concordance_list[[i]] <- fst::read.fst(path = paste0("data/GigaMUGA/GigaMUGA_founder_sample_concordance/",chr_concordance_files[[i]]))
}
founder_concordance_df <- Reduce(dplyr::full_join, chr_concordance_list)
founder_concordance_df_3 <- founder_concordance_df %>%
dplyr::left_join(., founderSamples %>%
dplyr::rename(sample = sample_id) %>%
dplyr::select(sample, dam, sire)) %>%
dplyr::group_by(sample, alt_chr, dam, sire, inferred.sex) %>%
dplyr::summarise(total.MATCH = sum(MATCH),
total.NO_MATCH = sum(`NO MATCH`),
concordance = total.MATCH/(total.MATCH+total.NO_MATCH))
auto_concordance <- founder_concordance_df_3 %>%
dplyr::filter(alt_chr == "Autosome")
X_concordance <- founder_concordance_df_3 %>%
dplyr::filter(alt_chr == "X")
founder_palette <- qtl2::CCcolors
names(founder_palette) <- unique(founderSamples$dam)
auto_concordance_plot <- ggplot(auto_concordance, mapping = aes(x = dam,
y = concordance,
color = dam,
fill = sire,
label = sample,
text = concordance)) +
geom_jitter(shape = 21, width = 0.25) +
scale_fill_manual(values = founder_palette) +
scale_colour_manual(values = founder_palette) +
# ylim(c(0.5,1.05)) +
labs(x = "Dam Founder Strain",
y = "Autosomal Genotype Concordance") +
facet_grid(.~inferred.sex) +
QCtheme +
theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1))
ggplotly(auto_concordance_plot, tooltip = c("label", "text"))
X_concordance_plot <- ggplot(X_concordance, mapping = aes(x = dam,
y = concordance,
color = dam,
fill = sire,
label = sample,
text = concordance)) +
geom_jitter(shape = 21, width = 0.25) +
scale_fill_manual(values = founder_palette) +
scale_colour_manual(values = founder_palette) +
# ylim(c(0.5,1.05)) +
labs(x = "Dam Founder Strain",
y = "X Chromosome Genotype Concordance") +
facet_grid(.~inferred.sex) +
QCtheme +
theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1))
ggplotly(X_concordance_plot, tooltip = c("label","text"))
```
We identified one sample, GC_15_F which appears to be a strain mixup. Based on the sample name, the sample is predicted to be an F1 hybrid from a cross between a PWK/PhJ female and 129S1/SvImJ male. This sample, however does not group with any other PWK/PhJ-derived samples in our sample dendrogram and, instead, falls in with other NZO/HILtJ samples. Additionally, the strain concordance above indicates that both autosomes and the X chromosome are nearly 50% concordant. This led us to hypothesize that the sample was in fact an (NZO/HILtJx129S1/SvImJ)F1 mouse. We performed an additional check to test this and, as displayed below, we have good evidence that this was indeed the case. We have indicated this switch in all sample metadata files.
```{r}
GC_15_F_files <- list.files("data/GigaMUGA/GC_15_F_ReSex_Results/")
GC_15_F_list <- list()
for(i in 1:length(GC_15_F_files)){
GC_15_F_list[[i]] <- read.csv(file = paste0("data/GigaMUGA/GC_15_F_ReSex_Results/",GC_15_F_files[[i]])) %>%
dplyr::mutate(chr = as.character(chr))
}
GC_15_F_concordance_df <- Reduce(dplyr::bind_rows, GC_15_F_list)
GC_15_F_concordance_df[is.na(GC_15_F_concordance_df)] <- 0
GC_15_F_concordance_summary <- GC_15_F_concordance_df %>%
dplyr::left_join(., founderSamples %>%
dplyr::rename(sample = sample_id) %>%
dplyr::select(sample, dam, sire)) %>%
dplyr::mutate(dam = "NZO/HILtJ") %>% # Sample mislabeled as PWK initially
dplyr::group_by(sample, alt_chr, dam, sire, inferred.sex) %>%
dplyr::summarise(total.MATCH = sum(MATCH),
total.NO_MATCH = sum(NO.MATCH),
concordance = total.MATCH/(total.MATCH+total.NO_MATCH))
DT::datatable(GC_15_F_concordance_summary, escape = FALSE)
```
## Writing reference files
The list of output file types following QC is as follows:
- Genotype file; rows = markers, columns = samples
- Probe intensity file; rows = markers, columns = samples
- Sample metadata; columns = sample, strain, sex
Each file type is generated for:
- All good samples
- Eight CC/DO founder strains
```{r output files for all samples}
bad_samples <- high.n.samples %>%
dplyr::filter(!sample_id %in% c("JAXMP_caroli_UNK_BC21325",
"JAXMP_minu_KE_BC24327",
"JAXMP_minu_KE_BC24339",
"JAXMP_pahari_TH_BC21314"))
#############################################
## Write Reference Genotypes - All Samples ##
#############################################
founder_sample_geno_files <- c(as.list(list.files(path = "data/GigaMUGA/GigaMUGA_founder_sample_genotypes/",
pattern = "gm_founder_genos_chr_")[1:19]),"M","NA",
list.files(path = "data/GigaMUGA/GigaMUGA_founder_sample_genotypes/",
pattern ="gm_founder_genos_chr_")[20],"Y")
nonfounder_sample_geno_files <- as.list(list.files(path = "data/GigaMUGA/GigaMUGA_reference_genotypes/", pattern = "gm_genos_chr_"))
future::plan(multisession, workers = 16)
make_chunks <- furrr:::make_chunks
make_chunks(n_x = length(founder_sample_geno_files), n_workers = 16)
reference_genos_list <- furrr::future_map2(.x = founder_sample_geno_files,
.y = nonfounder_sample_geno_files,
.f = writeReferenceGenotypes,
.options = furrr_options(seed = TRUE)) %>%
purrr::discard(., is.character)
# All reference genotypes
reference_genos_df <- Reduce(dplyr::bind_rows, reference_genos_list)
reference_genos_df %<>%
dplyr::left_join(., gm_metadata %>%
dplyr::select(marker, chr, bp_mm10, cM_cox)) %>%
dplyr::arrange(bp_mm10, cM_cox) %>%
select(-chr, -cM_cox, -bp_mm10)
###############################################
## Write Reference Intensities - All Samples ##
###############################################
reference_intensities_list <- furrr::future_map(.x = nonfounder_sample_geno_files,
.f = writeReferenceIntensities,
.options = furrr_options(seed = TRUE))
reference_X_intensities_df <- purrr::transpose(reference_intensities_list)[[1]] %>%
purrr::keep(., is.data.frame) %>%
Reduce(dplyr::bind_rows, .)
reference_Y_intensities_df <- purrr::transpose(reference_intensities_list)[[2]] %>%
purrr::keep(., is.data.frame) %>%
Reduce(dplyr::bind_rows, .)
reference_X_intensities_df %<>%
dplyr::left_join(., gm_metadata %>%
dplyr::select(marker, chr, bp_mm10, cM_cox)) %>%
dplyr::arrange(bp_mm10, cM_cox) %>%
select(-chr, -cM_cox, -bp_mm10)
reference_Y_intensities_df %<>%
dplyr::left_join(., gm_metadata %>%
dplyr::select(marker, chr, bp_mm10, cM_cox)) %>%
dplyr::arrange(bp_mm10, cM_cox) %>%
select(-chr, -cM_cox, -bp_mm10)
#################################################
## Write Consensus Genotypes - Founder Strains ##
#################################################
founder_consensus_files <- list.files(path = "data/GigaMUGA/GigaMUGA_founder_consensus_genotypes/",
pattern = "GigaMUGA_founder_consensus_imputed_genotypes_chr")
founder_consensus_genos <- purrr::map(.x = founder_consensus_files,
.f = writeFounderConsensusGenotypes) %>%
Reduce(dplyr::bind_rows, .)
for(i in 2:ncol(founder_consensus_genos)){
founder_consensus_genos[,i] <- unlist(purrr::transpose(strsplit(founder_consensus_genos[,i],""))[[1]])
}
founder_consensus_genos_Y <- read.csv(file = "output/GigaMUGA/GigaMUGA_founder_consensus_genotypes_chrY.csv") %>%
dplyr::select(-X) %>%
`colnames<-`(colnames(founder_consensus_genos))
founder_consensus_genos_M <- read.csv(file = "output/GigaMUGA/GigaMUGA_founder_consensus_genotypes_chrM.csv") %>%
dplyr::select(-X) %>%
`colnames<-`(colnames(founder_consensus_genos))
founder_consensus_genos %<>%
dplyr::bind_rows(., founder_consensus_genos_Y) %>%
dplyr::bind_rows(., founder_consensus_genos_M)
founder_consensus_genos %<>%
dplyr::left_join(., gm_metadata %>%
dplyr::select(marker, chr, bp_mm10, cM_cox)) %>%
dplyr::arrange(bp_mm10, cM_cox) %>%
select(-chr, -cM_cox, -bp_mm10)
####################################
## Write Founder Mean Intensities ##
####################################
founder_samples_strains <- founderSamples %>%
dplyr::filter(bg == "INBRED") %>%
dplyr::distinct(sample_id, dam) %>%
dplyr::rename(strain = dam) # if inbred, dam == strain
founder_mean_x_ints <- reference_X_intensities_df %>%
dplyr::select(marker,founder_samples_strains$sample_id) %>%
tidyr::pivot_longer(-marker, names_to = "sample_id", values_to = "X") %>%
dplyr::left_join(., founder_samples_strains) %>%
dplyr::filter(!is.na(X)) %>%
dplyr::group_by(marker, strain) %>%
dplyr::summarise(mean_x = mean(X)) %>%
tidyr::pivot_wider(names_from = strain, values_from = mean_x) %>%
dplyr::filter(marker %in% founder_consensus_genos$marker)
founder_mean_x_ints %<>%
dplyr::left_join(., gm_metadata %>%
dplyr::select(marker, chr, bp_mm10, cM_cox)) %>%
dplyr::arrange(bp_mm10, cM_cox) %>%
select(-chr, -cM_cox, -bp_mm10)
founder_mean_y_ints <- reference_Y_intensities_df %>%
dplyr::select(marker,founder_samples_strains$sample_id) %>%
tidyr::pivot_longer(-marker, names_to = "sample_id", values_to = "Y") %>%
dplyr::left_join(., founder_samples_strains) %>%
dplyr::filter(!is.na(Y)) %>%
dplyr::group_by(marker, strain) %>%
dplyr::summarise(mean_y = mean(Y)) %>%
tidyr::pivot_wider(names_from = strain, values_from = mean_y) %>%
dplyr::filter(marker %in% founder_consensus_genos$marker)
founder_mean_y_ints %<>%
dplyr::left_join(., gm_metadata %>%
dplyr::select(marker, chr, bp_mm10, cM_cox)) %>%
dplyr::arrange(bp_mm10, cM_cox) %>%
select(-chr, -cM_cox, -bp_mm10)
###################################
## Write Founder Sample Metadata ##
###################################
founder_metadata <- founderSamples %>%
dplyr::select(-bg) %>%
dplyr::rename(original_sex = predicted.sex,
correct_sex = inferred.sex,
sample = sample_id) %>%
dplyr::mutate(strain = dplyr::if_else(dam != sire, true = paste0("(",dam,"x",sire,")F1"), false = dam)) %>%
dplyr::mutate(dam = case_when(dam == "A/J" ~ "A",
dam == "C57BL/6J" ~ "B",
dam == "129S1/SvImJ" ~ "C",
dam == "NOD/ShiLtJ" ~ "D",
dam == "NZO/HILtJ" ~ "E",
dam == "CAST/EiJ" ~ "F",
dam == "PWK/PhJ" ~ "G",
dam == "WSB/EiJ" ~ "H"),
sire = case_when(sire == "A/J" ~ "A",
sire == "C57BL/6J" ~ "B",
sire == "129S1/SvImJ" ~ "C",
sire == "NOD/ShiLtJ" ~ "D",
sire == "NZO/HILtJ" ~ "E",
sire == "CAST/EiJ" ~ "F",
sire == "PWK/PhJ" ~ "G",
sire == "WSB/EiJ" ~ "H")) %>%
tidyr::unite("letter", dam:sire, sep = "") %>%
dplyr::ungroup() %>%
dplyr::select(sample, strain, correct_sex, original_sex, letter) %>%
# Individual sample switch
dplyr::mutate(strain = if_else(sample == "GC_15_F",
true = "(NZO/HILtJx129S1/SvImJ)F1",
false = strain),
letter = if_else(sample == "GC_15_F",
true = "EC",
false = letter))
reference_meta_nostrain <- predicted.sexes %>%
dplyr::filter(sample_id %in% colnames(reference_genos_df)[-1]) %>%
dplyr::left_join(., reSexed_samples %>%
dplyr::select(sample_id, inferred.sex)) %>%
dplyr::rename(sample = sample_id,
original_sex = predicted.sex,
correct_sex = inferred.sex) %>%
dplyr::left_join(., founder_metadata %>%
dplyr::select(sample, strain)) %>%
dplyr::mutate(strain = if_else(sample == "GC_15_F",
true = "(NZO/HILtJx129S1/SvImJ)F1",
false = strain))
unassigned_strains <- reference_meta_nostrain %>%
dplyr::filter(is.na(strain))
new_strains <- purrr::map(unassigned_strains$sample, findStrain) %>%
unlist()
unassigned_strains$strain <- new_strains
reference_sample_metadata <- unassigned_strains %>%
dplyr::mutate(correct_sex = dplyr::if_else(is.na(correct_sex), true = "unknown", false = correct_sex),
mouse.id.1 = stringr::str_sub(strain, -1),
strain = dplyr::if_else(mouse.id.1 %in% c("m","f"),
true = str_sub(string = strain, 1, nchar(strain)-1),
false = strain)) %>%
dplyr::select(-mouse.id.1) %>%
dplyr::mutate(strain = dplyr::case_when(strain == "JAXMP_do" ~ "JAXMP_dom",
strain == "JAXMP_" ~ "JAXMP_minu",
strain == "PANCEVO/EiJ31581" ~ "PANCEVO/EiJ",
str_detect(string = strain, pattern = "MWN") ~ "MWN",
str_detect(string = strain, pattern = "PAE") ~ "PAE",
str_detect(string = strain, pattern = "JAXMP_pahari") ~ "JAXMP_pahari",
str_detect(string = strain, pattern = "JAXMP_spt") ~ "JAXMP_spt",
str_detect(string = strain, pattern = "JAXMP_cooki") ~ "JAXMP_cooki",
str_detect(string = strain, pattern = "JAXMP_cptak") ~ "JAXMP_cptak",
str_detect(string = strain, pattern = "JAXMP_caroli") ~ "JAXMP_caroli",
str_detect(string = strain, pattern = "JAXMP_hort") ~ "JAXMP_hort",
TRUE ~ strain)) %>%
dplyr::bind_rows(.,reference_meta_nostrain %>%
dplyr::filter(!sample %in% unassigned_strains$sample)) %>%
dplyr::filter(sample %in% colnames(reference_genos_df)[-1]) %>%
dplyr::mutate(correct_sex = dplyr::case_when(sample == "FAM" ~ "unknown",
sample == "JAXMP_cookii_TH_BC19281" ~ "female",
TRUE ~ correct_sex)) %>%
dplyr::distinct()
###################
## WRITING FILES ##
###################
dir.create("output/GigaMUGA")
write.csv(reference_genos_df,
file = "output/GigaMUGA/GigaMUGA_genotypes.csv",
row.names = F)
if(file.exists("output/GigaMUGA/GigaMUGA_genotypes.csv.gz")){
system("rm output/GigaMUGA/GigaMUGA_genotypes.csv.gz")
}
system("gzip output/GigaMUGA/GigaMUGA_genotypes.csv")
write.csv(reference_X_intensities_df,
file = "output/GigaMUGA/GigaMUGA_x_intensities.csv",
row.names = F)
if(file.exists("output/GigaMUGA/GigaMUGA_x_intensities.csv.gz")){
system("rm output/GigaMUGA/GigaMUGA_x_intensities.csv.gz")
}
system("gzip output/GigaMUGA/GigaMUGA_x_intensities.csv")
write.csv(reference_Y_intensities_df,
file = "output/GigaMUGA/GigaMUGA_y_intensities.csv",
row.names = F)
if(file.exists("output/GigaMUGA/GigaMUGA_y_intensities.csv.gz")){
system("rm output/GigaMUGA/GigaMUGA_y_intensities.csv.gz")
}
system("gzip output/GigaMUGA/GigaMUGA_y_intensities.csv")
write.csv(reference_sample_metadata,
file = "output/GigaMUGA/GigaMUGA_sample_metadata.csv",
row.names = F)
write.csv(founder_consensus_genos,
file = "output/GigaMUGA/GigaMUGA_founder_consensus_genotypes.csv",
row.names = F)
if(file.exists("output/GigaMUGA/GigaMUGA_founder_consensus_genotypes.csv.gz")){
system("rm output/GigaMUGA/GigaMUGA_founder_consensus_genotypes.csv.gz")
}
system("gzip output/GigaMUGA/GigaMUGA_founder_consensus_genotypes.csv")
write.csv(founder_mean_x_ints,
file = "output/GigaMUGA/GigaMUGA_founder_mean_x_intensities.csv",
row.names = F)
if(file.exists("output/GigaMUGA/GigaMUGA_founder_mean_x_intensities.csv.gz")){
system("rm output/GigaMUGA/GigaMUGA_founder_mean_x_intensities.csv.gz")
}
system("gzip output/GigaMUGA/GigaMUGA_founder_mean_x_intensities.csv")
write.csv(founder_mean_y_ints,
file = "output/GigaMUGA/GigaMUGA_founder_mean_y_intensities.csv",
row.names = F)
if(file.exists("output/GigaMUGA/GigaMUGA_founder_mean_y_intensities.csv.gz")){
system("rm output/GigaMUGA/GigaMUGA_founder_mean_y_intensities.csv.gz")
}
system("gzip output/GigaMUGA/GigaMUGA_founder_mean_y_intensities.csv")
write.csv(founder_metadata,
file = "output/GigaMUGA/GigaMUGA_founder_metadata.csv",
row.names = F)
```