-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSimulationCode.R
More file actions
2690 lines (2268 loc) · 99.5 KB
/
SimulationCode.R
File metadata and controls
2690 lines (2268 loc) · 99.5 KB
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
#!/usr/bin/Rscript
#J. Harrison
#December 2018
#University of Wyoming
library(gtools)
library(rjags)
library(DESeq2)
library(edgeR)
library(EnvStats)
library(rstan)
library(exactRankTests)
library(nlme)
library(ggplot2)
library(ALDEx2)
# module load gcc/7.3.0
# module load r/3.5.0-py27
# module load r-rjags/4-6
# module load r-coda/0.19-1
# module load r-lattice/0.20-35
# module load r-rstan/2.17.2-py27
# module load r-rcpp
# module load r-rcppeigen
options(scipen=99)
#README
#You will have an additional file that has paramaters that will read one line at a time
#Each line will paramaterize a job, and all jobs will be run in concert.
#This program is made to be serially run via Slurm using the wrap_slurm_Moran_DMsim.pl script
#that script requires you to change a loop range so that the range matches
#the lines of parameters in your input parameter file.
#To those perusing this script, it is best to start at the bottom of the script
#where the function "main" is fed options from STDIN.
#Once you understand parameter input, then read function "main" with detours to
#each of the many functions that "main" calls.
#The parameters to be fed to this script are made via the
#simParamMaker.R script, which is just an expand grid of
#parameter vectors printed to an output file.
#####################
#Model specification#
#####################
community.model.level <- "model{
for(i in 1:N){
for(j in start[i]:end[i]){
datamatrix[j,] ~ dmulti(p[j,], nreads[j])
p[j,1:notus] ~ ddirch(pi[i,]*theta[i])
}
pi[i,1:notus] ~ ddirch(alpha)
theta[i] ~ dunif(0, 4000)
}
for(k in 1:notus){
alpha[k] <- 0.0000001
}
}"
#######################
#######################
#Function definitions##
#######################
#######################
##################################
#presented in alphabetical order #
##################################
aldexRun <- function(groupings,
otus,
fname = fname,
simcom_out = simcom_out){
aldeMC <- aldex(t(simcom_out$simulatedCommunity),
groupings,
mc.samples=1000,
test="t",
effect=TRUE,
include.sample.summary=FALSE,
denom="all",
verbose=FALSE)
#t test
positivesT <- which(aldeMC$we.eBH <= 0.05)
if(length(positivesT) >= 1){
negativesT <- otus[-which(otus %in% positivesT)]
}else{
negativesT <- otus
}
#Wilcoxon test
positivesW <- which(aldeMC$wi.eBH <= 0.05)
if(length(positivesW) >= 1){
negativesW <- otus[-which(otus %in% positivesW)]
}else{
negativesW <- otus
}
abund_category <- simcom_out$abund_category
different <- simcom_out$differentTaxa
params <- simcom_out$Parameters_alpha1_2_pi1_2
positives_diffT <- data.frame(positivesT, abund_category[positivesT])
negatives_diffT <- data.frame(negativesT, abund_category[negativesT])
# fp_effectsT <- params[1, positivesT[!(positivesT %in% different)]] - params[2, positivesT[!(positivesT %in% different)]]
#
# write.csv(fp_effectsT, file = paste("/project/microbiome/users/jharri62/DirichletSimulationPaper/dmmodelvetting/output/", fname, "_fp_effectsTaldex.csv"))
positives_diffW <- data.frame(positivesW, abund_category[positivesW])
negatives_diffW <- data.frame(negativesW, abund_category[negativesW])
# fp_effectsW <- params[1, positivesW[!(positivesW %in% different)]] - params[2, positivesW[!(positivesW %in% different)]]
#
# write.csv(fp_effectsW, file = paste("/project/microbiome/users/jharri62/DirichletSimulationPaper/dmmodelvetting/output/", fname, "_fp_effectsWaldex.csv"))
return(
list(
performanceAllT = fpr(
otus = otus,
xpos = positivesT,
xneg = negativesT,
different = simcom_out$differentTaxa
),
performance_abundT = fpr(
otus = otus[which(abund_category == "abund")],
xpos = positives_diffT$positives[which(positives_diffT$abund_category.positives. == "abund")],
xneg = negatives_diffT$negatives[which(negatives_diffT$abund_category.negatives. == "abund")],
different = simcom_out$exp_abund_differ
),
performance_medT = fpr(
otus = otus[which(abund_category == "med")],
xpos = positives_diffT$positives[which(positives_diffT$abund_category.positives. == "med")],
xneg = negatives_diffT$negatives[which(negatives_diffT$abund_category.negatives. == "med")],
different = simcom_out$exp_med_differ
),
performance_rareT = fpr(
otus = otus[which(abund_category == "rare")],
xpos = positives_diffT$positives[which(positives_diffT$abund_category.positives. == "rare")],
xneg = negatives_diffT$negatives[which(negatives_diffT$abund_category.negatives. == "rare")],
different = simcom_out$exp_rare_differ
),
performance_med_hiT = fpr(
otus = otus[which(abund_category %in% c("abund", "med"))],
xpos = positives_diffT$positives[which(positives_diffT$abund_category.positives. %in% c("abund", "med"))],
xneg = negatives_diffT$negatives[which(negatives_diffT$abund_category.negatives. %in% c("abund", "med"))],
different = c(simcom_out$exp_med_differ, simcom_out$exp_abund_differ)
),
#Wilcoxon
performanceAllW = fpr(
otus = otus,
xpos = positivesW,
xneg = negativesW,
different = different
),
performance_abundW = fpr(
otus = otus[which(abund_category == "abund")],
xpos = positives_diffW$positives[which(positives_diffW$abund_category.positives. == "abund")],
xneg = negatives_diffW$negatives[which(negatives_diffW$abund_category.negatives. == "abund")],
different = simcom_out$exp_abund_differ
),
performance_medW = fpr(
otus = otus[which(abund_category == "med")],
xpos = positives_diffW$positives[which(positives_diffW$abund_category.positives. == "med")],
xneg = negatives_diffW$negatives[which(negatives_diffW$abund_category.negatives. == "med")],
different = simcom_out$exp_med_differ
),
performance_rareW = fpr(
otus = otus[which(abund_category == "rare")],
xpos = positives_diffW$positives[which(positives_diffW$abund_category.positives. == "rare")],
xneg = negatives_diffW$negatives[which(negatives_diffW$abund_category.negatives. == "rare")],
different = simcom_out$exp_rare_differ
),
performance_med_hiW = fpr(
otus = otus[which(abund_category %in% c("abund", "med"))],
xpos = positives_diffW$positives[which(positives_diffW$abund_category.positives. %in% c("abund", "med"))],
xneg = negatives_diffW$negatives[which(negatives_diffW$abund_category.negatives. %in% c("abund", "med"))],
different = c(simcom_out$exp_med_differ, simcom_out$exp_abund_differ)
)
)
)
}
#################
#ANCOM function #
#################
# For debugging
# simcom_out <- simCom(
# modeltype = modeltype,
# notus = notus,
# nreads = nreads,
# nreps = nreps,
# precision = precision,
# seed = seed,
# num_da = num_da,
# effectsize = effectsize
# )
ancom <- function(simulatedData,
groupMem,
different,
otus,
fname = fname,
params = simcom_out$Parameters_alpha1_2_pi1_2,
abund_category,
rare_different = simcom_out$exp_rare_differ,
med_different = simcom_out$exp_med_differ,
abund_different = simcom_out$exp_abund_differ){
#This function takes the simulated community,
#the vector defining group membership,
#the vector of taxa that differ between treatment groups,
#and a vector from 1 to the total number of otus present within the data.
simulatedData[simulatedData == 1] <- 0
#Ancom looks for zeros to determine what to analyze, so converting back to zero
simulatedData2 <- data.frame(seq(1, length(groupMem), 1), simulatedData)
names(simulatedData2)[1] <- "Sample.ID"
metadat <- data.frame(simulatedData2$Sample.ID, groupMem)
names(metadat)[1] <- "Sample.ID"
#Perform the ANCOM analysis
ancom.out <- ANCOM.main(OTUdat = simulatedData2,
Vardat = metadat,
main.var = "groupMem",
adjusted = F,
sig = 0.05,
multcorr = 2,
repeated = FALSE,
prev.cut = 0.99)
#Identify those OTUs that ANCOM found to differ between sampling groups,
#and those OTUs that do not differ
#Note the if statement accounts for the bug in ANCOM where it assigns significance to all or most
#features. This bug is documented on the QIIME forums
#See: https://forum.qiime2.org/t/ancom-low-w-taxa-identified-as-significant-
#issues-workaround-ancom2-code-instructions/6040
#It is unclear what is causing this bug as it is not stable.
#ANCOM does not fail for all data simulated with the same parameters.
if(length(which(ancom.out$W.taxa$detected_0.9 == TRUE)) >= (dim(simulatedData)[2] * 0.9) ){
positives <- which(ancom.out$W.taxa$W_stat > 0)
negatives <- otus[-which(otus %in% positives)]
}else{
positives <- which(colnames(simulatedData) %in% ancom.out$W.taxa$otu.names[ancom.out$W.taxa$detected_0.9==TRUE])
if(length(positives) >= 1){
negatives <- otus[-which(otus %in% positives)]
}else{
negatives <- otus
}
}
positives_diff <- data.frame(positives, abund_category[positives])
negatives_diff <- data.frame(negatives, abund_category[negatives])
# fp_effects <- params[1, positives[!(positives %in% different)]] -
# params[2, positives[!(positives %in% different)]]
#
# write.csv(fp_effects, file = paste("/project/microbiome/users/jharri62/DirichletSimulationPaper/dmmodelvetting/output/", fname, "_fp_effectsDeseq.csv"))
return(
list(
performanceAll = fpr(
otus = otus,
xpos = positives,
xneg = negatives,
different = different
),
performance_abund = fpr(
otus = otus[which(abund_category == "abund")],
xpos = positives_diff$positives[which(positives_diff$abund_category.positives. == "abund")],
xneg = negatives_diff$negatives[which(negatives_diff$abund_category.negatives. == "abund")],
different = abund_different
),
performance_med = fpr(
otus = otus[which(abund_category == "med")],
xpos = positives_diff$positives[which(positives_diff$abund_category.positives. == "med")],
xneg = negatives_diff$negatives[which(negatives_diff$abund_category.negatives. == "med")],
different = med_different
),
performance_rare = fpr(
otus = otus[which(abund_category == "rare")],
xpos = positives_diff$positives[which(positives_diff$abund_category.positives. == "rare")],
xneg = negatives_diff$negatives[which(negatives_diff$abund_category.negatives. == "rare")],
different = rare_different
),
performance_med_hi = fpr(
otus = otus[which(abund_category %in% c("abund", "med"))],
xpos = positives_diff$positives[which(positives_diff$abund_category.positives. %in% c("abund", "med"))],
xneg = negatives_diff$negatives[which(negatives_diff$abund_category.negatives. %in% c("abund", "med"))],
different = c(med_different, abund_different)
)
)
)
}
#The first two functions are the ANCOM software, written by Mandal
ancom.W = function(otu_data,var_data,
adjusted,repeated,
main.var,adj.formula,
repeat.var,long,rand.formula,
multcorr,sig){
n_otu=dim(otu_data)[2]-1
otu_ids=colnames(otu_data)[-1]
if(repeated==F){
data_comp=data.frame(merge(otu_data,var_data,by="Sample.ID",all.y=T),row.names=NULL)
#data_comp=data.frame(merge(otu_data,var_data[,c("Sample.ID",main.var)],by="Sample.ID",all.y=T),row.names=NULL)
}else if(repeated==T){
data_comp=data.frame(merge(otu_data,var_data,by="Sample.ID"),row.names=NULL)
# data_comp=data.frame(merge(otu_data,var_data[,c("Sample.ID",main.var,repeat.var)],by="Sample.ID"),row.names=NULL)
}
base.formula = paste0("lr ~ ",main.var)
if(repeated==T){
repeat.formula = paste0(base.formula," | ", repeat.var)
}
if(adjusted==T){
adjusted.formula = paste0(base.formula," + ", adj.formula)
}
if( adjusted == F & repeated == F ){
fformula <- formula(base.formula)
} else if( adjusted == F & repeated == T & long == T ){
fformula <- formula(base.formula)
}else if( adjusted == F & repeated == T & long == F ){
fformula <- formula(repeat.formula)
}else if( adjusted == T & repeated == F ){
fformula <- formula(adjusted.formula)
}else if( adjusted == T & repeated == T ){
fformula <- formula(adjusted.formula)
}else{
stop("Problem with data. Dataset should contain OTU abundances, groups,
and optionally an ID for repeated measures.")
}
if( repeated==FALSE & adjusted == FALSE){
if( length(unique(data_comp[,which(colnames(data_comp)==main.var)]))==2 ){
tfun <- exactRankTests::wilcox.exact
} else{
tfun <- stats::kruskal.test
}
}else if( repeated==FALSE & adjusted == TRUE){
tfun <- stats::aov
}else if( repeated== TRUE & adjusted == FALSE & long == FALSE){
tfun <- stats::friedman.test
}else if( repeated== TRUE & adjusted == FALSE & long == TRUE){
tfun <- nlme::lme
}else if( repeated== TRUE & adjusted == TRUE){
tfun <- nlme::lme
}
logratio.mat <- matrix(NA, nrow=n_otu, ncol=n_otu)
for(ii in 1:(n_otu-1)){
for(jj in (ii+1):n_otu){
data.pair <- data_comp[,which(colnames(data_comp)%in%otu_ids[c(ii,jj)])]
lr <- log((1+as.numeric(data.pair[,1]))/(1+as.numeric(data.pair[,2])))
lr_dat <- data.frame( lr=lr, data_comp,row.names=NULL )
if(adjusted==FALSE&repeated==FALSE){ ## Wilcox, Kruskal Wallis
logratio.mat[ii,jj] <- tfun( formula=fformula, data = lr_dat)$p.value
}else if(adjusted==FALSE&repeated==TRUE&long==FALSE){ ## Friedman's
logratio.mat[ii,jj] <- tfun( formula=fformula, data = lr_dat)$p.value
}else if(adjusted==TRUE&repeated==FALSE){ ## ANOVA
model=tfun(formula=fformula, data = lr_dat,na.action=na.omit)
picker=which(gsub(" ","",row.names(summary(model)[[1]]))==main.var)
logratio.mat[ii,jj] <- summary(model)[[1]][["Pr(>F)"]][picker]
}else if(repeated==TRUE&long==TRUE){ ## GEE
model=tfun(fixed=fformula,data = lr_dat,
random = formula(rand.formula),
correlation=corAR1(),
na.action=na.omit)
picker=which(gsub(" ","",row.names(anova(model)))==main.var)
logratio.mat[ii,jj] <- anova(model)[["p-value"]][picker]
}
}
}
ind <- lower.tri(logratio.mat)
logratio.mat[ind] <- t(logratio.mat)[ind]
logratio.mat[which(is.finite(logratio.mat)==FALSE)] <- 1
mc.pval <- t(apply(logratio.mat,1,function(x){
s <- p.adjust(x, method = "BH")
return(s)
}))
a <- logratio.mat[upper.tri(logratio.mat,diag=FALSE)==TRUE]
b <- matrix(0,ncol=n_otu,nrow=n_otu)
b[upper.tri(b)==T] <- p.adjust(a, method = "BH")
diag(b) <- NA
ind.1 <- lower.tri(b)
b[ind.1] <- t(b)[ind.1]
#########################################
### Code to extract surrogate p-value
surr.pval <- apply(mc.pval,1,function(x){
s0=quantile(x[which(as.numeric(as.character(x))<sig)],0.95)
# s0=max(x[which(as.numeric(as.character(x))<alpha)])
return(s0)
})
#########################################
### Conservative
if(multcorr==1){
W <- apply(b,1,function(x){
subp <- length(which(x<sig))
})
### Moderate
} else if(multcorr==2){
W <- apply(mc.pval,1,function(x){
subp <- length(which(x<sig))
})
### No correction
} else if(multcorr==3){
W <- apply(logratio.mat,1,function(x){
subp <- length(which(x<sig))
})
}
return(W)
}
ANCOM.main = function(OTUdat,Vardat,
adjusted,repeated,
main.var,adj.formula,
repeat.var,longitudinal,
random.formula,
multcorr,sig,
prev.cut){
p.zeroes=apply(OTUdat[,-1],2,function(x){
s=length(which(x==0))/length(x)
})
zeroes.dist=data.frame(colnames(OTUdat)[-1],p.zeroes,row.names=NULL)
colnames(zeroes.dist)=c("Taxon","Proportion_zero")
zero.plot = ggplot(zeroes.dist, aes(x=Proportion_zero)) +
geom_histogram(binwidth=0.1,colour="black",fill="white") +
xlab("Proportion of zeroes") + ylab("Number of taxa") +
theme_bw()
#print(zero.plot)
OTUdat.thinned=OTUdat
OTUdat.thinned=OTUdat.thinned[,c(1,1+which(p.zeroes<prev.cut))]
otu.names=colnames(OTUdat.thinned)[-1]
W.detected <- ancom.W(OTUdat.thinned,Vardat,
adjusted,repeated,
main.var,adj.formula,
repeat.var,longitudinal,random.formula,
multcorr,sig)
W_stat <- W.detected
### Bubble plot
W_frame = data.frame(otu.names,W_stat,row.names=NULL)
W_frame = W_frame[order(-W_frame$W_stat),]
W_frame$detected_0.9=rep(FALSE,dim(W_frame)[1])
W_frame$detected_0.8=rep(FALSE,dim(W_frame)[1])
W_frame$detected_0.7=rep(FALSE,dim(W_frame)[1])
W_frame$detected_0.6=rep(FALSE,dim(W_frame)[1])
W_frame$detected_0.9[which(W_frame$W_stat>0.9*(dim(OTUdat.thinned[,-1])[2]-1))]=TRUE
W_frame$detected_0.8[which(W_frame$W_stat>0.8*(dim(OTUdat.thinned[,-1])[2]-1))]=TRUE
W_frame$detected_0.7[which(W_frame$W_stat>0.7*(dim(OTUdat.thinned[,-1])[2]-1))]=TRUE
W_frame$detected_0.6[which(W_frame$W_stat>0.6*(dim(OTUdat.thinned[,-1])[2]-1))]=TRUE
final_results=list(W_frame,zero.plot)
names(final_results)=c("W.taxa","PLot.zeroes")
return(final_results)
}
#CLR
clr <- function(x){
log(x) - (1/length(x))*sum(log(x))
}
######################################################
#DESEQ, determine differential expression using DESeq2
######################################################
# simulatedData = simcom_out$simulatedCommunity
# groupMem = groupings
# parameters = parameters
# different = simcom_out$differentTaxa
# otus = otus
# abund_category = simcom_out$abund_category
deseq <- function(simulatedData,
groupMem,
parameters,
params = simcom_out$Parameters_alpha1_2_pi1_2,
different,
otus,
simcom_out,
fname = fname,
abund_category,
rare_different = simcom_out$exp_rare_differ,
med_different = simcom_out$exp_med_differ,
abund_different = simcom_out$exp_abund_differ){
#This function takes the simulated community,
#the vector defining group membership,
# the vector of parameters used to make the data,
#the vector of taxa that differ between treatment groups (notzero),
#and a vector from 1 to the total number of otus present within the data.
#build two vectors, one for the treatment condition, the other for "batch",
#which is a needed argument for deseq
treatmentFactor <- data.frame(rep("batch1", dim(simulatedData)[1]),
groupMem)
names(treatmentFactor) <- c("batch", "condition")
#Remove OTUs with few reads, as per recommendations
#NOTE: we are not currently doing this to facilitate comparison among methods
# newmat <- simulatedData[,-which(colSums(simulatedData) <= 100)]
# simulatedData <- newmat
#Perform DESeq2 analysis
dds <- DESeqDataSetFromMatrix(countData = t(simulatedData),
colData = treatmentFactor,
design= ~condition)
dds <- estimateSizeFactors(dds)
#NOTE we use gene wise dispersion estimates because when replicates are used to estimate dispersion
#the function sometimes fails, particularly when data are simulated from a uniform distribution.
#I think this is because there is not enough variation among replicates for those cases.
dds <- estimateDispersionsGeneEst(dds)
dispersions(dds) <- mcols(dds)$dispGeneEst
dds <- nbinomWaldTest(dds)
dds_results <- results(dds)
#IMPORTANT: As per the DESEq2 vignette guidelines for benchmarking, I set NA values to 1.
#The adjusted p values output by DESEq2 are set to NA if the software thinks an outlier is present that should
#not be trusted, or if the mean number of sequences for that taxon is low enough that the results
#cannot be trusted. This is of course subject to change by the user in arbitrary ways.
ps <- ifelse(is.na(dds_results$padj), 1, dds_results$padj)
#Multiple comparison correction defaults to a Benjamini-Hochberg FDR correction
positives<- which(ps <= 0.05)
negatives <- which(ps > 0.05)
positives_diff <- data.frame(positives, abund_category[positives])
negatives_diff <- data.frame(negatives, abund_category[negatives])
#extract effect sizes for false positives
# fp_effects <- params[1, positives[!(positives %in% different)]] - params[2, positives[!(positives %in% different)]]
#
# write.csv(fp_effects, file = paste("/project/microbiome/users/jharri62/DirichletSimulationPaper/dmmodelvetting/output/", fname, "_fp_effectsDeseq.csv"))
# #
return(
list(
performanceAll = fpr(
otus = otus,
xpos = positives,
xneg = negatives,
different = different
),
performance_abund = fpr(
otus = otus[which(abund_category == "abund")],
xpos = positives_diff$positives[which(positives_diff$abund_category.positives. == "abund")],
xneg = negatives_diff$negatives[which(negatives_diff$abund_category.negatives. == "abund")],
different = abund_different
),
performance_med = fpr(
otus = otus[which(abund_category == "med")],
xpos = positives_diff$positives[which(positives_diff$abund_category.positives. == "med")],
xneg = negatives_diff$negatives[which(negatives_diff$abund_category.negatives. == "med")],
different = med_different
),
performance_rare = fpr(
otus = otus[which(abund_category == "rare")],
xpos = positives_diff$positives[which(positives_diff$abund_category.positives. == "rare")],
xneg = negatives_diff$negatives[which(negatives_diff$abund_category.negatives. == "rare")],
different = rare_different
),
performance_med_hi = fpr(
otus = otus[which(abund_category %in% c("abund", "med"))],
xpos = positives_diff$positives[which(positives_diff$abund_category.positives. %in% c("abund", "med"))],
xneg = negatives_diff$negatives[which(negatives_diff$abund_category.negatives. %in% c("abund", "med"))],
different = c(med_different, abund_different)
),
positives_diff = positives_diff,
negatives_diff = negatives_diff
)
)
}
#####################################################################################
#diffAbund: calculate differential relative abundance between control and treatment##
#####################################################################################
#For debugging
# SimulatedData = simcom_out$simulatedCommunity
# modelRun_out = modelRun_out$mcmcSamples
# groupings = groupings
# different = simcom_out$differentTaxa
# otus = otus
# uncommon = uncommon
# abund_category = simcom_out$abund_category
# exp_abund_differ = simcom_out$exp_abund_differ
# exp_med_differ = simcom_out$exp_med_differ
# exp_rare_differ = simcom_out$exp_rare_differ
diffAbund <- function(SimulatedData,
modelRun_out,
different,
groupings,
Parameters_alpha1_2_pi1_2,
otus,
fname = fname,
abund_category,
rare_different ,
med_different,
abund_different){
#Otus is a sequence from 1 to the number of otus in simulated dataset
calc_certain_diffsG <- function(mcmc_of_diffs){
positives <- vector()
negatives <- vector()
for(i in 1:dim(mcmc_of_diffs)[1]){
perc <- length(which(mcmc_of_diffs[i,] > 0)) / length(mcmc_of_diffs[i,])
if(perc >= 0.95 | perc <= 0.05){
positives <- c(positives, i)
}else{
negatives <- c(negatives, i)
}
}
return(list(positives = positives,
negatives = negatives))
}
diffs <- modelRun_out$pi[1,,,1:2] - modelRun_out$pi[2,,,1:2]
out <- calc_certain_diffsG(cbind(diffs[,,1], diffs[,,2]))
#extract effect sizes for false positives
# fp_effects <- Parameters_alpha1_2_pi1_2[1, out$positives[!(out$positives %in% different)]] - Parameters_alpha1_2_pi1_2[2, out$positives[!(out$positives %in% different)]]
#
# write.csv(fp_effects, file = paste("/project/microbiome/users/jharri62/DirichletSimulationPaper/dmmodelvetting/output/", fname, "_fp_effectsDMJags.csv", sep = ""))
##############################################
#Determine performance by abundance category #
##############################################
positives_diff <- data.frame(out$positives, abund_category[out$positives])
negatives_diff <- data.frame(out$negatives, abund_category[out$negatives])
#######################
#apply CLR and do over
#######################
#concatenate so that mcmc iterations are different columns
mcmc_clr_1 <- apply(cbind(modelRun_out$pi[1,,,1], modelRun_out$pi[1,,,2]),2,FUN = clr) #taxa as rows, mcmc samples as columns. iterating by column, so that we compute clr across taxa for each mcmc
mcmc_clr_2 <- apply(cbind(modelRun_out$pi[2,,,1], modelRun_out$pi[2,,,2]),2,FUN = clr)
diffs <- data.frame(matrix(nrow = dim(mcmc_clr_1)[1], ncol = dim(mcmc_clr_1)[2])) #taxa rows, mcmc samples columns, iterate by
for(i in 1:dim(mcmc_clr_1)[2]){
diffs[,i] <- mcmc_clr_1[,i] - mcmc_clr_2[,i] #differences in mcmc samples for all taxa
}
outclr <- calc_certain_diffsG(diffs)
# #The above line indexes properly because otus always starts at 1
#extract effect sizes for false positives
# fp_effects <- Parameters_alpha1_2_pi1_2[1, outclr$positives[!(outclr$positives %in% different)]] - Parameters_alpha1_2_pi1_2[2, outclr$positives[!(outclr$positives %in% different)]]
#
# write.csv(fp_effects, file = paste("/project/microbiome/users/jharri62/DirichletSimulationPaper/dmmodelvetting/output/", fname, "_fp_effectsDMJagsCLR.csv", sep = ""))
return(
list(
performanceAll = fpr(
otus = otus,
xpos = out$positives,
xneg = out$negatives,
different = different
),
performance_abund = fpr(
otus = otus[which(abund_category == "abund")],
xpos = positives_diff$positives[which(positives_diff$abund_category.positives. == "abund")],
xneg = negatives_diff$negatives[which(negatives_diff$abund_category.negatives. == "abund")],
different = abund_different
),
performance_med = fpr(
otus = otus[which(abund_category == "med")],
xpos = positives_diff$positives[which(positives_diff$abund_category.positives. == "med")],
xneg = negatives_diff$negatives[which(negatives_diff$abund_category.negatives. == "med")],
different = med_different
),
performance_rare = fpr(
otus = otus[which(abund_category == "rare")],
xpos = positives_diff$positives[which(positives_diff$abund_category.positives. == "rare")],
xneg = negatives_diff$negatives[which(negatives_diff$abund_category.negatives. == "rare")],
different = rare_different
),
performance_med_hi = fpr(
otus = otus[which(abund_category %in% c("abund", "med"))],
xpos = positives_diff$positives[which(positives_diff$abund_category.positives. %in% c("abund", "med"))],
xneg = negatives_diff$negatives[which(negatives_diff$abund_category.negatives. %in% c("abund", "med"))],
different = c(med_different, abund_different)
)
,positives_diff = positives_diff,
performanceAllclr = fpr(
otus = otus,
xpos = outclr$positives,
xneg = outclr$negatives,
different = different
)
)
)
}
diffStan <- function(SimulatedData,
different,
groupings,
Parameters_alpha1_2_pi1_2 = simcom_out$Parameters_alpha1_2_pi1_2,
otus,
fname = fname,
DM = DM,
abund_category = simcom_out$abund_category,
rare_different = simcom_out$exp_rare_differ,
med_different = simcom_out$exp_med_differ,
abund_different = simcom_out$exp_abund_differ){
fitstan_NUTS <- rstan::sampling(DM,
data=list(datamatrix=SimulatedData,
nreps=nrow(SimulatedData),
notus=ncol(SimulatedData),
N=2,
start = c(min(which(groupings == unique(groupings)[1])),
min(which(groupings ==unique(groupings)[2]))),
end = c(max(which(groupings == unique(groupings)[1])),
max(which(groupings == unique(groupings)[2])))),
chains=2,
control = list(max_treedepth = 10),
warmup=1000,
iter=2000,
thin=2,
algorithm="NUTS",
cores=2,
pars<-c("pi","theta"),
init = initcalculatorStan(dat = SimulatedData,
starts = c(min(which(groupings == unique(groupings)[1])),
min(which(groupings == unique(groupings)[2]))),
ends = c(max(which(groupings == unique(groupings)[1])),
max(which(groupings == unique(groupings)[2])))),
verbose=T)
est.pi<-rstan::extract(fitstan_NUTS,"pi")
diffs_NUTS <- est.pi$pi[,1,] - est.pi$pi[,2,]
calc_certain_diffs <- function(mcmc_of_diffs){
positives <- vector()
negatives <- vector()
for(i in 1:dim(mcmc_of_diffs)[2]){ #note the different dimension compared to rjags
perc <- length(which(mcmc_of_diffs[,i] > 0 ))/ length(mcmc_of_diffs[,i])
if(perc >= 0.95 | perc <= 0.05){
positives <- c(positives, i)
}else{
negatives <- c(negatives, i)
}
}
return(list(positives = positives,
negatives = negatives))
}
outNuts <- calc_certain_diffs(diffs_NUTS)
#extract effect sizes for false positives
# fp_effects <- Parameters_alpha1_2_pi1_2[1, outNuts$positives[!(outNuts$positives %in% different)]] - Parameters_alpha1_2_pi1_2[2, outNuts$positives[!(outNuts$positives %in% different)]]
#
# write.csv(fp_effects, file = paste("/project/microbiome/users/jharri62/DirichletSimulationPaper/dmmodelvetting/output/",fname,"_fp_effectsDMStan.csv", sep = ""))
positives_diff <- data.frame(outNuts$positives, abund_category[outNuts$positives])
negatives_diff <- data.frame(outNuts$negatives, abund_category[outNuts$negatives])
#Calculate RMSE
est.pi<-apply(rstan::extract(fitstan_NUTS,"pi")$pi,c(2,3),mean)
true.pi<- Parameters_alpha1_2_pi1_2
error.pi<-sqrt(mean((est.pi-true.pi)^2))
est.pi <- rstan::extract(fitstan_NUTS,"pi")
ci1 <- apply(est.pi$pi[,1,], 2, FUN=HDIofMCMC)
ci2 <- apply(est.pi$pi[,2,], 2, FUN=HDIofMCMC)
successes <- 0
fails <- 0
#Color designation is used for plots, if those are desired.
for(i in otus){
if(Parameters_alpha1_2_pi1_2[1,i] > ci1[1,i] & Parameters_alpha1_2_pi1_2[1,i] < ci1[2,i]){
successes <- successes + 1
}else{
fails <- fails + 1
}
if(Parameters_alpha1_2_pi1_2[2,i] > ci2[1,i] & Parameters_alpha1_2_pi1_2[2,i] < ci2[2,i]){
successes <- successes + 1
}else{
fails <- fails + 1
}
}
perf <- successes/(successes + fails)
write.csv(summary(fitstan_NUTS,
pars = c("pi"),
probs = c(0.025, 0.975))$summary,
file = paste("/project/microbiome/users/jharri62/DirichletSimulationPaper/dmmodelvetting/output/", fname, "_DiagnosticsDMStan.csv", sep = ""))
return(
list(
thetahmc = mean(rstan::extract(fitstan_NUTS,"theta")$theta),
performanceAll = fpr(
otus = otus,
xpos = outNuts$positives,
xneg = outNuts$negatives,
different = different
),
performance_abund = fpr(
otus = otus[which(abund_category == "abund")],
xpos = positives_diff$positives[which(positives_diff$abund_category.positives. == "abund")],
xneg = negatives_diff$negatives[which(negatives_diff$abund_category.negatives. == "abund")],
different = abund_different
),
performance_med = fpr(
otus = otus[which(abund_category == "med")],
xpos = positives_diff$positives[which(positives_diff$abund_category.positives. == "med")],
xneg = negatives_diff$negatives[which(negatives_diff$abund_category.negatives. == "med")],
different = med_different
),
performance_rare = fpr(
otus = otus[which(abund_category == "rare")],
xpos = positives_diff$positives[which(positives_diff$abund_category.positives. == "rare")],
xneg = negatives_diff$negatives[which(negatives_diff$abund_category.negatives. == "rare")],
different = rare_different
),
performance_med_hi = fpr(
otus = otus[which(abund_category %in% c("abund", "med"))],
xpos = positives_diff$positives[which(positives_diff$abund_category.positives. %in% c("abund", "med"))],
xneg = negatives_diff$negatives[which(negatives_diff$abund_category.negatives. %in% c("abund", "med"))],
different = c(med_different, abund_different)
),
positives_diff = positives_diff,
negatives_diff = negatives_diff,
rmse_hmc = error.pi,
hdi_overlap = perf
)
)
}
diffStan_VB <- function(SimulatedData= simcom_out$simulatedCommunity,
different = simcom_out$differentTaxa,
groupings,
Parameters_alpha1_2_pi1_2 = simcom_out$Parameters_alpha1_2_pi1_2,
otus,
fname = fname,
DM = DM,
abund_category,
rare_different = simcom_out$exp_rare_differ,
med_different = simcom_out$exp_med_differ,
abund_different = simcom_out$exp_abund_differ){
#This function originally defined in modelRun function
inits <- initcalculatorStan(dat = SimulatedData,
starts = c(min(which(groupings == unique(groupings)[1])),
min(which(groupings ==unique(groupings)[2]))),
ends = c(max(which(groupings == unique(groupings)[1])),
max(which(groupings == unique(groupings)[2]))))
fitstan_VB <-rstan::vb(DM,
data=list("datamatrix"=SimulatedData,
"nreps"=nrow(SimulatedData),
"notus"=ncol(SimulatedData),
"N"=2,
"start" = c(min(which(groupings == unique(groupings)[1])),
min(which(groupings ==unique(groupings)[2]))),
"end" = c(max(which(groupings == unique(groupings)[1])),
max(which(groupings == unique(groupings)[2])))),
algorithm="meanfield",
output_samples=1000,
check_data = T,
seed=123,
pars<-c("pi","theta")
#Note initialization seems to only make very modest speed improvements for vb
,init = list("p"= inits[[1]]$p,
"pi"= inits[[1]]$pi
# "alpha"= inits[[1]]$alpha,
# "theta"= inits[[1]]$theta
)
)
est.pi<-extract(fitstan_VB,"pi")
diffs_VB <- est.pi$pi[,1,] - est.pi$pi[,2,]
calc_certain_diffs <- function(mcmc_of_diffs){
positives <- vector()
negatives <- vector()
for(i in 1:dim(mcmc_of_diffs)[2]){
perc <- length(which(mcmc_of_diffs[,i] > 0 ))/ length(mcmc_of_diffs[,i])
if(perc >= 0.95 | perc <= 0.05){
positives <- c(positives, i)
}else{
negatives <- c(negatives, i)
}
}
return(list(positives = positives,
negatives = negatives))
}
outVB <- calc_certain_diffs(diffs_VB)
#extract effect sizes for false positives
# fp_effects <- Parameters_alpha1_2_pi1_2[1, outVB$positives[!(outVB$positives %in% different)]] -
# Parameters_alpha1_2_pi1_2[2, outVB$positives[!(outVB$positives %in% different)]]
#
# write.csv(fp_effects, file = paste("/project/microbiome/users/jharri62/DirichletSimulationPaper/dmmodelvetting/output/", fname,"_fp_effectsDMStanVB.csv", sep = ""))
#
positives_diff <- data.frame(outVB$positives, abund_category[outVB$positives])
negatives_diff <- data.frame(outVB$negatives, abund_category[outVB$negatives])
#Calculate RMSE
est.pi<-apply(est.pi$pi, c(2,3), mean)
true.pi<-Parameters_alpha1_2_pi1_2
error.pi<-sqrt(mean((est.pi-true.pi)^2))
est.pi<-extract(fitstan_VB,"pi")
#Truth in HDI
ci1 <- apply(est.pi$pi[,1,], 2, FUN=HDIofMCMC)
ci2 <- apply(est.pi$pi[,2,], 2, FUN=HDIofMCMC)
successes <- 0
fails <- 0
#Color designation is used for plots, if those are desired.
for(i in otus){
if(Parameters_alpha1_2_pi1_2[1,i] > ci1[1,i] & Parameters_alpha1_2_pi1_2[1,i] < ci1[2,i]){
successes <- successes + 1
}else{
fails <- fails + 1
}
if(Parameters_alpha1_2_pi1_2[2,i] > ci2[1,i] & Parameters_alpha1_2_pi1_2[2,i] < ci2[2,i]){
successes <- successes + 1
}else{
fails <- fails + 1
}
}