functions.R 36.6 KB
Newer Older
Rauschenberger's avatar
Rauschenberger committed
1

Rauschenberger's avatar
Rauschenberger committed
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

#' @name spliceQTL-package
#' @md
#' @aliases spliceQTL
#' 
#' @title
#' 
#' Alternative Splicing
#' 
#' @description
#' 
#' This R package includes various functions
#' for applying the global test of alternative splicing.
#' Some functions only work on the virtual machine (see below).
#' 
#' @seealso 
#' 
#' Prepare BBMRI and Geuvadis data:
#' * \code{\link{get.snps.geuvadis}} (not VM)
#' * \code{\link{get.snps.bbmri}} (only VM)
#' * \code{\link{get.exons.geuvadis}} (only VM)
#' * \code{\link{get.exons.bbmri}} (only VM)
#' 
#' Process samples and covariates:
#' * \code{\link{match.samples}}
#' * \code{\link{adjust.samples}}
Rauschenberger's avatar
Rauschenberger committed
28
#' * \code{\link{adjust.variables}}
Rauschenberger's avatar
Rauschenberger committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#' 
#' Search for exons and SNPs:
#' * \code{\link{map.genes}}
#' * \code{\link{map.exons}}
#' * \code{\link{map.snps}}
#' * \code{\link{drop.trivial}}
#' 
#' Test for alternative splicing:
#' * \code{\link{test.single}}
#' * \code{\link{test.multiple}}
#'
#' @keywords documentation
#' @docType package
#' 
NULL


Rauschenberger's avatar
Rauschenberger committed
46
47
48
49
50
#' @export
#' @title
#' Get SNP data (Geuvadis)
#' 
#' @description
Rauschenberger's avatar
Rauschenberger committed
51
52
53
54
55
56
57
#' This function transforms SNP data (local machine):
#' downloads missing genotype data from ArrayExpress,
#' transforms variant call format to binary files,
#' removes SNPs with low minor allele frequency,
#' labels SNPs in the format "chromosome:position",
#' changes sample identifiers
#'  
Rauschenberger's avatar
Rauschenberger committed
58
59
60
#' @param chr
#' chromosome: integer \eqn{1-22}
#' 
Rauschenberger's avatar
Rauschenberger committed
61
#' @param data
Rauschenberger's avatar
Rauschenberger committed
62
#' local directory for VCF (variant call format)
Rauschenberger's avatar
Rauschenberger committed
63
#' and SDRF (sample and data relationship format) files;
Rauschenberger's avatar
Rauschenberger committed
64
#' 
Rauschenberger's avatar
Rauschenberger committed
65
66
67
#' @param path
#' local directory for output
#' 
Rauschenberger's avatar
Rauschenberger committed
68
69
70
#' @examples
#' path <- "C:/Users/a.rauschenbe/Desktop/spliceQTL/data"
#' 
Rauschenberger's avatar
Rauschenberger committed
71
get.snps.geuvadis <- function(chr,data=NULL,path=getwd()){
Rauschenberger's avatar
Rauschenberger committed
72
    
Rauschenberger's avatar
Rauschenberger committed
73
74
75
76
77
78
79
80
81
82
83
84
    if(is.null(data)){
        data <- path
        # download SNP data
        file <- paste0("GEUVADIS.chr",chr,".PH1PH2_465.IMPFRQFILT_BIALLELIC_PH.annotv2.genotypes.vcf.gz")
        url <- paste0("http://www.ebi.ac.uk/arrayexpress/files/E-GEUV-1/genotypes/",file)
        destfile <- file.path(data,file)
        if(!file.exists(destfile)){
            utils::download.file(url=url,destfile=destfile,method="auto")
        }
        # transform with PLINK
        setwd(data)
        system(paste0("plink --vcf GEUVADIS.chr",chr,".PH1PH2_465.IMPFRQFILT_BIALLELIC_PH.annotv2.genotypes.vcf.gz",
Rauschenberger's avatar
Rauschenberger committed
85
                  " --maf 0.05 --geno 0 --make-bed --out snps",chr),invisible=FALSE)
Rauschenberger's avatar
Rauschenberger committed
86
87
88
89
90
91
92
93
        # obtain identifiers
        file <- "E-GEUV-1.sdrf.txt"
        url <- paste("http://www.ebi.ac.uk/arrayexpress/files/E-GEUV-1/",file,sep="")
        destfile <- file.path(data,file)
        if(!file.exists(destfile)){
            utils::download.file(url=url,destfile=destfile,method="auto")
        }
    }
Rauschenberger's avatar
Rauschenberger committed
94
95
    
    # read into R
Rauschenberger's avatar
Rauschenberger committed
96
97
98
    bed <- file.path(data,paste("snps",chr,".bed",sep=""))
    bim <- file.path(data,paste("snps",chr,".bim",sep=""))
    fam <- file.path(data,paste("snps",chr,".fam",sep=""))
Rauschenberger's avatar
Rauschenberger committed
99
100
101
    X <- snpStats::read.plink(bed=bed,bim=bim,fam=fam)
    X$fam <- NULL; all(diff(X$map$position) > 0)
    
Rauschenberger's avatar
Rauschenberger committed
102
    # filter MAF
Rauschenberger's avatar
Rauschenberger committed
103
104
105
106
107
108
109
110
111
112
113
    maf <- snpStats::col.summary(X$genotypes)$MAF
    cond <- maf >= 0.05
    X$genotypes <- X$genotypes[,cond]
    X$map <- X$map[cond,]
    
    # format
    colnames(X$genotypes) <- paste0(X$map$chromosome,":",X$map$position)
    snps <- methods::as(object=X$genotypes,Class="numeric")
    class(snps) <- "integer"
    
    # change identifiers
Rauschenberger's avatar
Rauschenberger committed
114
    samples <- utils::read.delim(file=file.path(data,"E-GEUV-1.sdrf.txt"))
Rauschenberger's avatar
Rauschenberger committed
115
116
117
118
119
120
121
122
123
124
125
126
127
    match <- match(rownames(snps),samples$Source.Name)
    rownames(snps) <- samples$Comment.ENA_RUN.[match]
    snps <- snps[!is.na(rownames(snps)),]
    
    save(object=snps,file=file.path(path,paste0("Geuvadis.chr",chr,".RData")))
}


