-
Notifications
You must be signed in to change notification settings - Fork 0
/
patch_gtrack.R
2003 lines (1628 loc) · 89.2 KB
/
patch_gtrack.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
'plot.gTrack' = function(x, ##pplot (for easy search)
y,
windows = si2gr(seqinfo(x)), ## windows to plot can be Granges or GRangesList
links = NULL, ## GRangesList of pairs of signed locations,
gap = NULL, ## spacing betwen windows (in bp)
y.heights = NULL, # should be scalar or length(windows) if windows is a GRangesList
y.gaps = NULL, # relative heights of gaps below and above stacks (xaxes will be drawn here)
cex.xlabel = 1,
cex.ylabel = 1,
max.ranges = NA, # parameter for max ranges to draw on canvas in each track (overrides formatting)
links.feat = NULL, # links features override for links (must be nrow 1 or length(links) data frame
verbose=FALSE,
legend.params = list(),
... ## additional args to draw.grl OR last minute formatting changes to gTrack object
) {
if (!missing(y))
windows = y
.Object = x
if (!missing(y))
windows = y
if (is(windows, 'numeric') | is(windows, 'integer'))
windows = as.character(windows)
if (is(windows, 'character'))
windows = unlist(parse.grl(windows, seqlengths(seqinfo(.Object))))
## make sure we have min legend data
if (!"xpos" %in% names(legend.params))
legend.params$xpos = 0
if (!"ypos" %in% names(legend.params))
legend.params$ypos = 1
if (!"plot" %in% names(legend.params))
legend.params$plot = TRUE
win.gap = gap ## PATCH: recasting some variable names
new.plot = TRUE
window.segs = list();
dotdot.args = list(...);
## parse the wind<ows into GRanges
windows = format_windows(windows, .Object)
windows = windows[width(windows)>0]
## if totally empty, plot blank and leave
if(!length(windows)) {
plot.blank(bg.col = bg.col)
return()
}
## make sure gTrack has all fields that are expected later
.Object <- prep_defaults_for_plotting(.Object)
if (length(dotdot.args)>0) {
format_name <- which(names(dotdot.args) == "name")
if (length(format_name) > 0) {
formatting(.Object)[, format_name] = dotdot.args[[format_name]]
}
}
if (is.null(formatting(.Object)$legend))
formatting(.Object)$legend = TRUE
else (any(is.na(formatting(.Object)$legend)))
formatting(.Object)$legend[is.na(formatting(.Object)$legend)] = TRUE
if (is.null(formatting(.Object)$legend.title))
formatting(.Object)$legend.title = NA
## name vs track.name saga
if (is.null(formatting(.Object)$track.name))
{
if (!is.null(formatting(.Object)$name))
formatting(.Object)$track.name = formatting(.Object)$name
else if (!is.null(formatting(.Object)$y.field))
formatting(.Object)$track.name = formatting(.Object)$y.field
else
formatting(.Object)$track.name = NA
}
has.colormap = sapply(colormap(.Object), length)>0
has.colorfield = !is.na(formatting(.Object)$gr.colorfield)
formatting(.Object)$legend = ifelse(is.na(formatting(.Object)$legend), formatting(.Object)$legend == TRUE & (has.colormap | has.colorfield), formatting(.Object)$legend)
numlegends = sum(formatting(.Object)$legend)
which.legend = which(formatting(.Object)$legend)
.Object$legend.title = ifelse(!is.na(.Object$legend.title), .Object$legend.title,
ifelse(has.colormap, names(colormap(.Object))[1:length(.Object)],
ifelse(has.colorfield, .Object$gr.colorfield,
ifelse(!is.na(.Object$track.name), .Object$track.name, ''))))
## add last minute formatting changes to gTrack
if (length(dotdot.args)>0)
for (f in intersect(names(dotdot.args), names(formatting(.Object))))
formatting(.Object)[, f] = dotdot.args[[f]]
## set the window gap .. so that windows don't collide
if (is.null(win.gap))
win.gap = sum(as.numeric(width(windows)))/30
## get the height of the stacks
if (is.null(y.heights) | length(y.heights) != length(windows))
##y.heights = rep(1, length(windows)) ## old from when we had windows as GRangesList
y.heights <- 1
## set the gaps between the gTracks
if (is.null(y.gaps) )
y.gaps = y.heights*0.8
else if (length(y.gaps) != length(windows))
y.gaps = rep(y.gaps[1], length(windows))
## ensure that we don't plot too much
if (!is.na(max.ranges))
formatting(.Object)$max.ranges = pmin(max.ranges, formatting(.Object)$max.ranges, na.rm = TRUE)
oth.ix = 1:(length(windows)-1);
top.gaps = 0.5*y.gaps
bottom.gaps = 0.5*y.gaps
if (length(windows)==1)
oth.ix = c()
ylim.stacks = data.frame(start = c(bottom.gaps[1], bottom.gaps[1] + cumsum(y.heights[oth.ix] + top.gaps[oth.ix] + bottom.gaps[oth.ix+1])),
end = cumsum(y.heights + top.gaps + bottom.gaps) - top.gaps)
oth.ix = 1:(length(.Object)-1);
if (length(.Object)==1)
oth.ix = c()
tmp.top.gaps = 0.5 * formatting(.Object)$ygap
tmp.bottom.gaps = 0.5 * formatting(.Object)$ygap
tmp.ylim.subplot = data.frame(start = c(tmp.bottom.gaps[1], tmp.bottom.gaps[1] +
cumsum(formatting(.Object)$height[oth.ix] + tmp.top.gaps[oth.ix] + tmp.bottom.gaps[oth.ix+1])),
end = cumsum(formatting(.Object)$height + tmp.top.gaps + tmp.bottom.gaps) - tmp.top.gaps)
ylim = c(0, max(ylim.stacks$end)+top.gaps[length(top.gaps)])
ylim.parent=ylim
window.ylims = data.frame(start = rep(NA, length(windows)), end = NA);
new.axis = TRUE;
this.windows = windows
#end(this.windows) <- end(this.windows) + 1 ## +1 added
#this.windows = gUtils::streduce(windows[[i]]) ##gr.stripstrand(GenomicRanges::trim(windows[[i]]))
##if (!inherits(this.windows, 'GRanges'))
## this.windows = gUtils::si2gr(this.windows)
i=1
this.ylim.subplot = tmp.ylim.subplot;
this.ylim.subplot$start = affine.map(pmin(1, this.ylim.subplot$start), ylim = unlist(ylim.stacks[i, c('start', 'end')]), xlim = c(0, 1))
this.ylim.subplot$end = affine.map(pmin(1, this.ylim.subplot$end), ylim = unlist(ylim.stacks[i, c('start', 'end')]), xlim = c(0, 1))
this.tmp.bottom.gap = tmp.bottom.gaps[1]*(ylim.stacks$end[i]-ylim.stacks$start[i])
this.xaxis.pos = this.ylim.subplot$start[1]-bottom.gaps[i]*0-this.tmp.bottom.gap
this.xaxis.pos.label = this.ylim.subplot$start[1]-5*bottom.gaps[i]/6-this.tmp.bottom.gap
ylim.stacks[i, 'xaxis.pos'] = this.xaxis.pos
## loop through the gTracks
for (j in 1:length(.Object))
{
par(xpd = NA);
cmap = colormap(.Object)[[j]];
cfield = names(colormap(.Object))[j]
if (is.na(cfield))
cfield = formatting(.Object)$gr.colorfield[j]
if (length(cmap)==0)
cmap = NA
## get the data into GRanges or GRangesList format
pre.filtered = FALSE;
if (.Object@formatting$triangle[j])
pre.filtered = TRUE
tt <- extract_data_from_tmp_dat(.Object, j, this.windows)
.Object = tt$o
tmp.dat = tt$t
this.windows = tt$w
## subsample if we need to for enforcing max.ranges
if (!is.na(formatting(.Object)$max.ranges[j]) && formatting(.Object)$max.ranges[j] > 0) {
tt <- enforce_max_ranges(.Object, pre.filtered, j, tmp.dat, this.windows)
tmp.dat = tt$t
pre.filtered = tt$p
}
## flag to tell us whether data is pre-filtered to window (ie in fftrack or rlelist)
## adjust y0 .bar
if (is.null((formatting(.Object)$y0.bar[j])) || is.na((formatting(.Object)$y0.bar[j])))
formatting(.Object)$y0.bar[j] = NA
## smooth the y.field data
if (!is.na(formatting(.Object)$y.field[j]) && is(tmp.dat, 'GRanges') && !is.na(formatting(.Object)$smooth[j]))
tmp.dat <- smooth_yfield(.Object, j, tmp.dat)
## fix y limits and apply log transform if needed
if (!is.na(formatting(.Object)$y.field[j]) && (is.na(formatting(.Object)$y0[j]) || is.na(formatting(.Object)$y1[j])))
.Object <- format_yfield_limits(.Object, j, tmp.dat, pre.filtered, this.windows)
# if (formatting(.Object[j])$format != 'ranges')
# stop("violated assumption. need to fix")
all.args = as.list(formatting(.Object[j]))
all.args = c(dotdot.args, all.args[!names(all.args) %in% names(dotdot.args)])
# all.args = list(
# col = formatting(.Object)$col[j],
# ywid = formatting(.Object)$ywid[j],
# border = formatting(.Object)$border[j],
# lwd.border = formatting(.Object)$lwd.border[j],
# adj.label = c(formatting(.Object)$hadj.label[j],
# formatting(.Object)$vadj.label[j]),
# gr.adj.label = c(0.5,
# formatting(.Object)$vadj.label[j]),
# angle = formatting(.Object)$angle[j],
# y.pad = formatting(.Object)$ypad[j],
# circles = formatting(.Object)$circles[j],
# lines = formatting(.Object)$lines[j],
# bars = formatting(.Object)$bars[j],
# y.grid.cex = formatting(.Object)$yaxis.cex[j],
# edges = edgs(.Object)[[j]],
# y0.bar = formatting(.Object)$y0.bar[j],
# stack.gap = formatting(.Object)$stack.gap[j])
# na.fields = names(formatting(.Object))[sapply(1:ncol(formatting(.Object)), function(field) is.na(formatting(.Object)[j, field]))]
# other.fields = setdiff(names(formatting(.Object)), c('name', 'height', 'ygap', 'stack.gap', 'lift', 'split', 'angle', 'format', 'lwd.border', 'source.file', 'source.file.chrsub', 'ypad', 'ywid', 'border', 'col', 'hadj.label', 'vadj.label', 'y.field', 'round', 'cex.ylabel', 'y.quantile', 'max.ranges', 'yaxis', 'yaxis.cex', 'is.null', 'yaxis.pretty', names(all.args))) ## remove na fields and anything else that might mess up draw.grl
#
# other.formats = structure(names = other.fields,
# lapply(other.fields, function(x) formatting(.Object)[j, x]))
# all.args[names(other.formats)] = other.formats;
#
# all.args = all.args[setdiff(names(all.args), setdiff(na.fields, c('col')))]
this.y.field = formatting(.Object)$y.field[j]
this.y.grid = NA;
if (is.na(this.y.field) | !(this.y.field %in% names(values(tmp.dat))))
this.y = this.ylim.subplot[j, ]
else
{
if (is.null(formatting(.Object)$log))
formatting(.Object)$log = NA
if (!is.na(formatting(.Object)$log[j]))
if (formatting(.Object)$log[j])
{
if (!is.null(tmp.dat$ywid))
tmp.dat$ywid = log10(tmp.dat$ywid)
values(tmp.dat)[, this.y.field] = log10(values(tmp.dat)[, this.y.field])
formatting(.Object)[j, 'y0'] = log10(formatting(.Object)[j, 'y0'])
formatting(.Object)[j, 'y1'] = log10(formatting(.Object)[j, 'y1'])
}
range.y = NULL;
if (all(c('y0', 'y1') %in% names(formatting(.Object))))
{
if (!is.na(formatting(.Object)[j, 'y0']) & !is.na(formatting(.Object)[j, 'y1']))
range.y = c(formatting(.Object)[j, 'y0'], formatting(.Object)[j, 'y1'])
else if (!is.na(formatting(.Object)[j, 'y0']) & is.na(formatting(.Object)[j, 'y1']))
range.y = c(formatting(.Object)[j, 'y0'], max(setdiff(values(tmp.dat)[, this.y.field], c(Inf, -Inf)), na.rm = T))
else if (is.na(formatting(.Object)[j, 'y0']) & !is.na(formatting(.Object)[j, 'y1']))
range.y = c(min(setdiff(values(tmp.dat)[, this.y.field], c(Inf, -Inf)), na.rm = T), formatting(.Object)[j, 'y1'])
}
if (length(tmp.dat)>0)
{
if (!is.null(tmp.dat$ywid)) ## remove any weird infinite ywids
{
if (any(ix <- is.infinite(values(tmp.dat)$ywid)))
values(tmp.dat)$ywid[ix] = NA
}
else
values(tmp.dat)$ywid = NA
if (is.null(range.y)) ## if y range is empty then pull from data
range.y = range(setdiff(values(tmp.dat)[, this.y.field], c(Inf, -Inf)), na.rm = T);
# range.y = range(setdiff(values(dat(.Object)[[j]])[, this.y.field], c(Inf, -Inf)), na.rm = T);
}
## however if there is a single data value, then we need to scale appropriately
if (diff(range.y)==0)
{
if (any(ix <- !is.na(values(tmp.dat)$ywid))) ## use ywid
range.y = range.y + 5*max(values(tmp.dat)$ywid[ix])*c(-1, 1)
else # otherwise use some arbitrary proportion around the value
range.y = range.y + abs(range.y)*0.2*c(-1, 1)
}
this.y.ticks = pretty(range.y, formatting(.Object)$yaxis.pretty[j])
if (is.null(formatting(.Object)$y.cap))
formatting(.Object)$y.cap = NA
if (!is.na(formatting(.Object)$y.cap[j])) ## cap values from top and bottom
this.y = affine.map(values(tmp.dat)[, this.y.field], ylim = unlist(this.ylim.subplot[j, ]), xlim = range(this.y.ticks), cap = formatting(.Object)$y.cap[j])
else
this.y = affine.map(values(tmp.dat)[, this.y.field], ylim = unlist(this.ylim.subplot[j, ]), xlim = range(this.y.ticks), cap = TRUE)
# this.y = affine.map(values(dat(.Object)[[j]])[, this.y.field], ylim = unlist(this.ylim.subplot[j, ]), xlim = range(this.y.ticks))
## if need, bump the range to include ybar base
# if (formatting(.Object)$y0.bar[j] < min(unlist(this.ylim.subplot[j, ])))
# this.ylim.subplot[j,'start'] <- formatting(.Object)$y0.bar[j]
if (is.na(formatting(.Object)$y0.bar[j]))
formatting(.Object)$y0.bar[j] = 0
all.args$y0.bar = affine.map(formatting(.Object)$y0.bar[j], ylim = unlist(this.ylim.subplot[j, ]), xlim = range(this.y.ticks))
if (formatting(.Object)$yaxis[j])
{
# make pretty grid in range.y
this.y.grid = structure(affine.map(this.y.ticks, ylim = unlist(this.ylim.subplot[j, ]), xlim = range(this.y.ticks)), names = this.y.ticks)
if (!is.na(formatting(.Object)$log[j]))
if (formatting(.Object)$log[j])
names(this.y.grid) = signif(10^this.y.ticks)
}
}
if (is.null(.Object[j]$bars))
formatting(.Object)$bars[j] = FALSE
else if (is.na(.Object[j]$bars))
formatting(.Object)$bars[j] = FALSE
if (.Object[j]$bars && is.na(all.args$y0.bar))
all.args$y0.bar = this.ylim.subplot[j, 1]
if (is.null(.Object$chr.sub))
.Object$chr.sub = FALSE
if (is.na(.Object$chr.sub[j]))
.Object$chr.sub[j] = FALSE
if (.Object[j]$chr.sub)
tmp.windows = gr.sub(windows, 'chr', '')
else
tmp.windows = this.windows
## fix legend params
this.legend.params = legend.params
if (!formatting(.Object)$legend[j])
this.legend.params$plot = FALSE
else
{
this.legend.params$xpos = NA
if (!is.null(formatting(.Object)$legend.xpos))
this.legend.params$xpos = is.formatting(.Object)$legend.xpos[j]
if (!is.null(formatting(.Object)$legend.ypos))
this.legend.params$ypos = formatting(.Object)$legend.ypos[j]
jj = match(j, which.legend)
if (is.na(this.legend.params$xpos))
this.legend.params$xpos = seq(0, 1, length.out = numlegends)[jj]
this.legend.params$xpos = seq(0, 1, length.out = numlegends)[jj]
this.legend.params$xjust = c(0, 0.5, 1)[as.integer(cut(this.legend.params$xpos, c(-0.01, 0.2, 0.8, 1)))]
this.legend.params$title = .Object$legend.title[j]
}
## remove field "y" from tmp.dat if it exists
if (is(tmp.dat, 'GRangesList'))
{
values(tmp.dat)$y = NULL
}
else
{
if (!is.null(tmp.dat$y))
tmp.dat$y = NULL
}
main.args <- list(grl=tmp.dat,y = this.y, ylim = ylim,
xaxis.pos = this.xaxis.pos,xaxis.pos.label = this.xaxis.pos.label,
win.gap = win.gap[i],windows = tmp.windows,
new.plot = new.plot, new.axis = new.axis,
gr.colorfield = cfield,gr.colormap = cmap,
legend = formatting(.Object)$legend[j],
y.grid = this.y.grid, verbose=verbose,
ylim.parent=ylim.parent,mdata=.Object@mdata[[j]],
leg.params = this.legend.params,
adj.label = c(formatting(.Object)$hadj.label[j],
formatting(.Object)$vadj.label[j]),
gr.adj.label = c(0.5,
formatting(.Object)$vadj.label[j]),
y.pad = formatting(.Object)$ypad[j],
y.grid.cex = formatting(.Object)$yaxis.cex[j],
edges = edgs(.Object)[[j]])
all.args <- c(main.args, all.args[!names(all.args) %in% names(main.args)])
## clear out na.args to make default setting simpler downstream
na.args = sapply(all.args, function(x) if(is.vector(x)) all(is.na(x)) else FALSE)
if (any(na.args))
all.args = all.args[!na.args]
# main.args = c(main.args, all.args[setdiff(names(all.args), names(main.args))]);
#
# other.args = dotdot.args
# other.args = other.args[setdiff(names(other.args), names(main.args))]
## make empty plot
if (new.plot)
{
blank.main.args <- all.args
###blank.main.args = main.args;
###blank.main.args[[1]] = blank.main.args[[1]][c()]
#blank.main.args$y = list(start = min(this.ylim.subplot$start), end = max(this.ylim.subplot$end))
# if (any(is.na(.Object@formatting$triangle)) & any(.Object@formatting$triangle))
# blank.main.args$y = list(start = min(this.ylim.subplot$start[is.na(.Object@formatting$triangle)]), end = max(this.ylim.subplot$end[is.na(.Object@formatting$triangle)])) ## JEREMIAH
# else
blank.main.args$grl <- GRanges()
blank.main.args$y = list(start=min(this.ylim.subplot$start), end = max(this.ylim.subplot$end))
blank.main.args$triangle=FALSE
blank.main.args$sep.draw=FALSE
do.call('draw.grl', blank.main.args)
##do.call('draw.grl', c(blank.main.args, other.args))
all.args$new.plot = FALSE
all.args$new.axis = FALSE
}
new.plot = FALSE
new.axis = FALSE
##arrg <- c(main.args, other.args)
##form <- as.list(formatting(.Object[j]))
##arrg <- c(arrg, form[!names(form) %in% names(arrg)]) ## add in remaining args
window.segs = list();
##window.segs[[i]] = do.call('draw.grl', c(main.args, other.args))
if (formatting(.Object[j])$triangle)
{
all.args$sigma= all.args$smooth
window.segs[[i]] <- do.call('draw.triangle', all.args[names(all.args) %in% c("grl","y","mdata","ylim.parent","windows","win.gap","sigma",
"cmap.min","cmap.max", "m.sep.lwd","m.bg.col","legend","leg.params",
"islog","gr.colormap")])
} else {
window.segs[[i]] <- do.call('draw.grl', all.args)
}
this.tname = formatting(.Object[j])$track.name
if (!is.na(this.tname))
{
ylab.las = if (is.null(dotdot.args[["ylab.las"]])) 0 else dotdot.args[["ylab.las"]]
ylab.adj = if (is.null(dotdot.args[["ylab.adj"]])) c(0.5, 1) else dotdot.args[["ylab.adj"]]
if (ylab.las %in% c(0,3)) {
ylab.angle = -90
} else if (ylab.las %in% c(1,2)) {
ylab.angle = 0
}
this.cex.ylabel = ifelse(!is.null(formatting(.Object[j])$cex.ylabel), formatting(.Object[j])$cex.ylabel, cex.ylabel)
text(par('usr')[2], mean(unlist(this.ylim.subplot[j, c('start', 'end')])),
this.tname, srt = ylab.angle, adj = ylab.adj, cex = this.cex.ylabel) ### ARG TO ROTATE
}
}
if (is.null(links))
links = GenomicRanges::GRangesList()
if (length(links)>0) # draw rearrangement links
{
# first map rearrangements to various windows>
win.u = this.windows
win.u$grl.ix = 1 ##holdover from grangeslist windows
##win.u = gr.stripstrand(grl.unlist(windows))
window.segs.u = do.call(rbind, window.segs)
window.segs.u$width = window.segs.u$end - window.segs.u$start + 1
window.segs.xlim = do.call('rbind', lapply(window.segs, function(x) data.frame(start = min(x$start), end = max(x$end))))
links.u = grl.unlist(links)
if (any(table(links.u$grl.ix)!=2))
stop('Links should be GRangesList of range pairs.')
links.p = grl.pivot(links)
## flip strands to conform to connectors convention (- connection to left side and + is connection to right side)
## with ra specification convention (- refers to segment to left of breakpoint and + refers to segment to right)
GenomicRanges::strand(links.p[[1]]) = c("-" = "+", "+" = "-")[as.character(GenomicRanges::strand(links.p[[1]]))]
GenomicRanges::strand(links.p[[2]]) = c("-" = "+", "+" = "-")[as.character(GenomicRanges::strand(links.p[[2]]))]
## find overlaps with windows and calculate their window specific coordinates
l1 = gr.findoverlaps(links.p[[1]], win.u)
values(l1) = cbind(as.data.frame(values(l1)), as.data.frame(values(links)[l1$query.id, , drop = FALSE]))
GenomicRanges::strand(l1) = GenomicRanges::strand(links.p[[1]])[l1$query.id]
l1$stack.id = win.u$grl.ix[l1$subject.id]
l1$y.pos = ylim.stacks$xaxis.pos[l1$stack.id]
l1$x.pos = mapply(function(x,y,z,a) (y-z)*a + x, x = window.segs.u[l1$subject.id,]$start, y = start(l1),
z = start(win.u[l1$subject.id]), a = window.segs.u$width[l1$subject.id] / width(win.u)[l1$subject.id])
l2 = gr.findoverlaps(links.p[[2]], win.u)
values(l2) = cbind(as.data.frame(values(l2)), as.data.frame(values(links)[l2$query.id, , drop = FALSE]))
GenomicRanges::strand(l2) = GenomicRanges::strand(links.p[[2]])[l2$query.id]
l2$stack.id = win.u$grl.ix[l2$subject.id]
l2$y.pos = ylim.stacks$xaxis.pos[l2$stack.id]
l2$x.pos = mapply(function(x,y,z,a) (y-z)*a + x, x = window.segs.u[l2$subject.id,]$start, y = start(l2),
z = start(win.u[l2$subject.id]), a = window.segs.u$width[l2$subject.id] / width(win.u)[l2$subject.id])
.fix.l = function(ll) {
if (!is.null(links.feat)) {
for (col in names(links.feat)) {
if (nrow(links.feat) == 1) {
values(ll)[, col] = links.feat[, col]
} else {
values(ll)[, col] = links.feat[ll$query.id, col]
}
}
}
# set up connectors
if (is.null(ll$v))
ll$v = y.gaps[ll$stack.id]/4
else
ll$v = y.gaps[ll$stack.id]*ll$v/2
if (is.null(ll$h))
ll$h = (window.segs.xlim$end[ll$stack.id] - window.segs.xlim$start[ll$stack.id])/20
else
ll$h = (window.segs.xlim$end[ll$stack.id] - window.segs.xlim$start[ll$stack.id])*ll$h
if (is.null(ll$arrow))
ll$arrow = TRUE
if (is.null(ll$cex.arrow))
ll$cex.arrow = 1
if (is.null(ll$lwd))
ll$lwd = 1
if (is.null(ll$lty))
ll$lty = 3
if (is.null(ll$col))
ll$col = 'red'
if (is.null(ll$col.arrow))
ll$col.arrow = ll$col
return(ll)
}
if (length(l1)>0)
l1 = .fix.l(l1)
if (length(l2)>0)
l2 = .fix.l(l2)
## now pair up / merge l1 and l2 using query.id as primary key
if (length(l1)>0 & length(l2)>0)
{
pairs = merge(data.frame(l1.id = 1:length(l1), query.id = l1$query.id), data.frame(l2.id = 1:length(l2), query.id = l2$query.id))[, c('l1.id', 'l2.id')]
l1.paired = GenomicRanges::as.data.frame(l1)[pairs[,1], ]
l2.paired = GenomicRanges::as.data.frame(l2)[pairs[,2], ]
}
else
{
l2.paired = l1.paired = data.frame()
pairs = data.frame()
}
## some l1 and l2 will be unpaired
l.unpaired = GRanges(seqlengths = GenomeInfoDb::seqlengths(links));
p1 = p2 = c();
if (nrow(pairs)>0)
{
p1 = pairs[,1]
p2 = pairs[,2]
}
if (length(l1)>0)
l.unpaired = grbind(l.unpaired, l1[setdiff(1:length(l1), p1)])
if (length(l2)>0)
l.unpaired = grbind(l.unpaired, l2[setdiff(1:length(l2), p2)])
if (length(l.unpaired)>0)
{
l.unpaired$v = l.unpaired$v/4
l.unpaired$h = l.unpaired$h/2
l.unpaired$col = alpha(l.unpaired$col, 0.5)
## unpaired will get a "bridge to nowhere" in the proper direction (eg down)
l.unpaired$y.pos = ylim.stacks$end[l.unpaired$stack.id]
# l.unpaired$y.pos2 = l.unpaired$y.pos + top.gaps[l.unpaired$stack.id]
l.unpaired$y.pos2 = l.unpaired$y.pos + l.unpaired$v
connectors(l.unpaired$x.pos, l.unpaired$y.pos, as.character(GenomicRanges::strand(l.unpaired)),
l.unpaired$x.pos, l.unpaired$y.pos2,
as.character(GenomicRanges::strand(l.unpaired)),
v = abs(l.unpaired$v), h = l.unpaired$h, type = 'S',
f.arrow = l.unpaired$arrow, b.arrow = l.unpaired$arrow,
cex.arrow = 0.2*l.unpaired$cex.arrow,
col.arrow = l.unpaired$col.arrow,
lwd = l.unpaired$lwd, lty = l.unpaired$lty, col = l.unpaired$col)
if (!is.null(l.unpaired$label))
{
cex = 0.5;
if (!is.null(l.unpaired$cex.label))
cex = l.unpaired$cex.label
# text(l.unpaired$x.pos, l.unpaired$y.pos2, l.unpaired$label, adj = c(0.5, 0.5), cex = cex)
l.unpaired$text.y.pos =l.unpaired$y.pos - (ylim.stacks$end[l.unpaired$stack.id]-ylim.stacks$start[l.unpaired$stack.id])/100
text(l.unpaired$x.pos, l.unpaired$text.y.pos, l.unpaired$label, adj = c(0.5, 1), cex = cex)
}
}
## now draw connectors for paired links
## pairs on the same level will get a "U" link,
## pairs on different levels will get "S" links
## fix y distances so that connections go from topmost part of bottom most connection to the bottom most part of
## top connection (ie the xaxis position)
if (nrow(l1.paired)>0)
{
l1.paired$bottom = l1.paired$y.pos < l2.paired$y.pos
if (any(l1.paired$bottom))
l1.paired$y.pos[l1.paired$bottom] = ylim.stacks$end[l1.paired$stack.id[l1.paired$bottom]]
if (any(!l1.paired$bottom))
l2.paired$y.pos[!l1.paired$bottom] = ylim.stacks$end[l2.paired$stack.id[!l1.paired$bottom]]
# also make all c type connections top connections with positive v
ctype = ifelse(l1.paired$stack.id == l2.paired$stack.id, 'U', 'S')
l1.paired$y.pos[ctype == 'U'] = ylim.stacks$end[l1.paired$stack.id[ctype == 'U']]
l2.paired$y.pos[ctype == 'U'] = ylim.stacks$end[l2.paired$stack.id[ctype == 'U']]
l1.paired$v[ctype == 'U'] = abs(l1.paired$v[ctype == 'U'])
win.width = diff(par('usr')[1:2])
l1.paired$v = l1.paired$v * affine.map(abs(l2.paired$x.pos - l1.paired$x.pos)/diff(par('usr')[1:2]), xlim = c(0, 1), ylim = c(0.5, 1)) ## make longer links taller
connectors(l1.paired$x.pos, l1.paired$y.pos, l1.paired$strand, l2.paired$x.pos, l2.paired$y.pos, l2.paired$strand,
v = l1.paired$v, h = l1.paired$h, type = ctype,
f.arrow = l1.paired$arrow, b.arrow = l1.paired$arrow, cex.arrow = 0.2*l1.paired$cex.arrow, col.arrow = l1.paired$col.arrow,
lwd = l1.paired$lwd, lty = l1.paired$lty, col = l1.paired$col)
if (!is.null(l1.paired$label))
{
cex = 0.5;
if (!is.null(l1.paired$cex.label))
cex = l1.paired$cex.label
## text(l1.paired$x.pos, l1.paired$y.pos+l1.paired$v/2, l1.paired$label, adj = c(0.5, 0.5), cex = cex)
## text(l2.paired$x.pos, l2.paired$y.pos+l1.paired$v/2, l2.paired$label, adj = c(0.5, 0.5), cex = cex)
l1.paired$text.y.pos = l1.paired$y.pos - (ylim.stacks$end[l1.paired$stack.id]-ylim.stacks$start[l1.paired$stack.id])/100
l2.paired$text.y.pos = l2.paired$y.pos - (ylim.stacks$end[l2.paired$stack.id]-ylim.stacks$start[l2.paired$stack.id])/100
text(l1.paired$x.pos, l1.paired$text.y.pos, l1.paired$label, adj = c(0.5, 1), cex = cex)
text(l2.paired$x.pos, l2.paired$text.y.pos, l2.paired$label, adj = c(0.5, 1), cex = cex)
}
}
}
}
oldgt <- get("plot.gTrack", envir = asNamespace("gTrack"))
environment(plot.gTrack) <- environment(oldgt)
attributes(plot.gTrack) <- attributes(oldgt) # don't know if this is really needed
assignInNamespace("plot.gTrack", plot.gTrack, ns="gTrack")
plot.gTrack = plot.gTrack
draw.grl = function(grl,
y = NULL, # can be either vector of length grl, or data.frame row / list with fields $start and $end
# specifying y coordinates to "pack" the granges into (or just length 2 list)
# note this is different from ylim, which determines the size of the canvas
ylim = NULL, # if null and y provided, will find range of y and plot
ylim.subplot = NULL,
ywid = NULL,
edges = NULL, ## data.frame specifying edges connecting items of grl, with fields $from $to indexing grl and optional fields $lwd, $col, $lty specifying formatting options for connectors, for gr the from arrow will leave the right side of a + range and left side of a - range, and enter the left side of a + range and right side of a - range. For grl, from arrows will be drawn from the last range in the "from" list item to the first range in the "to" list item
draw.paths = F, # if draw.paths = T will treat grl's as paths / contigs,
# connecting intervals joined by arrowed curved arcs using alternate stacking algo (ignoring y information)
draw.var = F, # if true, then varbase will be called on grl or unlist(grl)
var = NULL, # optional GRangesList of same length as grl specifying variant bases with value cols $type, $varbase (ie output of varbase)
# corresponding to each grl item
var.col = NULL, # named vector with variant colors to override - valid names are XA, XT, XG, XC, S, D, I
var.soft = T, ## whether to draw soft clips for varbase
windows, # windows specifies windows, can have optional meta data features $col and $border
win.gap = NULL,
stack.gap,
min.gapwidth = 1, # only applies if windows is not specified
col = NULL, border = NA, # all of these variables can be scalar or vectors of length(grl),
# can be over-ridden by values / columns in grl
col.backbone = alpha('gray', 0.8),
gr.colorfield = NULL, ## values field in the gr from which colors can be mapped
gr.colormap = NULL, ## named vector mapping fields in the gr.colorfield to colors, if unspecified brewer.master() will be applied
gr.labelfield = NULL, ## field of gr labels to draw.
grl.labelfield = NULL, ## field of grl to draw as label
leg.params,
labels = NULL, # vector of length(grl)
labels.suppress = F,
labels.suppress.grl = labels.suppress,
labels.suppress.gr = labels.suppress,
spc.label = 0.05, # number between 0 and 1 indicating spacing of label
adj.label = c(0, 1),
cex.label = 1,
cex.edge.label = cex.label,
gr.cex.label = 0.8 * cex.label,
gr.srt.label = 0,
gr.adj.label = c(0,0.5),
new.plot, new.axis,
sep.lty = 2,
sep.lwd = 1,
sep.bg.col = 'gray95',
sep.draw = TRUE,
y.pad, # this is the fractional padding to put on top and bottom of ranges if y is specified as $start and $end pair (def was 0.05)
xaxis.prefix = '', xaxis.suffix = 'MB', xaxis.unit = 1, xaxis.round = 3,
xaxis.interval = 'auto', xaxis.pos = 1,
xaxis.pos.label, xaxis.cex.label,
xaxis.newline = FALSE,
xaxis.chronly = FALSE,
xaxis.ticklen = 1,
xaxis.width = TRUE,
xaxis.label.angle = 0,
xaxis.cex.tick = 1,
ylim.grid = ylim, # can be also specified directly for plots with multiple axes and/or non-numeric tracks
y.grid = NA, # if non NA, then the number specifies the spacing between y grid (drawn from ylim[1] to ylim[2]), can also be named vector mapping grid.tick labels to plot locations
ylab = NULL,
y.grid.col = alpha('gray', 0.5),
y.grid.pretty = 5,
y.grid.cex = 1,
y.grid.lty = 2,
y.grid.lwd = 1,
path.col = 'black',
path.lwd = 1,
path.col.arrow = path.col,
path.cex.arrow = 1,
path.stack.y.gap = 1,
path.stack.x.gap = 0,
path.cex.v = 1,
path.cex.h = 1,
draw.backbone = NULL,
xlim = c(0, 20000), # xlim of canvas
points = NA, ## if non NA then will draw a given point with pch style
circles = FALSE, ## only one of these should be true, however if multiple are true then they will be interpreted in this order
bars = FALSE,
y0.bar = NULL,
lines = F,
angle, # angle of barbs to indicate directionality of ranges
verbose=FALSE,
triangle=FALSE, # trigger a triangle matrix plot
ylim.parent=NULL, ## ylim of the full thing. This is importat for angle preseveration
legend.params = list(plot=TRUE),
bg.col = NA, ## background of whole plot
ylab.las = 3,
ylab.adj = c(0.5, 1),
...)
{
now = Sys.time();
## PATCH: we are forgetting about any ylim.subplot settings done above .. WHY?
# ylim.subplot = NULL
empty.plot = FALSE
## PATCH: last minute defaults
if (is.na(xaxis.width))
xaxis.width = TRUE
if (is.na(xaxis.chronly))
xaxis.chronly = FALSE
if (is.na(xaxis.label.angle))
xaxis.label.angle = 0
if (length(grl)>0)
{
if (is.null(draw.backbone))
draw.backbone = TRUE
# if (inherits(grl, 'GappedAlignments'))
# grl = ga2gr(grl)
if ((inherits(grl, 'GRanges')))
{
if (!is.null(windows)) ## hack to get over stupid GRanges speed issues when we have a giant GRanges input (eg coverage)
{
strand(windows) <- rep("*", length(windows)) ## don't need strand on windows, mess up intersections
ix <- gUtils::gr.in(grl, windows)
grl = grl[ix]
if (!is.null(col))
if (length(col)!=1)
col = col[ix]
if (!is.null(border))
if (length(border)!=1)
border = border[ix]
if (!is.null(ywid))
if (length(ywid)!=1)
ywid = ywid[ix]
if (!is.null(y))
if (!is.list(y))
if (length(y)!=1)
y = y[ix]
if (!is.null(labels))
if (!is.list(labels))
if (length(labels)!=1)
labels = labels[ix]
if (!is.null(edges))
if (nrow(edges)>0 & all(c('from', 'to') %in% colnames(edges)))
{
if (data.table::is.data.table(edges))
edges = as.data.frame(edges)
ix.i = which(ix)
edges = edges[edges$from %in% ix.i | edges$to %in% ix.i,];
edges$from = match(edges$from, ix.i)
edges$to = match(edges$to, ix.i)
}
}
gr.names = names(grl);
names(grl) = NULL;
if (length(grl)>0)
grl = GenomicRanges::split(grl, 1:length(grl))
else
grl = GenomicRanges::GRangesList(grl)
names(grl) = gr.names;
}
if (is.null(labels))
if (is.null(values(grl)$labels))
labels = names(grl)
else
labels = values(grl)$labels
# make sure names are unique
names(grl) = 1:length(grl);
if (is.na(labels.suppress.grl))
labels.suppress.grl = FALSE
if (is.na(labels.suppress.gr))
labels.suppress.gr = FALSE
if (is.na(draw.var))
draw.var = F
if (is.na(draw.paths))
draw.paths = F
if (!is.null(gr.colorfield))
if (all(is.na(gr.colorfield)))
gr.colorfield = NULL
if (!is.null(gr.colormap))
if (all(is.na(gr.colormap)))
gr.colormap = NULL
else if (is.null(names(gr.colormap)))
gr.colormap = NULL
if (!is.null(col))
if (all(is.na(col)))
col = NULL
## postpone further color processing until later
if (is.null(col))
if (!is.null(values(grl)$col))
col = values(grl)$col
else if (is.null(gr.colorfield) & is.null(gr.colormap))
col = NA # 'black'
else
col = NA
if (is.na(col.backbone))
col.backbone = NULL
if (is.null(col.backbone))
col.backbone = col
# if (is.na(border))
# border = NULL
if (is.null(border))
border = NA
grl.props = cbind(data.frame(group = names(grl), col = col, stringsAsFactors = F), as.data.frame(values(grl)))
grl.props$border = border;
grl.props$ywid = ywid;
if (!is.null(y) & !is.list(y) & length(y)>0) ## if y coordinate is specified for the ranges
{
grl.props$y = y;
bad = is.na(y)
bad[which(is.infinite(y))] = TRUE
if (any(bad))
{
grl.props = grl.props[!bad, ]
grl = grl[!bad]
if (!is.null(labels))
labels = labels[!bad]
y = grl.props$y
}
}
if (!is.null(grl.labelfield))
{
if (!is.na(grl.labelfield))
{
if (grl.labelfield %in% names(grl.props))
grl.props$grl.labels = grl.props[, grl.labelfield]
}
else if (!is.null(labels))
grl.props$grl.labels = labels ## use $grl.labels to allow labeling of individual grs
}
else if (!is.null(labels))
if (!is.na(labels[1])) ## will only be null if labels is NULL and names(grl) was NULL
grl.props$grl.labels = labels ## use $grl.labels to allow labeling of individual grs
gr = tryCatch(grl.unlist(grl), error = function(e)
{
## ghetto solution if we get GRanges names snafu
gr = unlist(grl);
if (length(gr)>0)
{
tmpc = textConnection(names(gr));
cat('budget .. \n')
gr$grl.ix = read.delim(tmpc, sep = '.', header = F)[,1];
# gr$grl.iix = levapply(rep(1, length(gr)), gr$grl.ix, FUN = function(x) 1:length(x))
gr$grl.iix = data.table::data.table(ix = gr$grl.ix)[, iix := 1:length(ix), by = ix][, iix]
close(tmpc)
}
return(gr)
})
gr$group = grl.props$group[gr$grl.ix]
gr$group.ord = gr$grl.iix
gr$first = gr$grl.iix == 1
last = iix = NULL ## NOTE fix
if (length(gr)>0)
gr$last = data.table::data.table(iix = as.numeric(gr$grl.iix), ix = gr$grl.ix)[, last := iix == max(iix), by = ix][, last]
# gr$last = levapply(gr$grl.iix, gr$grl.ix, FUN = function(x) x == max(x))
grl.props$group = as.character(grl.props$group)
S4Vectors::values(gr) = cbind(as.data.frame(values(gr)),
grl.props[match(values(gr)$group, grl.props$group), setdiff(colnames(grl.props), c(colnames(values(gr)), 'group', 'labels')), drop = FALSE])
#####
## variant drawing
####
if (draw.var & is.null(var) & length(gr)>0)
{
# var = bamUtils::varbase(gr[gr.in(gr, windows)], soft = var.soft)
gix = which(gr.in(gr, windows))
var = varbase(gr[gix], soft = var.soft)
if (any(iix <- var$type == 'I'))
end(var[ix]) = end(var[ix])+1
names(var) = gix
}
else
gix = NULL
if (!is.null(var))
if (inherits(var, 'GRangesList'))
{
VAR.COL = get.varcol()
if (!is.null(var.col))
VAR.COL[names(var.col)] = var.col;
names(var) = NULL
if (!is.null(gix))
names(var) = gix
else
names(var) = 1:length(var)
# var.group = as.numeric(as.data.frame(var)$element)