-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathstartrac.R
507 lines (469 loc) · 22.3 KB
/
startrac.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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
#' @importFrom methods setClass setMethod setValidity validObject new slot
NULL
#' The Startrac Class
#'
#' The Startrac object store the data for tcr-based T cell dynamics analyis. The slots contained in Startrac object are listed below:
#' @slot aid character. aid of the object, used for identification of the object. For example, patient id. default: "AID"
#' @slot cell.data data.frame. Each line for a cell, and these columns as required: `Cell_Name`, `clone.id`, `patient`, `majorCluster`, `loc`
#' @slot cell.perm.data object. list of `Startrac`` objects constructed from permutated cell data
#' @slot clonotype.data data.frame. Each line for a clonotype; contain the clonotype level indexes information
#' @slot cluster.data data.frame. Each line for a cluster; contain the cluster level indexes information
#' @slot pIndex.migr data.frame. Each line for a cluster; pairwise migration index between the two locations indicated in the column name.
#' @slot pIndex.tran data.frame. Each line for a cluster; pairwise transition index betwwen the two major clusters indicated by the row name and column name.
#' @slot cluster.sig.data data.frame. Each line for a cluster; contains the p values of cluster indices.
#' @slot pIndex.sig.migr data.frame. Each line for a cluster; contains the p values of pairwise migration indices.
#' @slot pIndex.sig.tran data.frame. Each line for a cluster; contains the p values of pairwise transition indices.
#' @slot clonotype.dist.loc matrix. Each line for a clonotype and describe the cells distribution among the locations.
#' @slot clonotype.dist.cluster matrix. Each line for a clonotype and describe the cells distribution among the clusters.
#' @slot clust.size array. Number of cells of each major cluster.
#' @slot patient.size array. Number of cells of each patient.
#' @slot clone.size array. Number of cells of each clone.
#' @slot clone2patient array. Mapping from patient id to clone id.
#' @name Startrac
#' @rdname Startrac
#' @aliases Startrac-class
#' @exportClass Startrac
Startrac <- setClass("Startrac",
slots = c(aid = "character",
cell.data = "data.frame",
cell.perm.data = "list",
clonotype.data = "data.frame",
cluster.data = "data.frame",
cluster.sig.data = "data.frame",
pIndex.migr = "data.frame",
pIndex.tran = "data.frame",
pIndex.sig.migr = "data.frame",
pIndex.sig.tran = "data.frame",
clonotype.dist.loc = "matrix",
clonotype.dist.cluster = "matrix",
clust.size = "array",
patient.size = "array",
clone.size = "array",
clone2patient = "array"))
setValidity("Startrac",
function(object) {
msg <- NULL
if(!is.data.frame([email protected]) ||
!all(c("Cell_Name","clone.id","patient","majorCluster","loc") %in% colnames([email protected]))){
msg <- sprintf("cell.data must be data.frame and contain these columns: Cell_Name, clone.id, patient, majorCluster, loc")
}
if (is.null(msg)) TRUE
else msg
}
)
#' show method for Startrac
#
#' @param object A Startrac object
#' @name show
#' @aliases show,Startrac-method
#' @docType methods
setMethod("show",
signature = "Startrac",
definition = function(object) {
cat(sprintf("An object of class %s, aid %s, %d cells from %d clonotypes\n",
class(object),
object@aid,
nrow([email protected]),
length([email protected])))
invisible(x = NULL)
}
)
#' initialize method for Startrac
#
#' @importFrom plyr llply ldply
#' @param .Object A Startrac object
#' @param cell.data data.frame contains the input data
#' @param aid character analysis id
#' @param n.perm integer number of permutation will be performed. If NULL, no permutation. (default: NULL)
#' @param cores number of core to be used. Passed to doParallel::registerDoParallel. default: NULL.
#' @name initialize
#' @aliases initialize,Startrac-method
#' @docType methods
#' @rdname initialize-methods
#' @return an object of class \code{Startrac}
setMethod("initialize",
signature = "Startrac",
definition = function(.Object, cell.data, aid="AID",n.perm=NULL,cores=NULL){
.Object@aid <- aid
[email protected] <- as.data.frame(cell.data)
validObject(.Object)
[email protected] <- unclass(table([email protected][,c("clone.id","loc")]))
[email protected] <- unclass(table([email protected][,c("clone.id","majorCluster")]))
[email protected] <- unclass(table([email protected]$majorCluster))
[email protected] <- unclass(table([email protected]$patient))
[email protected] <- unclass(sort(table([email protected]$clone.id),decreasing = T))
.clone2patient <- unique([email protected][,c("patient","clone.id")])
.Object@clone2patient <- as.array(structure(.clone2patient$patient,
names=.clone2patient$clone.id))
[email protected] <- list()
if(!is.null(n.perm)){
registerDoParallel(cores=if(is.null(cores)) (detectCores()-2) else cores)
[email protected] <- llply(seq_len(n.perm),function(i){
perm.cell.data <- ldply(unique([email protected]$patient),function(pp){
.dat <- subset([email protected],patient==pp)
.dat$clone.id <- .dat$clone.id[sample(nrow(.dat))]
return(.dat)
})
###perm.cell.data$clone.id <- perm.cell.data$clone.id[sample(nrow(perm.cell.data))]
new("Startrac",perm.cell.data,aid=sprintf("perm%06d",i))
},.progress = "none",.parallel=T)
}
return(.Object)
}
)
#' Calculate cluster level indices
#
#' @name calIndex
#' @aliases calIndex calIndex,Startrac-method
#'
#' @importFrom plyr llply
#' @importFrom parallel makeCluster stopCluster detectCores
#' @importFrom doParallel registerDoParallel
#' @param object A Startrac object
#' @param n.perm integer number of permutation will be performed. If NULL, no permutation. (default: NULL)
#' @param cores number of core to be used. Passed to doParallel::registerDoParallel. default: NULL.
#' @param normEntropy logical; whether normalize migration and transition index. default: FALSE.
#' @return an object of class \code{Startrac}
Startrac.calIndex <- function(object,cores,n.perm,normEntropy)
{
### cluster level expansion index (STARTRAC-expa)
#### Todo: special case: number of clonotype is 1, i.e. sum(x>0)==1
.entropy <- mcol.entropy([email protected])
.entropy.max <- log2(colSums([email protected] > 0))
.gini <- apply([email protected],2,Gini)
#.GS <- mcol.gini_simpson([email protected])
[email protected] <- data.frame("aid"=object@aid,
"majorCluster"=colnames([email protected]),
"expa"=1-.entropy/.entropy.max,
"gini"=.gini,
"NCells"=colSums([email protected]),
#"gini_simpson"=.GS,
stringsAsFactors = F)
### clone level migration and transition index
if(normEntropy){
.entropy.migr.max <- log2(ncol([email protected]))
.entropy.tran.max <- log2(ncol([email protected]))
}else{
.entropy.migr.max <- 1
.entropy.tran.max <- 1
}
[email protected] <- data.frame("clone.id"=rownames([email protected]),
"migr"=mrow.entropy([email protected])/.entropy.migr.max,
"tran"=mrow.entropy([email protected])/.entropy.tran.max)
### cluster level migration index (STARTRAC-migr) and transition index (STARTRAC-tran)
weights.mtx <- sweep([email protected],2,colSums([email protected]),"/")
index.mtx <- t(weights.mtx) %*% (as.matrix([email protected][,c("migr","tran")]))
[email protected] <- cbind([email protected],index.mtx)
if(!is.null(n.perm)){
#cl <- makeCluster(if(is.null(cores)) (detectCores()-2) else cores)
#registerDoParallel(cl)
registerDoParallel(cores=if(is.null(cores)) (detectCores()-2) else cores)
[email protected] <- llply([email protected],function(x){
calIndex(x,cores=1,normEntropy=normEntropy)
},.progress = "none",.parallel=T)
#stopCluster(cl)
}
return(object)
}
#' @export
setGeneric("calIndex", function(object,cores=NULL,n.perm=NULL,normEntropy=FALSE) standardGeneric("calIndex"))
#' @rdname calIndex
#' @aliases calIndex
setMethod("calIndex", signature = "Startrac", definition = Startrac.calIndex)
#' Calculate pairwise indices
#
#' @name pIndex
#' @aliases pIndex pIndex,Startrac-method
#'
#' @importFrom data.table dcast
#' @importFrom plyr ldply adply
#' @importFrom utils combn
#' @importFrom parallel makeCluster stopCluster detectCores
#' @importFrom doParallel registerDoParallel
#' @param object A Startrac object
#' @param cores number of core to be used. Passed to doParallel::registerDoParallel. default: NULL.
#' @param n.perm integer number of permutation will be performed. If NULL, no permutation. (default: NULL)
#' @return an object of class \code{Startrac}
Startrac.pIndex <- function(object,cores,n.perm)
{
####### index given two cluster or loc
## migr
clone.dist.loc.majorCluster <- table([email protected][,c("majorCluster","clone.id","loc")])
#tic("migr")
#clone.dist.loc.majorCluster.debug <<- clone.dist.loc.majorCluster
withCallingHandlers({
cls.migr.index.df <- ldply(seq_len(dim(clone.dist.loc.majorCluster)[1]),function(i,clone.dist.loc.majorCluster){
dat.cls <- clone.dist.loc.majorCluster[i,,]
i.name <- dimnames(clone.dist.loc.majorCluster)[["majorCluster"]][i]
dat.cls.index <- NULL
if(!is.null(ncol(dat.cls)) && ncol(dat.cls)>=2){
comb.loc <- as.data.frame(t(combn(colnames(dat.cls),2)),stringsAsFactors=F)
dat.cls.pIndex.migr <- apply(comb.loc,1,function(x){
dat.block <- dat.cls[,x]
dat.block.clone.index <- mrow.entropy(dat.block)
dat.block.clone.index[is.na(dat.block.clone.index)] <- 0
t(rowSums(dat.block)/sum(dat.block)) %*% dat.block.clone.index
})
dat.cls.index <- cbind(data.frame(majorCluster=rep(i.name,nrow(comb.loc)),
pIndex.migr=dat.cls.pIndex.migr,
stringsAsFactors = F),
comb.loc)
}
return(dat.cls.index)
},clone.dist.loc.majorCluster=clone.dist.loc.majorCluster,.progress = "none",.parallel=F)
},warning=function(w) {
if(grepl("... may be used in an incorrect context:",conditionMessage(w)))
### strange bug, see https://github.com/hadley/plyr/issues/203
invokeRestart("muffleWarning")
})
#toc()
if(!is.null(cls.migr.index.df) && nrow(cls.migr.index.df)>0){
cls.migr.index.df$crossLoc <- sprintf("%s-%s",cls.migr.index.df$V1,cls.migr.index.df$V2)
[email protected] <- dcast(cls.migr.index.df,majorCluster ~ crossLoc,value.var = "pIndex.migr")
[email protected] <- cbind(data.frame(aid=object@aid,
[email protected][ [email protected][["majorCluster"]] ],
stringsAsFactors = F),
}else{
[email protected] <- data.frame()
}
## tran
if(!is.null(ncol([email protected])) && ncol([email protected])>=2){
##comb.cls <- as.data.frame(t(combn(colnames([email protected]),2)),stringsAsFactors=F)
comb.cls <- expand.grid(colnames([email protected]),
colnames([email protected]),stringsAsFactors = F)
comb.cls <- comb.cls[comb.cls[,1]!=comb.cls[,2],]
#tic("tran")
withCallingHandlers({
cls.tran.index.df <- adply(comb.cls,1,function(x,object){
dat.block <- [email protected][,c(x[[1]],x[[2]])]
dat.block.clone.index <- mrow.entropy(dat.block)
dat.block.clone.index[is.na(dat.block.clone.index)] <- 0
data.frame(pIndex.tran= t(rowSums(dat.block)/sum(dat.block)) %*% dat.block.clone.index)
},object=object,.progress = "none",.parallel=F)
},warning=function(w) {
if(grepl("... may be used in an incorrect context:",conditionMessage(w)))
### strange bug, see https://github.com/hadley/plyr/issues/203
invokeRestart("muffleWarning")
})
#toc()
[email protected] <- dcast(cls.tran.index.df,Var2~Var1,value.var = "pIndex.tran")
colnames([email protected])[1] <- "majorCluster"
[email protected] <- cbind(data.frame(aid=object@aid,
[email protected][ [email protected][["majorCluster"]] ],
stringsAsFactors = F),
if(!is.null(n.perm)){
#cl <- makeCluster(if(is.null(cores)) (detectCores()-2) else cores)
#registerDoParallel(cl)
registerDoParallel(cores=if(is.null(cores)) (detectCores()-2) else cores)
[email protected] <- llply([email protected],function(x){
pIndex(x,cores=1,n.perm=NULL)
},.progress = "none",.parallel=T)
#stopCluster(cl)
}
}else{
[email protected] <- data.frame()
if(!is.null(n.perm)){
### nothing needed to do
}
}
return(object)
}
#' @export
setGeneric("pIndex", function(object,cores=NULL,n.perm=NULL) standardGeneric("pIndex"))
#' @rdname pIndex
#' @aliases pIndex
setMethod("pIndex", signature = "Startrac", definition = Startrac.pIndex)
#' Get the p value given one Startrac object and a list of Startrac objects from permutation data
#
#' @name getSig
#' @aliases getSig getSig,Startrac-method
#'
#' @importFrom plyr laply
#' @importFrom data.table melt
#' @param obj A Startrac object
#' @param obj.perm A list of Startrac objects from permutation data
#' @return an object of class \code{Startrac}
Startrac.getSig <- function(obj,obj.perm)
{
.get.empirical.p <- function(obj,obj.perm,slot.name)
{
if(nrow(slot(obj,slot.name))==0){
return(data.frame())
}
a.index <- melt(slot(obj,slot.name),id.vars=c("aid","majorCluster","NCells"),variable.name="index")
if(!is.null(obj.perm)){
perm.mtx <- t(laply(obj.perm,function(x){
vv <- melt(slot(x,slot.name),id.vars=c("aid","majorCluster","NCells"),variable.name="index")
vv.mtx <- as.matrix(vv[,"value",drop=F])
rownames(vv.mtx) <- sprintf("%s.%s",vv[["majorCluster"]],vv[["index"]])
colnames(vv.mtx) <- x@aid
return(vv.mtx)
}))
stopifnot(all(sprintf("%s.%s",a.index$majorCluster,a.index$index)==rownames(perm.mtx)))
a.index$p.value <- sapply(seq_along(a.index$value),function(i){
v.rnd <- perm.mtx[i,,drop=F]
sum(v.rnd >= a.index$value[i])/length(v.rnd)
})
}else{
a.index$p.value <- NA_real_
}
return(a.index)
}
[email protected] <- .get.empirical.p(obj,obj.perm,"cluster.data")
[email protected] <- .get.empirical.p(obj,obj.perm,"pIndex.migr")
[email protected] <- .get.empirical.p(obj,obj.perm,"pIndex.tran")
return(obj)
}
#' @export
setGeneric("getSig", function(obj,obj.perm=NULL) standardGeneric("getSig"))
#' @rdname getSig
#' @aliases getSig
setMethod("getSig", signature = "Startrac", definition = Startrac.getSig)
#' The StartracOUt Class
#'
#' Object store the result of Startrac.run:
#' @slot proj character. identification of the object. For example, patient id. default: "AID"
#' @slot cluster.data data.frame. Each line for a cluster; contain the cluster level indexes information
#' @slot pIndex.migr data.frame. Each line for a cluster; pairwise migration index between the two locations indicated in the column name.
#' @slot pIndex.tran data.frame. Each line for a cluster; pairwise transition index betwwen the two major clusters indicated by the row name and column name.
#' @slot cluster.sig.data data.frame. Each line for a cluster; contains the p values of cluster indices.
#' @slot pIndex.sig.migr data.frame. Each line for a cluster; contains the p values of pairwise migration indices.
#' @slot pIndex.sig.tran data.frame. Each line for a cluster; contains the p values of pairwise transition indices.
#' @slot objects list. other objects
#' @name StartracOut
#' @rdname StartracOut
#' @aliases StartracOut-class
#' @exportClass StartracOut
StartracOut <- setClass("StartracOut",
slots = c(proj = "character",
cluster.data = "data.frame",
cluster.sig.data = "data.frame",
pIndex.migr = "data.frame",
pIndex.tran = "data.frame",
pIndex.sig.migr = "data.frame",
pIndex.sig.tran = "data.frame",
objects = "list"))
#' initialize method for StartracOut
#
#' @param .Object A StartracOut object
#' @param proj character analysis id
#' @aliases initialize,StartracOut-method
#' @docType methods
#' @return an object of class \code{StartracOut}
setMethod("initialize",
signature = "StartracOut",
definition = function(.Object, proj="AID"){
.Object@proj <- proj
return(.Object)
}
)
#' show method for StartracOut
#
#' @importFrom utils head
#' @param object A StartracOut object
#' @aliases show,StartracOut-method
#' @docType methods
setMethod("show",
signature = "StartracOut",
definition = function(object) {
cat(sprintf("An object of class %s, proj %s:\n",
class(object),
object@proj))
cat("head of the clusters' index:\n")
print(head([email protected]))
cat("head of the pairwise migration index:\n")
print(head([email protected]))
cat("head of the pairwise transition index:\n")
if(ncol([email protected])>0){
print(head([email protected][,1:min(5,ncol([email protected]))]))
}else{
print(head([email protected]))
}
invisible(x = NULL)
}
)
#' plot the indexes
#
#' @name plot
#' @aliases plot plot,StartracOut-method
#'
#' @importFrom plyr laply
#' @importFrom data.table melt as.data.table melt
#' @importFrom ggpubr ggbarplot ggboxplot
#' @importFrom ggplot2 facet_wrap theme element_text aes geom_text
#' @importFrom ComplexHeatmap Heatmap
#' @importFrom RColorBrewer brewer.pal
#' @importFrom circlize colorRamp2
#' @importFrom grDevices colorRampPalette
#' @param obj A object of StartracOut
#' @param index.type one of "cluster.all", "pairwise.migr", "pairwise.tran". (default:"cluster.all")
#' @param byPatient logical. plot indexes of each patient (default: FALSE)
#' @return a ggplot2 object or Heatmap-class object
StartracOut.plot <- function(obj,index.type,byPatient)
{
if(index.type=="cluster.all"){
if(byPatient){
p <- ggboxplot(as.data.table([email protected])[aid!=obj@proj,][order(majorCluster),],
x="majorCluster",y="value",palette = "npg",
color = "index", add = "point", outlier.colour=NULL) +
facet_wrap(~index,ncol=1,scales = "free_y") +
theme(axis.text.x=element_text(angle = 60,hjust = 1))
}else{
dat.plot <- as.data.table([email protected])[aid==obj@proj,]
dat.plot$p.value.label <- ""
dat.plot$p.value.label[dat.plot$p.value < 0.05] <- "*"
dat.plot$p.value.label[dat.plot$p.value < 0.01] <- "**"
dat.plot$p.value.label[dat.plot$p.value < 0.001] <- "***"
p <- ggbarplot(dat.plot[order(majorCluster),],
x="majorCluster",y="value",palette = "npg",fill = "index") +
facet_wrap(~index,ncol=1,scales = "free_y") +
coord_cartesian(clip="off") +
theme(axis.text.x=element_text(angle = 60,hjust = 1),strip.background = element_blank())
if(!all(is.na(dat.plot$p.value))){
p <- p + geom_text(aes(label=p.value.label,y=value),size=5)
}
}
}else if(index.type=="pairwise.migr"){
if(nrow([email protected])==0){ return(NULL) }
if(byPatient){
p <- ggboxplot(as.data.table([email protected])[aid!=obj@proj,][order(majorCluster),],
x="majorCluster",y="value",palette = "npg",
color = "index", add = "point", outlier.colour=NULL) +
facet_wrap(~index,ncol=1,scales = "free_y") +
theme(axis.text.x=element_text(angle = 60,hjust = 1))
}else{
dat.plot <- as.data.table([email protected])[aid==obj@proj,]
dat.plot$p.value.label <- ""
dat.plot$p.value.label[dat.plot$p.value < 0.05] <- "*"
dat.plot$p.value.label[dat.plot$p.value < 0.01] <- "**"
dat.plot$p.value.label[dat.plot$p.value < 0.001] <- "***"
p <- ggbarplot(dat.plot[order(majorCluster),],
x="majorCluster",y="value",palette = "npg",fill = "index") +
facet_wrap(~index,ncol=1,scales = "free_y") +
coord_cartesian(clip="off") +
theme(axis.text.x=element_text(angle = 60,hjust = 1),strip.background = element_blank())
if(!all(is.na(dat.plot$p.value))){
p <- p + geom_text(aes(label=p.value.label,y=value),size=5)
}
}
}else if(index.type=="pairwise.tran"){
if(nrow([email protected])==0){ return(NULL) }
## first 3 columns: aid, NCells, majorCluster
dat.plot <- as.matrix(subset([email protected],aid==obj@proj)[,c(-1,-2,-3)])
rownames(dat.plot) <- subset([email protected],aid==obj@proj)[,3]
dat.plot[is.na(dat.plot)] <- 0
yrange <- pretty(dat.plot)
col.heat <- colorRamp2(seq(0,max(yrange),length=15),
colorRampPalette(rev(brewer.pal(n=7,name="RdBu")))(15),
space = "LAB")
p <- Heatmap(dat.plot,name="pIndex.tran",col = col.heat)
}
return(p)
}
#' @export
setGeneric("plot", function(obj,index.type="cluster.all",byPatient=F) standardGeneric("plot"))
#' @rdname plot
#' @aliases plot
setMethod("plot", signature = "StartracOut", definition = StartracOut.plot)