-
Notifications
You must be signed in to change notification settings - Fork 19
/
Object_Conversion.R
1524 lines (1288 loc) · 53.2 KB
/
Object_Conversion.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
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#################### CONVERT TO LIGER ####################
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' Create liger object from one Seurat Object
#'
#' @param group.by Variable in meta data which contains variable to split data by, (default is "orig.ident").
#' To use split layers in Assay5 set `group.by = "layers"`.
#' @param layers_name name of meta.data column used to split layers if setting `group.by = "layers"`.
#' @param assay Assay containing raw data to use, (default is "RNA").
#' @param remove_missing logical, whether to remove missing genes with no counts when converting to
#' LIGER object (default is FALSE).
#' @param renormalize logical, whether to perform normalization after LIGER object creation (default is TRUE).
#' @param use_seurat_var_genes logical, whether to transfer variable features from Seurat object to
#' new LIGER object (default is FALSE).
#' @param use_seurat_dimreduc logical, whether to transfer dimensionality reduction coordinates from
#' Seurat to new LIGER object (default is FALSE).
#' @param reduction Name of Seurat reduction to transfer if `use_seurat_dimreduc = TRUE`.
#' @param keep_meta logical, whether to transfer columns in Seurat meta.data slot to LIGER cell.data
#' slot (default is TRUE).
#' @param verbose logical, whether to print status messages during object conversion (default is TRUE).
#'
#'
#' @references modified and enhanced version of `rliger::seuratToLiger`.
#'
#' @method as.LIGER Seurat
#'
#' @concept object_conversion
#'
#' @import cli
#' @import Seurat
#' @importFrom dplyr left_join join_by select any_of
#' @importFrom magrittr "%>%"
#' @importFrom tibble rownames_to_column column_to_rownames
#' @importFrom utils packageVersion
#'
#' @export
#' @rdname as.LIGER
#'
#' @examples
#' \dontrun{
#' liger_object <- as.LIGER(x = seurat_object)
#' }
#'
as.LIGER.Seurat <- function(
x,
group.by = "orig.ident",
layers_name = NULL,
assay = "RNA",
remove_missing = FALSE,
renormalize = TRUE,
use_seurat_var_genes = FALSE,
use_seurat_dimreduc = FALSE,
reduction = NULL,
keep_meta = TRUE,
verbose = TRUE,
...
) {
# temp liger version check
if (packageVersion(pkg = 'rliger') > "1.0.1") {
cli_abort(message = c("Liger functionality is currently restricted to rliger v1.0.1 or lower.",
"i" = "Functionality with rliger v2+ is currently in development."))
}
# Check Seurat
Is_Seurat(seurat_object = x)
# Run update to ensure functionality
if (isTRUE(x = verbose)) {
cli_inform(message = c("*" = "Checking Seurat object validity"))
}
x <- suppressMessages(UpdateSeuratObject(object = x))
# Check & Set Assay
if (!assay %in% Assays(object = x)) {
cli_abort(message = "Provided assay {.field {assay}} not found in Seurat object.")
}
if (assay != DefaultAssay(object = x)) {
cli_inform(c("*" = "Changing object DefaultAssay from ({.field {DefaultAssay(object = x)}}) to provided assay ({.field {assay}})."))
DefaultAssay(x) <- assay
}
# Check Assay5 for multiple layers
count_layers <- Layers(object = x, search = "counts", assay = assay)
# check split_name
if (group.by == "layers" && is.null(x = layers_name)) {
cli_abort(message = "When {.code group.by = 'layers'} please suppy name of meta.data column used to split layers to {.code layers_name}.")
}
if (!layers_name %in% colnames(x@meta.data)) {
cli_abort(message = "The value provided to {.code layers_name} ({.field {layers_name}}) was not found in object meta.data.")
}
if (isTRUE(x = Assay5_Check(seurat_object = x, assay = assay))) {
if (length(x = count_layers) > 1 && group.by != "layers") {
cli_abort(message = c("Multiple layers containing raw counts present ({.field {count_layers[1]}}, {.field {count_layers[2]}}, {.field ...}) and value provided to {.code group.by} is not {.val layers}.",
"i" = "To group LIGER object by assay layers please set {.code group.by = 'layers'}."
))
}
}
# Check meta data
if (group.by != "layers") {
group.by <- Meta_Present(object = x, meta_col_names = group.by, omit_warn = FALSE, print_msg = FALSE, return_none = TRUE)[[1]]
# stop if none found
if (length(x = group.by) == 0) {
cli_abort(message = c("{.code group.by} was not found.",
"i" = "No column found in object meta.data named: {.val {group.by}}.")
)
}
}
if (isTRUE(x = verbose)) {
cli_inform(message = c("*" = "Creating LIGER object."))
}
# Set ident to grouping variable
if (length(x = count_layers) == 1) {
Idents(object = x) <- group.by
}
# Check & Pull other relevant data
if (isTRUE(x = use_seurat_dimreduc)) {
# Extract default reduction
reduction <- reduction %||% DefaultDimReduc(object = x)
if (!reduction %in% Reductions(object = x)) {
cli_abort(message = "Provided reduction: {.field {reduction}} was not found in Seurat Object.")
}
reduc_coords <- Embeddings(object = x, reduction = reduction)
}
if (isTRUE(x = use_seurat_var_genes)) {
var_genes <- VariableFeatures(object = x)
if (!length(x = var_genes) > 0) {
cli_abort(message ="{.code use_seurat_var_genes = TRUE}, but no variable features found in Seurat object.")
}
}
# Get raw data & cells
if (length(x = count_layers) == 1) {
raw_data_full <- LayerData(object = x, layer = count_layers)
cells_per_dataset <- CellsByIdentities(object = x)
# Split data by dataset
idents <- names(x = cells_per_dataset)
raw_data_list <- lapply(idents, function(x){
raw_data_full[, cells_per_dataset[[x]]]
})
names(raw_data_list) <- idents
}
# If multiple layers
if (length(x = count_layers) > 1) {
raw_data_list <- lapply(count_layers, function (i){
counts <- LayerData(object = x, layer = i)
})
new_names <- gsub(pattern = "counts.", replacement = "", x = count_layers)
names(raw_data_list) <- new_names
}
# Create LIGER Object
liger_object <- rliger::createLiger(raw.data = raw_data_list, remove.missing = remove_missing)
if (isTRUE(x = renormalize)) {
if (isTRUE(x = verbose)) {
cli_inform(message = c("*" = "Normalizing data."))
}
liger_object <- rliger::normalize(object = liger_object, remove.missing = remove_missing)
}
# Add var genes
if (isTRUE(x = use_seurat_var_genes)) {
liger_object@var.genes <- var_genes
}
# Add dim reduc
if (isTRUE(x = use_seurat_dimreduc)) {
liger_object@tsne.coords <- reduc_coords
# Add new attribute to enable more accurate scCustomize plotting
attributes(liger_object)$reduction_key <- reduction
}
# transfer meta
if (isTRUE(x = keep_meta)) {
# extract meta data from liger object
seurat_meta <- Fetch_Meta(object = x)
# remove meta data values already transferred
seurat_meta <- seurat_meta %>%
select(-any_of(c("nFeature_RNA", "nCount_RNA"))) %>%
rownames_to_column("barcodes")
# pull current liger meta
liger_meta <- Fetch_Meta(object = liger_object) %>%
rownames_to_column("barcodes")
# join meta
new_liger_meta <- suppressMessages(left_join(x = liger_meta, y = seurat_meta, by = join_by("barcodes"))) %>%
column_to_rownames("barcodes")
# Add to LIGER object
liger_object@cell.data <- new_liger_meta
}
# return object
return(liger_object)
}
#' Create liger object from one Seurat Object
#'
#' @param group.by Variable in meta data which contains variable to split data by, (default is "orig.ident").
#' @param dataset_names optional, vector of names to use for naming datasets.
#' @param assay Assay containing raw data to use, (default is "RNA").
#' @param remove_missing logical, whether to remove missing genes with no counts when converting to
#' LIGER object (default is FALSE).
#' @param renormalize logical, whether to perform normalization after LIGER object creation (default is TRUE).
#' @param use_seurat_var_genes logical, whether to transfer variable features from Seurat object to
#' new LIGER object (default is FALSE).
#' @param var_genes_method how variable genes should be selected from Seurat objects if `use_seurat_var_genes = TRUE`. Can be either "intersect" or "union", (default is "intersect").
#' @param keep_meta logical, whether to transfer columns in Seurat meta.data slot to LIGER cell.data
#' slot (default is TRUE).
#' @param verbose logical, whether to print status messages during object conversion (default is TRUE).
#'
#'
#' @method as.LIGER list
#'
#' @concept object_conversion
#'
#' @import cli
#' @import Seurat
#' @importFrom dplyr left_join join_by select any_of bind_rows union intersect
#' @importFrom magrittr "%>%"
#' @importFrom stringr str_to_lower
#' @importFrom tibble rownames_to_column column_to_rownames
#' @importFrom utils packageVersion
#'
#' @export
#' @rdname as.LIGER
#'
#' @examples
#' \dontrun{
#' liger_object <- as.LIGER(x = seurat_object_list)
#' }
#'
as.LIGER.list <- function(
x,
group.by = "orig.ident",
dataset_names = NULL,
assay = "RNA",
remove_missing = FALSE,
renormalize = TRUE,
use_seurat_var_genes = FALSE,
var_genes_method = "intersect",
keep_meta = TRUE,
verbose = TRUE,
...
) {
# temp liger version check
if (packageVersion(pkg = 'rliger') > "1.0.1") {
cli_abort(message = c("Liger functionality is currently restricted to rliger v1.0.1 or lower.",
"i" = "Functionality with rliger v2+ is currently in development."))
}
# Check Seurat
seurat_check <- unlist(lapply(x, function(x) {
inherits(x = x, what = "Seurat")
}))
if (any(seurat_check) == "FALSE") {
cli_abort(message = "One or more of items in list are not Seurat Objects.")
}
# Run update to ensure functionality
if (isTRUE(x = verbose)) {
cli_inform(message = c("*" = "Checking Seurat object validity"))
}
x <- lapply(x, function(y) {
suppressMessages(UpdateSeuratObject(object = y))
})
# Check Assay5 for multiple layers
for (i in x) {
if (isTRUE(x = Assay5_Check(seurat_object = i, assay = assay))) {
layers_check <- Layers(object = i, search = "counts")
if (length(x = layers_check) > 1) {
cli_abort(message = c("Multiple layers containing raw counts present {.field {head(x = layers_check, n = 2)}}.",
"i" = "Please run {.code JoinLayers} before converting to LIGER object."))
}
}
}
# Check meta data
if (is.null(x = dataset_names)) {
for (j in x) {
group.by <- Meta_Present(object = j, meta_col_names = group.by, omit_warn = FALSE, print_msg = FALSE, return_none = TRUE)[[1]]
# stop if none found
if (length(x = group.by) == 0) {
cli_abort(message = c("{.code group.by} was not found in all objects in list.",
"i" = "All objects must contain column in meta.data named: {.val {group.by}}.")
)
}
}
} else {
if (length(x = dataset_names) != length(x = x)) {
cli_abort(message = "The number of {.code dataset_names} provided ({.field {length(x = dataset_names)}}) does not match number of Seurat objects in list ({.field {length(x = x)}}).")
}
}
# Check & Set Assay
for (k in x) {
if (!assay %in% Assays(object = k)) {
cli_abort(message = "Provided assay {.field {assay}} not found in all Seurat objects in list.")
}
}
for (l in x) {
if (assay != DefaultAssay(object = l)) {
cli_inform(c("*" = "Changing object DefaultAssay from ({.field {DefaultAssay(object = x)}}) to provided assay ({.field {assay}})."))
DefaultAssay(l) <- assay
}
}
if (isTRUE(x = use_seurat_var_genes)) {
var_genes <- lapply(x, function(z) {
VariableFeatures(object = z)
})
for (m in var_genes) {
if (!length(x = m) > 0) {
cli_abort(message ="{.code use_seurat_var_genes = TRUE}, but not all objects in list have variable features.")
}
}
var_genes_method <- str_to_lower(string = var_genes_method)
if (!var_genes_method %in% c("intersect", "union")) {
cli_abort(message = "{.code var_genes_method} must be either {.field intersect} or {.field union}.")
}
if (var_genes_method == "union") {
var_genes <- reduce(var_genes, function(a, b) {
union(x = a, y = b)})
}
if (var_genes_method == "intersect") {
var_genes <- reduce(var_genes, function(c, d) {
intersect(x = c, y = d)
})
}
}
# Get raw data & cells
raw_data_list <- lapply(x, function(e){
counts_layer <- Layers(object = e, search = "counts")
LayerData(object = e, layer = counts_layer)
})
if (is.null(x = dataset_names)) {
group_names <- unique(x = sapply(1:length(x = x), function(f) {
obj_meta <- Fetch_Meta(object = x[[f]]) %>%
select(any_of(group.by)) %>%
unique()
if (length(x = obj_meta) > 1) {
cli_abort(message = c("Some objects in list have multiple values within the {.field {group.by}} column.",
"i" = "This column must only contain one value per object"))
}
}))
if (length(x = group_names) != length(x = x)) {
cli_abort(message = c("Some objects in list have the same values within the {.field {group.by}} column.",
"i" = "All objects must have unique value in this column."))
}
names(x = raw_data_list) <- group_names
} else {
names(x = raw_data_list) <- dataset_names
}
# Create LIGER Object
if (isTRUE(x = verbose)) {
cli_inform(message = c("*" = "Creating LIGER object."))
}
liger_object <- rliger::createLiger(raw.data = raw_data_list, remove.missing = remove_missing)
if (isTRUE(x = renormalize)) {
if (isTRUE(x = verbose)) {
cli_inform(message = c("*" = "Normalizing data."))
}
liger_object <- rliger::normalize(object = liger_object, remove.missing = remove_missing)
}
# Add var genes
if (isTRUE(x = use_seurat_var_genes)) {
liger_object@var.genes <- var_genes
}
# transfer meta
if (isTRUE(x = keep_meta)) {
# extract meta data from seurat object
seurat_meta <- lapply(x, function(g) {
obj_meta <- Fetch_Meta(object = g) %>%
select(-any_of(c("nFeature_RNA", "nCount_RNA")))
})
seurat_meta <- bind_rows(seurat_meta) %>%
rownames_to_column("barcodes")
# pull current liger meta
liger_meta <- Fetch_Meta(object = liger_object) %>%
rownames_to_column("barcodes")
# join meta
new_liger_meta <- suppressMessages(left_join(x = liger_meta, y = seurat_meta, by = join_by("barcodes"))) %>%
column_to_rownames("barcodes")
# Add to LIGER object
liger_object@cell.data <- new_liger_meta
}
# return object
return(liger_object)
}
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#################### CONVERT TO SEURAT ####################
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' Convert objects to \code{Seurat} objects
#'
#' Merges raw.data and scale.data of object, and creates Seurat object with these values along with slots
#' containing dimensionality reduction coordinates, iNMF factorization, and cluster assignments.
#' Supports Seurat V3/4 and V4.
#'
#' Stores original dataset identity by default in new object metadata if dataset names are passed
#' in nms. iNMF factorization is stored in dim.reduction object with key "iNMF".
#'
#' @param x \code{liger} object.
#' @param nms By default, labels cell names with dataset of origin (this is to account for cells in
#' different datasets which may have same name). Other names can be passed here as vector, must have
#' same length as the number of datasets. (default names(H)).
#' @param renormalize Whether to log-normalize raw data using Seurat defaults (default TRUE).
#' @param use.liger.genes Whether to carry over variable genes (default TRUE).
#' @param by.dataset Include dataset of origin in cluster identity in Seurat object (default FALSE).
#' @param keep_meta logical. Whether to transfer additional metadata (nGene/nUMI/dataset already transferred)
#' to new Seurat Object. Default is TRUE.
#' @param reduction_label Name of dimensionality reduction technique used. Enables accurate transfer
#' or name to Seurat object instead of defaulting to "tSNE".
#' @param seurat_assay Name to set for assay in Seurat Object. Default is "RNA".
#' @param assay_type what type of Seurat assay to create in new object (Assay vs Assay5).
#' Default is NULL which will default to the current user settings.
#' See \code{\link{Convert_Assay}} parameter `convert_to` for acceptable values.
#' @param add_barcode_names logical, whether to add dataset names to the cell barcodes when
#' creating Seurat object, default is FALSE.
#' @param barcode_prefix logical, if `add_barcode_names = TRUE` should the names be added as
#' prefix to current cell barcodes/names or a suffix (default is TRUE; prefix).
#' @param barcode_cell_id_delimiter The delimiter to use when adding dataset id to barcode
#' prefix/suffix. Default is "_".
#' @param ... unused.
#'
#' @return Seurat object with raw.data, scale.data, reduction_label, iNMF, and ident slots set.
#'
#' @references Original function is part of LIGER package \url{https://github.com/welch-lab/liger} (Licence: GPL-3).
#' Function was modified for use in scCustomize with additional parameters/functionality.
#'
#' @method as.Seurat liger
#' @return Seurat object.
#'
#' @concept object_conversion
#'
#' @import cli
#' @import Matrix
#' @import Seurat
#' @importFrom dplyr any_of pull select
#' @importFrom magrittr "%>%"
#' @importFrom methods as new
#' @importFrom utils packageVersion
#'
#' @export
#' @rdname as.Seurat
#'
#' @examples
#' \dontrun{
#' seurat_object <- as.Seurat(x = liger_object)
#' }
#'
as.Seurat.liger <- function(
x,
nms = names(x@H),
renormalize = TRUE,
use.liger.genes = TRUE,
by.dataset = FALSE,
keep_meta = TRUE,
reduction_label = "UMAP",
seurat_assay = "RNA",
assay_type = NULL,
add_barcode_names = FALSE,
barcode_prefix = TRUE,
barcode_cell_id_delimiter = "_",
...
) {
# temp liger version check
if (packageVersion(pkg = 'rliger') > "1.0.1") {
cli_abort(message = c("Liger functionality is currently restricted to rliger v1.0.1 or lower.",
"i" = "Functionality with rliger v2+ is currently in development."))
}
if (is.null(x = reduction_label)) {
cli_abort(message = c("{.code reduction_label} parameter was not set.",
"*" = "LIGER objects do not store name of dimensionality reduction technique used.",
"i" = "In order to retain proper labels in Seurat object please set {.code reduction_label} to {.val tSNE}, {.val UMAP}, {.val etc}."))
}
# Adjust name for dimreduc key
key_name <- paste0(reduction_label, "_")
# adjust raw data slot if needed
if (!inherits(x = x@raw.data[[1]], what = 'dgCMatrix')) {
x@raw.data <- lapply(x@raw.data, as, Class = "CsparseMatrix")
}
# check assay_type is ok
if (!is.null(x = assay_type)) {
# Check accepted
accepted_V3 <- c("Assay", "assay", "V3", "v3")
accepted_V5 <- c("Assay5", "assay5", "V5", "v5")
if (!convert_to %in% c(accepted_V5, accepted_V3)) {
cli_abort(message = c("Value provided to {.code convert_to} ({.field {convert_to}}) was not accepted value.",
"i" = "Accepted values to convert to V3/4 are: {.field {accepted_V3}}",
"i" = "Accepted values to convert to V5 are: {.field {accepted_V5}}"))
}
# set assay value
if (convert_to %in% accepted_V5) {
if (packageVersion(pkg = 'Seurat') < "5") {
cli_abort(message = "Seurat version must be v5.0.0 or greater to create To create Assay5.")
}
convert_to <- "v5"
}
if (convert_to %in% accepted_V3) {
convert_to <- "v3"
}
}
# merge raw data
if (isTRUE(x = add_barcode_names)) {
raw.data <- Merge_Sparse_Data_All(matrix_list = x@raw.data, add_cell_ids = nms, prefix = barcode_prefix, cell_id_delimiter = barcode_cell_id_delimiter)
} else {
raw.data <- Merge_Sparse_Data_All(matrix_list = x@raw.data)
}
# create object
new.seurat <- CreateSeuratObject(counts = raw.data, assay = seurat_assay)
# normalize data
if (isTRUE(x = renormalize)) {
new.seurat <- Seurat::NormalizeData(new.seurat)
} else {
if (length(x = x@norm.data) > 0) {
if (isTRUE(x = add_barcode_names)) {
norm.data <- Merge_Sparse_Data_All(matrix_list = x@norm.data, add_cell_ids = nms, prefix = barcode_prefix, cell_id_delimiter = barcode_cell_id_delimiter)
} else {
norm.data <- Merge_Sparse_Data_All(matrix_list = x@norm.data)
}
new.seurat <- SetAssayData(object = new.seurat, layer = "data", slot = "data", new.data = norm.data)
}
}
if (length(x = x@var.genes) > 0 && isTRUE(x = use.liger.genes)) {
VariableFeatures(object = new.seurat) <- x@var.genes
}
if (length(x = x@scale.data) > 0) {
scale.data <- t(x = Reduce(rbind, x@scale.data))
colnames(x = scale.data) <- colnames(x = raw.data)
new.seurat <- SetAssayData(object = new.seurat, layer = "scale.data", slot = "scale.data", new.data = scale.data)
}
if (all(dim(x = x@W) > 0) && all(dim(x = x@H.norm) > 0)) {
inmf.loadings <- t(x = x@W)
rinmf.loadings <- inmf.loadings
dimnames(x = inmf.loadings) <- list(x@var.genes,
paste0("iNMF_", seq_len(ncol(inmf.loadings))))
dimnames(x = rinmf.loadings) <- list(x@var.genes,
paste0("rawiNMF_", seq_len(ncol(rinmf.loadings))))
inmf.embeddings <- x@H.norm
rinmf.embeddings <- do.call(what = 'rbind', args = x@H)
dimnames(x = inmf.embeddings) <- list(unlist(x = lapply(x@scale.data, rownames), use.names = FALSE),
paste0("iNMF_", seq_len(ncol(inmf.loadings))))
dimnames(x = rinmf.embeddings) <- list(unlist(x = lapply(x@scale.data, rownames), use.names = FALSE),
paste0("rawiNMF_", seq_len(ncol(x = inmf.loadings))))
inmf.obj <- CreateDimReducObject(
embeddings = inmf.embeddings,
loadings = inmf.embeddings,
assay = seurat_assay,
global = TRUE,
key = "iNMF_"
)
new.seurat[["iNMF"]] <- inmf.obj
rinmf.obj <- CreateDimReducObject(
embeddings = rinmf.embeddings,
loadings = rinmf.loadings,
key = "rawiNMF_",
global = TRUE,
assay = seurat_assay
)
}
if (all(dim(x = x@tsne.coords) > 0)) {
dimreduc.embeddings <- x@tsne.coords
dimnames(x = dimreduc.embeddings) <- list(rownames(x@H.norm),
paste0(key_name, 1:2))
dimreduc.obj <- CreateDimReducObject(
embeddings = dimreduc.embeddings,
assay = seurat_assay,
global = TRUE,
key = key_name
)
new.seurat[[reduction_label]] <- dimreduc.obj
}
new.seurat$orig.ident <- x@cell.data$dataset
idents <- x@clusters
if (length(x = idents) == 0 || isTRUE(x = by.dataset)) idents <- x@cell.data$dataset
Idents(object = new.seurat) <- idents
# transfer meta
if (isTRUE(x = keep_meta)) {
# extract meta data from liger object
liger_meta <- Fetch_Meta(object = x)
# remove meta data values already transferred
liger_meta <- liger_meta %>%
select(-any_of(c("nUMI", "nGene", "dataset")))
# extract meta data names
meta_names <- colnames(x = liger_meta)
# add meta data to new seurat object
for (meta_var in meta_names){
meta_transfer <- liger_meta %>%
pull(meta_var)
names(x = meta_transfer) <- colnames(x = new.seurat)
new.seurat <- AddMetaData(object = new.seurat,
metadata = meta_transfer,
col.name = meta_var)
}
}
if (!is.null(x = assay_type)) {
options_list <- options()
if (options_list$Seurat.object.assay.version != convert_to) {
new.seurat <- Convert_Assay(seurat_object = new.seurat, convert_to = convert_to)
}
}
# return object
return(new.seurat)
}
#' Create a Seurat object containing the data from a liger object `r lifecycle::badge("soft-deprecated")`
#'
#' Merges raw.data and scale.data of object, and creates Seurat object with these values along with
#' tsne.coords, iNMF factorization, and cluster assignments. Supports Seurat V2 and V3.
#'
#' Stores original dataset identity by default in new object metadata if dataset names are passed
#' in nms. iNMF factorization is stored in dim.reduction object with key "iNMF".
#'
#' @param liger_object \code{liger} object.
#' @param nms By default, labels cell names with dataset of origin (this is to account for cells in
#' different datasets which may have same name). Other names can be passed here as vector, must have
#' same length as the number of datasets. (default names(H)).
#' @param renormalize Whether to log-normalize raw data using Seurat defaults (default TRUE).
#' @param use.liger.genes Whether to carry over variable genes (default TRUE).
#' @param by.dataset Include dataset of origin in cluster identity in Seurat object (default FALSE).
#' @param keep_meta logical. Whether to transfer additional metadata (nGene/nUMI/dataset already transferred)
#' to new Seurat Object. Default is TRUE.
#' @param reduction_label Name of dimensionality reduction technique used. Enables accurate transfer
#' or name to Seurat object instead of defaulting to "tSNE".
#' @param seurat_assay Name to set for assay in Seurat Object. Default is "RNA".
#' @param assay_type what type of Seurat assay to create in new object (Assay vs Assay5).
#' Default is NULL which will default to the current user settings.
#' See \code{\link{Convert_Assay}} parameter `convert_to` for acceptable values.
#' @param add_barcode_names logical, whether to add dataset names to the cell barcodes when
#' creating Seurat object, default is FALSE.
#' @param barcode_prefix logical, if `add_barcode_names = TRUE` should the names be added as
#' prefix to current cell barcodes/names or a suffix (default is TRUE; prefix).
#' @param barcode_cell_id_delimiter The delimiter to use when adding dataset id to barcode
#' prefix/suffix. Default is "_".
#'
#' @return Seurat object with raw.data, scale.data, reduction_label, iNMF, and ident slots set.
#'
#' @references Original function is part of LIGER package \url{https://github.com/welch-lab/liger} (Licence: GPL-3).
#' Function was slightly modified for use in scCustomize with keep.meta parameter. Also posted as
#' PR to liger GitHub.
#'
#' @import cli
#' @import Matrix
#' @importFrom dplyr any_of pull select
#' @importFrom magrittr "%>%"
#' @importFrom methods as new
#' @importFrom utils packageVersion
#'
#' @export
#'
#' @concept object_conversion
#'
#' @examples
#' \dontrun{
#' seurat_object <- Liger_to_Seurat(liger_object = LIGER_OBJ, reduction_label = "UMAP")
#' }
Liger_to_Seurat <- function(
liger_object,
nms = names(liger_object@H),
renormalize = TRUE,
use.liger.genes = TRUE,
by.dataset = FALSE,
keep_meta = TRUE,
reduction_label = "UMAP",
seurat_assay = "RNA",
assay_type = NULL,
add_barcode_names = FALSE,
barcode_prefix = TRUE,
barcode_cell_id_delimiter = "_"
) {
lifecycle::deprecate_soft(when = "2.1.0",
what = "Liger_to_Seurat()",
with = "as.Seurat()",
details = c("i" = "Please adjust code now to prepare for full deprecation.")
)
if (is.null(x = reduction_label)) {
cli_abort(message = c("{.code reduction_label} parameter was not set.",
"*" = "LIGER objects do not store name of dimensionality reduction technique used.",
"i" = "In order to retain proper labels in Seurat object please set {.code reduction_label} to {.val tSNE}, {.val UMAP}, {.val etc}."))
}
# Adjust name for dimreduc key
key_name <- paste0(reduction_label, "_")
# adjust raw data slot if needed
if (!inherits(x = liger_object@raw.data[[1]], what = 'dgCMatrix')) {
liger_object@raw.data <- lapply(liger_object@raw.data, as, Class = "CsparseMatrix")
}
# check assay_type is ok
if (!is.null(x = assay_type)) {
# Check accepted
accepted_V3 <- c("Assay", "assay", "V3", "v3")
accepted_V5 <- c("Assay5", "assay5", "V5", "v5")
if (!convert_to %in% c(accepted_V5, accepted_V3)) {
cli_abort(message = c("Value provided to {.code convert_to} ({.field {convert_to}}) was not accepted value.",
"i" = "Accepted values to convert to V3/4 are: {.field {accepted_V3}}",
"i" = "Accepted values to convert to V5 are: {.field {accepted_V5}}"))
}
# set assay value
if (convert_to %in% accepted_V5) {
if (packageVersion(pkg = 'Seurat') < "5") {
cli_abort(message = "Seurat version must be v5.0.0 or greater to create To create Assay5.")
}
convert_to <- "v5"
}
if (convert_to %in% accepted_V3) {
convert_to <- "v3"
}
}
# merge raw data
if (isTRUE(x = add_barcode_names)) {
raw.data <- Merge_Sparse_Data_All(matrix_list = liger_object@raw.data, add_cell_ids = nms, prefix = barcode_prefix, cell_id_delimiter = barcode_cell_id_delimiter)
} else {
raw.data <- Merge_Sparse_Data_All(matrix_list = liger_object@raw.data)
}
# create object
new.seurat <- CreateSeuratObject(counts = raw.data, assay = seurat_assay)
# normalize data
if (isTRUE(x = renormalize)) {
new.seurat <- Seurat::NormalizeData(new.seurat)
} else {
if (length(x = liger_object@norm.data) > 0) {
if (isTRUE(x = add_barcode_names)) {
norm.data <- Merge_Sparse_Data_All(matrix_list = liger_object@norm.data, add_cell_ids = nms, prefix = barcode_prefix, cell_id_delimiter = barcode_cell_id_delimiter)
} else {
norm.data <- Merge_Sparse_Data_All(matrix_list = liger_object@norm.data)
}
new.seurat <- SetAssayData(object = new.seurat, layer = "data", slot = "data", new.data = norm.data)
}
}
if (length(x = liger_object@var.genes) > 0 && isTRUE(x = use.liger.genes)) {
VariableFeatures(object = new.seurat) <- liger_object@var.genes
}
if (length(x = liger_object@scale.data) > 0) {
scale.data <- t(x = Reduce(rbind, liger_object@scale.data))
colnames(x = scale.data) <- colnames(x = raw.data)
new.seurat <- SetAssayData(object = new.seurat, layer = "scale.data", slot = "scale.data", new.data = scale.data)
}
if (all(dim(x = liger_object@W) > 0) && all(dim(x = liger_object@H.norm) > 0)) {
inmf.loadings <- t(x = liger_object@W)
rinmf.loadings <- inmf.loadings
dimnames(x = inmf.loadings) <- list(liger_object@var.genes,
paste0("iNMF_", seq_len(ncol(inmf.loadings))))
dimnames(x = rinmf.loadings) <- list(liger_object@var.genes,
paste0("rawiNMF_", seq_len(ncol(rinmf.loadings))))
inmf.embeddings <- liger_object@H.norm
rinmf.embeddings <- do.call(what = 'rbind', args = liger_object@H)
dimnames(x = inmf.embeddings) <- list(unlist(x = lapply(liger_object@scale.data, rownames), use.names = FALSE),
paste0("iNMF_", seq_len(ncol(inmf.loadings))))
dimnames(x = rinmf.embeddings) <- list(unlist(x = lapply(liger_object@scale.data, rownames), use.names = FALSE),
paste0("rawiNMF_", seq_len(ncol(x = inmf.loadings))))
inmf.obj <- CreateDimReducObject(
embeddings = inmf.embeddings,
loadings = inmf.embeddings,
assay = seurat_assay,
global = TRUE,
key = "iNMF_"
)
new.seurat[["iNMF"]] <- inmf.obj
rinmf.obj <- CreateDimReducObject(
embeddings = rinmf.embeddings,
loadings = rinmf.loadings,
key = "rawiNMF_",
global = TRUE,
assay = seurat_assay
)
}
if (all(dim(x = liger_object@tsne.coords) > 0)) {
dimreduc.embeddings <- liger_object@tsne.coords
dimnames(x = dimreduc.embeddings) <- list(rownames(liger_object@H.norm),
paste0(key_name, 1:2))
dimreduc.obj <- CreateDimReducObject(
embeddings = dimreduc.embeddings,
assay = seurat_assay,
global = TRUE,
key = key_name
)
new.seurat[[reduction_label]] <- dimreduc.obj
}
new.seurat$orig.ident <- liger_object@cell.data$dataset
idents <- liger_object@clusters
if (length(x = idents) == 0 || isTRUE(x = by.dataset)) idents <- liger_object@cell.data$dataset
Idents(object = new.seurat) <- idents
# transfer meta
if (isTRUE(x = keep_meta)) {
# extract meta data from liger object
liger_meta <- Fetch_Meta(object = liger_object)
# remove meta data values already transferred
liger_meta <- liger_meta %>%
select(-any_of(c("nUMI", "nGene", "dataset")))
# extract meta data names
meta_names <- colnames(x = liger_meta)
# add meta data to new seurat object
for (meta_var in meta_names){
meta_transfer <- liger_meta %>%
pull(meta_var)
names(x = meta_transfer) <- colnames(x = new.seurat)
new.seurat <- AddMetaData(object = new.seurat,
metadata = meta_transfer,
col.name = meta_var)
}
}
if (!is.null(x = assay_type)) {
options_list <- options()
if (options_list$Seurat.object.assay.version != convert_to) {
new.seurat <- Convert_Assay(seurat_object = new.seurat, convert_to = convert_to)
}
}
# return object
return(new.seurat)
}
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#################### CONVERT TO ANNDATA ####################
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#' Create & Save Anndata Object
#'
#' @param file_path directory file path and/or file name prefix. Defaults to current wd.
#' @param file_name file name.
#' @param assay Assay containing data to use, (default is "RNA").
#' @param main_layer the layer of data to become default layer in anndata object (default is "data").
#' @param other_layers other data layers to transfer to anndata object (default is "counts").
#' @param transer_dimreduc logical, whether to transfer dimensionality reduction coordinates from
#' Seurat to anndata object (default is TRUE).
#' @param verbose logical, whether to print status messages during object conversion (default is TRUE).
#'
#'
#' @references Seurat version modified and enhanced version of `sceasy::seurat2anndata` (sceasy package: \url{https://github.com/cellgeni/sceasy}; License: GPL-3. Function has additional checks and supports Seurat V3 and V5 object structure.
#'
#' @method as.anndata Seurat
#'
#' @concept object_conversion
#'
#' @import cli
#' @import Seurat
#' @importFrom stringr str_to_lower
#'
#' @export
#' @rdname as.anndata
#'
#' @examples
#' \dontrun{
#' as.anndata(x = seurat_object, file_path = "/folder_name", file_name = "anndata_converted.h5ad")
#' }
#'
as.anndata.Seurat <- function(
x,
file_path,
file_name,
assay = "RNA",
main_layer = "data",
other_layers = "counts",
transer_dimreduc = TRUE,
verbose = TRUE,
...
) {
# Check reticulate installed
reticulate_check <- is_installed(pkg = "reticulate")
if (isFALSE(x = reticulate_check)) {
cli_abort(message = c(
"Please install the {.val reticulate} package to use {.code as.anndata}.",
"i" = "This can be accomplished with the following commands: ",
"----------------------------------------",
"{.field `install.packages({symbol$dquote_left}reticulate{symbol$dquote_right})`}",
"----------------------------------------"
))
}
# Set file_path before path check if current dir specified as opposed to leaving set to NULL
if (!is.null(x = file_path) && file_path == "") {
file_path <- NULL
}
# Check file path is valid
if (!is.null(x = file_path)) {