forked from mskilab-org/gGnome
-
Notifications
You must be signed in to change notification settings - Fork 0
/
converters.R
executable file
·2719 lines (2336 loc) · 109 KB
/
converters.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
# assigning this operator since sometimes R tries to use the ggplot2 operator instead of the gUtils one (depending on the order of libraries loaded in a session)
`%+%` = gUtils::`%+%`
#' @name breakgraph
#' @title breakgraph
#'
#' @description
#' Builds a gGraph by breaking the reference genome at the points specified in tile
#' Treats tile as nothing but breakpoints, no metadata, nothing special
#' Juncs can be either a GRangesList of junctions in proper format or a Junction Object
#' If tile has length 0, this function creates a simple graph (1 node per chromosome, each one full length)
#' If genome is specified, it will try to use that genome instead - if it is invalid it wil use the default#'
#' unlists a list of vectors, matrices, data.tables into a data.table indexed by the list id
#'
#' @param tile GRanges of tiles
#' @param juncs Junction object or grl coercible to Junctions object
#' @param genome seqinfo or seqlengths
#' @return list with gr and edges which can be input into standard gGnome constructor
#' @author Marcin Imielinski, Joe DeRose, Xiaotong Yao
#' @keywords internal
#' @noRd
breakgraph = function(breaks = NULL,
juncs = NULL,
genome = NULL)
{
## Make sure user entered some input
if (is.null(breaks) & is.null(juncs)) {
stop("Cannot have both breaks and juncs be NULL, must be some input")
}
## If juncs is not Junction Object, try to convert it
if(!is.null(juncs) && !inherits(juncs, "Junction")) {
juncs = tryCatch(Junction$new(juncs),
error = function(e) {
NULL
})
if (is.null(juncs)) {
stop("Input is not a valid junctions set.")
}
}
## Validate breaks as GRanges
if (!is.null(breaks) && !inherits(breaks, "GRanges")){
breaks = tryCatch(GRanges(breaks),
error=function(e){
NULL
})
if (is.null(breaks)){
stop("Input cannot be converted into a GRanges object.")
}
}
## If the user provided a genome, check if it is valid. If it isn't, set to NULL
if (!is.null(genome)) {
tmp = tryCatch(si2gr(genome), error=function(e) NULL)
if (is.null(tmp)) {
genome = NULL
warning('Provided genome not coercible to seqinfo')
}
else
{
genome = seqinfo(tmp)
}
}
if (is.null(genome))
{
if (!is.null(breaks)){
genome = seqinfo(breaks)
}
else if (!is.null(juncs)){
genome = seqinfo(juncs$grl)
}
else{
stop('Provided genome not coercible to Seqinfo object and no breaks or junc provided. Must provide either breaks, junc, or genome argument to this constructor')
}
}
## Build a GRanges from the default genome
## FIXME: if using misc chr, definitely need to specify genome
nodes = gr.stripstrand(si2gr(genome))
edges = data.table(n1 = numeric(0), n2 = numeric(0), n1.side = numeric(0), n2.side = numeric(0), type = character(0))
## Break the genome based on whether there is breaks or juncs
if (!is.null(breaks) && length(breaks) > 0) {
tmp.br = gr.stripstrand(breaks)[, c()]
tmp.br$break.id = 1:length(tmp.br)
nodes = gr.disjoin(grbind(tmp.br, nodes))
}
if (!is.null(juncs) && length(juncs) > 0) {
## collapse node with positive and
juncsGR = gr.start(gr.fix(grl.unlist(juncs$grl), nodes), ignore.strand = FALSE) ## grl.ix keeps track of junction id
nodes = gr.fix(nodes, juncsGR)
## keep track of nmeta to paste back later
nodes$nid = 1:length(nodes)
nmeta = as.data.table(values(nodes))
## disjoin nodes and bps
bps = juncsGR[, c('grl.ix')] ## trim bps to first base
dnodes = sort(gr.disjoin(grbind(nodes, gr.stripstrand(bps))))
bpov = dnodes %*% bps ## merge back with bps to figure out where to trim dnodes
strand(bpov) = strand(bps)[bpov$subject.id]
## mark whether bps have a negative strand or positive strand junction attaching to them
## (each bp should have at least one has.neg or has.pos = TRUE)
has = gr2dt(bpov)[, .(has.pos = any(strand=='+'), has.neg = any(strand=='-')), keyby = query.id][.(1:length(dnodes)), ]
## merge this info back to dnodes, not that non bp intervals will have has.neg and has.pos = NA
dnodes = merge(gr2dt(dnodes)[, query.id := 1:.N], has, by = 'query.id', all = TRUE)
setkey(dnodes, query.id)
dnodes[, is.bp := !is.na(has.neg)]
dnodes[, has.neg := ifelse(is.na(has.neg), FALSE, has.neg)]
dnodes[, has.pos := ifelse(is.na(has.pos), FALSE, has.pos)]
## merge dnodes with next interval if that interval
## precedes a has.pos = FALSE
## merge dnodes with previous interval if that interval
## follows a has.neg = FALSE
## the following grouping will encode this principle
## i.e. we always increment the group counter from node to node except when
## current node has.pos = FALSE and previous node has.neg = FALSE
## and at least one of the nodes is a bp node
dnodes[, increment := !((is.bp | c(FALSE, is.bp[-.N])) & c(TRUE, !has.neg[-.N]) & !has.pos), by = seqnames]
dnodes[, group := cumsum(sign(increment)), by = seqnames]
## collapse dnodes with same group in same seqnames
## but don't merge across nids
nodes = dt2gr(dnodes[, .(start = start[1], end = end[.N]), by = .(seqnames, group, nid)], seqlengths = seqlengths(nodes))
## paste back metadata
values(nodes) = nmeta[nodes$nid, ]
nodes.left = gr.start(nodes); nodes.left$side = 'left';
nodes.right = gr.end(nodes); nodes.right$side = 'right'
nodes.right$nid = nodes.left$nid = 1:length(nodes)
node.ends = unique(grbind(nodes.left, nodes.right))
ov = gr2dt(juncsGR[, c('grl.ix', 'grl.iix')] %*% node.ends)[order(grl.iix), ]
## Map the Junctions to an edge table
## Mapping is as follows in terms of junctions a -> b
## a- => leaves/enters left side of base a
## a+ => leaves/enters right side of base a
## a- <-> a+ => leaves left side of base a, enters right side of base a (NOT THE BASE NEXT TO a)
ov[, strand := as.character(strand(juncsGR))[query.id]]
setkeyv(ov, c('grl.ix', 'grl.iix'))
### ov should have exactly one row per grl.ix grl.iix combo
new.edges =
merge(
ov[.(1:length(juncs), rep(1, length(juncs))),
.(grl.ix = 1:length(juncs),
n1 = node.ends$nid[subject.id],
n1.side = ifelse(strand == '-', 1, 0))],
ov[.(1:length(juncs), rep(2, length(juncs))),
.(
grl.ix = 1:length(juncs),
n2 = node.ends$nid[subject.id],
n2.side = ifelse(strand == '-', 1, 0))],
by = 'grl.ix'
)[, type := 'ALT']
## new.edges = ov[, .(
## n1 = node.ends$nid[subject.id[1]],
## n2 = node.ends$nid[subject.id[2]],
## n1.side = ifelse(strand[1] == '-', 1, 0),
## n2.side = ifelse(strand[2] == "-", 1, 0),
## type = "ALT"
## ), keyby = grl.ix]
if (length(setdiff(1:length(juncs), new.edges$grl.ix))>0)
stop('Error in breakgraph generation - some junctions failed to be incorporated')
## Remove junctions that aren't in the genome selected
## this will have n1 or n2 NA
new.edges = new.edges[!(is.na(n1) | is.na(n2)), ]
## reconcile new.edges with metadata
if (!is.null(juncsGR))
if (ncol(values(juncs$grl))>0)
new.edges = cbind(new.edges, as.data.table(values(juncs$grl)[new.edges$grl.ix, , drop = FALSE]))
edges = rbind(edges, new.edges, fill = TRUE)
}
## now make reference edges
nodesdt = as.data.table(nodes[, c()])
nodesdt[, node.id := 1:.N]
nodesdt[, endnext := end +1]
ref.edges = merge(nodesdt, nodesdt, by.x = c('seqnames', 'endnext'),
by.y = c('seqnames', 'start'),
allow.cartesian = TRUE)
if (nrow(ref.edges)>0)
{
ref.edges = ref.edges[, .(n1 = node.id.x, n1.side = 1, n2 = node.id.y, n2.side = 0)]
ref.edges$type = "REF"
edges = rbind(edges, ref.edges, fill = TRUE)
}
nodes$qid = NULL
names(nodes) = NULL
## let nodes inherit break metadata using results of disjoin above
if (!is.null(breaks) && !is.null(nodes$break.id)){
if (ncol(values(breaks))>0){
values(nodes) = values(breaks)[nodes$break.id, ]
}
}
NONO.FIELDS = c('from', 'to')
if (any(nono.ix <- names(edges) %in% NONO.FIELDS))
{
warning(paste('removing reserved edge metadata fields from edges:', paste(NONO.FIELDS, collapse = ',')))
edges = edges[, !nono.ix, with = FALSE]
}
NONO.FIELDS = c('node.id', 'snode.id', 'index')
if (any(nono.ix <- names(values(nodes)) %in% NONO.FIELDS))
{
warning(paste('removing reserved edge metadata fields from nodes:', paste(NONO.FIELDS, collapse = ',')))
nodes = nodes[, !nono.ix]
}
return(list(nodes = nodes, edges = edges))
}
#' @name rck2gg
#' @title rck2gg
#'
#' @description
#' Constructor for creating gGraph from RCK output file
#'
#' @param rck.dirname (character) directory name containing RCK outputs
#' @param simplify (logical) merge adjacent regions with same total CN? default FALSE
#' @param haploid (logical) create total CN (unphased) graph? default TRUE. FALSE NOT IMPLEMENTED YET.
#' @param prefix (character) prefix in the RCK output files (namely {prefix}rck.scnt.tsv {prefix}rck.acnt.tsv)
#'
#' @return list of gr and edges that can be input into standard gGraph constructor
#' @author Marcin Imielinski, Zi-Ning Choo, Xiaotong Yao
#' @keywords internal
#' @noRd
rck2gg = function(rck.dirname, haploid = TRUE, simplify = TRUE, prefix = '')
{
if (!dir.exists(rck.dirname)) {
stop("Input RCK directory not found")
}
scnt.fname = file.path(rck.dirname, paste0(prefix, "rck.scnt.tsv"))
acnt.fname = file.path(rck.dirname, paste0(prefix, "rck.acnt.tsv"))
if (!file.exists(scnt.fname) | !file.exists(acnt.fname)) {
stop("Required output files rck.scnt.tsv and rck.acnt.tsv cannot be located")
}
## read segment copy numbers
segs.dt = fread(scnt.fname)
## extract total CN from allelic CN if haploid == TRUE
seg.ptn = "cn=\\{'c1': \\{'A': ([0-9]+), 'B': ([0-9]+)\\}\\}"
if (all( grep(seg.ptn, segs.dt$extra[1], value = FALSE) == 0)) {
stop("rck.scnt.tsv not properly formatted")
}
segs.dt[, A := gsub(seg.ptn, "\\1", extra) %>% as.numeric]
segs.dt[, B := gsub(seg.ptn, "\\2", extra) %>% as.numeric]
segs.dt[, total := A + B]
## read adjacency copy numbers
adjs.dt = fread(acnt.fname)
## check valid extra field
adjs.ptn = "aid=\\w+;cn=\\{'c1': \\{'AA': ([0-9]+), 'AB': ([0-9]+), 'BA': ([0-9]+), 'BB': ([0-9]+)}};at=\\w+"
if (all( grep(adjs.ptn, adjs.dt$extra[1], value = FALSE) == 0)) {
stop("rck.acnt.tsv not properly formatted")
}
adjs.dt[, ":="(AA = gsub(adjs.ptn, "\\1", extra) %>% as.numeric, ## CN of junction endpoints
AB = gsub(adjs.ptn, "\\2", extra) %>% as.numeric,
BA = gsub(adjs.ptn, "\\3", extra) %>% as.numeric,
BB = gsub(adjs.ptn, "\\4", extra) %>% as.numeric)]
## total CN
adjs.dt[, total := AA + AB + BA + BB]
## get n1 and n2 sides
adjs.dt[, n1.side := ifelse(strand1 == "+", "right", "left")]
adjs.dt[, n2.side := ifelse(strand2 == "+", "right", "left")]
## only ALT junctions with nonzero total CN
## alt.dt = adjs.dt[grep("^[0-9]+$", aid, value = FALSE),][total > 0,] ## if not start with R
adjs.dt = adjs.dt[grepl("^[0-9]+$", aid) | (total > 0)]
adjs.dt[, type := ifelse(grepl("^[0-9]+$", aid), "ALT", "REF")]
if (haploid) {
nodes.gr = dt2gr(segs.dt[, .(seqnames = chr, start, end, cn = A + B)])
## prepare edge data table
edges.dt = adjs.dt[, .(chr1, coord1, chr2, coord2, n1.side, n2.side, cn = AA + AB + BA + BB, type)]
## n1 coordinates
edges.n1 = GRanges(seqnames = edges.dt$chr1, ranges = IRanges(start = edges.dt$coord1, width = 1))
## n2 coordinates
edges.n2 = GRanges(seqnames = edges.dt$chr2, ranges = IRanges(start = edges.dt$coord2, width = 1))
## add corresponding nodes
n1.mt = gr.match(edges.n1, nodes.gr)
n2.mt = gr.match(edges.n2, nodes.gr)
edges.dt[, n1 := n1.mt]
edges.dt[, n2 := n2.mt]
nodes.gr$ywid = 0.8
} else {
nodes.gr = dt2gr(
rbind(segs.dt[, .(seqnames = chr, start, end, cn = A, total = A + B, haplotype = "A")],
segs.dt[, .(seqnames = chr, start, end, cn = B, total = A + B, haplotype = "B")])
)
## prepare edge data table
edges.dt = rbind(
adjs.dt[, .(chr1, coord1, chr2, coord2, n1.side, n2.side, type,
n1.haplotype = "A", n2.haplotype = "A", cn = AA, total)],
adjs.dt[, .(chr1, coord1, chr2, coord2, n1.side, n2.side, type,
n1.haplotype = "A", n2.haplotype = "B", cn = AB, total)],
adjs.dt[, .(chr1, coord1, chr2, coord2, n1.side, n2.side, type,
n1.haplotype = "B", n2.haplotype = "A", cn = BA, total)],
adjs.dt[, .(chr1, coord1, chr2, coord2, n1.side, n2.side, type,
n1.haplotype = "B", n2.haplotype = "B", cn = BB, total)]
)
## n1 coordinates
edges.n1 = GRanges(seqnames = edges.dt$chr1,
ranges = IRanges(start = edges.dt$coord1, width = 1),
haplotype = edges.dt$n1.haplotype)
## n2 coordinates
edges.n2 = GRanges(seqnames = edges.dt$chr2,
ranges = IRanges(start = edges.dt$coord2, width = 1),
haplotype = edges.dt$n2.haplotype)
## add corresponding nodes
n1.mt = gr.match(edges.n1, nodes.gr, by = "haplotype")
n2.mt = gr.match(edges.n2, nodes.gr, by = "haplotype")
edges.dt[, n1 := n1.mt]
edges.dt[, n2 := n2.mt]
## formatting
nodes.gr$col = ifelse(nodes.gr$haplotype == "A", alpha("red", 0.5), alpha("blue", 0.5))
nodes.gr$ywid = 0.8
edges.dt[cn == 0, col := alpha("gray", 0.01)]
}
if (simplify) {
edges.dt = edges.dt[cn > 0]
nodes.gr = inferLoose(nodes.gr, edges.dt)
}
return(list(nodes = nodes.gr, edges = edges.dt))
}
#' @name pr2gg
#' @title pr2gg
#'
#' @description
#' ## Generates a gGraph from a prego output file
#'
#' @return list of gr and edges that can be input into standard gGraph constructor
#' @author Marcin Imielinski, Joe DeRose, Xiaotong Yao
#' @keywords internal
#' @noRd
pr2gg = function(fn, simplify = TRUE)
{
if (file.info(fn)$isdir)
fn = paste0(fn, '/.')
res.tmp = readLines(paste(dirname(fn), 'intervalFile.results', sep = '/'))
chrm.map.fn = paste(dirname(fn), "chrm.map.tsv", sep = '/')
if (file.exists(chrm.map.fn)){
chrm.map = fread(chrm.map.fn)[,setNames(V1, V2)]
}
res = structure(lapply(split(res.tmp, cumsum(grepl("edges", res.tmp))),
function(x) {
rd = read.delim(textConnection(x),
strings = F,
skip = 1,
header = F,
col.names = c("node1", "chr1",
"pos1", "node2",
"chr2", "pos2", "cn"))
if (exists("chrm.map")){
rd$chr1 = chrm.map[rd$chr1]
rd$chr2 = chrm.map[rd$chr2]
}
else {
rd = rd[which(rd$chr1 %in% as.character(1:24) &
rd$chr2 %in% as.character(1:24)),]
rd$chr1 = gsub("24", "Y", gsub("23","X",rd$chr1))
rd$chr2 = gsub("24", "Y", gsub("23","X",rd$chr2))
}
return(rd)
}),
names = gsub(":", "", grep("edges", res.tmp, value = T)))
res[[1]]$tag = paste0(res[[1]]$node1, ":", res[[1]]$node2)
## turn into our nodes
nodes = GRanges(res[[1]]$chr1,
IRanges(res[[1]]$pos1,
res[[1]]$pos2),
strand = "+",
cn = res[[1]]$cn,
left.tag = res[[1]]$node1,
right.tag = res[[1]]$node2)
edges = rbind(as.data.table(res[[2]])[, type := 'REF'],
as.data.table(res[[3]])[, type := 'ALT'])
if (nrow(edges)>0)
{
edges[, n1.left := match(node1, nodes$left.tag)]
edges[, n1.right := match(node1, nodes$right.tag)]
edges[, n2.left := match(node2, nodes$left.tag)]
edges[, n2.right := match(node2, nodes$right.tag)]
edges[, n1 := ifelse(is.na(n1.left), n1.right, n1.left)]
edges[, n1.side := ifelse(is.na(n1.left), 'right', 'left')]
edges[, n2 := ifelse(is.na(n2.left), n2.right, n2.left)]
edges[, n2.side := ifelse(is.na(n2.left), 'right', 'left')]
if (simplify)
{
edges = edges[cn>0, ]
}
}
nodes = inferLoose(nodes, edges)
return(list(nodes = gr.fix(nodes), edges = edges))
}
#' @name jab2gg
#' @title jab2gg
#' @description
#'
#' Constructor for creating a gGraph object from a jabba output ## Generates a gGraph from a prego output file
#'
#' @return list of gr and edges that can be input into standard gGraph constructor
#' @author Marcin Imielinski, Joe DeRose, Xiaotong Yao
#' @keywords internal
#' @noRd
jab2gg = function(jabba)
{
## Validate our input
if (is.list(jabba)) {
if (!all(is.element(c("segstats", "adj",
"purity", "ploidy"),
names(jabba)))){
stop("The input is not a JaBbA output.")
}
} else if (is.character(jabba) && grepl(".rds$", jabba)){
if (file.exists(jabba)){
jabba = readRDS(jabba)
} else {
stop("JaBbA file not found")
}
}
else if (inherits(jabba, 'gGraph'))
{
return(list(nodes = jabba$nodes$gr, edges = jabba$edges$dt))
}
else {
stop("Error loading jabba object from provided .rds path or object: please check input")
}
## second round check .. just in case .rds file had gGraph object inside it
if (inherits(jabba, 'gGraph'))
{
## don't discard purity/ploidy metadata if included
return(list(nodes = jabba$nodes$gr,
edges = jabba$edges$dt,
purity = jabba$meta$purity,
ploidy = jabba$meta$ploidy))
}
if (is.null(jabba$segstats$loose))
jabba$segstats$loose = FALSE
if (is.null(jabba$segstats$cn))
jabba$segstats$cn = NA
afields = c('cn', 'type', 'parent')
if (!is.null(jabba$asegstats) && inherits(jabba$asegstats, 'GRanges') && length(jabba$asegstats) == 2 * length(jabba$segstats) && length(setdiff(afields, names(mcols(jabba$asegstats)))) == 0){
snodes = jabba$segstats
aseg.dt = gr2dt(jabba$asegstats[, afields])
aseg.dt.dcast = dcast.data.table(aseg.dt, parent ~ type, value.var = 'cn')
setkey(aseg.dt.dcast, 'parent')
snodes$cn.low = aseg.dt.dcast$low
snodes$cn.high = aseg.dt.dcast$high
snodes = snodes %Q% (loose == FALSE)
} else {
snodes = jabba$segstats %Q% (loose == FALSE)
}
snodes$index = 1:length(snodes)
snodes$snode.id = ifelse(as.logical(strand(snodes)=='+'), 1, -1) * gr.match(snodes, unique(gr.stripstrand(snodes)))
if (length(snodes)==0)
return(gG(genome = seqinfo(segs)))
sedges = spmelt(jabba$adj[jabba$segstats$loose == FALSE, jabba$segstats$loose == FALSE])
nodes = snodes %Q% (strand == '+')
if (!is.null(nodes$eslack.in) & !is.null(nodes$eslack.out))
{
nodes$loose.left = nodes$eslack.in>0
nodes$loose.right = nodes$eslack.out>0
nodes$loose.cn.left = nodes$eslack.in
nodes$loose.cn.right = nodes$eslack.out
# nodes$loose = nodes$loose.left | nodes$loose.right
}
## don't do this o/w edgesdt won't have n1, n2, n1.side, n2.side
## if (nrow(sedges)==0)
## gG(nodes = nodes)
setnames(sedges, c('from', 'to', 'cn'))
setkeyv(sedges, c('from', 'to'))
sedges[, type := 'REF']
if (nrow(jabba$ab.edges)>0)
{
ab.edges = as.data.table(rbind(jabba$ab.edges[, 1:2, '+'],
jabba$ab.edges[, 1:2, '-']))
ab.edges[, jid := rep(1:nrow(jabba$ab.edges),2)]
ab.edges = ab.edges[!is.na(from) & !is.na(to), ]
if (nrow(ab.edges)>0)
{
if (ncol(values(jabba$junctions))>0)
{
ab.edges = as.data.table(cbind(ab.edges, values(jabba$junctions)[ab.edges$jid, ]))
if (!is.null(ab.edges$cn))
ab.edges[, cn := NULL] ## confilct with the cn inferred from adj
}
sedges[.(ab.edges$from, ab.edges$to), type := 'ALT']
ab.cols = c('from', 'to', setdiff(names(ab.edges), c('sedge.id', names(sedges))))
sedges = merge(sedges, ab.edges[, ab.cols, with = FALSE], by = c('from', 'to'), all.x = TRUE)
}
}
## rescue any hom-del ref edge
if (!is.null(jabba$edges$cn))
{
if (any(data.table(jabba$edges)[type=="reference", cn==0])){
sedges = rbind(sedges,
data.table(jabba$edges)[cn==0 & type=="reference",
.(from, to, type="REF", cn)],
fill=T)
}
}
edges = convertEdges(snodes, sedges, metacols = TRUE)
return(list(nodes = nodes,
edges = edges,
purity = jabba$purity,
ploidy = jabba$ploidy
))
## return(list(nodes = nodes[, intersect(c('cn', 'loose.left', 'loose.right', 'loose.cn.left', 'loose.cn.right'), names(values(nodes)))],
## edges = edges))
}
#' @name wv2gg
#' @title wv2gg
#' @description
#'
#' Constructor for creating a gGraph object from Weaver output
#'
#' @param weaver directory containing SV_CN_PHASE and REGION_CN_PHASE files
#' @return list of gr and edges that can be input into standard gGraph constructor
#' @author Marcin Imielinski, Joe DeRose, Xiaotong Yao
#' @keywords internal
#' @noRd
wv2gg = function(weaver, simplify = TRUE)
{
if (!file.info(weaver)$isdir)
weaver = dirname(weaver)
if (!dir.exists(weaver)){
stop("Error: Invalid input weaver directory!")
}
if (!all(is.element(c("SV_CN_PHASE", "REGION_CN_PHASE"), dir(weaver))) ){
stop('Error: Need "SV_CN_PHASE" and "REGION_CN_PHASE".')
}
region = data.table(read.delim(
paste(weaver, "REGION_CN_PHASE", sep="/"),
header = FALSE, sep = "\t"))
sv.fn = paste(weaver, "SV_CN_PHASE", sep="/")
if (file.size(sv.fn)>0){
sv = data.table(read.delim(sv.fn, header = FALSE, sep = "\t"))
names(sv) = c("chr1", "pos1", "side1", "allele1",
"chr2", "pos2", "side2", "allele2",
"cn", "unknown1", "unknown2", "timing", "class")[1:ncol(sv)]
}
else {
sv = NULL
}
## define the columns
names(region) = c("seqnames", "start", "end", "acn", "bcn")
region[, cn := acn + bcn]
## names(snp) = c("seqnames", "pos", "ref", "alt", "acn", "bcn")
## Xiaotong remove this on Apr 23
## don't need to do anything to the segment locations
## region$start = region$start+1 ## start coordinates appear to be 0 centric
## region$end = region$end+2 ## end coordinates appear to be "left-centric"
ss = dt2gr(region)
ss = gr.fix(ss)
## get junctions
## ALERT: in the file, +/- means right/left end of a segment
## exactly reverse of what we define a junction
strmap = setNames(c("+", "-"), c("-", "+"))
## sv.select = sv[!is.na(allele1) & !is.na(allele2)]
junc = NULL
if (!is.null(sv)){
sv = sv[which(allele1 !=0 & allele2 !=0), ]
if (simplify)
{
sv = sv[cn>0, ]
}
if (nrow(sv)>0)
{
bps = grbind(
dt2gr(
sv[, .(seqnames = chr1,
start = pos1,
end = pos1,
jix=.I, ii = 1,
strand = strmap[side1])],
seqlengths = seqlengths(ss)),
dt2gr(
sv[, .(seqnames = chr2,
start = pos2,
end = pos2,
jix=.I, ii = 2,
strand = strmap[side2])],
seqlengths = seqlengths(ss))
)
## Xiaotong remove this on Apr 23
## don't need to nudge anymore since we keep the segment faithful
## bps = grbind(
## dt2gr(
## sv[, .(seqnames = chr1,
## start = ifelse(side1=="-", pos1+1, pos1+2),
## end = ifelse(side1=="-", pos1+1, pos1+2),
## jix=.I, ii = 1,
## strand = strmap[side1])], seqlengths = seqlengths(ss)),
## dt2gr(
## sv[, .(seqnames = chr2,
## start = ifelse(side2=="-", pos2+1, pos2+2),
## end = ifelse(side2=="-", pos2+1, pos2+2),
## jix=.I, ii = 2,
## strand = strmap[side2])], seqlengths = seqlengths(ss))
## )
## sanity check, all raw.bp at this point should
## locate at left/right boundary of segements
ss.ends = c(gr.start(ss), gr.end(ss))
if (any(!bps %^% ss.ends)){
warning("Eligible SVs not matching segment ends!")
}
## create junctions
junc = grl.pivot(split(bps, bps$ii))
toget = intersect(c("allele1", "allele2", "cn", "unknown1", "unknown2", "timing", "class"), colnames(sv))
values(junc) = sv[, toget, with=F]
}
}
return(breakgraph(breaks = ss, juncs = junc))
}
#' @name remixt2gg
#' @title remixt2gg
#' @description
#'
#' Constructor for creating a gGraph object from remiXT output
#'
#' @return list of gr and edges that can be input into standard gGraph constructor
#' @author Marcin Imielinski, Joe DeRose, Xiaotong Yao
#' @keywords internal
#' @noRd
remixt2gg= function(remixt, simplify = TRUE)
{
if (!dir.exists(remixt)){
stop("Input ReMixT directory not found.")
} else if (length(rmt.out <- dir(remixt, "cn.tsv$|brk.tsv$", full.names=TRUE)) != 2){
stop("Required output files cn.tsv$ and brk.tsv$ cannot be located.")
}
rmt.seg = fread(grep("cn.tsv", rmt.out, value=TRUE))
rmt.seg[, ":="(start = data.table::shift(end)+1)]
rmt.seg[, start := ifelse(start > end, 1, start)]
rmt.seg[is.na(start), start:=1]
rmt.seg[, cn := major_1 + minor_1]
setnames(rmt.seg, 'chromosome', 'seqnames')
rmt.tile = dt2gr(rmt.seg)
rmt.bks = fread(grep("brk.tsv", rmt.out, value=TRUE))
if (nrow(rmt.bks)>0){
strmap = setNames(c("+", "-"), c("-", "+"))
rmt.bks[, cn := cn_1] ## only consider major clone right now
## add 1 to "+" positions since our breakgraph convention is to add + junctions to the left of the specified breakpoint
## while the remixt convention is to add them to the base immediately following the breakpoint
if (simplify)
{
rmt.bks = rmt.bks[cn>0, ]
}
bp1 = dt2gr(rmt.bks[, .(seqnames=chromosome_1,
start=position_1 + sign(strmap[strand_1]=='+'),
end=position_1 + sign(strmap[strand_1]=='+'),
strand=strmap[strand_1])], seqlengths = seqlengths(rmt.tile))
bp2 = dt2gr(rmt.bks[, .(seqnames=chromosome_2,
start=position_2 + sign(strmap[strand_2]=='+'),
end=position_2 + sign(strmap[strand_2]=='+'),
strand=strmap[strand_2])], seqlengths = seqlengths(rmt.tile))
juncs = grl.pivot(GRangesList(list(bp1, bp2)))
values(juncs) = rmt.bks[, .(prediction_id, cn, cn_0, cn_1, cn_2, n_1, side_1, n_2, side_2)]
} else {
juncs = NULL
}
return(breakgraph(breaks = rmt.tile, juncs = juncs))
}
#' @name read_vcf
#' @title read_vcf: utility function to read VCF into GRanges object
#'
#' @name read_vcf
#' @importFrom VariantAnnotation readVcf
#' @keywords internal
#' @noRd
read_vcf = function (fn, gr = NULL, hg = "hg19", geno = NULL, swap.header = NULL,
verbose = FALSE, add.path = FALSE, tmp.dir = "~/temp/.tmpvcf",
...)
{
in.fn = fn
if (verbose){
cat("Loading", fn, "\n")}
if (!is.null(gr)) {
tmp.slice.fn = paste(tmp.dir, "/vcf_tmp", gsub("0\\.",
"", as.character(runif(1))), ".vcf", sep = "")
cmd = sprintf("bcftools view %s %s > %s", fn, paste(gr.string(gr.stripstrand(gr)),
collapse = " "), tmp.slice.fn)
if (verbose){
cat("Running", cmd, "\n")
}
system(cmd)
fn = tmp.slice.fn
}
if (!is.null(swap.header)) {
if (!file.exists(swap.header)){
stop(sprintf("Swap header file %s does not exist\n",
swap.header))
}
system(paste("mkdir -p", tmp.dir))
tmp.name = paste(tmp.dir, "/vcf_tmp", gsub("0\\.", "",
as.character(runif(1))), ".vcf", sep = "")
if (grepl("gz$", fn)){
system(sprintf("zcat %s | grep '^[^#]' > %s.body",
fn, tmp.name))
} else system(sprintf("grep '^[^#]' %s > %s.body", fn,
tmp.name))
if (grepl("gz$", swap.header)){
system(sprintf("zcat %s | grep '^[#]' > %s.header",
swap.header, tmp.name))
} else{
system(sprintf("grep '^[#]' %s > %s.header", swap.header,
tmp.name))
}
system(sprintf("cat %s.header %s.body > %s", tmp.name,
tmp.name, tmp.name))
vcf = readVcf(tmp.name, hg, ...)
system(sprintf("rm %s %s.body %s.header", tmp.name, tmp.name,
tmp.name))
} else{
vcf = readVcf(fn, hg, ...)
}
out = granges(vcf)
if (!is.null(values(out))){
values(out) = cbind(values(out), info(vcf))
}
else values(out) = info(vcf)
if (!is.null(geno)) {
if (geno){
for (g in names(geno(vcf))) {
geno = names(geno(vcf))
warning(sprintf("Loading all geno field:\n\t%s",
paste(geno, collapse = ",")))
}
}
gt = NULL
for (g in geno) {
m = as.data.frame(geno(vcf)[[g]])
names(m) = paste(g, names(m), sep = "_")
if (is.null(gt)){
gt = m
} else{
gt = cbind(gt, m)
}
}
values(out) = cbind(values(out), as(gt, "DataFrame"))
}
if (!is.null(gr)){
system(paste("rm", tmp.slice.fn))
}
if (add.path){
values(out)$path = in.fn
}
return(out)
}
#' @name read.juncs
#' @title read.juncs
#'
#' @description load SV data as GRangesList
#'
#' @details
#' Reads a file containing SVs and returns a GRangesList.
#' Supported file types are:
#' - .rds (containing GRangesList or Junction object)
#' - .bedpe/.bedpe.gz
#' - .vcf/.vcf.gz
#'
#' VCF files produced from the following WGS junction callers are supported:
#' - SvABA (https://github.com/walaj/svaba)
#' - GRIDSS (https://github.com/PapenfussLab/gridss)
#' - delly (https://github.com/dellytools/delly)
#' - novoBreak (https://github.com/czc/nb_distribution)
#'
#' In addition, the following long read callers are supported:
#' - SVIM (https://github.com/eldariont/svim/wiki)
#' - PBSV (https://github.com/PacificBiosciences/pbsv)
#' - Sniffles2 (https://github.com/fritzsedlazeck/Sniffles)
#' - cuteSV (https://github.com/tjiangHIT/cuteSV)
#'
#' This function will load rearangements with the following SVTYPE values:
#' - DEL (requires END field)
#' - DUP (requires END field)
#' - INV (requires END field)
#' - TRA (for this SVTYPE, the INFO fields CHR2 and CT are also required)
#' - BND (requires ALT field with proper formatting)
#'
#' Note that we currently ignore SVTYPE INS rearrangements. In addition, SVTYPE BND rearrangements must have an ALT field corresponding to a single distal site. At this time, we will not load single breakends without a distal site, or breakends with multiple distal sites.
#'
#' @param rafile (character) path to junctions file
#' @param keep.features (logical) keep metadata? default TRUE
#' @param seqlengths (numeric) a named numeric vector of contig lengths. default NULL
#' @param chr.convert (logical) strip chr prefix on contig names? default FALSE
#' @param get.loose (logical) get loose ends. warning: not implemented yet!
#' @param standard.only (logical) retain only junctions between standard assembled chromosomes. default FALSE
#' @param flipstrand (logical) flip junction strands? default FALSE
#' @param verbose (logical) default FALSE
#'
#' @return
#' GRangesList if get.loose = FALSE
#' list if get.loose = TRUE (with slots $junctions and $loose) where $junctions is GRangesList and $loose is a signed GRanges
read.juncs = function(rafile,
keep.features = TRUE,
seqlengths = NULL,
chr.convert = FALSE,
get.loose = FALSE,
standard.only = FALSE,
flipstrand = FALSE,
verbose = FALSE,
...)
{
## check file existence
if (is.null(rafile) || is.na(rafile) || (!file.exists(rafile)) || (!file.info(rafile)$size))
{
stop("invalid file supplied: ", rafile)
}
## helper function to implement seqlevel manipulations
finalize.grl = function(grl,
seqlengths = NULL,
chr.convert = FALSE,
standard.only = FALSE,
flipstrand = FALSE)
{
if (!length(grl)) {
return(grl)
}
gp = gUtils::grl.pivot(grl)
bp1 = gp[[1]]
bp2 = gp[[2]]
bedpe.dt = data.table(chr1 = as.character(seqnames(bp1)),
start1 = start(bp1),
end1 = start(bp1),
chr2 = as.character(seqnames(bp2)),
start2 = start(bp2),
end2 = start(bp2),
strand1 = as.character(strand(bp1)),
strand2 = as.character(strand(bp2)))
## grab seqlengths from grl if any exist
grl.seqlengths = seqlengths(grl)
if (is.null(seqlengths))
{
if (all(!is.na(grl.seqlengths)))
{
if (chr.convert)
{
names(grl.seqlengths) = gsub("chr", "", names(grl.seqlengths))
}
seqlengths = grl.seqlengths
}
}
## substitute chr1 and chr2 prefix
if (chr.convert)
{
bedpe.dt[, chr1 := gsub("chr", "", chr1)]
bedpe.dt[, chr2 := gsub("chr", "", chr2)]
}
## keep everything by default
bedpe.dt[, keep := TRUE]
## but filter junctions to keep if desired
if (standard.only)
{
if (!is.null(seqlengths))
{
which.std = which(gsub("chr", "", names(seqlengths)) %in% c(as.character(1:22), "X", "Y"))
seqlengths = seqlengths[which.std]
bedpe.dt[, keep := chr1 %in% names(seqlengths) & chr2 %in% names(seqlengths)]
}
else
{
## make sure both chr1 and chr2 are standard chromosomes
bedpe.dt[, keep := gsub("chr", "", chr1) %in% c(as.character(1:22), "X", "Y") &
gsub("chr", "", chr2) %in% c(as.character(1:22), "X", "Y")]
}
}
if (!is.null(seqlengths))
{
bedpe.dt[, keep := chr1 %in% names(seqlengths) & chr2 %in% names(seqlengths)]
}
if (flipstrand)
{
bedpe.dt[, strand1 := ifelse(strand1 == "+", "-", "+")]
bedpe.dt[, strand2 := ifelse(strand2 == "+", "-", "+")]
}
bp1.new = bedpe.dt[(keep), GRanges(seqnames = chr1,
ranges = IRanges(start = start1,
width = 1),
strand = strand1,
seqlengths = seqlengths)]
bp2.new = bedpe.dt[(keep), GRanges(seqnames = chr2,
ranges = IRanges(start = start2,
width = 1),
strand = strand2,
seqlengths = seqlengths)]
new.grl = grl.pivot(GRangesList(bp1.new, bp2.new))
values(new.grl) = values(grl)[which(bedpe.dt[, keep]),]
return(new.grl)
}
## reading GRangesList
if (grepl(".rds$", rafile))
{