#' @export
#' @title
#' Get SNP data (BBMRI)
#' 
#' @description
Rauschenberger's avatar
Rauschenberger committed
128
129
130
131
132
133
#' This function transforms SNP data (virtual machine):
#' limits analysis to specified biobanks,
#' reads in genotype data in chunks,
#' removes SNPs with missing values (multiple biobanks/technologies),
#' removes SNPs with low minor allele frequency,
#' fuses data from multiple biobanks/technologies
Rauschenberger's avatar
Rauschenberger committed
134
135
136
137
138
139
140
141
142
143
#' 
#' @param chr
#' chromosome: integer \eqn{1-22}
#' 
#' @param biobank
#' character "CODAM", "LL", "LLS", "NTR", "PAN", "RS", or NULL (all)
#' 
#' @param path
#' data directory
#' 
Rauschenberger's avatar
Rauschenberger committed
144
#' @param size
Rauschenberger's avatar
Rauschenberger committed
145
146
#' maximum number of SNPs to read in at once;
#' trade-off between memory usage (low) and speed (high)
Rauschenberger's avatar
Rauschenberger committed
147
#' 
Rauschenberger's avatar
Rauschenberger committed
148
149
150
#' @examples
#' path <- "/virdir/Scratch/arauschenberger/trial"
#'
Rauschenberger's avatar
Rauschenberger committed
151
get.snps.bbmri <- function(chr,biobank=NULL,path=getwd(),size=500*10^3){
Rauschenberger's avatar
Rauschenberger committed
152
153
154
155
156
157
158
159
160
161
162
163

    start <- Sys.time()
    message(rep("-",times=20)," chromosome ",chr," ",rep("-",times=20))
    
    p <- 5*10^6 # (maximum number of SNPs per chromosome, before filtering)
    skip <- seq(from=0,to=p,by=size)
    if(is.null(biobank)){
        study <- c("CODAM","LL","LLS0","LLS1","NTR0","NTR1","PAN","RS")
    } else if(biobank=="LLS"){
        study <- c("LLS0","LLS1")
    } else if(biobank=="NTR"){
        study <- c("NTR0","NTR1")
Rauschenberger's avatar
Rauschenberger committed
164
    } else if(biobank %in% c("CODAM","LL","PAN","RS")){
Rauschenberger's avatar
Rauschenberger committed
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
        study <- biobank
    } else{
        stop("Invalid biobank.",call.=FALSE)
    }
    collect <- matrix(list(),nrow=length(skip),ncol=length(study))
    colnames(collect) <- study
    
    for(i in seq_along(skip)){
        message("\n","chunk ",i,": ",appendLF=FALSE)
        for(j in seq_along(study)){
            message(study[j],"  ",appendLF=FALSE)
            
            # Locating files on virtual machine.
            dir <- study[j]
            if(study[j]=="LLS0"){dir <- "LLS/660Q"}
            if(study[j]=="LLS1"){dir <- "LLS/OmniExpr"}
            if(study[j]=="NTR0"){dir <- "NTR/Affy6"}
            if(study[j]=="NTR1"){dir <- "NTR/GoNL"}
            path0 <- file.path("/mnt/virdir/Backup/RP3_data/HRCv1.1_Imputation",dir)
Rauschenberger's avatar
Rauschenberger committed
184
            path1 <- path
Rauschenberger's avatar
Rauschenberger committed
185
186
187
188
189
            file0 <- paste0("chr",chr,".dose.vcf.gz")
            file1 <- paste0(study[j],".chr",chr,".dose.vcf.gz")
            file2 <- paste0(study[j],".chr",chr,".dose.vcf")
            
            # Reading in files.
Rauschenberger's avatar
Rauschenberger committed
190
191
            #vcf <- vcfR::read.vcfR(file=file.path(path1,file2),skip=skip[i],nrows=size,verbose=FALSE)
            vcf <- vcfR::read.vcfR(file=file.path(path0,file0),skip=skip[i],nrows=size,verbose=FALSE)
Rauschenberger's avatar
Rauschenberger committed
192
193
194
195
196
197
198
199
200
201
202
            vcf <- vcf[vcf@fix[,"CHROM"]!="",] # bug fix
            vcf@fix[,"ID"] <- paste0(vcf@fix[,"ID"],"_",seq_len(dim(vcf)["variants"]))
            collect[i,j][[1]] <- vcf
            stop <- dim(vcf)["variants"]==0
            final <- dim(vcf)["variants"]<size
            if(stop){break}
        }
        print(utils::object.size(collect),units="Gb")
        end <- Sys.time()
        if(stop){break}
        
Rauschenberger's avatar
Rauschenberger committed
203
        # only retain SNPs measured in all studies
Rauschenberger's avatar
Rauschenberger committed
204
        position <- lapply(seq_along(study),function(j) collect[i,j][[1]]@fix[,"POS"])
Rauschenberger's avatar
Rauschenberger committed
205
206
207
208
209
210
        common <- Reduce(f=intersect,x=position)
        for(j in seq_along(study)){
            cond <- match(x=common,table=position[[j]])
            collect[i,j][[1]] <- collect[i,j][[1]][cond,]
        }
        
Rauschenberger's avatar
Rauschenberger committed
211
212
213
214
215
216
217
218
219
        # Calculating minor allele frequency.
        num <- numeric(); maf <- list()
        for(j in seq_along(study)){
            num[j] <- dim(collect[i,j][[1]])["gt_cols"] # replace by adjusted sample sizes?
            maf[[j]] <- num[j]*vcfR::maf(collect[i,j][[1]])[,"Frequency"]
        }
        cond <- rowSums(do.call(what="cbind",args=maf))/sum(num)>0.05
        if(sum(cond)==0){if(final){break}else{next}}
        
Rauschenberger's avatar
Rauschenberger committed
220
        # Extracting genotypes.
Rauschenberger's avatar
Rauschenberger committed
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
        for(j in seq_along(study)){
            gt <- vcfR::extract.gt(collect[i,j][[1]][cond,])
            gt[gt=="0|0"] <- 0
            gt[gt=="0|1"|gt=="1|0"] <- 1
            gt[gt=="1|1"] <- 2
            storage.mode(gt) <- "integer"
            collect[i,j][[1]] <- gt
        }
        
        if(final){break}
    }
    
    # Removing empty rows.
    cond <- apply(collect,1,function(x) all(sapply(x,length)==0))
    collect <- collect[!cond,,drop=FALSE]
Rauschenberger's avatar
Rauschenberger committed
236

Rauschenberger's avatar
Rauschenberger committed
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
    # Fusing all matrices.
    snps <- NULL
    for(i in seq_len(nrow(collect))){
        inner <- NULL
        for(j in seq_len(ncol(collect))){
            add <- collect[i,j][[1]]
            colnames(add) <- paste0(colnames(collect)[j],":",colnames(add))
            inner <- cbind(inner,add)
        }
        snps <- rbind(snps,inner)
    }
    attributes(snps)$time <- end-start
    rownames(snps) <- sapply(strsplit(x=rownames(snps),split="_"),function(x) x[[1]])
    snps <- t(snps)
    
    # Filter samples.
    rownames(snps) <- sub(x=rownames(snps),pattern="LLS0|LLS1",replacement="LLS")
    rownames(snps) <- sub(x=rownames(snps),pattern="NTR0|NTR1",replacement="NTR")
Rauschenberger's avatar
Rauschenberger committed
255

Rauschenberger's avatar
Rauschenberger committed
256
257
258
259
260
261
262
263
264
265
266
267
268
    if(is.null(biobank)){
        save(object=snps,file=file.path(path1,paste0("BBMRI.chr",chr,".RData")))
    } else {
        save(object=snps,file=file.path(path1,paste0(biobank,".chr",chr,".RData")))
    }
}


#' @export
#' @title
#' Get exon data (Geuvadis)
#' 
#' @description
Rauschenberger's avatar
Rauschenberger committed
269
270
271
272
#' This function transforms exon data (virtual machine):
#' retains exons on the autosomes,
#' labels exons in the format "chromosome_start_end",
#' extracts corresponding gene names
Rauschenberger's avatar
Rauschenberger committed
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
#' 
#' @param path
#' data directory 
#' 
#' @examples
#' path <- "/virdir/Scratch/arauschenberger/trial"
#' 
get.exons.geuvadis <- function(path=getwd()){

    nrows <- 303544
    file <-"/virdir/Scratch/rmenezes/data_counts.txt"
    exons <- utils::read.table(file=file,header=TRUE,nrows=nrows)
    exons <- exons[exons[,"chr"] %in% 1:22,] # autosomes
    rownames(exons) <- exon_id <- paste0(exons[,"chr"],"_",exons[,"start"],"_",exons[,"end"])
    gene_id <- as.character(exons[,4])
    exons <- t(exons[,-c(1:4)])

    save(list=c("exons","exon_id","gene_id"),file=file.path(path,"Geuvadis.exons.RData"))
}


