-
Notifications
You must be signed in to change notification settings - Fork 0
/
final_analysis.rmd
1763 lines (1439 loc) · 59.2 KB
/
final_analysis.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: "Data Analysis Supplement"
output:
html_document:
highlight: null
theme: lumen
toc: no
toc_float: no
pdf_document:
toc: yes
date: "March 6, 2020"
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, eval=FALSE, tidy.opts=list(width.cutoff=60),tidy=TRUE)
```
## Introduction
This document was prepared in support of our paper:
<center>
<b>The inflammasome of circulatory collapse: single cell analysis of survival on extra corporeal life support.</b>
Eric J. Kort MD, Matthew Weiland, Edgars Grins MD, Emily Eugster MS, Hsiao-yun Milliron PhD, Catherine Kelty MS, Nabin Manandhar Shrestha PhD, Tomasz Timek MD, Marzia Leacche MD, Stephen J Fitch MD, Theodore J Boeve MD, Greg Marco MD, Michael Dickinson MD, Penny Wilton MD, Stefan Jovinge MD PhD
</center>
The following sections document how the data for this paper were processed and
how the figures were generated. Those who wish to do so can recreate the
figures from the paper from data posted on GEO under accession
[GSE127221](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE127221), and
the code below. For efficient compiling of this document, the "eval=FALSE"
option was set globally. Readers desiring to repeat the analysis can either run
each code chunk below manually, or change the setting line at the top of the Rmd
file from:
```bash
knitr::opts_chunk$set(echo = TRUE, eval=FALSE)
```
to
```bash
knitr::opts_chunk$set(echo = TRUE, eval=TRUE)
```
And then knit the entire document, a process which may take several hours, and
may also fail if insufficient RAM is available.
The result of running this code is that all processed data and generated figures
will be produced and saved to the Final_Data directory. The figures should match
exactly what is in the publication (except for small variations due to random
processes--for example, the jitter applied to do plots to enable visualization
of overlapping points may be slightly different).
Since the processed data elements created below are save as RDS files in the
chunks that create them, you can execute just some of the chunks and then pick
up where you left off later.
## Pre-requisites
Running the following analysis requires a computer with R version >= 3.5.0 and
128GB of RAM, with `pandoc`, and development libraries for SSL, XML, and curl
installed. This would be achieved on a debian flavored server as follows:
```bash
sudo -s
apt-get update
apt-get -y install pandoc
apt-get -y install libssl-dev
apt-get -y install libcurl4-openssl-dev
apt-get -y install libxml2-dev
```
To run the following analysis, the file
[`GSE127221_PBMC_merged_filtered_recoded.rds`](ftp://ftp.ncbi.nlm.nih.gov/geo/series/GSE127nnn/GSE127221/suppl/GSE127221_PBMC_merged_filtered_recoded.rds.gz)
must be obtained from the GEO series related to this study (GSE127221). The
second panel of figure 4b requires the list of genes from Supplmental Table S5,
which is available in the gitub repository as `Final_Data/table_s5.txt`. The
following code assumes these files are within a subdirectory named "Final_Data"
underneath the working directory. Note that cloning the github repo will create
the necessary directory structure with supporting files. However,
`PBMC_merged_filtered_recoded.rds` is too large for the gitub repository, and
thus must be obtained from GEO using the linke above and saved in the Final_Data
directory.
For example:
```bash
git clone https://github.com/vanandelinstitute/va_ecls
cd va_ecls/Final_Data
wget ftp://ftp.ncbi.nlm.nih.gov/geo/series/GSE127nnn/GSE127221/suppl/GSE127221_PBMC_merged_filtered_recoded.rds.gz
gunzip *.gz
cd ..
```
If you are not using Rstudio, the following step (from within an R session) is required to install the rmarkdown tools. If you are using Rstudio, you can skip this.
```{r, eval=FALSE}
install.packages("rmarkdown")
# the next line will render this documnt, generating all the intermediate data files and figures
rmarkdown::render("final_analysis.rmd")
```
If you are using Rstudio, just click the Knit button, or run each chunk individually.
Next we check for, conditionally install, and load the required libraries:
```{r}
setRepositories(ind=c(1,2,3,4))
reqpkg <- c("clusterProfiler",
"cowplot",
"dendextend",
"devtools",
"doParallel",
"DOSE",
"dplyr",
"foreach",
"ggplot2",
"GGally",
"ggpubr",
"ggplotify",
"grid",
"irlba",
"Matrix",
"org.Hs.eg.db",
"pheatmap",
"reshape2",
"rsvd",
"survminer",
"stringr",
"survival")
missingpkg <- reqpkg[-which(reqpkg %in% installed.packages())]
if(length(missingpkg)) install.packages(missingpkg)
if(!"harmony" %in% installed.packages())
devtools::install_github("immunogenomics/harmony")
if(!"uwot" %in% installed.packages())
devtools::install_github("jlmelville/uwot")
if(!"rstatix" %in% installed.packages())
devtools::install_github("kassambara/rstatix")
reqpkg <- c(reqpkg, "harmony", "uwot", "rstatix")
for(i in reqpkg)
library(i, character.only = TRUE)
```
## Data Pre Processing
The data file `GSE127221_PBMC_merged_filtered_recoded.rds` contaings sequencing
data that was aligned and converted to UMI counts with the inDrop pipeline.
Barcodes were filtered to retain only cells with at least 500 unique counts.
As shown below, we then further filtered this dataset to select cells with
between 750 and 7500 unique counts in an effort to select true, single cells. We
then normalized by library size, scaled by a constant (10000), and log
transformed, as follows:
```{r}
dat <- readRDS("Final_Data/GSE127221_PBMC_merged_filtered_recoded.rds")
# filtering, somewhat subjectively, for true, single cells
cellCounts <- Matrix::rowSums(dat)
dat <- dat[which(cellCounts < 7500 & cellCounts > 750), ]
geneCounts <- Matrix::colSums(dat)
dat <- dat[ , which(geneCounts >= 10)]
# we want cells as row and genes as columns for ALRA
dat.m <- as(dat, "matrix")
rm(dat)
# normalize to library size and log transform
sizes <- rowSums(dat.m)
dat.n <- sweep(dat.m, MARGIN = 1, sizes, "/")
dat.n <- dat.n * 10E3
dat.n <- log(dat.n + 1)
saveRDS(dat.n, file="Final_Data/PBMC_merged_filtered_normalized.rds")
source("https://raw.githubusercontent.com/KlugerLab/ALRA/master/alra.R")
# ALRA uses the random SVD for performance reasons. If we don't set a seed,
# the results of the imputation will be very nearly but not exactly the same
# between runs.
set.seed(1010)
dat.imp <- alra(dat.n, k=50, q = 40)[[3]]
rownames(dat.imp) <- rownames(dat.n)
saveRDS(dat.imp, file="Final_Data/PBMC_merged_filtered_alra.rds")
```
For batch effect removal and UMAP visualization, we first need the principle
component loadings for the imputed dataset. Calculating just a partial PC
matrix (the first 20 PCs, which is plenty as we shall see from plotting the
standard deviations for each PC) using the `irlba` package makes this task much
more tractable in terms of both memory and time requirements.
```{r}
library(irlba)
dat.imp <- readRDS("Final_Data/PBMC_merged_filtered_alra.rds")
dat.pc <- prcomp_irlba(dat.imp, n=20)
rownames(dat.pc$x) <- rownames(dat.imp)
plot(dat.pc$sdev)
saveRDS(dat.pc, file="Final_Data/PBMC_merged_filtered_alra_pc.rds")
```
Next we regress away donor (batch) effect using the Harmony algorithm.
```{r}
library(harmony)
dat.pc <- readRDS("Final_Data/PBMC_merged_filtered_alra_pc.rds")
# patient id is the library id and each patient was a separate sequencing library
id <- gsub("\\..*", "", rownames(dat.pc$x))
dat.pc.h <- HarmonyMatrix(dat.pc$x, do_pca = FALSE,
data.frame(id=id),
"id",
theta = 4)
saveRDS(dat.pc.h, file="Final_Data/PBMC_merged_filtered_alra_pc_harmony.rds")
```
We can use these PC loadings to further reduce dimensionality (to 2 dimensions
suitable for visualization) with UMAP.
```{r}
library(uwot)
dat.pc.h <- readRDS(file="Final_Data/PBMC_merged_filtered_alra_pc_harmony.rds")
set.seed(1010)
umap.h <- umap(dat.pc.h, min_dist = 0.2, n_neighbors = 15, n_threads = 7)
umap.h <- data.frame(id = gsub("\\..*", "", rownames(dat.pc.h)),
UMAP1 = umap.h[,1],
UMAP2 = umap.h[,2])
saveRDS(umap.h, "Final_Data/PBMC_merged_filtered_alra_pc_harmony_umap.rds")
```
Note that we could put all of this data into a `SingleCellExperiment` object or
a Seurat or Monocol object. For most of the operations below which rely on the
normalized count data itself, there seemed to be negligible benefit for doing so
for the purposes of this analysis, so we prefered to keep the expression matrix
and metadata as separate objects and work on them directly. But feel free to
select another data structure that best fits your needs.
## Plot formats
We define a theme to tweak plotting formatting (I prefer bold axis labels,
etc.) and keep things consistent. We also create a helper function for the UMAP
plots.
```{r}
my_theme <- theme_bw() + theme(
strip.background = element_blank(),
strip.text = element_text(face = "bold", margin = margin(0,0,5,0), size=10),
panel.spacing = unit(1, "lines"),
plot.margin=unit(c(0.5,0.5,0.5,0.5),"cm"),
plot.title = element_text(size = 10,
margin=margin(0,0,5,0),
face="bold"),
axis.text = element_text(size=10),
axis.title.y = element_text(face = "bold",
margin = margin(t = 0, r = 0, b = 0, l = 0, unit="pt")),
axis.title.x = element_text(face = "bold",
margin = margin(t = 2, r = 0, b = 0, l = 0))
)
my_theme_wide_lab <- theme(
axis.title.y = element_text(face = "bold", margin = margin(t = 0, r = 10, b = 0, l = 0))
)
my_theme_no_labs <- my_theme + theme(axis.title = element_text(size=0))
my_theme_no_space <- my_theme + theme(plot.margin=unit(c(0,0,0,0),"cm"))
my_theme_wider_lab <- theme(
axis.title.y = element_text(face = "bold", margin = margin(t = 0, r = 20, b = 0, l = 0))
)
my_theme_pretty_grid <- theme(
panel.grid.major.y = element_line(color = "#8DBCD2", size = .3),
panel.grid.minor.y = element_line(color = "#A8CFD1", size = .1)
)
# pretty print p values
fp <- function(p) {
if(p < 0.001)
return("p < 0.001")
return(paste("p = ", round(p, 3)))
}
plotUmap <- function(p1, p2, size=1, alpha=0.1, color, label, palette, legend.position = "none") {
dat <- melt(data.frame(UMAP1 = p1, UMAP2 = p2, color=color),
id.vars = c("UMAP1", "UMAP2", "color"))
ggplot(dat, aes(x=UMAP2, y=UMAP1, color = color)) +
geom_point(alpha=alpha, pch=19, size=size, stroke=0) +
annotate("text", x = -10, y = -12, size=3, hjust=0, label = label) +
theme_bw() +
my_theme +
ylim(c(-12,12)) +
xlim(c(-12,12)) +
scale_color_manual(values=palette) +
theme(legend.position = legend.position) +
guides(color = guide_legend(override.aes = list(size=5, alpha=1)))
}
# helper function to load up data (unless, in the case of the largeish
# dat.imp object, it is already loaded). This is only every necessary
# if we are running just portions of the code below as opposed to rendering
# everything in one shot top to bottom.
load_init <- function() {
if(!exists("dat.imp"))
dat.imp <<- readRDS("Final_Data/PBMC_merged_filtered_alra.rds")
md <<- readRDS("Final_Data/metadata_clin_cyt.rds")
ix <- which(md$group == "Initial")
md <<- md[ix,]
md$Survived <<- factor(md$surv_time < 72, labels = c("Survived", "Died"))
}
types <- readRDS("Final_Data/cell_types.rds")
```
## Figure 1
```{r}
# load our data if we haven't already
load_init()
pv <- foreach (i = c(1:4)) %do% {
t.test(md[, i]~md$Survived)$p.value
}
pv.ev <- foreach (i = c(1:4)) %do% {
t.test(md[, i]~md$Survived, var.equal=TRUE)$p.value
}
# SOFA and eGFR have equal variance, the other two variables
# do not.
pv[[3]] <- pv.ev[[3]]
pv[[4]] <- pv.ev[[4]]
pv.a <- pv
# extract partial dataset to clean up labels, etc.
dat <- md[, 1:4]
dat$Survived <- md$Survived
colnames(dat) <- c("Age", "Arterial pH", "SOFA", "eGFR", "Survived")
# Panel 1A
pl_a <- foreach(i = 1:4) %do% {
gd <- data.frame(Survived = dat$Survived, y = dat[,i])
ggplot(gd, aes(x = Survived, y=y)) +
geom_jitter(width=0.1, height=0.1) +
stat_summary(fun.y = median, color = "red", geom ="point", aes(group = 1), size = 3,
show.legend = FALSE) +
ylab(colnames(dat)[i]) +
annotate("text",
size = 3,
fontface = 2,
label = fp(as.numeric(pv.a[i])),
x = -Inf,
y = Inf,
hjust = -0.1,
vjust = 1.5) +
scale_y_continuous(expand=expand_scale(mult = c(0.1,0.2), add = 0)) +
xlab("") +
theme_bw() +
my_theme +
my_theme_wide_lab +
my_theme_pretty_grid +
theme(axis.text.x = element_text(angle=315, hjust=0.1, vjust=0.5)) +
theme(plot.margin = unit(c(0.1,1,0.2,0.2), "lines"))
}
# png("fig_1a.png", width=1500, height=1500, res=300)
# plot_grid(plotlist=pl_a, ncol = 2, align="v")
# dev.off()
# Panel 1B
pv <- foreach (i = 9:13) %do% {
wilcox.test(md[, i]~md$Survived)$p.value
}
# note: we cannot do the p-value adjustment here because the other cytokines
# are not included in the dataset provided in this repository. So we will
# simply hard code the Holm corrected p-values here.
#pv <- p.adjust(pv, "holm")
pv <- c( 0.016174682, 0.011424845, 0.001272499, 0.008249142, 0.011424845)
# extra dataset to clean up labels, etc.
dat <- md[ , 9:13]
dat$Survived <- md$Survived
colnames(dat) <- gsub("(.{2,3})_(.{1,2})_.*", "\\1-\\2", colnames(dat))
options(scipen=1000000)
pl_b <- foreach(i = 1:5) %do% {
gd <- data.frame(Survived = dat$Survived, y = dat[,i]+1)
ggplot(gd, aes(x = Survived, y=y)) +
geom_jitter(width=0.05, height=0.05) +
stat_summary(fun.y = median,
color = "red",
geom ="point",
aes(group = 1),
size = 3,
show.legend = FALSE) +
ylab(bquote(log[10] ~ bold(.(colnames(dat)[i])) ~ scriptstyle("(pg/ml)"))) +
annotate("text",
size = 3,
fontface = 2,
label = paste("adj.", fp(as.numeric(pv[i]))),
x = -Inf,
y = Inf,
hjust = -0.1,
vjust = 1.5) +
scale_y_continuous(minor_breaks = scales::extended_breaks(15),
trans = "log10", breaks=c(0, 1, 10, 100, 1000, 10000, 100000),
labels = function(x) { format(round(log10(x)), scientific = FALSE)},
expand=expand_scale(mult = c(0.1,0.2), add = 0)) +
xlab("") +
theme_bw() +
my_theme +
my_theme_wide_lab +
my_theme_pretty_grid +
theme(axis.text.x = element_text(angle=315, hjust=0.1, vjust=0.5)) +
theme(plot.margin = unit(c(0.1,1,0,0.2), "lines"))
}
a <- plot_grid(plotlist=c(pl_a), ncol = 2, align="v")
b <- plot_grid(plotlist=c(pl_b), ncol = 2, align="v")
tiff("fig1.tif", compression = "lzw", width=4000, height=9000, res = 800)
plot_grid(a + theme(plot.margin = unit(c(.7, 0, 0, .7), "cm")),
b + theme(plot.margin = unit(c(.7, 0, 0, .7), "cm")),
nrow = 2,
ncol = 1,
rel_heights = c(0.4, 0.6),
labels = c("A", "B"))
dev.off()
# png("fig_1b.png", width=1500, height=2200, res=300)
# plot_grid(plotlist=c(pl), ncol = 2, align="v")
# dev.off()
```
## Figure 2
Figure 2A is just a schematic providing an overview of the study. The remaining
panels require inferred cell types, so we will do that first. Cell types are
defined based on RNA expression of canonical surface markers (see supplemental
Table S2 accompanying the paper). The original CITE-Seq paper (Zheng, et al.)
showed excellent correspondence between mRNA levels and cell surface protein
levels, so we decided that simply using mRNA expression as a proxy for cell
surface marker protein level might be a reasonable approach. We also tried a
more sophisticated anchor transfer method to leverage more the gene expression
data available here, but that method performed poorly in terms of correlation to
our FACS data. Since this simple method performed well, we just stuck with that.
First we define a list structure containig our cell type definitions. The
"gate" field indicates whether the corresponding marker should be expressed
(`gate = 1`) or not expressed (`gate = 0`). If `gate` is > 1, then `(gate - 1)`
is used as the threshold, although this was case only applies to erythrocytes
since hemolysis results in some HBA1 RNA is most droplets. We then apply
these gates to each cell. Where this results in more than one cell type
assignment (i.e., ambiguous assignment), the cells is assigned the "Unknown"
cell type.
```{r}
# load our data if we haven't already
load_init()
cellTypeDefs <- list(
"B Cells" = list(markers = c("CD19", "CD3E"),
gate = c(1, 0)),
# CD4 subpopulations can by CD2+/- and FOXP3 +/-, but not double positive
# Except for CD4 regulatory T which are double positive
"CD4+ Naive T" = list(markers = c("CD3E", "CD4", "CD8A", "CD2", "FOXP3", "NCAM1"),
gate = c(1, 1, 0, 0, 0, 0)),
"CD4+ Naive T" = list(markers = c("CD3E", "CD4", "CD8A", "CD2", "IL2RA", "FOXP3", "NCAM1" ),
gate = c(1, 1, 0, 0, 0, 1, 0)),
"CD4+ Memory T" = list(markers = c("CD3E", "CD4", "CD8A", "CD2", "B3GAT1", "FOXP3", "NCAM1"),
gate = c(1, 1, 0, 1, 0, 0, 0)),
"CD4+ Memory T" = list(markers = c("CD3E"
, "CD4", "CD8A", "CD2", "B3GAT1", "IL2RA", "FOXP3", "NCAM1"),
gate = c(1, 1, 0, 1, 0, 0, 1, 0)),
"CD4+ Effector T" = list(markers = c("CD3E", "CD4", "CD8A", "CD2", "B3GAT1", "FOXP3", "NCAM1"),
gate = c(1, 1, 0, 1, 1, 0, 0)),
"CD4+ Effector T" = list(markers = c("CD3E", "CD4", "CD8A", "CD2", "B3GAT1", "IL2RA", "FOXP3", "NCAM1"),
gate = c(1, 1, 0, 1, 1, 0, 1, 0)),
"CD4+ Reg T" = list(markers = c("CD3E", "CD4", "CD8A", "IL2RA", "FOXP3", "NCAM1"),
gate = c(1, 1, 0, 1, 1, 0)),
"CD8+ Memory T" = list(markers = c("CD3E", "CD4", "CD8A", "CD2", "B3GAT1", "NCAM1"),
gate = c(1, 0, 1, 1, 0, 0)),
"CD8+ Naive T" = list(markers = c("CD3E", "CD4", "CD8A", "CD2", "NCAM1"),
gate = c(1, 0, 1, 0, 0)),
"CD8+ Effector T" = list(markers = c("CD3E", "CD4", "CD8A", "CD2", "B3GAT1", "NCAM1"),
gate = c(1, 0, 1, 1, 1, 0)),
"NKT CD4+" = list(markers = c("CD3E", "CD4", "CD8A", "CD19", "NCAM1"),
gate = c(1, 1, 0, 0, 1)),
"NKT CD8+" = list(markers = c("CD3E", "CD4", "CD8A", "CD19", "NCAM1"),
gate = c(1, 0, 1, 0, 1)),
"NKT CD4- CD8-" = list(markers = c("CD3E", "CD4", "CD8A", "CD19", "NCAM1"),
gate = c(1, 0, 0, 0, 1)),
"NK" = list(markers = c("CD3E", "CD19", "NCAM1"),
gate = c(0, 0, 1)),
"CD16- Monocytes" = list(markers = c("CD14", "FCGR3A"),
gate = c(1, 0)),
"CD16+ Monocytes" = list(markers = c("CD14", "FCGR3A"),
gate = c(1, 1)),
"DC" = list(markers = c("CD3E", "CD14", "CD19", "NCAM1", "HLA-DRA"),
gate = c(0, 0, 0, 0, 1)),
"Erythrocytes" = list(markers = c("HBA1"),
gate = c(7))
)
classify <- function(dat, types) {
class <- rep(NA, nrow(dat))
res <- foreach(i = 1:length(types)) %do% {
m <- types[[i]][["markers"]]
cl <- foreach(j = 1:length(types[[i]][["markers"]]), .combine = "&") %do% {
if(types[[i]][["gate"]][j]) {
return(dat[ , m[j]] > types[[i]][["gate"]][j] - 1)
} else {
return(dat[ , m[j]] == 0)
}
}
if(length(which(cl)) > 0) {
class[which(cl & !is.na(class))] <- "AMBIG"
class[which(cl & is.na(class))] <- names(types)[i]
}
}
class
}
types <- classify(dat.imp, cellTypeDefs)
types[ which(types == "AMBIG") ] <- NA
types[ which(is.na(types)) ] <- "Unknown"
```
Note that the cell type definitions we have specified successfully assigns > 81%
of cells to a single cell type, with less than 6% of cells assigned to more than
one cell type (these abmiguous cell type assignments are removed). Some of the
remaining ~17% of cells may be unassigned due to technical drop outs, while the
others may be cell types we did not defined such as granulocytes that were not
successfully removed by the ficoll gradient isolation of PBMCs, circulating
epithelial cells, etc. Some may also represent empty droplets containing just
background RNA from lysed cells that made it past our data filtering step.
For figures legends and other plots, we want the cell types to be in a specific
order that is consistent and intuitive. So we define a function to set the
order of the cell type labels for any given list of cell types. We also want the
cell types to have consistent colors accross figures where applicable, so we
create a helper function for that too.
```{r}
cellTypes <- c('B Cells',
'CD4+ Naive T',
'CD4+ Memory T',
'CD4+ Effector T',
'CD4+ Reg T',
'CD8+ Naive T',
'CD8+ Memory T',
'CD8+ Effector T',
"NKT CD4+",
"NKT CD8+",
"NKT CD4- CD8-",
'NK',
'CD16- Monocytes',
'CD16+ Monocytes',
'DC',
'Erythrocytes',
'Unknown')
fixOrder <- function(x) {
order <- cellTypes[which(cellTypes %in% unique(x))]
factor(x, levels=order)
}
getCellPallette <- function(x) {
x <- factor(x)
cols<-c('#FFEE58',
'#E65100',
'#F57F15',
'#FF8A65',
'#FFCC80',
'#0277BD',
'#0097A7',
'#00BCD4',
'#1A237E',
'#512DA8',
'#9C27B0',
'#9FA8DA',
'gray', '#dddddd', "black", "red")
ix <- match(levels(x), cellTypes)
return(cols[ix])
}
types <- fixOrder(types)
saveRDS(types, "Final_Data/cell_types.rds")
```
To validate our scRNASeq analysis, we also performed FACS analysis on the same
samples to directly measure the surface marker expression of major lymphocyte
population markers. The percentages of the lymphocyte gate comprised of each
subtype as determined by FACS are included in the metadata file. Proportion of
lymphocytes in each population as assigned by FACS vs. scRNASeq is compared in
Panel B.
```{r}
# load our data if we haven't already
load_init()
md <- readRDS("Final_Data/metadata_facs.rds")
options(scipen=1000000)
fig2B <- function() {
# accumulate all our cell counts per sample, dropping non-lymphocytes
ids <- gsub("\\..*", "", rownames(dat.imp))
sc.counts <- as.data.frame.matrix(table(ids, types))[ , -c(16:17)]
# aggregate some sub-populations to match flow populations
sc.counts$`T Cells` <- sc.counts$`CD4+ Naive T` +
sc.counts$`CD4+ Memory T` +
sc.counts$`CD4+ Effector T` +
sc.counts$`CD4+ Reg T` +
sc.counts$`CD8+ Naive T` +
sc.counts$`CD8+ Memory T` +
sc.counts$`CD8+ Effector T` +
sc.counts$`NKT CD4+` +
sc.counts$`NKT CD8+` +
sc.counts$`NKT CD4- CD8-`
sc.counts$`CD4+ T Cells` <- sc.counts$`CD4+ Naive T` +
sc.counts$`CD4+ Memory T` +
sc.counts$`CD4+ Effector T` +
sc.counts$`CD4+ Reg T` +
sc.counts$`NKT CD4+`
sc.counts$`CD8+ T Cells` <- sc.counts$`CD8+ Naive T` +
sc.counts$`CD8+ Memory T` +
sc.counts$`CD8+ Effector T` +
sc.counts$`NKT CD8+`
# and convert to % of lymphocytes
sc.lymphs <- table(grepl("CD4", types) |
grepl("CD8", types) |
grepl("B Cell", types) |
grepl("NK", types), ids)[2,]
sc.props <- sweep(sc.counts, 1, sc.lymphs, "/")
sc.props <- as.data.frame.matrix(sc.props)
sc.props <- sc.props[match(md$id, rownames(sc.props)),]
# sanity check
all.equal(as.character(md$id), rownames(sc.props))
# extract the populations we are interested in
sc <- data.frame("B Cells" = sc.props$`B Cells`)
flow <- data.frame("B Cells" = md$`B Cells`)
# put space back in column names
colnames(sc)[1] <- "B Cells"
colnames(flow)[1] <- "B Cells"
sc$`T Cells` <- sc.props$`T Cells`
flow$`T Cells` <- md$`T Cells`
sc$`CD4+ T Cells` <- sc.props$`CD4+ T Cells`
flow$`CD4+ T Cells` <- md$`CD4+ T Cells`
sc$`CD8+ T Cells` <- sc.props$`CD8+ T Cells`
flow$`CD8+ T Cells` <- md$`CD8+ T Cells`
sc$`NK Cells` <- sc.props$NK
flow$`NK Cells` <- md$`NK Cells`
# assemble, melt, and plot
flow$ID <- md$id
sc$ID <- md$id
flow_m <- melt(flow, id.vars = c("ID"))
sc_m <- melt(sc, id.vars = c("ID"))
dat <- data.frame(ID = flow_m$ID, Population = flow_m$variable, Flow=flow_m$value, scRNASeq = sc_m$value)
ggplot(dat, aes(x = Flow, y = scRNASeq)) +
geom_smooth(method='lm',formula=y~x, color="#cccccc", se = FALSE) +
geom_point() +
stat_cor(method = "pearson",
aes(label = paste(..rr.label.., fp(..p..), sep = "~`,`~")),
size=3,
label.x = 0,
label.y = 0.95,
digits = 3,
color="black") +
facet_wrap( ~ Population, scales = "free", ncol = 3) +
scale_x_continuous(limits=c(0,1)) + scale_y_continuous(limits=c(0,1)) +
xlab(label = "Flow Cytometry") +
theme_bw(base_size=10) +
my_theme +
my_theme_wide_lab +
theme(
axis.text.x = element_text(angle = 315, hjust = 0),
legend.position = "none"
)
}
F2B <- fig2B()
png("fig2_b.png", height=1500, width=2000, type = "cairo", res = 300)
print(F2B)
dev.off()
```
Next we wanted to visualize the clustering of cells in two dimensional space
based on global gene expression in order to get a sense for whether we were
capturing major biological signals in the the scRNASeq data. What we are hoping
for is that there is minimal clustering by patient ID (after batch correction)
and predominant clustering by cell type. We also see whether there are
substantial clusters that distinguish cells from surviving vs. non-surving
patients at this level of analysis (if not, deeper interrogation within cell
types may be required).
```{r}
load_init()
types <- readRDS("Final_Data/cell_types.rds")
# types is the type of each cell, defined above
pal_cell <- getCellPallette(types)
# get palette of random colors for patient ID
colors = grDevices::colors()[grep('gr(a|e)y', grDevices::colors(), invert = T)]
set.seed(1010)
pal_id <- sample(colors, 38)
# and a two level palette for survival
pal_surv <- c("#1F70B0", "#BE1D2A")
umap <- readRDS("Final_Data/PBMC_merged_filtered_alra_pc_harmony_umap.rds")
ix <- which(types=="Unknown")
umap <- umap[-ix,]
types <- types[-ix]
dat <- dat.imp[-ix,]
ix.cell <- match(umap$id, md$Paper_ID)
a1 <- plotUmap(umap$UMAP1, umap$UMAP2,
color = umap$id,
label = "Normalized, color = id",
palette = pal_id)
a2 <- plotUmap(umap$UMAP1, umap$UMAP2,
color = types,
label = "Normalized, color = cell type",
palette = pal_cell,
legend.position = "bottom")
a3 <- plotUmap(umap$UMAP1, umap$UMAP2,
color = md$Survived[ix.cell],
label = "Normalized, color = survival",
palette = pal_surv,
legend.position = "bottom")
# extract the legends to put them in their own panels
leg1 <- get_legend(a2 +
guides(color = guide_legend(override.aes = list(size=5, alpha=1),
ncol=3,
title="Cell Type")) +
theme(legend.text = element_text(margin = margin(l = 2, r = 10, unit = "pt")),
legend.title = element_text(face=2, margin=margin(r=10, unit="pt"))))
leg2 <- get_legend(a3 +
guides(color=guide_legend(override.aes = list(size=5, alpha=1), title="Survival")) +
theme(legend.text = element_text(margin = margin(l = 2, r = 10, unit = "pt")),
legend.title = element_text(face=2, margin=margin(r=10, unit="pt"))))
a2 <- a2 + theme(legend.position = "none")
a3 <- a3 + theme(legend.position = "none")
# and assemble the plot
png("fig2_cde.png", height=1500, width=3000, type = "cairo", res = 300)
leg <- plot_grid(leg1, leg2, nrow=1, rel_widths = c(0.7, 0.3))
p <- plot_grid(a1, a2, a3,
nrow = 1, labels = c("", "", ""))
p <- plot_grid(p, leg,
nrow=2,
rel_heights = c(0.7, .3))
print(p)
dev.off()
```
## Supplemental Figure S1
Figure S1, stratified by surviving vs. non-surviving patients (72 hours).
```{r}
# load our data if we haven't already
load_init()
types <- readRDS("Final_Data/cell_types.rds")
figS1 <- function() {
ids <- gsub("\\..*", "", rownames(dat.imp))
# cell counts per patient, dropping unknown cells
# and erythrocytes
sc.counts <- as.data.frame.matrix(table(ids, types))[ , -c(16:17)]
# now convert to proportion of total cells
totals <- apply(sc.counts, 1, sum)
sc.counts.p <- sweep(sc.counts, 1, totals, "/")
ix <- match(rownames(sc.counts.p), as.character(md$Paper_ID))
# sanity check
all.equal(rownames(sc.counts.p), as.character(md$Paper_ID)[ix])
sc.counts.p$Survival <- md$Survived[ix]
sc.counts.p$ID <- md$Paper_ID[ix]
dat_m <- melt(sc.counts.p, id.vars = c("Survival", "ID"))
dat_m$variable <- fixOrder(dat_m$variable)
# now calculated p-value for t-test between survival groups
# for each cell type, adjusting for multiple comparisons
# and also format resulting labels and locations for plotting
stat.test <- dat_m %>%
group_by(variable) %>%
t_test(value ~ Survival)
stat.test$p.adj <- p.adjust(method = "holm", stat.test$p)
stat.test$yloc <- 0.75 * unlist(tapply(dat_m$value, INDEX = dat_m$variable, max))
stat.test$x <- rep(1, nrow(stat.test))
stat.test$p <- paste0(" p=", format(round(stat.test$p,3), nsmall=3), "\n",
"adj. p=", format(round(stat.test$p.adj,3), nsmall=1))
median2 <- function(x) { t <- median(x, na.rm=TRUE); return(data.frame(ymin=t, ymax=t, y=t))}
# And plot. Colors will match the colors in Figure 2, and Figure 3A
ggplot(dat_m, aes(x=Survival, y=value, color=variable)) +
stat_summary(fun.data = median2, size = 0.5, geom="crossbar", width=0.6) +
stat_pvalue_manual(stat.test, label = "p", remove.bracket = TRUE,
x="x", hjust=0,
y.position = "yloc",
tip.length = 0,
size = 3.5,
color="#444444") +
geom_jitter(width=0.07) +
scale_color_manual( values = getCellPallette(dat_m$variable)) +
ylab("Proportion of all Cells") +
facet_wrap( ~ variable, scales = "free", nrow = 5) +
my_theme +
my_theme_wide_lab +
theme(legend.position = "none")
}
FS1 <- figS1()
png("figS1.png", height=3000, width=2000, type = "cairo", res = 300)
print(FS1)
dev.off()
```
## Figure 3
As none of the major cell types seemed predictive of survival, we wanted to
drill into each cell type and find biological processes and surface markers that
might distinguish surviving vs. non-surviving patients. Panel B displays the
results of this analysis. For identification of differentially expressed genes
and associated biological processes, we limited our analysis to those genes that
had variable expression defined as having an expression level normalized robust
z-score greater than 2. This approach is the same as that described in Zheng et
al. (2017) and Macosko, et al. (2015).
Here is the function we used to calculate the dispersion for each gene:
```{r}
dispersion <- function(x, dim=2, verbose=FALSE) {
if(verbose) message("Calculating means (1 of 4)")
means <- apply(x, dim, mean, na.rm=TRUE)
if(verbose) message("Calculating dispersion (2 of 4)")
disp <- apply(x, dim, function(x) { var(x, na.rm=TRUE) / mean(x, na.rm=TRUE)})
if(verbose) message("Binning (3 of 4)")
bins <- cut(means, quantile(means, seq(0, 1, len = 20)), include.lowest = TRUE)
if(verbose) message("Normalizing (4 of 4)")
rv <- tapply(disp, bins, function(y) { abs(y - median(y)) / mad(y)})
rv <- unlist(rv)
names(rv) <- gsub("\\[.*\\]\\.", "", names(rv))
rv
}
```
We then used this function to identify the variable gene set based on cells of
known type (as defined above) that were not erythrocytes.
```{r}
# load our data if we haven't already
load_init()
types <- readRDS("Final_Data/cell_types.rds")
ix <- which(!types %in% c("Erythrocytes", "Unknown"))
dat <- dat.imp[ix,]
disp <- dispersion(dat)
ix <- which(disp > 2)
gg <- gsub(".*\\]\\.", "", names(disp))
gg <- gg[ix]
# remove pseudogenes and non-coding genes from a list of genes
expGenes <- function(x) {
x <- x[-which(grepl("A\\w\\d*\\.\\d", x))]
x <- x[-which(grepl("C\\d{1,2}orf", x))]
x <- x[-which(grepl("^LINC\\d+$", x))]
x
}
gg <- expGenes(gg)
ix <- which(colnames(dat) %in% gg)
dat <- dat[,ix]
saveRDS(dat, file = "Final_Data/PBMC_merged_filtered_alra_variable_genes.rds")
```
Now we need helper functions to calculate the proportion of cells within each
subtype that express each gene for each patient.
```{r}
# load our data if we haven't already
load_init()
applyById <- function(x, ids, FUN=function(x) { sum(x>0) }) {
ids.x <- gsub("\\..*", "", names(x))
rv <- foreach(i=ids, .combine = c) %do% {
ix <- which(ids.x == i)
if(length(ix)) {
FUN(x[ix])
} else {
0
}
}
names(rv) <- ids
rv
}
# convenience wrapper
countsById <- function(x, ids) {
applyById(x, ids, length)
}
# convenience alias
positiveById <- function(x, ids) {
applyById(x,ids)
}
R_na_zero <- function(x) {
ix <- which(is.na(x))
if(length(ix)) x[ix] <- 0
x
}
genesProp <- function(types, dat, cluster=TRUE) {
calcRatio <- function(x, ix.s, ix.d, ids.s, ids.d) {