-
Notifications
You must be signed in to change notification settings - Fork 0
/
recipe-class.R
1205 lines (1091 loc) · 29.2 KB
/
recipe-class.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
# CLASS RECIPE -----------------------------------------------------------------
## class unions ----
#' @rdname Recipe-class
methods::setClassUnion("phyloseq_or_null", c("phyloseq", "NULL"))
#' @rdname Recipe-class
methods::setClassUnion("tibble_or_NULL", c("tbl_df", "NULL"))
## class def ----
#' Recipe-class object
#'
#' A Recipe is a description of the steps to be applied to a data set in order
#' to prepare it for data analysis.
#'
#' @slot phyloseq Phyloseq-class object.
#' @slot var_info A tibble that contains the current set of terms in the data
#' set. This initially defaults to the same data contained in `var_info`.
#' @slot tax_info A tibble that contains the current set of taxonomic levels
#' that will be used in the analysis.
#' @slot steps List of step-class objects that will be used by DA.
#'
#' @name Recipe-class
#' @rdname Recipe-class
#' @exportClass Recipe
#' @return Recipe-class object
#' @autoglobal
methods::setClass(
Class = "Recipe",
slots = c(
phyloseq = "phyloseq_or_null",
var_info = "tibble_or_NULL",
tax_info = "tibble_or_NULL",
steps = "list"
),
prototype = list(
phyloseq = NULL,
var_info = NULL,
tax_info = NULL,
steps = list()
)
)
## constructor ----
#' Create a Recipe for preprocessing data
#'
#' A Recipe is a description of the steps to be applied to a data set in order
#' to prepare it for data analysis.
#'
#' @param microbiome_object Phyloseq-class object or
#' TreeSummarizedExperiment-class object.
#' @param var_info A character string of column names corresponding to variables
#' that will be used in any context.
#' @param tax_info A character string of taxonomic levels that will be used in
#' any context.
#' @param steps list with steps.
#'
#' @return An object of class `Recipe` with sub-objects: \item{phyloseq}{object
#' of class `phyloseq` with taxa abundance information.} \item{var_info}{A
#' tibble that contains the current set of terms in the data set. This
#' initially defaults to the same data contained in `var_info`.}
#' \item{tax_info}{A tibble that contains the current set of taxonomic levels
#' that will be used in the analysis.}
#'
#' @aliases Recipe
#' @export
#' @autoglobal
#' @tests
#' data(metaHIV_phy)
#' colnames(metaHIV_phy@tax_table) <-
#' c("Kingdom", "Phylum", "Class", "Order", "Family", "Genus", "Sp")
#'
#' expect_error(
#' recipe(metaHIV_phy, var_info = "RiskGroup2", tax_info = "Species")
#' )
#'
#' data(GlobalPatterns, package = "mia")
#' expect_s4_class(recipe(GlobalPatterns), "Recipe")
#'
#' @examples
#' data(metaHIV_phy)
#'
#' ## Define recipe
#' rec <-
#' recipe(metaHIV_phy, var_info = "RiskGroup2", tax_info = "Phylum") |>
#' step_subset_taxa(tax_level = "Kingdom", taxa = c("Bacteria", "Archaea")) |>
#' step_filter_taxa(.f = "function(x) sum(x > 0) >= (0.3 * length(x))") |>
#' step_metagenomeseq(rm_zeros = 0.01) |>
#' step_maaslin()
#'
#' ## Prep recipe
#' da_results <- prep(rec)
#'
#' ## Consensus strategy
#' n_methods <- 2
#' da_results <- bake(da_results, count_cutoff = n_methods)
#'
#' ## Results
#' cool(da_results)
#'
#' ## You can also crate a recipe without var and tax info
#' rec <- recipe(metaHIV_phy)
#'
#' rec
#'
#' ## And define them later
#' rec <- rec |>
#' add_var("RiskGroup2") |>
#' add_tax("Genus")
#'
#' rec
#'
#' ## When trying to add an identical step to an existing one, the system
#' ## returns an information message.
#' rec <- step_ancom(rec)
#' rec <- step_ancom(rec)
#'
#' ## The same with bake
#' da_results <- bake(da_results)
#' da_results <- bake(da_results)
recipe <- function(microbiome_object = NULL,
var_info = NULL,
tax_info = NULL,
steps = list()) {
var_info <- tibble::tibble(vars = var_info)
tax_info <- tibble::tibble(tax_lev = tax_info)
expected <- c("Kingdom", "Phylum", "Class", "Order",
"Family", "Genus", "Species")
if (!is(microbiome_object, "phyloseq") &&
!is(microbiome_object, "TreeSummarizedExperiment")) {
rlang::abort(
c(
"The input object must be a phyloseq or TreeSummarizedExperiment object."
)
)
}
if (is(microbiome_object, "TreeSummarizedExperiment")) {
microbiome_object <-
mia::makePhyloseqFromTreeSummarizedExperiment(microbiome_object)
}
if (!all(colnames(microbiome_object@tax_table) %in% expected)) {
rlang::abort(
c(
glue::glue(
"'rank' must be a value from {crayon::bgMagenta('taxonomyRanks()')}."
),
glue::glue(
"Rename the columns from the tax_table slot of your input phyloseq ",
"with standard names.",
),
glue::glue(
"Standard names: {stringr::str_c(expected, collapse = ', ')}."
)
)
)
}
methods::new(
Class = "Recipe",
phyloseq = microbiome_object,
var_info = var_info,
tax_info = tax_info,
steps = steps
)
}
## validity ----
methods::setValidity(
Class = "Recipe",
method = function(object) {
TRUE
}
)
## printing ----
methods::setMethod("show", signature = "Recipe", definition = function(object) {
cli::cat_rule(crayon::blue("DAR Recipe"))
cat("Inputs:\n\n")
## Phyloseq
phy <- get_phy(object)
ntax <- phyloseq::ntaxa(phy)
nsam <- phyloseq::nsamples(phy)
cat(
glue::glue(
" {info()} phyloseq object with {crayon::blue(ntax)} taxa and ",
"{crayon::blue(nsam)} samples"
),
"\n"
)
## Variable
if (length(get_var(object)) == 0) {
cat(
glue::glue(
" {cross()} undefined variable of interest. Use ",
"{crayon::bgMagenta('add_var()')} to add it to Recipe!"
),
"\n"
)
} else {
var <- get_var(object) %>% dplyr::pull(1)
var_vals <- sample_data(object) %>% dplyr::pull(.env$var)
if (is.character(var_vals) | is.factor(var_vals)) {
levs <- factor(var_vals) %>% levels() %>% stringr::str_c(collapse = ", ")
msg <- glue::glue("class: {class(var_vals)}, levels: {levs}")
}
if (is.numeric(var_vals)) {
msg <- glue::glue("class: numeric")
}
cat(glue::glue(
" {info()} variable of interes {crayon::blue(var)} ({msg})"
),
"\n"
)
}
## Taxa
if (length(get_tax(object)) == 0) {
cat(
glue::glue(
" {cross()} undefined taxonomic level. Use ",
"{crayon::bgMagenta('add_tax()')} to add it to Recipe!"
),
"\n"
)
} else {
cat(glue::glue(
" {info()} taxonomic level {crayon::blue(get_tax(object))}"),
"\n\n"
)
}
## Steps
if (length(object@steps) > 0) {
cat("Preporcessing steps:\n\n")
object@steps %>%
purrr::walk(~ {
if (stringr::str_detect(.x[['id']], "subset|filter|rarefaction")) {
id <-
glue::glue("id = {.x[['id']]}") %>%
crayon::silver()
class(.x)[[1]]
cat(c(glue::glue(" {dot()} {class(.x)[[1]]}() {id}"), "\n"))
}
})
}
cat("\n")
if (length(object@steps) > 0) {
cat("DA steps:\n\n")
object@steps %>%
purrr::walk(~ {
if (!stringr::str_detect(.x[['id']], "subset|filter|rarefaction")) {
id <-
glue::glue("id = {.x[['id']]}") %>%
crayon::silver()
class(.x)[[1]]
cat(c(glue::glue(" {dot()} {class(.x)[[1]]}() {id}"), "\n"))
}
})
}
})
# METHODS RECIPE ---------------------------------------------------------------
## get_var ----
#' Returns var_info from Recipe-class object
#'
#' @param rec A `Recipe` object
#'
#' @aliases get_var
#' @return Tibble containing `var_info`.
#' @export
#' @autoglobal
#' @examples
#' data(metaHIV_phy)
#'
#' ## Define recipe
#' rec <-
#' recipe(metaHIV_phy, var_info = "RiskGroup2", tax_info = "Species")
#'
#' ## Extract variable of interest
#' get_var(rec)
methods::setGeneric("get_var", function(rec) standardGeneric("get_var"))
#' @rdname get_var
#' @export
methods::setMethod(
f = "get_var",
signature = "Recipe",
definition = function(rec) { rec@var_info }
)
## get_tax ----
#' Returns tax_info from Recipe-class object
#'
#' @param rec A `Recipe` object
#'
#' @aliases get_tax
#' @return Tibble containing `tax_info`.
#' @export
#' @autoglobal
#' @examples
#' data(metaHIV_phy)
#'
#' ## Define recipe
#' rec <-
#' recipe(metaHIV_phy, var_info = "RiskGroup2", tax_info = "Species")
#'
#' ## Extract taxonomic level
#' get_tax(rec)
methods::setGeneric("get_tax", function(rec) standardGeneric("get_tax"))
#' @rdname get_tax
#' @export
#' @autoglobal
methods::setMethod(
f = "get_tax",
signature = "Recipe",
definition = function(rec) { rec@tax_info }
)
## get_phy ----
#' Returns phyloseq from Recipe-class object
#'
#' @param rec A `Recipe` object
#'
#' @aliases get_phy
#' @return Phyloseq class object
#' @export
#' @autoglobal
#' @examples
#' data(metaHIV_phy)
#'
#' ## Define recipe
#' rec <-
#' recipe(metaHIV_phy, var_info = "RiskGroup2", tax_info = "Species")
#'
#' ## Extract phyloseq object
#' get_phy(rec)
methods::setGeneric("get_phy", function(rec) standardGeneric("get_phy"))
#' @rdname get_phy
#' @export
#' @autoglobal
methods::setMethod(
f = "get_phy",
signature = "Recipe",
definition = function(rec) { rec@phyloseq }
)
## add_var ----
#' Adds variable of interest to the Recipe
#'
#' @param rec A `Recipe` object.
#' @param var_info A character string of column names corresponding to variables
#' that will be used in any context.
#'
#' @aliases add_var
#' @return A `Recipe` object.
#' @export
#' @autoglobal
#' @examples
#' data(metaHIV_phy)
#'
#' ## Define recipe
#' rec <- recipe(metaHIV_phy)
#'
#' ## add var info
#' rec <- add_var(rec, var_info = "RiskGroup2")
#' rec
#'
#' ## add var info to a prep-recipe returns an error
#' data(test_prep_rec)
#' err <- testthat::expect_error(
#' add_var(test_prep_rec, var_info = "RiskGroup2")
#' )
#'
#' err
methods::setGeneric("add_var", function(rec, var_info)
standardGeneric("add_var"))
#' @rdname add_var
#' @export
#' @autoglobal
methods::setMethod(
f = "add_var",
signature = "Recipe",
definition = function(rec, var_info) {
rec@var_info <- tibble::tibble(vars = var_info)
rec
}
)
## add_tax ----
#' Adds taxonomic level of interest in the Recipe.
#'
#' @param rec A `Recipe` object.
#' @param tax_info A character string of taxonomic levels that will be used in
#' any context.
#'
#' @aliases add_tax
#' @return A `Recipe` object.
#' @export
#' @autoglobal
#' @examples
#' data(metaHIV_phy)
#'
#' ## Define recipe
#' rec <-
#' recipe(metaHIV_phy)
#'
#' ## add var info
#' rec <- add_tax(rec, tax_info = "Species")
#' rec
#'
#' ## add tax info to a prep-Recipe returns an error
#' data(test_prep_rec)
#' err <- testthat::expect_error(
#' add_tax(test_prep_rec, tax_info = "Species")
#' )
#'
#' err
methods::setGeneric("add_tax", function(rec, tax_info)
standardGeneric("add_tax"))
#' @rdname add_tax
#' @export
#' @autoglobal
methods::setMethod(
f = "add_tax",
signature = "Recipe",
definition = function(rec, tax_info) {
rec@tax_info <- tibble::tibble(vars = tax_info)
rec
}
)
## Phyloseq slots as tibble from Recipe ----
#' Extracts tax_table from phyloseq inside a Recipe
#'
#' @param rec A Recipe or Recipe step.
#'
#' @return A tibble
#' @export
#' @autoglobal
#' @examples
#' data(metaHIV_phy)
#'
#' ## Define recipe
#' rec <-
#' recipe(metaHIV_phy, var_info = "RiskGroup2", tax_info = "Species")
#'
#' ## Extract tax_table from phyloseq object
#' tax_table(rec)
methods::setGeneric("tax_table", function(rec) standardGeneric("tax_table"))
#' @rdname tax_table
#' @export
#' @autoglobal
methods::setMethod(
f = "tax_table",
signature = "Recipe",
definition = function(rec) {
rec@phyloseq@tax_table %>%
to_tibble("taxa_id") %>%
dplyr::select(taxa_id, taxa = !!get_tax(rec)[[1]])
}
)
#' Extracts sample_data from phyloseq inside a Recipe
#'
#' @param rec A Recipe or Recipe step.
#'
#' @return A tibble
#' @export
#' @autoglobal
#' @examples
#' data(metaHIV_phy)
#'
#' ## Define recipe
#' rec <-
#' recipe(metaHIV_phy, var_info = "RiskGroup2", tax_info = "Species")
#'
#' ## Extract sample_data from phyloseq object
#' sample_data(rec)
methods::setGeneric("sample_data", function(rec) standardGeneric("sample_data"))
#' @rdname sample_data
#' @export
#' @autoglobal
methods::setMethod(
f = "sample_data",
signature = "Recipe",
definition = function(rec) {
rec@phyloseq %>%
phyloseq::sample_data() %>%
to_tibble("sample_id") %>%
dplyr::select(sample_id, !!get_var(rec)[[1]])
}
)
#' Extracts otu_table from phyloseq inside a Recipe
#'
#' @param rec A Recipe or Recipe step.
#'
#' @return A tibble
#' @export
#' @autoglobal
#' @examples
#' data(metaHIV_phy)
#'
#' ## Define recipe
#' rec <-
#' recipe(metaHIV_phy, var_info = "RiskGroup2", tax_info = "Species")
#'
#' ## Extract otu_table from phyloseq object
#' otu_table(rec)
methods::setGeneric("otu_table", function(rec) standardGeneric("otu_table"))
#' @rdname otu_table
#' @export
#' @autoglobal
methods::setMethod(
f = "otu_table",
signature = "Recipe",
definition = function(rec) {
rec@phyloseq %>%
phyloseq::otu_table() %>%
to_tibble("taxa_id")
}
)
# CLASS PrepRecipe ------------------------------------------------------------
## class def ----
#' PrepRecipe-class object
#'
#' A PrepRecipe is Recipe with the results corresponding to the steps defined
#' in the Recipe.
#'
#' @slot results Contains the results of all defined analysis in the Recipe.
#' @slot bakes Contains the executed bakes.
#'
#' @name PrepRecipe-class
#' @rdname PrepRecipe-class
#' @exportClass PrepRecipe
#' @return PrepRecipe-class object
#' @autoglobal
methods::setClass(
Class = "PrepRecipe",
contains = "Recipe",
slots = c(results = "list", bakes = "list")
)
## constructor ----
#' Create a PrepRecipe.
#'
#' A PrepRecipe is Recipe with the results corresponding to the steps defined
#' in the Recipe.
#'
#' @param rec A Recipe object.
#' @param results list with the results
#' @param bakes list with saved bakes
#'
#' @return An object of class `PrepRecipe`.
#' @autoglobal
#' @keywords internal
#' @aliases PrepRecipe
prep_recipe <- function(rec, results, bakes) {
methods::new(
Class = "PrepRecipe",
results = results,
bakes = bakes,
rec
)
}
## validity ----
methods::setValidity(
Class = "Recipe",
method = function(object) {
TRUE
}
)
## printing ----
#' @param object A Recipe object.
#'
#' @rdname Recipe-class
#' @autoglobal
methods::setMethod(
"show",
signature = "PrepRecipe",
definition = function(object) {
cli::cat_rule(crayon::blue("DAR Results"))
cat("Inputs:\n\n")
## Phyloseq
phy <- get_phy(object)
ntax <- phyloseq::ntaxa(phy)
nsam <- phyloseq::nsamples(phy)
cat(
glue::glue(
" {info()} phyloseq object with {crayon::blue(ntax)} taxa and ",
"{crayon::blue(nsam)} samples"
),
"\n"
)
## Variable
var <- NULL
if (nrow(get_var(object)) > 0) {
var <- get_var(object) %>% dplyr::pull(vars)
}
if (is.null(var)) {
cat(
glue::glue(
" {cross()} undefined variable of interest. Use ",
"{crayon::bgMagenta('add_var()')} to add it to Recipe!"
),
"\n"
)
} else {
var <- get_var(object) %>% dplyr::pull(1)
var_vals <- sample_data(object) %>% dplyr::pull(.env$var)
if (is.character(var_vals) | is.factor(var_vals)) {
levs <-
factor(var_vals) %>% levels() %>% stringr::str_c(collapse = ", ")
msg <- glue::glue("class: {class(var_vals)}, levels: {levs}")
}
if (is.numeric(var_vals)) {
msg <- glue::glue("class: numeric")
}
cat(glue::glue(
" {info()} variable of interes {crayon::blue(var)} ({msg})"),
"\n")
}
## Taxa
var <- NULL
if (nrow(get_tax(object)) > 0) {
var <- get_tax(object) %>% dplyr::pull(tax_lev)
}
if (is.null(var)) {
cat(
glue::glue(
" {cross()} undefined taxonomic level. Use ",
"{crayon::bgMagenta('add_tax()')} to add it to Recipe!"
),
"\n"
)
} else {
cat(glue::glue(
" {info()} taxonomic level {crayon::blue(get_tax(object))}"
),
"\n\n")
}
## Results
cat("Results:\n\n")
names(object@results) %>%
purrr::discard(stringr::str_detect(., "step_subster|step_filter")) %>%
purrr::walk( ~ {
n_taxa <-
object@results[[.x]][[1]] %>%
dplyr::filter(signif == TRUE) %>%
dplyr::pull(taxa_id) %>%
unique() %>%
length()
n_taxa <- crayon::silver(glue::glue("diff_taxa = {n_taxa}"))
cat(c(glue::glue(" {tick()} {.x} {n_taxa}"), "\n"))
})
if (length(object@results) > 0) {
n_overlap <-
find_intersections(object) %>%
dplyr::filter(
sum_methods == length(steps_ids(object, type = "da"))
) %>%
nrow()
cli::cat_line()
cat(glue::glue(
" {info()} {n_overlap} taxa are present in all tested methods"),
"\n\n"
)
}
## Bakes
if (length(object@bakes) > 0) {
cat("Bakes:\n\n")
object@bakes %>%
purrr::iwalk(~ {
msg <-
.x %>%
purrr::map2_chr(names(.), ~ {
if (is.null(.x)) {
.x <- "NULL"
}
if (.y == "weights" & .x != "NULL") {
.x <-
glue::glue("{names(.x)} = {.x}") %>%
stringr::str_c(collapse = ", ") %>%
stringr::str_c("c(", ., ")")
}
glue::glue("{.y}: {.x}")
}) %>% stringr::str_c(collapse = ", ")
cat(c(
glue::glue(
" {dot()} {crayon::blue(crayon::bold(paste0(.y, ' ->')))} ",
"{crayon::silver(msg)}"
),
"\n"
))
})
}
}
)
# METHODS PREP_RECIPE ----------------------------------------------------------
#' @noRd
#' @keywords internal
#' @autoglobal
required_pkgs_prep <- function(x, ...) {
c("furrr", "future")
}
## add_var ----
#' @rdname add_var
#' @export
#' @autoglobal
methods::setMethod(
f = "add_var",
signature = "PrepRecipe",
definition = function(rec, var_info) {
rlang::abort("var_info can only be added to a non-PrepRecipe")
}
)
## add_tax ----
#' @rdname add_tax
#' @export
#' @autoglobal
methods::setMethod(
f = "add_tax",
signature = "PrepRecipe",
definition = function(rec, tax_info) {
rlang::abort("tax_info can only be added to a non-PrepRecipe")
}
)
## prep ----
#' Performs all the steps defined in a Recipe
#'
#' For a Recipe with at least one preprocessing or DA operation run the steps in
#' a convenient order.
#'
#' @param rec A `Recipe` object. and furrr packages.
#' @param parallel if FALSE, no palatalization. if TRUE, parallel execution
#' using future and furrr packages.
#' @param workers Number of workers for palatalization.
#' @param force Force the reexecution of all steps. This remove previous
#' results.
#'
#' @aliases prep
#' @return A `PrepRecipe` object.
#' @export
#' @autoglobal
#' @examples
#' data(metaHIV_phy)
#'
#' ## Define Recipe
#' rec <-
#' recipe(metaHIV_phy, var_info = "RiskGroup2", tax_info = "Class") |>
#' step_subset_taxa(tax_level = "Kingdom", taxa = c("Bacteria", "Archaea")) |>
#' step_filter_taxa(.f = "function(x) sum(x > 0) >= (0.03 * length(x))") |>
#' step_maaslin()
#'
#' ## Prep Recipe
#' da_results <- prep(rec)
#'
#' ## If you try
#'
#' ## Consensus strategy
#' n_methods <- 2
#' da_results <- bake(da_results, count_cutoff = n_methods)
#' da_results
#'
#' ## If you try to run prep on an object of class PrepRecipe it returns an
#' ## error.
#' err <- testthat::expect_error(prep(da_results))
#' err
#'
#' ## You can force the overwrite with:
#' prep(rec, force = TRUE)
#'
#' ## This function can operate in parallel thanks to future and furrr packages.
#' prep(rec, parallel = TRUE, workers = 2)
methods::setGeneric(
name = "prep",
def = function(rec,
parallel = TRUE,
workers = 4,
force = FALSE) {
standardGeneric("prep")
}
)
#' @rdname prep
#' @export
methods::setMethod(
f = "prep",
signature = "Recipe",
definition = function(rec, parallel, workers, force) {
if ("results" %in% methods::slotNames(rec) & !force) {
rlang::abort(c(
"The input Recipe has already been prep!",
i = glue::glue(
"To force the rerun of all steps plese run ",
"{crayon::bgMagenta('prep(rec, force = T)')}"
)
))
}
check <- utils::capture.output(required_deps(rec))
if (length(check) > 0) {
rlang::abort(c(
"Not all necessary dependencies are installed.",
i = glue::glue(
"Use {crayon::bgMagenta('required_deps(rec)')} to see how to ",
"install them."
)
))
}
## Phyloseq preporcessing steps
to_execute <-
rec@steps %>%
purrr::map_chr(step_to_expr) %>%
purrr::keep(stringr::str_detect(., "run_subset|run_filter"))
to_execute <-
rec@steps %>%
purrr::map_chr(step_to_expr) %>%
purrr::keep(stringr::str_detect(., "run_rarefaction")) %>%
c(to_execute, .)
for (.x in to_execute) {
rec <- eval(parse(text = .x))
}
## DA steps
names <-
purrr::map_chr(rec@steps, ~ .x[["id"]]) %>%
purrr::discard(stringr::str_detect(., "subset|filter|rarefaction"))
if (parallel) {
recipes_pkg_check(required_pkgs_prep(), "prep()")
future::plan(future::multisession, workers = workers)
on.exit(future::plan(future::sequential))
res <-
rec@steps %>%
purrr::map_chr(step_to_expr) %>%
rarefy_msg() %>%
purrr::discard(
stringr::str_detect(., "run_subset|run_filter|run_rarefaction")
) %>%
furrr::future_map( ~ {
rec <- rec
eval(parse(text = .x))
},
.options = furrr::furrr_options(
seed = TRUE,
packages = "dar",
conditions = structure("condition", exclude = "message")
))
names(res) <- names
}
if (!parallel) {
res <-
rec@steps %>%
purrr::map(step_to_expr) %>%
rarefy_msg() %>%
purrr::discard(
stringr::str_detect(., "run_subset|run_filter|run_rarefaction")
) %>%
purrr::map(~ {
rec <- rec
eval(parse(text = .x))
})
names(res) <- names
}
prep_recipe(rec, res, list())
}
)
## Find intersections ----
#' Returns data.frame with OTU intersection between methods
#'
#' @param rec A `Recipe` object.
#' @param steps character vector with step_ids to take in account.
#' @param tidy Boolan indicating if result must be in tidy format.
#'
#' @aliases intersection_df
#' @return data.frame class object
#' @export
#' @autoglobal
#' @examples
#' data(test_prep_rec)
#'
#' df <- intersection_df(test_prep_rec)
#' head(df)
#'
#' ## intersection_df function needs a prep-Recipe. If you pass a a non-prep
#' ## recipe the output is an error.
#' data(test_rec)
#' err <- testthat::expect_error(intersection_df(test_rec))
#' err
methods::setGeneric(
name = "intersection_df",
def = function(rec, steps = steps_ids(rec, "da"), tidy = FALSE) {
standardGeneric("intersection_df")
}
)
#' @rdname intersection_df
#' @export
#' @autoglobal
methods::setMethod(
f = "intersection_df",
signature = "Recipe",
definition = function(rec, steps, tidy) {
rlang::abort(c(
"This function needs a PrepRecipe!",
glue::glue(
"Run {crayon::bgMagenta('prep(rec)')} and then retry last command."
)
))
}
)
#' @rdname intersection_df
#' @export
#' @autoglobal
methods::setMethod(
f = "intersection_df",
signature = "PrepRecipe",
definition = function(rec, steps, tidy) {
df <- names(rec@results) %>%
purrr::keep(. %in% steps) %>%
purrr::set_names() %>%
purrr::map_dfc( ~ {
taxa <-
rec@results[[.x]][[1]] %>%
dplyr::filter(signif == TRUE) %>%
dplyr::pull(taxa_id)