#' @export
#' @title
#' Get exon data (BBMRI)
#' 
#' @description
Rauschenberger's avatar
Rauschenberger committed
299
300
301
302
303
304
305
306
#' This function transforms exon data (virtual machine):
#' loads quality controlled gene expression data,
#' extracts sample identifiers,
#' removes samples without SNP data,
#' loads exon expression data,
#' extracts sample identifiers,
#' retains samples that passed quality control,
#' retains exons on the autosomes
Rauschenberger's avatar
Rauschenberger committed
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
#' 
#' @param path
#' data directory 
#' 
#' @examples
#' path <- "/virdir/Scratch/arauschenberger/trial"
#' 
get.exons.bbmri <- function(path=getwd()){
    
    # sample identifiers:
    # (1) loading quality controlled gene expression data 
    # (2) extracting sample identifiers
    # (3) removing identifiers without SNP data
    # (4) translating identifiers
    utils::data(rnaSeqData_ReadCounts_BIOS_cleaned,package="BBMRIomics") # (1)
Rauschenberger's avatar
Rauschenberger committed
322
323
    cd <- SummarizedExperiment::colData(counts)[,c("biobank_id","imputation_id","run_id")] # (2)
    counts <- NULL
Rauschenberger's avatar
Rauschenberger committed
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
    names(cd) <- substr(names(cd),start=1,stop=3) # abbreviate names
    cd <- cd[!is.na(cd$imp),] # (3)
    cd$id <- NA # (4)
    cd$id[cd$bio=="CODAM"] <- sapply(strsplit(x=cd$imp[cd$bio=="CODAM"],split="_"),function(x) x[[2]])
    cd$id[cd$bio=="LL"] <- sub(pattern="1_LLDeep_",replacement="",x=cd$imp[cd$bio=="LL"])
    cd$id[cd$bio=="LLS"] <- sapply(strsplit(x=cd$imp[cd$bio=="LLS"],split="_"),function(x) x[[2]])
    cd$id[cd$bio=="NTR"] <- sapply(strsplit(x=cd$imp[cd$bio=="NTR"],split="_"),function(x) x[[2]])
    cd$id[cd$bio=="PAN"] <- cd$imp[cd$bio=="PAN"]
    cd$id[cd$bio=="RS"] <- sub(pattern="RS1_|RS2_|RS3_",replacement="",x=cd$imp[cd$bio=="RS"])
    
    # Identify individual not with "id" but with "bio:id".
    any(duplicated(cd$id)) # TRUE
    sapply(unique(cd$bio),function(x) any(duplicated(cd$id[x]))) # FALSE
    
    # exon data:
    # (1) loading exon expression data
    # (2) extracting sample identifiers
    # (3) retaining autosomes
    # (4) retaining samples from above
    load("/virdir/Backup/RP3_data/RNASeq/v2.1.3/exon_base/exon_base_counts.RData") # (1)
    colnames(counts) <- sub(pattern=".exon.base.count.gz",replacement="",x=colnames(counts)) # (2)
    autosomes <- sapply(strsplit(x=rownames(counts),split="_"),function(x) x[[1]] %in% 1:22) # (3)
    exons <- counts[autosomes,cd$run] # (3) and (4)
    exon_id <- exon_id[autosomes] # (3)
    gene_id <- gene_id[autosomes] # (3)
    colnames(exons) <- paste0(cd$bio,":",cd$id)
    exons <- t(exons)
    
    save(list=c("exons","exon_id","gene_id"),file=file.path(path,"BBMRI.exons.RData"))
}


Rauschenberger's avatar
Rauschenberger committed
356
357
358
359
360
#' @export
#' @title
#' Prepare data matrices
#' 
#' @description
Rauschenberger's avatar
Rauschenberger committed
361
362
#' This function removes duplicate samples from each matrix,
#' only retains samples appearing in all matrices,
Rauschenberger's avatar
Rauschenberger committed
363
#' and brings samples into the same order.
Rauschenberger's avatar
Rauschenberger committed
364
#' 
Rauschenberger's avatar
Rauschenberger committed
365
#' @param ...
Rauschenberger's avatar
Rauschenberger committed
366
367
#' matrices with samples in the rows and variables in the columns,
#' with sample identifiers as rows names
Rauschenberger's avatar
Rauschenberger committed
368
#' 
Rauschenberger's avatar
Rauschenberger committed
369
370
#' @param message
#' display messages\strong{:} logical
Rauschenberger's avatar
Rauschenberger committed
371
372
#' 
#' @examples
Rauschenberger's avatar
Rauschenberger committed
373
374
375
#' X <- matrix(rnorm(6),nrow=3,ncol=2,dimnames=list(c("A","B","C")))
#' Z <- matrix(rnorm(9),nrow=3,ncol=3,dimnames=list(c("B","A","B")))
#' match.samples(X,Z)
Rauschenberger's avatar
Rauschenberger committed
376
#' 
Rauschenberger's avatar
Rauschenberger committed
377
match.samples <- function(...,message=TRUE){
Rauschenberger's avatar
Rauschenberger committed
378
    
Rauschenberger's avatar
Rauschenberger committed
379
380
    list <- list(...)
    if(length(list)==1 & is.list(list[[1]])){list <- list[[1]]}
Rauschenberger's avatar
Rauschenberger committed
381
382
383
384
385
    if(is.null(names(list))){
        names(list) <- sapply(substitute(list(...))[-1],deparse)
    }
    names <- names(list)
    
Rauschenberger's avatar
Rauschenberger committed
386
    # check input
Rauschenberger's avatar
Rauschenberger committed
387
388
389
    cond <- sapply(list,function(x) !is.matrix(x))
    if(any(cond)){
        stop("Provide matrices!",call.=FALSE)
Rauschenberger's avatar
Rauschenberger committed
390
    }
Rauschenberger's avatar
Rauschenberger committed
391
392
393
    cond <- sapply(list,function(x) is.null(rownames(x)))
    if(any(cond)){
        stop("Provide row names!",call.=FALSE)
Rauschenberger's avatar
Rauschenberger committed
394
395
    }
    
Rauschenberger's avatar
Rauschenberger committed
396
    # remove duplicated samples
Rauschenberger's avatar
Rauschenberger committed
397
    duplic <- lapply(list,function(x) duplicated(rownames(x)))
Rauschenberger's avatar
Rauschenberger committed
398
    for(i in seq_along(list)){
Rauschenberger's avatar
Rauschenberger committed
399
400
401
        number <- round(100*mean(duplic[[i]]))
        if(message){message(number," duplicates in \"",names[i],"\"")}
        list[[i]] <- list[[i]][!duplic[[i]],,drop=FALSE]
Rauschenberger's avatar
Rauschenberger committed
402
    }
Rauschenberger's avatar
Rauschenberger committed
403
404
    
    # retain overlapping samples
Rauschenberger's avatar
Rauschenberger committed
405
406
407
    all <- Reduce(f=intersect,x=lapply(list,rownames))
    for(i in seq_along(list)){
        percent <- round(100*mean(rownames(list[[i]]) %in% all))
Rauschenberger's avatar
Rauschenberger committed
408
        if(message){message(percent,"% overlap in \"",names[i],"\"")}
Rauschenberger's avatar
Rauschenberger committed
409
        list[[i]] <- list[[i]][all,,drop=FALSE]
Rauschenberger's avatar
Rauschenberger committed
410
    }
Rauschenberger's avatar
Rauschenberger committed
411
412
    
    # check output
Rauschenberger's avatar
Rauschenberger committed
413
414
    cond <- sapply(list,function(x) any(duplicated(rownames(x))))
    if(any(cond)){
Rauschenberger's avatar
Rauschenberger committed
415
416
        stop("Duplicate samples!",call.=FALSE)
    }
Rauschenberger's avatar
Rauschenberger committed
417
418
    cond <- sapply(list,function(x) nrow(x)!=nrow(list[[1]]))
    if(any(cond)){
Rauschenberger's avatar
Rauschenberger committed
419
420
        stop("Different sample sizes!",call.=FALSE)
    }
Rauschenberger's avatar
Rauschenberger committed
421
422
    cond <- sapply(list,function(x) any(rownames(x)!=rownames(list[[1]])))
    if(any(cond)){
Rauschenberger's avatar
Rauschenberger committed
423
424
425
        stop("Different sample names!",call.=FALSE)
    }
    
Rauschenberger's avatar
Rauschenberger committed
426
    return(list)
Rauschenberger's avatar
Rauschenberger committed
427
428
429
430
431
432
433
}

