-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrough-draft_evaluate-categories_expression_initial.Rmd
3279 lines (2835 loc) · 107 KB
/
rough-draft_evaluate-categories_expression_initial.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
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
---
title: "rough-draft_evaluate-categories_expression_initial.Rmd"
author: "KA"
email: "[email protected]"
output:
html_notebook:
toc: yes
toc_float: true
---
<br />
## Get situated
### Code
<details>
<summary><i>Code: Get situated</i></summary>
```{r Get situated, results='hide', message=FALSE, warning=FALSE}
#!/usr/bin/env Rscript
library(ggplot2)
library(ggpubr)
library(PCAtools)
library(rstatix)
library(tidyverse)
library(treemap)
options(scipen = 999)
options(ggrepel.max.overlaps = Inf)
if(stringr::str_detect(getwd(), "kalavattam")) {
p_local <- "/Users/kalavattam/Dropbox/FHCC"
} else {
p_local <- "/Users/kalavatt/projects-etc"
}
p_wd <- "2022-2023_RRP6-NAB3/results/2023-0215"
setwd(paste(p_local, p_wd, sep = "/"))
getwd()
rm(p_local, p_wd)
```
</details>
<br />
<br />
## Load "comprehensive" `gtf` files
### Code
<details>
<summary><i>Code: Load "comprehensive" `gtf` files</i></summary>
```{r Load "comprehensive" gtf files, results='hide', message=FALSE, warning=FALSE}
#!/usr/bin/env Rscript
p_gtf <- "./outfiles_gtf-gff3/comprehensive/S288C_reference_genome_R64-1-1_20110203"
f_S <- "processed_features-intergenic_sense.gtf"
comp_S <- paste(p_gtf, f_S, sep = "/") %>%
rtracklayer::import() %>%
tibble::as_tibble() %>%
dplyr::arrange(seqnames, start) %>%
dplyr::select(-c(score, phase)) %>%
dplyr::rename(category = type.1)
f_SA <- "processed_features-intergenic_sense-antisense.gtf"
comp_SA <- paste(p_gtf, f_SA, sep = "/") %>%
rtracklayer::import() %>%
tibble::as_tibble() %>%
dplyr::arrange(seqnames, start) %>%
dplyr::select(-c(score, phase)) %>%
dplyr::rename(category = type.1)
rm(p_gtf, f_S, f_SA)
```
</details>
<br />
<br />
## Load counts matrices against "comprehensive" `gtf`s
### Code
<details>
<summary><i>Code: Load "comprehensive" `gtf` files</i></summary>
```{r Load counts matrices against "comprehensive" gtfs, results='hide', message=FALSE, warning=FALSE}
#!/usr/bin/env Rscript
read_in_counts_matrix <- function(x) {
# ...
# :param x: counts matrix from htseq-count
# :return y: counts matrix as tibble
y <- readr::read_tsv(x, show_col_types = FALSE) %>%
dplyr::rename(gene_id = ...1)
return(y)
}
p_cm <- "./outfiles_htseq-count/comprehensive/S288C_reference_genome_R64-1-1_20110203/UT_prim_UMI"
f_SA_all <- "all-bams.hc-strd-eq.union.nonunique-all.processed_features-intergenic_sense-antisense.tsv"
f_S_all <- "all-bams.hc-strd-eq.union.nonunique-all.processed_features-intergenic_sense.tsv"
f_SA_frac <- "all-bams.hc-strd-eq.union.nonunique-fraction.processed_features-intergenic_sense-antisense.tsv"
f_S_frac <- "all-bams.hc-strd-eq.union.nonunique-fraction.processed_features-intergenic_sense.tsv"
f_SA_none <- "all-bams.hc-strd-eq.union.nonunique-none.processed_features-intergenic_sense-antisense.tsv"
f_S_none <- "all-bams.hc-strd-eq.union.nonunique-none.processed_features-intergenic_sense.tsv"
f_SA_rand <- "all-bams.hc-strd-eq.union.nonunique-random.processed_features-intergenic_sense-antisense.tsv"
f_S_rand <- "all-bams.hc-strd-eq.union.nonunique-random.processed_features-intergenic_sense.tsv"
t_SA_all <- read_in_counts_matrix(paste(p_cm, f_SA_all, sep = "/"))
t_S_all <- read_in_counts_matrix(paste(p_cm, f_S_all, sep = "/"))
t_SA_rand <- read_in_counts_matrix(paste(p_cm, f_SA_rand, sep = "/"))
t_S_rand <- read_in_counts_matrix(paste(p_cm, f_S_rand, sep = "/"))
t_SA_frac <- read_in_counts_matrix(paste(p_cm, f_SA_frac, sep = "/"))
t_S_frac <- read_in_counts_matrix(paste(p_cm, f_S_frac, sep = "/"))
t_S_none <- read_in_counts_matrix(paste(p_cm, f_S_none, sep = "/"))
t_SA_none <- read_in_counts_matrix(paste(p_cm, f_SA_none, sep = "/"))
rm(
p_cm, f_SA_frac, f_S_frac, f_SA_none, f_S_none, f_SA_all, f_S_all,
f_SA_rand, f_S_rand
)
```
</details>
<br />
<br />
## Evaluate the assignments from `htseq-count`
<b>Goal</b>: All counts/read pairs need to be accounted for; `htseq-count` counts should equal `samtools view` counts (after taking certain things—*see below*—into consideration)
### Perform and assess the foundational work
#### Code
<details>
<summary><i>Code: Evaluate the assignments from `htseq-count`</i></summary>
```{r Evaluate the assignments from htseq-count, results='hide', message=FALSE, warning=FALSE}
#!/usr/bin/env Rscript
# Create "test" dataframes from t_S_none columns 1 and 2 ---------------------
test <- t_S_none[, 1:2]
# Clean up column names
colnames(test)[2] <- colnames(test)[2] %>%
gsub("bams_renamed/UT_prim_UMI/", "", .) %>%
gsub("\\.UT_prim_UMI\\.bam", "", .)
# Extract the five "summary values" calculated by htseq-count; they are at the
#+ end of the matrices and have names that begin with two underscore characters
underscore <- test %>%
dplyr::filter(stringr::str_detect(gene_id, "^__[a-zA-Z0-9_]*$"))
# View(underscore)
# Extract the per-feature counts scored by htseq-count
counts <- test %>%
dplyr::filter(!stringr::str_detect(gene_id, "^__[a-zA-Z0-9_]*$"))
# View(counts)
# Determine and compare various tallies --------------------------------------
# Tally the non-underscore-category counts (read pairs)
counts$`n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1` %>% sum() # [1] 6765861
#IMPORTANT
# Tally the underscore-category counts (read pairs)
underscore$`n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1` %>% sum() # [1] 21827889
# 14968733 + 1607213 + 5251943 # [1] 21827889
# Tally the number of reads (records) in the bam
# ❯ samtools view -c n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1.UT_prim_UMI.bam
# 57187500
# Tally the number of read pairs in the bam
# ❯ echo $(( 57187500 / 2 ))
# 28593750
# Bam read pairs minus underscore-category counts
28593750 - 21827889 # [1] 6765861
#NOTE This is equal to the tally of non-underscore-category counts above
#CONCLUSION 1/2 We seem to have counts that are consistent between the bam and
#CONCLUSION 2/2 the counts matrix
```
```{bash, eval=FALSE}
#!/bin/bash
# Get situated
grabnode # 1 CPU, defaults
ml SAMtools/1.16.1-GCC-11.2.0
cd /home/kalavatt/tsukiyamalab/kalavatt/2022-2023_RRP6-NAB3 \
|| echo "cd'ing failed; check on this"
cd results/2023-0215/bams_renamed/UT_prim_UMI \
|| echo "cd'ing failed; check on this"
# Assess the total number of reads in the bam --------------------------------
samtools view -c \
n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1.UT_prim_UMI.bam # 57187500
echo $(( 57187500 / 2 )) # 28593750
# Assess S. cerevisiae mitochondiral and non-S. cerevisiae reads -------------
# Tally numbers of unimapping reads
samtools view \
n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1.UT_prim_UMI.bam \
Mito A B C D E F 20S \
| awk '/\<NH:i:1\>/' \
| wc -l # 27447604
echo $(( 27447604 / 2 )) # 13723802 unimapping read pairs
# Tally numbers multimapping reads
samtools view \
n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1.UT_prim_UMI.bam \
Mito A B C D E F 20S \
| awk '!/\<NH:i:1\>/' \
| wc -l # 4233128
echo $(( 4233128 / 2 )) # 2116564 multimapping read pairs
# Tally numbers of all reads
samtools view -c \
n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1.UT_prim_UMI.bam \
Mito A B C D E F 20S # 31680732
echo $(( 31680732 / 2 )) # 15840366 total read pairs
if [[ $(( 4233128 + 27447604 )) -eq 31680732 ]]; then
echo "Tally of total reads equals sum of numbers of multimapping and" \
"unimapping reads"
else
echo "Tally of total reads does not equal sum of numbers of multimapping" \
"and unimapping alignments"
fi
# Assess S. cerevisiae I-XVI reads -------------------------------------------
# Tally numbers of unimapping reads
samtools view \
n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1.UT_prim_UMI.bam \
I II III IV V VI VII VIII IX X XI XII XIII XIV XV XVI \
| awk '/\<NH:i:1\>/' \
| wc -l # 19236010
echo $(( 19236010 / 2 )) # 9618005 unimapping read pairs
# Tally numbers multimapping reads
samtools view \
n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1.UT_prim_UMI.bam \
I II III IV V VI VII VIII IX X XI XII XIII XIV XV XVI \
| awk '!/\<NH:i:1\>/' \
| wc -l # 6270758
echo $(( 6270758 / 2 )) # 3135379 multimapping read pairs
# Tally numbers of all reads
samtools view -c \
n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1.UT_prim_UMI.bam \
I II III IV V VI VII VIII IX X XI XII XIII XIV XV XVI # 25506768
echo $(( 25506768 / 2 )) # 12753384 total read pairs
if [[ $(( 6270758 + 19236010 )) -eq 25506768 ]]; then
echo "Tally of total reads equals sum of numbers of multimapping" \
"and unimapping reads"
else
echo "Tally of total reads does not equal sum of numbers of multimapping" \
"and unimapping reads"
fi
# Final assessments and conclusion -------------------------------------------
echo $(( 9618005 + 13723802 )) # 23341807 total unimapping read pairs
echo $(( 3135379 + 2116564 )) # 5251943 total multimapping read pairs
# `underscore`
# __no_feature 14968733
# __ambiguous 1607213
# __too_low_aQual 0
# __not_aligned 0
# __alignment_not_unique 5251943
# Steps for processing (#CONCLUSION)
#+ 1. From __alignment_not_unique, need to subtract multimappers against S.
#+ cerevisiae Mito, K. lactis A-F, and 20S
#+ 2. From __no_feature, need to subtract unimappers against S. cerevisiae
#+ Mito, K. lactis A-F, and 20S
# In practice...
hc_anu=$(( 5251943 - 2116564 )) # 3135379: New value for __alignment_not_unique # 1
hc_nf=$(( 14968733 - 13723802 )) # 1244931: New value for __no_feature # 2
hc_ambi=1607213
hc_val=6765861 # sum(counts$`n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1`) / 2
echo $(( hc_anu + hc_nf + hc_ambi )) # 5987523 (sans "valid")
echo $(( hc_val + hc_anu + hc_nf + hc_ambi )) # 12753384
# It took all day, but I finally go this fucker reconciled. Nice.
```
</details>
<br />
#### Notes
<details>
<summary><i>Notes: Evaluate the assignments from `htseq-count`</i></summary>
Per the sum of counts (read pairs) in dataframe `underscore`, there are <u>21,827,889 <b>invalid</b> counts</u> in the test bam.
After calling `samtools view -c n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1.UT_prim_UMI.bam`, we see that there are <u>28,593,750</u> counts (<u>57,187,500</u> aligned reads) in the file.
Looking at dataframe `t_S_none`—specifically, the five "summary values" calculated by `htseq-count`—and the results from calls to `samtools view`, we see that...
- 14,968,733 are classified "`__no_feature`" (read pairs that could not be assigned to any feature),
- 1,607,213 are "`__ambiguous`" (read pairs that could have been assigned to more than one feature and thus are not counted for any of them),
- 0 are "`__to_low_aQual`" (read pairs that were skipped due to the `-a` option—<i>not applicable to us since we used `STAR` to align reads</i>),
- 0 are "`__not_aligned`" (read pairs in the `bam` file without alignment),
- 5,251,943 are "`__alignment_not_unique`" (read pairs that align to more than one location in the reference as indicated by the `NH` tag), and
- 6,765,861 are "valid" counts (from `counts$n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1 %>% sum()`).
(<i>Quick check</i>: Does the sum of `__no_feature`, `__ambiguous`, `__alignment_not_unique` equal 21,827,889 as described above? <i>Yes.</i> `14968733 + 1607213 + 5251943 # [1] 21827889`)
<b>Goal</b>: We need to exclude counts associated with <u>*S. cerevisiae* chromosome Mito, *K. lactis* chromosomes A-F, and 20S</u> (<i>"Mito-KL-20S"</i> for short) from the five "summary values" calculated by `htseq-count`. We can achieve this goal by taking the following steps:
1. Calculate and store the <mark>number of <b>multimappers</b> associated with <i>"Mito-KL-20S"</i></mark>: `multi_Mito-KL-20S`.
2. Calculate and store the <mark>number of <b>unimappers</b> associated with <i>"Mito-KL-20S"</i></mark>: `uni_Mito-KL-20S`.
3. Calculate and store the <mark>number of <b>unimappers</b> associated with <i>S. cerevisiae chromosomes I-XVI</i></mark>: `uni_I-XVI`.
4. Subtract `multi_Mito-KL-20S` from "`__alignment_not_unique`"; store the new value: "`__alignment_not_unique_I-XVI`"
5. Subtract `uni_Mito-KL-20S` from "`__no_feature`"; store the new value: "`__no_feature_I-XVI`".
6. Calculate and store <mark>*(i)* the sum of "`__no_feature_I-XVI`", *(ii)* "`__ambiguous`", *(iii)* "`__alignment_not_unique_I-XVI`", and *(iv)* "valid" counts (e.g., from `sum(counts$n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1)`)</mark>: `summary-updated`.
7. Calculate and store the <mark>number of all counts associated with <i>S. cerevisiae chromosomes I-XVI</i></mark>: `counts_I-XVI`.
8. <mark>Check that the sum from step #5 equals the value from step #6</mark>. If `TRUE`, then everything is OK and we're good to proceed; if `FALSE`, then we need to troubleshoot why.
</details>
<br />
### Perform the steps and update dataframe `underscore`
#### Code
<details>
<summary><i>Code: Perform the steps and update dataframe `underscore`</i></summary>
```{r Perform the steps and update dataframe underscore, results='hide', message=FALSE, warning=FALSE}
#!/usr/bin/env Rscript
# Perform steps 1-7 as described ---------------------------------------------
`uni_Mito-KL-20S` <- 13723802
`multi_Mito-KL-20S` <- 2116564
`uni_I-XVI` <- 9618005
`multi_I-XVI` <- 3135379
`__alignment_not_unique` <- as.numeric(underscore[5, 2])
`__alignment_not_unique_I-XVI` <- `__alignment_not_unique` - `multi_Mito-KL-20S`
`__no_feature` <- as.numeric(underscore[1, 2])
`__no_feature_I-XVI` <- `__no_feature` - `uni_Mito-KL-20S`
`__ambiguous` <- as.numeric(underscore[2, 2])
`__valid_counts` <- sum(counts[, 2])
`summary-updated` <- sum(
`__no_feature_I-XVI`,
`__ambiguous`,
`__alignment_not_unique_I-XVI`,
`__valid_counts`
)
`counts_I-XVI` <- 12753384
`summary-updated` == `counts_I-XVI` # [1] TRUE
# Update dataframe underscore ------------------------------------------------
underscore <- underscore %>%
tibble::add_row(
gene_id = deparse(substitute(`__alignment_not_unique_I-XVI`)),
`n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1` = `__alignment_not_unique_I-XVI`,
.after = nrow(underscore)
) %>%
tibble::add_row(
gene_id = deparse(substitute(`__no_feature_I-XVI`)),
`n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1` = `__no_feature_I-XVI`,
.after = 1
) %>%
tibble::add_row(
gene_id = deparse(substitute(`__valid_counts`)),
`n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1` = `__valid_counts`,
.before = 1
)
# Clean up -------------------------------------------------------------------
rm(
`uni_Mito-KL-20S`, `multi_Mito-KL-20S`, `uni_I-XVI`, `multi_I-XVI`,
`__alignment_not_unique`, `__alignment_not_unique_I-XVI`, `__no_feature`,
`__no_feature_I-XVI`, `__ambiguous`, `__valid_counts`
)
```
</details>
<br />
<br />
## Using the test dataframes, set up/flesh out the analysis
### Code
<details>
<summary><i>Code: Using the test dataframes, set up/flesh out the analysis</i></summary>
```{r Using the test dataframes, set up/flesh out the analysis, results='hide', message=FALSE, warning=FALSE}
#!/usr/bin/env Rscript
test_joined <- dplyr::full_join(test, comp_S, by = "gene_id") %>%
dplyr::select(c(
gene_id, `n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1`, seqnames,
start, end, width, strand, source, category, orf_classification
))
`test_joined_sum-by-seqnames` <- test_joined %>%
dplyr::filter(!is.na(seqnames)) %>%
dplyr::group_by(seqnames) %>%
dplyr::summarize(
`sum-of-counts` = sum(`n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1`),
`number-of-features` = dplyr::n()
)
# seqnames sum-of-counts number-of-features
# <fctr> <dbl> <int>
# I 114509 387
# II 540531 1433
# III 144565 649
# IV 918454 2617
# V 396056 1083
# VI 124511 485
# VII 581405 1939
# VIII 268683 1020
# IX 236196 782
# X 371552 1297
# XI 383392 1153
# XII 528894 1838
# XIII 517916 1648
# XIV 478974 1372
# XV 662740 1909
# XVI 497483 1640
df_tmp_1 <- test_joined %>%
dplyr::filter(!is.na(category)) %>%
dplyr::group_by(category) %>%
dplyr::summarize(
`sum-of-counts` = sum(`n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1`),
`number-of-features` = dplyr::n()
)
# category sum-of-counts number-of-features
# <chr> <dbl> <int>
# ARS 21264 674
# PG 5142 14
# TE 39744 334
# centromere 0 32
# gene 5154259 6575
# intergenic 1210817 13162
# ncRNA 80248 14
# rRNA 3105 25
# snRNA 163506 6
# snoRNA 83096 77
# tRNA 19 275
# telomere 4661 64
df_tmp_2 <- underscore %>%
dplyr::slice(c(3, 4, nrow(underscore))) %>%
dplyr::rename(c(
category = gene_id,
`sum-of-counts` = `n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1`
)) %>%
dplyr::mutate(`number-of-features` = NA_integer_)
# category sum-of-counts number-of-features
# <chr> <dbl> <int>
# __no_feature_I-XVI 1244931 NA
# __ambiguous 1607213 NA
# __alignment_not_unique_I-XVI 3135379 NA
`test_joined_sum-by-category` <- dplyr::bind_rows(df_tmp_1, df_tmp_2)
rm(df_tmp_1, df_tmp_2)
# category sum-of-counts number-of-features
# <chr> <dbl> <int>
# ARS 21264 674
# PG 5142 14
# TE 39744 334
# centromere 0 32
# gene 5154259 6575
# intergenic 1210817 13162
# ncRNA 80248 14
# rRNA 3105 25
# snRNA 163506 6
# snoRNA 83096 77
# tRNA 19 275
# telomere 4661 64
# __no_feature_I-XVI 1244931 NA
# __ambiguous 1607213 NA
# __alignment_not_unique_I-XVI 3135379 NA
# # Check that total counts are correct
# sum(`test_joined_sum-by-category`[, 2]) == `counts_I-XVI` # [1] TRUE
# sum(`test_joined_sum-by-category`[, 2]) == `summary-updated` # [1] TRUE
```
<br />
```{r}
#!/usr/bin/env Rscript
# # Refresher: Make stacked bar charts with test data --------------------------
# specie <- c(
# rep("sorgho", 3), rep("poacee", 3), rep("banana", 3), rep("triticum", 3)
# )
# condition <- rep(c("normal", "stress", "Nitrogen"), 4)
# value <- abs(rnorm(12, 0, 15))
# data <- data.frame(specie, condition, value)
#
# rm(specie, condition, value)
#
# # Grouped
# ggplot(data, aes(fill = condition, y = value, x = specie)) +
# geom_bar(position = "dodge", stat = "identity")
#
# # Stacked
# ggplot(data, aes(fill = condition, y = value, x = specie)) +
# geom_bar(position = "stack", stat = "identity")
#
# # Stacked and percent
# ggplot(data, aes(fill = condition, y = value, x = specie)) +
# geom_bar(position = "fill", stat = "identity")
#
# treemap::treemap(
# data,
# index = c("specie", "condition"),
# vSize = "value",
# type = "index"
# )
#
# rm(data)
# Apply above to `test_joined_sum-by-category` -------------------------------
df <- `test_joined_sum-by-category` %>%
dplyr::mutate(sample = "n3-d_Q_day7_tcn_N_aux-T_tc-F_rep1_tech1") %>%
dplyr::relocate(sample, .before = category) %>%
dplyr::filter(!stringr::str_detect(
category, "__alignment_not_unique_I-XVI"
))
df$category <- df$category %>%
gsub("__", "", .) %>%
gsub("_I-XVI", "", .) %>%
gsub("PG", "pseudogene", .)
df %>%
ggplot(aes(fill = category, y = `sum-of-counts`, x = sample)) +
geom_bar(position = "dodge", stat = "identity") +
scale_fill_manual(values = length(df$category) %>% viridisLite::viridis())
df %>%
ggplot(aes(fill = category, y = `sum-of-counts`, x = sample)) +
geom_bar(position = "stack", stat = "identity") +
scale_fill_manual(values = length(df$category) %>% viridisLite::viridis())
df %>%
ggplot(aes(fill = category, y = `sum-of-counts`, x = sample)) +
geom_bar(position = "fill", stat = "identity") +
scale_fill_manual(values = length(df$category) %>% viridisLite::viridis())
treemap::treemap(
df,
index = "category",
vSize = "sum-of-counts",
type = "index",
position.legend = "right",
palette = length(df$category) %>% viridisLite::viridis(),
title = ""
)
set.seed(24)
treemap::treemap(
df,
index = "category",
vSize = "sum-of-counts",
type = "index",
position.legend = "right",
palette = length(df$category) %>% viridisLite::viridis() %>% sample(),
title = ""
)
```
```{r}
#!/usr/bin/env Rscript
# Clean up
rm(
counts, df, test, test_joined, `test_joined_sum-by-category`,
`test_joined_sum-by-seqnames`, underscore, `counts_I-XVI`,
`summary-updated`
)
```
</details>
<br />
<br />
## Isolate and preprocess relevant WT G1 and Q datasets
### Isolate relevant WT G1 and Q datasets ("Ovation" datasets)
#### Code
<details>
<summary><i>Code: Isolate relevant WT G1 and Q datasets ("Ovation" datasets)</i></summary>
```{r}
#!/usr/bin/env Rscript
# Create a vector of "relevant" WT Q and G1 dataset names
relevant <- colnames(t_S_none)[stringr::str_detect(colnames(t_S_none), "ovn")]
# Isolate the features for the relevant datasets
t_S_none_rel <- t_S_none[, c("gene_id", relevant)] %>%
dplyr::filter(!stringr::str_detect(gene_id, "^__"))
# tail(t_S_none_rel)
# Clean up column names
colnames(t_S_none_rel) <- colnames(t_S_none_rel) %>%
gsub("bams_renamed/UT_prim_UMI/", "", .) %>%
gsub("\\.UT_prim_UMI\\.bam", "", .) %>%
gsub("*_day._ovn*", "", .) %>%
gsub("aux-F_tc-F_", "", .) %>%
gsub("_tech1", "", .)
# Isolate htseq-count "summary values"for the relevant datasets
`t_S_none_rel_htseq-count-summary` <- t_S_none[, c("gene_id", relevant)] %>%
dplyr::filter(stringr::str_detect(gene_id, "^__"))
# `t_S_none_rel_htseq-count-summary`
# Again, clean up column names
colnames(`t_S_none_rel_htseq-count-summary`) <-
colnames(`t_S_none_rel_htseq-count-summary`) %>%
gsub("bams_renamed/UT_prim_UMI/", "", .) %>%
gsub("\\.UT_prim_UMI\\.bam", "", .) %>%
gsub("*_day._ovn*", "", .) %>%
gsub("aux-F_tc-F_", "", .) %>%
gsub("_tech1", "", .)
rm(relevant)
```
</details>
<br />
### Join relevant sample data with "positional" (etc.) information
#### Code
<details>
<summary><i>Code: Join relevant sample data with "positional" (etc.) information</i></summary>
```{r}
t_S_none_rel_joined <- dplyr::full_join(t_S_none_rel, comp_S, by = "gene_id")
t_S_none_rel_joined
```
</details>
<br />
### Create a metadata matrix for WT G1 and Q datasets ("Ovation" datasets)
#### Code
<details>
<summary><i>Code: Create a metadata matrix for WT G1 and Q datasets ("Ovation" datasets)</i></summary>
```{r}
metadata <- t_S_none_rel[, 2:ncol(t_S_none_rel)] %>%
colnames() %>%
stringr::str_split("_") %>%
as.data.frame() %>%
t() %>%
as.data.frame()
rownames(metadata) <- t_S_none_rel[, 2:ncol(t_S_none_rel)] %>% colnames()
colnames(metadata) <- c("genotype", "state", "transcription", "replicate")
metadata
```
</details>
<br />
### Record positional information in a `GRanges` object
#### Code
<details>
<summary><i>Code: Record positional information in a `GRanges` object</i></summary>
```{r Record positional information in a GRanges object, echo=FALSE, results='hide', message=FALSE}
record_positional_info <- function(tibble) {
pos_info <- GenomicRanges::GRanges(
seqnames = tibble$seqnames,
ranges = IRanges::IRanges(tibble$start, tibble$end),
strand = tibble$strand,
length = tibble$width,
gene_id = tibble$gene_id,
transcript_id = tibble$transcript_id,
category = tibble$category,
orf_classification = tibble$orf_classification,
source_id = tibble$source_id
)
return(pos_info)
}
t_S_none_rel_pos_info <- record_positional_info(t_S_none_rel_joined)
```
</details>
<br />
<br />
## Test replicate consistency via PCA of non-normalized counts
### Initialize necessary functions
#### Code
<details>
<summary><i>Code: Initialize necessary functions</i></summary>
```{r}
#!/usr/bin/env Rscript
get_name_of_var <- function(v) {
#TODO Write a description of this function
#
# :param v: ...
# :return v: ...
return(deparse(substitute(v)))
}
#TODO Add return description
get_top_loadings <- function(x, y, z, a) {
#TODO Write a description of this function
#
# :param x: dataframe of PC loadings <data.frame>
# :param y: character element for column in dataframe x <chr>
# :param z: whether to select all loadings sorted from largest to smallest
# absolute value ('all'), positive loadings sorted from largest
# to smallest value ('pos'), or negative loadings sorted from
# largest to smallest absolute value ('neg') <str>
# :param a: whether or not to keep 'sign' and 'abs' columns added in the
# course of processing the dataframe <logical>
# :return b: ...
b <- as.data.frame(x[[y]])
rownames(b) <- rownames(x)
colnames(b) <- y
b[["sign"]] <- ifelse(
b[[y]] > 0,
"pos",
ifelse(
b[[y]] == 0,
"zero",
"neg"
)
)
b[["abs"]] <- abs(b[[y]])
if(z == "all") {
b <- dplyr::arrange(b, by = desc(abs))
} else if(z == "pos") {
b <- b[b[[y]] > 0, ] %>% dplyr::arrange(., by = desc(abs))
} else if(z == "neg") {
b <- b[b[[y]] < 0, ] %>% dplyr::arrange(., by = desc(abs))
} else {
stop(paste0("Stopping: param z must be either 'all', 'pos', or 'neg'"))
}
if(isTRUE(a)) {
paste0("Retaining 'sign' and 'abs' columns")
} else if(isFALSE(a)) {
b <- b %>% dplyr::select(-c(sign, abs))
} else {
stop(paste0("Stopping: param a must be either 'TRUE' or 'FALSE'"))
}
return(b)
}
#TODO Add return description
plot_biplot <- function(
pca, PC_x, PC_y,
loadings_show, loadings_n,
meta_color, meta_shape,
x_min, x_max, y_min, y_max
) {
#TODO Write a description of this function
#
# :param pca: "pca" list object obtained by running PCAtools::pca()
# :param PC_x: PC to plot on the x axis <chr>
# :param PC_y: PC to plot on the y axis <chr>
# :param loadings_show: whether to overlay component loadings or not <lgl>
# :param loadings_n: number of top loadings to show <int >= 0>
# :param meta_color: column in "pca" list metadata to color by <chr>
# :param meta_shape: column in "pca" list metadata to shape by <chr>
# :param x_min: minimum value on x axis <dbl>
# :param x_max: maximum value on x axis <dbl>
# :param y_min: minimum value on y axis <dbl>
# :param y_max: maximum value on y axis <dbl>
# :param title: title of biplot <dbl>
# :return image: ...
image <- pca %>%
PCAtools::biplot(
x = PC_x,
y = PC_y,
lab = NULL,
showLoadings = loadings_show,
ntopLoadings = loadings_n,
boxedLoadingsNames = TRUE,
colby = meta_color,
shape = meta_shape,
encircle = FALSE,
ellipse = FALSE,
max.overlaps = Inf,
xlim = c(x_min, x_max),
ylim = c(y_min, y_max)
) +
theme_slick
return(image)
}
#TODO Add return description
plot_pos_neg_loadings_each_axis <- function(
df_all, df_pos, df_neg,
PC_x, PC_y,
row_start, row_end,
x_min, x_max, y_min, y_max,
x_nudge, y_nudge, x_label, y_label,
col_line_pos, col_line_neg, col_seg_pos, col_seg_neg
) {
#TODO Write a description of this function
#
# :param df_all: dataframe: all loadings (from, e.g., PCAtools)
# :param df_pos: dataframe: positive loadings ordered largest to smallest
# :param df_neg: dataframe: negative loadings ordered smallest to largest
# :param PC_x: PC to plot on the x axis
# :param PC_y: PC to plot on the y axis
# :param row_start: row from which to begin subsetting the PCs on x and y
# :param row_end: row at which to end subsetting the PCs on x and y
# :param x_min: minimum value on x axis <dbl>
# :param x_max: maximum value on x axis <dbl>
# :param y_min: minimum value on y axis <dbl>
# :param y_max: maximum value on y axis <dbl>
# :param x_nudge: amount to nudge labels on the x axis <dbl>
# :param y_nudge: amount to nudge labels on the y axis <dbl>
# :param x_label: x axis label <chr>
# :param y_label: y axis label <chr>
# :param col_line_pos: color: lines, arrows for positive loadings <chr>
# :param col_line_neg: color: lines, arrows for negative loadings <chr>
# :param col_seg_pos: color: segments connecting arrowhead and text bubble
# for positive loadings <chr>
# :param col_seg_neg: color: segments connecting arrowhead and text bubble
# for negative loadings <chr>
# :return image: ...
filter_pos_1 <- rownames(df_pos[[PC_x]][row_start:row_end, ])
filter_pos_2 <- rownames(df_pos[[PC_y]][row_start:row_end, ])
filter_neg_1 <- rownames(df_neg[[PC_x]][row_start:row_end, ])
filter_neg_2 <- rownames(df_neg[[PC_y]][row_start:row_end, ])
loadings_filter_pos_1 <- df_all[rownames(df_all) %in% filter_pos_1, ]
loadings_filter_pos_2 <- df_all[rownames(df_all) %in% filter_pos_2, ]
loadings_filter_neg_1 <- df_all[rownames(df_all) %in% filter_neg_1, ]
loadings_filter_neg_2 <- df_all[rownames(df_all) %in% filter_neg_2, ]
images <- list()
images[["PC_x_pos"]] <- plot_loadings(
loadings_filter_pos_1,
loadings_filter_pos_1[[PC_x]],
loadings_filter_pos_1[[PC_y]],
x_min, x_max, y_min, y_max, x_nudge, y_nudge,
x_label, y_label, col_line_pos, col_seg_pos
)
images[["PC_y_pos"]] <- plot_loadings(
loadings_filter_pos_2,
loadings_filter_pos_2[[PC_x]],
loadings_filter_pos_2[[PC_y]],
x_min, x_max, y_min, y_max, x_nudge, y_nudge,
x_label, y_label, col_line_pos, col_seg_pos
)
images[["PC_x_neg"]] <- plot_loadings(
loadings_filter_neg_1,
loadings_filter_neg_1[[PC_x]],
loadings_filter_neg_1[[PC_y]],
x_min, x_max, y_min, y_max, -y_nudge, x_nudge,
x_label, y_label, col_line_neg, col_seg_neg
)
images[["PC_y_neg"]] <- plot_loadings(
loadings_filter_neg_2,
loadings_filter_neg_2[[PC_x]],
loadings_filter_neg_2[[PC_y]],
x_min, x_max, y_min, y_max, x_nudge, -y_nudge,
x_label, y_label, col_line_neg, col_seg_neg
)
return(images)
}
#TODO Add return description
plot_loadings <- function(x, y, z, a, b, d, e, f, g, h, i, j, k) {
#TODO Write a description of this function
#
# :param x: dataframe of PC loadings w/gene names as rownames <data.frame>
# :param y: column in dataframe to plot on x axis <dbl>
# :param z: column in dataframe to plot on y axis <dbl>
# :param a: minimum value on x axis <dbl>
# :param b: maximum value on x axis <dbl>
# :param d: minimum value on y axis <dbl>
# :param e: maximum value on y axis <dbl>
# :param f: amount to nudge labels on the x axis <dbl>
# :param g: amount to nudge labels on the y axis <dbl>
# :param h: x axis label <chr>
# :param i: y axis label <chr>
# :param j: color of line and arrow <chr>
# :param k: color of segment connecting arrowhead and text bubble <chr>
# :return l: ...
l <- ggplot2::ggplot(x, ggplot2::aes(x = y, y = z)) + #TODO #FUNCTION
ggplot2::coord_cartesian(xlim = c(a, b), ylim = c(d, e)) +
ggplot2::geom_segment(
aes(xend = 0, yend = 0, alpha = 0.5),
color = j,
arrow = ggplot2::arrow(
ends = "first",
type = "open",
length = unit(0.125, "inches")
)
) +
ggrepel::geom_label_repel(
mapping = ggplot2::aes(
fontface = 1, segment.color = k, segment.size = 0.25
),
label = rownames(x),
label.size = 0.05,
direction = "both",
nudge_x = f, # 0.02
nudge_y = g, # 0.04
force = 4,
force_pull = 1,
hjust = 0
) +
ggplot2::xlab(h) +
ggplot2::ylab(i) +
theme_slick_no_legend
return(l)
}
#TODO Add return description
draw_scree_plot <- function(pca, horn, elbow) {
#TODO Write a description of this function
#
# :param pca: "pca" list object obtained by running PCAtools::pca()
# :param horn: ...
# :param elbow: ...
# :return scree: ...
scree <- PCAtools::screeplot(
pca,
components = PCAtools::getComponents(pca),
vline = c(horn, elbow),
vlineWidth = 0.25,
sizeCumulativeSumLine = 0.5,
sizeCumulativeSumPoints = 1.5
) +
geom_text(aes(horn + 1, 50, label = "Horn's", vjust = 2)) +
geom_text(aes(elbow + 1, 50, label = "Elbow", vjust = -2)) +
theme_slick +
ggplot2::theme(axis.text.x = element_text(angle = 90, hjust = 1))
return(scree)
}
#TODO Add return description
# Set up custom ggplot2 plot themes ------------------------------------------
theme_slick <- theme_classic() +
theme(
panel.grid.major = ggplot2::element_line(linewidth = 0.4),
panel.grid.minor = ggplot2::element_line(linewidth = 0.2),
axis.line = ggplot2::element_line(linewidth = 0.2),
axis.ticks = ggplot2::element_line(linewidth = 0.4),
axis.text = ggplot2::element_text(color = "black"),
axis.title.x = ggplot2::element_text(),
axis.title.y = ggplot2::element_text(),
plot.title = ggplot2::element_text(),
text = element_text(family = "")
)
theme_slick_no_legend <- theme_slick + theme(legend.position = "none")
```
</details>
<br />
### Create "`pca`" object and evaluate significant PCs
#### Code
<details>
<summary><i>Code: Create "`pca`" object and evaluate significant PCs</i></summary>
```{r}
#!/usr/bin/env Rscript
# Create a PCAtools "pca" S4 object for the raw counts -----------------------
#+ Assign unique row names too
obj_pca <- PCAtools::pca(
t_S_none_rel[, 2:ncol(t_S_none_rel)],
metadata = metadata
)
rownames(obj_pca$loadings) <- dplyr::pull(t_S_none_rel, gene_id)
# Determine "significant" PCs with Horn's parallel analysis ------------------
#+ See Horn, 1965
horn <- PCAtools::parallelPCA(mat = t_S_none_rel[, 2:ncol(t_S_none_rel)])
# horn$n