-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTractorMix.score.R
More file actions
306 lines (243 loc) · 11.4 KB
/
TractorMix.score.R
File metadata and controls
306 lines (243 loc) · 11.4 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
#' Tractor score test
#'
#' @param obj The output form glmm.kin from GMMAT package
#' @param infiles a vector of input file names in order (e.g. anc0.dosage.txt, anc1.dosage.txt)
#' @param outfiles file name for the summary statistics
#' @param AC_threshold If a variant has *all* ancestry-specific allele counts greater than this value, Tractor-Mix will run a full model; otherwise, Tractor-Mix will drop ancestries with low AC, and only use ancestries with high AC for calculation.
#' @return A list of summary statistics, based on users' input.
#' @export
#'
# version: 0.0.1
# date of edit: 02/14/2025
script_version <- "0.0.1"
message(paste("TractorMix.score Script Version :", script_version), "\n")
TractorMix.score <- function(obj, infiles, AC_threshold = 50, outfiles, n_core = 4, chunk_size = 2048) {
## install required packages
required_packages <- c("Matrix", "data.table", "doParallel", "foreach", "dplyr", "abind")
for (pkg in required_packages) {
if (!require(pkg, character.only = TRUE)) {
install.packages(pkg, dependencies = TRUE)
suppressMessages(library(pkg, character.only = TRUE))
}
}
# determine if n_core is correct
if(n_core>detectCores()) {
stop(paste0("Error: n_core must be less than ", detectCores(),"!"))
}
if (n_core > 1) {
n_core = n_core - 1
} else if (n_core <= 0) {
stop(paste0("Error: --nthreads must be 1 or more!"))
}
# number of ancestries
n_anc = length(infiles)
# filter for certain variants
iffilter = NA
# type of test
if (is.na(AC_threshold)){stop("AC_threshold must be specified")}
if (AC_threshold %% 1 != 0){stop("AC_threshold must be an integer")}
if (any(grepl("gaussian", as.character(obj$call)))){
message("Run Tractor-Mix on continuous phenotype")
} else if (any(grepl("binomial", as.character(obj$call)))){
message("Run Tractor-Mix on binary phenotype")
} else {
stop("You must specify `family = gaussian()` or `family = binomial()` in `glmmkin()`")
}
# use wc -l to find the number of SNPs in each file
# ASSUME: dosage files are equal length
if (!endsWith(infiles[1],".gz")){
wc_op <- paste("wc -l", infiles[1]) %>%
system(intern = T) %>%
trimws("left") %>%
strsplit(" ")
} else {
wc_op <- paste("zcat <", infiles[1], "| wc -l") %>%
system(intern = T) %>%
trimws("left") %>%
strsplit(" ")
}
n_SNPs = wc_op[[1]][1] %>% as.numeric() -1
# setup a result table
# 2-way: CHR, POS, ID, REF, ALT, Chi2, P, Eff_anc0, Eff_anc1, Pval_anc0, Pval_anc1, AC_count_anc0, AC_count_anc1, include_anc0, include_anc1
resDF = setNames(data.frame(matrix(data = NA, nrow = 0, ncol = (7 + 5 * n_anc))),
c("CHR", "POS", "ID", "REF", "ALT", "Chi2", "P",
paste0("Eff_anc", 0:(n_anc-1)),
paste0("SE_anc", 0:(n_anc-1)),
paste0("Pval_anc", 0:(n_anc-1)),
paste0("AC_count", 0:(n_anc-1)),
paste0("include_anc", 0:(n_anc-1))))
write.table(resDF, outfiles, quote = F, row.names = F, sep = "\t")
# retrieve file names, and check if consistent
files_colnames = lapply(infiles, function(infile){colnames(fread(input = infile, sep = "\t", skip = 0, nrows = 1))})
if (all(sapply(files_colnames, function(x) identical(x, files_colnames[[1]])))){
sample_id = files_colnames[[1]][6:length(files_colnames[[1]])]
}else{
stop("Sample order in dosage files do not match!")
}
# ASSUME: obj$id_include is a subset of samples in dosage files
sample2Use = match(obj$id_include, sample_id)
if (any(is.na(sample2Use))){
stop("The null model contains samples that are not in the dosage files;
remove unmatched samples before fitting the null model")
}
# define column class
colclasses = c(rep("character", 5), rep("integer", length(sample_id)))
if(!is.null(obj$P)){
################################################################################################
################################### Full GRM ###################################################
################################################################################################
# Score test; shared across all SNPs
X = obj$X
W = diag(obj$fitted.values * (1 - obj$fitted.values))
P = obj$P
tildeT= diag(nrow(X)) - X %*% solve(t(X) %*% W %*% X) %*% t(X) %*% W
# Parallel
cl <- makeCluster(n_core)
registerDoParallel(cl)
pb <- txtProgressBar(min = 0, max = ceiling(n_SNPs / chunk_size), style = 3)
chunk_idx = 0
while (chunk_idx < ceiling(n_SNPs / chunk_size)){
files = lapply(infiles,
function(infile){fread(input = infile,
sep = "\t",
skip = 1 + chunk_idx * chunk_size,
nrows = chunk_size,
colClasses = colclasses)})
meta_info = files[[1]][,1:5]
geno_info = abind(lapply(files, function(file){ unname(as.matrix(file[, 6:(length(sample_id) + 5)])[,sample2Use]) }), along = 3)
# parallelization within each chunk
n_SNPs_chunk = nrow(files[[1]])
sumstats_chunk = foreach(i = 1:n_SNPs_chunk, .combine = rbind, .inorder = TRUE) %dopar% {
# parse genotype
anc_eff = rep(NA, n_anc)
anc_se = rep(NA, n_anc)
anc_pval = rep(NA, n_anc)
# parse genotype, filter based on AC
G_ = geno_info[i,,]
AC = colSums(G_)
filter_mask = AC > AC_threshold
if (!any(filter_mask)){
res = rep(NA, ncol(resDF) - 5)
names(res) = NULL
return(res)
}
iffilter = !all(filter_mask)
# G is the genotype to use, regardless of whether this variants should drop some ancestries
G = as.matrix(G_[,filter_mask])
Score = t(G) %*% obj$scaled.residuals
VarScore = t(G) %*% P %*% G
if (!iffilter){
joint_chi2 = try(t(Score) %*% solve(VarScore) %*% Score, silent=TRUE)
} else {
joint_chi2 = NA
}
if(class(joint_chi2)[1] != "try-error") { # VarScore is invertable
if (!iffilter){
joint_pval = pchisq(as.numeric(joint_chi2), df = n_anc, lower.tail = F)
anc_eff = t(Score) %*% solve(VarScore)
anc_se = sqrt(diag(solve(VarScore)))
anc_pval = sapply((anc_eff/anc_se)^2, function(teststats){pchisq(as.numeric(teststats), df = 1, lower.tail = F)})
} else {
joint_pval = NA
anc_eff[filter_mask] = t(Score) %*% solve(VarScore)
anc_se[filter_mask] = sqrt(diag(solve(VarScore)))
anc_pval = sapply((anc_eff/anc_se)^2, function(teststats){pchisq(as.numeric(teststats), df = 1, lower.tail = F)})
}
res = c(round(as.numeric(joint_chi2), 5),
signif(as.numeric(joint_pval), 5),
round(as.numeric(anc_eff), 5),
round(as.numeric(anc_se), 5),
signif(as.numeric(anc_pval), 5),
AC,
filter_mask)
} else { # VarScore is not invertable
res = rep(NA, ncol(resDF) - 5)
}
names(res) = NULL
return(res)
}
write.table(cbind(meta_info, sumstats_chunk), outfiles, quote = F, row.names = F, sep = "\t", append = T, col.names = F)
chunk_idx = chunk_idx + 1
setTxtProgressBar(pb, chunk_idx)
}
close(pb)
stopCluster(cl)
} else {
################################################################################################
################################### Sparse GRM #################################################
################################################################################################
obj$Sigma_iX = Matrix(obj$Sigma_iX, sparse = TRUE) # this is solve(Sigma) %*% X
obj$Sigma_i <- Matrix(obj$Sigma_i, sparse = TRUE) # this is solve(Sigma)
obj$cov = Matrix(obj$cov, sparse = TRUE)
# Parallel
cl <- makeCluster(n_core)
registerDoParallel(cl)
pb <- txtProgressBar(min = 0, max = ceiling(n_SNPs / chunk_size), style = 3)
chunk_idx = 0
while (chunk_idx < ceiling(n_SNPs / chunk_size)){
files = lapply(infiles,
function(infile){fread(input = infile, sep = "\t",
skip = 1 + chunk_idx * chunk_size,
nrows = chunk_size,
colClasses = colclasses)})
meta_info = files[[1]][,1:5]
geno_info = abind(lapply(files, function(file){ unname(as.matrix(file[, 6:(length(sample_id) + 5)])[,sample2Use]) }), along = 3)
# parallelization within each chunk
n_SNPs_chunk = nrow(files[[1]])
sumstats_chunk = foreach(i = 1:n_SNPs_chunk, .combine = rbind, .inorder = TRUE, .packages=c("Matrix") ) %dopar% {
anc_eff = rep(NA, n_anc)
anc_se = rep(NA, n_anc)
anc_pval = rep(NA, n_anc)
# parse genotype, filter based on AC
G_ = geno_info[i,,]
AC = colSums(G_)
filter_mask = AC > AC_threshold
if (!any(filter_mask)){
res = rep(NA, ncol(resDF) - 5)
names(res) = NULL
return(res)
}
iffilter = !all(filter_mask)
# G is the genotype to use, regardless of whether this variants should drop some ancestries
G = as.matrix(G_[,filter_mask])
XSigma_iG = t(obj$Sigma_iX) %*% G
VarScore = t(G) %*% obj$Sigma_i %*% G - t(XSigma_iG) %*% obj$cov %*% XSigma_iG
Score = t(G) %*% obj$scaled.residuals
if (!iffilter){
joint_chi2 = try(t(Score) %*% solve(VarScore) %*% Score, silent = T)
} else {
joint_chi2 = NA
}
if(class(joint_chi2)[1] != "try-error") { # VarScore is invertable
if (!iffilter){
joint_pval = pchisq(as.numeric(joint_chi2), df = n_anc, lower.tail = F)
anc_eff = t(Score) %*% solve(VarScore)
anc_se = sqrt(diag(solve(VarScore)))
anc_pval = sapply((anc_eff/anc_se)^2, function(teststats){pchisq(as.numeric(teststats), df = 1, lower.tail = F)})
} else {
joint_pval = NA
anc_eff[filter_mask] = t(Score) %*% solve(VarScore)
anc_se[filter_mask] = sqrt(diag(solve(VarScore)))
anc_pval = sapply((anc_eff/anc_se)^2, function(teststats){pchisq(as.numeric(teststats), df = 1, lower.tail = F)})
}
res = c(round(as.numeric(joint_chi2), 5),
signif(as.numeric(joint_pval), 5),
round(as.numeric(anc_eff), 5),
round(as.numeric(anc_se), 5),
signif(as.numeric(anc_pval), 5),
AC,
filter_mask)
} else { # VarScore is not invertable
res = rep(NA, ncol(resDF) - 5)
}
names(res) = NULL
return(res)
}
write.table(cbind(meta_info, sumstats_chunk), outfiles, quote = F, row.names = F, sep = "\t", append = T, col.names = F)
chunk_idx = chunk_idx + 1
setTxtProgressBar(pb, chunk_idx)
}
close(pb)
stopCluster(cl)
}
}