#' @export
#' @title
#' Adjust library sizes
#' 
#' @description
Rauschenberger's avatar
Rauschenberger committed
434
#' This function adjusts RNA-seq expression data for different library sizes.
Rauschenberger's avatar
Rauschenberger committed
435
#' 
Rauschenberger's avatar
Rauschenberger committed
436
437
#' @param x
#' matrix with \eqn{n} rows (samples) and \eqn{p} columns (variables)
Rauschenberger's avatar
Rauschenberger committed
438
439
#' 
#' @examples
Rauschenberger's avatar
Rauschenberger committed
440
441
442
443
#' n <- 5; p <- 10
#' x <- matrix(rnbinom(n=n*p,mu=5,size=1/0.5),nrow=n,ncol=p)
#' x[1,] <- 10*x[1,]
#' adjust.samples(x)
Rauschenberger's avatar
Rauschenberger committed
444
#' 
Rauschenberger's avatar
Rauschenberger committed
445
adjust.samples <- function(x){
Rauschenberger's avatar
Rauschenberger committed
446
447
448
449
450
451
    if(!is.matrix(x)){
        stop("no matrix argument",call.=FALSE)
    }
    if(!is.numeric(x)){
        stop("no numeric argument",call.=FALSE)
    }
Rauschenberger's avatar
Rauschenberger committed
452
    if(!is.integer(x)&&any(round(x)!=x)){
Rauschenberger's avatar
Rauschenberger committed
453
        warning("non-integer values",call.=FALSE)
Rauschenberger's avatar
Rauschenberger committed
454
    }
Rauschenberger's avatar
Rauschenberger committed
455
    if(any(x<0)){
Rauschenberger's avatar
Rauschenberger committed
456
        warning("negative values",call.=FALSE)
Rauschenberger's avatar
Rauschenberger committed
457
    }
Rauschenberger's avatar
Rauschenberger committed
458
459
460
    n <- nrow(x); p <- ncol(x)
    lib.size <- rowSums(x)
    norm.factors <- edgeR::calcNormFactors(object=t(x),lib.size=lib.size)
Rauschenberger's avatar
Rauschenberger committed
461
    gamma <- norm.factors*lib.size/mean(lib.size)
Rauschenberger's avatar
Rauschenberger committed
462
    gamma <- matrix(gamma,nrow=n,ncol=p,byrow=FALSE)
Rauschenberger's avatar
Rauschenberger committed
463
464
    x <- x/gamma
    return(x)
Rauschenberger's avatar
Rauschenberger committed
465
466
467
468
469
470
471
472
473
}

#' @export
#' @title
#' Adjust exon length
#' 
#' @description
#' This function adjusts exon expression data for different exon lengths.
#' 
Rauschenberger's avatar
Rauschenberger committed
474
#' @param x
Rauschenberger's avatar
Rauschenberger committed
475
476
#' matrix with \eqn{n} rows (samples) and \eqn{p} columns (exons)
#' 
Rauschenberger's avatar
Rauschenberger committed
477
#' @param offset
Rauschenberger's avatar
Rauschenberger committed
478
#' exon length\strong{:} vector of length \eqn{p}
Rauschenberger's avatar
Rauschenberger committed
479
#' 
Rauschenberger's avatar
Rauschenberger committed
480
481
#' @param group
#' gene names\strong{:} vector of length \eqn{p}
Rauschenberger's avatar
Rauschenberger committed
482
483
484
485
#' 
#' @examples
#' NA
#' 
Rauschenberger's avatar
Rauschenberger committed
486
adjust.variables <- function(x,offset,group){
Rauschenberger's avatar
Rauschenberger committed
487
488
489
    if(!is.numeric(x)|!is.matrix(x)){
        stop("Argument \"x\" is no numeric matrix.",call.=FALSE)
    }
Rauschenberger's avatar
Rauschenberger committed
490
491
492
493
494
    if(!is.numeric(offset)|!is.vector(offset)){
        stop("Argument \"offset\" is no numeric vector.",call.=FALSE)
    }
    if(any(offset<0)){
        stop("Argument \"offset\" takes negative values",call.=FALSE)   
Rauschenberger's avatar
Rauschenberger committed
495
    }
Rauschenberger's avatar
Rauschenberger committed
496
497
498
499
    if(!is.character(group)|!is.vector(group)){
        stop("Argument \"group\" is no character vector.",call.=FALSE)
    }
    if(ncol(x)!=length(group)|ncol(x)!=length(offset)){
Rauschenberger's avatar
Rauschenberger committed
500
501
        stop("Contradictory dimensions.",call.=FALSE)
    }
Rauschenberger's avatar
Rauschenberger committed
502
503
    n <- nrow(x); p <- ncol(x); names <- dimnames(x)
    x <- as.numeric(x)
Rauschenberger's avatar
Rauschenberger committed
504
    offset <- rep(offset,each=n)
Rauschenberger's avatar
Rauschenberger committed
505
506
507
    group <- strsplit(group,split=",")
    group <- sapply(group,function(x) x[[1]][1])
    group <- rep(group,each=n)
Rauschenberger's avatar
Rauschenberger committed
508
    lmer <- lme4::lmer(x ~ offset + (1|group)); gc()
Rauschenberger's avatar
Rauschenberger committed
509
510
511
    x <- matrix(stats::residuals(lmer),nrow=n,ncol=p,dimnames=names)
    x <- x-min(x)
    return(x)
Rauschenberger's avatar
Rauschenberger committed
512
513
514
515
516
517
518
}

#' @export
#' @title
#' Search for genes
#' 
#' @description
Rauschenberger's avatar
Rauschenberger committed
519
#' This function retrieves all protein-coding genes on a chromosome.
Rauschenberger's avatar
Rauschenberger committed
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
#' 
#' @param chr
#' chromosome\strong{:} integer 1-22
#' 
#' @param path
#' path to gene transfer format files (.gtf)
#' 
#' @param release
#' character "NCBI36", "GRCh37", or "GRCh38"
#' 
#' @param build
#' integer 49-91
#' 
#' @examples
#' NA
#' 
Rauschenberger's avatar
Rauschenberger committed
536
537
538
map.genes <- function(chr,path=getwd(),release="GRCh37",build=71){
    
    # check input
Rauschenberger's avatar
Rauschenberger committed
539
    if(!chr %in% 1:22){
Rauschenberger's avatar
Rauschenberger committed
540
541
542
543
544
545
546
547
548
        stop("Invalid argument \"chr\".",call.=FALSE)
    }
    if(!release %in% c("NCBI36","GRCh37","GRCh38")){
        stop("Invalid argument \"release\".",call.=FALSE)
    }
    if(!build %in% 49:91){
        stop("Invalid argument \"build\".",call.=FALSE)
    }
    
Rauschenberger's avatar
Rauschenberger committed
549
550
    file <- paste0("Homo_sapiens.",release,".",build,".gtf")
    if(!file.exists(file.path(path,file))){
Rauschenberger's avatar
Rauschenberger committed
551
552
553
554
555
556
557
558
559
        url <- paste0("ftp://ftp.ensembl.org/pub/release-",build,
                      "/gtf/homo_sapiens/",file,".gz")
        destfile <- file.path(path,paste0(file,".gz"))
        utils::download.file(url=url,destfile=destfile,method="auto")
        R.utils::gunzip(filename=destfile,remove=FALSE,overwrite=TRUE)
    }
    object <- refGenome::ensemblGenome()
    refGenome::basedir(object) <- path
    refGenome::read.gtf(object,filename=file)
Rauschenberger's avatar
Rauschenberger committed
560
561
562
563
564
565
    x <- refGenome::getGenePositions(object=object,by="gene_id")
    x <- x[x$seqid==chr & x$gene_biotype=="protein_coding",]
    x <- x[,c("gene_id","seqid","start","end")]
    rownames(x) <- NULL
    colnames(x)[colnames(x)=="seqid"] <- "chr"
    return(x)
Rauschenberger's avatar
Rauschenberger committed
566
567
568
569
570
571
572
}

