-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgam_randomise.R
331 lines (255 loc) · 14.1 KB
/
gam_randomise.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
##############################################################################
################ ###############
################ GAM Randomise Wrapper ###############
################ Angel Garcia de la Garza ###############
################ [email protected] ###############
################ 05/02/2017 ###############
##############################################################################
suppressMessages(require(optparse))
##############################################################################
################ Option List ###############
##############################################################################
option_list = list(
make_option(c("-c", "--covariates"), action="store", default=NA, type='character',
help="Full path to RDS covariate file."),
make_option(c("-o", "--output"), action="store", default=NA, type='character',
help="Full path to output directory"),
make_option(c("-p", "--imagepaths"), action="store", default=NA, type='character',
help="Name of the variable in the covariate file that contains the path to the images to be analyzed"),
make_option(c("-m", "--mask"), action="store", default=NA, type='character',
help="Full path to mask"),
make_option(c("-i", "--inclusion"), action="store", default=NA, type='character',
help="Name of inclusion variable on dataset. By default 1 means include. This will subset your rds file"),
make_option(c("-u", "--subjId"), action="store", default=NA, type='character',
help="subjID name on the covariates dataset"),
make_option(c("-f", "--ffull"), action="store", default=NA, type='character',
help="Formula for full model, should only include the right hand side of the formula.
Example: ~ stai_stai_tr+sex+s(age)+s(age,by=sex)"),
make_option(c("-r", "--freduced"), action="store", default=NA, type='character',
help="Formula for covariates of the reduced model, should only include the right hand side of the formula.
Example: ~ stai_stai_tr+sex+s(age)"),
make_option(c("-k", "--splits"), action="store", default=10, type='numeric',
help="number of splits to divide the data in, default is 10. To minimize data usage"),
make_option(c("-d", "--skipfourD"), action="store", default=FALSE, type='logical',
help="Option to skip creation of fourdD image and look for it in the Analysis Directory.
4D image must be labeled as 'fourd.nii.gz'. Will also skip smoothing step.
Default (FALSE) means to not skip"),
make_option(c("-s", "--smoothing"), action="store", default=NA, type='numeric',
help="The smoothing in sigmas required for the fourd image. Please write in 0 if no smoothing is wanted"),
make_option(c("-t", "--thresh"), action="store", default=0.01, type='numeric',
help="P-value threshold for cluster correction"),
make_option(c("-n", "--nsim"), action="store", default=500, type='numeric',
help="Number of simulations, default is 500"),
make_option(c("-e", "--execute"), action="store", default=FALSE, type='logical',
help="Whether to run the command default is to only print out command
Default (FALSE) means to not execute")
)
opt = parse_args(OptionParser(option_list=option_list))
for (i in 1:length(opt)){
if (is.na(opt)[i] == T) {
cat('User did not specify all arguments.\n')
cat('Use gam_randomise.R -h for an expanded usage menu.\n')
quit()
}
}
print("##############################################################################")
print("################ Generalized Additive Model Randomise Script ###############")
print("################ Angel Garcia de la Garza ###############")
print("################ [email protected] ###############")
print("################ Version 3.0.1 ###############")
print("##############################################################################")
##############################################################################
################ Load Libraries ###############
##############################################################################
print("Loading Libraries")
suppressMessages(require(ggplot2))
suppressMessages(require(base))
suppressMessages(require(reshape2))
suppressMessages(require(nlme))
suppressMessages(require(lme4))
suppressMessages(require(gamm4))
suppressMessages(require(stats))
suppressMessages(require(knitr))
suppressMessages(require(mgcv))
suppressMessages(require(plyr))
suppressMessages(require(oro.nifti))
suppressMessages(require(parallel))
suppressMessages(require(optparse))
suppressMessages(require(fslr))
suppressMessages(require(voxel))
##############################################################################
################ Declare Variables ###############
##############################################################################
print("Reading Arguments")
subjDataName <- opt$covariates
OutDirRoot <- opt$output
namePaths <- opt$imagepaths
maskName <- opt$mask
inclusionName <- opt$inclusion
subjID <- opt$subjId
fullFormula <- opt$ffull
redFormula <- opt$freduced
splits <- opt$splits
smooth <- opt$smoothing
skipFourD <- opt$skipfourD
thresh <- opt$thresh
nsim <- opt$nsim
runCommand <- opt$execute
##############################################################################
################ Load subject data ###############
##############################################################################
print("Loading covariates file")
subjData<-readRDS(subjDataName) ##Read Data
subset <- which(subjData[inclusionName] == 1) ##Find subset for analysis
subjData <- subjData[subset, ] #subset data
##############################################################################
################ Create Analysis Directory ###############
##############################################################################
print("Creating Analysis Directory")
OutDir <- paste0(OutDirRoot, "/n",dim(subjData)[1],"_",namePaths,"_",inclusionName,"_smooth",as.character(smooth))
dir.create(OutDir)
setwd(OutDir)
##############################################################################
################ Create and output fourd image ###############
##############################################################################
if (!skipFourD) {
print("Merging images and saving out a fourd image")
subjList <- as.character(subjData[,grep(namePaths, names(subjData))])
length.subj <- length(subjList)
k <- splits
break.subj <- ceiling(length.subj / k)
if (break.subj == 1) {
k = 1
break.subj <- ceiling(length.subj / k )
} else if (break.subj < k ) {
k = break.subj - 1
break.subj <- ceiling(length.subj / k )
}
subMergeNames <- "foo"
for (i in 1:k) {
if (i == k) {
out <- paste0("fourd_",i,".nii.gz")
fslmerge(subjList[(1 + (i-1)*break.subj):length.subj], direction="t", outfile=out, drop_dim=F)
subMergeNames <- c(subMergeNames, out)
} else {
out <- paste0("fourd_",i,".nii.gz")
fslmerge(subjList[(1 + (i-1)*break.subj):((i)*break.subj)], direction="t", outfile=out, drop_dim=F)
subMergeNames <- c(subMergeNames, out)
}
}
subMergeNames <- subMergeNames[-1]
fslmerge(subMergeNames, direction="t", outfile="fourd.nii.gz")
system('rm -f fourd_*.nii.gz')
} else {
print("Skipping fourd image creation; Script will looking for file names fourd.nii.gz under first level directory")
}
system(paste0("scp ", maskName," ",OutDir, "/mask.nii.gz"), wait=T)
print("mask succesfully copied")
##############################################################################
################ Make Output Directory ###############
##############################################################################
print("Creating output directory")
outName <- gsub("~", "", fullFormula)
outName <- gsub(" ", "", outName)
outName <- gsub("\\+","_",outName)
outName <- gsub("\\(","",outName)
outName <- gsub("\\)","",outName)
outName <- gsub(",","",outName)
outName <- gsub("\\.","",outName)
outName <- gsub("=","",outName)
outName <- gsub("\\*","and",outName)
outName <- gsub(":","and",outName)
print("Creating output directory")
outNameRed <- gsub("~", "", redFormula)
outNameRed <- gsub(" ", "", outNameRed)
outNameRed <- gsub("\\+","_",outNameRed)
outNameRed <- gsub("\\(","",outNameRed)
outNameRed <- gsub("\\)","",outNameRed)
outNameRed <- gsub(",","",outNameRed)
outNameRed <- gsub("\\.","",outNameRed)
outNameRed <- gsub("=","",outNameRed)
outNameRed <- gsub("\\*","and",outNameRed)
outNameRed <- gsub(":","and",outNameRed)
outsubDir <- paste0("n",dim(subjData)[1],"gam_randomise_full_",outName,"_reduced_",outNameRed)
outsubDir<-paste(OutDir,outsubDir,sep="/")
logDir<-paste(OutDir,"logs",sep="/")
#Will return a warning if logDir and outsubDir already exist
dir.create(logDir)
dir.create(outsubDir)
system(paste('rm -f', file.path(outsubDir, '*')))
##############################################################################
################ Output summary files ###############
##############################################################################
setwd(outsubDir)
write.table(subjData[, namePaths], paste0(namePaths,".csv"), row.names = F, col.names=FALSE)
write.table(subjData[, subjID], paste0(subjID,".csv"), row.names = F, col.names=FALSE)
print("Succesfully wrote paths and id files")
##############################################################################
################ Echo Arguments ###############
##############################################################################
system( paste0("echo Arguments are: >> ", outsubDir,"/logs.txt"))
system( paste0("echo Covariates file is: ", subjDataName,">> ", outsubDir,"/logs.txt"))
system( paste0("echo Output directory is: ", OutDir,">> ", outsubDir,"/logs.txt"))
system( paste0("echo Path name variable in covarites file is: ", namePaths,">> ", outsubDir,"/logs.txt"))
system( paste0("echo Mask path is: ", maskName,">> ", outsubDir,"/logs.txt"))
system( paste0("echo Inclusion variable name is: ", inclusionName,">> ", outsubDir,"/logs.txt"))
system( paste0("echo ID variable name is: ", subjID,">> ", outsubDir,"/logs.txt"))
system( paste0("echo Formula for full model is: ", outName,">> ", outsubDir,"/logs.txt"))
system( paste0("echo Formula for reduced model is: ", outNameRed,">> ", outsubDir,"/logs.txt"))
#system( paste0("echo Number of splits is: ", splits," >> ", outsubDir,"/logs.txt"))
system( paste0("echo Skip 4D image creation is: ", skipFourD,">> ", outsubDir,"/logs.txt"))
system( paste0("echo Threshold for correction is: ", thresh,">> ", outsubDir,"/logs.txt"))
#system( paste0("echo Number of simulations is: ", nsim," >> ", outsubDir,"/logs.txt"))
system( paste0("echo Run command is: ", outName,">> ", runCommand,"/logs.txt"))
###cleanup logdir
system(paste('rm -f', file.path(logDir, '*')))
print("Succesfully created log files")
##############################################################################
################ Create Design Matrix ###############
##############################################################################
subjData$dummy <- rnorm(dim(subjData)[1])
# model matrices
X = model.matrix(gam(update.formula(fullFormula, "dummy ~ .") , data=subjData))
Xred = model.matrix(gam(update.formula(redFormula, "dummy ~ .") , data=subjData))
print("Succesfully generated design matrices")
##############################################################################
################ Output Design and Contrasts ###############
##############################################################################
## DESIGN AND CONTRASTS ##
# design file
n = nrow(X)
p = ncol(X)
p2 = p - ncol(Xred)
matfile = file.path(outsubDir, 'design.mat')
cat('/NumWaves\t', ncol(X), '\n/NumPoints\t', nrow(X), '\n/PPheights\t', paste(apply(X, 2, function(x) abs(diff(range(x))) ), collapse='\t'), '\n\n/Matrix\n', sep='', file=matfile)
write.table(X, append=TRUE, file=matfile, row.names=FALSE, col.names=FALSE)
print("Succesfully created randomise design file")
# contrast file
confile1 = file.path(outsubDir, 'design.con') # for f-test
cons = matrix(0, nrow=p2, ncol=ncol(X))
cons[ cbind(1:(p2), which(! colnames(X) %in% colnames(Xred) ) ) ] = 1
cat('/ContrastName1\t temp\n/ContrastName2\t\n/NumWaves\t', ncol(X), '\n/NumPoints\t', nrow(cons), '\n/PPheights\t', paste(rep(1,ncol(cons)), collapse='\t'), '\n/RequiredEffect\t1\t1\n\n/Matrix\n', sep='', file=confile1)
write.table(cons, append=TRUE, file=confile1, row.names=FALSE, col.names=FALSE)
print("Succesfully created randomise contrast file")
# fts file
ftsfile = file.path(outsubDir, 'design.fts')
fts = matrix(1, nrow=1, ncol=nrow(cons)) # ftest of all contrasts
cat('/NumWaves\t', nrow(cons), '\n/NumContrasts\t', 1, '\n\n/Matrix\n', sep='', file=ftsfile)
write.table(fts, append=TRUE, file=ftsfile, row.names=FALSE, col.names=FALSE)
print("Succesfully created randomise f-test file")
##############################################################################
################ Generate and Run command ###############
##############################################################################
mergednifti <- paste0(OutDir, "/fourd.nii.gz")
maskfile <- paste0(OutDir, "/mask.nii.gz")
# t distribution is two tailed, F is one tailed. -x outputs voxelwise statistics -N outputs null distribution text files
# F-test
fcmd = paste('randomise -i', mergednifti, '-m', maskfile, '-o', file.path(outsubDir, 'randomise'), '-d', matfile, '-t', confile1, '-f', ftsfile, '--fonly -F', qf( (1-thresh),df1=p2, df2=(n-p) ), '-x -N -n', nsim, '--uncorrp' )
print("Succesfully created call")
##Change run
if (runCommand) {
system(fcmd)
print("Succesfully ran randomise")
}
print(fcmd)
print("Script is done")