[727782]: / R / fit_ZICP.R

Download this file

244 lines (213 with data), 6.9 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
fit.ZICP <- function(features,
metadata,
link = "log",
formula = NULL,
random_effects_formula = NULL,
correction = 'BH',
cores = 4,
optimizer = 'nlminb',
na.action = na.exclude) {
######################################
# Fit and summary functions for ZICP #
######################################
if (is.null(random_effects_formula)) {
##########################
# Fixed effects modeling #
##########################
model_function <- function(formula,
data,
link,
optimizer,
na.action) {
return(
zcpglm(
formula = formula,
data = data,
link = link,
optimizer = optimizer,
na.action = na.action
)
)
}
summary_function <- function(fit) {
zicp_out <-
capture.output(zicp_summary <-
cplm::summary(fit)$coefficients$tweedie)
para <- as.data.frame(zicp_summary)[-1,-3]
para$base.model <- 'ZICP'
para$tweedie.index <- round(fit$p, 3)
para$name <- rownames(zicp_summary)[-1]
return(para)
}
} else{
###########################
# Random effects modeling #
###########################
formula <-
paste('. ~', paste(all.vars(formula)[-1], collapse = ' + '), '.', sep = ' + ')
formula <- update(random_effects_formula, formula)
model_function <- function(formula,
data,
link,
optimizer,
na.action) {
return(
glmmTMB::glmmTMB(
formula = formula,
data = data,
family = glmmTMB::tweedie(link = link),
ziformula = ~ 1,
na.action = na.action
)
)
}
summary_function <- function(fit) {
glmmTMB_summary <- coef(summary(fit))
para <- as.data.frame(glmmTMB_summary$cond)[-1,-3]
para$base.model <-
ifelse(is.null(glmmTMB_summary$zi), 'CPLM', 'ZICP')
para$tweedie.index <-
round(unname(plogis(fit$fit$par["thetaf"]) + 1), 3)
para$name <- rownames(glmmTMB_summary$cond)[-1]
return(para)
}
}
#######################################
# Init cluster for parallel computing #
#######################################
cluster <- NULL
if (cores > 1)
{
logging::loginfo("Creating cluster of %s R processes", cores)
cluster <- parallel::makeCluster(cores)
clusterExport(
cluster,
c(
"features",
"metadata",
"formula",
"link",
"optimizer",
"na.action",
"model_function",
"summary_function"
),
envir = environment()
)
}
##############################
# Apply per-feature modeling #
##############################
outputs <-
pbapply::pblapply(seq_len(ncol(features)), cl = cluster, function(x) {
#################################
# Create per-feature data frame #
#################################
featuresVector <- features[, x]
logging::loginfo("Fitting model to feature number %d, %s",
x,
colnames(features)[x])
dat_sub <-
data.frame(expr = as.numeric(featuresVector), metadata)
#############
# Fit model #
#############
fit <- tryCatch({
fit1 <-
model_function(
formula = formula,
data = dat_sub,
link = link,
optimizer = optimizer,
na.action = na.action
)
}, error = function(err) {
fit1 <-
try({
model_function(
formula = formula,
data = dat_sub,
link = link,
optimizer = optimizer,
na.action = na.action
)
})
return(fit1)
})
#################
# Gather Output #
#################
output <- list()
if (all(!inherits(fit, "try-error"))) {
output$para <- summary_function(fit)
}
else{
logging::logwarn(paste("Fitting problem for feature", x, "returning NA"))
output$para <-
as.data.frame(matrix(NA, nrow = ncol(metadata) - 1, ncol = 5)) # Everything except offset
output$para$name <-
colnames(metadata)[-ncol(metadata)] # Everything except offset
}
colnames(output$para) <-
c('coef',
'stderr' ,
'pval',
'base.model',
'tweedie.index',
'name')
output$para$feature <- colnames(features)[x]
return(output)
})
####################
# Stop the cluster #
####################
if (!is.null(cluster))
parallel::stopCluster(cluster)
#####################################
# Bind the results for each feature #
#####################################
paras <-
do.call(rbind, lapply(outputs, function(x) {
return(x$para)
}))
################################
# Apply correction to p-values #
################################
paras$qval <-
as.numeric(p.adjust(paras$pval, method = correction))
#####################################################
# Determine the metadata names from the model names #
#####################################################
metadata_names <- setdiff(colnames(metadata), "offset")
# order the metadata names by decreasing length
metadata_names_ordered <-
metadata_names[order(nchar(metadata_names), decreasing = TRUE)]
# find the metadata name based on the match
# to the beginning of the string
extract_metadata_name <- function(name) {
return(metadata_names_ordered[mapply(startsWith,
name,
metadata_names_ordered)][1])
}
paras$metadata <-
unlist(lapply(paras$name, extract_metadata_name))
# compute the value as the model contrast minus metadata
paras$value <-
mapply(function(x, y) {
if (x == y)
x
else
gsub(x, "", y)
}, paras$metadata, paras$name)
##############################
# Sort by decreasing q-value #
##############################
paras <- paras[order(paras$qval, decreasing = FALSE),]
paras <-
dplyr::select(paras,
c('feature', 'metadata', 'value'),
dplyr::everything())
paras <- dplyr::select(paras,-name)
rownames(paras) <- NULL
return(list("results" = paras))
}