#' @export
#' @title
#' Search for exons
#' 
#' @description
Rauschenberger's avatar
Rauschenberger committed
573
#' This function attributes exons to genes.
Rauschenberger's avatar
Rauschenberger committed
574
#' 
Rauschenberger's avatar
Rauschenberger committed
575
#' @param gene
Rauschenberger's avatar
Rauschenberger committed
576
577
#' gene names\strong{:} vector with one entry per gene,
#' including the gene names
Rauschenberger's avatar
Rauschenberger committed
578
#' 
Rauschenberger's avatar
Rauschenberger committed
579
#' @param exon
Rauschenberger's avatar
Rauschenberger committed
580
581
582
#' exon names\strong{:} vector with one entry per exon,
#' including the corresponding \emph{gene} names
#' (separated by comma if multiple gene names)
Rauschenberger's avatar
Rauschenberger committed
583
584
585
586
587
588
#' 
#' @details
#' The exon names should contain the gene names. For each gene, this function
#' returns the indices of the exons.
#' 
#' @examples
Rauschenberger's avatar
Rauschenberger committed
589
590
591
#' gene <- c("A","B","C")
#' exon <- c("A","A,B","B","B,C","C")
#' map.exons(gene,exon)
Rauschenberger's avatar
Rauschenberger committed
592
#'
Rauschenberger's avatar
Rauschenberger committed
593
594
595
map.exons <- function(gene,exon){
    p <- length(gene)
    x <- list()
Rauschenberger's avatar
Rauschenberger committed
596
597
598
    pb <- utils::txtProgressBar(min=0,max=p,style=3)
    for(i in seq_len(p)){
        utils::setTxtProgressBar(pb=pb,value=i)
Rauschenberger's avatar
Rauschenberger committed
599
600
        which <- as.integer(grep(pattern=gene[i],x=exon))
        x[[i]] <- which
Rauschenberger's avatar
Rauschenberger committed
601
    }
Rauschenberger's avatar
Rauschenberger committed
602
603
604
    close(con=pb)
    names(x) <- gene
    return(x)
Rauschenberger's avatar
Rauschenberger committed
605
606
}

Rauschenberger's avatar
Rauschenberger committed
607

Rauschenberger's avatar
Rauschenberger committed
608
609
610
611
612
#' @export
#' @title
#' Search for SNPs
#' 
#' @description
Rauschenberger's avatar
Rauschenberger committed
613
#' This function attributes SNPs to genes.
Rauschenberger's avatar
Rauschenberger committed
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
#' 
#' @param gene.chr
#' chromosome\strong{:}
#' numeric vector with one entry per gene
#' 
#' @param gene.start
#' start position\strong{:}
#' numeric vector with one entry per gene
#' 
#' @param gene.end
#' end position\strong{:}
#' numeric vector with one entry per gene
#' 
#' @param snp.chr
#' integer 1-22
#' 
#' @param snp.pos
#' chromosomal position of SNPs\strong{:}
#' numeric vector with one entry per SNP
#' 
Rauschenberger's avatar
Rauschenberger committed
634
635
636
637
#' @param dist
#' number of base pairs before start position\strong{:}
#' integer
#' 
Rauschenberger's avatar
Rauschenberger committed
638
#' @examples
Rauschenberger's avatar
Rauschenberger committed
639
640
641
#' gene.chr <- rep(1,times=5)
#' gene.start <- 1:5
#' gene.end <- 2:6
Rauschenberger's avatar
Rauschenberger committed
642
#'
Rauschenberger's avatar
Rauschenberger committed
643
644
645
646
647
648
#' snp.chr <- rep(1,times=100)
#' snp.pos <- seq(from=1,to=4.9,length.out=100)
#' 
#' map.snps(gene.chr,gene.start,gene.end,snp.chr,snp.pos,dist=0)
#'
map.snps <- function(gene.chr,gene.start,gene.end,snp.chr,snp.pos,dist=10^3){
Rauschenberger's avatar
Rauschenberger committed
649
650
651
    if(length(gene.chr)!=length(gene.start)|length(gene.chr)!=length(gene.end)){
        stop("Invalid.",call.=FALSE)
    }
Rauschenberger's avatar
Rauschenberger committed
652
653
654
    if(!is.numeric(snp.chr)|!is.numeric(snp.pos)){
        stop("Invalid.",call.=FALSE)
    }
Rauschenberger's avatar
Rauschenberger committed
655
    p <- length(gene.start)
Rauschenberger's avatar
Rauschenberger committed
656
    x <- data.frame(from=integer(length=p),to=integer(length=p))
Rauschenberger's avatar
Rauschenberger committed
657
658
659
660
661
    pb <- utils::txtProgressBar(min=0,max=p,style=3)
    for(i in seq_len(p)){ # 
        utils::setTxtProgressBar(pb=pb,value=i)
        chr <- snp.chr == gene.chr[i]
        if(!any(chr)){next}
Rauschenberger's avatar
Rauschenberger committed
662
        start <- snp.pos >= (gene.start[i] - dist)
Rauschenberger's avatar
Rauschenberger committed
663
664
665
        end <- snp.pos <= gene.end[i] + 0
        which <- as.integer(which(chr & start & end))
        if(length(which)==0){next}
Rauschenberger's avatar
Rauschenberger committed
666
667
        x$from[i] <- min(which)
        x$to[i] <- max(which)
Rauschenberger's avatar
Rauschenberger committed
668
669
670
        if(length(which)==1){next}
        if(!all(diff(which)==1)){stop("SNPs are in wrong order!")}
    }
Rauschenberger's avatar
Rauschenberger committed
671
672
    close(con=pb)
    return(x)
Rauschenberger's avatar
Rauschenberger committed
673
674
}

Rauschenberger's avatar
Rauschenberger committed
675

Rauschenberger's avatar
Rauschenberger committed
676
677
#' @export
#' @title
Rauschenberger's avatar
Rauschenberger committed
678
#' Drop trivial tests
Rauschenberger's avatar
Rauschenberger committed
679
680
#' 
#' @description
Rauschenberger's avatar
Rauschenberger committed
681
#' This function trops trivial tests.
Rauschenberger's avatar
Rauschenberger committed
682
683
684
#' 
#' @param map
#' list with names "genes", "exons", and "snps"
Rauschenberger's avatar
Rauschenberger committed
685
686
#' (output from \code{\link{map.genes}}, \code{\link{map.exons}},
#' and \code{\link{map.snps}})
Rauschenberger's avatar
Rauschenberger committed
687
688
#' 
#' @details
Rauschenberger's avatar
Rauschenberger committed
689
#' This functions drops tests for genes without SNPs or with a single exon.
Rauschenberger's avatar
Rauschenberger committed
690
691
692
693
#' 
#' @examples
#' NA
#' 
Rauschenberger's avatar
Rauschenberger committed
694
drop.trivial <- function(map){
Rauschenberger's avatar
Rauschenberger committed
695
696
697
698
699
700
701
702
703
704
705
    
    # check input
    if(length(map)!=3){
        stop("Unexpected argument length.",call.=FALSE)
    }
    if(any(names(map)!=c("genes","exons","snps"))){
        stop("Unexpected argument names.",call.=FALSE)
    }
    
    # search
    p <- nrow(map$genes)
Rauschenberger's avatar
Rauschenberger committed
706
707
    pass <- rep(NA,times=p)
    pb <- utils::txtProgressBar(min=0,max=p,style=3)
Rauschenberger's avatar
Rauschenberger committed
708
    for(i in seq_len(p)){
Rauschenberger's avatar
Rauschenberger committed
709
710
711
712
713
714
715
716
717
718
        utils::setTxtProgressBar(pb=pb,value=i)
        ys <- map$exons[[i]]
        check <- logical()
        # Exclude genes without SNPs:
        check[1] <- map$snps$from[i] > 0
        check[2] <- map$snps$to[i] > 0
        # Exclude genes with single exon:
        check[3] <- length(ys) > 1
        pass[i] <- all(check)
    }
Rauschenberger's avatar
Rauschenberger committed
719
    close(con=pb)
Rauschenberger's avatar
Rauschenberger committed
720
721
722
723
724
725
726
727
728
    
    # check output
    if(any(pass[map$snps$to==0 & map$snps$from==0])){
        stop("Genes without any SNPs.",call.=FALSE)
    }
    if(any(pass[sapply(map$exons,length)<2])){
        stop("Genes without multiple exons.",call.=FALSE)
    }
    
Rauschenberger's avatar
Rauschenberger committed
729
730
731
732
    map$genes <- map$genes[pass,]
    map$exons <- map$exons[pass]
    map$snps <- map$snps[pass,]
    return(map)
Rauschenberger's avatar
Rauschenberger committed
733
734
735
736
737
}


