-
Notifications
You must be signed in to change notification settings - Fork 24
/
Internal_Utilities.R
1544 lines (1313 loc) · 48 KB
/
Internal_Utilities.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
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#################### Operators ####################
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' Set a default value if an object is NOT null
#'
#' @param lhs An object to set if it's NOT null
#' @param rhs The value to provide if x is NOT null
#'
#' @return lhs if lhs is null, else rhs
#'
#' @author Hadley Wickham
#' @references \url{https://adv-r.hadley.nz/functions.html#missing-arguments}
#'
#' @noRd
#'
`%iff%` <- function(lhs, rhs) {
if (!is.null(x = lhs)) {
return(rhs)
} else {
return(lhs)
}
}
#' Set a default value if an object is null
#'
#' @param lhs An object to set if it's null
#' @param rhs The value to provide if x is null
#'
#' @return rhs if lhs is null, else lhs
#'
#' @author Hadley Wickham
#' @references \url{https://adv-r.hadley.nz/functions.html#missing-arguments}
#'
#' @noRd
#'
`%||%` <- function(lhs, rhs) {
if (!is.null(x = lhs)) {
return(lhs)
} else {
return(rhs)
}
}
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#################### Object Checks ####################
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' Check Seurat Object
#'
#' Checks if object is of class: Seurat and returns error message if not.
#'
#' @param seurat_object Seurat object name.
#'
#' @import cli
#'
#' @return error if not Seurat object.
#'
#' @noRd
#'
Is_Seurat <- function(
seurat_object
) {
if (!inherits(what = "Seurat", x = seurat_object)) {
cli_abort(message = "{.code seurat_object} provided is not an object of class: Seurat.")
}
}
#' Check LIGER Object
#'
#' Checks if object is of class: liger and returns error message if not.
#'
#' @param liger_object liger object name.
#'
#' @import cli
#'
#' @return error is not LIGER object
#'
#' @noRd
#'
Is_LIGER <- function(
liger_object
) {
if (class(x = liger_object)[[1]] != "liger") {
cli_abort(message = "{.code liger_object} provided is not an object of class: liger")
}
}
#' Check for assays present in object
#
#' Checks Seurat object for the presence of assays against list of specified assays
#'
#' @param seurat_object Seurat object name.
#' @param assay_list vector of genes to check.
#' @param print_msg logical. Whether message should be printed if all features are found. Default is TRUE.
#' @param omit_warn logical. Whether to print message about features that are not found in current object.
#'
#' @import cli
#'
#' @return List of found vs not found assays.
#'
#' @noRd
#'
Assay_Present <- function(
seurat_object,
assay_list,
print_msg = TRUE,
omit_warn = TRUE
) {
# Check Seurat
Is_Seurat(seurat_object = seurat_object)
# get all features
possible_assays <- Assays(object = seurat_object)
# If any features not found
if (any(!assay_list %in% possible_assays)) {
bad_assays <- assay_list[!assay_list %in% possible_assays]
found_assays <- assay_list[assay_list %in% possible_assays]
if (length(x = found_assays) == 0) {
cli_abort(message = "No requested assays found.")
}
# Return message of assays not found
if (length(x = bad_assays) > 0 && isTRUE(x = omit_warn)) {
cli_warn(message = c("The following assays were omitted as they were not found:",
"i" = "{.field {glue_collapse_scCustom(input_string = bad_assays, and = TRUE)}}.")
)
}
# Combine into list and return
assay_list <- list(
found_assays = found_assays,
bad_assays = bad_assays
)
return(assay_list)
}
# Print all found message if TRUE
if (isTRUE(x = print_msg)) {
cli_inform(message = "All assays present.")
}
# Return full input gene list.
# Combine into list and return
assay_list <- list(
found_assays = assay_list,
bad_assays = NULL
)
return(assay_list)
}
#' Check whether assay is V5
#
#' Checks Seurat object to verify whether it is composed of "Assay" or "Assay5" slots.
#'
#' @param seurat_object Seurat object name.
#' @param assay name of assay to check, default is NULL.
#'
#' @return TRUE if seurat_object contains "Assay5" class.
#'
#' @noRd
#'
Assay5_Check <- function(
seurat_object,
assay = NULL
){
assay <- assay %||% DefaultAssay(object = seurat_object)
if (inherits(x = seurat_object@assays[[assay]], what = "Assay")) {
return(FALSE)
}
if (inherits(x = seurat_object@assays[[assay]], what = "Assay5")) {
return(TRUE)
}
}
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#################### WARN/ERROR MESSAGING ####################
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' Stop function without error message
#'
#' Modifies R options within the function call only to hide the error message from `stop` while
#' keeping global options preserved outside of function.
#'
#' @return stops function without error message
#'
#' @author Stibu
#' @references \url{https://stackoverflow.com/a/42945293/15568251}
#' @details \url{https://creativecommons.org/licenses/by-sa/3.0/}
#'
#' @noRd
#'
stop_quietly <- function() {
opt <- options(show.error.messages = FALSE)
on.exit(options(opt))
stop()
}
#' Custom glue collapse
#
#' Customized glue_collapse that is based on the number of items in input list
#'
#' @param input_string input string to be collapsed.
#' @param and logical. Whether to use "and" or "or" in the collapsed string
#'
#' @return collapsed string
#'
#' @importFrom glue glue_collapse
#'
#' @noRd
#'
glue_collapse_scCustom <- function(
input_string,
and = TRUE
) {
# Check length of input string
input_length <- length(x = input_string)
# set last seperator
if (isTRUE(x = and)) {
last_sep <- " and "
} else {
last_sep <- " or "
}
if (input_length <= 3) {
glue_collapse(x = input_string, sep = ", ", last = last_sep)
} else {
glue_collapse(x = input_string, sep = ", ", last = paste0(",", last_sep))
}
}
#' Perform Feature and Meta Checks before plotting
#'
#' Wraps the `Feature_Present`, `Meta_Present`, `Reduction_Loading_Present`, and `Case_Check` into
#' single function to perform feature checks before plotting.
#'
#' @param object Seurat object
#' @param features vector of features and/or meta data variables to plot.
#' @param assay Assay to use (default all assays present).
#'
#' @return vector of features and/or meta data that were found in object.
#'
#' @noRd
#'
#' @keywords internal
#'
Feature_PreCheck <- function(
object,
features,
assay = NULL
) {
# set assay (if null set to active assay)
assay <- assay %||% Assays(object = object)
# Check features and meta to determine which features present
features_list <- Feature_Present(data = object, features = features, omit_warn = FALSE, print_msg = FALSE, case_check_msg = FALSE, return_none = TRUE, seurat_assay = assay)
meta_list <- Meta_Present(object = object, meta_col_names = features_list[[2]], omit_warn = FALSE, print_msg = FALSE, return_none = TRUE)
reduction_list <- Reduction_Loading_Present(seurat_object = object, reduction_names = meta_list[[2]], omit_warn = FALSE, print_msg = FALSE, return_none = TRUE)
all_not_found_features <- reduction_list[[2]]
all_found_features <- c(features_list[[1]], meta_list[[1]], reduction_list[[1]])
# Stop if no features found
if (length(x = all_found_features) < 1) {
cli_abort(message = c("No features were found.",
"*" = "The following are not present in object:",
"i" = "{.field {glue_collapse_scCustom(input_string = all_not_found_features, and = TRUE)}}")
)
}
# Return message of features not found
if (length(x = all_not_found_features) > 0) {
op <- options(warn = 1)
on.exit(options(op))
cli_warn(message = c("The following features were omitted as they were not found:",
"i" = "{.field {glue_collapse_scCustom(input_string = all_not_found_features, and = TRUE)}}")
)
}
# Check feature case and message if found
Case_Check(seurat_object = object, gene_list = all_not_found_features, case_check_msg = TRUE, return_features = FALSE)
# return all found features
return(all_found_features)
}
#' Ask yes/no question to proceed
#'
#' Asks the user to answer yes/no question and returns logical value depending on
#' the answer.
#'
#' @return logical
#'
#' @references function modified from function in devtools R package (License: MIT) \url{https://github.com/r-lib/devtools}.
#' @details \url{https://github.com/r-lib/devtools/blob/9f27cc3e6335e74d6f51ed331509ebda56747901/R/release.R#L147-L156}.
#'
#' @import cli
#'
#' @noRd
#'
yesno <- function(msg, .envir = parent.frame()) {
yeses <- c("Yes")
nos <- c("No")
cli_inform(message = msg, .envir = .envir)
qs <- c("Yes", "No")
rand <- sample(length(qs))
utils::menu(qs[rand]) != which(rand == 1)
}
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#################### QC HELPERS ####################
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' Ensembl Mito IDs
#'
#' Retrieves Ensembl IDs for mitochondrial genes
#'
#' @param species species to retrieve IDs.
#'
#' @return vector of Ensembl Gene IDs
#'
#' @import cli
#'
#' @keywords internal
#'
#' @noRd
#'
Retrieve_Ensembl_Mito <- function(
species
) {
# Accepted species names
accepted_names <- data.frame(
Mouse_Options = c("Mouse", "mouse", "Ms", "ms", "Mm", "mm"),
Human_Options = c("Human", "human", "Hu", "hu", "Hs", "hs"),
Marmoset_Options = c("Marmoset", "marmoset", "CJ", "Cj", "cj", NA),
Zebrafish_Options = c("Zebrafish", "zebrafish", "DR", "Dr", "dr", NA),
Rat_Options = c("Rat", "rat", "RN", "Rn", "rn", NA),
Drosophila_Options = c("Drosophila", "drosophila", "DM", "Dm", "dm", NA),
Macaque_Options = c("Macaque", "macaque", "Rhesus", "macaca", "mmulatta", NA)
)
# Species Spelling Options
mouse_options <- accepted_names$Mouse_Options
human_options <- accepted_names$Human_Options
marmoset_options <- accepted_names$Marmoset_Options
zebrafish_options <- accepted_names$Zebrafish_Options
rat_options <- accepted_names$Rat_Options
drosophila_options <- accepted_names$Drosophila_Options
macaque_options <- accepted_names$Macaque_Options
if (species %in% marmoset_options) {
cli_abort(message = "Marmoset mitochondrial genome is not part of current Ensembl build.")
}
if (species %in% mouse_options) {
mito_ensembl <- ensembl_mito_id$Mus_musculus_mito_ensembl
}
if (species %in% human_options) {
mito_ensembl <- ensembl_mito_id$Homo_sapiens_mito_ensembl
}
if (species %in% zebrafish_options) {
mito_ensembl <- ensembl_mito_id$Danio_rerio_mito_ensembl
}
if (species %in% rat_options) {
mito_ensembl <- ensembl_mito_id$Rattus_norvegicus_mito_ensembl
}
if (species %in% drosophila_options) {
mito_ensembl <- ensembl_mito_id$Drosophila_melanogaster_mito_ensembl
}
if (species %in% macaque_options) {
mito_ensembl <- ensembl_mito_id$Macaca_mulatta_mito_ensembl
}
return(mito_ensembl)
}
#' Ensembl Ribo IDs
#'
#' Retrieves Ensembl IDs for ribosomal genes
#'
#' @param species species to retrieve IDs.
#'
#' @return vector of Ensembl Gene IDs
#'
#' @import cli
#'
#' @keywords internal
#'
#' @noRd
#'
Retrieve_Ensembl_Ribo <- function(
species
) {
# Accepted species names
accepted_names <- data.frame(
Mouse_Options = c("Mouse", "mouse", "Ms", "ms", "Mm", "mm"),
Human_Options = c("Human", "human", "Hu", "hu", "Hs", "hs"),
Marmoset_Options = c("Marmoset", "marmoset", "CJ", "Cj", "cj", NA),
Zebrafish_Options = c("Zebrafish", "zebrafish", "DR", "Dr", "dr", NA),
Rat_Options = c("Rat", "rat", "RN", "Rn", "rn", NA),
Drosophila_Options = c("Drosophila", "drosophila", "DM", "Dm", "dm", NA),
Macaque_Options = c("Macaque", "macaque", "Rhesus", "macaca", "mmulatta", NA)
)
# Species Spelling Options
mouse_options <- accepted_names$Mouse_Options
human_options <- accepted_names$Human_Options
marmoset_options <- accepted_names$Marmoset_Options
zebrafish_options <- accepted_names$Zebrafish_Options
rat_options <- accepted_names$Rat_Options
drosophila_options <- accepted_names$Drosophila_Options
macaque_options <- accepted_names$Macaque_Options
if (species %in% mouse_options) {
ribo_ensembl <- ensembl_ribo_id$Mus_musculus_ribo_ensembl
}
if (species %in% human_options) {
ribo_ensembl <- ensembl_ribo_id$Homo_sapiens_ribo_ensembl
}
if (species %in% zebrafish_options) {
ribo_ensembl <- ensembl_ribo_id$Callithrix_jacchus_ribo_ensembl
}
if (species %in% zebrafish_options) {
ribo_ensembl <- ensembl_ribo_id$Danio_rerio_ribo_ensembl
}
if (species %in% rat_options) {
ribo_ensembl <- ensembl_ribo_id$Rattus_norvegicus_ribo_ensembl
}
if (species %in% drosophila_options) {
ribo_ensembl <- ensembl_ribo_id$Drosophila_melanogaster_ribo_ensembl
}
if (species %in% macaque_options) {
ribo_ensembl <- ensembl_ribo_id$Macaca_mulatta_ribo_ensembl
}
return(ribo_ensembl)
}
#' Retrieve MSigDB Gene Lists
#'
#' Retrieves species specific gene lists for MSigDB QC Hallmark lists: "HALLMARK_OXIDATIVE_PHOSPHORYLATION",
#' "HALLMARK_APOPTOSIS", and "HALLMARK_DNA_REPAIR".
#'
#' @param species species to retrieve IDs.
#'
#' @return list of 3 sets of gene_symbols
#'
#' @import cli
#'
#' @keywords internal
#'
#' @noRd
#'
Retrieve_MSigDB_Lists <- function(
species
) {
# Accepted species names
accepted_names <- data.frame(
Mouse_Options = c("Mouse", "mouse", "Ms", "ms", "Mm", "mm"),
Human_Options = c("Human", "human", "Hu", "hu", "Hs", "hs"),
Marmoset_Options = c("Marmoset", "marmoset", "CJ", "Cj", "cj", NA),
Zebrafish_Options = c("Zebrafish", "zebrafish", "DR", "Dr", "dr", NA),
Rat_Options = c("Rat", "rat", "RN", "Rn", "rn", NA),
Drosophila_Options = c("Drosophila", "drosophila", "DM", "Dm", "dm", NA),
Macaque_Options = c("Macaque", "macaque", "Rhesus", "macaca", "mmulatta", NA)
)
# Species Spelling Options
mouse_options <- accepted_names$Mouse_Options
human_options <- accepted_names$Human_Options
marmoset_options <- accepted_names$Marmoset_Options
zebrafish_options <- accepted_names$Zebrafish_Options
rat_options <- accepted_names$Rat_Options
drosophila_options <- accepted_names$Drosophila_Options
macaque_options <- accepted_names$Macaque_Options
if (species %in% marmoset_options) {
cli_abort(message = "Marmoset is not currently a part of MSigDB gene list database.")
}
# set prefix
if (species %in% mouse_options) {
prefix <- "Mus_musculus_"
}
if (species %in% human_options) {
prefix <- "Homo_sapiens_"
}
if (species %in% zebrafish_options) {
prefix <- "Dario_rerio_"
}
if (species %in% rat_options) {
prefix <- "Rattus_norvegicus_"
}
if (species %in% drosophila_options) {
prefix <- "Drosophila_melanogaster_"
}
if (species %in% macaque_options) {
prefix <- "Macaca_mulatta_"
}
# set list names
oxphos <- paste0(prefix, "msigdb_oxphos")
apop <- paste0(prefix, "msigdb_apop")
dna_repair <- paste0(prefix, "msigdb_dna_repair")
# pull lists
qc_gene_list <- list(
oxphos = msigdb_qc_gene_list[[oxphos]],
apop = msigdb_qc_gene_list[[apop]],
dna_repair = msigdb_qc_gene_list[[dna_repair]]
)
return(qc_gene_list)
}
#' Retrieve IEG Gene Lists
#'
#' Retrieves species specific IEG gene lists
#'
#' @param species species to retrieve IDs.
#'
#' @return list of 2 sets of gene_symbols
#'
#' @import cli
#'
#' @keywords internal
#'
#' @noRd
#'
Retrieve_IEG_Lists <- function(
species
) {
# Accepted species names
accepted_names <- data.frame(
Mouse_Options = c("Mouse", "mouse", "Ms", "ms", "Mm", "mm"),
Human_Options = c("Human", "human", "Hu", "hu", "Hs", "hs"),
Marmoset_Options = c("Marmoset", "marmoset", "CJ", "Cj", "cj", NA),
Zebrafish_Options = c("Zebrafish", "zebrafish", "DR", "Dr", "dr", NA),
Rat_Options = c("Rat", "rat", "RN", "Rn", "rn", NA),
Drosophila_Options = c("Drosophila", "drosophila", "DM", "Dm", "dm", NA),
Macaque_Options = c("Macaque", "macaque", "Rhesus", "macaca", "mmulatta", NA)
)
# Species Spelling Options
mouse_options <- accepted_names$Mouse_Options
human_options <- accepted_names$Human_Options
marmoset_options <- accepted_names$Marmoset_Options
zebrafish_options <- accepted_names$Zebrafish_Options
rat_options <- accepted_names$Rat_Options
drosophila_options <- accepted_names$Drosophila_Options
macaque_options <- accepted_names$Macaque_Options
if (species %in% c(marmoset_options, zebrafish_options, rat_options, drosophila_options, macaque_options)) {
cli_abort(message = "Rat, Marmoset, Macaque, Zebrafish, and Drosophila are not currently supported.")
}
# set prefix
if (species %in% mouse_options) {
prefix <- "Mus_musculus_"
}
if (species %in% human_options) {
prefix <- "Homo_sapiens_"
}
# set list names
ieg <- paste0(prefix, "IEG")
# pull lists
qc_gene_list <- list(
ieg = ieg_gene_list[[ieg]]
)
return(qc_gene_list)
}
#' Add MSigDB Gene Lists Percentages
#'
#' Adds percentage of counts from 3 hallmark MSigDB hallmark gene sets: "HALLMARK_OXIDATIVE_PHOSPHORYLATION",
#' "HALLMARK_APOPTOSIS", and "HALLMARK_DNA_REPAIR".
#'
#' @param seurat_object object name.
#' @param species Species of origin for given Seurat Object. Only accepted species are: mouse, human,
#' zebrafish, rat, drosophila, or rhesus macaque (name or abbreviation)
#' @param oxphos_name name to use for the new meta.data column containing percent MSigDB Hallmark oxidative
#' phosphorylation counts. Default is "percent_oxphos".
#' @param apop_name name to use for the new meta.data column containing percent MSigDB Hallmark apoptosis counts.
#' Default is "percent_apop".
#' @param dna_repair_name name to use for the new meta.data column containing percent MSigDB Hallmark DNA repair counts.
#' Default is "percent_oxphos".
#' @param assay Assay to use (default is the current object default assay).
#' @param overwrite Logical. Whether to overwrite existing meta.data columns. Default is FALSE meaning that
#' function will abort if columns with any one of the names provided to `mito_name` `ribo_name` or
#' `mito_ribo_name` is present in meta.data slot.
#'
#' @return Seurat object
#'
#' @import cli
#'
#' @keywords internal
#'
#' @noRd
#'
Add_MSigDB_Seurat <- function(
seurat_object,
species,
oxphos_name = "percent_oxphos",
apop_name = "percent_apop",
dna_repair_name = "percent_dna_repair",
assay = NULL,
overwrite = FALSE
) {
# Accepted species names
accepted_names <- list(
Mouse_Options = c("Mouse", "mouse", "Ms", "ms", "Mm", "mm"),
Human_Options = c("Human", "human", "Hu", "hu", "Hs", "hs"),
Marmoset_Options = c("Marmoset", "marmoset", "CJ", "Cj", "cj", NA),
Zebrafish_Options = c("Zebrafish", "zebrafish", "DR", "Dr", "dr", NA),
Rat_Options = c("Rat", "rat", "RN", "Rn", "rn", NA),
Drosophila_Options = c("Drosophila", "drosophila", "DM", "Dm", "dm", NA),
Macaque_Options = c("Macaque", "macaque", "Rhesus", "macaca", "mmulatta", NA)
)
if (!species %in% unlist(x = accepted_names)) {
cli_inform(message = "The supplied species ({.field {species}}) is not currently supported.")
}
# Check Seurat
Is_Seurat(seurat_object = seurat_object)
# Check name collision
if (any(duplicated(x = c(oxphos_name, apop_name, dna_repair_name)))) {
cli_abort(message = "One or more of values provided to {.code oxphos_name}, {.code apop_name}, {.code dna_repair_name} are identical.")
}
# Overwrite check
if (oxphos_name %in% colnames(x = [email protected]) || apop_name %in% colnames(x = [email protected]) || dna_repair_name %in% colnames(x = [email protected])) {
if (isFALSE(x = overwrite)) {
cli_abort(message = c("Columns with {.val {oxphos_name}} and/or {.val {apop_name}} already present in meta.data slot.",
"i" = "*To run function and overwrite columns set parameter {.code overwrite = TRUE} or change respective {.code oxphos_name}, {.code apop_name}, and/or {.code dna_repair_name}*")
)
}
cli_inform(message = c("Columns with {.val {oxphos_name}} and/or {.val {apop_name}} already present in meta.data slot.",
"i" = "Overwriting those columns as {.code overwrite = TRUE.}")
)
}
# Set default assay
assay <- assay %||% DefaultAssay(object = seurat_object)
# Retrieve gene lists
msigdb_gene_list <- Retrieve_MSigDB_Lists(species = species)
oxphos_found <- Feature_PreCheck(object = seurat_object, features = msigdb_gene_list[["oxphos"]])
apop_found <- Feature_PreCheck(object = seurat_object, features = msigdb_gene_list[["apop"]])
dna_repair_found <- Feature_PreCheck(object = seurat_object, features = msigdb_gene_list[["dna_repair"]])
# Add mito and ribo columns
if (length(x = oxphos_found) > 0) {
seurat_object[[oxphos_name]] <- PercentageFeatureSet(object = seurat_object, features = oxphos_found, assay = assay)
}
if (length(x = apop_found) > 0) {
seurat_object[[apop_name]] <- PercentageFeatureSet(object = seurat_object, features = apop_found, assay = assay)
}
if (length(x = dna_repair_found) > 0) {
seurat_object[[dna_repair_name]] <- PercentageFeatureSet(object = seurat_object, features = dna_repair_found, assay = assay)
}
# Log Command
seurat_object <- LogSeuratCommand(object = seurat_object)
# return final object
return(seurat_object)
}
#' Add IEG Gene List Percentages
#'
#' Adds percentage of counts from IEG genes from mouse and human.
#'
#' @param seurat_object object name.
#' @param species Species of origin for given Seurat Object. Only accepted species are: mouse, human (name or abbreviation).
#' @param ieg_name name to use for the new meta.data column containing percent IEG gene counts. Default is "percent_ieg".
#' @param assay Assay to use (default is the current object default assay).
#' @param overwrite Logical. Whether to overwrite existing meta.data columns. Default is FALSE meaning that
#' function will abort if columns with the name provided to `ieg_name` is present in meta.data slot.
#'
#' @return Seurat object
#'
#' @import cli
#'
#' @keywords internal
#'
#' @noRd
#'
Add_IEG_Seurat <- function(
seurat_object,
species,
ieg_name = "percent_ieg",
assay = NULL,
overwrite = FALSE
) {
# Accepted species names
accepted_names <- list(
Mouse_Options = c("Mouse", "mouse", "Ms", "ms", "Mm", "mm"),
Human_Options = c("Human", "human", "Hu", "hu", "Hs", "hs"),
Marmoset_Options = c("Marmoset", "marmoset", "CJ", "Cj", "cj", NA),
Zebrafish_Options = c("Zebrafish", "zebrafish", "DR", "Dr", "dr", NA),
Rat_Options = c("Rat", "rat", "RN", "Rn", "rn", NA),
Drosophila_Options = c("Drosophila", "drosophila", "DM", "Dm", "dm", NA),
Macaque_Options = c("Macaque", "macaque", "Rhesus", "macaca", "mmulatta", NA)
)
if (!species %in% unlist(x = accepted_names)) {
cli_inform(message = "The supplied species ({.field {species}}) is not currently supported.")
}
# Check Seurat
Is_Seurat(seurat_object = seurat_object)
# Overwrite check
if (ieg_name %in% colnames(x = [email protected])) {
if (isFALSE(x = overwrite)) {
cli_abort(message = c("Column with {.val {ieg_name}} already present in meta.data slot.",
"i" = "*To run function and overwrite column set parameter {.code overwrite = TRUE} or change respective {.code ieg_name}*")
)
}
cli_inform(message = c("Column with {.val {ieg_name}} already present in meta.data slot.",
"i" = "Overwriting those column as {.code overwrite = TRUE.}")
)
}
# Set default assay
assay <- assay %||% DefaultAssay(object = seurat_object)
# Retrieve gene lists
ieg_gene_list <- Retrieve_IEG_Lists(species = species)
ieg_found <- Feature_PreCheck(object = seurat_object, features = ieg_gene_list[["ieg"]])
# Add mito and ribo columns
if (length(x = ieg_found) > 0) {
seurat_object[[ieg_name]] <- PercentageFeatureSet(object = seurat_object, features = ieg_found, assay = assay)
}
# Log Command
seurat_object <- LogSeuratCommand(object = seurat_object)
# return final object
return(seurat_object)
}
#' Return default QC features
#'
#' Returns default QC features full names when provided with shortcut name.
#'
#' @param seurat_object object name.
#' @param features vector of features to check against defaults.
#' @param print_defaults return the potential accepted default values.
#'
#' @return list of found and not found features
#'
#' @import cli
#'
#' @keywords internal
#'
#' @noRd
#'
Return_QC_Defaults <- function(
seurat_object,
features,
print_defaults = FALSE
) {
# default values
feature_defaults <- list(
feature = c("features", "Features", "genes", "Genes"),
UMIs = c("counts", "Counts", "umis", "umi", "UMI", "UMIs", "UMIS"),
mito = c("mito", "Mito"),
ribo = c("ribo", "Ribo"),
mito_ribo = c("mito_ribo", "Mito_Ribo"),
complexity = c("complexity", "Complexity"),
top_pct = c("top_pct", "Top_Pct"),
IEG = c("ieg", "IEG"),
OXPHOS = c("oxphos", "OXPHOS"),
APOP = c("apop", "Apop"),
DNA_Repair = c("dna_repair", "DNA_Repair")
)
# if print is TRUE
if (isTRUE(x = print_defaults)) {
cli_inform(message = c("Accepted default values are:",
"{.field {glue_collapse_scCustom(input_string = unlist(feature_defaults), and = TRUE)}}"))
stop_quietly()
}
# Assign values
if (any(features %in% feature_defaults[[1]])) {
default1 <- "nFeature_RNA"
} else {
default1 <- NULL
}
if (any(features %in% feature_defaults[[2]])) {
default2 <- "nCount_RNA"
} else {
default2 <- NULL
}
if (any(features %in% feature_defaults[[3]])) {
default3 <- "percent_mito"
} else {
default3 <- NULL
}
if (any(features %in% feature_defaults[[4]])) {
default4 <- "percent_ribo"
} else {
default4 <- NULL
}
if (any(features %in% feature_defaults[[5]])) {
default5 <- "percent_mito_ribo"
} else {
default5 <- NULL
}
if (any(features %in% feature_defaults[[6]])) {
default6 <- "log10GenesPerUMI"
} else {
default6 <- NULL
}
if (any(features %in% feature_defaults[[7]])) {
default7 <- grep(pattern = "percent_top", x = colnames(x = [email protected]), value = TRUE)
} else {
default7 <- NULL
}
if (any(features %in% feature_defaults[[8]])) {
default8 <- "percent_ieg"
} else {
default8 <- NULL
}
if (any(features %in% feature_defaults[[9]])) {
default9 <- "percent_oxphos"
} else {
default9 <- NULL
}
if (any(features %in% feature_defaults[[10]])) {
default10 <- "percent_apop"
} else {
default10 <- NULL
}
if (any(features %in% feature_defaults[[11]])) {
default11 <- "percent_dna_repair"
} else {
default11 <- NULL
}
# All found defaults
all_found_defaults <- c(default1, default2, default3, default4, default5, default6, default7, default8, default9, default10, default11)
# get not found features
not_found_defaults <- features[!features %in% unlist(feature_defaults)]
# create return list
feat_list <- list(
found_defaults = all_found_defaults,
not_found_defaults = not_found_defaults
)
# return feature list
return(feat_list)
}
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#################### GENERAL HELPERS ####################
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' Calculate the percentage of a vector above some threshold
#'
#' @param x Vector of values
#' @param threshold Threshold to use when calculating percentage
#'
#' @return Returns the percentage of `x` values above the given threshold
#'
#' @author Satija Lab & all co-Authors of Seurat Package
#' @references See Utilities.R in source code of Seurat \url{https://github.com/satijalab/seurat/blob/master/R/utilities.R} (Licence: GPL-3).
#'
#' @note modified from Seurat version to return a percentage instead of proportion/decimal as part of `Percent_Expressing` function. To be replaced following next Seurat version update.
#'
#' @keywords internal
#'
#' @noRd
#'
PercentAbove_Seurat <- function(x, threshold) {
return((length(x = x[x > threshold]) / length(x = x))*100)
}
#' Extract delimiter information from a string.
#'
#' Parses a string (usually a cell name) and extracts fields based on a delimiter
#'
#' @param string String to parse.
#' @param field Integer(s) indicating which field(s) to extract. Can be a vector multiple numbers.
#' @param delim Delimiter to use, set to underscore by default.
#'
#' @return A new string, that parses out the requested fields, and (if multiple), rejoins them with the same delimiter
#'
#' @references See Utilities.R in source code of Seurat \url{https://github.com/satijalab/seurat/blob/master/R/utilities.R} (Licence: GPL-3).
#'
#' @keywords internal
#'
#' @noRd
#'
ExtractField <- function(string, field = 1, delim = "_") {
fields <- as.numeric(x = unlist(x = strsplit(x = as.character(x = field), split = ",")))
if (length(x = fields) == 1) {
return(strsplit(x = string, split = delim)[[1]][field])
}
return(paste(strsplit(x = string, split = delim)[[1]][fields], collapse = delim))
}
#' Calculate the middle value between two numbers
#'
#' @param min Lower value.
#' @param max Higher value.
#'
#' @return Returns number in middle of two provided values.
#'
#' @references Code to calculate middle value from: adapted from: \url{https://stackoverflow.com/a/54147509/15568251}.
#' Renamed and wrapped into function by Samuel Marsh.
#'
#' @keywords internal
#'
#' @noRd
#'
Middle_Number <- function(
min,
max
) {
min_max <- c(min, max)
middle <- min_max[-length(min_max)] + diff(min_max) / 2
return(middle)
}
#' Symmetrical setdiff
#'
#' tests for differences between two vectors symmetrically.
#'
#' @param x first vector to test
#' @param y second vector to test
#'