-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmethods.R
executable file
·2264 lines (1966 loc) · 93.2 KB
/
methods.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#' Main Function for SCCOMP Estimate
#'
#' @description
#' The `sccomp_estimate` function performs linear modeling on a table of cell counts or proportions,
#' which includes a cell-group identifier, sample identifier, abundance (counts or proportions), and factors
#' (continuous or discrete). The user can define a linear model using an R formula,
#' where the first factor is the factor of interest. Alternatively, `sccomp` accepts
#' single-cell data containers (e.g., Seurat, SingleCellExperiment, cell metadata, or
#' group-size) and derives the count data from cell metadata.
#'
#' @import dplyr
#' @importFrom magrittr %$%
#' @importFrom magrittr divide_by
#' @importFrom magrittr multiply_by
#' @importFrom magrittr equals
#' @importFrom rlang quo_is_null
#' @importFrom SingleCellExperiment colData
#' @importFrom parallel detectCores
#' @importFrom rlang inform
#' @importFrom lifecycle is_present
#' @importFrom lifecycle deprecate_warn
#'
#' @param .data A tibble including cell_group name column, sample name column,
#' abundance column (counts or proportions), and factor columns.
#' @param formula_composition A formula describing the model for differential abundance.
#' @param formula_variability A formula describing the model for differential variability.
#' @param .sample A column name as a symbol for the sample identifier.
#' @param .cell_group A column name as a symbol for the cell-group identifier.
#' @param .abundance A column name as a symbol for the cell-group abundance, which can be counts (> 0) or proportions (between 0 and 1, summing to 1 across `.cell_group`).
#' @param cores Number of cores to use for parallel calculations.
#' @param bimodal_mean_variability_association Logical, whether to model mean-variability as bimodal.
#' @param prior_mean A list specifying prior knowledge about the mean distribution, including intercept and coefficients.
#' @param prior_overdispersion_mean_association A list specifying prior knowledge about mean/variability association.
#' @param percent_false_positive A real number between 0 and 100 for outlier identification.
#' @param inference_method Character string specifying the inference method to use ('pathfinder', 'hmc', or 'variational').
#' @param .sample_cell_group_pairs_to_exclude A column name indicating sample/cell-group pairs to exclude.
#' @param output_directory A character string specifying the output directory for Stan draws.
#' @param verbose Logical, whether to print progression details.
#' @param enable_loo Logical, whether to enable model comparison using the LOO package.
#' @param noise_model A character string specifying the noise model (e.g., 'multi_beta_binomial').
#' @param exclude_priors Logical, whether to run a prior-free model.
#' @param use_data Logical, whether to run the model data-free.
#' @param mcmc_seed An integer seed for MCMC reproducibility.
#' @param max_sampling_iterations Integer to limit the maximum number of iterations for large datasets.
#' @param pass_fit Logical, whether to include the Stan fit as an attribute in the output.
#' @param sig_figs Number of significant figures to use for Stan model output. Default is 9.
#' @param .count DEPRECATED. Use .abundance instead.
#' @param approximate_posterior_inference DEPRECATED. Use inference_method instead.
#' @param variational_inference DEPRECATED. Use inference_method instead.
#' @param ... Additional arguments passed to the `cmdstanr::sample` function.
#'
#' @return A tibble (`tbl`) with the following columns:
#' \itemize{
#' \item cell_group - The cell groups being tested.
#' \item parameter - The parameter being estimated from the design matrix described by the input `formula_composition` and `formula_variability`.
#' \item factor - The covariate factor in the formula, if applicable (e.g., not present for Intercept or contrasts).
#' \item c_lower - Lower (2.5%) quantile of the posterior distribution for a composition (c) parameter.
#' \item c_effect - Mean of the posterior distribution for a composition (c) parameter.
#' \item c_upper - Upper (97.5%) quantile of the posterior distribution for a composition (c) parameter.
#' \item c_pH0 - Probability of the null hypothesis (no difference) for a composition (c). This is not a p-value.
#' \item c_FDR - False-discovery rate of the null hypothesis for a composition (c).
#' \item c_n_eff - Effective sample size for a composition (c) parameter.
#' \item c_R_k_hat - R statistic for a composition (c) parameter, should be within 0.05 of 1.0.
#' \item v_lower - Lower (2.5%) quantile of the posterior distribution for a variability (v) parameter.
#' \item v_effect - Mean of the posterior distribution for a variability (v) parameter.
#' \item v_upper - Upper (97.5%) quantile of the posterior distribution for a variability (v) parameter.
#' \item v_pH0 - Probability of the null hypothesis for a variability (v).
#' \item v_FDR - False-discovery rate of the null hypothesis for a variability (v).
#' \item v_n_eff - Effective sample size for a variability (v) parameter.
#' \item v_R_k_hat - R statistic for a variability (v) parameter.
#' \item count_data - Nested input count data.
#' }
#'
#' @examples
#'
#' print("cmdstanr is needed to run this example.")
#' # Note: Before running the example, ensure that the 'cmdstanr' package is installed:
#' # install.packages("cmdstanr", repos = c("https://stan-dev.r-universe.dev/", getOption("repos")))
#'
#' \donttest{
#' if (instantiate::stan_cmdstan_exists()) {
#' data("counts_obj")
#'
#' estimate <- sccomp_estimate(
#' counts_obj,
#' ~ type,
#' ~1,
#' sample,
#' cell_group,
#' count,
#' cores = 1
#' )
#'
#' # Note!
#' # If counts are available, do not use proportion.
#' # Using proportion ignores the high uncertainty of low counts
#'
#' estimate_proportion <- sccomp_estimate(
#' counts_obj,
#' ~ type,
#' ~1,
#' sample,
#' cell_group,
#' proportion,
#' cores = 1
#' )
#'
#' }
#' }
#'
#' @export
sccomp_estimate <- function(.data,
formula_composition = ~1,
formula_variability = ~1,
.sample,
.cell_group,
.abundance = NULL,
# Secondary arguments
cores = detectCores(),
bimodal_mean_variability_association = FALSE,
percent_false_positive = 5,
inference_method = "pathfinder",
prior_mean = list(intercept = c(0, 1), coefficients = c(0, 1)),
prior_overdispersion_mean_association = list(
intercept = c(5, 2),
slope = c(0, 0.6),
standard_deviation = c(10, 20)
),
.sample_cell_group_pairs_to_exclude = NULL,
output_directory = "sccomp_draws_files",
verbose = TRUE,
enable_loo = FALSE,
noise_model = "multi_beta_binomial",
exclude_priors = FALSE,
use_data = TRUE,
mcmc_seed = sample(1e5, 1),
max_sampling_iterations = 20000,
pass_fit = TRUE,
sig_figs = 9,
...,
# DEPRECATED
.count = NULL,
approximate_posterior_inference = NULL,
variational_inference = NULL) {
# rlang::inform(
# message = "sccomp says: From version 1.7.12 the logit fold change threshold for significance has been changed from 0.2 to 0.1.",
# .frequency = "once",
# .frequency_id = "new_logit_fold_change_threshold"
# )
# Run the function
check_and_install_cmdstanr()
UseMethod("sccomp_estimate", .data)
}
#' @export
sccomp_estimate.Seurat <- function(.data,
formula_composition = ~1,
formula_variability = ~1,
.sample,
.cell_group,
.abundance = NULL,
# Secondary arguments
cores = detectCores(),
bimodal_mean_variability_association = FALSE,
percent_false_positive = 5,
inference_method = "pathfinder",
prior_mean = list(intercept = c(0, 1), coefficients = c(0, 1)),
prior_overdispersion_mean_association = list(
intercept = c(5, 2),
slope = c(0, 0.6),
standard_deviation = c(10, 20)
),
.sample_cell_group_pairs_to_exclude = NULL,
output_directory = "sccomp_draws_files",
verbose = TRUE,
enable_loo = FALSE,
noise_model = "multi_beta_binomial",
exclude_priors = FALSE,
use_data = TRUE,
mcmc_seed = sample(1e5, 1),
max_sampling_iterations = 20000,
pass_fit = TRUE,
sig_figs = 9,
...,
# DEPRECATED
.count = NULL,
approximate_posterior_inference = NULL,
variational_inference = NULL) {
if (!is.null(.abundance))
stop("sccomp says: .abundance argument can be used only for data frame input")
if (!is.null(.count))
stop("sccomp says: .count argument can be used only for data frame input")
# DEPRECATION OF approximate_posterior_inference
if (lifecycle::is_present(approximate_posterior_inference) & !is.null(approximate_posterior_inference)) {
lifecycle::deprecate_warn("1.7.7", "sccomp::sccomp_estimate(approximate_posterior_inference = )", details = "The argument approximate_posterior_inference is now deprecated. Please use inference_method. By default, inference_method value is inferred from approximate_posterior_inference.")
inference_method <- ifelse(approximate_posterior_inference == "all", "variational", "hmc")
}
# DEPRECATION OF variational_inference
if (lifecycle::is_present(variational_inference) & !is.null(variational_inference)) {
lifecycle::deprecate_warn("1.7.11", "sccomp::sccomp_estimate(variational_inference = )", details = "The argument variational_inference is now deprecated. Please use inference_method. By default, inference_method value is inferred from variational_inference")
inference_method <- ifelse(variational_inference, "variational", "hmc")
}
# Prepare column names
.sample <- enquo(.sample)
.cell_group <- enquo(.cell_group)
.sample_cell_group_pairs_to_exclude <- enquo(.sample_cell_group_pairs_to_exclude)
.data[[]] |>
sccomp_estimate(
formula_composition = formula_composition,
formula_variability = formula_variability,
!!.sample,
!!.cell_group,
# Secondary arguments
cores = cores,
bimodal_mean_variability_association = bimodal_mean_variability_association,
percent_false_positive = percent_false_positive,
inference_method = inference_method,
prior_mean = prior_mean,
prior_overdispersion_mean_association = prior_overdispersion_mean_association,
.sample_cell_group_pairs_to_exclude = !!.sample_cell_group_pairs_to_exclude,
output_directory = output_directory,
verbose = verbose,
enable_loo = enable_loo,
noise_model = noise_model,
exclude_priors = exclude_priors,
use_data = use_data,
mcmc_seed = mcmc_seed,
max_sampling_iterations = max_sampling_iterations,
pass_fit = pass_fit,
sig_figs = sig_figs,
...
)
}
#' @export
sccomp_estimate.SingleCellExperiment <- function(.data,
formula_composition = ~1,
formula_variability = ~1,
.sample,
.cell_group,
.abundance = NULL,
# Secondary arguments
cores = detectCores(),
bimodal_mean_variability_association = FALSE,
percent_false_positive = 5,
inference_method = "pathfinder",
prior_mean = list(intercept = c(0, 1), coefficients = c(0, 1)),
prior_overdispersion_mean_association = list(
intercept = c(5, 2),
slope = c(0, 0.6),
standard_deviation = c(10, 20)
),
.sample_cell_group_pairs_to_exclude = NULL,
output_directory = "sccomp_draws_files",
verbose = TRUE,
enable_loo = FALSE,
noise_model = "multi_beta_binomial",
exclude_priors = FALSE,
use_data = TRUE,
mcmc_seed = sample(1e5, 1),
max_sampling_iterations = 20000,
pass_fit = TRUE,
sig_figs = 9,
...,
# DEPRECATED
.count = NULL,
approximate_posterior_inference = NULL,
variational_inference = NULL) {
if (!is.null(.abundance))
stop("sccomp says: .abundance argument can be used only for data frame input")
if (!is.null(.count))
stop("sccomp says: .count argument can be used only for data frame input")
# DEPRECATION OF approximate_posterior_inference
if (lifecycle::is_present(approximate_posterior_inference) & !is.null(approximate_posterior_inference)) {
lifecycle::deprecate_warn("1.7.7", "sccomp::sccomp_estimate(approximate_posterior_inference = )", details = "The argument approximate_posterior_inference is now deprecated. Please use inference_method. By default, inference_method value is inferred from approximate_posterior_inference.")
inference_method <- ifelse(approximate_posterior_inference == "all", "variational", "hmc")
}
# DEPRECATION OF variational_inference
if (lifecycle::is_present(variational_inference) & !is.null(variational_inference)) {
lifecycle::deprecate_warn("1.7.11", "sccomp::sccomp_estimate(variational_inference = )", details = "The argument variational_inference is now deprecated. Please use inference_method. By default, inference_method value is inferred from variational_inference")
inference_method <- ifelse(variational_inference, "variational", "hmc")
}
# Prepare column names
.sample <- enquo(.sample)
.cell_group <- enquo(.cell_group)
.sample_cell_group_pairs_to_exclude <- enquo(.sample_cell_group_pairs_to_exclude)
.data |>
colData() |>
sccomp_estimate(
formula_composition = formula_composition,
formula_variability = formula_variability,
!!.sample,
!!.cell_group,
# Secondary arguments
cores = cores,
bimodal_mean_variability_association = bimodal_mean_variability_association,
percent_false_positive = percent_false_positive,
inference_method = inference_method,
prior_mean = prior_mean,
prior_overdispersion_mean_association = prior_overdispersion_mean_association,
.sample_cell_group_pairs_to_exclude = !!.sample_cell_group_pairs_to_exclude,
output_directory = output_directory,
verbose = verbose,
enable_loo = enable_loo,
noise_model = noise_model,
exclude_priors = exclude_priors,
use_data = use_data,
mcmc_seed = mcmc_seed,
max_sampling_iterations = max_sampling_iterations,
pass_fit = pass_fit,
sig_figs = sig_figs,
...
)
}
#' @export
sccomp_estimate.DFrame <- function(.data,
formula_composition = ~1,
formula_variability = ~1,
.sample,
.cell_group,
.abundance = NULL,
# Secondary arguments
cores = detectCores(),
bimodal_mean_variability_association = FALSE,
percent_false_positive = 5,
inference_method = "pathfinder",
prior_mean = list(intercept = c(0, 1), coefficients = c(0, 1)),
prior_overdispersion_mean_association = list(
intercept = c(5, 2),
slope = c(0, 0.6),
standard_deviation = c(10, 20)
),
.sample_cell_group_pairs_to_exclude = NULL,
output_directory = "sccomp_draws_files",
verbose = TRUE,
enable_loo = FALSE,
noise_model = "multi_beta_binomial",
exclude_priors = FALSE,
use_data = TRUE,
mcmc_seed = sample(1e5, 1),
max_sampling_iterations = 20000,
pass_fit = TRUE,
sig_figs = 9,
...,
# DEPRECATED
.count = NULL,
approximate_posterior_inference = NULL,
variational_inference = NULL) {
if (!is.null(.abundance))
stop("sccomp says: .abundance argument can be used only for data frame input")
if (!is.null(.count))
stop("sccomp says: .count argument can be used only for data frame input")
# Prepare column names
.sample <- enquo(.sample)
.cell_group <- enquo(.cell_group)
.abundance <- enquo(.abundance)
.sample_cell_group_pairs_to_exclude <- enquo(.sample_cell_group_pairs_to_exclude)
.data |>
as.data.frame() |>
sccomp_estimate(
formula_composition = formula_composition,
formula_variability = formula_variability,
!!.sample,
!!.cell_group,
.abundance = !!.abundance,
# Secondary arguments
cores = cores,
bimodal_mean_variability_association = bimodal_mean_variability_association,
percent_false_positive = percent_false_positive,
inference_method = inference_method,
prior_mean = prior_mean,
prior_overdispersion_mean_association = prior_overdispersion_mean_association,
.sample_cell_group_pairs_to_exclude = !!.sample_cell_group_pairs_to_exclude,
output_directory = output_directory,
verbose = verbose,
enable_loo = enable_loo,
noise_model = noise_model,
exclude_priors = exclude_priors,
use_data = use_data,
mcmc_seed = mcmc_seed,
max_sampling_iterations = max_sampling_iterations,
pass_fit = pass_fit,
sig_figs = sig_figs,
...
)
}
#' @importFrom purrr when
#' @export
sccomp_estimate.data.frame <- function(.data,
formula_composition = ~1,
formula_variability = ~1,
.sample,
.cell_group,
.abundance = NULL,
# Secondary arguments
cores = detectCores(),
bimodal_mean_variability_association = FALSE,
percent_false_positive = 5,
inference_method = "pathfinder",
prior_mean = list(intercept = c(0, 1), coefficients = c(0, 1)),
prior_overdispersion_mean_association = list(
intercept = c(5, 2),
slope = c(0, 0.6),
standard_deviation = c(10, 20)
),
.sample_cell_group_pairs_to_exclude = NULL,
output_directory = "sccomp_draws_files",
verbose = TRUE,
enable_loo = FALSE,
noise_model = "multi_beta_binomial",
exclude_priors = FALSE,
use_data = TRUE,
mcmc_seed = sample(1e5, 1),
max_sampling_iterations = 20000,
pass_fit = TRUE,
sig_figs = 9,
...,
# DEPRECATED
.count = NULL,
approximate_posterior_inference = NULL,
variational_inference = NULL) {
# Prepare column names
.sample <- enquo(.sample)
.cell_group <- enquo(.cell_group)
.abundance <- enquo(.abundance)
.count <- enquo(.count)
.sample_cell_group_pairs_to_exclude <- enquo(.sample_cell_group_pairs_to_exclude)
# Deprecation of .count
if (rlang::quo_is_symbolic(.count)) {
rlang::warn("The argument '.count' is deprecated. Please use '.abundance' instead. This because now `sccomp` cam model both counts and proportions.")
.abundance <- .count
}
# DEPRECATION OF approximate_posterior_inference
if (lifecycle::is_present(approximate_posterior_inference) & !is.null(approximate_posterior_inference)) {
lifecycle::deprecate_warn("1.7.7", "sccomp::sccomp_estimate(approximate_posterior_inference = )", details = "The argument approximate_posterior_inference is now deprecated. Please use inference_method. By default, inference_method value is inferred from approximate_posterior_inference.")
inference_method <- ifelse(approximate_posterior_inference == "all", "variational", "hmc")
}
# DEPRECATION OF variational_inference
if (lifecycle::is_present(variational_inference) & !is.null(variational_inference)) {
lifecycle::deprecate_warn("1.7.11", "sccomp::sccomp_estimate(variational_inference = )", details = "The argument variational_inference is now deprecated. Please use inference_method. By default, inference_method value is inferred from variational_inference")
inference_method <- ifelse(variational_inference, "variational", "hmc")
}
if (quo_is_null(.abundance))
res <- sccomp_glm_data_frame_raw(
.data,
formula_composition = formula_composition,
formula_variability = formula_variability,
!!.sample,
!!.cell_group,
# Secondary arguments
cores = cores,
bimodal_mean_variability_association = bimodal_mean_variability_association,
percent_false_positive = percent_false_positive,
inference_method = inference_method,
prior_mean = prior_mean,
prior_overdispersion_mean_association = prior_overdispersion_mean_association,
.sample_cell_group_pairs_to_exclude = !!.sample_cell_group_pairs_to_exclude,
output_directory = output_directory,
verbose = verbose,
enable_loo = enable_loo,
exclude_priors = exclude_priors,
use_data = use_data,
mcmc_seed = mcmc_seed,
max_sampling_iterations = max_sampling_iterations,
pass_fit = pass_fit,
sig_figs = sig_figs,
...
)
else
res = sccomp_glm_data_frame_counts(
.data,
formula_composition = formula_composition,
formula_variability = formula_variability,
!!.sample,
!!.cell_group,
.count = !!.abundance,
# Secondary arguments
cores = cores,
bimodal_mean_variability_association = bimodal_mean_variability_association,
percent_false_positive = percent_false_positive,
inference_method = inference_method,
prior_mean = prior_mean,
prior_overdispersion_mean_association = prior_overdispersion_mean_association,
.sample_cell_group_pairs_to_exclude = !!.sample_cell_group_pairs_to_exclude,
output_directory = output_directory,
verbose = verbose,
enable_loo = enable_loo,
exclude_priors = exclude_priors,
use_data = use_data,
mcmc_seed = mcmc_seed,
max_sampling_iterations = max_sampling_iterations,
pass_fit = pass_fit,
sig_figs = sig_figs,
...
)
message("sccomp says: to do hypothesis testing run `sccomp_test()`,
the `test_composition_above_logit_fold_change` = 0.1 equates to a change of ~10%, and
0.7 equates to ~100% increase, if the baseline is ~0.1 proportion.
Use `sccomp_proportional_fold_change` to convert c_effect (linear) to proportion difference (non-linear).")
res |>
# Track input parameters
add_attr(noise_model, "noise_model")
}
#' sccomp_remove_outliers main
#'
#' @description
#' The `sccomp_remove_outliers` function takes as input a table of cell counts with columns for cell-group identifier, sample identifier, integer count, and factors (continuous or discrete). The user can define a linear model using an input R formula, where the first factor is the factor of interest. Alternatively, `sccomp` accepts single-cell data containers (e.g., Seurat, SingleCellExperiment, cell metadata, or group-size) and derives the count data from cell metadata.
#'
#' @import dplyr
#' @importFrom magrittr %$% divide_by multiply_by equals
#' @importFrom rlang quo_is_null quo_is_symbolic inform
#' @importFrom SingleCellExperiment colData
#' @importFrom parallel detectCores
#' @importFrom tidyr unnest nest
#'
#' @param .estimate A tibble including a cell_group name column, sample name column, read counts column (optional depending on the input class), and factor columns.
#' @param percent_false_positive A real number between 0 and 100 (not inclusive), used to identify outliers with a specific false positive rate.
#' @param cores Integer, the number of cores to be used for parallel calculations.
#' @param inference_method Character string specifying the inference method to use ('pathfinder', 'hmc', or 'variational').
#' @param output_directory A character string specifying the output directory for Stan draws.
#' @param verbose Logical, whether to print progression details.
#' @param mcmc_seed Integer, used for Markov-chain Monte Carlo reproducibility. By default, a random number is sampled from 1 to 999999.
#' @param max_sampling_iterations Integer, limits the maximum number of iterations in case a large dataset is used, to limit computation time.
#' @param enable_loo Logical, whether to enable model comparison using the R package LOO. This is useful for comparing fits between models, similar to ANOVA.
#' @param sig_figs Number of significant figures to use for Stan model output. Default is 9.
#' @param approximate_posterior_inference DEPRECATED, use the `variational_inference` argument.
#' @param variational_inference DEPRECATED Logical, whether to use variational Bayes for posterior inference. It is faster and convenient. Setting this argument to `FALSE` runs full Bayesian (Hamiltonian Monte Carlo) inference, which is slower but the gold standard.
#' @param ... Additional arguments passed to the `cmdstanr::sample` function.
#'
#' @return A tibble (`tbl`), with the following columns:
#' \itemize{
#' \item cell_group - The cell groups being tested.
#' \item parameter - The parameter being estimated from the design matrix described by the input formula_composition and formula_variability.
#' \item factor - The covariate factor in the formula, if applicable (e.g., not present for Intercept or contrasts).
#' \item c_lower - Lower (2.5%) quantile of the posterior distribution for a composition (c) parameter.
#' \item c_effect - Mean of the posterior distribution for a composition (c) parameter.
#' \item c_upper - Upper (97.5%) quantile of the posterior distribution for a composition (c) parameter.
#' \item c_n_eff - Effective sample size, the number of independent draws in the sample. The higher, the better.
#' \item c_R_k_hat - R statistic, a measure of chain equilibrium, should be within 0.05 of 1.0.
#' \item v_lower - Lower (2.5%) quantile of the posterior distribution for a variability (v) parameter.
#' \item v_effect - Mean of the posterior distribution for a variability (v) parameter.
#' \item v_upper - Upper (97.5%) quantile of the posterior distribution for a variability (v) parameter.
#' \item v_n_eff - Effective sample size for a variability (v) parameter.
#' \item v_R_k_hat - R statistic for a variability (v) parameter, a measure of chain equilibrium.
#' \item count_data - Nested input count data.
#' }
#'
#' @examples
#'
#' print("cmdstanr is needed to run this example.")
#' # Note: Before running the example, ensure that the 'cmdstanr' package is installed:
#' # install.packages("cmdstanr", repos = c("https://stan-dev.r-universe.dev/", getOption("repos")))
#'
#' \donttest{
#' if (instantiate::stan_cmdstan_exists()) {
#' data("counts_obj")
#'
#' estimate = sccomp_estimate(
#' counts_obj,
#' ~ type,
#' ~1,
#' sample,
#' cell_group,
#' count,
#' cores = 1
#' ) |>
#' sccomp_remove_outliers(cores = 1)
#' }
#' }
#'
#' @export
sccomp_remove_outliers <- function(.estimate,
percent_false_positive = 5,
cores = detectCores(),
inference_method = .estimate |> attr("inference_method"),
output_directory = "sccomp_draws_files",
verbose = TRUE,
mcmc_seed = sample(1e5, 1),
max_sampling_iterations = 20000,
enable_loo = FALSE,
sig_figs = 9,
# DEPRECATED
approximate_posterior_inference = NULL,
variational_inference = NULL,
...
) {
if(inference_method == "variational")
rlang::inform(
message = "sccomp says: From version 1.7.7 the model by default is fit with the variational inference method (inference_method = \"variational\"; much faster). For a full Bayesian inference (HMC method; the gold standard) use inference_method = \"hmc\".",
.frequency = "once",
.frequency_id = "variational_message"
)
# Run the function
check_and_install_cmdstanr()
UseMethod("sccomp_remove_outliers", .estimate)
}
#' @importFrom readr write_file
#' @export
sccomp_remove_outliers.sccomp_tbl = function(.estimate,
percent_false_positive = 5,
cores = detectCores(),
inference_method = .estimate |> attr("inference_method"),
output_directory = "sccomp_draws_files",
verbose = TRUE,
mcmc_seed = sample(1e5, 1),
max_sampling_iterations = 20000,
enable_loo = FALSE,
sig_figs = 9,
# DEPRECATED
approximate_posterior_inference = NULL,
variational_inference = NULL,
...
) {
# DEPRECATION OF approximate_posterior_inference
if (is_present(approximate_posterior_inference) & !is.null(approximate_posterior_inference)) {
deprecate_warn("1.7.7", "sccomp::sccomp_estimate(approximate_posterior_inference = )", details = "The argument approximate_posterior_inference is now deprecated please use variational_inference. By default variational_inference value is inferred from approximate_posterior_inference.")
inference_method = ifelse(approximate_posterior_inference == "all", "variational","hmc")
}
# DEPRECATION OF variational_inference
if (is_present(variational_inference) & !is.null(variational_inference)) {
deprecate_warn("1.7.11", "sccomp::sccomp_estimate(variational_inference = )", details = "The argument variational_inference is now deprecated please use inference_method. By default inference_method value is inferred from variational_inference")
inference_method = ifelse(variational_inference, "variational","hmc")
}
# Prepare column same enquo
.sample = .estimate |> attr(".sample")
.cell_group = .estimate |> attr(".cell_group")
.count = .estimate |> attr(".count")
.sample_cell_group_pairs_to_exclude = .estimate |> attr(".sample_cell_group_pairs_to_exclude")
# Formulae
formula_composition = .estimate |> attr("formula_composition")
formula_variability = .estimate |> attr("formula_variability")
noise_model = .estimate |> attr("noise_model")
# Get model input
data_for_model = .estimate |> attr("model_input")
# Credible interval
CI = 1 - (percent_false_positive/100)
# Count data
.data =
.estimate |>
select(!!.cell_group, count_data) |>
unnest(count_data) |>
distinct() |>
# Drop previous outlier estimation for the new one
select(-any_of(c(
".lower" , ".median" , ".upper" , "Rhat" , "truncation_down" ,
"truncation_up" , "outlier" , "contains_outliers"
)))
# Random intercept
random_effect_elements = .estimate |> attr("formula_composition") |> parse_formula_random_effect()
# Load model
mod_rng = load_model("glm_multi_beta_binomial_generate_data", threads = cores)
rng = mod_rng |> sample_safe(
generate_quantities_fx,
attr(.estimate , "fit")$draws(format = "matrix"),
# This is for the new data generation with selected factors to do adjustment
data =
.estimate |>
attr("model_input") |>
c(list(
# Add subset of coefficients
X_original = data_for_model$X,
N_original = data_for_model$N,
length_X_which = ncol(data_for_model$X),
length_XA_which = ncol(data_for_model$XA),
X_which = seq_len(ncol(data_for_model$X)) |> as.array(),
XA_which = seq_len(ncol(data_for_model$Xa)) |> as.array(),
# Random intercept common variable between grouping 1 and 2
ncol_X_random_eff_new = ncol(data_for_model$X_random_effect) |> c(ncol(data_for_model$X_random_effect_2) ), # I could put this in the intial data
length_X_random_effect_which = ncol(data_for_model$X_random_effect) |> c(ncol(data_for_model$X_random_effect_2)),
# Grouping 1
X_random_effect_which = seq_len(ncol(data_for_model$X_random_effect)) |> as.array(),
# Grouping 2 - Random intercept DUPLICATED
X_random_effect_which_2 = seq_len(ncol(data_for_model$X_random_effect_2)) |> as.array(),
create_intercept = FALSE
)),
parallel_chains = ifelse(
inference_method %in% c("variational", "pathfinder") |
attr(.estimate , "fit") |> is("CmdStanPathfinder"),
1,
attr(.estimate , "fit")$num_chains()
),
threads_per_chain = cores,
sig_figs = sig_figs
)
# Free memory
rm(.estimate)
# Detect outliers
truncation_df =
.data |>
left_join(
summary_to_tibble(rng, "counts", "N", "M", probs = c(0.05, 0.95)) |>
nest(data = -N) |>
mutate(!!.sample := rownames(data_for_model$X)) |>
unnest(data) |>
nest(data = -M) |>
mutate(!!.cell_group := colnames(data_for_model$y)) |>
unnest(data) ,
by = c(quo_name(.sample), quo_name(.cell_group))
) |>
# Add truncation
mutate( truncation_down = `5%`, truncation_up = `95%`) |>
# Add outlier stats
mutate( outlier = !(!!.count >= `5%` & !!.count <= `95%`) ) |>
nest(data = -M) |>
mutate(contains_outliers = map_lgl(data, ~ .x |> filter(outlier) |> nrow() > 0)) |>
unnest(data) |>
mutate(
truncation_down = case_when( outlier ~ -1, TRUE ~ truncation_down),
truncation_up = case_when(outlier ~ -1, TRUE ~ truncation_up),
)
# Add censoring
data_for_model$is_truncated = 1
data_for_model$truncation_up = truncation_df |> select(N, M, truncation_up) |> spread(M, truncation_up) |> as_matrix(rownames = "N") |> apply(2, as.integer)
data_for_model$truncation_down = truncation_df |> select(N, M, truncation_down) |> spread(M, truncation_down) |> as_matrix(rownames = "N") |> apply(2, as.integer)
data_for_model$truncation_not_idx =
(data_for_model$truncation_down >= 0) |>
t() |>
as.vector() |>
which() |>
intersect(data_for_model$user_forced_truncation_not_idx) |>
sort()
data_for_model$TNS = length(data_for_model$truncation_not_idx)
data_for_model$truncation_not_idx_minimal =
truncation_df |>
select(N, M, truncation_down) |>
spread(M, truncation_down) |>
mutate(row = row_number()) |>
pivot_longer(
cols = -c(N, row),
names_to = "columns",
values_to = "value"
) |>
filter(value == -1) |>
select(row, columns) |>
mutate(columns = as.integer(columns)) |>
as.matrix()
data_for_model$TNIM = nrow(data_for_model$truncation_not_idx_minimal)
message("sccomp says: outlier identification - step 1/2")
my_quantile_step_2 = 1 - (0.1 / data_for_model$N)
# This step gets the credible interval to control for within-category false positive rate
# We want a category-wise false positive rate of 0.1, and we have to correct for how many samples we have in each category
CI_step_2 = (1-my_quantile_step_2) / 2 * 2
fit2 =
data_for_model |>
fit_model(
"glm_multi_beta_binomial",
cores = cores,
quantile = my_quantile_step_2,
inference_method = inference_method,
output_directory = output_directory,
verbose = verbose,
seed = mcmc_seed,
max_sampling_iterations = max_sampling_iterations,
pars = c("beta", "alpha", "prec_coeff", "prec_sd", "alpha_normalised", "random_effect", "random_effect_2"),
sig_figs = sig_figs,
...
)
rng2 = mod_rng |> sample_safe(
generate_quantities_fx,
fit2$draws(format = "matrix"),
# This is for the new data generation with selected factors to do adjustment
data = data_for_model |> c(list(
# Add subset of coefficients
X_original = data_for_model$X,
N_original = data_for_model$N,
length_X_which = ncol(data_for_model$X),
length_XA_which = ncol(data_for_model$XA),
X_which = seq_len(ncol(data_for_model$X)) |> as.array(),
XA_which = seq_len(ncol(data_for_model$Xa)) |> as.array(),
# Random intercept common variable between grouping 1 and 2
ncol_X_random_eff_new = ncol(data_for_model$X_random_effect) |> c(ncol(data_for_model$X_random_effect_2) ), # I could put this in the intial data
length_X_random_effect_which = ncol(data_for_model$X_random_effect) |> c(ncol(data_for_model$X_random_effect_2)),
# Grouping 1
X_random_effect_which = seq_len(ncol(data_for_model$X_random_effect)) |> as.array(),
# Grouping 2 - Random intercept DUPLICATED
X_random_effect_which_2 = seq_len(ncol(data_for_model$X_random_effect_2)) |> as.array(),
create_intercept = FALSE
)),
parallel_chains = ifelse(inference_method %in% c("variational", "pathfinder"), 1, fit2$num_chains()),
threads_per_chain = cores,
sig_figs = sig_figs
)
rng2_summary =
summary_to_tibble(rng2, "counts", "N", "M", probs = c(CI_step_2, 0.5, 1-CI_step_2))
column_quantile_names = rng2_summary |> colnames() |> str_subset("\\%") |> _[c(1,3)]
rng2_summary =
rng2_summary |>
# !!! THIS COMMAND RELIES ON POSITION BECAUSE IT'S NOT TRIVIAL TO MATCH
# !!! COLUMN NAMES BASED ON LIMITED PRECISION AND/OR PERIODICAL QUANTILES
rename(
.lower := !!as.symbol(column_quantile_names[1]) ,
.median = `50%`,
.upper := !!as.symbol(column_quantile_names[2])
) |>
nest(data = -N) |>
mutate(!!.sample := rownames(data_for_model$X)) |>
unnest(data) |>
nest(data = -M) |>
mutate(!!.cell_group := colnames(data_for_model$y)) |>
unnest(data)
# Detect outliers
truncation_df2 =
.data |>
left_join(rng2_summary,
by = c(quo_name(.sample), quo_name(.cell_group))
) |>
# Add truncation
mutate( truncation_down = .lower, truncation_up = .upper) |>
# Add outlier stats
mutate( outlier = !(!!.count >= .lower & !!.count <= .upper) ) |>
nest(data = -M) |>
mutate(contains_outliers = map_lgl(data, ~ .x |> filter(outlier) |> nrow() > 0)) |>
unnest(data) |>
mutate(
truncation_down = case_when( outlier ~ -1, TRUE ~ truncation_down),
truncation_up = case_when(outlier ~ -1, TRUE ~ truncation_up)
)
data_for_model$truncation_up = truncation_df2 |> select(N, M, truncation_up) |> spread(M, truncation_up) |> as_matrix(rownames = "N") |> apply(2, as.integer)
data_for_model$truncation_down = truncation_df2 |> select(N, M, truncation_down) |> spread(M, truncation_down) |> as_matrix(rownames = "N") |> apply(2, as.integer)
data_for_model$truncation_not_idx =
(data_for_model$truncation_down >= 0) |>
t() |>
as.vector() |>
which() |>
intersect(data_for_model$user_forced_truncation_not_idx) |>
sort()
data_for_model$TNS = length(data_for_model$truncation_not_idx)
# LOO
data_for_model$enable_loo = TRUE & enable_loo
message("sccomp says: outlier-free model fitting - step 2/2")
# Print design matrix
message(sprintf("sccomp says: the composition design matrix has columns: %s", data_for_model$X |> colnames() |> paste(collapse=", ")))
message(sprintf("sccomp says: the variability design matrix has columns: %s", data_for_model$Xa |> colnames() |> paste(collapse=", ")))
fit3 =
data_for_model |>
# Run the first discovery phase with permissive false discovery rate
fit_model(
"glm_multi_beta_binomial",
cores = cores,
quantile = CI,
inference_method = inference_method,
output_directory = output_directory,
verbose = verbose,
seed = mcmc_seed,
max_sampling_iterations = max_sampling_iterations,
pars = c("beta", "alpha", "prec_coeff","prec_sd", "alpha_normalised", "random_effect", "random_effect_2", "log_lik"),
...
)
# # Make the fit standalone
# temp_rds_file <- tempfile(fileext = ".rds")
# fit3$save_object(file = temp_rds_file)
# fit3 = readRDS(temp_rds_file)
# file.remove(temp_rds_file)
# Create a dummy tibble
tibble() |>
# Attach association mean concentration
add_attr(fit3, "fit") |>
add_attr(data_for_model, "model_input") |>
add_attr(truncation_df2, "truncation_df2") |>
add_attr(.sample, ".sample") |>
add_attr(.cell_group, ".cell_group") |>
add_attr(.count, ".count") |>
add_attr(formula_composition, "formula_composition") |>
add_attr(formula_variability, "formula_variability") |>
add_attr(parse_formula(formula_composition), "factors" ) |>
add_attr(inference_method, "inference_method" ) |>
# Add class to the tbl
add_class("sccomp_tbl") |>
# Print estimates
sccomp_test() |>
# drop hypothesis testing as the estimation exists without probabilities.
# For hypothesis testing use sccomp_test
select(-contains("_FDR"), -contains("_pH0")) |>