#' @export
#' @title
Rauschenberger's avatar
Rauschenberger committed
738
#' Conduct single test
Rauschenberger's avatar
Rauschenberger committed
739
740
#' 
#' @description
Rauschenberger's avatar
Rauschenberger committed
741
#' This function tests for alternative splicing.
Rauschenberger's avatar
Rauschenberger committed
742
743
744
745
746
747
748
749
750
751
752
#' 
#' @param Y
#' exon expression\strong{:}
#' matrix with \eqn{n} rows (samples) and \eqn{p} columns (exons)
#' 
#' @param X
#' SNP genotype\strong{:}
#' matrix with \eqn{n} rows (samples) and \eqn{q} columns (SNPs)
#' 
#' @param map
#' list with names "genes", "exons", and "snps"
Rauschenberger's avatar
Rauschenberger committed
753
754
#' (output from \code{\link{map.genes}}, \code{\link{map.exons}},
#' and \code{\link{map.snps}})
Rauschenberger's avatar
Rauschenberger committed
755
756
757
758
759
760
761
762
763
764
765
766
#' 
#' @param i
#' gene index\strong{:}
#' integer between \eqn{1} and \code{nrow(map$genes)}
#' 
#' @param limit
#' cutoff for rounding \code{p}-values
#' 
#' @param steps
#' size of permutation chunks\strong{:}
#' integer vector
#' 
Rauschenberger's avatar
Rauschenberger committed
767
768
769
#' @param rho
#' correlation\strong{:}
#' numeric vector with values between \eqn{0} and \eqn{1}
Rauschenberger's avatar
Rauschenberger committed
770
#' 
Rauschenberger's avatar
Rauschenberger committed
771
772
773
774
775
776
777
778
#' @details
#' The maximum number of permutations equals \code{sum(steps)}. Permutations is
#' interrupted if at least \code{limit} test statistics for the permuted data
#' are larger than the test statistic for the observed data.
#' 
#' @examples
#' NA
#' 
Rauschenberger's avatar
Rauschenberger committed
779
test.single <- function(Y,X,map,i,limit=NULL,steps=NULL,rho=c(0,0.5,1)){
Rauschenberger's avatar
Rauschenberger committed
780
781
782
    
    if(is.null(limit)){limit <- 5}
    if(is.null(steps)){steps <- c(10,20,20,50)}
Rauschenberger's avatar
Rauschenberger committed
783
    
Rauschenberger's avatar
Rauschenberger committed
784
    # check input
Rauschenberger's avatar
Rauschenberger committed
785
786
787
788
789
790
    if(!is.numeric(limit)){
        stop("Argument \"limit\" is not numeric.",call.=FALSE)
    }
    if(limit<1){
        stop("Argument \"limit\" is below one.",call.=FALSE)
    }
Rauschenberger's avatar
Rauschenberger committed
791
    if(!is.numeric(steps)|!is.vector(steps)){
Rauschenberger's avatar
Rauschenberger committed
792
793
794
795
796
797
        stop("Argument \"steps\" is no numeric vector.",call.=FALSE)
    }
    if(sum(steps)<2){
        stop("Too few permutations \"sum(steps)\".",call.=FALSE)
    }
    
Rauschenberger's avatar
Rauschenberger committed
798
    # extract data
Rauschenberger's avatar
Rauschenberger committed
799
    ys <- map$exons[[i]]
Rauschenberger's avatar
Rauschenberger committed
800
    y <- Y[,ys,drop=FALSE]
Rauschenberger's avatar
Rauschenberger committed
801
    xs <- seq(from=map$snps$from[i],to=map$snps$to[i],by=1)
Rauschenberger's avatar
Rauschenberger committed
802
803
    x <- X[,xs,drop=FALSE]
    rm(Y,X); silent <- gc()
Rauschenberger's avatar
Rauschenberger committed
804
    
Rauschenberger's avatar
Rauschenberger committed
805
    # test effects
Rauschenberger's avatar
Rauschenberger committed
806
807
    pvalue <- rep(x=NA,times=length(rho))
    for(j in seq_along(rho)){
Rauschenberger's avatar
Rauschenberger committed
808
809
        tstat <- spliceQTL:::G2.multin(
            dep.data=y,indep.data=x,nperm=steps[1]-1,rho=rho[j])$Sg
Rauschenberger's avatar
Rauschenberger committed
810
        for(nperm in steps[-1]){
Rauschenberger's avatar
Rauschenberger committed
811
812
            tstat <- c(tstat,spliceQTL:::G2.multin(
                dep.data=y,indep.data=x,nperm=nperm,rho=rho[j])$Sg[-1])
Rauschenberger's avatar
Rauschenberger committed
813
            if(sum(tstat >= tstat[1]) >= limit){break}
Rauschenberger's avatar
Rauschenberger committed
814
        }
Rauschenberger's avatar
Rauschenberger committed
815
        pvalue[j] <- mean(tstat >= tstat[1],na.rm=TRUE)
Rauschenberger's avatar
Rauschenberger committed
816
    }
Rauschenberger's avatar
Rauschenberger committed
817

Rauschenberger's avatar
Rauschenberger committed
818
819
820
821
    return(pvalue)
}


