-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGRIN-ALEX-library.R
1987 lines (1603 loc) · 75.2 KB
/
GRIN-ALEX-library.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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
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
990
991
992
993
994
995
996
997
998
999
1000
############################
# Supporting packages
library(writexl)
library(circlize)
library(biomaRt)
####################################
## Notes (03/03/2022) by Abdel
# I modified grin.stats function by adding prep.data and find.overlap before running count.hits function in line 64
################################################
## Notes (03-07-2022)
# I replaced prep.lsn.type.matrix with an older version of the function (return required results without any errors)
# I added three functions (genomewide.lsn.plot, compute.gw.coordinates and default.grin.colors) to prepare genomewide lesion plot (manhattan plot)
###################################################
# Notes (03-08-2022)
# I modified top.grin.gene.plots function to plot only protein coding genes by gene.name not by ensembl.ID. Some biotypes might have so many genes by the same gene name such as (Y_RNA and U6) which stop the code
# I also modified grin.gene.plot function to plot genes by gene name not by ensembl.ID
#####################################
# Notes (8/24/21)
# moved order.index.lsn.data and order.index.gene.data up before
# creation of glp.data to try and remedy mismatch of pointers from
# glp.data to gene.data
#######################################
# interactive GRIN analysis
# rough idea
# grin.interactive=function()
# {
# lsn.file=file.choose() # user specifies input file
# lsn.data=read.csv(lsn.file)
# genome.assembly=select.list("hg19","hg18")
# gene.data=get.gene.data(genome.assembly)
# chr.data=get.chrom.size.data(genome.assembly)
# res=grin.stats(lsn.data,gene.data,chr.size)
# output.dir=paste0(dirname(lsn.file),"/GRIN/",)
# write.grin.xlsx(res)
# }
######################################
# Complete GRIN analysis
grin.stats=function(lsn.data, # data.frame with columns ID (subject identifier), chrom, loc.start, loc.end, lsn.type
gene.data=NULL, # data.frame with columns gene, chrom, loc.start, loc.end
chr.size=NULL, # data.frame with columns chrom and size
genome.version=NULL) # character string with genome version
{
if (is.null(genome.version)&&(is.null(gene.data)||is.null(chr.size)))
{
genome.version=select.list(c("Human_GRCh38",
"Human_GRCh37",
"Mouse_HGCm39",
"Mouse_HGCm38"))
}
if (is.character(genome.version))
{
ensembl.data=get.ensembl.grin.data(genome.version)
if (is.null(gene.data))
{
gene.data=ensembl.data$gene.data
gene.data$gene=gene.data$Ensembl_ID
}
if (is.null(chr.size))
chr.size=ensembl.data$chr.size
}
prep.data=prep.gene.lsn.data(lsn.data,
gene.data)
find.overlap=find.gene.lsn.overlaps(prep.data)
hit.cnt=count.hits(find.overlap)
hit.pvals=prob.hits(hit.cnt,
chr.size)
return(hit.pvals)
}
########################################
# Generate plots of GRIN analysis
top.grin.gene.plots=function(grin.res, # result of grin.stats
lsn.clrs=NULL, # vector of color names with
q.max=0.10, # q-value threshold for plots
max.plots.per.type=25, # maximum number of plots per lesion type
max.plots.overall=250) # overall maximum number
{
lsn.types=unique(grin.res$lsn.data$lsn.type)
if (is.null(lsn.clrs))
{
lsn.clrs=default.grin.colors(lsn.types)
}
gene.stats=grin.res[["gene.hits"]]
gene.stats=gene.stats[gene.stats$biotype=="protein_coding",]
max.plots.per.type=min(max.plots.per.type,
nrow(gene.stats))
top.genes=NULL
p.clms=c(paste0("p.nsubj.",lsn.types),
paste0("p",1:length(lsn.types),".nsubj"))
q.clms=c(paste0("q.nsubj.",lsn.types),
paste0("q",1:length(lsn.types),".nsubj"))
for (i in 1:length(p.clms))
{
ord=order(gene.stats[,p.clms[i]])
gene.stats=gene.stats[ord,]
keep=which(gene.stats[,q.clms[i]]<q.max)
if (length(keep)>0)
{
keep=keep[keep<max.plots.per.type]
top.genes=c(top.genes,gene.stats[keep,"gene"])
}
}
top.genes=unique(top.genes)
if (length(top.genes)==0)
stop("No genes meet selection criteria for plotting.")
top.gene.rows=which(is.element(gene.stats$gene,top.genes))
top.gene.stats=gene.stats[top.gene.rows,]
ord.crit=rowSums(log10(top.gene.stats[,paste0("q.nsubj.",lsn.types)]))
ord=order(ord.crit)
top.gene.stats=top.gene.stats[ord,]
ntop=nrow(top.gene.stats)
top.gene.stats=top.gene.stats[1:min(ntop,max.plots.overall),]
#top.genes.sel=top.gene.stats[top.gene.stats$biotype=="protein_coding",]
top.genes=top.gene.stats$gene.name
for (i in 1:length(top.genes))
{
grin.gene.plot(grin.res,
top.genes[i],
lsn.clrs=lsn.clrs)
}
}
####################################################
# Plot lesion data and GRIN results for one gene
grin.gene.plot=function(grin.res,
gene,
lsn.clrs=NULL,
expand=0.3)
{
# Find the requested gene
if (length(gene)!=1)
stop("Exactly one gene must be specified!")
gene.data=grin.res[["gene.data"]]
gene.mtch=which(gene.data[,"gene.name"]==gene)
if (length(gene.mtch)==0)
stop(paste0(gene," not found in gene.data."))
if (length(gene.mtch)>1)
stop(paste0("Multiple matches of ",gene," found in gene data."))
gene.chr=gene.data[gene.mtch,"chrom"]
gene.start=gene.data[gene.mtch,"loc.start"]
gene.end=gene.data[gene.mtch,"loc.end"]
gene.size=(gene.end-gene.start)+1
# Find lesions on the same chromosome as the gene
lsn.dset=order.index.lsn.data(grin.res[["lsn.data"]])
lsn.data=lsn.dset$lsn.data
lsn.types=unique(lsn.data$lsn.type)
if (is.null(lsn.clrs))
lsn.clrs=default.grin.colors(lsn.types)
lsn.index=lsn.dset$lsn.index
lsn.ind.mtch=which(lsn.index$chrom==gene.chr)
if (length(lsn.ind.mtch)==0)
stop(paste0("No lesions overlap ",gene,"."))
lsn.chr.rows=NULL
for (i in lsn.ind.mtch)
{
blk.rows=(lsn.index$row.start[i]:lsn.index$row.end[i])
lsn.chr.rows=c(lsn.chr.rows,blk.rows)
}
lsn.chr.rows=unlist(lsn.chr.rows)
lsn.chr.data=lsn.data[lsn.chr.rows,]
if (any(lsn.chr.data$chrom!=gene.chr))
stop(paste0("Error in finding lesions on same chromosome as gene ",gene,"."))
# Find lesions at overlap the gene
ov.rows=which((lsn.chr.data$loc.start<=gene.end)&(lsn.chr.data$loc.end>=gene.start))
if (length(ov.rows)==0)
stop(paste0("No lesions overlap gene ",gene,"."))
lsn.gene=lsn.chr.data[ov.rows,]
# define plotting data
x.start=gene.start-expand*gene.size
x.end=gene.end+expand*gene.size
lsn.gene$subj.num=as.numeric(as.factor(lsn.gene$ID))
lsn.gene$lsn.clr=lsn.clrs[lsn.gene$lsn.type]
lsn.gene$type.num=as.numeric(as.factor(lsn.gene$lsn.type))
n.type=max(lsn.gene$type.num)
n.subj=max(lsn.gene$subj.num)
lsn.gene$y0=-lsn.gene$subj.num+(lsn.gene$type.num-1)/n.type
lsn.gene$y1=-lsn.gene$subj.num+lsn.gene$type.num/n.type
lsn.gene$x0=pmax(lsn.gene$loc.start,x.start)
lsn.gene$x1=pmin(lsn.gene$loc.end,x.end)
plot(c(x.start-0.20*(x.end-x.start),x.end),
c(+0.1,-1.3)*n.subj,type="n",
main="",
xlab="",
ylab="",axes=F)
rect(x.start,
-(1:n.subj),
x.end,
-(1:n.subj)+1,
col=c("snow","gainsboro")[1+(1:n.subj)%%2],
border=NA)
segments(c(gene.start,gene.end),
rep(-n.subj,2),
c(gene.start,gene.end),
rep(0,2),
col="darkgray")
rect(lsn.gene$x0,
lsn.gene$y0,
lsn.gene$x1,
lsn.gene$y1,
col=lsn.gene$lsn.clr,
border=lsn.gene$lsn.clr)
segments(c(gene.start,gene.end),
rep(-n.subj,2),
c(gene.start,gene.end),
rep(0,2),
col="darkgray",lty=2)
text(x.start,-lsn.gene$subj.num+0.5,
lsn.gene$ID,pos=2,cex=0.5)
text(c(gene.start,gene.end),
-n.subj,
c(gene.start,gene.end),
pos=1)
text((gene.start+gene.end)/2,
0,gene,pos=3,cex=1.5)
lgd=legend((x.start+x.end)/2,-1.10*n.subj,
fill=lsn.clrs,
legend=names(lsn.clrs),
ncol=length(lsn.clrs),
xjust=0.5,border=NA,
cex=0.75,bty="n")
text(lgd$text$x[1]-0.05*diff(range(lgd$text$x)),
-c(1.20,1.25,1.30)*n.subj,
c("n","-log10p","-log10q"),pos=2)
gene.stats=grin.res[["gene.hits"]]
stat.mtch=which(gene.stats$gene.name==gene)
gene.stats=gene.stats[stat.mtch,]
text(lgd$text$x,-1.20*n.subj,
gene.stats[,paste0("nsubj.",names(lsn.clrs))],
cex=0.75)
text(lgd$text$x,-1.25*n.subj,
round(-log10(gene.stats[,paste0("p.nsubj.",names(lsn.clrs))]),2),
cex=0.75)
text(lgd$text$x,-1.30*n.subj,
round(-log10(gene.stats[,paste0("q.nsubj.",names(lsn.clrs))]),2),
cex=0.75)
}
###############################################################
prob.hits=function(hit.cnt,chr.size=NULL)
{
if (is.null(chr.size))
chr.size=impute.chrom.size(hit.cnt$lsn.data,
hit.cnt$gene.data)
###################
# order and index gene.lsn.data
ord=order(hit.cnt$gene.lsn.data$lsn.type,
hit.cnt$gene.lsn.data$lsn.chrom,
hit.cnt$gene.lsn.data$gene.row,
hit.cnt$gene.lsn.data$ID)
hit.cnt$gene.lsn.data=hit.cnt$gene.lsn.data[ord,]
m=nrow(hit.cnt$gene.lsn.data)
new.sect=which((hit.cnt$gene.lsn.data$gene.chrom[-1]!=hit.cnt$gene.lsn.data$gene.chrom[-m])|
(hit.cnt$gene.lsn.data$lsn.type[-1]!=hit.cnt$gene.lsn.data$lsn.type[-m])|
(hit.cnt$gene.lsn.data$gene.row[-1]!=hit.cnt$gene.lsn.data$gene.row[-m]))
sect.start=c(1,new.sect+1)
sect.end=c(new.sect,m)
gene.lsn.index=cbind.data.frame(lsn.type=hit.cnt$gene.lsn.data$lsn.type[sect.start],
chrom=hit.cnt$gene.lsn.data$gene.chrom[sect.start],
gene.row=hit.cnt$gene.lsn.data$gene.row[sect.start],
row.start=sect.start,
row.end=sect.end,
n.lsns=sect.end-sect.start+1)
k=nrow(gene.lsn.index)
new.chr=which(gene.lsn.index$chrom[-1]!=gene.lsn.index$chrom[-k])
chr.start=c(1,new.chr+1)
chr.end=c(new.chr,k)
gene.lsn.chr.index=cbind.data.frame(lsn.type=gene.lsn.index$lsn.type[chr.start],
chrom=gene.lsn.index$chrom[chr.start],
row.start=chr.start,
row.end=chr.end,
n.rows=chr.end-chr.start+1)
nr.li=nrow(hit.cnt$lsn.index)
new.chr=which((hit.cnt$lsn.index$lsn.type[-1]!=hit.cnt$lsn.index$lsn.type[-nr.li])|
(hit.cnt$lsn.index$chrom[-1]!=hit.cnt$lsn.index$chrom[-nr.li]))
chr.start=c(1,new.chr+1)
chr.end=c(new.chr,nr.li)
lsn.chr.index=cbind.data.frame(lsn.type=hit.cnt$lsn.index$lsn.type[chr.start],
chrom=hit.cnt$lsn.index$chrom[chr.start],
row.start=chr.start,
row.end=chr.end)
b=nrow(gene.lsn.chr.index)
g=nrow(hit.cnt$nhit.mtx)
nlt=ncol(hit.cnt$nhit.mtx)
p.nsubj=p.nhit=matrix(1,g,nlt)
colnames(p.nsubj)=colnames(p.nhit)=colnames(hit.cnt$nhit.mtx)
for (i in 1:b)
{
# find rows for affected genes
gli.start.row=gene.lsn.chr.index$row.start[i]
gli.end.row=gene.lsn.chr.index$row.end[i]
gld.start.row=gene.lsn.index$row.start[gli.start.row]
gld.end.row=gene.lsn.index$row.end[gli.end.row]
gld.rows=gld.start.row:gld.end.row
gene.rows=unique(hit.cnt$gene.lsn.data$gene.row[gld.rows])
n.genes=length(gene.rows)
# find rows for lesions of this type on this chromosomes
lsn.chr.mtch=which((lsn.chr.index$lsn.type==gene.lsn.chr.index$lsn.type[i])&
(lsn.chr.index$chrom==gene.lsn.chr.index$chrom[i]))
lsn.index.start.row=lsn.chr.index$row.start[lsn.chr.mtch]
lsn.index.end.row=lsn.chr.index$row.end[lsn.chr.mtch]
lsn.start.row=hit.cnt$lsn.index$row.start[lsn.index.start.row]
lsn.end.row=hit.cnt$lsn.index$row.end[lsn.index.end.row]
lsn.rows=lsn.start.row:lsn.end.row
n.lsns=length(lsn.rows)
lsn.type=hit.cnt$lsn.data$lsn.type[lsn.start.row]
message(paste0("Computing p-values for ",
n.genes," gene(s) on chromosome ",
gene.lsn.chr.index$chrom[i],
" affected by ",
n.lsns," ",lsn.type,
" (data block ",i," of ",b,"): ",date()))
# find chromosome size
chr.mtch=which(gene.lsn.chr.index$chrom[i]==chr.size$chrom)
chrom.size=chr.size$size[chr.mtch]
# obtain gene sizes, lesion sizes, and gene hit probabilities
lsn.size=hit.cnt$lsn.data$loc.end[lsn.rows]-hit.cnt$lsn.data$loc.start[lsn.rows]+1
gene.size=hit.cnt$gene.data$loc.end[gene.rows]-hit.cnt$gene.data$loc.start[gene.rows]+1
log.pr=log(rep(lsn.size,each=n.genes)+rep(gene.size,times=n.lsns))-log(chrom.size)
pr.gene.hit=matrix(exp(log.pr),n.genes,n.lsns)
pr.gene.hit[pr.gene.hit>1]=1
lsn.subj.IDs=hit.cnt$lsn.data$ID[lsn.rows]
pr.subj=row.prob.subj.hit(pr.gene.hit,lsn.subj.IDs)
max.nsubj=max(hit.cnt$nsubj.mtx[gene.rows,lsn.type])
max.nhit=max(hit.cnt$nhit.mtx[gene.rows,lsn.type])
pr.nhit=row.bern.conv(pr.gene.hit,max.nhit)
pr.nsubj=row.bern.conv(pr.subj,max.nsubj)
for (j in 1:n.genes)
{
nsubj=hit.cnt$nsubj.mtx[gene.rows[j],lsn.type]
nhit=hit.cnt$nhit.mtx[gene.rows[j],lsn.type]
p.nsubj[gene.rows[j],lsn.type]=sum(pr.nsubj[j,(nsubj+1):(max.nsubj+1)])
p.nhit[gene.rows[j],lsn.type]=sum(pr.nhit[j,(nhit+1):(max.nhit+1)])
}
}
rownames(p.nhit)=rownames(hit.cnt$nhit.mtx)
rownames(p.nsubj)=rownames(hit.cnt$nsubj.mtx)
colnames(hit.cnt$nhit.mtx)=paste0("nhit.",colnames(hit.cnt$nhit.mtx))
colnames(hit.cnt$nsubj.mtx)=paste0("nsubj.",colnames(hit.cnt$nsubj.mtx))
colnames(p.nhit)=paste0("p.",colnames(hit.cnt$nhit.mtx))
colnames(p.nsubj)=paste0("p.",colnames(hit.cnt$nsubj.mtx))
# Compute q-values
message(paste0("Computing q-values: ",date()))
q.nhit=p.nhit
q.nsubj=p.nsubj
for (i in 1:ncol(q.nhit))
{
pi.hat=min(1,2*mean(p.nhit[,i],na.rm=T))
q.nhit[,i]=pi.hat*p.adjust(p.nhit[,i],method="fdr")
pi.hat=min(1,2*mean(p.nsubj[,i],na.rm=T))
q.nsubj[,i]=pi.hat*p.adjust(p.nsubj[,i],method="fdr")
}
colnames(q.nhit)=paste0("q.",colnames(hit.cnt$nhit.mtx))
colnames(q.nsubj)=paste0("q.",colnames(hit.cnt$nsubj.mtx))
# Now get ordered p-values
message(paste0("Computing p-values for number of lesion types affecting genes: ",date()))
p.ord.nhit=p.order(p.nhit)
colnames(p.ord.nhit)=paste0("p",1:ncol(p.nhit),".nhit")
p.ord.nsubj=p.order(p.nsubj)
colnames(p.ord.nsubj)=paste0("p",1:ncol(p.nsubj),".nsubj")
# q-values of ordered p-values
q.ord.nhit=p.ord.nhit
q.ord.nsubj=p.ord.nsubj
message(paste0("Computing q-values for number of lesion types affecting genes: ",date()))
for (i in 1:ncol(p.ord.nhit))
{
pi.hat=min(1,2*mean(p.ord.nhit[,i],na.rm=T))
q.ord.nhit[,i]=pi.hat*p.adjust(p.ord.nhit[,i],method="fdr")
pi.hat=min(1,2*mean(p.ord.nsubj[,i],na.rm=T))
q.ord.nsubj[,i]=pi.hat*p.adjust(p.ord.nsubj[,i],method="fdr")
}
colnames(q.ord.nsubj)=paste0("q",1:ncol(p.nsubj),".nsubj")
colnames(q.ord.nhit)=paste0("q",1:ncol(p.nhit),".nhit")
gd.clms=setdiff(colnames(hit.cnt$gene.data),c("glp.row.start","glp.row.end"))
lsn.clms=setdiff(colnames(hit.cnt$lsn.data),c("glp.row.start","glp.row.end"))
gd.clms=c("gene.row",setdiff(gd.clms,"gene.row"))
lsn.clms=c("lsn.row",setdiff(lsn.clms,"lsn.row"))
gene.res=cbind.data.frame(hit.cnt$gene.data[,gd.clms],
hit.cnt$nsubj.mtx,
p.nsubj,
q.nsubj,
p.ord.nsubj,
q.ord.nsubj,
hit.cnt$nhit.mtx,
p.nhit,
q.nhit,
p.ord.nhit,
q.ord.nhit)
res=list(gene.hits=gene.res,
lsn.data=hit.cnt$lsn.data[,lsn.clms],
gene.data=hit.cnt$gene.data[,gd.clms],
gene.lsn.data=hit.cnt$gene.lsn.data,
chr.size=chr.size,
gene.index=hit.cnt$gene.index,
lsn.index=hit.cnt$lsn.index)
return(res)
}
###########################################
# Prepare gene and lesion data for later computations
prep.gene.lsn.data=function(lsn.data, # lesion data: ID, chrom, loc.start, loc.end, lsn.type
gene.data, # gene locus data: gene, chrom, loc.start, loc.end
mess.freq=10) # message frequency: display message every mess.freq^{th} lesion block
{
saf=options()$stringsAsFactors
options(stringsAsFactors=F)
# order lesion data by type, chromosome, and subject
lsn.dset=order.index.lsn.data(lsn.data)
lsn.data=lsn.dset$lsn.data
lsn.index=lsn.dset$lsn.index
# order and index gene locus data by chromosome and position
gene.dset=order.index.gene.data(gene.data)
gene.data=gene.dset$gene.data
gene.index=gene.dset$gene.index
# Extract some basic information
g=nrow(gene.data) # number of genes
l=nrow(lsn.data) # number of lesions
# Create gene position data
message(paste0("Formatting gene position data for counting: ",date()))
gene.pos.data=rbind.data.frame(cbind.data.frame(ID="", # gene start data
lsn.type="",
lsn.row=NA,
gene=gene.data[,"gene"],
gene.row=gene.data[,"gene.row"],
chrom=gene.data[,"chrom"],
pos=gene.data[,"loc.start"],
cty=1),
cbind.data.frame(ID="", # gene end data
lsn.type="",
lsn.row=NA,
gene=gene.data[,"gene"],
gene.row=gene.data[,"gene.row"],
chrom=gene.data[,"chrom"],
pos=gene.data[,"loc.end"],
cty=4)
)
# order gene position data
ord=order(gene.pos.data[,"chrom"],
gene.pos.data[,"pos"],
gene.pos.data[,"cty"])
gene.pos.data=gene.pos.data[ord,]
# Create lesion position data with one row for each edge of each lesion
message(paste0("Formatting lesion position data for counting: ",date()))
lsn.pos.data=rbind.data.frame(cbind.data.frame(ID=lsn.data[,"ID"],
lsn.type=lsn.data[,"lsn.type"],
lsn.row=lsn.data[,"lsn.row"],
gene="",
gene.row=NA,
chrom=lsn.data[,"chrom"],
pos=lsn.data[,"loc.start"],
cty=2),
cbind.data.frame(ID=lsn.data[,"ID"],
lsn.type=lsn.data[,"lsn.type"],
lsn.row=lsn.data[,"lsn.row"],
gene="",
gene.row=NA,
chrom=lsn.data[,"chrom"],
pos=lsn.data[,"loc.end"],
cty=3))
# order lesion position data
ord=order(lsn.pos.data[,"chrom"],
lsn.pos.data[,"pos"],
lsn.pos.data[,"cty"])
lsn.pos.data=lsn.pos.data[ord,]
# Combine gene & lesion data
message(paste0("Combining formatted gene and lesion postion data: ",date()))
gene.lsn.data=rbind.data.frame(gene.pos.data,
lsn.pos.data)
# Order and index gene & lesion data
ord=order(gene.lsn.data[,"chrom"],
gene.lsn.data[,"pos"],
gene.lsn.data[,"cty"])
gene.lsn.data=gene.lsn.data[ord,]
m=nrow(gene.lsn.data)
gene.lsn.data[,"glp.row"]=1:m
# compute vector to order gene.lsn.data by lsn.row and gene.row
ord=order(gene.lsn.data[,"lsn.row"],
gene.lsn.data[,"gene.row"],
gene.lsn.data[,"cty"])
# use that vector to add gene.lsn.data row.start and row.end indices to lsn.data
lsn.pos=gene.lsn.data[ord[1:(2*l)],]
lsn.data[,"glp.row.start"]=lsn.pos[2*(1:l)-1,"glp.row"]
lsn.data[,"glp.row.end"]=lsn.pos[2*(1:l),"glp.row"]
# use that vector to add gene.lsn.data row.start and row.end indices to gene.data
gene.pos=gene.lsn.data[ord[-(1:(2*l))],]
gene.data[,"glp.row.start"]=gene.pos[2*(1:g)-1,"glp.row"]
gene.data[,"glp.row.end"]=gene.pos[2*(1:g),"glp.row"]
# Double-check table pointers from lsn.data and gene.data to gene.lsn.data
message(paste0("Verifying structure of combined gene and lesion data: ",date()))
glp.gene.start=gene.lsn.data[gene.data$glp.row.start,c("gene","chrom","pos")]
colnames(glp.gene.start)=c("gene","chrom","loc.start")
ok.glp.gene.start=all(glp.gene.start==gene.data[,c("gene","chrom","loc.start")])
glp.gene.end=gene.lsn.data[gene.data$glp.row.end,c("gene","chrom","pos")]
colnames(glp.gene.end)=c("gene","chrom","loc.end")
ok.glp.gene.end=all(glp.gene.end==gene.data[,c("gene","chrom","loc.end")])
glp.lsn.start=gene.lsn.data[lsn.data$glp.row.start,c("ID","chrom","pos","lsn.type")]
colnames(glp.lsn.start)=c("ID","chrom","loc.start","lsn.type")
ok.glp.lsn.start=all(glp.lsn.start==lsn.data[,c("ID","chrom","loc.start","lsn.type")])
glp.lsn.end=gene.lsn.data[lsn.data$glp.row.end,c("ID","chrom","pos","lsn.type")]
colnames(glp.lsn.end)=c("ID","chrom","loc.end","lsn.type")
ok.glp.lsn.end=all(glp.lsn.end==lsn.data[,c("ID","chrom","loc.end","lsn.type")])
# Double-check table pointers from gene.lsn.data to gene.data and lsn.data
glp.gene.start=gene.lsn.data[gene.lsn.data$cty==1,c("gene.row","gene","chrom","pos")]
ok.gene.start=all(glp.gene.start[,c("gene","chrom","pos")]==gene.data[glp.gene.start$gene.row,c("gene","chrom","loc.start")])
glp.gene.end=gene.lsn.data[gene.lsn.data$cty==4,c("gene.row","gene","chrom","pos")]
ok.gene.end=all(glp.gene.end[,c("gene","chrom","pos")]==gene.data[glp.gene.end$gene.row,c("gene","chrom","loc.end")])
glp.lsn.start=gene.lsn.data[gene.lsn.data$cty==2,c("lsn.row","ID","chrom","pos","lsn.type")]
ok.lsn.start=all(glp.lsn.start[,c("ID","chrom","pos","lsn.type")]==lsn.data[glp.lsn.start$lsn.row,c("ID","chrom","loc.start","lsn.type")])
glp.lsn.end=gene.lsn.data[gene.lsn.data$cty==3,c("lsn.row","ID","chrom","pos","lsn.type")]
ok.lsn.end=all(glp.lsn.end[,c("ID","chrom","pos","lsn.type")]==lsn.data[glp.lsn.end$lsn.row,c("ID","chrom","loc.end","lsn.type")])
all.ok=all(c(ok.glp.gene.start,ok.glp.gene.end,
ok.glp.lsn.start,ok.glp.lsn.end,
ok.gene.start,ok.gene.end,
ok.lsn.start,ok.lsn.end))
if (!all.ok)
stop("Error in constructing and indexing combined lesion and gene data.")
message(paste0("Verified correct construction and indexing of combined lesion and gene data: ",date()))
return(list(lsn.data=lsn.data,
gene.data=gene.data,
gene.lsn.data=gene.lsn.data,
gene.index=gene.index,
lsn.index=lsn.index))
}
#############################################
# Use the results of prep.gene.lsn.data to find lesion-gene overlaps
find.gene.lsn.overlaps=function(gl.data)
{
gene.data=gl.data$gene.data
lsn.data=gl.data$lsn.data
lsn.index=gl.data$lsn.index
gene.index=gl.data$gene.index
gene.lsn.data=gl.data$gene.lsn.data
m=nrow(gene.lsn.data)
message(paste0("Scanning through combined lesion and gene data to find gene-lesion overlaps: ",date()))
gene.row.mtch=NULL # initialize vector for rows of gene data matched to rows of lesion data
lsn.row.mtch=NULL # initialize vector for rows of lesion data matched to rows of gene data
current.genes=NULL # initialize vector of genes overlapping this point of the scan
current.lsns=NULL # initialize vector of lesions overlapping this point of the scan
for (i in 1:m) # loop over rows of gene.lsn.data
{
# enter a gene
if (gene.lsn.data$cty[i]==1)
{
# add this gene to the set of current genes
current.genes=c(current.genes,
gene.lsn.data$gene.row[i])
# match this gene to set of current lesions
lsn.row.mtch=c(lsn.row.mtch,current.lsns) # add current lesions to lsn.row.mtch
gene.row.mtch=c(gene.row.mtch, # add this gene for each current lesion
rep(gene.lsn.data$gene.row[i],
length(current.lsns)))
}
# exit a gene
if (gene.lsn.data$cty[i]==4)
{
# drop this gene from the set of current genes
current.genes=setdiff(current.genes,
gene.lsn.data$gene.row[i])
}
if (gene.lsn.data$cty[i]==2) # enter a lesion
{
lsn.row.mtch=c(lsn.row.mtch,
rep(gene.lsn.data$lsn.row[i],length(current.genes)))
gene.row.mtch=c(gene.row.mtch,current.genes)
current.lsns=c(current.lsns,
gene.lsn.data$lsn.row[i])
}
if (gene.lsn.data$cty[i]==3)
{
current.lsns=setdiff(current.lsns,
gene.lsn.data$lsn.row[i])
}
}
message(paste0("Completed scan of combined gene-lesion data: ",date()))
# Generate the gene-lesion hit data
gene.lsn.hits=cbind.data.frame(gene.data[gene.row.mtch,
c("gene.row","gene","chrom","loc.start","loc.end")],
lsn.data[lsn.row.mtch,
c("lsn.row","ID","chrom","loc.start","loc.end","lsn.type")])
colnames(gene.lsn.hits)=c("gene.row","gene","gene.chrom","gene.loc.start","gene.loc.end",
"lsn.row","ID","lsn.chrom","lsn.loc.start","lsn.loc.end","lsn.type")
res=list(lsn.data=lsn.data,
gene.data=gene.data,
gene.lsn.data=gene.lsn.data,
gene.lsn.hits=gene.lsn.hits,
gene.index=gene.index,
lsn.index=lsn.index)
return(res)
}
#####################################################
# Count hits
count.hits=function(ov.data)
{
lsn.data=ov.data$lsn.data
lsn.index=ov.data$lsn.index
gene.lsn.hits=ov.data$gene.lsn.hits
gene.lsn.data=ov.data$gene.lsn.data
gene.data=ov.data$gene.data
gene.index=ov.data$gene.index
g=nrow(gene.data)
# Compute the number of hits matrix
lsn.types=sort(unique(lsn.index[,"lsn.type"]))
k=length(lsn.types)
nhit.mtx=matrix(0,g,k)
colnames(nhit.mtx)=lsn.types
nhit.tbl=table(gene.lsn.hits$gene.row,
gene.lsn.hits$lsn.type)
nhit.rows=as.numeric(rownames(nhit.tbl))
for (i in 1:ncol(nhit.tbl))
nhit.mtx[nhit.rows,colnames(nhit.tbl)[i]]=nhit.tbl[,i]
# Compute the matrix of the number of subjects with a hit
gene.subj.type=paste0(gene.lsn.hits$gene.row,"_",
gene.lsn.hits$ID,"_",
gene.lsn.hits$lsn.type)
dup.gene.subj.type=duplicated(gene.subj.type)
subj.gene.hits=gene.lsn.hits[!dup.gene.subj.type,]
nsubj.mtx=matrix(0,g,k)
colnames(nsubj.mtx)=lsn.types
nsubj.tbl=table(subj.gene.hits$gene.row,
subj.gene.hits$lsn.type)
nsubj.rows=as.numeric(rownames(nsubj.tbl))
for (i in 1:ncol(nsubj.tbl))
nsubj.mtx[nsubj.rows,colnames(nsubj.tbl)[i]]=nsubj.tbl[,i]
res=list(lsn.data=lsn.data,
lsn.index=lsn.index,
gene.data=gene.data,
gene.index=gene.index,
nhit.mtx=nhit.mtx,
nsubj.mtx=nsubj.mtx,
gene.lsn.data=gene.lsn.hits,
glp.data=gene.lsn.data)
return(res)
}
######################################
# Create a binary lesion hit matrix
prep.binary.lsn.mtx=function(overlap.data, # result of find.overlaps
min.ngrp=0) # omit rows with fewer than min.ngrp hit or fewer than min.ngrp not hit
{
gene.lsn=overlap.data$gene.lsn.hits
# Order and index data by gene and lesion type
gene.lsn.type=paste0(gene.lsn$gene,"_",gene.lsn$lsn.type)
ord=order(gene.lsn$gene,gene.lsn$lsn.type)
gene.lsn=gene.lsn[ord,]
m=nrow(gene.lsn)
new.gene.lsn=which((gene.lsn$gene[-1]!=gene.lsn$gene[-m])|
(gene.lsn$lsn.type[-1]!=gene.lsn$lsn.type[-m]))
row.start=c(1,new.gene.lsn+1)
row.end=c(new.gene.lsn,m)
gene.lsn.indx=gene.lsn$gene.lsn[row.start]
gene.lsn.index=cbind.data.frame(gene=gene.lsn$gene[row.start],
lsn.type=gene.lsn$lsn.type[row.start],
row.start=row.start,
row.end=row.end)
k=nrow(gene.lsn.index)
uniq.ID=unique(gene.lsn$ID)
n=length(uniq.ID)
gene.lsn.mtx=matrix(0,k,n)
colnames(gene.lsn.mtx)=as.character(uniq.ID)
rownames(gene.lsn.mtx)=paste0(gene.lsn.indx$gene,"_",
gene.lsn.index$lsn.type)
for (i in 1:k)
{
rows=(gene.lsn.index$row.start[i]:gene.lsn.index$row.end[i])
ids=as.character(gene.lsn$ID[rows])
gene.lsn.mtx[i,ids]=1
}
n.hit=rowSums(gene.lsn.mtx)
min.n=pmin(n.hit,n-n.hit)
keep.row=which(min.n>min.ngrp)
gene.lsn.mtx=matrix(gene.lsn.mtx[keep.row,],
length(keep.row),n)
colnames(gene.lsn.mtx)=as.character(uniq.ID)
rownames(gene.lsn.mtx)=paste0(gene.lsn.index$gene,"_",
gene.lsn.index$lsn.type)[keep.row]
return(gene.lsn.mtx)
}
######################################################
# prepare lesion type matrix
prep.lsn.type.matrix=function(overlap.data)
{
gene.lsn=overlap.data$gene.lsn.hits
# order and index gene-lesion overlaps by subject ID and gene
ord=order(gene.lsn$ID,
gene.lsn$gene)
gene.lsn=gene.lsn[ord,]
m=nrow(gene.lsn)
new.block=which((gene.lsn$ID[-1]!=gene.lsn$ID[-m])|
(gene.lsn$gene[-1]!=gene.lsn$gene[-m]))
row.start=c(1,new.block+1)
row.end=c(new.block,m)
ID.gene.index=cbind.data.frame(ID=gene.lsn$ID[row.start],
gene=gene.lsn$gene[row.start],
row.start=row.start,
row.end=row.end)
# initialize the result matrix
lsn.types=sort(unique(gene.lsn$lsn.type))
uniq.genes=unique(ID.gene.index$gene)
uniq.IDs=unique(ID.gene.index$ID)
grp.mtx=matrix("none",
length(uniq.genes),
length(uniq.IDs))
rownames(grp.mtx)=uniq.genes
colnames(grp.mtx)=uniq.IDs
# fill in the matrix
n.index=nrow(ID.gene.index)
for (i in 1:n.index)
{
gene.lsn.rows=(ID.gene.index$row.start[i]:ID.gene.index$row.end[i])
block.ID=ID.gene.index$ID[i]
block.gene=ID.gene.index$gene[i]
block.lsns=gene.lsn$lsn.type[gene.lsn.rows]
block.lsns=unique(block.lsns)
if (length(block.lsns)==1) grp.mtx[block.gene,block.ID]=block.lsns
else grp.mtx[block.gene,block.ID]="multiple"
}
return(grp.mtx)
}
#######################################
# Write GRIN results to an xlsx file
write.grin.xlsx=function(grin.result,
output.file) # output of grin.stats
{
saf=options()$stringsAsFactors
options(stringsAsFactors = F)
rpt.res=grin.result[c("gene.hits",
"gene.lsn.data",
"lsn.data",
"gene.data",
"chr.size")]
################################
# Contents of the data sheets
sheet.int=cbind.data.frame(sheet.name=c("gene.hits",
"gene.lsn.data",
"lsn.data",
"gene.data",
"chr.size"),
col.name="entire sheet",
meaning=c("GRIN statistical results",
"gene-lesion overlaps",
"input lesion data",
"input gene location data",
"input chromosome size data"))
######################################
# Interpretation of gene hit stats
gh.cols=colnames(rpt.res[["gene.hits"]])
genehit.int=cbind.data.frame(sheet.name="gene.hits",
col.name=gh.cols,
meaning=gh.cols)
rownames(genehit.int)=gh.cols
rpt.clms=c("gene.row","gene","loc.start","loc.end")
rpt.defs=c("gene data row index",
"gene name",
"locus of left edge of gene",
"locus of right edge of gene")
rpt.indx=rep(NA,length(rpt.clms))
for (i in 1:length(rpt.clms))
rpt.indx[i]=which(genehit.int$col.name==rpt.clms[i])
genehit.int$meaning[rpt.indx]=rpt.defs
nsubj.clms=which(substring(gh.cols,1,5)=="nsubj")
genehit.int$meaning[nsubj.clms]=paste0("Number of subjects with a ",
substring(gh.cols[nsubj.clms],7)," lesion ",
genehit.int$meaning[nsubj.clms])
p.nsubj.clms=which(substring(gh.cols,1,7)=="p.nsubj")
genehit.int$meaning[p.nsubj.clms]=paste0("p-value for the number of subjects with a ",
substring(gh.cols[p.nsubj.clms],9)," lesion ",
genehit.int$meaning[p.nsubj.clms])
q.nsubj.clms=which(substring(gh.cols,1,7)=="q.nsubj")
genehit.int$meaning[q.nsubj.clms]=paste0("FDR estimate for the number of subjects with a ",
substring(gh.cols[q.nsubj.clms],9)," lesion ",
genehit.int$meaning[q.nsubj.clms])
nhit.clms=which(substring(gh.cols,1,4)=="nhit")
genehit.int$meaning[nhit.clms]=paste0("Number of ",
substring(gh.cols[nhit.clms],6)," lesions ",
genehit.int$meaning[nhit.clms])
p.nhit.clms=which(substring(gh.cols,1,6)=="p.nhit")
genehit.int$meaning[p.nhit.clms]=paste0("p-value for the number of ",
substring(gh.cols[p.nhit.clms],8)," lesions ",
genehit.int$meaning[p.nhit.clms])
q.nhit.clms=which(substring(gh.cols,1,6)=="q.nhit")
genehit.int$meaning[q.nhit.clms]=paste0("FDR estimate for the number of ",
substring(gh.cols[q.nhit.clms],8)," lesions ",
genehit.int$meaning[q.nhit.clms])
p1.nsubj.clms=paste0("p",1:length(nsubj.clms),".nsubj")
genehit.int[p1.nsubj.clms,"meaning"]=paste0("p-value for the number of subjects ",
"with any ",1:length(nsubj.clms)," type(s) of lesion ",
"overlapping the gene locus")
q1.nsubj.clms=paste0("q",1:length(nsubj.clms),".nsubj")
genehit.int[q1.nsubj.clms,"meaning"]=paste0("FDR estimate for the number of subjects ",
"with any ",1:length(nsubj.clms)," type(s) of lesion ",
"overlapping the gene locus")
p1.nhit.clms=paste0("p",1:length(nhit.clms),".nhit")
genehit.int[p1.nhit.clms,"meaning"]=paste0("p-value for the number of ",
"any ",1:length(nhit.clms)," type(s) of lesion ",
"overlapping the gene locus")
q1.nhit.clms=paste0("q",1:length(nhit.clms),".nhit")
genehit.int[q1.nhit.clms,"meaning"]=paste0("FDR estimate for the number of",
" any ",1:length(nhit.clms)," type(s) of lesion ",
"overlapping the gene locus")
#######################################
# Lesion data interpretation
lsn.clms=colnames(rpt.res[["lsn.data"]])
lsn.int=cbind.data.frame(sheet.name="lsn.data",
col.name=lsn.clms,
meaning=lsn.clms)
rpt.clms=c("ID","chrom","loc.start","loc.end","lsn.type")
int.clms=c(which(lsn.int[,"col.name"]=="ID"),
which(lsn.int[,"col.name"]=="chrom"),
which(lsn.int[,"col.name"]=="loc.start"),
which(lsn.int[,"col.name"]=="loc.end"),
which(lsn.int[,"col.name"]=="lsn.type"))
lsn.int[int.clms,"meaning"]=c("Input Subject Identifier",
"Input Chromosome",
"Input Gene Locus Left Edge",
"Input Gene Locus Right Edge",
"Input Lesion Type")