Brogrammer94
/
Spatial-transcriptomics-reveals-molecular-dysfunction-associated-with-cortical-Lewy-pathology
Public
forked from Goralsth/Spatial-transcriptomics-reveals-molecular-dysfunction-associated-with-cortical-Lewy-pathology
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Helper_functions_Pipeline_Hu_NatComms_Final.Rmd
2081 lines (1491 loc) · 69.3 KB
/
Helper_functions_Pipeline_Hu_NatComms_Final.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Helper_Functions_Pipeline"
author: "Thomas Goralski"
date: '2022-07-26'
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
You must ensure that DCC files are the correct version, the following function will make that conversion. Only run if you need to
```{r}
#set file path to DCC files
files <- list.files(path="DCC-20220830", pattern=NULL, all.files=FALSE,full.names=FALSE)
#change working direcotry to folder with DCC files
setwd("DCC-20220830")
#loop to change version
for (file in files) {
tx <- readLines(file)
tx2 <- gsub(pattern = "Pipeline_dev", replace = "Pipeline_2.0.0", x = tx)
writeLines(tx2, con=file)
}
```
The below are helper functions for the GeoMX data analysis pipline. The get_qc function is highly verbose. I suggest running Qc manually until you have a feeling for what QC is doing, then use get_qc as a effecient method of getting QC reports
```{r}
############################################################################################################################################################################
#' get_libraries
#'
#' @param library_list vector containing names (string) of packages needed
#'
#' @return
#' @export
#'
#' @examples
#'
#'@summary Given a list of packages, loads packages.
#'
#'
get_libraries<-function(library_list){
for(i in library_list){
package<- i
library(package, character.only = TRUE)
}
}
############################################################################################################################################################################
#' Run_Qc
#'
#' @param Dataset geoMX data to perform qc on
#' @param Parameters Qc parameters
#' @param segment_id IN QUOTES : colname from annotation file that designates segment strategy
#' @param neg_norm determine if negative normalization should be performed
#' @param
#'
#' @summary return QC'd and normalized data.
#'
#'
#'
#'
#'
invisible(run_qc<-function(Dataset, Parameters, segment_id, neg_norm=FALSE ){
#shift all number then 1 to one so when log normalized they will be 0.
probe_data_qc <- shiftCountsOne(Dataset, useDALogic = TRUE)
#first make sure phenotype data is categorical
# Save this as a data frame
qc_param_tab <- data.frame(Parameter=names(GeomxTools:::DEFAULTS), 'Default value'=as.numeric(GeomxTools:::DEFAULTS), 'Actual value'=as.numeric(Parameters))
#nested function
makeQCHistogram<-function(object, annotation_col=NULL, bins=NULL, fill_by=NULL, xintercept=NULL, scale_trans=NULL){
## Plotting
# Extract data frame of QC data from the NanoStringGeoMxSet object.
plot_df <- sData(object)
# Create histogram
plt <- ggplot(plot_df,
aes_string(x = paste0("unlist(`", annotation_col, "`)"),
fill = fill_by)) +
geom_histogram(bins = bins) +
geom_vline(xintercept = xintercept, lty = "dashed", color = "black") +
theme_bw() + guides(fill = "none") +
labs(x = annotation_col, y = "Segments, #", title = annotation_col)+
scale_fill_manual(values=c(NeuN="steelblue1", pSyn= "firebrick1"))
# Facet the histogram if "fill_by" is specified
if(!is.null(fill_by)) {
plt <- plt +
facet_wrap(as.formula(paste("~", fill_by)), nrow = length(unique(plot_df[,fill_by])))
}
# Add continuous x-axis if "scale_trans" is specified
if(!is.null(scale_trans)) {
plt <- plt +
scale_x_continuous(trans = scale_trans)
}
# Plot Histogram
print(plt)
}
# Assess QC flags using setSegmentQCFlags
probe_data_qc <- setSegmentQCFlags(probe_data_qc, qcCutoffs = Parameters)
QCResults <- protocolData(probe_data_qc)[["QCFlags"]]
flag_columns <- colnames(QCResults)
QC_Summary <- data.frame(Pass = colSums(!QCResults[, flag_columns]),
Flag = colSums(QCResults[, flag_columns]))
QCResults$QCStatus <- apply(QCResults, 1L, function(x) {
ifelse(sum(x) == 0L, "PASS", "WARNING")
})
QC_Summary["TOTAL FLAGS", ] <-
c(sum(QCResults[, "QCStatus"] == "PASS"),
sum(QCResults[, "QCStatus"] == "WARNING"))
pData(Dataset)$QC <- QCResults$QCStatus
dt_params$autoWidth <- FALSE
dt_params$buttons <- list(list(extend = "copy"),
list(extend = "csv", filename = "SegmentQCSummary.csv"),
list(extend = "excel", filename = "SegmentQCSummary.xlsx"))
qc_sums<-DT::datatable(
QC_Summary[, ],
extensions = c("Buttons", "Scroller", "FixedColumns"),
options = dt_params)
print(qc_sums)
# Create summary table of NTCs
# ntc_summary_tab <- ddply(sData(probe_data_qc) %>%
# dplyr::select(Plate_ID, NTC_ID, NTC), .(Plate_ID, NTC_ID), function(x){
# ntc_well <- x$NTC_ID[1]
# ntc_count <- x$NTC[1]
# n_samples <- nrow(x)
# return(data.frame('NTC Well ID'=ntc_well, 'NTC counts' = ntc_count, 'Samples'=n_samples))
# }) %>% dplyr::select(-NTC_ID)
# colnames(ntc_summary_tab) <- c("Plate", "NTC Well", "NTC Counts", "Samples")
# Return data table with summary of QC flags, if any are identified
# Un-embed data frames from the QC data
for (column in colnames(sData(probe_data_qc))) {
if (inherits(sData(probe_data_qc)[,column], "data.frame") && ncol(sData(probe_data_qc)[,column])==1){
probe_data_qc@protocolData@data[,column] <- sData(probe_data_qc)[, column][,1]
}
}
# calculate the negative geometric means for each module
negativeGeoMeans <-
esBy(negativeControlSubset(probe_data_qc),
GROUP = "Module",
FUN = function(x) {
assayDataApply(x, MARGIN = 2, FUN = ngeoMean, elt = "exprs")
})
# Convert embedded matrix to df then to AnnotatedDataFrame
protocolData(probe_data_qc) <- as(
cbind(
as(protocolData(probe_data_qc), "data.frame"),
as.data.frame(negativeGeoMeans)
), "AnnotatedDataFrame")
# Here are the module names
pkcs <- annotation(probe_data_qc)
modules <- gsub(".pkc", "", pkcs)
# Copy the Negative geoMeans from sData to pData
negCols <- paste0("NegGeoMean_", modules)
# negCols <- colnames(sData(probe_data_qc)[["NegGeoMean"]])
pData(probe_data_qc)[, negCols] <- sData(probe_data_qc)[, which(colnames(sData(probe_data_qc)) %in% modules)]
# detatch neg_geomean columns ahead of aggregateCounts call
pData(probe_data_qc) <- pData(probe_data_qc)[, !colnames(pData(probe_data_qc)) %in% negCols]
seg_qc_samples_to_remove <- rownames(QCResults)[QCResults$QCStatus!="PASS"]
probe_data_qc_for_seg_qc_plots <- probe_data_qc # for plotting (appendix) before filtering
pre_filter <- dim(probe_data_qc)
if(length(seg_qc_samples_to_remove)>0){
probe_data_qc <- probe_data_qc[,-which(colnames(probe_data_qc) %in% seg_qc_samples_to_remove)]
}
passed_seg_qc <- dim(probe_data_qc)
#start QC lots
p <- makeQCHistogram(probe_data_qc_for_seg_qc_plots,
annotation_col = "Trimmed (%)",
fill_by = segment_id,
bins = 50,
xintercept = Parameters$percentTrimmed)
ggsave(p, filename = file.path(qc_dir, "trimmed.svg"), width=3, height=3) #save plot
#Rinse Wash repeat
p <- makeQCHistogram(probe_data_qc_for_seg_qc_plots,
annotation_col = "Aligned (%)",
fill_by = segment_id,
bins = 50,
xintercept = Parameters$percentAligned)
ggsave(p, filename = file.path(qc_dir, "aligned.svg"), width=3, height=3)
#Rinse Wash repeat
p <- makeQCHistogram(probe_data_qc_for_seg_qc_plots,
annotation_col = "Saturated (%)",
fill_by = segment_id,
bins = 50,
xintercept = Parameters$percentSaturation) +
labs(title = "Sequencing Saturation (%)",
x = "Sequencing Saturation (%)")
ggsave(p, filename = file.path(qc_dir, "saturated.svg"), width=3, height=3)
p <- makeQCHistogram(probe_data_qc_for_seg_qc_plots,
annotation_col = "area",
fill_by = segment_id,
bins = 50,
xintercept = Parameters$minArea)
ggsave(p, filename = file.path(qc_dir, "area.svg"), width=3, height=3)
#Rinse wash repeat
p <- makeQCHistogram(probe_data_qc_for_seg_qc_plots,
annotation_col = "AOINucleiCount",
fill_by = segment_id,
bins = 50,
xintercept = Parameters$minNuclei)
ggsave(p, filename = file.path(qc_dir, "Nuclei.svg"), width=3, height=3)
for(ann in modules) {
p <- makeQCHistogram(probe_data_qc_for_seg_qc_plots,
annotation_col = ann,
fill_by = segment_id,
bins = 50,
xintercept = 2,
scale_trans = "log10")
ggsave(p, filename = file.path(qc_dir, paste0(ann, ".svg")), width=6, height=6)
}
# QC probes across remaining segments
probe_data_qc <- setBioProbeQCFlags(probe_data_qc,
qcCutoffs = Parameters,
removeLocalOutliers = TRUE)
ProbeQCResults <- fData(probe_data_qc)[["QCFlags"]]
# Define QC table for Probe QC
ProbeQC_summary <- data.frame(Passed = sum(rowSums(ProbeQCResults[, -1]) == 0),
Global = sum(ProbeQCResults$GlobalGrubbsOutlier),
Local = sum(rowSums(ProbeQCResults[, -2:-1]) > 0
& !ProbeQCResults$GlobalGrubbsOutlier))
#get summary table
probe_sums<-DT::datatable(
ProbeQC_summary[, ],
extensions = c("Buttons", "Scroller", "FixedColumns"),
options = dt_params)
# remove flagged probes
probe_data_qc <-
subset(probe_data_qc,
fData(probe_data_qc)[["QCFlags"]][,c("LowProbeRatio")] == FALSE &
fData(probe_data_qc)[["QCFlags"]][,c("GlobalGrubbsOutlier")] == FALSE)
passed_bioprobe_qc <- dim(probe_data_qc)
print(probe_sums)
#Nested Function
getGenesAboveLOQ<-function(object,
elt="loq_mat",
return_matrix=FALSE,
loq_critical=Parameters$loqCutoff,
loq_min=2,
n=2,
agg_function = formals(GeomxTools::aggregateCounts)$FUN) {
## Check the input
# Note: with setMethod of signature NanoStringGeoMxSet,
# the object class is already checked. However, the second part
# of spec #1 should be checked.
if(featureType(object)!="Probe"){
stop("Input NanoStringGeoMxSet needs to have featureType of Probe.")
}
# The return_matrix argument must be logical.
if(!inherits(return_matrix, "logical")){
stop("return_matrix must be logical: TRUE, FALSE.")
}
# If return_matrix is FALSE, elt needs to be
# a character with at length > 1.
if(!return_matrix){
if(!inherits(elt, "character")){
stop("Please provide a character for elt.")
}
if(nchar(elt) == 0){
stop("elt can not be a zero-length variable name.")
}
}
# If return_matrix is FALSE, elt must point to an empty element in object
if(!return_matrix & !is.null(assayDataElement(object, elt=elt))){
stop(paste0("Assay data element ",
elt,
" is not NULL. Please provide a new element name.")
)
}
# The loq_critical is a single, positive numeric value
if(!inherits(loq_critical, "numeric")){
stop("loq_critical needs to be numeric.")
} else if(length(loq_critical)!=1){
stop("loq_critical needs to be a single numeric value.")
} else if(loq_critical < 0){
stop("loq_critical needs to be positive.")
}
# The loq_min is a single, positive numeric value
if(!inherits(loq_min, "numeric")){
stop("loq_min needs to be numeric.")
} else if(length(loq_min)!=1){
stop("loq_min needs to be a single numeric value.")
} else if(loq_min < 0){
stop("loq_min needs to be positive.")
}
# The n is a single, positive numeric value
if(!inherits(n, "numeric")){
stop("n needs to be numeric.")
} else if(length(n)!=1){
stop("n needs to be a single numeric value.")
} else if(n < 0){
stop("n needs to be positive.")
}
## Processing
# What modules are used?
modules <- unique(fData(object)[["Module"]])
# negative subset of object
neg_subset <- NanoStringNCTools::subset(object, CodeClass == "Negative")
# Here are the negative geoMeans per module
negativeGeoMeans <-
NanoStringNCTools::esBy(neg_subset,
GROUP = "Module",
FUN = function(x) {
assayDataApply(x, MARGIN = 2, FUN = ngeoMean, elt = "exprs")
})
# prepend NegGeoMean_ to column names
colnames(negativeGeoMeans) <- paste0("NegGeoMean_", colnames(negativeGeoMeans))
# Here are the negative geoSDs per module
negativeGeoSDs <-
NanoStringNCTools::esBy(neg_subset,
GROUP = "Module",
FUN = function(x) {
assayDataApply(x, MARGIN = 2, FUN = ngeoSD, elt = "exprs")
})
# prepend NegGeoSD_ to column names
colnames(negativeGeoSDs) <- paste0("NegGeoSD_", colnames(negativeGeoSDs))
# add geoMeans and geoSDs to pData
means_and_SDs <- cbind(negativeGeoMeans, negativeGeoSDs)
pData(object) <- cbind(pData(object), means_and_SDs[row.names(pData(object)),]) # ensure row.name order
# Sample-specific (row) LOQ for each pool (column)
LOQ_df <- do.call(cbind, lapply(modules, function(module){
module_cols <- paste0(c("NegGeoMean_", "NegGeoSD_"), module)
loq_module <- data.frame(apply(pData(object)[,module_cols], 1, function(i){
pmax(loq_min, (i[1]*(i[2]^n)))
}))
colnames(loq_module) <- paste0("LOQ_",module)
return(loq_module)
}))
# add LOQ column(s) to pData(object). This is conditional on the
# number of columns (i.e., modules)
if(ncol(LOQ_df)==1){
pData(object)[[colnames(LOQ_df)]] <- LOQ_df[row.names(pData(object)),]
} else {
pData(object) <- cbind(pData(object), LOQ_df[row.names(pData(object)),])
}
# strip leading LOQ_ from column names so they are identical to the module names
# (used downstream)
colnames(LOQ_df) <- gsub("LOQ_", "", colnames(LOQ_df))
# geoMean, geoSD, and LOQ are at the sample level. Aggregate probe counts
# to target level for feature data.
object <- aggregateCounts(object, FUN=as.character(agg_function))
# Create logical LOQ matrix.
loq_mat <- do.call(rbind, lapply(modules, function(module){
module_logic <- fData(object)[["Module"]] == module
mat_module <- t(esApply(object[module_logic, ], MARGIN = 1,
FUN = function(x) {
x > LOQ_df[, module]
}))
return(mat_module)
}))
# Restore the row order and column order
loq_mat <- loq_mat[rownames(object),]
loq_mat <- loq_mat[,colnames(object)]
# Detection rate (adds 2 columns to fData(object) and one to pData(object))
pData(object)$GenesDetected <- colSums(loq_mat, na.rm = TRUE) # number of features expressed above sample-specific LOQ
fData(object)$DetectedSegments <- rowSums(loq_mat, na.rm = TRUE) # number of samples above LOQ for each feature
fData(object)$DetectionRate <- fData(object)$DetectedSegments / nrow(pData(object))
# Return the matrix or the modified object
if(return_matrix){
return(loq_mat)
} else {
assayDataElement(object, elt=elt) <- loq_mat
return(object)
}
}
#start limit of qunatification analysis
loq_data <- getGenesAboveLOQ(probe_data_qc,
loq_critical=Parameters$loqCutoff,
loq_min = 2,
n = 2)
# Define QC table for Probe QC
Probeloq_summary <- data.frame(beforeLOQ= length(rownames(probe_data_qc)),
afterLOQ = length(rownames(loq_data)),
totalbelowLOQ = length(rownames(probe_data_qc))-length(rownames(loq_data)))
#get summary table
probe_loq<-DT::datatable(
Probeloq_summary[, ],
extensions = c("Buttons", "Scroller", "FixedColumns"),
options = dt_params)
print(probe_loq)
pData(loq_data)$FeatureDetectionRate <- pData(loq_data)$GenesDetected/nrow(loq_data)
pData(loq_data)$FeatureDetectionBin <- cut(pData(loq_data)$FeatureDetectionRate,
breaks = c(-1e-16, 0.01, 0.05, 0.1, 0.15, 1), #-1e-16 to include zeros
labels = c("<1%", "1-5%", "5-10%", "10-15%", ">15%"))
#nested function
getColorPalette <- function(input, # Input must be data.frame
start = 1 , # Which color to start with
custom = NULL, # A custom color palette, vector of type character
method = "Map"){ # Color palette type (this could change in the future)
## Check input
# input should be a data.frame
if(!inherits(input, "data.frame")){
stop("input must be a data.frame")
}
# start must be a positive numeric integer.
if(!is.null(start)) {
if (!inherits(start, "numeric")) {
stop("start must be numeric.")
}
if (start %% 1 != 0) {
stop(paste0("The start given, ", start, " is not an integer."))
}
if (start < 1) {
stop("start must be >= 1.")
}
}
# custom must be a vector of mode character
if(!is.null(custom)) {
if(!inherits(custom, "character")){
stop("custom color palette must be a vector of mode character")
}
if(length(custom) < 1){
stop("custom must be at least length 1")
}
if(is.vector(custom) & is.list(custom)){
stop("custom must be a vector of mode character, not a list")
}
}
# method mustbe a character either: "Map", "Main", or "Other"; "Map" is default
if(!method %in% c("Map","Main","Other")){
stop("method must be one of: 'Main', 'Map', or 'Other'")
}
# Make a palette data frame for reference at start of report
l <- start
input <- as.data.frame(input)
color_pal <- list()
input[] <- lapply(input, factor)
for (i in 1:ncol(input)) {
input[, i] <-
factor(input[, i], levels = levels(factor(input[, i])), order = TRUE)
pal <- report_pals(method = method,
n = length(levels(factor(input[, i]))),
start = l,
custom = custom)
names(pal) <- levels(input[, i])
l <- l + length(levels(input[, i]))
color_pal[[length(color_pal) + 1]] <- pal
}
names(color_pal) <- names(input)
return(color_pal)
}
#Helper function:
# Grab colors depending on which method: Main, Map, other
report_pals <- function(method = NULL, # which palette type (Main, Map, or Other)
n = NULL, # how many colors to include in the palette
start = NULL, # what color to start on
custom = NULL) { # list of custom colors to be used as a palette
if(!is.null(custom)) {
pal <- custom
} else {
if(method == "Main") {
# define palette for use in boxplots / scatter plots with annotations, n = 10 colors
pal <- c("#3A6CA1", "#FFD861", "#CF4244", "#47BAB4", "#474747", "#EB739E", "#318026", "#A66293", "#F28E2B", "#8F6954")
#defaults: blues , yellows , reds , teals , grays , pinks , greens , purples , oranges , browns
} else if(method == "Map") {
# define palette to be passed to annotation maps (heatmap), n = 20 colors
pal <- c("#3A6CA1", "#FFD861", "#D86769", "#AEE8E2", "#999999", "#FABFD2", "#318026", "#A66293", "#F28E2B", "#E3C0AC",
"#A0CBE8", "#9E7E20", "#FFBFBD", "#2CABA3", "#474747", "#EB739E", "#A0E391", "#E8C1DE", "#FCB36A", "#B0846B")
} else if(method == "Other") {
# define palette to be passed to other types of factors that could be useful in the future: cell types, genes, etc, n = 20 colors
pal <- c("#3A6CA1", "#FFD861", "#D86769", "#AEE8E2", "#999999", "#FABFD2", "#318026", "#A66293", "#F28E2B", "#E3C0AC",
"#A0CBE8", "#9E7E20", "#FFBFBD", "#2CABA3", "#474747", "#EB739E", "#A0E391", "#E8C1DE", "#FCB36A", "#B0846B")
}
}
ntot <- n + start - 1
if(ntot > length(pal)) {
pal <- rep(pal, ceiling(ntot / length(pal)))
}
return(pal[seq(start, ntot)])
}
# set report color palette
pal_main <- getColorPalette(pData(probe_data)[, factors_of_interest[c(2:length(factors_of_interest),1)]], method = "Main")
#pick segmentation strategy to color by from pData
Ind<-which(factors_of_interest==segment_id)
p <- ggplot(pData(loq_data),
aes(x = FeatureDetectionBin)) +
geom_bar(aes_string(fill = gene_detection_rate_color_by)) +
geom_text(stat = "count", aes(label = ..count..), vjust = -0.5) +
theme_bw() +
scale_fill_manual(values = c("steelblue1", "firebrick1")) +
scale_x_discrete(drop=FALSE) +
scale_y_continuous(expand = expansion(mult = c(0, 0.1))) +
labs(x = "Gene Detection Rate",
y = "Segments, #",
fill = "class")
ggsave(p, filename = file.path(qc_dir, "segments_with_x_above_LOQ.svg"), width=6, height=5)
print(p)
# capture segments with low target detection rates
low_content_segments <-
!pData(loq_data)$FeatureDetectionRate >= loq_segment_filter_proportion
low_content_Ids <- rownames(pData(loq_data))[low_content_segments]
high_content_Ids <- rownames(pData(loq_data))[!low_content_segments]
# save these to probe_data as QC flags for graphing in the sankey diagram
pData(probe_data)[low_content_Ids, "QC"] <- "WARNING"
saveRDS(object=probe_data, file=file.path(object_dir, "probe_data.RDS"))
#save these to probe data qc for data table output
#make data table
segQCresults <- pData(probe_data_qc)[["QC"]]
# Define QC table for Probe QC
segQC_summary <- data.frame(Passed = length(high_content_Ids) ,
Fail = length(low_content_Ids))
#get summary table
seg_sums<-DT::datatable(
segQC_summary[, ],
extensions = c("Buttons", "Scroller", "FixedColumns"),
options = dt_params)
#print the summary of segments filtered
print(seg_sums)
# remove low content segments from the data
loq_data <- loq_data[, !low_content_segments]
passed_loq_filter_segment <- dim(loq_data)
# Recalculate proportions in filtered dataset
fData(loq_data)$DetectedSegments <-
rowSums(assayDataElement(loq_data, elt = "loq_mat"), na.rm = TRUE)
fData(loq_data)$DetectionRate <-
fData(loq_data)$DetectedSegments / nrow(pData(loq_data))
# Preparing summary data.frame
the_proportions <- c(0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5)
plot_detect <- data.frame(Freq=100*the_proportions) # proportions to percent transformation
plot_detect$Number <- unlist(lapply(the_proportions, function(x){
sum(fData(loq_data)$DetectionRate >= x)
}))
plot_detect$Rate <- plot_detect$Number / nrow(fData(loq_data))
rownames(plot_detect) <- plot_detect$Freq
# Creating ggplot object
p <- ggplot(plot_detect, aes(x = as.factor(Freq), y = Rate, fill = Rate)) +
geom_bar(stat = 'identity') +
geom_text(aes(label = formatC(Number, format = 'd', big.mark = ',')),
vjust=1.6, color = 'black', size = 4) +
scale_fill_gradient2(low = 'orange2', mid = 'lightblue',
high = 'dodgerblue3', midpoint = 0.65,
limits = c(0,1),
labels = scales::percent) +
theme_bw() +
scale_y_continuous(labels = scales::percent, limits = c(0,1),
expand = expansion(mult = c(0, 0))) +
labs(x = '% of Segments',
y = 'Genes Detected, % of Panel > LOQ')
# save and figure results
ggsave(p, filename = file.path(qc_dir, "features_with_x_above_LOQ.svg"), width=6, height=5)
print(p)
# set threshold for segment QC and filter to segments with reasonable target detection
target_data <- loq_data[fData(loq_data)$DetectionRate > loq_feature_filter_proportion |
fData(loq_data)$Negative==TRUE |
fData(loq_data)$TargetName %in% allow_list, ]
# Set targets without the negative probe for reporting purposes
target_data_no_negative <- loq_data[fData(loq_data)$DetectionRate > loq_feature_filter_proportion |
fData(loq_data)$TargetName %in% allow_list, ]
passed_loq_filter_features <- dim(target_data_no_negative)
#identify pheno data set
pheno_data_post_filter <- pData(loq_data)
pheno_data_post_filter[is.na(pheno_data_post_filter)] <- "NA"
PD_vec<-c("01-52","07-39","14-12","16-15","16-39","18-12","18-14","18-65","19-31")
cases<-pheno_data_post_filter$Case
PD_ind_qc<- cases %in% PD_vec
#PD_ind_qc<-which(PD_ind==TRUE)
pheno_data_post_filter<-pheno_data_post_filter[PD_ind_qc,]
sample_overview <- pheno_data_post_filter %>% dplyr::select(eval(factors_of_interest)) %>% plyr::count()
sample_overview_set <- gather_set_data(sample_overview, 1:length(factors_of_interest))
#specify sammple overview set
# pheno_data <- pData(probe_data)
# pheno_data[is.na(pheno_data)] <- "NA"
# pData(probe_data) <- pheno_data
#
# sample_overview <- pheno_data %>% dplyr::select(eval(factors_of_interest)) %>% plyr::count()
# sub<-which(sample_overview$AllenscData=="AI")
# sample_overview<-sample_overview[-sub,]
# sub<-which(sample_overview$AllenscData=="CPu")
# sample_overview<-sample_overview[-sub,]
# sample_overview_set <- gather_set_data(sample_overview, 1:length(factors_of_interest))
colors<- c("dodgerblue1", "firebrick1")
# Plot SanKey
p <- ggplot(data=sample_overview_set[,],
aes(x, id=id, split=y, value=freq)) +
geom_parallel_sets(aes_string(fill=sankey_focal_factor), alpha=0.5) +
geom_parallel_sets_axes(axis.width = 0.2) +
geom_parallel_sets_labels(color = "white", size = 2.5) +
theme_classic(base_size = 12) +
theme(legend.position = "bottom",
axis.ticks.y = element_blank(),
axis.line = element_blank(),
axis.text.y = element_blank()) +
scale_y_continuous(expand = expansion(0)) +
scale_x_discrete(expand = expansion(c(0, 0.2))) +
scale_fill_manual(values = colors) +
labs(x = "", y = "") +
annotate(geom = "segment", x = length(factors_of_interest) + 0.25,
xend = length(factors_of_interest) + 0.25,
y = round_any(nrow(pheno_data_post_filter)/10, 10),
yend = round_any(nrow(pheno_data_post_filter)/10, 10) +
round_any(nrow(pheno_data_post_filter)/4, 25), lwd = 2) +
annotate(geom = "text", x = length(factors_of_interest) + 0.35,
y = round_any(nrow(pheno_data_post_filter)/10, 10) +
round_any(nrow(pheno_data_post_filter)/4, 25)/2,
angle = 270, size = 5, hjust = 0.5,
label = paste0(round_any(nrow(pheno_data_post_filter)/4, 25), " segments"))
ggsave(p, filename = file.path(qc_dir, "SanKey_afterQC.svg"), width=3, height=3)
print(p)
if("QC" %in% factors_of_interest) {
factors_of_interest <- setdiff(factors_of_interest, "QC")
}
if(neg_norm==TRUE){
target_data <- normalize(target_data, norm_method = "neg",
fromElt = "exprs", toElt = "neg_norm")
assayDataElement(object = target_data, elt = "log_neg") <-
assayDataApply(target_data, 2, FUN = log, base = 2, elt = "neg_norm")
}
#nomralize nuclei count
# use norm_method = "quant" and desiredQuantile = 0.75 to normalize to Q3
assayDataElement(object = target_data, elt = "nuclei")<-t(assayDataApply(target_data, 1, FUN =function(x) x/target_data@phenoData@data$AOINucleiCount, elt="exprs"))
target_data <- normalize(target_data,
norm_method = "quant",
fromElt = "exprs",
toElt = "q_norm",
desiredQuantile = 0.75)
target_data <- normalize(target_data,
norm_method = "quant",
fromElt = "nuclei",
toElt = "nuc_q_norm",
desiredQuantile = 0.75)
#ind<-which(target_data@assayData$q_norm< 1)
#assayDataElement(object=target_data, elt = "q_norm")[ind]<-1
#ind<-which(target_data@assayData$nuc_q_norm< 1)
#assayDataElement(object=target_data, elt = "nuc_q_norm")[ind]<-1
assayDataElement(object = target_data, elt = "log_q") <-
assayDataApply(target_data, 2, FUN = log, base = 2, elt = "q_norm")
assayDataElement(object = target_data, elt = "nuc_log_q") <-
assayDataApply(target_data, 2, FUN = log, base = 2, elt = "nuc_q_norm")
#the above sets the original zeros to the minimum value observed in post normalization of the data. While this is biasing data somewhat, this is necessary and desirable to other methods typically utilized, such as adding 1 to all values, adding one to all 0 values, etc. This bias essential sets our zero values to the limit of detection in our dataset, which is about the minimum bias we can hopeful when dealing with zeros.
#if you want to use background subtraction, it's in the dataset
target_data <- normalize(target_data, norm_method = "subtractBackground",
fromElt = "exprs", toElt = "background_subtraction")
assayDataElement(target_data, "background_subtraction") <-
assayDataElement(target_data, elt= "background_subtraction") + 1
assayDataElement(object = target_data, elt = "log_background_subtraction") <-
assayDataApply(target_data, 2, FUN = log, base = 2, elt = "background_subtraction")
target_data <- normalize(target_data, norm_method = "quant",
fromElt = "background_subtraction", desiredQuantile = 0.75, toElt = "q_backSub_norm")
assayDataElement(object = target_data, elt = "log_backSub_q") <-
assayDataApply(target_data, 2, FUN = log, base = 2, elt = "q_backSub_norm")
saveRDS(object=target_data, file=file.path(object_dir, "target_data.RDS"))
negativeProbefData <- subset(fData(target_data), CodeClass == "Negative")
neg_probes <- unique(negativeProbefData$TargetName)
# Graph Q3 value vs negGeoMean of Negatives
ann_of_interest <- "segment"
Stat_data <-
data.frame(row.names = colnames(exprs(target_data)),
Segment = colnames(exprs(target_data)),
Annotation = pData(target_data)[, ann_of_interest],
Q3 = unlist(apply(exprs(target_data), 2,
quantile, 0.75, na.rm = TRUE)),
NegProbe = exprs(target_data)[neg_probes, ])
Stat_data_m <- melt(Stat_data, measure.vars = c("Q3", "NegProbe"),
variable.name = "Statistic", value.name = "Value")
plt1 <- ggplot(Stat_data_m,
aes(x = Value, fill = Statistic)) +
geom_histogram(bins = 40) + theme_bw() +
scale_x_continuous(trans = "log2") +
facet_wrap(~Annotation, nrow = 1) +
scale_fill_brewer(palette = 3, type = "qual") +
labs(x = "Counts", y = "Segments, #")
plt2 <- ggplot(Stat_data,
aes(x = NegProbe, y = Q3, color = Annotation)) +
geom_abline(intercept = 0, slope = 1, lty = "dashed", color = "darkgray") +
geom_point() + guides(color = "none") + theme_bw() +
scale_x_continuous(trans = "log2") +
scale_y_continuous(trans = "log2") +
theme(aspect.ratio = 1) +
labs(x = "Negative Probe GeoMean, Counts", y = "Q3 Value, Counts")+
scale_color_manual(values=c(NeuN="steelblue1", pSyn= "firebrick1"))
plt3 <- ggplot(Stat_data,
aes(x = NegProbe, y = Q3 / NegProbe, color = Annotation)) +
geom_hline(yintercept = 1, lty = "dashed", color = "darkgray") +
geom_point() + theme_bw() +
scale_x_continuous(trans = "log2") +
scale_y_continuous(trans = "log2") +
theme(aspect.ratio = 1) +
labs(x = "Negative Probe GeoMean, Counts", y = "Q3/NegProbe Value, Counts")+
scale_color_manual(values=c(NeuN="steelblue1", pSyn= "firebrick1"))
btm_row <- plot_grid(plt2, plt3, nrow = 1, labels = c("B", ""),
rel_widths = c(0.43,0.57))
p<-plot_grid(plt1, btm_row, ncol = 1, labels = c("A", ""))
ggsave(p, filename = file.path(qc_dir, paste0("q3_counts.svg")), "svg",
width=10, height=6)
print(p)
negativeProbefData <- subset(fData(target_data), CodeClass == "Negative")
neg_probes <- unique(negativeProbefData$TargetName)
# Graph Q3 value vs negGeoMean of Negatives
ann_of_interest <- "segment"
Stat_data <-
data.frame(row.names = colnames(exprs(target_data)),
Segment = colnames(exprs(target_data)),
Annotation = pData(target_data)[, ann_of_interest],
Q3 = unlist(apply(target_data@assayData$nuclei, 2,
quantile, 0.75, na.rm = TRUE)),
NegProbe = target_data@assayData$nuclei[neg_probes, ])
Stat_data_m <- melt(Stat_data, measure.vars = c("Q3", "NegProbe"),
variable.name = "Statistic", value.name = "Value")
plt1 <- ggplot(Stat_data_m,
aes(x = Value, fill = Statistic)) +
geom_histogram(bins = 40) + theme_bw() +