Rauschenberger's avatar
Rauschenberger committed
822
823
#' @export
#' @title
Rauschenberger's avatar
Rauschenberger committed
824
#' Conduct multiple tests
Rauschenberger's avatar
Rauschenberger committed
825
826
#' 
#' @description
Rauschenberger's avatar
Rauschenberger committed
827
#' This function tests for alternative splicing.
Rauschenberger's avatar
Rauschenberger committed
828
829
830
831
832
833
834
835
836
#' 
#' @param Y
#' exon expression\strong{:}
#' matrix with \eqn{n} rows (samples) and \eqn{p} columns (exons)
#' 
#' @param X
#' SNP genotype\strong{:}
#' matrix with \eqn{n} rows (samples) and \eqn{q} columns (SNPs)
#' 
Rauschenberger's avatar
Rauschenberger committed
837
838
839
840
#' @param map
#' list with names "genes", "exons", and "snps"
#' (output from \code{map.genes}, \code{map.exons}, and \code{map.snps})
#' 
Rauschenberger's avatar
Rauschenberger committed
841
842
843
844
#' @param rho
#' correlation\strong{:}
#' numeric vector with values between \eqn{0} and \eqn{1}
#' 
Rauschenberger's avatar
Rauschenberger committed
845
846
847
848
#' @param spec
#' number of cores\strong{:}
#' positive integer
#' 
Rauschenberger's avatar
Rauschenberger committed
849
850
851
852
#' @param min
#' minim chunk size\strong{:}
#' positive integer
#' 
Rauschenberger's avatar
Rauschenberger committed
853
854
855
856
#' @param steps
#' number of iteration chunks\strong{:}
#' positive integer
#' 
Rauschenberger's avatar
Rauschenberger committed
857
858
859
860
861
862
863
#' @details
#' Automatic adjustment of the number of permutations
#' such that Bonferroni-significant p-values are possible.
#' 
#' @examples
#' NA
#' 
Rauschenberger's avatar
Rauschenberger committed
864
test.multiple <- function(Y,X,map,rho=c(0,0.5,1),spec=1,min=100,steps=20){
Rauschenberger's avatar
Rauschenberger committed
865
    
Rauschenberger's avatar
Rauschenberger committed
866
867
868
    p <- nrow(map$genes)
    
    # permutations
Rauschenberger's avatar
Rauschenberger committed
869
    if(FALSE){ # old
Rauschenberger's avatar
Rauschenberger committed
870
871
872
873
874
875
876
877
878
        min <- 5
        max <- p/0.05+1
        limit <- ceiling(0.05*max/p)
        base <- 1.5 # adjust sequence
        from <- log(min,base=base)
        to <- log(max,base=base)
        steps <- c(min,diff(unique(round(base^(seq(from=from,to=to,length.out=20))))))
    }
    
Rauschenberger's avatar
Rauschenberger committed
879
    if(FALSE){ # new
Rauschenberger's avatar
Rauschenberger committed
880
881
        max <- p/0.05+1
        limit <- ceiling(0.05*max/p)
Rauschenberger's avatar
Rauschenberger committed
882
        steps <- diff(limit^seq(from=1,to=log(max)/log(limit),length.out=pmin(p,steps))) # was (p,20)
Rauschenberger's avatar
Rauschenberger committed
883
        steps <- c(limit,round(steps)) # Or replace "limit" by "minimum # of permutations"!
Rauschenberger's avatar
Rauschenberger committed
884
        steps[steps==0] <- 1
Rauschenberger's avatar
Rauschenberger committed
885
886
        steps[length(steps)] <- max-sum(steps[-length(steps)])
    }
Rauschenberger's avatar
Rauschenberger committed
887
    
Rauschenberger's avatar
Rauschenberger committed
888
889
890
    if(TRUE){
        max <- p/0.05+1
        limit <- ceiling(0.05*max/p)
Rauschenberger's avatar
Rauschenberger committed
891
        steps <- diff(limit^seq(from=log(min),to=log(max)/log(limit),length.out=steps)) # was pmin(p,steps)
Rauschenberger's avatar
Rauschenberger committed
892
        steps[steps<min] <- min
Rauschenberger's avatar
Rauschenberger committed
893
894
895
896
897
        #for(i in 1:10){
        #    cond <- steps>10^i & steps<10^(i+1)
        #    steps[cond] <- ceiling(steps[cond]/10^i)*10^i 
        #}
        steps = signif(steps,digits=1)
Rauschenberger's avatar
Rauschenberger committed
898
899
        steps <- steps[cumsum(steps)<=max]
        steps[length(steps)+1] <- max-sum(steps)
Rauschenberger's avatar
Rauschenberger committed
900
901
    }
    
Rauschenberger's avatar
Rauschenberger committed
902
903
904
    if(any(steps<0)){stop("negative step",call.=FALSE)}
    if(max != sum(steps)){stop("invalid step",call.=FALSE)}

Rauschenberger's avatar
Rauschenberger committed
905
906
907
908
909
910
    if(spec==1){
        pvalue <- lapply(X=seq_len(p),FUN=function(i) spliceQTL::test.single(Y=Y,X=X,map=map,i=i,limit=limit,steps=steps,rho=rho))
    } else {
        type <- ifelse(test=.Platform$OS.type=="windows",yes="PSOCK",no="FORK")
        cluster <- parallel::makeCluster(spec=spec,type=type)
        parallel::clusterSetRNGStream(cl=cluster,iseed=1)
Rauschenberger's avatar
Rauschenberger committed
911
912
        #parallel::clusterExport(cl=cluster,varlist=c("Y","X","map","limit","steps","rho"),envir=environment())
        #parallel::clusterEvalQ(cl=cluster,library(spliceQTL,lib.loc="/virdir/Scratch/arauschenberger/library"))
Rauschenberger's avatar
Rauschenberger committed
913
914
915
        pvalue <- parallel::parLapply(cl=cluster,X=seq_len(p),fun=function(i) test.single(Y=Y,X=X,map=map,i=i,limit=limit,steps=steps,rho=rho))
        #pvalue <- parallel::parLapply(cl=cluster,X=seq_len(p),fun=function(i) test.trial(y=Y[,map$exons[[i]],drop=FALSE],x=X[,seq(from=map$snps$from[i],to=map$snps$to[i],by=1),drop=FALSE],limit=limit,steps=steps,rho=rho))
        parallel::stopCluster(cluster)
Rauschenberger's avatar
Rauschenberger committed
916
        rm(cluster)
Rauschenberger's avatar
Rauschenberger committed
917
    }
Rauschenberger's avatar
Rauschenberger committed
918
    
Rauschenberger's avatar
Rauschenberger committed
919
    # tyding up
Rauschenberger's avatar
Rauschenberger committed
920
    pvalue <- do.call(what=rbind,args=pvalue)
Rauschenberger's avatar
Rauschenberger committed
921
    colnames(pvalue) <- paste0("rho=",rho)
Rauschenberger's avatar
Rauschenberger committed
922
923
    rownames(pvalue) <- map$genes$gene_id
    
Rauschenberger's avatar
Rauschenberger committed
924
    return(pvalue)
Rauschenberger's avatar
Rauschenberger committed
925
926
}

Rauschenberger's avatar
Rauschenberger committed
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
#' @export
#' @title
#' Plot grid
#' 
#' @description
#' This function tests for alternative splicing.
#' 
#' @param x
#' vector
#' 
#' @param y
#' vector
#' 
#' @param xlim
#' horizontal limits
#' 
#' @param ylim
#' vertical limits
#' 
#' @param n
#' grid resolution
#' 
#' @examples
#' x <- stats::rbeta(n=100,shape1=0.2,shape2=0.5)
#' y <- stats::rbeta(n=100,shape1=0.2,shape2=0.5)
#' grid(x,y)
#' 
grid <- function(x,y,xlim=NULL,ylim=NULL,n=10){
    # open plot
    if(is.null(xlim)){xlim <- range(x)}
    if(is.null(ylim)){ylim <- range(y)}
    graphics::plot.new()
    graphics::plot.window(xlim=xlim,ylim=ylim)
    graphics::box()
    graphics::axis(side=1)
    graphics::axis(side=2)
    
    # density
    xc <- seq(from=xlim[1],to=xlim[2],length.out=n+1)
    yc <- seq(from=ylim[2],to=ylim[1],length.out=n+1)
    M <- matrix(integer(),nrow=n,ncol=n)
    for(i in seq_len(n)){
        for(j in seq_len(n)){
            M[i,j] <- sum(x >= xc[i] & x <= xc[i+1] & y <= yc[j] & y >= yc[j+1])
        }
    }
    M <- M/(1.5*max(M))
    
    # fill plot
    for(i in seq_len(n)){
        for(j in seq_len(n)){
            graphics::polygon(x=c(xc[i],xc[i],xc[i+1],xc[i+1]),
                              y=c(yc[j],yc[j+1],yc[j+1],yc[j]),
                              col=gray(level=1-M[i,j]))
        }
    }
    graphics::segments(x0=xc,y0=ylim[1],y1=ylim[2],col="white")
    graphics::segments(x0=xlim[1],x1=xlim[2],y0=yc,col="white")
    graphics::points(x=x,y=y,pch=16,cex=0.5)
}



Rauschenberger's avatar
Rauschenberger committed
990

Rauschenberger's avatar
Rauschenberger committed
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
# test.trial <- function(y,x,limit=NULL,steps=NULL,rho=c(0,0.5,1)){
#     
#     if(is.null(limit)){limit <- 5}
#     if(is.null(steps)){steps <- c(10,20,20,50)}
#     
#     # check input
#     if(!is.numeric(limit)){
#         stop("Argument \"limit\" is not numeric.",call.=FALSE)
#     }
#     if(limit<1){
#         stop("Argument \"limit\" is below one.",call.=FALSE)
#     }
#     if(!is.numeric(steps)|!is.vector(steps)){
#         stop("Argument \"steps\" is no numeric vector.",call.=FALSE)
#     }
#     if(sum(steps)<2){
#         stop("Too few permutations \"sum(steps)\".",call.=FALSE)
#     }
#     
#     # test effects
#     pvalue <- rep(x=NA,times=length(rho))
#     for(j in seq_along(rho)){
#         tstat <- spliceQTL:::G2.multin(
#             dep.data=y,indep.data=x,nperm=steps[1]-1,rho=rho[j])$Sg
#         for(nperm in steps[-1]){
#             tstat <- c(tstat,spliceQTL:::G2.multin(
#                 dep.data=y,indep.data=x,nperm=nperm,rho=rho[j])$Sg[-1])
#             if(sum(tstat >= tstat[1]) >= limit){break}
#         }
#         pvalue[j] <- mean(tstat >= tstat[1],na.rm=TRUE)
#     }
#     
#     return(pvalue)
# }

