-
Notifications
You must be signed in to change notification settings - Fork 0
/
adipo_deconv.Rmd
1713 lines (1458 loc) · 49.3 KB
/
adipo_deconv.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: "Decovlution of differentiating adipoyctes"
author: "Mahmoud Shaaban"
date: "2/3/2020"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE, error = FALSE, cache = TRUE)
```
# Overview
The code in this document reproduces the figures and tables for the manuscript
titled "Decovlution of differentiating adipoyctes." We start by obtaining the
the input data, loading the required libraries and explaining the structure of
the analysis workflow. The rest of the document shows the code to generate the
output of the analysis including the intermediary data objects and the final
figures and tables.
# Obtaining the data
This analysis is based on gene expression data from a time course experiment
of 3T3-L1 induced for differentiation using MDI and sampled at multiple time
points. Another similar dataset of induced human primary adipocytes using the
same protocol. Finally, a dataset of gene expression of induced 3T3-L1 with
chemical course perturbation is used.
The following code chunck downloads the datasets to the `data/` directory. The
contents of this directory include:
- `adipo_counts.rds`: A `SummarizedExperiment` containing the RNA-Seq gene
expression of the time course experiment of 3T3-L1 pre-adipocytes
- `primary_adipocyte.rds`: An `ExpressionSet` containing the microarrays gene
expression of the time course experiment of human primary adipocytes
- `perturbations_md.csv`: A text file containing the metadata of the
perturbation experiments
- `pharmacological_perturbation.rds`: A `SummarizedExperiment` object
containing the microarrays gene expression with induction and perturbations of
3T3-L1 pre-adipocytes
```{r get_data}
# download data files
if (!file.exists('data.zip')) {
download.file(
'https://ndownloader.figshare.com/articles/12840101/versions/1',
destfile = 'data.zip'
)
unzip('data.zip', exdir = 'data')
}
```
# Loading libraries
The following code chunk load the required R packages. These packages fall in
one of four categories: data management, analysis, visualization and annotation.
```{r load_libraries}
# data management
library(SummarizedExperiment)
library(reshape2)
library(tidyverse)
# analysis packages
library(clusterProfiler)
library(debCAM)
library(pdist)
library(limma)
library(PSEA)
library(deSolve)
library(scales)
library(DESeq2)
library(usedist)
library(fgsea)
library(Hmisc)
library(pcr)
# data visualization
library(xtable)
library(ggalt)
library(gridExtra)
library(png)
library(ComplexHeatmap)
library(cowplot)
library(circlize)
library(GGally)
# annotation packages
library(org.Mm.eg.db)
library(GO.db)
```
# Prepaing the gene expression data
## Differentiating 3T3-L1 pre-adipocytes
The dataset `adipo_counts` consists of RNA-Seq read counts in mm10 known genes.
The samples were generated from MDI-induced 3T3-L1 adipocytes and profiled at
different times points.
```{r mouse_cell}
# load gene counts
adipo_counts <- read_rds('data/adipo_counts.rds')
# extract the expression matrix
mat <- assay(adipo_counts)
dim(mat)
# extract time info
time <- adipo_counts$time
table(time)
```
Now we need to subset the data to the differentiation stages with sufficient
samples. Then we transform the `SummarizedExperiment` object into `DESeq` object
to apply the transformation `vst`.
```{r make_deseq_object}
# filter low samples stage
se <- adipo_counts[, adipo_counts$stage %in% c(0, 1, 3)]
# transform the data
dds <- DESeqDataSet(se, ~stage)
dds_transform <- vst(dds)
```
## Differentiating human primary adipocytes
The dataset `primary_se` was generated by treating human sub-cutanous fat cells
using MDI. The samples were collected before and 7 days after treatment and
profiled using microarrays.
```{r human_cell}
# load primary adipocytes
primary_se <- read_rds('data/primary_adipocyte.rds')
dim(primary_se)
# inverse the log2 transformation
primary_mat <- 2 ^ na.omit(exprs(primary_se))
# extract group information
group <- primary_se$group
table(group)
```
## Drug perturbation of differentiating 3T3-L1
The dataset `pharma_mats` is the expression matrices composed of several
experiments. In each experiment, MDI-induced 3T3-L1 cells were treated with a
drug/compound and compared to non-treated controls.
```{r perturbations}
# load selected sample info
selected_samples <- read_csv('data/perturbations_md.csv')
selected_list <- split(selected_samples, selected_samples$series_id)
table(selected_samples$treatment_type)
# load and subset data
pharma <- read_rds('data/pharmacological_perturbation.rds')
pharma_mats <- map(selected_list, function(x) {
se <- pharma[, colnames(pharma) %in% x$sample_id]
na.omit(assay(se))
})
map(pharma_mats, dim)
# reverse the log2 transformation
pharma_mats$GSE42220 <- 2^pharma_mats$GSE42220
pharma_mats$GSE64075 <- 2^pharma_mats$GSE64075
```
# Data analysis
## Multi-dimensional scaling (MDS) analysis
In this section, we apply multidimensional scaling (MDS) analysis to
differentiating adipocytes. The distances between the samples are calculated
using `dist` and passed to `cmdscale`
```{r perform_mds}
# dissimilarity of samples
d <- dist(t(assay(dds_transform)))
# multidimensional scaling
mds <- cmdscale(d)
# format mds table
mds_df <- mutate(as.data.frame(mds),
stage = ifelse(se$stage == 3, 'S2', paste0('S', se$stage)))
```
This figure shows the first two dimensions of the MDS colored by stage of
differentiation. In other words, the samples are laid out on two dimensions
plane in a way to approximate the distances among them.
```{r plot_mds}
# make mds plot
mds_df %>%
ggplot(aes(x = V1, y = V2, color = stage)) +
geom_point() +
geom_encircle() +
labs(x = 'Dimension One',
y = 'Dimension Two',
color = 'Differentiation') +
theme_bw() +
theme(legend.position = 'none',
panel.grid = element_blank(),
panel.border = element_rect(size = 1.2)) +
annotate('text', -50, 50, label = 'S0', color = 'red') +
annotate('text', 90, 50, label = 'S1', color = 'blue') +
annotate('text', 50, -50, label = 'S2', color = 'darkgreen')
```
A simple diagnostic of this analysis is to calculate the distances between
samples within and inbetween each groups. The groups can be compared using
`t.test`.
```{r more_distances}
# calculate full matrix distances
dist_groups <- dist_groups((d), dds_transform$stage)
# show the distribution of the distances
# hist(d)
hist(dist_groups$Distance)
# split the distances by labels
dist_group_list <- split(dist_groups$Distance, dist_groups$Label)
# test 0 and 1 samples are farther than samples withing 0
t.test(dist_group_list$`Between 0 and 1`,
dist_group_list$`Within 0`,
alternative = 'greater')
# test 0 and 3 samples are farther than samples withing 0
t.test(dist_group_list$`Between 0 and 3`,
dist_group_list$`Within 0`,
alternative = 'greater')
```
Other diagnostics for the MDS is to show the godness-of-fit which shows how
much of the variance is explained by the two dimensions.
```{r more_mds}
# call mds with diagnostics
mds2 <- cmdscale(dist(t(assay(dds_transform))),
k = 2,
list. = TRUE,
eig = TRUE)
# eigenvalues
barplot(mds2$eig)
# gof
mds2$GOF
# dissimilarity
dissim <- cmdscale(1/(cor((assay(dds_transform)))),
k = 2,
eig = TRUE)
# stress
k <- 2:10
stress <- map(k, function(x) MASS::isoMDS(d, k = x)$stress)
plot(k, unlist(stress))
```
## Deconvolution analysis
```{r deconvolve_mouse}
# set a seed
set.seed(111)
# run deconvolution
rCAM <- CAM(mat,
K = 2:5,
thres.low = 0.30,
thres.high = 0.95,
cores = 4)
```
```{r mdl}
# calculate mdl
mdl <- MDL(rCAM)
# format mdl table
mdl <- tibble(Data = mdl@datalengths,
Model = mdl@mdls,
k = mdl@K) %>%
gather(key, val, -k)
```
```{r mdl_plot}
# plot mdl
mdl %>%
ggplot(aes(x = k, y = val, group = key, color = key)) +
geom_point() +
geom_line(size = 1.2) +
scale_y_continuous(labels = scales::scientific) +
labs(x = 'Number of Sources', y = 'Code Length', color = '') +
theme_linedraw() +
theme(legend.position = 'top') -> mdl_plot
```
```{r extract_estimates}
# extract estimate matrices and markers
n <- 3
aset <- Amat(rCAM, n)
sset <- Smat(rCAM, n)
markers <- MGsforA(rCAM, n)
names(markers) <- paste0('P', 1:3)
```
```{r fraction_time_plot}
# plot fractions over time
aset_df <- aset %>%
as_tibble() %>%
setNames(paste0('P', 1:3)) %>%
mutate(time = time) %>%
gather(pop, frac, -time)
aset_df %>%
ggplot(aes(x = time, y = frac, color = pop, group = pop)) +
geom_point() +
geom_smooth(se = FALSE) +
labs(x = 'Time (hour)', y = 'Fraction of Cells') +
theme_bw() +
theme(legend.position = 'none',
panel.grid = element_blank(),
panel.border = element_rect(size = 1.5)) +
annotate('text', x = rep(260, 3), y = c(.03, .32, .65),
label = c('P3', 'P1', 'P2'),
color = c('blue', 'red', 'darkgreen')) -> fraction_time
```
```{r get_simplex}
# extract simplex data
devtools::install('debCAM/')
simplex <- debCAM::simplexplot(mat,
aset,
markers,
plot = FALSE)
# format simplex table
simplex <- as_tibble(t(simplex)) %>%
mutate(gene = rownames(t(simplex))) %>%
left_join(melt(markers) %>% setNames(c('gene', 'pop'))) %>%
mutate(pop = ifelse(!is.na(pop), paste0('P', pop), NA))
```
```{r simplex_plot}
# plot simplex
simplex %>%
ggplot(aes(x = V1, y = V2)) +
geom_point(color = 'gray') +
geom_point(data = na.omit(simplex), aes(color = pop)) +
labs(x = 'Dimension One', y = 'Dimension Two',
color = 'Sup-Population') +
theme_bw() +
theme(legend.position = 'none',
panel.grid = element_blank(),
panel.border = element_rect(size = 1.5)) +
annotate('text', x = c(-.05, .15, 0), y = c(-.25, 0, .2),
label = c('P3', 'P1', 'P2'),
color = c('blue', 'red', 'darkgreen')) -> simplexplot
```
```{r markers_plot}
# plot the adipogenic markers
adipo_markers <- list('Adipogenic' = c('Pparg', 'Cebpb', 'Cebpa', 'Adipoq'),
'Lipogenic' = c('Lpl', 'Acly', 'Fasn', 'Plin1', 'Lipe'))
# subset estimated expression by adipogenic markers
adipo_mat <- sset[rownames(sset) %in% unlist(adipo_markers),]
adipo_mat <- adipo_mat[unlist(adipo_markers),]
# rename columns
colnames(adipo_mat) <- paste0('P', 1:3)
# make heatmap
png(filename = 'manuscript/adipogenic_markers.png',
height = 9, width = 6, units = 'cm', res = 300)
exprs_color <- colorRamp2(c(0, 20), c('white', 'darkblue'))
Heatmap(log2(adipo_mat + 1),
col = exprs_color,
row_split = rep(names(adipo_markers), lengths(adipo_markers)),
show_heatmap_legend = FALSE,
column_names_rot = 0,
column_names_centered = TRUE)
dev.off()
```
```{r other_markers}
#other_markers <- list(
# 'Insulin' = c('Insr', 'Irs1', 'Slc2a4', 'Pdgfb'),
# 'WT1' = c('Wt1', 'Ucp1'),
# 'Keratins' = c('Krt5', 'Krt14', 'Krt15')
# )
other_markers <- c('Insr', 'Irs1', 'Slc2a4', 'Pdgfb')
# subset the estimated expression matrix by other marekrs
other_mat <- sset[rownames(sset) %in% other_markers,]
other_mat <- other_mat[other_markers,]
# rename the columns
colnames(other_mat) <- paste0('P', 1:3)
# make a plot
png(filename = 'manuscript/other_markers.png',
height = 6, width = 6, units = 'cm', res = 300)
exprs_color <- colorRamp2(c(0, 15), c('white', 'darkblue'))
Heatmap(log2(other_mat + 1),
col = exprs_color,
show_heatmap_legend = FALSE,
column_names_rot = 0,
column_names_centered = TRUE)
dev.off()
```
```{r markers_stats}
# calculate markers stats (fold-change)
fold_change <- MGstatistic(mat + .01,
aset,
boot.alpha = 0.05,
nboot = 1000,
cores = 4)
# format markers statistics
markers_stats <- fold_change %>%
rownames_to_column('gene') %>%
dplyr::filter(gene %in% unlist(markers), OVE.FC != Inf, !grepl('Rik', gene)) %>%
mutate(idx = paste0('P', idx),
gene = fct_reorder(gene, OVE.FC)) %>%
group_by(idx)
```
```{r markers_fc_plot}
markers_stats %>%
dplyr::slice(1:5) %>%
ggplot(aes(x = gene, y = log2(OVE.FC))) +
geom_col() +
scale_y_continuous(limits = c(0,6.2), expand = c(0, .1)) +
facet_wrap(~idx, scales = 'free_x') +
theme_bw() +
theme(axis.text.x = element_text(angle = 45, hjust = 1),
strip.background = element_blank(),
panel.spacing = unit(-.05, 'cm'),
panel.grid = element_blank(),
panel.border = element_rect(size = 1.5)) +
labs(x = '', y = 'Fold-change (log_2)') -> markers_fc
```
```{r more_markersstats}
# summarizing fold-change of the markers
summary(markers_stats$OVE.FC)
markers_stats %>%
ggplot(aes(x = log2(OVE.FC))) +
geom_density() +
facet_wrap(~idx)
summary(markers_stats$OVE.FC.alpha)
markers_stats %>%
ggplot(aes(x = (OVE.FC.alpha))) +
geom_density() +
facet_wrap(~idx)
```
```{r more_markers}
mm <- adipo_markers
mm$other <- other_markers
melt(mm) %>%
setNames(c('gene', 'category')) %>%
left_join(rownames_to_column(fold_change, 'gene'))
```
```{r estimate_human}
# subset to common gene symbols
new_markers <- map(markers, function(x) {
intersect(toupper(x), rownames(primary_mat))
})
# estimate the populations fractions
set.seed(111)
rre <- redoASest(primary_mat,
new_markers,
maxIter = 10)
# format re-restimated fractions
rre_df <- as_tibble(rre$Aest) %>%
setNames(paste0('P', 1:3)) %>%
mutate(group = factor(group, levels = c('NDf', 'Df'))) %>%
gather(pop, frac, -group)
rre_ave <- rre_df %>%
group_by(pop, group) %>%
dplyr::summarise(frac = mean(frac))
```
```{r primary_plot}
# make a plot for the fractions in primary adipocytes
rre_df %>%
ggplot() +
geom_jitter(aes(x = group, y = frac, color = pop, group = pop),
width = .1) +
geom_point(data = rre_ave,
aes(x = group, y = frac, color = pop, group = pop)) +
geom_line(data = rre_ave, aes(x = group, y = frac, color = pop, group = pop), size = 1) +
theme_linedraw() +
theme(legend.position = 'top') +
labs(x = '', y = 'Fraction of Cells') +
theme_bw() +
theme(legend.position = 'none',
panel.grid = element_blank(),
panel.border = element_rect(size = 1.5)) +
annotate('text', x = rep(2.3, 3), y = c(.05, .35, .62),
label = c('P3', 'P1', 'P2'),
color = c('blue', 'red', 'darkgreen')) +
scale_x_discrete(labels = c('HPP', 'HPP + MDI')) -> primary_adipocytes
```
```{r distances}
# calculate distance between sub-populations
## common symbols
ind <- intersect(toupper(rownames(sset)), rownames(rre$Sest))
## rename rows
mm <- sset
rownames(mm) <- toupper(rownames(mm))
## subset matrix
mm <- mm[ind,]
hs <- rre$Sest[ind,]
## get distances
dist_models <- as.matrix(pdist(t(log2(mm + 1)), t(log2(hs + 1))))
## rename columns and rows
rownames(dist_models) <- paste0('P', 1:3)
colnames(dist_models) <- paste0('P', 1:3)
## get correlations
m1 <- as.matrix(scale(mm))
colnames(m1) <- paste('MMP', 1:3)
m2 <- as.matrix(scale(hs))
colnames(m2) <- paste('HSP', 1:3)
cor_mat <- cor(m1, m2, method = 'spearman')
colnames(cor_mat) <- paste0('P', 1:3)
rownames(cor_mat) <- paste0('P', 1:3)
```
```{r distances_plot,eval=FALSE}
# make a distance heatmap
png(filename = 'manuscript/distances.png',
height = 5, width = 5, units = 'cm', res = 300)
dmat <- (dist_models/min(dist_models)) - 1
dist_color <- colorRamp2(c(0, max(dmat)), c('white', 'darkblue'))
Heatmap(dmat,
col = dist_color,
show_heatmap_legend = FALSE,
column_names_rot = 0,
column_names_centered = TRUE)
dev.off()
```
```{r correlations_plot}
# make a distance heatmap
png(filename = 'manuscript/distances.png',
height = 5, width = 5, units = 'cm', res = 300)
cor_color <- colorRamp2(c(min(cor_mat), max(cor_mat)),
c('white', 'darkblue'))
Heatmap(cor_mat,
col = cor_color,
show_heatmap_legend = FALSE,
column_names_rot = 0,
column_names_centered = TRUE)
dev.off()
```
```{r more_population_correlations}
rcorr(m1, m2, type = 'spearman') %>%
map_df(melt, .id = 'type')
```
```{r iterations}
# run iterated estimations of fractions
iterated_rre <- rerun(100, {
# sample markers to lowest group number
m <- map(markers, ~sample(.x, 35))
# estimate fractions
a <- redoASest(mat,
m,
maxIter = 2,
methy = FALSE)
# formate the coutpus
a$Aest %>%
as_tibble() %>%
setNames(paste0('P', 1:3)) %>%
mutate(time = adipo_counts$time)
}) %>%
bind_rows(.id = 'iteration')
```
```{r iterations_plot}
# make iterations plot
iterated_rre %>%
gather(pop, frac, -time,-iteration) %>%
ggplot(aes(y = frac, x = time, group = iteration)) +
geom_smooth() +
facet_wrap(~pop, nrow = 1) +
labs(x = 'Time (hour)', y = 'Fraction of Cells',
color = 'Sub-population') +
theme_bw() +
theme(panel.spacing = unit(-.05, 'cm'),
strip.background = element_blank(),
panel.grid = element_blank(),
panel.border = element_rect(size = 1.5)) -> fraction_time_iterations
```
```{r iterations_bootstrapping}
# gather estimated fractions by populations
iteractions_groups <- iterated_rre %>%
gather(pop, frac, starts_with('P'))
# show the density of estimated fractions at different times
iteractions_groups %>%
ggplot(aes(x = frac, group = as.factor(time))) +
geom_density() +
facet_wrap(~pop)
# show the histogram of the cv of estimated fractions
iteractions_stats <- iteractions_groups %>%
group_by(time, pop) %>%
summarise(ave = mean(frac),
se = var(frac),
cv = se/ave)
iteractions_stats %>%
ggplot(aes(x = cv)) +
geom_histogram() +
facet_wrap(~pop)
# what is most cv like?
iteractions_stats %>%
with(cv < .1) %>%
table()
# calculate bias in bootstrapped estimates
iterations_bias <- aset_df %>%
group_by(time, pop) %>%
summarise(frac = mean(frac)) %>%
ungroup() %>%
full_join(iteractions_stats) %>%
mutate(bias = frac - ave)
# show the distribution of bias
iterations_bias %>%
ggplot(aes(x = abs(bias))) +
geom_histogram() +
facet_wrap(~pop)
iterations_bias %>%
with(bias < .1) %>%
table()
```
```{r deconv_pharma}
# run deconv
pharma_rre <- map(pharma_mats, function(x) {
redoASest(x, markers)
})
# extract fractions
pharma_fractions <- map_df(pharma_rre, function(x) {
as_tibble(x$Aest) %>%
setNames(paste0('P', 1:3)) %>%
mutate(sample_id = rownames(x$Aest))
}, .id = 'series_id') %>%
gather(pop, frac, starts_with('P'))
```
## Over-representation analysis
```{r go_annotations}
# extract annotations
## get mouse gene symbols
symbols <- keys(org.Mm.eg.db, 'SYMBOL')
## get go ids to symbols
term2gene <- AnnotationDbi::select(org.Mm.eg.db,
symbols,
'GO',
'SYMBOL') %>%
dplyr::select(term = GO, gene = SYMBOL) %>%
unique()
## get go terms
terms <- as.data.frame(GOTERM)
terms <- tibble(ID = terms$go_id,
term = terms$Term,
definition = terms$Definition,
ontology = terms$Ontology)
## intersect markers symbols with go symbols
markers_symbols <- map(markers, intersect, y = unique(term2gene$gene))
str(markers_symbols)
```
```{r over_representation}
# run over-representation test
comp <- map_df(markers_symbols,
function(x) {
enricher(x,
TERM2GENE = term2gene,
pAdjustMethod = 'fdr')@result
}, .id = 'population')
```
```{r}
# set.seed(123)
# comp2 <- compareCluster(markers_symbols,
# fun = 'enricher',
# TERM2GENE = term2gene,
# pAdjustMethod = 'fdr')
# comp2@compareClusterResult %>%
# inner_join(terms) %>%
# as_tibble() %>%
# dplyr::select(Cluster, ontology, term, pvalue, p.adjust, qvalue, Count) %>%
# dplyr::filter(p.adjust < .2) %>%
# unique() %>%
# arrange(Cluster, ontology, desc(Count)) %>%
# write_csv('manuscript/tables/marker_enrichment.csv')
```
```{r more_ova}
# inner_join(terms, comp) %>%
# dplyr::filter(pvalue < .05, Count > 3) %>%
# dplyr::select(population, ontology, term, pvalue, p.adjust, qvalue) %>%
# unique() %>%
# arrange(population, ontology) %>%
# write_csv('manuscript/tables/marker_enrichment.csv')
```
```{r gsea}
ove_fc <- MGstatistic(sset + 1,
A = paste0('P', 1:3),
boot.alpha = 0.05,
cores = 4)
ove_fc2 <- map2(split(ove_fc$OVE.FC, ove_fc$idx),
split(rownames(ove_fc), ove_fc$idx),
function(vec, nm) {
names(vec) <- nm
vec
})
str(ove_fc2)
go_ids <- dplyr::filter(comp, p.adjust < .2, Count > 2) %>%
pull(ID) %>%
unique()
go_terms <- AnnotationDbi::select(org.Mm.eg.db,
go_ids,
'SYMBOL',
'GO') %>%
with(split(SYMBOL, GO)) %>%
map(unique)
comp_pops <- map_df(ove_fc2, function(x) {
ind <- c('GO:0050873', 'GO:0004879', 'GO:0003707')
fgsea(go_terms[ind],
x,
nperm = 1000,
nproc = 4)
}, .id = 'pop') %>%
left_join(terms, by = c('pathway'='ID'))
```
## Differential expression analysis
```{r occupancy}
# # get counts in peaks
# peak_counts <- read_rds('data/peak_counts.rds')
#
# # subset to POLR2A
# se_pol <- peak_counts[, grepl('POLR2A', peak_counts$factor)]
#
# # aggregate by gene
# mat_pol <- assay(se_pol) %>%
# as_tibble() %>%
# mutate(gene = as.character(mcols(se_pol)$geneId)) %>%
# group_by(gene) %>%
# summarise_all(sum) %>%
# ungroup() %>%
# column_to_rownames('gene')
```
```{r estimate_fractions_occupance}
# # estimate fractions based on occupancy
# rre_pol <- redoASest(mat_pol, markers, maxIter = 10)
```
```{r population_markers}
# cell cycle index genes
mat_pop <- assay(adipo_counts)[c('Ank2', 'Aldoc', 'Gapdh'),
adipo_counts$time %in% c(0:10 * 24)]
tt <- adipo_counts$time[adipo_counts$time %in% c(0:10 * 24)]
as_tibble(t(mat_pop)) %>%
mutate(time = tt) %>%
group_by(time) %>%
summarise_all(mean)
```
```{r occupancy_fractions}
# rre_pol$Aest %>%
# as_tibble() %>%
# setNames(paste0('P', 1:3)) %>%
# mutate(time = se_pol$time) %>%
# gather(pop, frac, -time) %>%
# ggplot(aes(x = time, y = frac, color = pop, group = pop)) +
# geom_point() +
# geom_smooth(se = FALSE) +
# labs(x = 'Time Point (hour)', y = 'Fraction of Cells',
# color = 'Sub-population') +
# theme_linedraw() +
# theme(legend.position = 'top') -> fraction_time_trans
```
```{r cc_index}
# define calculate index function
calculate_index <- function(mat, pos, neg = NULL, n) {
vecs <- list(pos = pos, neg = neg) %>%
map(function(x) {
ind <- rownames(mat) %in% x
m <- mat[ind,]
m
})
if(!is.null(neg)) {
(colSums(vecs$pos) - vecs$neg)/n
} else {
colSums(vecs$pos)/n
}
}
# cell cycle index genes
indecies <- list(
pos = c('Mki67', 'Rb1', 'Hist1h2ae', 'Ccnb1', 'Cbx3', 'Gapdh', 'Ccnb2'),
neg = c('E2f1')
)
mat <- assay(dds_transform)
time <- dds_transform$time
cc_index <- tibble(
t = time[time %in% c(0, 24, 48)],
i = calculate_index(
mat[,time %in% c(0, 24, 48)],
indecies$pos,
indecies$neg,
8)
)
```
```{r cc_index_ecdf}
cc_index %>%
ggplot(aes(x = scales::rescale(i, to = c(0, 1)), color = as.factor(t))) +
stat_ecdf(size = 1.5) +
theme_bw() +
theme(legend.position = c(.2, .8),
panel.grid = element_blank(),
legend.background = element_blank(),
panel.border = element_rect(size = 1.5)) +
labs(x = 'Cell Cycle Index',
y = 'Cumulative Distribution',
color = '') -> cc_index_ecdf
```
```{r more_ecdf}
cc_groups <- split(cc_index$i, cc_index$t)
ks.test(cc_groups$`24`, cc_groups$`0`, alternative = 'less')
ks.test(cc_groups$`24`, cc_groups$`48`, alternative = 'less')
```
```{r cc_expression}
cc_expression <- mat[rownames(mat) %in% unlist(indecies), time %in% c(0, 24, 48)] %>%
melt() %>%
as_tibble() %>%
setNames(c('gene', 'id', 'count')) %>%
inner_join(tibble(id = dds$id, time = as.factor(dds$time)))
```
```{r more_cc_expression}
# run deseq with time as a factor
dds_time <- DESeqDataSet(se, ~as.factor(time))
dds_time <- DESeq(dds_time)
# get fold change for all genes
stats <- list('0' = 'as.factor.time.0',
'48' = 'as.factor.time.48') %>%
map(function(x) {
res <- results(dds_time,
contrast = list('as.factor.time.24', x),
tidy = TRUE)
vec <- res$log2FoldChange
names(vec) <- res$row
vec
})
# calculate enrichment of cell cycle indicies
set.seed(12345)
map_df(stats,
function(x) {
fgsea::fgsea(list('Cell Cycle' = unlist(indecies)),
x,
nperm = 1000,
nproc = 4)
}, .id = 'time')
```
```{r cc_index_expression}
cc_expression %>%
ggplot(aes(x = time, y = rescale(count, c(0, 1)))) +
geom_boxplot(notch = TRUE, size = 1) +
labs(x = 'Time (hr)',
y = 'Expression of Cell Cycle Genes') +
theme_bw() +
theme(panel.grid = element_blank(),
panel.border = element_rect(size = 1.5)) -> cc_index_expression
```
```{r cc_population_specific}
# population specific expression of cell cycle index genes
models <- map(list('24 vs 0 (hr)' = c(0, 24),
'48 vs 24 (hr)' = c(24, 48)), function(t) {
ind <- dds$time %in% t
se <- dds[, ind]
se <- se[rowMeans(assay(se)) > 0,]
fac <- ifelse(se$time == t[1], 0, 1)
refs <- map(markers, function(x) marker(assay(se), intersect(rownames(se), x)))
diffs <- map(refs, function(x) fac * x)
gens <- unlist(indecies)
names(gens) <- unlist(indecies)
list(
P1 = map(gens,function(i) lm(assay(se)[i,] ~ refs$P1 + diffs$P1)),
P2 = map(gens,function(i) lm(assay(se)[i,] ~ refs$P2 + diffs$P2))
)
})
cr <- map_df(models,
function(t) map_df(t,
function(p) map_df(p,
function(p) {
tibble(cr = as.numeric(residuals(p) + as.matrix(p$model[,-1]) %*% p$coef[-1]),
ref = p$model[, 2],
diff = p$model[, 3])
}, .id = 'gene'),.id = 'pop'), .id = 'time')
```
```{r cc_psea}
cr %>%
ggplot(aes(x = ref, y = rescale(cr))) +
geom_point(size = .5, color = 'darkgray') +
geom_smooth(method = 'lm', se = FALSE) +
facet_grid(pop ~ time) +
labs(x = 'Population Specific Expression',
y = 'Partial Residuals') +
scale_y_continuous(breaks = seq(0, 1, .2), labels = seq(0, 1, .2)) +
theme_bw() +
theme(panel.grid = element_blank(),
panel.border = element_rect(size = 1.5),
strip.background = element_blank(),