-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.R
1313 lines (793 loc) · 44.7 KB
/
server.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
server <- function(input, output){
library(tibble)
library(dplyr)
library(ggpubr)
library(gtools)
library(shinyWidgets)
values <- reactiveValues()
# Max allowed size of the for the uploaded csv files
options(shiny.maxRequestSize=75*1024^2)
# Setup a brush table function to show more info about data points in top 5 plots
output$brushtop5 <- renderTable({
validate(
need(input$brushtop5, "Draw a rectangle around data points for further information")
)
brushedPoints(top5_df_brush, input$brushtop5)
}, striped = T, hover = T, spacing = "s")
# Disable download button until the execution
shinyjs::disable("download_res")
shinyjs::disable("download_top5")
observeEvent(analyzed_df(), {
shinyjs::enable("download_res")
shinyjs::enable("download_top5")
})
################################################################################################################################
# Define conditional dynamic file upload prompted when user selects "Custom" as reference data
output$ui_sel_ref <- renderUI ({
if (input$sel_reference == "Custom"){
fileInput("ref_file", "Upload custom reference file",
multiple = F,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv"))
}
})
# Select reference cell subsets to analyze
output$ui_sel_subsets <- renderUI ({
if(input$sel_reference == "ImmGen (mouse)"){
pickerInput("cell_subsets", "Select reference cell subsets to include in analysis",
multiple = T,
choices = c("B cell", "Basophil", "DC", "Eosinophil", "gd-T cell",
"Granulocyte", "ILC-1", "ILC-2", "ILC-3", "Macrophage",
"Mast cell", "Monocyte", "NK cell", "NKT cell", "Pre-B cell",
"Pre-T cell", "Stem-Progenitor", "Stromal", "T cell", "Treg"),
selected = c("B cell", "Basophil", "DC", "Eosinophil", "gd-T cell",
"Granulocyte", "ILC-1", "ILC-2", "ILC-3", "Macrophage",
"Mast cell", "Monocyte", "NK cell", "NKT cell", "Pre-B cell",
"Pre-T cell", "Stem-Progenitor", "Stromal", "T cell", "Treg"),
options = list(`actions-box` = TRUE))
} else if(input$sel_reference == "Presorted RNAseq (mouse)"){
pickerInput("cell_subsets", "Select reference cell subsets to analyze",
multiple = T,
choices = c("Adipocyte", "Astrocyte", "B cell", "Cardiomyocyte",
"Dendritic cell", "Endothelial cell", "Epithelial cell", "Erythrocyte",
"Fibroblast", "Granulocyte" , "Hepatocyte" , "Macrophage" ,
"Microglia", "Monocyte", "Neurons", "NK cell",
"Oligodendrocyte", "T cell"),
selected = c("Adipocyte", "Astrocyte", "B cell", "Cardiomyocyte",
"Dendritic cell", "Endothelial cell", "Epithelial cell", "Erythrocyte",
"Fibroblast", "Granulocyte" , "Hepatocyte" , "Macrophage" ,
"Microglia", "Monocyte", "Neurons", "NK cell",
"Oligodendrocyte", "T cell"),
options = list(`actions-box` = TRUE))
} else if(input$sel_reference == "Blueprint-Encode (human)"){
pickerInput("cell_subsets", "Select reference cell subsets to analyze",
multiple = T,
choices = c("Adipocyte", "B cell" , "CD4+ T cell", "CD8+ T cell",
"Chondrocyte", "DC", "Endothelial cell", "Eosinophil" ,
"Epithelial cell", "Erythrocyte", "Fibroblast" , "HSC" ,
"Keratinocyte", "Macrophage", "Melanocyte" , "Mesangial cell",
"Monocyte", "Myocyte", "Neurons", "Neutrophil",
"NK cell" , "Pericyte", "Skeletal muscle", "Smooth muscle" ),
selected = c("Adipocyte", "B cell" , "CD4+ T cell", "CD8+ T cell",
"Chondrocyte", "DC", "Endothelial cell", "Eosinophil" ,
"Epithelial cell", "Erythrocyte", "Fibroblast" , "HSC" ,
"Keratinocyte", "Macrophage", "Melanocyte" , "Mesangial cell",
"Monocyte", "Myocyte", "Neurons", "Neutrophil",
"NK cell" , "Pericyte", "Skeletal muscle", "Smooth muscle" ),
options = list(`actions-box` = TRUE))
} else if(input$sel_reference == "Primary Cell Atlas (human)"){
pickerInput("cell_subsets", "Select reference cell subsets to analyze",
multiple = T,
choices = c( "Astrocyte", "B cell", "BM" ,
"Chondrocyte" , "CMP" , "DC",
"Embryonic stem cell", "Endothelial cell", "Epithelial cell",
"Erythroblast", "Fibroblast" , "Gametocyte" ,
"GMP" , "Hepatocyte", "HSC" ,
"iPS cell" , "Keratinocyte" , "Macrophage" ,
"MEP" , "Monocyte", "MSC" ,
"Myelocyte" , "Neuroepithelial cell", "Neurons" ,
"Neutrophil", "NK cell" , "Osteoblast" ,
"Platelet", "Pre-B cell" , "Pro-B cell" ,
"Pro-Myelocyte" , "Smooth muscle cell", "T cell" ,
"Tissue stem cell"),
selected = c("Astrocyte", "B cell", "BM" ,
"Chondrocyte" , "CMP" , "DC",
"Embryonic stem cell", "Endothelial cell", "Epithelial cell",
"Erythroblast", "Fibroblast" , "Gametocyte" ,
"GMP" , "Hepatocyte", "HSC" ,
"iPS cell" , "Keratinocyte" , "Macrophage" ,
"MEP" , "Monocyte", "MSC" ,
"Myelocyte" , "Neuroepithelial cell", "Neurons" ,
"Neutrophil", "NK cell" , "Osteoblast" ,
"Platelet", "Pre-B cell" , "Pro-B cell" ,
"Pro-Myelocyte" , "Smooth muscle cell", "T cell" ,
"Tissue stem cell"),
options = list(`actions-box` = TRUE))
} else if(input$sel_reference == "DICE (human)"){
pickerInput("cell_subsets", "Select reference cell subsets to analyze",
multiple = T,
choices = c("CD4+ T cell", "CD8+ T cell", "NK cell", "B cell", "Monocyte"),
selected = c("CD4+ T cell", "CD8+ T cell", "NK cell", "B cell", "Monocyte"),
options = list(`actions-box` = TRUE))
} else if(input$sel_reference == "Hematopoietic diff (human)"){
pickerInput("cell_subsets", "Select reference cell subsets to analyze",
multiple = T,
choices = c("B cell" , "Basophil" , "CD4+ T cell" , "CD8+ T cell" , "CMP" ,
"Dendritic cell", "Eosinophil" , "Erythroid cell", "GMP" , "Granulocyte" ,
"HSC", "Megakaryocyte" , "MEP" , "Monocyte", "NK cell",
"NK T cell"),
selected = c("B cell" , "Basophil" , "CD4+ T cell" , "CD8+ T cell" , "CMP" ,
"Dendritic cell", "Eosinophil" , "Erythroid cell", "GMP" , "Granulocyte" ,
"HSC", "Megakaryocyte" , "MEP" , "Monocyte", "NK cell",
"NK T cell"),
options = list(`actions-box` = TRUE))
} else if(input$sel_reference == "Presorted RNAseq (human)"){
pickerInput("cell_subsets", "Select reference cell subsets to analyze",
multiple = T,
choices = c( "B cell" , "Basophil", "CD4+ T cell", "CD8+ T cell" , "Dendritic cell",
"MAIT-gdT" , "Monocyte", "Neutrophil" , "NK cell", "Progenitor" ),
selected = c( "B cell" , "Basophil", "CD4+ T cell", "CD8+ T cell" , "Dendritic cell",
"MAIT-gdT" , "Monocyte", "Neutrophil" , "NK cell", "Progenitor" ),
options = list(`actions-box` = TRUE))
} else {}
})
# Create a dynamic UI object to enable upload dialog upon selection of 'Custom'
output$ui_sel_ref_annot <- renderUI ({
if (input$sel_reference == "Custom"){
fileInput("annot_file", "Upload custom annotation file (optional)",
multiple = F,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv"))
}
})
# Show example input file format for logFC dot product method
output$sample_data_file_logfc <- renderImage({
list(src = "data/cluster_expr_IMG.png",
alt = "Sample SCseq data",
width=500)
}, deleteFile = F)
# Show example input file format for reference data set
output$sample_reference_file <- renderImage({
list(src = "data/ref_data_IMG.png",
alt = "Sample reference data",
width=500)
}, deleteFile = F)
# Show example input file format for reference annotation
output$sample_annotation_file <- renderImage({
list(src = "data/ref_annot_IMG.png",
alt = "Sample annotation data",
width=500)
}, deleteFile = F)
################################################################################################################################
# Read uploaded differential expression file
user_data <- reactive({
inFile <- input$data_file
if(grepl("logFC", input$comp_method)){
if(input$example_data == T){
dat <- read.csv("data/Trimmed_cluster_signatures.csv",
check.names = T,
strip.white = T,
stringsAsFactors = F)
} else {
validate(
need(input$data_file != "", "Please upload a data set or use example data")
)
# Make sure the file type is correct
validate(
need(tools::file_ext(inFile$name) %in% c(
'text/csv',
'text/comma-separated-values',
'text/plain',
'csv'
), "Wrong File Format try again!"))
dat <- read.csv(inFile$datapath, check.names=TRUE, strip.white = TRUE, stringsAsFactors = F)
validate(
need(!anyNA(colnames(dat)), "Unnamed column is found in the uploaded data. Please fix this problem and try again. When manually preparing dataframes, sometimes, empty-looking columns may have 'invisible' data associated with them. Try deleting these columns using a spreadsheet software or re-make a clean csv file.")
)
# Make sure the column names are proper for correct subsetting
validate(
need(
{if(sum(Reduce("|", lapply(c("logfc", "gene", "cluster"), grepl, colnames(dat), ignore.case=T))) == 3) TRUE else FALSE},
"Formatting error: Make sure your dataset contains at least three columns named 'logfc', 'gene', and 'cluster' (Capitalization of the column names is not important. Data can have other columns which will be ignored). Did you mean to use correlation methods instead?"
)
)
}
# Define column names to allow flexibility in case and close matches in column names
gene_column <<- grep("gene", colnames(dat), ignore.case = T, value = T)
logFC_column <<- grep("logfc", colnames(dat), ignore.case = T, value = T)
cluster_column <<- grep("cluster", colnames(dat), ignore.case = T, value = T)
req(input$run)
# Convert gene symbols to lower case letters to allow mouse-vs-human comparisons
dat[,gene_column] <- tolower(dat[,gene_column])
dat
} else {
if(is.null(inFile) & input$example_data == T){
dat <- readRDS("data/til_scseq_exprs_mean_subset.rds")
req(input$run)
gene_column <<- grep("gene", colnames(dat), ignore.case = T, value = T)
dat
} else {
validate(
need(input$data_file != "", "Please upload a data set or use example data")
)
# Make sure the file type is correct
validate(
need(tools::file_ext(inFile$name) %in% c(
'text/csv',
'text/comma-separated-values',
'text/plain',
'csv'
), "Wrong File Format. File needs to be a .csv file."))
dat <- read.csv(inFile$datapath, check.names=TRUE, strip.white = TRUE, stringsAsFactors = F)
validate(
need(!anyNA(colnames(dat)), "Unnamed column is found in the uploaded data. Please fix this problem and try again. When manually preparing dataframes, sometimes, empty-looking columns may have 'invisible' data associated with them. Try deleting these columns using a spreadsheet software or re-make a clean csv file.")
)
# Make sure the column names are proper for correct subsetting
validate(
need(
{if(sum(Reduce("|", lapply(c("logfc", "gene"), grepl, colnames(dat), ignore.case=T))) == 1) TRUE else FALSE},
"Formatting error: Make sure your dataset contains a column named 'gene' (capitalization is not important, duplicate gene column is not allowed). Other columns should contain average gene expression per cluster. Did you mean to use logFC comparison methods?"
)
)
req(input$run)
gene_column <<- grep("gene", colnames(dat), ignore.case = T, value = T)
dat[,gene_column] <- tolower(dat[,gene_column])
dat <- dat[!duplicated(dat[,gene_column]),]
dat
}
}
}) # close user_data reactive object
################################################################################################################################
# Delay slider update
var_filt <- reactive({input$var_filter})
#############################################################################################################################
# Keep selected reference subsets in analysis
subsets_in_analysis <- reactive({
if(input$sel_reference != "Custom"){
select_positions <- which(reference_annotation()[, "reference_cell_type"] %in% input$cell_subsets)
# Bump positions by one (the corresponding column number due to first column being gene name in ref)
select_positions <- select_positions + 1
# Append position 1 to select gene column
select_positions <- c(1, select_positions) # make this prettier by using name matching (no ordering is needed)
values$subset_num <- length(select_positions)-1
select_positions
} else if(input$sel_reference == "Custom"){
# expand on this to enable factor level matching from custom files
select_positions <- dim(ref_data())[2]
values$subset_num <- length(select_positions)-1
select_positions
}
})
################################################################################################################################
# Read reference dataset
ref_data <- eventReactive(input$run, {
# if(grepl("logFC", input$comp_method)){
if(input$sel_reference == "ImmGen (mouse)"){
# Read main expression dataframe
reference <- as.data.frame(readRDS("data/immgen.rds"))
# Name of the gene column in reference data
ref_gene_column <<- grep("gene", colnames(reference), ignore.case = T, value = T)
} else if(input$sel_reference == "Presorted RNAseq (mouse)"){
# Read main expression dataframe
reference <- as.data.frame(readRDS("data/mmrnaseq_expr.rds"))
# Name of the gene column in reference data
ref_gene_column <<- grep("gene", colnames(reference), ignore.case = T, value = T)
} else if(input$sel_reference == "Blueprint-Encode (human)"){
# Read main expression dataframe
reference <- as.data.frame(readRDS("data/blueprint_expr.rds"))
# Name of the gene column in reference data
ref_gene_column <<- grep("gene", colnames(reference), ignore.case = T, value = T)
} else if(input$sel_reference == "Primary Cell Atlas (human)"){
# Read main expression dataframe
reference <- as.data.frame(readRDS("data/hpca_expr.rds"))
# Name of the gene column in reference data
ref_gene_column <<- grep("gene", colnames(reference), ignore.case = T, value = T)
} else if(input$sel_reference == "DICE (human)"){
# Read main expression dataframe
reference <- as.data.frame(readRDS("data/dice_expr.rds"))
# Name of the gene column in reference data
ref_gene_column <<- grep("gene", colnames(reference), ignore.case = T, value = T)
} else if(input$sel_reference == "Hematopoietic diff (human)"){
# Read main expression dataframe
reference <- as.data.frame(readRDS("data/hema_expr.rds"))
# Name of the gene column in reference data
ref_gene_column <<- grep("gene", colnames(reference), ignore.case = T, value = T)
} else if(input$sel_reference == "Presorted RNAseq (human)"){
# Read main expression dataframe
reference <- as.data.frame(readRDS("data/hsrnaseq_expr.rds"))
# Name of the gene column in reference data
ref_gene_column <<- grep("gene", colnames(reference), ignore.case = T, value = T)
} else {
validate(
need(input$ref_file != "", "Please upload reference data set")
)
in_refFile <- input$ref_file
# Make sure the file type is correct
validate(
need(tools::file_ext(in_refFile$name) %in% c(
'text/csv',
'text/comma-separated-values',
'text/plain',
'csv'
), "Wrong File Format. File needs to be a .csv file."))
reference <- read.csv(in_refFile$datapath,
check.names=TRUE,
strip.white = TRUE,
stringsAsFactors = F)
ref_gene_column <<- grep("gene", colnames(reference), ignore.case = T, value = T)
}
reference[,ref_gene_column] <- tolower(reference[,ref_gene_column])
# Report dims of unfiltered reference dataframe
values$ref_rows <- dim(reference)[1]
values$ref_cols <- dim(reference)[2]-1
# Subset the reference to the relevant subsets in analysis
reference <- reference[, subsets_in_analysis()]
# Apply quantile filtering
if(var_filt() != 100){
var_vec <- apply(reference[, !colnames(reference) %in% ref_gene_column], 1, var, na.rm=T)
keep_var <- quantile(var_vec, probs = 1-var_filt()/100, na.rm = T)
keep_genes <- var_vec >= keep_var
# Return reference data frame
reference <- as.data.frame(reference[keep_genes, ])
} else {
keep_genes <- rep(T, dim(as.data.frame(reference))[1])
reference <- as.data.frame(reference)
}
if(grepl("logFC", input$comp_method)){
# Calculate row means for each gene (mean expression across the reference cell types)
gene_avg <- rowMeans(reference[, !colnames(reference) %in% ref_gene_column])
# Calculate the ratio of gene expression in a given cell type compared
# to the average of the whole cohort. Calculate log (natural) fold change
# Linear data
# reference_ratio <- log1p(sweep(reference[,!colnames(reference) %in% ref_gene_column], 1, FUN="/", gene_avg))
# Log scale data
reference_ratio <- sweep(reference[,!colnames(reference) %in% ref_gene_column], 1, FUN="-", gene_avg)
# Combine gene names and the log fold change in one data frame
reference <- cbind(tolower(reference[,ref_gene_column]), reference_ratio)
colnames(reference)[1] <- ref_gene_column
}
# else {
#
# if(input$sel_reference == "ImmGen (mouse)"){
#
# reference <- readRDS("data/immgen.rds")
#
# ref_gene_column <<- grep("gene", colnames(reference), ignore.case = T, value = T)
#
# } else if (input$sel_reference == "Custom"){
#
# in_refFile <- input$ref_file
#
# reference <- read.csv(in_refFile$datapath, check.names=TRUE, strip.white = TRUE, stringsAsFactors = F)
#
# ref_gene_column <<- grep("gene", colnames(reference), ignore.case = T, value = T)
#
# reference[,ref_gene_column] <- tolower(reference[,ref_gene_column])
#
#
# }
#
# }
# # Subset the reference to the relevant subsets in analysis
# reference <- reference[, subsets_in_analysis()]
# # Report dims of unfiltered reference dataframe
#
# values$ref_rows <- dim(reference)[1]
# values$ref_cols <- dim(reference)[2]-1
# # Apply quantile filtering
# if(var_filt() != 100){
#
# var_vec <- apply(reference[, !colnames(reference) %in% ref_gene_column], 1, var, na.rm=T)
#
# keep_var <- quantile(var_vec, probs = 1-var_filt()/100, na.rm = T)
#
# keep_genes <- var_vec >= keep_var
#
# # Return reference data frame
# refdat <- as.data.frame(reference[keep_genes, ])
#
# } else {
# keep_genes <- rep(T, dim(as.data.frame(reference))[1])
# refdat <- as.data.frame(reference)
# }
# Report gene number after filtering
values$keep_genes <- sum(keep_genes)
reference
})
################################################################################################################################
# Read immgen annotation file for explanations of cell types
reference_annotation <- eventReactive(input$run, {
if(input$sel_reference == "ImmGen (mouse)"){
# This file was obtained from the ImmGen website source code that runs the analysis modules.
# It features detailed information about the cellular origins and sorting methods and makes the results
# understandable by providing long names and descriptions to abbreviated cell types
ref_annotation <-readRDS("data/immgen_annot.rds")
ref_annotation
} else if(input$sel_reference == "Presorted RNAseq (mouse)"){
ref_annotation <- readRDS("data/mmrnaseq_samples.rds")
ref_annotation
} else if(input$sel_reference == "Blueprint-Encode (human)"){
ref_annotation <- readRDS("data/blueprint_samples.rds")
ref_annotation
} else if(input$sel_reference == "Primary Cell Atlas (human)"){
ref_annotation <- readRDS("data/hpca_samples.rds")
ref_annotation
} else if(input$sel_reference == "DICE (human)"){
ref_annotation <- readRDS("data/dice_samples.rds")
ref_annotation
} else if(input$sel_reference == "Hematopoietic diff (human)"){
ref_annotation <- readRDS("data/hema_samples.rds")
ref_annotation
} else if(input$sel_reference == "Presorted RNAseq (human)"){
ref_annotation <- readRDS("data/hsrnaseq_samples.rds")
ref_annotation
} else if(input$sel_reference == "Custom"){
annotFile <- input$annot_file
ref_annotation <- read.csv(annotFile$datapath, check.names=TRUE, strip.white = TRUE, stringsAsFactors = F)
ref_annotation
}
})
################################################################################################################################
# Define a reactive cluster object that will store cluster information
clusters <- reactive({
if(grepl("logFC", input$comp_method)){
# Get the clusters and sort them in incrementing order from cluster column
# This is needed to generate results per cluster
gtools::mixedsort(
levels(
as.factor(
pull(user_data(), grep("cluster", x = colnames(user_data()), ignore.case = T, value = T)
)
)
)
)
} else {
gtools::mixedsort(
levels(
as.factor(
colnames(user_data())[!grepl("gene", colnames(user_data()), ignore.case = T)]
)
)
)}
}) # close clusters reactive object
################################################################################################################################
# Compare user_data against reference file
analyzed_df <- eventReactive(input$run, {
req(input$run)
if(grepl("logFC", input$comp_method)){
if(input$comp_method == "logFC dot product"){
# Initiate a master data frame to store the results
master_df <- data.frame()
# Indicate progress of the calculations
withProgress(message = 'Analysis in progress', value = 0, {
values$current_cluster <- character()
values$genes_in_analysis <- numeric()
# Iterate over clusters to calculate a distinct identity score for each reference cell type
for (i in clusters()) {
values$current_cluster <- c(values$current_cluster, i)
# Increment the progress bar, and update the detail text.
incProgress(1/length(clusters()), detail = paste("Analyzing cluster", i))
# Subset on the cluster in iteration
sel_clst <- user_data() %>%
filter(!!rlang::sym(cluster_column) == i) %>%
select_(.dots = c(gene_column, logFC_column))
genes_in_analysis <- length(intersect(sel_clst[, gene_column], ref_data()[, ref_gene_column]))
values$genes_in_analysis <- c(values$genes_in_analysis, genes_in_analysis)
# Merge SCseq cluster log FC value with immgen log FC for shared genes
merged <- merge(sel_clst, ref_data(), by.x = gene_column, by.y = ref_gene_column)
# Calculate a scoring matrix by multiplying log changes of clusters and immgen cells
reference_scoring <- data.frame(apply(merged[,3:dim(merged)[2]],2,function(x){x*merged[,2]}), check.names = FALSE)
# Calculate the aggregate score of each immgen cell type by adding
score_sum <- colSums(reference_scoring)
# Store identity scores in a data frame
df <- data.frame(identity_score = score_sum)
df <- rownames_to_column(df, var="reference_id")
# Merge results with annotation data for informative graphs
if(input$sel_reference != "Custom"){ #ImmGen (previously)
df <- left_join(df, reference_annotation(), by=c("reference_id" = "short_name"))
} else if (input$sel_reference == "Custom" & !is.null(input$annot_file)){
df <- left_join(df, reference_annotation(), by=c("reference_id" = "short_name"))
} else if(input$sel_reference == "Custom" & is.null(input$annot_file)){
# If annotation file is not provided for custom analyses, the table will be populated
# with "Upload annotation file" reminder
df$reference_cell_type <- rep("Upload annotation file", dim(ref_data())[2]-1)
df$short_name <- colnames(ref_data())[!colnames(ref_data()) %in% ref_gene_column]
df$long_name <- rep("Upload annotation file", dim(ref_data())[2]-1)
df$description <- rep("Upload annotation file", dim(ref_data())[2]-1)
}
# Store cluster information in a column
df$cluster <- i
# Add confidence-of-prediction calculations here and append to the df
# Calculate the mean and standard deviation of the aggregate scores per reference cell type
mean_score_sum <- mean(df$identity_score)
score_sum_sd <- sd(df$identity_score)
# Calculate the distance of the identity score from population mean (how many std devs apart?)
df$z_score <- (df$identity_score - mean_score_sum)/score_sum_sd
# Calculate the proportion of the genes changing in the same direction between unknown cluster and reference cell type
df$percent_pos_correlation <- {
ngenes <- dim(reference_scoring)[1]
pos_corr_vector <- numeric()
for(i in 1:dim(reference_scoring)[2]){
# Calculate number of genes positively correlated (upregulated or downregulated in both unk cluster and reference)
pos_cor <- ( sum(reference_scoring[, i] > 0) / ngenes ) * 100
pos_corr_vector <- c(pos_corr_vector, pos_cor)
} #close for loop
pos_corr_vector
} # close expression
# Add calculation results under the master data frame to have a composite results file
master_df <- rbind(master_df,df)
} # close for loop that iterates over clusters
})
# Return results into reactive object
master_df
# If correlation method is used, algorithm follows the steps below to calculate a
# correlation coefficient for each cluster and reference cell type pairs.
} else { ################### Correlation methods ###########################################################
# Initiate master data frame to store results
master_df <- data.frame()
# Print progress
withProgress(message = 'Analysis in progress', value = 0, {
# Pass comp_method variable from the user-selected radio buttons
if(input$comp_method == "logFC Spearman") comp_method = "spearman" else if(input$comp_method == "logFC Pearson") comp_method = "pearson"
values$current_cluster <- character()
values$genes_in_analysis <- numeric()
# Iterate analysis for each cluster. The loop below will calculate a distinct correlation
# coefficient for each cluster-reference cell pairs
for (i in clusters()) {
# Increment the progress bar, and update the detail text.
incProgress(1/length(clusters()), detail = paste("Analyzing cluster", i))
trim_dat <- user_data() %>%
filter(!!rlang::sym(cluster_column) == i)
dat_genes <- trim_dat[gene_column] %>% pull() %>% as.character
ref_genes <- ref_data()[ref_gene_column] %>% pull() %>% as.character
common_genes <- intersect(dat_genes, ref_genes)
values$genes_in_analysis <- c(values$genes_in_analysis, length(common_genes))
values$current_cluster <- c(values$current_cluster, i)
trim_dat <- trim_dat %>%
filter(!!rlang::sym(gene_column) %in% common_genes) %>%
arrange(!!rlang::sym(gene_column)) %>%
select(- !!rlang::sym(gene_column))
trim_ref <- ref_data() %>%
filter(!!rlang::sym(ref_gene_column) %in% common_genes) %>%
arrange(!!rlang::sym(ref_gene_column)) %>%
select(- !!rlang::sym(ref_gene_column))
# Calculate correlation between the the cluster (single column in trimmed input data) and each of the
# reference cell subsets (columns of the trimmed reference data)
cor_df <- cor(trim_dat[logFC_column], trim_ref, method = comp_method)
# Store results in a data frame
df <- data.frame(identity_score = cor_df[1,])
df <- rownames_to_column(df, var="reference_id")
# Combine results with reference annotations
if(input$sel_reference != "Custom"){ #ImmGen (previously)
df <- left_join(df, reference_annotation(), by=c("reference_id" = "short_name"))
} else if (input$sel_reference == "Custom" & !is.null(input$annot_file)){
df <- left_join(df, reference_annotation(), by=c("reference_id" = "short_name"))
} else if(input$sel_reference == "Custom" & is.null(input$annot_file)){
# Fill in with reminder if annotation file is not updated
df$reference_cell_type <- rep("Upload annotation file", dim(ref_data())[2]-1)
df$short_name <- colnames(ref_data())[!colnames(ref_data()) %in% ref_gene_column]
df$long_name <- rep("Upload annotation file", dim(ref_data())[2]-1)
df$description <- rep("Upload annotation file", dim(ref_data())[2]-1)
}
# Store cluster information in a column
df$cluster <- i
# Add confidence-of-prediction calculations here and append to the df
# Calculate the mean and standard deviation of the aggregate scores per reference cell type
mean_cor_coeff <- mean(df$identity_score)
cor_coeff_sd <- sd(df$identity_score)
# Calculate the distance of the identity score from population mean (how many std devs apart?)
df$z_score <- (df$identity_score - mean_cor_coeff)/cor_coeff_sd
# Add all the results to the master data frame
master_df <- rbind(master_df,df)
} # close for loop that iterates over clusters
}) # Close with progress
# Return master data frame to reactive object
master_df
}
} else {
values$genes_in_analysis <- numeric()
values$current_cluster <- character()
dat_genes <- user_data()[gene_column] %>% pull() %>% as.character
ref_genes <- ref_data()[ref_gene_column] %>% pull() %>% as.character
common_genes <- intersect(dat_genes, ref_genes)
values$genes_in_analysis <- c(values$genes_in_analysis, length(common_genes))
trim_dat <- user_data() %>%
filter(!!rlang::sym(gene_column) %in% common_genes) %>%
arrange(!!rlang::sym(gene_column)) %>%
select_(.dots = paste0("-", gene_column))
trim_ref <- ref_data() %>%
filter(!!rlang::sym(ref_gene_column) %in% common_genes) %>%
arrange(!!rlang::sym(ref_gene_column)) %>%
select_(.dots = paste0("-", ref_gene_column))
master_df <- data.frame()
withProgress(message = 'Analysis in progress', value = 0, {
if(input$comp_method == "Spearman (all genes)") comp_method = "spearman" else if(input$comp_method == "Pearson (all genes)") comp_method = "pearson"
for (i in clusters()) {
values$current_cluster <- c(values$current_cluster, i)
# Increment the progress bar, and update the detail text.
incProgress(1/length(clusters()), detail = paste("Analyzing cluster", i))
cor_df <- cor(trim_dat[i], trim_ref, method = comp_method)
df <- data.frame(identity_score = cor_df[1,])
df <- rownames_to_column(df, var="reference_id")
if(input$sel_reference != "Custom"){ #ImmGen (previously)
df <- left_join(df, reference_annotation(), by=c("reference_id" = "short_name"))
} else if (input$sel_reference == "Custom" & !is.null(input$annot_file)){
df <- left_join(df, reference_annotation(), by=c("reference_id" = "short_name"))