-
Notifications
You must be signed in to change notification settings - Fork 4
/
reactives.R
1666 lines (1469 loc) · 51.1 KB
/
reactives.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
# reactive values ------------------------------------------------------------------
inputFileStats <- reactiveValues(
stats = NULL
)
# store cell groups that are defined on the fly using the modular 2D plot
groupNames <- reactiveValues(
namesDF = data.frame()
)
# colors for samples
sampleCols <- reactiveValues(
colPal = allowedColors
)
# colors for clusters
clusterCols <- reactiveValues(
colPal = allowedColors
)
# Here, we store projections that are created during the session. These can be selections of cells or other values that
# are not possible to precalculate.
sessionProjections <- reactiveValues(
prjs = data.frame()
)
# inputDataFunc ----
# loads singleCellExperiment
# only counts, rowData, and colData are used. Everything else needs to be recomputed
inputDataFunc <- function(inFile) {
"!DEBUG start shiny"
debugme::debug("plot render start", pkg = ".")
if (DEBUG) cat(file = stderr(), "inputDataFunc started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "inputDataFunc")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "inputDataFunc")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("inputDataFunc", id = "inputDataFunc", duration = NULL)
}
stats <- tibble(.rows = length(inFile$datapath))
stats$names <- inFile$name
stats$nFeatures <- 0
stats$nCells <- 0
#
cat(file = stderr(), paste("reading", inFile$name[1], "\n"))
fp <- inFile$datapath[1]
# fp ="scEx.Rds"
# fp ="../scShinyHubData/patty1A.v2.Rds"
# a bit of cleanup
rm(list = c("scEx", "scEx_log", "featureData"))
fpLs <- load(fp)
scExFound <- FALSE
for (varName in fpLs) {
if ("SingleCellExperiment" %in% class(get(varName))) {
scEx <- get(varName)
scExFound <- TRUE
}
}
if (!scExFound) {
return(NULL)
}
fdAll <- rowData(scEx)
pdAll <- colData(scEx)
exAll <- assays(scEx)[["counts"]]
stats[1, "nFeatures"] <- nrow(fdAll)
stats[1, "nCells"] <- nrow(pdAll)
# read multiple files
if (length(inFile$datapath) > 1) {
for (fpIdx in 2:length(inFile$datapath)) {
cat(file = stderr(), paste("reading", inFile$name[fpIdx], "\n"))
fp <- inFile$datapath[fpIdx]
fpLs <- load(fp)
if (!"scEx" %in% fpLs) {
next()
}
fdIdx <- intersect(rownames(fdAll), rownames(rowData(scEx)))
# if (length(fdIdx) != nrow(fd)) {
# cat(file = stderr(), "Houston, there is a problem with the features\n")
# }
# fd <- featuredata[fdIdx, ]
fdAll <- fdAll[fdIdx, ]
pd1 <- colData(scEx)
ex1 <- assays(scEx)[["counts"]][fdIdx, ]
if (sum(rownames(pdAll) %in% rownames(pd1)) > 0) {
cat(file = stderr(), "Houston, there are cells with the same name\n")
rownames(pd1) <- paste0(rownames(pd1), "_", fpIdx)
pdAll <- rbind(pdAll, pd1)
colnames(ex1) <- rownames(pd1)
} else {
pdAll <- rbind(pdAll, pd1)
}
stats[fpIdx, "nFeatures"] <- nrow(fd)
stats[fpIdx, "nCells"] <- nrow(pd1)
exAll <- Matrix::cbind2(exAll[fdIdx, ], ex1)
}
}
exAll <- as(exAll, "dgTMatrix")
scEx <- SingleCellExperiment(
assay = list(counts = exAll),
colData = pdAll,
rowData = fdAll
)
cat(stderr(), "Loaded")
dataTables <- list()
featuredata <- rowData(scEx)
# handle different extreme cases for the symbol column (already encountered)
if (is.factor(featuredata$symbol)) {
if (levels(featuredata$symbol) == "NA") {
featuredata$symbol = toupper(rownames(featuredata))
rowData(scEx) <- featuredata
}
}
if ("symbol" %in% colnames(featuredata)) {
featuredata$symbol = toupper(featuredata$symbol)
rowData(scEx) <- featuredata
}
# dataTables$featuredataOrg <- rowData(scEx)
dataTables$scEx <- scEx
dataTables$featuredata <- featuredata
if (is.null(scEx$barcode)) {
showNotification("scEx doesn't contain barcode column", type = "error")
return(NULL)
}
# some checks
if (sum(is.infinite(assays(scEx)[["counts"]])) > 0) {
if (!is.null(getDefaultReactiveDomain())) {
showNotification("scEx contains infinite values",
type = "error"
)
}
return(NULL)
}
if ("sampleNames" %in% names(colData(scEx))) {
sampNames <- levels(colData(scEx)$sampleNames)
isolate({
# sampleCols$colPal <- colorRampPalette(brewer.pal(
# n = 6, name =
# "PRGn"
# ))(length(sampNames))
sampleCols$colPal <- allowedColors[seq_along(sampNames)]
names(sampleCols$colPal) <- sampNames
})
} else {
showNotification("scEx - colData doesn't contain sampleNames",
duration = NULL, type = "error"
)
}
if (sum(c("id", "symbol") %in% colnames(rowData(scEx))) < 2) {
if (!is.null(getDefaultReactiveDomain())) {
showNotification("scEx - rowData doesn't contain id and/or symbol columns",
duration = NULL, type = "error"
)
}
}
if (!sum(c("symbol", "Gene.Biotype", "Description") %in% colnames(featuredata)) == 3) {
if (!is.null(getDefaultReactiveDomain())) {
showNotification("featuredata - one of is missing: symbol, Gene.Biotype, Description)",
duration = NULL, type = "error"
)
}
if (!"Gene.Biotype" %in% colnames(featuredata)) {
featuredata$"Gene.Biotype" <- "not given"
}
if (!"Description" %in% colnames(featuredata)) {
featuredata$"Description" <- "not given"
}
featuredata$symbol = toupper(featuredata$symbol)
dataTables$featuredata <- featuredata
}
# if (is.null(rowData(dataTables$scEx)$symbol)){
#
# }
inputFileStats$stats <- stats
return(dataTables)
}
# inputData ----
# internal, should not be used by plug-ins
inputData <- reactive({
if (DEBUG) cat(file = stderr(), "inputData started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "inputData")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "inputData")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("inputData", id = "inputData", duration = NULL)
}
inFile <- input$file1
if (is.null(inFile)) {
if (DEBUG) cat(file = stderr(), "inputData: NULL\n")
return(NULL)
}
if (DEBUGSAVE) {
save(file = "~/scShinyHubDebug/inputData.RData", list = c(ls(), ls(envir = globalenv())))
}
# load(file='~/scShinyHubDebug/inputData.RData')
retVal <- inputDataFunc(inFile)
exportTestValues(inputData = {list(assays(retVal$scEx)[["counts"]], rowData(retVal$scEx), colData(retVal$scEx)) })
return(retVal)
})
medianENSGfunc <- function(scEx) {
if (DEBUG) cat(file = stderr(), "medianENSGfunc started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "medianENSGfunc")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "medianENSGfunc")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("medianENSGfunc", id = "medianENSGfunc", duration = NULL)
}
geneC <- Matrix::colSums(scEx > 0, na.rm = TRUE)
return(median(t(geneC)))
}
# medianENSG ----
medianENSG <- reactive({
if (DEBUG) cat(file = stderr(), "medianENSG started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "medianENSG")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "medianENSG")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("medianENSG", id = "medianENSG", duration = NULL)
}
scEx_log <- scEx_log()
if (is.null(scEx)) {
if (DEBUG) {
cat(file = stderr(), "medianENSG:NULL\n")
}
return(0)
}
scEx_log <- assays(scEx_log)[[1]]
if (ncol(scEx_log) <= 1 | nrow(scEx_log) < 1) {
return(0)
}
retVal <- medianENSGfunc(scEx_log)
exportTestValues(medianENSG = { retVal })
return(retVal)
})
medianUMIfunc <- function(scEx) {
if (DEBUG) cat(file = stderr(), "medianUMIfunc started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "medianUMIfunc")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "medianUMIfunc")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("medianUMIfunc", id = "medianUMIfunc", duration = NULL)
}
umiC <- Matrix::colSums(scEx, na.rm = TRUE)
return(median(t(umiC)))
}
# medianUMI ----
medianUMI <- reactive({
if (DEBUG) cat(file = stderr(), "medianUMI started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "medianUMI")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "medianUMI")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("medianUMI", id = "medianUMI", duration = NULL)
}
scEx <- scEx()
if (is.null(scEx)) {
if (DEBUG) {
cat(file = stderr(), "medianUMI:NULL\n")
}
return(0)
}
if (DEBUGSAVE) {
save(file = "~/scShinyHubDebug/medianUMI.RData", list = c(ls(), ls(envir = globalenv())))
}
# load(file='~/scShinyHubDebug/medianUMI.RData')
scEx <- assays(scEx)[["counts"]]
retVal <- medianUMIfunc(scEx)
exportTestValues(medianUMI = { retVal })
return(retVal)
})
# for now we don't have a way to specifically select cells
# we could cluster numbers or the like
# internal, should not be used by plug-ins
useCellsFunc <-
function(dataTables,
geneNames,
rmCells,
rmPattern,
keepCells,
cellKeepOnly) {
if (DEBUG) cat(file = stderr(), "useCellsFunc started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "useCellsFunc")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "useCellsFunc")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("useCellsFunc", id = "useCellsFunc", duration = NULL)
}
if (DEBUGSAVE) {
save(file = "~/scShinyHubDebug/useCellsFunc.RData", list = c(ls()))
}
# load(file='~/scShinyHubDebug/useCellsFunc.Rdata')
goodCols <- rep(TRUE, ncol(dataTables$scEx))
scEx <- assays(dataTables$scEx)[[1]]
#### start: cells with genes expressed
# take only cells where these genes are expressed with at least one read
genesin <- toupper(geneNames)
genesin <- gsub(" ", "", genesin, fixed = TRUE)
genesin <- strsplit(genesin, ",")
genesin <- genesin[[1]]
cellKeep <- toupper(keepCells)
cellKeep <- gsub(" ", "", cellKeep, fixed = TRUE)
cellKeep <- strsplit(cellKeep, ",")
cellKeep <- cellKeep[[1]]
cellKeepOnly <- toupper(cellKeepOnly)
cellKeepOnly <- gsub(" ", "", cellKeepOnly, fixed = TRUE)
cellKeepOnly <- strsplit(cellKeepOnly, ",")
cellKeepOnly <- cellKeepOnly[[1]]
# specifically remove cells
if (nchar(rmCells) > 0) {
cellsRM <- toupper(rmCells)
cellsRM <- gsub(" ", "", cellsRM, fixed = TRUE)
cellsRM <- strsplit(cellsRM, ",")
cellsRM <- cellsRM[[1]]
goodCols[which(toupper(colnames(dataTables$scEx)) %in% cellsRM)] <- FALSE
}
# remove cells by pattern
if (nchar(rmPattern) > 0) {
goodCols[grepl(rmPattern, colnames(dataTables$scEx))] <- FALSE
}
if (!length(cellKeep) == 0) {
ids <- which(toupper(colnames(dataTables$scEx)) %in% cellKeep)
goodCols[ids] <- TRUE
}
# genes that have to be expressed at least in one of them.
selCols <- rep(FALSE, length(goodCols))
if (!length(genesin) == 0) {
ids <- which(toupper(dataTables$featuredata$symbol) %in% genesin)
if (length(ids) == 1) {
selCols <- scEx[ids, ] > 0
} else if (length(ids) == 0) {
showNotification(
"not enough cells, check gene names for min coverage",
type = "warning",
duration = NULL
)
return(NULL)
} else {
selCols <- Matrix::colSums(scEx[ids, ]) > 0
}
goodCols <- goodCols & selCols
}
if (!length(cellKeepOnly) == 0) {
goodCols[c(1:length(goodCols))] <- FALSE
ids <- which(toupper(colnames(dataTables$scEx)) %in% cellKeepOnly)
goodCols[ids] <- TRUE
}
#### end: cells with genes expressed
return(goodCols)
}
# useCells ----
# works on cells only
# internal, should not be used by plug-ins
useCells <- reactive({
if (DEBUG) cat(file = stderr(), "useCells started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "useCells")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "useCells")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("useCells", id = "useCells", duration = NULL)
}
dataTables <- inputData()
geneNames <- input$minExpGenes
rmCells <- input$cellsFiltersOut
rmPattern <- input$cellPatternRM
keepCells <- input$cellKeep
cellKeepOnly <- input$cellKeepOnly
# useGenes = isolate(useGenes())
if (!exists("dataTables") || is.null(dataTables)) {
if (DEBUG) {
cat(file = stderr(), "useCells:NULL\n")
}
return(NULL)
}
retVal <- useCellsFunc(
dataTables,
geneNames,
rmCells,
rmPattern,
keepCells,
cellKeepOnly
)
exportTestValues(useCells = { retVal })
return(retVal)
})
useGenesFunc <-
function(dataTables,
ipIDs, # regular expression of genes to be removed
geneListSelection,
genesKeep,
geneLists) {
if (DEBUG) cat(file = stderr(), "useGenesFunc started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "useGenesFunc")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "useGenesFunc")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("useGenesFunc", id = "useGenesFunc", duration = NULL)
}
gList <- geneLists # global variable, assigning it locally ensures that it will be saved
if (DEBUGSAVE) {
save(file = "~/scShinyHubDebug/useGenesFunc.Rdata", list = c(ls(), ls(envir = globalenv())))
}
# load(file='~/scShinyHubDebug/useGenesFunc.Rdata')
# regular expression with gene names to be removed
if (nchar(ipIDs) > 0) {
keepIDs <- !grepl(ipIDs, dataTables$featuredata$symbol)
} else {
keepIDs <- rep(TRUE, nrow(dataTables$scEx))
}
genesKeep <- toupper(genesKeep)
genesKeep <- gsub(" ", "", genesKeep, fixed = TRUE)
genesKeep <- strsplit(genesKeep, ",")
genesKeep <- genesKeep[[1]]
keepGeneIds <- which(dataTables$featuredata$symbol %in% genesKeep)
# dataTables$featuredata$symbol[keepIDs]
# gene groups to be included
if (!is.null(geneListSelection)) {
selectedgeneList <- get_selected(geneListSelection)
if (length(selectedgeneList) > 0) {
selGenes <- c()
for (sIdx in 1:length(selectedgeneList)) {
print(sIdx)
att <- attr(selectedgeneList[[sIdx]], "ancestry")
if (length(att) > 0) {
selGenes <- c(selGenes, gList[[att]][[selectedgeneList[[sIdx]]]])
}
}
selGenes <- unique(selGenes)
keepIDs <- (rownames(dataTables$scEx) %in% selGenes) & keepIDs
}
}
keepIDs[keepGeneIds] <- TRUE
return(keepIDs)
}
# before gene filtering -----
beforeFilterCounts <- reactive({
if (DEBUG) cat(file = stderr(), "beforeFilterCounts started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "beforeFilterCounts")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "beforeFilterCounts")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("beforeFilterCounts", id = "beforeFilterCounts", duration = NULL)
}
dataTables <- inputData()
ipIDs <- input$selectIds # regular expression of genes to be removed
if (!exists("dataTables") |
is.null(dataTables) |
length(dataTables$featuredata$symbol) == 0) {
if (DEBUG) {
cat(file = stderr(), "beforeFilterCounts: NULL\n")
}
return(NULL)
}
if (DEBUGSAVE) {
save(file = "~/scShinyHubDebug/beforeFilterCounts.RData", list = c(ls(), ls(envir = globalenv())))
}
# load(file="~/scShinyHubDebug/beforeFilterCounts.RData")
geneIDs <- NULL
if (nchar(ipIDs) > 0) {
geneIDs <- grepl(ipIDs, dataTables$featuredata$symbol)
}
if (is.null(geneIDs)) {
return(rep(0, nrow(dataTables$featuredata)))
}
retVal = Matrix::colSums(assays(dataTables$scEx)[["counts"]][geneIDs, ])
exportTestValues(beforeFilterCounts = { retVal })
return(retVal)
})
# useGenes ----
# collects information from all places where genes being removed or specified
useGenes <- reactive({
if (DEBUG) cat(file = stderr(), "useGenes started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "useGenes")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "useGenes")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("useGenes", id = "useGenes", duration = NULL)
}
dataTables <- inputData()
ipIDs <- input$selectIds # regular expression of genes to be removed
genesKeep <- input$genesKeep
geneListSelection <- input$geneListSelection
if (!exists("dataTables") |
is.null(dataTables) |
length(dataTables$featuredata$symbol) == 0) {
if (DEBUG) {
cat(file = stderr(), "useGenes: NULL\n")
}
return(NULL)
}
if (!is.null(getDefaultReactiveDomain())) {
showNotification("which genes to use", id = "useGenes", duration = NULL)
}
retVal <- useGenesFunc(dataTables, ipIDs, geneListSelection, genesKeep, geneLists)
exportTestValues(useGenes = { retVal })
return(retVal)
})
# will be called recursively to ensure that nothing changes when cells/genes are changing.
scExFunc <-
function(scExOrg,
useCells,
useGenes,
minGene,
minG,
maxG) {
if (DEBUG) cat(file = stderr(), "scExFunc started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "scExFunc")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "scExFunc")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("scExFunc", id = "scExFunc", duration = NULL)
}
if (!is.null(getDefaultReactiveDomain())){
removeNotification(id = "scExFunc1")
removeNotification(id = "scExFunc2")
}
# change names to be hopefully a bit more clear
changed <- FALSE # trace if something changed
keepGenes <- useGenes
keepCells <- useCells
scEx <- assays(scExOrg)[[1]]
# overall gene expression Min
if (!is.null(minGene)) {
selGenes <- Matrix::rowSums(scEx[, keepCells]) >= minGene
selGenes <- keepGenes & selGenes
if (!all(selGenes == keepGenes)) {
keepGenes <- selGenes
changed <- TRUE
}
}
# min reads per cell
if (!is.null(minG)) {
selCols <- Matrix::colSums(scEx[keepGenes, ], na.rm = FALSE) > minG
selCols[is.na(selCols)] <- FALSE
selCols <- keepCells & selCols
if (!all(selCols == keepCells)) {
keepCells <- selCols
changed <- TRUE
}
}
# max reads per cell
if (!is.null(maxG)) {
selCols <- Matrix::colSums(scEx[keepGenes, ], na.rm = FALSE) <= maxG
selCols[is.na(selCols)] <- FALSE
selCols <- selCols & keepCells
if (!all(selCols == keepCells)) {
changed <- TRUE
keepCells <- selCols
}
}
if (sum(keepCells) == 0) {
showNotification("not enough cells left",
type = "warning",
id = "scExFunc1",
duration = NULL
)
return(NULL)
}
if (sum(keepGenes) == 0) {
showNotification("not enough genes left",
type = "warning",
id = "scExFunc1",
duration = NULL
)
return(NULL)
}
# if something changed, check that it doesn't change again
scExNew <- scExOrg[keepGenes, keepCells]
if (changed) {
scExNew <- scExFunc(scExOrg[keepGenes, keepCells], useCells[keepCells], useGenes[keepGenes], minGene, minG, maxG)
if (is.null(scExNew)) {
return(NULL)
}
}
pD <- colData(scExNew)
for (colN in colnames(pD)) {
if (colN == "barcode") next()
if (class(pD[, colN]) %in% c("character")) {
pD[, colN] <- factor(as.character(pD[, colN]))
}
}
colData(scExNew) <- pD
return(scExNew)
}
# scEx ----
# apply filters that depend on genes & cells
# it is here that useCells and useGenes are combined and applied to select for
scEx <- reactive({
if (DEBUG) cat(file = stderr(), "scEx started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "scEx")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "scEx")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("scEx", id = "scEx", duration = NULL)
}
dataTables <- inputData()
useCells <- useCells()
useGenes <- useGenes()
minGene <- input$minGenesGS # min number of reads per gene
minG <- input$minGenes # min number of reads per cell
maxG <- input$maxGenes # max number of reads per cell
if (!exists("dataTables") |
is.null(dataTables) | is.null(useGenes) | is.null(useCells)) {
if (DEBUG) {
cat(file = stderr(), "scEx: NULL\n")
}
return(NULL)
}
if (DEBUGSAVE) {
save(file = "~/scShinyHubDebug/scEx.RData", list = c(ls(), ls(envir = globalenv())))
}
# load(file="~/scShinyHubDebug/scEx.RData")
retVal <- scExFunc(
scExOrg = dataTables$scEx,
useCells = useCells,
useGenes = useGenes,
minGene = minGene,
minG = minG,
maxG = maxG
)
exportTestValues(scEx = { list(rowData(retVal), colData(retVal)) })
return(retVal)
})
# rawNormalization ----
rawNormalization <- reactive({
if (DEBUG) cat(file = stderr(), "rawNormalization started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "rawNormalization")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "rawNormalization")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("rawNormalization", id = "rawNormalization", duration = NULL)
}
scEx <- scEx()
names(assays(scEx)) = "logcounts"
exportTestValues(rawNormalization = {str(scEx)})
return(scEx)
})
# scEx_log ----
scEx_log <- reactive({
if (DEBUG) cat(file = stderr(), "scEx_log started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "scEx_log")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "scEx_log")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("scEx_log", id = "scEx_log", duration = NULL)
}
scEx <- scEx()
normMethod <- input$normalizationRadioButton
if (is.null(scEx)) {
if (DEBUG) {
cat(file = stderr(), "scEx_log:NULL\n")
}
return(NULL)
}
if (DEBUGSAVE) {
save(file = "~/scShinyHubDebug/scEx_log.RData", list = c(ls(), ls(envir = globalenv())))
}
# load(file="~/scShinyHubDebug/scEx_log.RData")
scEx_log <- do.call(normMethod, args = list())
exportTestValues(scEx_log = { assays(scEx_log)["logcounts"] })
return(scEx_log)
})
# scExLogMatrixDisplay ----
# scExLog matrix with symbol as first column
# TODO
# we should probably just rename the rows and then have an option to tableSelectionServer that shows (or not) rownames
scExLogMatrixDisplay <- reactive({
if (DEBUG) cat(file = stderr(), "scExLogMatrixDisplay started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "scExLogMatrixDisplay")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "scExLogMatrixDisplay")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("scExLogMatrixDisplay", id = "scExLogMatrixDisplay", duration = NULL)
}
# dataTables = inputData()
# useCells = useCells()
# useGenes = useGenes()
scEx_log <- scEx_log()
if (is.null(scEx_log)) {
if (DEBUG) {
cat(file = stderr(), "scExLogMatrixDisplay:NULL\n")
}
return(NULL)
}
if (DEBUGSAVE) {
save(file = "~/scShinyHubDebug/scExLogMatrixDisplay.RData", list = c(ls(), ls(envir = globalenv())))
}
# load(file="~/scShinyHubDebug/scExLogMatrixDisplay.RData")
# TODO
if (ncol(scEx_log) > 20000) {
}
retVal <- data.frame(symbol=make.names(rowData(scEx_log)$symbol, unique = TRUE), stringsAsFactors = FALSE)
retVal <- cbind(retVal,
as.matrix(assays(scEx_log)[[1]]))
rownames(retVal) <- make.names(rowData(scEx_log)$symbol, unique = TRUE)
return(retVal)
})
pcaFunc <- function(scEx_log) {
if (DEBUG) cat(file = stderr(), "pcaFunc started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "pcaFunc")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "pcaFunc")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("pcaFunc", id = "pcaFunc", duration = NULL)
}
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "pcawarning")
if (DEBUGSAVE) {
save(file = "~/scShinyHubDebug/pcaFunc.RData", list = c(ls(), ls(envir = globalenv())))
}
# load(file="~/scShinyHubDebug/pcaFunc.RData")
scaterPCA <- tryCatch({
# not sure, but this works on another with dgTMatrix
if (class(assays(scEx_log)[["logcounts"]]) == "dgTMatrix") {
assays(scEx_log)[["logcounts"]] <- as(assays(scEx_log)[["logcounts"]], "dgCMatrix")
}
scater::runPCA(scEx_log,
ncomponents = 10, method = "irlba",
ntop = 500, exprs_values = "logcounts"
)
},
error = function(e) {
cat(file = stderr(), paste("error in PCA:", e))
if (!is.null(getDefaultReactiveDomain())) {
showNotification(
"Problem with PCA, probably not enough cells?",
type = "warning",
id = "pcawarning",
duration = NULL
)
}
cat(file = stderr(), "PCA FAILED!!!\n")
return(NULL)
},
finally = {
cat( file = stderr(), paste("pca done\n"))
}
)
if (is.null(scaterPCA)) return(NULL)
# pca = reducedDim(scaterPCA, "PCA")
# attr(pca,"percentVar")
#
return(list(
x = SingleCellExperiment::reducedDim(scaterPCA, "PCA"),
var_pcs = attr(SingleCellExperiment::reducedDim(scaterPCA, "PCA"), "percentVar")
))
}
# pca ----
pca <- reactive({
if (DEBUG) cat(file = stderr(), "pca started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "pca")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "pca")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("pca", id = "pca", duration = NULL)
}
scEx_log <- scEx_log()
if (is.null(scEx_log)) {
if (DEBUG) {
cat(file = stderr(), "pca:NULL\n")
}
return(NULL)
}
retVal <- pcaFunc(scEx_log)
printTimeEnd(start.time, "pca")
exportTestValues(pca = { retVal })
return(retVal)
})
scranCluster <- function(pca, scEx_log, seed, clusterSource,
geneSelectionClustering="", minClusterSize=2, clusterMethod="PCA", featureData) {
if (DEBUG) cat(file = stderr(), "scranCluster started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "scranCluster")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "scranCluster")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("scranCluster", id = "scranCluster", duration = NULL)
}
set.seed(seed)
geneid <- geneName2Index(geneSelectionClustering, featureData)
params <- list(
min.mean = NULL,
min.size = minClusterSize,
method = clusterMethod
)
if (clusterSource == "PCA") {
params$x <- t(pca$x)
} else {
params$x <- scEx_log
params$assay.type <- "logcounts"
if (length(geneid) > 0)
params$subset.row <- geneid
}
retVal <- tryCatch({
do.call("quickCluster", params)
},
error = function(e) {
cat(file = stderr(), paste("\nProblem with clustering", e, "\n\n"))
return(NULL)
}#,
# warning = function(e){
# cat(file = stderr(), paste("\nclustering produced Warning:\n",e , "\n"))
# return(do.call("quickCluster", params))
# }
)
retVal = data.frame(Barcode = colData(scEx_log)$barcode,
Cluster = retVal)
rownames(retVal) = retVal$Barcode
return(retVal)
}
# dbCluster ----
dbCluster <- reactive({
if (DEBUG) cat(file = stderr(), "dbCluster started.\n")
start.time <- base::Sys.time()
on.exit({
printTimeEnd(start.time, "dbCluster")
if (!is.null(getDefaultReactiveDomain()))
removeNotification(id = "dbCluster")
})
if (!is.null(getDefaultReactiveDomain())) {
showNotification("dbCluster", id = "dbCluster", duration = NULL)
}
kNr <- input$kNr
clustering <- scran_Cluster()
if (DEBUGSAVE) {
save(file = "~/scShinyHubDebug/dbCluster.RData", list = c(ls(), ls(envir = globalenv())))
}
# load(file="~/scShinyHubDebug/dbCluster.RData")
if (is.null(clustering)) {
if (DEBUG) {
cat(file = stderr(), "dbCluster: NULL\n")
}
return(NULL)
}
dbCluster <- clustering$Cluster
#cluster colors
inCols = list()
lev <- levels(dbCluster)