forked from jzhoulab/orca
-
Notifications
You must be signed in to change notification settings - Fork 0
/
orca_utils.py
executable file
·1056 lines (934 loc) · 37.4 KB
/
orca_utils.py
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
"""
This module contains the utilities for Orca-based applications,
including a class for structural variants and plotting utilities.
"""
import os
import pathlib
import uuid
from copy import deepcopy
from collections import OrderedDict, namedtuple
from bisect import bisect
import matplotlib
from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np
import pygenometracks.plotTracks
from colormaps import hnh_cmap_ext5, bwcmap
matplotlib.rcParams["pdf.fonttype"] = 42
matplotlib.rcParams["ps.fonttype"] = 42
ORCA_PATH = str(pathlib.Path(__file__).parent.absolute())
def _draw_region(ax, linestart, lineend, color, matlen):
ax.plot(
[-matlen / 50, -matlen / 50],
[matlen * linestart - 0.5 - 0.1, (matlen) * lineend - 0.5 + 0.1],
solid_capstyle="butt",
color=color,
linewidth=8,
zorder=10,
clip_on=False,
)
def _draw_site(ax, linepos, mode, matlen, color="black"):
if mode == "double":
ax.plot(
[-(matlen) / 20, -0.5],
[(matlen) * linepos - (matlen) / 100.0 - 0.5, (matlen) * linepos - 0.5],
color=color,
linewidth=0.2,
zorder=10,
clip_on=False,
)
ax.plot(
[-(matlen) / 20, -0.5],
[(matlen) * linepos + (matlen) / 100.0 - 0.5, (matlen) * linepos - 0.5],
color=color,
linewidth=0.2,
zorder=10,
clip_on=False,
)
elif mode == "single":
ax.plot(
[-(matlen) / 20, -0.5],
[(matlen) * linepos - 0.5, (matlen) * linepos - 0.5],
color=color,
linewidth=0.2,
zorder=10,
clip_on=False,
)
def genomeplot(
output,
show_genes=False,
show_tracks=False,
show_coordinates=True,
unscaled=False,
file=None,
cmap=None,
unscaled_cmap=None,
colorbar=True,
maskpred=False,
vmin=-1,
vmax=2,
model_labels = ["H1-ESC", "HFF"]
):
"""
Plot the multiscale prediction outputs for 32Mb output.
Parameters
----------
output : dict
The result dictionary to plot as returned by `genomepredict_256Mb`.
show_genes : bool, optional
Default is False. If True, plot the retrieved
gene annotations corresponding to all windows used for the multiscale prediction.
show_tracks : bool, optional
Default is False. If True, plot the retrieved
chromatin tracks for CTCF, chromatin accessibility and histone marks
for all windows used for the multiscale prediction.
show_coordinates : bool, optional
Default is True. If True, annotate the generated plot with the
genome coordinates.
unscaled : bool, optional
Default is False. If True, plot the predictions and observations
without normalizing by distance-based expectation.
file : str or None, optional
Default is None. The output file prefix. No output file is generated
if set to None.
cmap : str or None, optional
Default is None. The colormap for plotting scaled interactions (log
fold over distance-based background). If None, use colormaps.hnh_cmap_ext5.
unscaled_cmap : str or None, optional
Default is None. The colormap for plotting unscaled interactions (log
balanced contact score). If None, use colormaps.hnh_cmap_ext5.
colorbar : bool, optional
Default is True. Whether to plot the colorbar.
maskpred : bool, optional
Default is True. If True, the prediction heatmaps are masked at positions
where the observed data have missing values when observed data are provided
in output dict.
vmin : int, optional
Default is -1. The lowerbound value for heatmap colormap.
vmax : int, optional
Default is 2. The upperbound value for heatmap colormap.
model_labels : list(str), optional
Model labels for plotting. Default is ["H1-ESC", "HFF"].
Returns
-------
None
"""
if cmap is None:
cmap = hnh_cmap_ext5
if unscaled_cmap is None:
unscaled_cmap = hnh_cmap_ext5
if output["predictions"][0][0].ndim == 3:
predictions = []
for modeli in range(len(output["predictions"])):
ndims = output["predictions"][modeli][0].shape[0]
predictions += [[output['predictions'][modeli][i][j] for i in range(6)] for j in range(ndims)]
output["predictions"] = predictions
n_axes = len(output["predictions"])
if output["experiments"] is not None:
n_axes += len(output["predictions"])
fig, all_axes = plt.subplots(figsize=(36, 6 * n_axes), nrows=n_axes, ncols=6)
for row_axes in all_axes:
for ax in row_axes:
ax.get_xaxis().set_ticks([])
ax.get_yaxis().set_ticks([])
for i, xlabel in enumerate(["1Mb", "2Mb", "4Mb", "8Mb", "16Mb", "32Mb"]):
all_axes[-1, i].set_xlabel(xlabel, labelpad=20, fontsize=20, weight="black")
if output["experiments"] is not None:
current_axis = 0
for label in model_labels:
for suffix in [" Pred", " Obs"]:
all_axes[current_axis, 0].set_ylabel(
label + suffix,
labelpad=20,
fontsize=20,
weight="black",
rotation="horizontal",
ha="right",
va="center",
)
current_axis += 1
else:
current_axis = 0
for label in model_labels:
for suffix in [" Pred"]:
all_axes[current_axis, 0].set_ylabel(
label + suffix,
labelpad=20,
fontsize=20,
weight="black",
rotation="horizontal",
ha="right",
va="center",
)
current_axis += 1
current_row = 0
for model_i in range(len(output["predictions"])):
for ii, ax in enumerate(reversed(all_axes[current_row])):
s = int(output["start_coords"][ii])
e = int(output["end_coords"][ii])
regionstr = output["chr"] + ":" + str(s) + "-" + str(e)
if show_coordinates:
ax.set_title(regionstr, fontsize=14, pad=4)
if unscaled:
plotmat = output["predictions"][model_i][ii] + np.log(output["normmats"][model_i][ii])
im = ax.imshow(
plotmat,
interpolation="none",
cmap=unscaled_cmap,
vmax=np.max(np.diag(plotmat, k=1)),
)
else:
plotmat = output["predictions"][model_i][ii]
im = ax.imshow(plotmat, interpolation="none", cmap=cmap, vmin=vmin, vmax=vmax)
if output["annos"]:
for r in output["annos"][ii]:
if len(r) == 3:
_draw_region(ax, r[0], r[1], r[2], plotmat.shape[1])
elif len(r) == 2:
_draw_site(ax, r[0], r[1], plotmat.shape[1])
ax.axis([-0.5, plotmat.shape[1] - 0.5, -0.5, plotmat.shape[1] - 0.5])
ax.invert_yaxis()
if maskpred:
if output["experiments"]:
ax.imshow(
np.isnan(output["experiments"][0][ii]), interpolation="none", cmap=bwcmap,
)
current_row += 1
if output["experiments"]:
for ii, ax in enumerate(reversed(all_axes[current_row])):
s = int(output["start_coords"][ii])
e = int(output["end_coords"][ii])
regionstr = output["chr"] + ":" + str(s) + "-" + str(e)
if show_coordinates:
ax.set_title(regionstr, fontsize=14, pad=4)
if unscaled:
plotmat = output["experiments"][model_i][ii] + np.log(output["normmats"][model_i][ii])
im = ax.imshow(
plotmat,
interpolation="none",
cmap=unscaled_cmap,
vmax=np.max(np.diag(plotmat, k=1)),
)
else:
plotmat = output["experiments"][model_i][ii]
im = ax.imshow(plotmat, interpolation="none", cmap=cmap, vmin=vmin, vmax=vmax)
if output["annos"]:
for r in output["annos"][ii]:
if len(r) == 3:
_draw_region(ax, r[0], r[1], r[2], plotmat.shape[1])
elif len(r) == 2:
_draw_site(ax, r[0], r[1], plotmat.shape[1])
ax.axis([-0.5, plotmat.shape[1] - 0.5, -0.5, plotmat.shape[1] - 0.5])
ax.invert_yaxis()
current_row += 1
if colorbar:
fig.colorbar(im, ax=all_axes.ravel().tolist(), fraction=0.02, shrink=0.1, pad=0.005)
if show_genes:
for p in [
ORCA_PATH + "/resources/hg38.refGeneSelectMANE.bed.gz",
ORCA_PATH + "/resources/hg38.refGeneSelectMANE.bed.gz.tbi",
]:
if not os.path.exists(p):
show_genes = False
print(
"`show_genes` is turned off because resource file " + p + " is not available."
)
break
if show_tracks:
for p in [
ORCA_PATH + "/extra/H1_CTCF_ENCFF473IZV.bigWig",
ORCA_PATH + "/extra/H1_RAD21_ENCFF913JGA.bigWig",
ORCA_PATH + "/extra/H1_DNase_ENCFF131HMO.bigWig",
ORCA_PATH + "/extra/H1_H3K4me3_ENCFF623ZAW.bigWig",
ORCA_PATH + "/extra/H1_POLR2A_ENCFF379IRQ.bigWig",
ORCA_PATH + "/extra/H1_H3K27ac_ENCFF423TVA.bigWig",
ORCA_PATH + "/extra/H1_H3K4me1_ENCFF584AVI.bigWig",
ORCA_PATH + "/extra/H1_H3K36me3_ENCFF141YAA.bigWig",
ORCA_PATH + "/extra/H1_H3K27me3_ENCFF912ZUR.bigWig",
ORCA_PATH + "/extra/H1_H3K9me3_ENCFF752UGN.bigWig",
ORCA_PATH + "/extra/foreskin_fibroblast_CTCF_ENCFF761RHS.bigWig",
ORCA_PATH + "/extra/foreskin_fibroblast_DNase_ENCFF113YFF.bigWig",
ORCA_PATH + "/extra/foreskin_fibroblast_H3K4me3_ENCFF442WNT.bigWig",
ORCA_PATH + "/extra/foreskin_fibroblast_H3K27ac_ENCFF078JZB.bigWig",
ORCA_PATH + "/extra/foreskin_fibroblast_H3K4me1_ENCFF449DEA.bigWig",
ORCA_PATH + "/extra/foreskin_fibroblast_H3K36me3_ENCFF954UKB.bigWig",
ORCA_PATH + "/extra/foreskin_fibroblast_H3K27me3_ENCFF027GWJ.bigWig",
ORCA_PATH + "/extra/foreskin_fibroblast_H3K9me3_ENCFF946TXL.bigWig",
]:
if not os.path.exists(p):
show_tracks = False
print(
"`show_tracks` is turned off because resource file " + p + " is not available."
)
break
if show_genes or show_tracks:
browser_tracks = (
"""
[spacer]
height = 0.5
[x-axis]
where = top
fontsize = 12
[spacer]
height = 0.05
"""
+ (
"""
[test gtf collapsed]
file = {ORCA_PATH}/resources/hg38.refGeneSelectMANE.bed.gz
height = 25
merge_transcripts = true
prefered_name = gene_name
max_labels = 10000
fontsize = 9
file_type = bed
gene_rows = 40
display = stacked
""".format(
ORCA_PATH=ORCA_PATH
)
if show_genes
else ""
)
+ (
"""
[bigwig file test]
file = {ORCA_PATH}/extra/H1_CTCF_ENCFF473IZV.bigWig
# height of the track in cm (optional value)
height = 2
title = H1-CTCF
summary_method = mean
file_type = bigwig
[bigwig file test]
file = {ORCA_PATH}/extra/H1_RAD21_ENCFF913JGA.bigWig
# height of the track in cm (optional value)
height = 2
title = H1-RAD21
summary_method = mean
file_type = bigwig
[bigwig file test]
file = {ORCA_PATH}/extra/H1_DNase_ENCFF131HMO.bigWig
# height of the track in cm (optional value)
height = 2
title = H1-DNase
summary_method = mean
file_type = bigwig
color = #2A6D8F
[bigwig file test]
file = {ORCA_PATH}/extra/H1_H3K4me3_ENCFF623ZAW.bigWig
# height of the track in cm (optional value)
height = 2
title = H1-H3K4me3
summary_method = mean
file_type = bigwig
color = #E76F51
[bigwig file test]
file = {ORCA_PATH}/extra/H1_POLR2A_ENCFF379IRQ.bigWig
# height of the track in cm (optional value)
height = 2
title = H1-POL2
summary_method = mean
file_type = bigwig
color = #E76F51
[bigwig file test]
file = {ORCA_PATH}/extra/H1_H3K27ac_ENCFF423TVA.bigWig
# height of the track in cm (optional value)
height = 2
title = H1-H3K27ac
summary_method = mean
file_type = bigwig
color = #F4A261
[bigwig file test]
file = {ORCA_PATH}/extra/H1_H3K4me1_ENCFF584AVI.bigWig
# height of the track in cm (optional value)
height = 2
title = H1-H3K4me1
summary_method = mean
file_type = bigwig
color = #F4A261
[bigwig file test]
file = {ORCA_PATH}/extra/H1_H3K36me3_ENCFF141YAA.bigWig
# height of the track in cm (optional value)
height = 2
title = H1-H3K36me3
summary_method = mean
file_type = bigwig
color = #E9C46A
[bigwig file test]
file = {ORCA_PATH}/extra/H1_H3K27me3_ENCFF912ZUR.bigWig
# height of the track in cm (optional value)
height = 2
title = H1-H3K27me3
summary_method = mean
file_type = bigwig
color = #264653
[bigwig file test]
file = {ORCA_PATH}/extra/H1_H3K9me3_ENCFF752UGN.bigWig
# height of the track in cm (optional value)
height = 2
title = H1-H3K9me3
summary_method = mean
file_type = bigwig
color = #264653
[spacer]
height = 2
[bigwig file test]
file = {ORCA_PATH}/extra/foreskin_fibroblast_CTCF_ENCFF761RHS.bigWig
# height of the track in cm (optional value)
height = 2
title = HFF-CTCF
summary_method = mean
file_type = bigwig
[bigwig file test]
file = {ORCA_PATH}/extra/foreskin_fibroblast_DNase_ENCFF113YFF.bigWig
# height of the track in cm (optional value)
height = 2
title = HFF-DNase
summary_method = mean
file_type = bigwig
color = #2A6D8F
[bigwig file test]
file = {ORCA_PATH}/extra/foreskin_fibroblast_H3K4me3_ENCFF442WNT.bigWig
# height of the track in cm (optional value)
height = 2
title = HFF-H3K4me3
summary_method = mean
file_type = bigwig
color = #E76F51
[bigwig file test]
file = {ORCA_PATH}/extra/foreskin_fibroblast_H3K27ac_ENCFF078JZB.bigWig
# height of the track in cm (optional value)
height = 2
title = HFF-H3K27ac
summary_method = mean
file_type = bigwig
color = #F4A261
[bigwig file test]
file = {ORCA_PATH}/extra/foreskin_fibroblast_H3K4me1_ENCFF449DEA.bigWig
# height of the track in cm (optional value)
height = 2
title = HFF-H3K4me1
summary_method = mean
file_type = bigwig
color = #F4A261
[bigwig file test]
file = {ORCA_PATH}/extra/foreskin_fibroblast_H3K36me3_ENCFF954UKB.bigWig
# height of the track in cm (optional value)
height = 2
title = HFF-H3K36me3
summary_method = mean
file_type = bigwig
color = #E9C46A
[bigwig file test]
file = {ORCA_PATH}/extra/foreskin_fibroblast_H3K27me3_ENCFF027GWJ.bigWig
# height of the track in cm (optional value)
height = 2
title = HFF-H3K27me3
summary_method = mean
file_type = bigwig
color = #264653
[bigwig file test]
file = {ORCA_PATH}/extra/foreskin_fibroblast_H3K9me3_ENCFF946TXL.bigWig
# height of the track in cm (optional value)
height = 2
title = HFF-H3K9me3
summary_method = mean
file_type = bigwig
color = #264653
""".format(
ORCA_PATH=ORCA_PATH
)
if show_tracks
else ""
)
)
filename = str(uuid.uuid4())
with open(f"/dev/shm/{filename}.ini", "w") as fh:
fh.write(browser_tracks)
gbfigs = []
for ii, label in enumerate(["32Mb", "16Mb", "8Mb", "4Mb", "2Mb", "1Mb"]):
regionstr = (
output["chr"]
+ ":"
+ str(int(output["start_coords"][ii]))
+ "-"
+ str(int(output["end_coords"][ii]))
)
args = (
f"--tracks /dev/shm/{filename}.ini --region {regionstr} "
"--trackLabelFraction 0.03 --width 40 --dpi 10 "
f"--outFileName /dev/shm/{filename}.png --title {label}".split()
)
_ = pygenometracks.plotTracks.main(args)
gbfigs.append(plt.gcf())
os.remove(f"/dev/shm/{filename}.png")
os.remove(f"/dev/shm/{filename}.ini")
if file is not None:
with PdfPages(file) as pdf:
pdf.savefig(fig, dpi=300)
plt.show()
with PdfPages((".").join(file.split(".")[:-1]) + ".anno.pdf") as pdf:
for fig in reversed(gbfigs):
pdf.savefig(fig)
else:
if file is not None:
with PdfPages(file) as pdf:
pdf.savefig(fig, dpi=300)
plt.close("all")
def genomeplot_256Mb(
output,
show_coordinates=True,
unscaled=False,
file=None,
cmap=None,
unscaled_cmap=None,
colorbar=True,
maskpred=True,
vmin=-1,
vmax=2,
model_labels=["H1-ESC", "HFF"]
):
"""
Plot the multiscale prediction outputs for 256Mb output.
Parameters
----------
output : dict
The result dictionary to plot as returned by `genomepredict_256Mb`.
show_coordinates : bool, optional
Default is True. If True, annotate the generated plot with the
genome coordinates.
unscaled : bool, optional
Default is False. If True, plot the predictions and observations
without normalizing by distance-based expectation.
file : str or None, optional
Default is None. The output file prefix. No output file is generated
if set to None.
cmap : str or None, optional
Default is None. The colormap for plotting scaled interactions (log
fold over distance-based background). If None, use colormaps.hnh_cmap_ext5.
unscaled_cmap : str or None, optional
Default is None. The colormap for plotting unscaled interactions (log
balanced contact score). If None, use colormaps.hnh_cmap_ext5.
colorbar : bool, optional
Default is True. Whether to plot the colorbar.
maskpred : bool, optional
Default is True. If True, the prediction heatmaps are masked at positions
where the observed data have missing values when observed data are provided
in output dict.
vmin : int, optional
Default is -1. The lowerbound value for heatmap colormap.
vmax : int, optional
Default is 2. The upperbound value for heatmap colormap.
model_labels : list(str), optional
Model labels for plotting. Default is ["H1-ESC", "HFF"].
Returns
-------
None
"""
if cmap is None:
cmap = hnh_cmap_ext5
if unscaled_cmap is None:
unscaled_cmap = hnh_cmap_ext5
if output["predictions"][0][0].ndim == 3:
predictions = []
for modeli in range(len(output["predictions"])):
ndims = output["predictions"][modeli][0].shape[0]
predictions += [[output['predictions'][modeli][i][j] for i in range(6)] for j in range(ndims)]
output["predictions"] = predictions
n_axes = len(output["predictions"])
if output["experiments"] is not None:
n_axes += len(output["predictions"])
fig, all_axes = plt.subplots(figsize=(24, 6 * n_axes), nrows=n_axes, ncols=4)
for row_axes in all_axes:
for ax in row_axes:
ax.get_xaxis().set_ticks([])
ax.get_yaxis().set_ticks([])
for i, xlabel in enumerate(["32Mb", "64Mb", "128Mb", "256Mb"]):
all_axes[-1, i].set_xlabel(xlabel, labelpad=20, fontsize=20, weight="black")
if output["experiments"] is not None:
current_axis = 0
for label in model_labels:
for suffix in [" Pred", " Obs"]:
all_axes[current_axis, 0].set_ylabel(
label + suffix,
labelpad=20,
fontsize=20,
weight="black",
rotation="horizontal",
ha="right",
va="center",
)
current_axis += 1
else:
current_axis = 0
for label in model_labels:
for suffix in [" Pred"]:
all_axes[current_axis, 0].set_ylabel(
label + suffix,
labelpad=20,
fontsize=20,
weight="black",
rotation="horizontal",
ha="right",
va="center",
)
current_axis += 1
def _plot_pred(ii, ax, model_i, key="predictions", maskpred=False):
s = int(output["start_coords"][ii])
e = int(output["end_coords"][ii])
padlen = int(output["start_coords"][ii] + 256000000 / 2 ** (ii)) - e
if padlen > 0 and output["padding_chr"] is not None:
regionstr = (
output["chr"]
+ ":"
+ str(s)
+ "-"
+ str(e)
+ "; "
+ output["padding_chr"]
+ ":0-"
+ str(padlen)
)
else:
regionstr = output["chr"] + ":" + str(s) + "-" + str(e)
if show_coordinates:
ax.set_title(regionstr, fontsize=14, pad=4)
if unscaled:
plotmat = output[key][model_i][ii] + np.log(output["normmats"][model_i][ii])
im = ax.imshow(
plotmat,
interpolation="none",
cmap=unscaled_cmap,
vmax=np.max(np.diag(plotmat, k=1)),
)
else:
plotmat = output[key][model_i][ii]
im = ax.imshow(plotmat, interpolation="none", cmap=cmap, vmin=vmin, vmax=vmax)
if padlen > 0:
# draw chr boundary
chrlen_ratio = 1 - padlen / (256000000 / 2 ** (ii))
ax.plot(
[chrlen_ratio * plotmat.shape[0] - 0.5, chrlen_ratio * plotmat.shape[0] - 0.5],
[-0.5, plotmat.shape[0] - 0.5],
color="black",
linewidth=0.2,
zorder=10,
)
ax.plot(
[-0.5, plotmat.shape[0] - 0.5],
[chrlen_ratio * plotmat.shape[0] - 0.5, chrlen_ratio * plotmat.shape[0] - 0.5],
color="black",
linewidth=0.2,
zorder=10,
)
if output["annos"]:
for r in output["annos"][ii]:
if len(r) == 3:
_draw_region(ax, r[0], r[1], r[2], plotmat.shape[1])
elif len(r) == 2:
_draw_site(ax, r[0], r[1], plotmat.shape[1])
ax.axis([-0.5, plotmat.shape[1] - 0.5, -0.5, plotmat.shape[1] - 0.5])
ax.invert_yaxis()
if maskpred:
if output["experiments"]:
ax.imshow(
np.isnan(output["experiments"][0][ii]), interpolation="none", cmap=bwcmap,
)
return im
current_row = 0
for model_i in range(len(output["predictions"])):
for ii, ax in enumerate(reversed(all_axes[current_row])):
im = _plot_pred(ii, ax, model_i, key="predictions", maskpred=maskpred)
current_row += 1
if output["experiments"]:
for ii, ax in enumerate(reversed(all_axes[current_row])):
im = _plot_pred(ii, ax, model_i, key="experiments")
current_row += 1
if colorbar:
fig.colorbar(im, ax=all_axes.ravel().tolist(), fraction=0.02, shrink=0.1, pad=0.005)
if file is not None:
with PdfPages(file) as pdf:
pdf.savefig(fig, dpi=300)
plt.close("all")
GRange = namedtuple("GRange", ["chr", "start", "end", "strand"])
LGRange = namedtuple("LGRange", ["len", "ref"])
class StructuralChange2(object):
"""
This class stores and manupulating structural changes for a single
chromosome and allow querying the mutated chromosome by coordinates by providing
utilities for retrieving the corresponding reference genome segments.
The basic operations that StructuralChange2 supports are duplication, deletion,
inversion, insertion, and concatenation. StructuralChange2 objects can be concatenated with '+'
operator, this operation allows concatenating two chromosomes. '+' can be combined with
other basic operations to create fused chromosomes.
These operations can be used sequentially to introduce arbitrarily complex
structural changes. However, note that the coordinates are dynamically updated
after each operation reflecting the current state of the chromosome, thus coordinates
specified in later operation must take into account of the effects of all previous
operations.
Parameters
----------
chr_name : str
Name of the reference chromosome.
length : int
The length of the reference chromosome.
Attributes
-------
segments : list(LGRange)
List of reference genome segments that constitute the (mutated)
chromosome. Each element is a LGRange namedtuple (length and a
GRange namedtuple (chr: str, start: int, end: int, strand: str)).
chr_name : str
Name of the chromosome
coord_points : list(int)
Stores `N+1` key coordinates where `N` is the number of segments. The
key coordinates are 0, segment junction positions, and chromosome end
coordinate. `coord_points` reflects the current state of the chromosome.
"""
def __init__(self, chr_name, length):
self.segments = [LGRange(length, GRange(chr_name, 0, length, "+"))]
self.chr_name = chr_name
self.coord_points = [0, length]
def _coord_sync(self):
self.coord_points = [0]
for seg in self.segments:
self.coord_points.append(self.coord_points[-1] + seg.len)
def _split(self, pos):
segind = bisect(self.coord_points, pos) - 1
segstart = self.coord_points[segind]
if pos != segstart:
# split segment
ref_chr, ref_s, ref_e, ref_strand = self.segments[segind].ref
if ref_strand == "+":
ref_1 = GRange(ref_chr, ref_s, ref_s + pos - segstart, "+")
ref_2 = GRange(ref_chr, ref_s + pos - segstart, ref_e, "+")
else:
ref_1 = GRange(ref_chr, ref_e - (pos - segstart), ref_e, "-")
ref_2 = GRange(ref_chr, ref_s, ref_e - (pos - segstart), "-")
self.segments[segind] = LGRange(ref_1.end - ref_1.start, ref_1)
self.segments.insert(segind + 1, LGRange(ref_2.end - ref_2.start, ref_2))
self._coord_sync()
def __add__(self, b):
a = deepcopy(self)
a.segments = a.segments + b.segments
alen = len(a.coord_points)
a.coord_points = a.coord_points + b.coord_points[1:]
for i in range(alen, len(a.coord_points)):
a.coord_points[i] += a.coord_points[alen - 1]
return a
def duplicate(self, start, end):
"""
Duplicate a genomic region.
"""
# start and end in cgenome coordinates
self._split(start)
self._split(end)
ind_s = bisect(self.coord_points, start) - 1
ind_e = bisect(self.coord_points, end) - 1
for i, seg in enumerate(self.segments[ind_s:ind_e]):
self.segments.insert(ind_e + i, deepcopy(seg))
self._coord_sync()
def insert(self, start, length, strand="+", name=None):
"""
Insert a genomic sequence with given length.
"""
self._split(start)
ind_s = bisect(self.coord_points, start) - 1
if not name:
name = "ins" + str(start) + "_" + str(length)
self.segments.insert(ind_s, LGRange(length, GRange(name, 0, length, strand)))
self._coord_sync()
def delete(self, start, end):
"""
Delete a genomic region.
"""
# start and end in cgenome coordinates
self._split(start)
self._split(end)
ind_s = bisect(self.coord_points, start) - 1
ind_e = bisect(self.coord_points, end) - 1
del self.segments[ind_s:ind_e]
self._coord_sync()
def invert(self, start, end):
"""
Invert a genomic region.
"""
# start and end in cgenome coordinates
self._split(start)
self._split(end)
ind_s = bisect(self.coord_points, start) - 1
ind_e = bisect(self.coord_points, end) - 1
self.segments[ind_s:ind_e] = self.segments[ind_s:ind_e][::-1]
for i in range(ind_s, ind_e):
self.segments[i] = LGRange(
self.segments[i].len,
GRange(
self.segments[i].ref.chr,
self.segments[i].ref.start,
self.segments[i].ref.end,
"-" if self.segments[i].ref.strand == "+" else "-",
),
)
self._coord_sync()
def query(self, start, end):
"""
Retrieve the segments in the reference genome that constitute
the specified interval in the mutated genome.
"""
ind_s = bisect(self.coord_points, start) - 1
ind_e = bisect(self.coord_points, end)
ref_coords = [deepcopy(seg.ref) for seg in self.segments[ind_s:ind_e]]
if ref_coords[0]:
if ref_coords[0].strand == "+":
ref_coords[0] = GRange(
ref_coords[0].chr,
ref_coords[0].start + start - self.coord_points[ind_s],
ref_coords[0].end,
ref_coords[0].strand,
)
else:
ref_coords[0] = GRange(
ref_coords[0].chr,
ref_coords[0].start,
ref_coords[0].end - (start - self.coord_points[ind_s]),
ref_coords[0].strand,
)
# when end exceeds length
if ind_e == len(self.coord_points):
if end > self.coord_points[-1]:
print(f"Warning: query end {end} exceed limit {self.coord_points[-1]}!")
else:
if ref_coords[-1]:
if ref_coords[-1].strand == "+":
ref_coords[-1] = GRange(
ref_coords[-1].chr,
ref_coords[-1].start,
ref_coords[-1].end - (self.coord_points[ind_e] - end),
ref_coords[-1].strand,
)
else:
ref_coords[-1] = GRange(
ref_coords[-1].chr,
ref_coords[-1].start + (self.coord_points[ind_e] - end),
ref_coords[-1].end,
ref_coords[-1].strand,
)
return ref_coords
def query_ref(self, chr_name, start, end):
"""
Retrieve regions that correspond to the specified reference genome interval
in the mutated genome.
"""
current_coords = []
ref_coords = []
for i, (seglen, refseg) in enumerate(self.segments):
if refseg.chr == chr_name:
if start < refseg.end or end >= refseg.start:
ref_coords.append(
[
np.clip(start, refseg.start, refseg.end),
np.clip(end, refseg.start, refseg.end),
]
)
if refseg.strand == "+":
current_coords.append(
[
self.coord_points[i] + np.clip(start - refseg.start, 0, seglen),
self.coord_points[i] + np.clip(end - refseg.start, 0, seglen),
"+",
]
)
else:
current_coords.append(
[
self.coord_points[i + 1] - np.clip(start - refseg.start, 0, seglen),
self.coord_points[i + 1] - np.clip(end - refseg.start, 0, seglen),
"-",
]
)
return ref_coords, current_coords
def __getitem__(self, key):
if isinstance(key, slice):
return self.query(key.start, key.stop)
def process_anno(anno_scaled, base=0, window_radius=16000000):
"""
Process annotations to the format used by Orca plotting
functions such as `genomeplot` and `genomeplot_256Mb`.
Parameters
----------
anno_scaled : list(list(...))
List of annotations. Each annotation can be a region specified by
`[start: int, end: int, info:str]` or a position specified by
`[pos: int, info:str]`.
Acceptable info strings for region currently include color names for
matplotlib. Acceptable info strings for position are currently
'single' or 'double', which direct whether the annotation is drawn
by single or double lines.
base : int
The starting position of the 32Mb (if window_radius is 16000000)
or 256Mb (if window_radius is 128000000) region analyzed.
window_radius : int
The size of the region analyzed. It must be either 16000000 (32Mb region)
or 128000000 (256Mb region).
Returns
-------
annotation : list
Processed annotations with coordinates transformed to relative coordinate
in the range of 0-1.
"""
annotation = []
for r in anno_scaled:
if len(r) == 3:
annotation.append(
[(r[0] - base) / (window_radius * 2), (r[1] - base) / (window_radius * 2), r[2],]
)
elif len(r) == 2:
annotation.append([(r[0] - base) / (window_radius * 2), r[1]])
else: