-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathcalculateDMM.R
321 lines (300 loc) · 11.3 KB
/
calculateDMM.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
#' Dirichlet-Multinomial Mixture Model: Machine Learning for Microbiome Data
#'
#' These functions are accessors for functions implemented in the
#' \code{\link[DirichletMultinomial:DirichletMultinomial-package]{DirichletMultinomial}}
#' package
#'
#' @param x a numeric matrix with samples as rows or a
#' \code{\link[SummarizedExperiment:SummarizedExperiment-class]{SummarizedExperiment}}
#' object.
#'
#' @param assay.type \code{Character scalar}. Specifies the name of the
#' assay used in calculation. (Default: \code{"counts"})
#'
#' @param exprs_values Deprecated. Use \code{assay.type} instead.
#'
#' @param assay_name Deprecated. Use \code{assay.type} instead.
#'
#' @param k \code{Numeric scalar}. The number of Dirichlet components to fit.
#' See \code{\link[DirichletMultinomial:dmn]{dmn}}. (Default: \code{1})
#'
#' @param BPPARAM A
#' \code{\link[BiocParallel:BiocParallelParam-class]{BiocParallelParam}}
#' object specifying whether the calculation should be parallelized.
#'
#' @param transposed \code{Logical scalar}. Is \code{x} transposed with samples
#' in rows? (Default: \code{FALSE})
#'
#' @param type \code{Character scalar}. The type of measure used for the
#' goodness of fit. One of \sQuote{laplace}, \sQuote{AIC} or \sQuote{BIC}.
#'
#' @param name \code{Character scalar}. The name to store the result in
#' \code{\link[SummarizedExperiment:RangedSummarizedExperiment-class]{metadata}}
#'
#' @param variable \code{Character scalar}. A variable from \code{colData} to
#' use as a grouping variable. Must be a character of factor.
#'
#' @param seed \code{Numeric scalar}. Random number seed. See
#' \code{\link[DirichletMultinomial:dmn]{dmn}}
#'
#' @param ... optional arguments not used.
#'
#' @return
#' \code{calculateDMN} and \code{getDMN} return a list of \code{DMN} objects,
#' one element for each value of k provided.
#'
#' \code{bestDMNFit} returns the index for the best fit and \code{getBestDMNFit}
#' returns a single \code{DMN} object.
#'
#' \code{calculateDMNgroup} returns a
#' \code{\link[DirichletMultinomial:DMNGroup-class]{DMNGroup}} object
#'
#' \code{performDMNgroupCV} returns a \code{data.frame}
#'
#' @seealso
#' \code{\link[DirichletMultinomial:DMN-class]{DMN-class}},
#' \code{\link[DirichletMultinomial:DMNGroup-class]{DMNGroup-class}},
#' \code{\link[DirichletMultinomial:dmn]{dmn}},
#' \code{\link[DirichletMultinomial:dmngroup]{dmngroup}},
#' \code{\link[DirichletMultinomial:cvdmngroup]{cvdmngroup }},
#' \code{\link[DirichletMultinomial:fitted]{accessors for DMN objects}}
#'
#' @name calculateDMN
#'
#' @examples
#' fl <- system.file(package="DirichletMultinomial", "extdata", "Twins.csv")
#' counts <- as.matrix(read.csv(fl, row.names=1))
#' fl <- system.file(package="DirichletMultinomial", "extdata", "TwinStudy.t")
#' pheno0 <- scan(fl)
#' lvls <- c("Lean", "Obese", "Overwt")
#' pheno <- factor(lvls[pheno0 + 1], levels=lvls)
#' colData <- DataFrame(pheno = pheno)
#'
#' tse <- TreeSummarizedExperiment(assays = list(counts = counts),
#' colData = colData)
#'
#' library(bluster)
#'
#' # Compute DMM algorithm and store result in metadata
#' tse <- addCluster(tse, name = "DMM", DmmParam(k = 1:3, type = "laplace"),
#' by = "samples", full = TRUE)
#'
#' # Get the list of DMN objects
#' metadata(tse)$DMM$dmm
#'
#' # Get and display which objects fits best
#' bestFit <- metadata(tse)$DMM$best
#' bestFit
#'
#' # Get the model that generated the best fit
#' bestModel <- metadata(tse)$DMM$dmm[[bestFit]]
#' bestModel
#'
#' # Get the sample-cluster assignment probability matrix
#' head(metadata(tse)$DMM$prob)
#'
#' # Get the weight of each component for the best model
#' bestModel@mixture$Weight
NULL
#' @importFrom DirichletMultinomial dmn
#' @importFrom stats runif
.calculate_DMN <- function(x, k = 1, BPPARAM = SerialParam(),
seed = runif(1, 0, .Machine$integer.max), ...){
if(!is.numeric(k) ||
length(k) == 0 ||
anyNA(k) ||
any(k <= 0) ||
any(k != as.integer(k))){
stop("'k' must be an integer vector with positive values only.",
call. = FALSE)
}
#
old <- getAutoBPPARAM()
setAutoBPPARAM(BPPARAM)
on.exit(setAutoBPPARAM(old))
if (!(bpisup(BPPARAM) || is(BPPARAM, "MulticoreParam"))) {
bpstart(BPPARAM)
on.exit(bpstop(BPPARAM), add = TRUE)
}
ans <- BiocParallel::bplapply(k, DirichletMultinomial::dmn, count = x,
seed = seed, ...,
BPPARAM = BPPARAM)
ans
}
#' @rdname calculateDMN
#' @export
setMethod("calculateDMN", signature = c(x = "ANY"), .calculate_DMN)
#' @rdname calculateDMN
#' @export
setMethod("calculateDMN", signature = c(x = "SummarizedExperiment"),
function(x, assay.type = assay_name, assay_name = exprs_values,
exprs_values = "counts", transposed = FALSE, ...){
.Deprecated(old="calculateDMN", new="cluster",
"Now calculateDMN is deprecated.
Use cluster with DMMParam parameter instead.")
mat <- assay(x, assay.type)
if(!transposed){
mat <- t(mat)
}
calculateDMN(mat, ...)
}
)
#' @rdname calculateDMN
#' @importFrom S4Vectors metadata<-
#' @export
runDMN <- function(x, name = "DMN", ...){
.Deprecated(old="runDMN", new="cluster",
"Now runDMN is deprecated.
Use cluster with DMMParam parameter instead.")
if(!is(x,"SummarizedExperiment")){
stop("'x' must be a SummarizedExperiment")
}
metadata(x)[[name]] <- calculateDMN(x, ...)
x
}
################################################################################
# accessors
#' @importFrom S4Vectors metadata
.get_dmn <- function(x, name){
dmn <- metadata(x)[[name]]
if(is.null(dmn)){
stop("No data found for '",name,"'.", call. = FALSE)
}
all_dmn <- vapply(dmn, is, logical(1), "DMN")
if(!all(all_dmn)){
stop("'name' does not a list of DMN objects.", call. = FALSE)
}
dmn
}
.get_dmn_fit_FUN <- function(type){
type <- match.arg(type, c("laplace","AIC","BIC"))
fit_FUN <- switch(type,
laplace = DirichletMultinomial::laplace,
AIC = DirichletMultinomial::AIC,
BIC = DirichletMultinomial::BIC)
fit_FUN
}
#' @rdname calculateDMN
#' @importFrom DirichletMultinomial laplace AIC BIC
#' @export
setMethod("getDMN", signature = c(x = "SummarizedExperiment"),
function(x, name = "DMN"){
.Deprecated(old="getDMN", new="cluster",
"Now getDMN is deprecated.
Use cluster with DMMParam parameter
and full parameter set as true instead.")
.get_dmn(x, name)
}
)
.get_best_dmn_fit <- function(dmn, fit_FUN){
fit <- vapply(dmn, fit_FUN, numeric(1))
which.min(fit)
}
#' @rdname calculateDMN
#' @importFrom DirichletMultinomial laplace AIC BIC
#' @export
setMethod("bestDMNFit", signature = c(x = "SummarizedExperiment"),
function(x, name = "DMN", type = c("laplace","AIC","BIC")){
.Deprecated(old="bestDMNFit", new="cluster",
"Now bestDMNFit is deprecated.
Use cluster with DMMParam parameter
and full parameter set as true instead.")
#
dmn <- getDMN(x, name)
fit_FUN <- .get_dmn_fit_FUN(type)
#
.get_best_dmn_fit(dmn, fit_FUN)
}
)
#' @rdname calculateDMN
#' @importFrom DirichletMultinomial laplace AIC BIC
#' @export
setMethod("getBestDMNFit", signature = c(x = "SummarizedExperiment"),
function(x, name = "DMN", type = c("laplace","AIC","BIC")){
.Deprecated(old="getBestDMNFit", new="cluster",
"Now getBestDMNFit is deprecated.
Use cluster with DMMParam parameter
and full parameter set as true instead.")
dmn <- getDMN(x, name)
fit_FUN <- .get_dmn_fit_FUN(type)
dmn[[.get_best_dmn_fit(dmn, fit_FUN)]]
}
)
################################################################################
# DMN group
#' @importFrom DirichletMultinomial dmngroup
#' @importFrom stats runif
.calculate_DMNgroup <- function(x, variable, k = 1,
seed = runif(1, 0, .Machine$integer.max), ...){
# input check
if(!is.factor(variable) && is.character(variable)){
variable <- factor(variable, unique(variable))
} else if(!is.factor(variable)) {
stop("'variable' must be a factor or a character value.", call. = FALSE)
}
#
variable <- droplevels(variable)
dmngroup(x, variable, k = k, seed = seed, ...)
}
#' @rdname calculateDMN
#' @export
setMethod("calculateDMNgroup", signature = c(x = "ANY"), .calculate_DMNgroup)
#' @rdname calculateDMN
#' @export
setMethod("calculateDMNgroup", signature = c(x = "SummarizedExperiment"),
function(x, variable,
assay.type = assay_name, assay_name = exprs_values,
exprs_values = "counts", transposed = FALSE, ...){
mat <- assay(x, assay.type)
if(!transposed){
mat <- t(mat)
}
variable <- colData(x)[,variable]
if(is.null(variable)){
stop("No data found in '",variable,
"' column of colData(x).", call. = FALSE)
}
calculateDMNgroup(x = mat, variable = variable, ...)
}
)
################################################################################
# DMN group cross validations
#' @importFrom DirichletMultinomial cvdmngroup
#' @importFrom stats runif
.perform_DMNgroup_cv <- function(x, variable, k = 1,
seed = runif(1, 0, .Machine$integer.max), ...){
# input check
if(!is.factor(variable) && is.character(variable)){
variable <- factor(variable, unique(variable))
} else if(!is.factor(variable)) {
stop("'variable' must be a factor or a character value.", call. = FALSE)
}
variable <- droplevels(variable)
if(is.null(names(k)) || !all(names(k) %in% levels(variable))){
stop("'k' must be named. Names must fit the levels of 'variable'.",
call. = FALSE)
}
#
cvdmngroup(nrow(x), x, variable, k = k, seed = seed, ...)
}
#' @rdname calculateDMN
#' @export
setMethod("performDMNgroupCV", signature = c(x = "ANY"), .perform_DMNgroup_cv)
#' @rdname calculateDMN
#' @export
setMethod("performDMNgroupCV", signature = c(x = "SummarizedExperiment"),
function(x, variable,
assay.type = assay_name, assay_name = exprs_values,
exprs_values = "counts", transposed = FALSE, ...){
mat <- assay(x, assay.type)
if(!transposed){
mat <- t(mat)
}
variable <- colData(x)[,variable]
if(is.null(variable)){
stop("No data found in '",variable,
"' column of colData(x).", call. = FALSE)
}
performDMNgroupCV(x = mat, variable = variable, ...)
}
)