Rauschenberger's avatar
Rauschenberger committed
1026

Rauschenberger's avatar
Rauschenberger committed
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
#--- spliceQTL test functions --------------------------------------------------

# Function: G2.multin
# This is to compute the G2 test statistic under the assumption that the response follows a multinomial distribution
### Input 
### dep data and indep data with samples on the rows and genes on the columns
### grouping: Either a logical value = F or a matrix with a single column and same number of rows as samples. 
###         Column name should be defined.
###         Contains clinical information of the samples. 
###         Should have two groups only. 
### nperm : number of permutations 
### rho: the null correlation between SNPs
### mu: the null correlation between observations corresponding to different exons and different individuals
Rauschenberger's avatar
Rauschenberger committed
1040
#
Rauschenberger's avatar
Rauschenberger committed
1041
1042
### Output
### A list containing G2 p.values and G2 test statistics
Rauschenberger's avatar
Rauschenberger committed
1043
#
Rauschenberger's avatar
Rauschenberger committed
1044
1045
1046
### Example : G2T = G2(dep.data = cgh, indep.data = expr, grouping=F, stand=TRUE, nperm=1000)
### G2 p.values : G2T$G2p
### G2 TS : G2T$$Sg
Rauschenberger's avatar
Rauschenberger committed
1047
#
Rauschenberger's avatar
Rauschenberger committed
1048
G2.multin <- function(dep.data,indep.data,stand=TRUE,nperm=100,grouping=F,rho=0,mu=0){
Rauschenberger's avatar
Rauschenberger committed
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
    
    nperm = nperm
    ## check for the number of samples in dep and indep data
    
    
    if (nrow(dep.data)!=nrow(indep.data)){
        cat("number of samples not same in dep and indep data","\n")
    }
    
    if(any(abs(rho)>1)){
        cat("correlations rho larger than abs(1) are not allowed")
    }
    
    nresponses <- ncol(dep.data)
    ncovariates <- ncol(indep.data)
    ### centering and standardizing the data are not done in this case
    
    #  dep.data = scale(dep.data,center=T,scale=stand)
    #  indep.data = scale(indep.data,center=T,scale=stand)
    
    #### No  grouping of the samples.
    
    ## Calculate U=(I-H)Y and UU', where Y has observations on rows; also tau.mat=X*W.rho*X', 
    ##   where X has observations on rows and variables on columns
    ##  and W.rho = I + rho*(J-I), a square matrix with as many rows as columns in X
    ## NOTE: this formulation uses X with n obs on the rows and m covariates no the columns, so it is the transpose of the first calculations
    nsamples <- nrow(dep.data)
    n.persample <- rowSums(dep.data)
    n.all <- sum(dep.data)
    H <- (1/n.all)*matrix( rep(n.persample,each=nsamples),nrow=nsamples,byrow=T)
    U <- (diag(rep(1,nsamples)) - H) %*% dep.data
    ## Now we may have a vector of values for rho - so we define tau.mat as an array, with the 3rd index corresponding to the value of rho
    tau.mat <- array(0,dim=c(nsamples,nsamples,length(rho)))
    for(xk in 1:length(rho))  
    {  
        if (rho[xk]==0) { tau.mat[,,xk] <- tcrossprod(indep.data) } 
        else { w.rho <- diag(rep(1,ncovariates)) + rho[xk]*(tcrossprod(rep(1,ncovariates)) -diag(rep(1,ncovariates))  )
        tau.mat[,,xk] <- indep.data %*% w.rho %*% t(indep.data)}
        
    }
    ######################################
    ### NOTES ARMIN START ################
    # all(X %*% t(X) == tau.mat[,,1]) # rho = 0 -> TRUE
    # all(X %*% (t(X) %*% X) %*% t(X) == tau.mat[,,1]) # rho = 1
    # plot(as.numeric(X %*% (t(X) %*% X) %*% t(X)),as.numeric(tau.mat[,,1]))
    ### NOTES ARMIN END ##################
    ######################################
    samp_names = 1:nsamples ## this was rownames(indep.data), but I now do this so that rownames do not have to be added to the array tau.mat
    Sg = get.g2stat.multin(U,mu=mu,rho=rho,tau.mat)
    ### now we will have a vector as result, with one value per combination of values of rho and mu
    #
    ### G2 
    ### Permutations
    # When using permutations: only the rows of tau.mat are permuted
    # To check how the permutations can be efficiently applied, see tests_permutation_g2_multin.R
    
    
    perm_samp = matrix(0, nrow=nrow(indep.data), ncol=nperm)   ## generate the permutation matrix
    for(i in 1:ncol(perm_samp)){
        perm_samp[,i] = samp_names[sample(1:length(samp_names),length(samp_names))]
    }
    
    ## permutation starts - recompute tau.mat  (or recompute U each time)
    for (perm in 1:nperm){
        tau.mat.perm = tau.mat[perm_samp[,perm],,,drop=FALSE]          # permute rows
        tau.mat.perm = tau.mat.perm[,perm_samp[,perm],,drop=FALSE]     # permute columns
        
Rauschenberger's avatar
Rauschenberger committed
1116
        Sg = c(Sg,spliceQTL:::get.g2stat.multin(U, mu=mu,rho=rho,tau.mat.perm) )
Rauschenberger's avatar
Rauschenberger committed
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
    }
    
    ########################################################################
    
    #### G2 test statistic
    # *** recompute for a vector of values for each case - just reformat the result with as many rows as permutations + 1,
    # and as many columns as combinations of values of rho and mu
    Sg = matrix(Sg,nrow=nperm+1,ncol=length(mu)*length(rho))
    colnames(Sg) <- paste(rep("rho",ncol(Sg)),rep(1:length(rho),each=length(mu)),rep("mu",ncol(Sg)),rep(1:length(mu),length(rho)) )
    
    ### Calculte G2 pval
Rauschenberger's avatar
Rauschenberger committed
1128
    G2p =  apply(Sg,2,spliceQTL:::get.pval.percol) 
Rauschenberger's avatar
Rauschenberger committed
1129
1130
1131
1132
    
    return (list(perm = perm_samp,G2p = G2p,Sg = Sg))
}

Rauschenberger's avatar
Rauschenberger committed
1133

Rauschenberger's avatar
Rauschenberger committed
1134
1135
1136
1137
1138
1139
1140
1141
# Function: get.g2stat.multin
# Computes the G2 test statistic given two data matrices, under a multinomial distribution
# This is used internally by the G2 function
# Inputs: 
#  U = (I-H)Y, a n*K matrix where n=number obs and K=number multinomial responses possible
#  tau.mat = X' W.rho X, a n*n matrix : both square, symmetric matrices with an equal number of rows
# Output: test statistic (single value)
# 
Rauschenberger's avatar
Rauschenberger committed
1142
get.g2stat.multin <- function(U, mu, rho, tau.mat){
Rauschenberger's avatar
Rauschenberger committed
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
    g2tstat <- NULL
    for(xk in 1:length(rho))
    {
        for(xj in 1:length(mu))
        {
            if(mu[xj]==0) { g2tstat <- c(g2tstat, sum( diag( tcrossprod(U) %*% tau.mat[,,xk] ) ) )
            } else {
                g2tstat <- c(g2tstat, (1-mu[xj])*sum(diag( tcrossprod(U) %*% tau.mat[,,xk] ) ) + mu[xj]*sum( t(U) %*% tau.mat[,,xk] %*% U )  )
            }
            
        }
    }
    g2tstat
}

Rauschenberger's avatar
Rauschenberger committed
1158

Rauschenberger's avatar
Rauschenberger committed
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
# Function: get.pval.percol
# This function takes a vector containing the observed test stat as the first entry, followed by values generated by permutation,
# and computed the estimated p-value
# Input
# x: a vector with length nperm+1
# Output
# the pvalue computed
get.pval.percol <- function(x){
    pval = mean(x[1]<= c(Inf , x[2:length(x)]))
    pval
}